content
stringlengths
5
1.05M
c = 0 s = 0 t = 0 iterator = 0 mass = list() for y in range(4): aux = list(map(int, input().split())) c = aux[0] s = aux[1] spec = list(map(int, input().split())) iterator = s while iterator < c*2 - 1: if iterator > s: break spec[iterat...
from nn import FN, Sigmoid, Tanh, ReLU import numpy as np import matplotlib.pyplot as plt class XOR(object): def __init__(self, batch_size, input_shape, hidden_shape, output_shape, learning_rate, active_func): self.fn1 = FN(batch_size, input_shape, hidden_shape, learning_rate) sel...
class dc_config(object): """ DC Client configuration file. Specifies which channels from the server to break out in the client and their layout. Attributes ---------- headerLayout: (int, int) Specifies the layout of the header as [row, column]. Starts from 0. channel_di...
# coding: UTF-8 from __future__ import absolute_import import unittest from usig_normalizador_amba.NormalizadorDireccionesAMBA import NormalizadorDireccionesAMBA from usig_normalizador_amba.Calle import Calle from usig_normalizador_amba.Errors import ErrorCalleInexistente from test_commons import cargarCallejeroEstat...
import pytest import numpy as np import pandas as pd from tensortrade.data import DataFeed, Stream, BinOp def test_lag(): s1 = Stream([1, 2, 3, 4, 5]).rename("stream") assert s1.name == "stream" lag = s1.lag() assert lag.name == "Lag(stream,1)" feed = DataFeed([lag]) feed.compile() v...
import logging import os from abc import ABC, abstractmethod import yaml from pytorch_pretrained_biggan import BigGAN from wikipedia2vec import Wikipedia2Vec from deep_lyric_visualizer.helpers import dict_assign, setup_logger, find_first_file_with_ext import re setup_logger() logger = logging.getLogger(__name__) c...
import pytest from tests.conftest import browser_instance @pytest.fixture(scope="session") def browser(base_url): with browser_instance() as browser: browser.base_url = base_url browser.open("/disappearing_elements") yield browser
from picamera import PiCamera import time import cv2 import numpy as np from config import WIDTH, HEIGHT, CHANNEL, MINIMUM_DISTANCE, CP_WIDTH, CP_HEIGHT from ultrasonic import getDistance camera = PiCamera() def getImage(): camera.resolution = (HEIGHT, WIDTH) errors = False im = np.empty(( WIDTH, HEIGHT, 3), dtype...
from pathlib import Path def read(filename='in'): file_path = Path(__file__).parent / filename with file_path.open('r') as file: return read_lines(file.readlines()) def read_lines(lines): return [read_line(line.strip()) for line in lines] def read_line(line): return [int(b) for b in line]
import argparse import yaml import coloredlogs import json import logging import os import datetime import shelve import schedule import requests import time from twilio.rest import Client coloredlogs.install(level="INFO") log = logging.getLogger("main") class LuxMedSniper: LUXMED_LOGIN_URL = 'https://portalpacj...
import asyncio import unittest import multiprocessing import random import string import subprocess import traceback import os from earlgrey import MessageQueueStub, MessageQueueService, MessageQueueType, message_queue_task def available_credential(username, password): try: subprocess.check_output(["rabb...
str1=input("Enter the string :") list1=str1.split() list2=set(list1) list3=list(list2) print(list1) print(list2) print(list3) list4=[] list5=[] counter=0 for i in range(len(list3)): counter=0 for j in range(len(list1)): if list3[i]==list1[j]: counter+=1 list4=list3[i],counter list5.append(list4) print(list5...
class Solution(object): def fullJustify(self, words, maxWidth): """ :type words: List[str] :type maxWidth: int :rtype: List[str] """ allLi = [] li = [] oneLi = 0 for word in words: if (len(word) + oneLi + len(li)) <= maxWidth: ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Wrapper for visualize.py @author: thomas """ if __name__ == '__main__' and __package__ is None: from os import sys, path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) import os import argparse from common.visualize import loop_directori...
import unittest import nose.tools from tspsolver.tsp_generator import TSPGenerator from ..simulator import Simulator class SimulatorTest(unittest.TestCase): def setUp(self): self._num_points = 30 gen = TSPGenerator(self._num_points) self._data = gen.generate() def test_evolve(self):...
from imdb import IMDb # create an instance of the IMDb class ia = IMDb() # get a movie ep = ia.get_movie_episodes('6567314') eps = ep["data"]["episodes"] videos = [] import pdb;pdb.set_trace() for s in eps.keys(): for e in eps[s].keys(): item = eps[s][e] videos.append({ "episode": ite...
def test(): assert ( 'spacy.blank("es")' in __solution__ ), "¿Creaste el modelo de español en blanco?" assert ( len(nlp.pipe_names) == 1 and nlp.pipe_names[0] == "ner" ), "¿Añadiste el entity recognizer al pipeline?" assert ( len(ner.labels) == 1 and ner.labels[0] == "ROPA" ...
from autocurry import autocurry # noinspection PyMethodMayBeStatic,PyCallingNonCallable class TestAutocurryDecorator(object): def test_positional_arguments(self): @autocurry def add(a, b, c): return a + b + c assert add(1, 2, 3) == 6 assert add(1, 2)(3) == 6 a...
"""Helper functions""" import hashlib from pathlib import Path def sha256sum(filename: Path) -> str: """Calculate the SHA256 value of a file""" # https://stackoverflow.com/questions/22058048/hashing-a-file-in-python h = hashlib.sha256() b = bytearray(128 * 1024) mv = memoryview(b) with open(f...
class Vec2: x: float y: float def __init__(self, x:float, y:float) -> None: self.x = x self.y = y
""" parent packages """ from __future__ import absolute_import import sys
# Copyright 2022 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, sof...
import json from typing import List, Dict, Any import os import urllib from urllib.parse import quote, quote_plus import glob from PIL import Image S3_PREFIX = "https://s3.amazonaws.com/pai-datastore/images" NUM_OF_KEYPOINTS = 18 COCO_HEADER = {"info": {"description": "Passenger Labeling 1"}, "licenses"...
import os import numpy from multiprocessing import Process from ad_coyote_lake import merge_datasets from ad_coyote_lake import advection_diffusion_with_wind_model use_multiprocessing = True diffusion_coeff_array = numpy.append( numpy.arange(10.0, 100.0, 10.0 ), numpy.arange(100.0 ,1100.0 ,100.0)...
# -*- coding:utf-8 -*- """ Small script that runs all unit tests and checks their coverage for the module. If all tests pass, and coverage PERCENTAGE is above the number given as parameter, the script exits with 0, otherwise 1. """ import os import sys import coverage import argparse # import environment # noqa: F4...
from ..circuit import QubitCircuit __all__ = ["to_chain_structure"] def to_chain_structure(qc, setup="linear"): """ Method to resolve 2 qubit gates with non-adjacent control/s or target/s in terms of gates with adjacent interactions for linear/circular spin chain system. Parameters --------...
# from tests.enablelog import ScriptLog # from tests.enablelog import banner # import pprint # from .context import mdslib from tests.enablelog import ScriptLog, banner sl = ScriptLog("switch.log") log = sl.log log.info("Starting Test...") from mdslib.switch import Switch user = 'admin' pw = 'nbv!2345' ip_address ...
/home/runner/.cache/pip/pool/65/4c/34/8743e42d7cfd1f4aac3ca8120f4fe45fc4a92c7f328dbdd1bc85a4b8e8
import torch import os import net import torch.nn as nn def load_net(dataset, net_type, nb_classes, embed=False, sz_embedding=512): if net_type == 'bn_inception': model = net.bn_inception(pretrained=True) model.last_linear = nn.Linear(1024, nb_classes) model.load_state_dict(torch.load('ne...
n = int(input()) s = set(map(int, input().split())) N = int(input()) for _ in range(N): data = input().split(' ') if data[0] == 'pop': s.pop() elif data[0] == 'remove': s.remove(int(data[1])) elif data[0] == 'discard': s.discard(int(data[1])) print(sum(s))
import flask import boto3 import botocore import json import datetime from flask_sqlalchemy import SQLAlchemy from sqlalchemy.sql.functions import func import sys import os import random MAX_REQUESTS_TO_AWS = 20 MAX_PROMPT_LENGTH = 200 class Config(object): DEBUG = False TESTING = False CSRF_ENABLED = Tru...
from collections import deque from module.seeding.peak.basic_peak_finder import PeakFinder class WindowPeakFinder(PeakFinder): def __init__(self, threshold, window): super().__init__(threshold) self.window = window self.queue = deque(window * [0.0], window) self.size = 0 ...
from spn.data.datasets import get_binary_data, get_nips_data, get_mnist from os.path import dirname path = dirname(__file__) import numpy as np import sys sys.path.append("/home/shao/simple_spn/simple_spn/src") from spn.algorithms.Inference import log_likelihood, conditional_log_likelihood from spn.algorithms.Learni...
# Copyright (C) 2018 Garth N. Wells # # SPDX-License-Identifier: MIT """This module contains a collection of functions related to geographical data. """ from importlib_metadata import import_module from haversine import haversine, Unit from floodsystem.utils import sorted_by_key# noqa from floodsystem.stationdat...
## This module contains the class Fit as well as the constants that this class uses # The range of mu, [0, 1], is split into several intervals. # The model is linear in the parameters of the fit on each interval. # The constraints on the function: the intensity at mu = 1 is set, # the function is continuous everywhe...
#!/usr/bin/env python """Example: $ ./script/make_spkg.py ../sfepy-2009.3/ /home/share/software/packages/femhub-0.9.3 0 0 """ import os, sys, shutil import sfepy spkg_skeleton_dir = sys.argv[1] femhub_dir = sys.argv[2] make_dist = int(sys.argv[3]) install = int(sys.argv[4]) if make_dist: os.system('python setup....
# from rdflib import ConjunctiveGraph from unittest import TestCase from jsongraph import reflect from .util import make_test_graph, ORG_URI class ReflectTestCase(TestCase): def setUp(self): super(ReflectTestCase, self).setUp() self.graph = make_test_graph() def test_predicates(self): ...
import random, time, sqlite3 conn = sqlite3.connect('d.db') cur = conn.cursor() for i in range(100): cur.execute('CREATE TABLE IF NOT EXISTS random(val REAL)') cur.execute('DELETE FROM random') conn.commit() t = 10 q = 5 for i in range(t): cur.execute('INSERT INTO random VALUES ({})'...
#!./bin/python # -*- coding: utf-8 -*- # ---------------------------------------------------------------------- # NSQ Publish API # ---------------------------------------------------------------------- # Copyright (C) 2007-2017 The NOC Project # See LICENSE for details # -----------------------------------------------...
import torch from torch import nn import torch.nn.functional as F from models.detection_model import DetectionModel class ResNetModel(DetectionModel): default_params = { "model_type": "resnet", "model_version": 1.0, "input_shape": (1, 240, 320), "initial_filters": 16, "num...
#!usr/bin/env python """nonmetric multidimensional scaling (nmds) see, for example: Jan de Leeuw 2004 (monotone regression), Rencher 2002: Methods of multivariate analysis, and the original work: Kruskal 1964: Nonmetric multidimensional scaling """ from __future__ import division from numpy import array, multiply, s...
import numpy as np import pickle import os from sklearn.metrics import f1_score, accuracy_score from sklearn.neural_network import MLPClassifier from sklearn.naive_bayes import BernoulliNB import lightgbm as lgb from lightgbm import LGBMClassifier from stacking_ensemble import SklearnWrapper, LightGBMWrapper, Stacki...
from . import Feature, FeatureTestResult from .join_feature import JoinFeature class MIPBackend(Feature): r""" A feature describing whether a :class:`MixedIntegerLinearProgram` backend is available. """ def _is_present(self): r""" Test for the presence of a :class:`MixedIntegerLinearPr...
""" Copyright 2018-2019 Skyscanner Ltd 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, softwar...
import hashlib from flask.ext.babel import gettext as _ from flask.ext.login import LoginManager # configure Flask-Login from app import app, db, on_application_ready from app.models.user import User login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = "mod_auth.login" login_manager....
from typing import Dict, List, Any, Union from overrides import overrides import torch from torch.nn.modules import Linear, Dropout import torch.nn.functional as F from transformers.modeling_bert import BertModel from allennlp.data import TextFieldTensors, Vocabulary from allennlp.models.model import Model from allen...
import logging logger = logging.getLogger(__name__) from drovirt.models.tasks import TaskStatus class BaseTask: def __init__(self, task): self.task = task self.task_id = task.get('id', None) if not self.task_id: raise Exception("Received task without id") self.result = ...
# Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle. # Note that the row index starts from 0. # In Pascal's triangle, each number is the sum of the two numbers directly above it. # Example: # Input: 3 # Output: [1,3,3,1] class Solution(object): def getRow(self, rowIn...
import pytest import uuid from fastapi import status from tests.api.node import ( INVALID_UPDATE_FIELDS, NONEXISTENT_FIELDS, VALID_DIRECTIVES, VALID_TAGS, VALID_THREAT_ACTOR, VALID_THREATS, ) from tests.helpers import create_test_user # # INVALID TESTS # @pytest.mark.parametrize( "key,...
# -*- coding: utf-8 -*- """ Created on Tue Mar 30 21:22:23 2021 @author: BassitA """ from generalFunctions import * from helrClassifier import * from bioPerformance import * import pickle import multiprocessing as mp import gc from itertools import repeat def main(): dataset = 'Cele...
from matplotlib import pyplot as plt import csv from absl import app, flags, logging from absl.flags import FLAGS import os import scipy.io import numpy as np import cv2 import tqdm from sklearn.metrics import average_precision_score from sklearn.metrics import recall_score from sklearn.metrics import accuracy_score fr...
''' Created by auto_sdk on 2019.07.01 ''' from dingtalk.api.base import RestApi class OapiProcessTemplateUpgradeRequest(RestApi): def __init__(self,url=None): RestApi.__init__(self,url) self.detail_component_id = None self.form_component_id = None self.process_code = None self.userid = None def getHttpMeth...
import re import pathlib from typing import IO, List import numpy.typing as npt import numpy as np str_path: str pathlib_path: pathlib.Path str_file: IO[str] bytes_file: IO[bytes] bag_obj: np.lib.npyio.BagObj[int] npz_file: np.lib.npyio.NpzFile AR_i8: npt.NDArray[np.int64] AR_LIKE_f8: List[float] class BytesWriter...
""" Full of social stuff with the other characters Up ur social links dialogue.py Max Ferguson """ from main import * sLink = {"Steve": 0, "Zara": 0, "Aeyden": 0, "Emil": 0, "Douche": 0, "Diana": 0, "Cheryl": 0, "Hiram": 0, "Eduardo": 0} def steve(place, sLink, stats, name, pronouns): """ "Dykey" cis Werewol...
from django.db import models class Article(models.Model): title = models.CharField(max_length=128) content = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True)
#!/usr/bin/env python # Confidential Information of Forward Networks, Inc. # Copyright (c) 2015 Forward Networks, Inc. All rights reserved. ''' This script uploads a zipped snapshot file. You can test it with the snapshot located in fwd-api-data/snapshots/linear-basic.zip. ''' import argparse import os import sys t...
import argparse import json import torch import torch.nn as nn import torch.optim as optim import torchvision.transforms as transforms from datasets.shapes_dataset import ShapesClassificationDataset, ShapesCounterDataset, ShapesCounterDataset135 from datasets.transformers import RandomVerticalFlip, RandomHorizontalFli...
# doctests are disabled because of issue #1521 from sympy.core import Symbol from sympy.core.relational import Relational from sympy.logic.boolalg import Boolean, Not class AssumptionsContext(set): """Set representing assumptions. This is used to represent global assumptions, but you can also use this cl...
# Copyright (c) 2021 PaddlePaddle 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 app...
import os, sys import pickle import numpy as np from pdb import set_trace as st from nninst_utils.fs import ensure_dir, IOAction images_per_class = 10 model_label = "dropout" model_dir = f"result/resnet10cifar10/model_{model_label}" attack_dir = os.path.join(model_dir, "attack", "test") attack_names = [ "FGSM_1"...
# Copyright 2020 Open Source Robotics Foundation, Inc. # # 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...
# Copyright 2019 The Oppia 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 ...
import os os.system('git add data/*') os.system('git add data/a2c/*') os.system('git add models/*') os.system('git add models/a2c/*') os.system('git add logs/*') os.system('git add logs/a2c/*') os.system('git commit -m "new results"') os.system('git push origin devel')
# coding=utf-8 from HTMLParser import HTMLParser from urllib import urlopen class DataParser(HTMLParser): def __init__(self): HTMLParser.__init__(self) self._url = '' self._is_path = False self._is_a = False self._is_preview = False self._is_trash = False se...
#!/usr/bin/env python # # // SPDX-License-Identifier: BSD-3-CLAUSE # # (C) Copyright 2018, Xilinx, Inc. # #!/usr/bin/python from __future__ import print_function from progressbar import ProgressBar import numpy as np import tensorflow as tf from xfdnn.rt.xdnn_util import make_list from xfdnn.rt.xdnn_io import loadIm...
import logging from autogluon.core.constants import REGRESSION, SOFTCLASS from autogluon.core.utils.try_import import try_import_rapids_cuml from .rf_model import RFModel logger = logging.getLogger(__name__) # TODO: Improve memory safety # TODO: Respect time limit # TODO: Depending on max_depth parameter, RFRapids...
from tensor_network.tensor_apis.base_api import BaseTensorAPI, OutOfMemoryError from tensor_network.tensor_apis.numpy_apis import NumpyAPI class NumpyTensor: def __init__(self, base, tensorflow, dtype): self._base = base self._tensorflow = tensorflow self._dtype = dtype def __setitem_...
import AppKit import objc from PyObjCTools.TestSupport import TestCase class TestNSUserInterfaceValidationHelper(AppKit.NSObject): def action(self): return 1 def tag(self): return 1 def validateUserInterfaceItem_(self, a): return 1 class TestNSUserInterfaceValidation(TestCase):...
import logging import os import time from collections import defaultdict from queue import Queue from typing import Tuple, Callable, Dict, Optional import numpy as np from dqo import log_utils from dqo.db.clients import DatabaseClient from dqo.db.models import Database from dqo.lab.query_executor import QueryExecutor...
from django.contrib import admin from settings.models import ContactDetail, Social, SliderImage class ContactDetailAdmin(admin.ModelAdmin): class Meta: model = ContactDetail class SocialAdmin(admin.ModelAdmin): list_display = ['service', 'url'] class Meta: model = Social class Slider...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'des.ui' # # Created by: PyQt5 UI code generator 5.15.4 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, Q...
import struct from unittest import mock import pytest from aiokafka.record.legacy_records import ( LegacyRecordBatch, LegacyRecordBatchBuilder ) from aiokafka.errors import CorruptRecordException @pytest.mark.parametrize("magic", [0, 1]) @pytest.mark.parametrize("key,value,checksum", [ (b"test", b"Super", [2...
# Used for pytest, do not delete
import module.utils from module.Classification_module.cl_basic import cl_basic from module.Classification_module.target import target_detect from module.Classification_module.cl_sub import cl_sub from pprint import pprint def classification(parsed_text): classification_main_result = cl_basic(parsed_text) ...
sexo=str(input('Sexo [F/M]: ')).upper().strip() while not sexo in 'FM': print('Dado incorreto.TENTE NOVAMENTE!') sexo = str(input('Sexo [F/M]: ')).upper().strip() print('FIM')
"""Experience, ranking, and leveling related utility functions.""" from util.const import lvl_base def get_level_xp(n): """Calculate the XP required to be a level.""" return lvl_base * (n**2 + n)/2 + lvl_base def xp_level(ixp): """Calculate current level from XP.""" xp = int(ixp) level = 0 whil...
from django import db from django.conf import settings from django.test import TestCase from models import (User, UserProfile, UserStat, UserStatResult, StatDetails, AdvancedUserStat, Image, Product) class ReverseSelectRelatedTestCase(TestCase): def setUp(self): # Explicitly enable debug for these tes...
import discord, difflib, traceback from discord.ext import commands from core.views import dymview class OnError(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_command_error(self, ctx:commands.Context, error): if isinstance(error, commands.Comm...
import urllib import urllib2 import urlparse from datetime import timedelta from unicodedata import normalize from django.conf import settings from django.contrib import messages from django.http import HttpResponseRedirect, HttpResponse from django.contrib.auth import logout as auth_logout from django.contrib.auth.de...
# 1404 - Thieves of Kerning City from net.swordie.ms.enums import Stat sm.setSpeakerID(1052001) response = sm.sendAskYesNo("So you want to become a Thief?") if response: sm.completeQuestNoRewards(parentID) sm.jobAdvance(400) # Thief sm.resetAP(False, 400) sm.giveItem(2070000, 500) sm.giveItem(133...
import codecs import networkx as nx from itertools import combinations f = codecs.open('data/corpus/docs_topic.tsv', 'r', 'utf-8') edges = [] nodes = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24, 25,26] # name = { # '0': 'Nagyobb csoportok', # '1': 'Kisebb csoportok: egyéni portré...
class PairingBasisGen: def generateFermi(self): for i in range(0,self.nParticles): self.below_fermi.append(i) for j in range(self.nParticles, self.nSpStates): self.above_fermi.append(j) def generateStates(self): for sp in range(0,self.nSpStates/2): se...
from rest_framework.filters import OrderingFilter class CustomFilter(OrderingFilter): pass
#!/usr/bin/env python # Copyright (c) 2015: # Istituto Nazionale di Fisica Nucleare (INFN), Italy # # See http://www.infn.it for details on the copyrigh holder # # 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 ...
# -*- coding: utf-8 -*- import unittest from starlette.testclient import TestClient from app.main import app client = TestClient(app) class Test(unittest.TestCase): def test_silly_make_one_delay(self): response = client.get("/api/v1/silly-users/make-one?delay=1") assert response.status_code ==...
#!/usr/bin/env python ''' Nets Handles the structures of neural networks. ''' # imports import tensorflow as tf tf.enable_eager_execution() import numpy as np import logging import sys # helper functions def gru(units, reverse = False): """ Parameters ---------- units : param reverse: (Def...
import cv2 import numpy as np import tensorflow as tf from utils.imagenet_utils import * from time import time if __name__ == '__main__': model_path, input_dims, input_name, output_names = \ 'models/mobilenet_v2/model.pb', (224, 224), 'input', ['MobilenetV2/Predictions/Reshape_1:0'] #with tf.device('/G...
from flask import Flask import json import getdata data = getdata.return_data() app = Flask( 'ENS-DIR' ) @app.route( '/' ) def index(): return 'Welcome to ENS DIR API' @app.route( '/address/<address>' ) def address_route( address ): if address in data[ 'addresses' ]: return json.dumps( data[ 'address...
import pyparsing from pyparsing import Literal, CaselessKeyword, CaselessLiteral, \ Word, Optional, OneOrMore, Group, Combine, ZeroOrMore, nums, \ Forward, StringEnd, restOfLine, alphas, alphanums, Empty, \ Or def _unsigned_simple_number(): # fnumber : 102.43, 12304.3e10, # .32??? ...
import string with open('input.txt', 'r') as inputf: inlist = inputf.readlines() result = 0 i=0 inlist.append('\n') #needed for last group to check for j in range(len(inlist)): if (inlist[j] == '\n'): for letter in string.ascii_lowercase: result += letter in (''.join(inlist[i:j])) i...
"""Unit tests for the route authentication plugin.""" import logging import unittest from datetime import datetime, timezone from unittest.mock import Mock import bottle from routes.plugins import AuthPlugin, InjectionPlugin class AuthPluginTest(unittest.TestCase): """Unit tests for the route authentication an...
''' Simple altitude-hold PID controller to test dynamics Copyright (C) 2020 Simon D. Levy MIT License ''' import gym import numpy as np import matplotlib.pyplot as plt import argparse import gym_copter DURATION = 5 # seconds ALTITUDE_TARGET = 10 # meters # PID params ALT_P = 1.0 VEL_P = 1.0 VEL_I = 0 VEL_...
class OutputSystem: """A system which sends its level out on an output address""" def __init__(self, address, output): self._address = address self._output = output def set_level(self, level): self._output.set_level(self._address, level) class CompoundSystem: """A system made...
PORT = 31232 MAX_MSG_LEN = 65536
import numpy as np from sklearn.model_selection import KFold from sklearn.metrics import average_precision_score from sklearn.svm.classes import SVC from sklearn.metrics.pairwise import laplacian_kernel from sklearn.model_selection import ParameterGrid from sklearn.multiclass import OneVsRestClassifier import copy cla...
#!/usr/bin/env python3 # Copyright 2004-present Facebook. All Rights Reserved. from ...messages import Message class WSServerMessage(Message): """ A message representing data that was/will be communicated to WebSocket. """ data: str
from django.contrib import admin from image_cropping import ImageCroppingMixin # Register your models here. from news.models import NewsModel class NewsModelAdmin(ImageCroppingMixin, admin.ModelAdmin): readonly_fields = ["preview_count"] fields = [ "image", "name", "text", "cropping", "preview_count" ...
# # UEFI signature validation # # Copyright (C) 2019 Canonical, Ltd. # Author: Mathieu Trudel-Lapierre <mathieu.trudel-lapierre@canonical.com> # # This program 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; v...
import random import os op='s' while(op=='s'): print("\n") print("* "+"-"*29+" *") print("|\tJogo de Adivinhação\t|") print("* "+"-"*29+" *\n") inicio = random.randrange(0, 401) fim = random.randrange(600, 1001) print(f"Descubra o número sorteado entre {inicio} e {fim}\n") lista = l...
""" Problem 3: Largest prime factor https://projecteuler.net/problem=3 The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? """ from src.common.primes import get_prime_factors def main() -> None: """Main function.""" number = 600851475143 prime_fa...