content
stringlengths
5
1.05M
import os import json import dataiku import pandas as pd from dataiku.customrecipe import * from dku_azure_vision import * from azure.cognitiveservices.vision.computervision.models import VisualFeatureTypes #============================================================================== # SETUP #=======================...
# Copyright 2013 Huawei Technologies Co.,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 # # Unl...
#!/usr/bin/env python3 # encoding: utf-8 ''' @author: jkiesele ''' import sys import os import tempfile from argparse import ArgumentParser from pdb import set_trace import logging logging.basicConfig(format='%(asctime)s:%(levelname)s:%(name)s: %(message)s') logging.getLogger().setLevel(logging.INFO) from Deep...
def add_unet_config(cfg): # UNet settings cfg.MODEL.BACKBONE.ACTIVATION = 'relu' cfg.MODEL.BACKBONE.UNET_CHANNELS = [64, 128, 256, 512, 1024] cfg.MODEL.SEM_SEG_HEAD.UNETPP_USE_SUBNET_IN_INFERENCE = 0 cfg.MODEL.SEM_SEG_HEAD.SEM_SEG_LOSS_TYPE = 'CrossEntropy' cfg.INPUT.ENABLE_RANDOM_BRIGHT...
import FWCore.ParameterSet.Config as cms from DQMServices.Core.DQMEDHarvester import DQMEDHarvester effPlotterLoose = DQMEDHarvester("EfficiencyPlotter", folder = cms.string("Muons/EfficiencyAnalyzer"), phiMin = cms.double(-3.2), ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __Lisence__ = "BSD" __maintainer__ = "Justin Furuness" __email__ = "jfuruness@gmail.com, agorbenko97@gmail.com" __status__ = "Development" from math import e import random from matplotlib.pyplot import Circle, text class Anim_User: """Animated User""" patch_ra...
import numpy as np class Segmentation(object): """Segmentation of fields of view. This class handles the segmentation of fields of view in (nx, ny) segments. Attributes: nx (int): Number of segments along x-axis (0-index). ny (int): Number of segments along y-axi...
import cupy as np def kernel(A, B, C, D): return A @ B @ C @ D
import JeevesLib import unittest import mock # from mock import MagicMock from mock import patch import Auth import ExternNetwork from ExternNetwork import Request, Response import HealthMgr class TestHealthWeb(unittest.TestCase): def setUp(self): JeevesLib.init() # x = Auth.Test() # self.auth = Authent...
import shades canvas = shades.Canvas() black = shades.BlockColor((20, 20, 20)) red = shades.BlockColor((255, 20, 0)) blue = shades.BlockColor((0, 139, 200)) swirl = shades.SwirlOfShades( shades = [ (0.25, 0.3, black), (0.3, 0.4, red), (0.4, 0.45, black), (0.55, 0.6, black), ...
import telebot from datetime import datetime, timedelta import urllib.request, json bot_token = '808951815:AAEHHP271TDAib_Bo2IdPexCoXLqM8SnTj4' # NOT THE ACTUAL TOKEN FOR OUR BOT bot = telebot.TeleBot(token = bot_token) def getTemp(location): utc_now = datetime.utcnow() sg_now = utc_now + timedelta(hours=8) ...
from bs4 import BeautifulSoup from modules.crawler.etc.url_parser import URLparser from modules.crawler.dbs.mongo.db_manager import db_manager from selenium import webdriver import datetime from modules.crawler.login import everytime import time from selenium.webdriver.common.by import By from selenium.webdriver.suppor...
import time from typing import List from collections import defaultdict class UnionFindSet: def __init__(self): self.parents = defaultdict() def find(self, x) -> int: """Return node(id=x)'s root node id.""" self.parents.setdefault(x, x) # set as default if x not exists if x ...
# Computational Linear Algebra ex2 # By: Nick Space Cowboy import numpy as np import time if __name__ == "__main__": s = time.time() # Generates a random 1000x1000 matrix with values between zero to 1 million A = np.array(np.random.randint (0,1000000,(1000,1000))) b = np.zeros(1000) # Changes the 69th value of t...
import sys import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as pl # import pylab as pl if len(sys.argv) != 2: print("Need a filename for the plot output. Exiting...") else: outputFile = sys.argv[1] data = [] for line in sys.stdin: data.append(line.strip()) data=map(int, data...
from __future__ import annotations from spark_auto_mapper_fhir.fhir_types.uri import FhirUri from spark_auto_mapper_fhir.value_sets.generic_type import GenericTypeCode from spark_auto_mapper.type_definitions.defined_types import AutoMapperTextInputType # This file is auto-generated by generate_classes so do not edi...
from django.db import models # https://docs.djangoproject.com/fr/3.1/intro/tutorial02/ # Cette fonction est utilisée pour formater les URL from django.urls import reverse from django.contrib.auth.models import User # Create your models here. # # https://fr.wikipedia.org/wiki/XML_Bookmark_Exchange_Language class B...
import numpy as np from itertools import repeat from functools import reduce import multiprocessing as mp import math import h5py from sklearn.model_selection import train_test_split def load_data(filename): return np.load(filename, allow_pickle=True) def sampling(data, num): try: data, y = data ...
from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter class Command(BaseXpressDemocracyClubCsvImporter): council_id = "E07000210" addresses_name = "parl.2019-12-12/Version 1/Democracy_Club__12December2019Mole.tsv" stations_name = "parl.2019-12-12/Version 1/Democracy_Club__12De...
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. # # 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 appl...
import numpy as np from rlberry.agents.bandits import BanditWithSimplePolicy import logging logger = logging.getLogger(__name__) # TODO : fix bug when doing several fit, the fit do not resume. Should define # self.rewards and self.action and resume training. class IndexAgent(BanditWithSimplePolicy): """ ...
from keras.layers import Input, Dense, Dropout, Embedding, Conv1D, MaxPooling1D, Flatten, concatenate from keras.models import Model import numpy as np def text_classifier_model(vocab_size, maxlen, num_classes): # This returns a tensor inputs = Input(shape=(maxlen,), dtype=np.int32) predictions = Dense(nu...
from clifford import * import random import math class ConformalGeometricAlgebra(object): def __init__(self, resolution=1e-15): self.layout, self.blades = Cl(4,1) pretty() self.resolution = resolution eps(self.resolution) self.e1, self.e2, self.e3, self.e_hat, self.e = [sel...
''' Aula 09 - Input (Entrada de Dados do Usuário) ''' ''' # Exemplo de aplicação com input: nome = input ("Qual o seu nome ? ") idade = input( "Qual a sua idade? ") ano_nascimento = 2021 - int(idade) print (f'{nome} tem {idade} anos. {nome} nasceu em {ano_nascimento}') ''' # Exemplo de cálculo: numero1 = int(input("D...
import time from redis import StrictRedis from .. import BaseLock, LockTimeout class RedisLock(BaseLock): url_scheme = 'redis' @classmethod def get_client(cls, **connection_args): host = connection_args.get('host') or 'localhost' port = connection_args.get('port') or 6379 passwo...
import copy import torch class BYOL(torch.nn.Module): r"""Base backbone-agnostic BYOL architecture. The BYOL architecture was proposed by Grill et al. in Bootstrap Your Own Latent: A New Approach to Self-Supervised Learning https://arxiv.org/abs/2006.07733 Two views are separately forwarded ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """测试自定义ma的创建""" class TestMaCreataion: def test_init_app(self, app): from app.extensions.marshal import ma from marshmallow import EXCLUDE ma.init_app(app) class TestSchema(ma.Schema): pass assert TestSchema.Met...
''' input pwm files output tab-deliminated location table (future work) output motif hit file (.mhit) 9-29-2015 Yichao combines Rami's code ''' import shutil from utils import Fimo from utils import general_utils import re import os def run_fimo(jid, confDict,fileList): MS_folders = [] MS_dir = jid+...
from enum import IntEnum from local_modules.libinput_mappers import GestureSwipeUpdate # will only be ever cleaning up as much data as needed, the rest needs cleanup too def cleanup_swipe_event_list(event_list): # remove + from the start and s from the end event_list[GestureSwipeUpdate.TIME] = event_list[Gestu...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Common Python library imports # Pip package imports # Internal package imports from .unit import Unit from .soil_type import SoilType from .agricultural_type import AgriculturalType from .region import Region from .country import Country from .crop_type import CropType ...
'''communicate and read/write configuration info''' import sys import os.path import configparser def str2bool(S): '''convert a string to a boolean we use only the first letter''' return { '0': False, 'n': False, 'N': False, 'f': False, 'F': False, '1': True...
from __future__ import print_function import calendar from datetime import datetime from itertools import chain, ifilterfalse from operator import itemgetter from platform import python_version_tuple import nltk from bs4 import BeautifulSoup from six import iteritems if python_version_tuple()[0] == '3': imap = ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function from __future__ import division from __future__ import absolute_import import argparse from DBGater.db_singleton_mongo import SynDevAdmin __author__ = 'Ziqin (Shaun) Rong' __maintainer__ = 'Ziqin (Shaun) Rong' __email__ = 'rongzq08@g...
#!/usr/bin/env python # -*- coding: utf-8 -*- from typing import Dict, Iterator, List, Optional, Union, Literal, Tuple import os CWD = os.path.dirname(os.path.abspath(__file__)) DIR_DATA = os.path.join(CWD, '..', '..', 'data') import math import json from tqdm import tqdm from multiprocessing import Pool from sqlalchem...
# -*- coding: utf-8 -*- from __future__ import absolute_import from .morphology import GrayscaleGrindPeakImageFilter, GrayscaleFillHoleImageFilter from .denoising import GradientAnisotropicDiffusion, CurvatureAnisotropicDiffusion, GaussianBlurImageFilter, MedianImageFilter from .arithmetic import MultiplyScalarVolumes,...
"""Implementation of :class:`jukeboxcore.reftrack.ReftypeInterface` for Assets.""" from collections import defaultdict from functools import partial import maya.cmds as cmds from jukeboxcore import djadapter from jukeboxcore.filesys import JB_File from jukeboxcore.reftrack import ReftypeInterface, ReftrackAction from...
#!/usr/bin/env python import httplib import json import os host = os.getenv('ELASTICSEARCH_HOST', "localhost") port = os.getenv('ELASTICSEARCH_PORT', "5601") http = httplib.HTTPConnection(host+":"+port) try: http.request("GET", "/_stats/indexes") except Exception as e: print(type(e)) response = http.getresponse...
# Problem : https://www.hackerrank.com/challenges/nested-list/problem # Score : 10 points(MAX) n = int(input()) # Numerod e alunos alunos = [[input(), float(input())] for _ in range(n)] # Para cada aluno fazemos um input de nome, nota(float) def organiza(aluno_nota): """ :param aluno_nota: lista de alunos,...
print 'Hello world' print 'Hello again' # comment
import ROOT import numpy as np import melp from melp import Detector from melp.clustering.misc import* import melp.clustering.tracking as clump_tr #clustering that checks for every frame if in the frame before or after are constituents of clusters from "middle" frame #----------------------------------------------...
import paho.mqtt.client as mqtt import time import sys def on_connect(client, userdata, flags, rc): print(f"Connected with result code {rc}") client = mqtt.Client() client.on_connect = on_connect client.connect("broker.emqx.io", 1883, 60) client.publish(f'raspberry/sensorweb{sys.argv[1]}', payload=sys.argv[2], q...
import asyncio import re import time from typing import Optional from nonebot import MessageSegment from nonebot import on_command, CommandSession from nonebot import on_natural_language, NLPSession, IntentCommand from nonebot.command.argfilter import extractors, validators from IAI.iai.common.aio import requests fro...
import re from Products.ZenRRD.CommandParser import CommandParser class who(CommandParser): def processResults(self, cmd, result): valueMap = { 'total': 0 } # process command output if cmd.result.output: for line in cmd.result.output.splitlines(): if re.search('...
from Node import Node from typing import Tuple, List from Un_representation import O_equationset def prune(reachable_in_k, L, m, n, W): """ method used to prune after each step of the coverability algorithm :param reachable_in_k: the values the coverability method generated with a single step :return:...
# Generated by Django 2.2.2 on 2019-06-24 00:56 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('live', '0002_auto_20190623_2145'), ] operations = [ migrations.AddField( model_name='live', name='like', ...
import os from torch.nn import ReLU from math import floor import numpy as np import matplotlib.pyplot as plt from utils.config import config def output_size_conv2d_layer(height, width, layer): kernel_size, stride, padding, dilation = layer.kernel_size, layer.stride, layer.padding, layer.dilation kernel_size ...
import os import numpy as np from typing import List MODULE_DIR = os.path.dirname(os.path.realpath(__file__)) PROJECT_DIR = os.path.join(MODULE_DIR, "..") INPUT_SOURCE_DIR = os.path.join(PROJECT_DIR, "input") class Die: def __init__(self): self.last_roll = 0 self.roll_count = 0 def roll(self...
#!/usr/bin/env python3 import OpenSSL from OpenSSL import crypto import base64 import hashlib key_file = open("../public.pem", "r") key = key_file.read() key_file.close() pkey = crypto.load_publickey(crypto.FILETYPE_PEM, key) with open("../sample.bin","rb") as f: with open("sign.sha256", "rb") as s: x509 =...
import cv2 import numpy import cProfile # read image img_name='../lenna512x512.png' src = cv2.imread(img_name, cv2.IMREAD_UNCHANGED) # apply guassian blur on src image cProfile.run('dst = cv2.GaussianBlur(src,(5,5),cv2.BORDER_DEFAULT)') # display input and output image cv2.imshow("Gaussian Smoothing",numpy.hstack((...
# This file is part of Buildbot. Buildbot 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, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
DEBUG = 8 import argparse import numpy as np import os from os.path import dirname import torch import torchvision from torch.utils.tensorboard import SummaryWriter import tqdm if DEBUG>0: from utils.models1 import Classifier else: from utils.models import Classifier from utils.dataset import NCaltech101 from...
from http import HTTPStatus as status from random import randint from typing import Callable, Optional import pytest from bson import ObjectId from faker import Faker from pymongo.results import InsertOneResult from app.core.utils import encode_share_key from . import AuthData, client, db from .conftest import Create...
from testdriver import * from transformers import pipeline, TextClassificationPipeline, BertTokenizer, BertForSequenceClassification if torchscript: print('TorchScript not supported!') exit(-1) txt = [ 'I hate you', 'I love you', 'The sun looks beautiful today', 'So call me maybe', 'This merchant is cra...
# Generated by Django 3.1.4 on 2021-01-11 15:28 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('wagtail_wordpress_importer', '0070_customfieldslayoutsubfield_custom_field'), ] operations = [ migrations.RemoveField( model_name='custo...
''' Functions used to process results from IAFD Version History --------------- Date Modification 06 Apr 2021 Return unprocessed cast and director lists if IAFD returns a 403 Error, rather than an exce...
""" This file is to enable and disable modules on will. If module name is "True", the module will be enabled within Ableton. Otherwise the functionalities will not be used. """ MIXER_ENABLED=True TRANSPORT_ENABLED=True
''' run_flipflop.py Written using Python 2.7.12 @ Matt Golub, October 2018. Please direct correspondence to mgolub@stanford.edu. ''' from __future__ import absolute_import from __future__ import division from __future__ import print_function import pdb import sys import argparse import numpy as np PATH_TO_FIXED_POIN...
import _pickle as cPickle import gzip import random import numpy as np import os,time,subprocess,glob from stackPH import lifeVect,histVect from scipy.ndimage.morphology import distance_transform_edt from skimage.filters import threshold_otsu from skimage.transform import resize import matplotlib.pyplot as plt from mpl...
from PIL import Image as Im from PIL import ImageFile from os import walk, path, makedirs, listdir, name import random import time from math import floor # Helper Variables and Flags slash = "\\" if name == 'nt' else "/" ImageFile.LOAD_TRUNCATED_IMAGES = True # Folders input_folder = "." + slash + "input" output_fo...
#!/usr/bin/env python import json from skimage.color import deltaE_ciede2000 # For reducing the colourset # requires scikit-image def rgb2one(r): return (float(r[0]/256),float(r[1]/256),float(r[2]/256)) ##with open("dmc.json") as w: #with open("limited.json") as w: with open("raw/color.json") as w: DMC ...
import logging import sys import re from cme.helpers.misc import called_from_cmd_args from termcolor import colored from datetime import datetime #The following hooks the FileHandler.emit function to remove ansi chars before logging to a file #There must be a better way of doing this, but this way we might save some p...
from django.test import TestCase from django.core.exceptions import ValidationError from django.contrib.flatpages.models import FlatPage from oscar.core.validators import ExtendedURLValidator from oscar.core.validators import URLDoesNotExistValidator class TestExtendedURLValidatorWithVerifications(TestCase): """...
from sklearn.model_selection import train_test_split import numpy as np import pandas as pd import scipy as sp from copy import deepcopy import os DIR, filename = os.path.split(__file__) class Simulation(): def __init__(self, num_sample=1000, num_feat=2, num_genes=10000, dispersion_min=25, ...
from .summarizer import KeywordSummarizer from .summarizer import KeysentenceSummarizer
def is_python_26(): import sys return sys.version_info[:2] == (2, 6) if is_python_26(): import unittest2 as unittest else: import unittest class expected_failure_when(object): def __init__(self, condition): self.condition = condition def __call__(self, function): if self.cond...
import unittest import logging import multiprocessing import socket import time import os from flask import Flask from typing import List from bagua.bagua_define import TensorDeclaration, BaguaCoreTelemetrySpan from bagua.service import AutotuneService, AutotuneClient from bagua.bagua_define import BaguaHyperparameter,...
import numpy as np # Inputs inputs = [[1, 2, 3, 2.5], [2.0, 5.0, -1.0, 2.0], [-1.5, 2.7, 3.3, -0.8]] # Weights weights = [[0.2, 0.8, -0.5, 1.0], [0.5, -0.91, 0.26, -0.5], [-0.26, -0.27, 0.17, 0.87]] # Bias biases = [2,3,0.5] # Weights weights1 = [[0.1, -0.14, -0.5], [-0.5, 0.12, -0.33],...
#!/usr/bin/env python # # Copyright (c) 2018 Sarah Tollman, 2021 Theo Jepsen # All rights reserved. # # This software was developed by Stanford University and the University of Cambridge Computer Laboratory # under National Science Foundation under Grant No. CNS-0855268, # the University of Cambridge Computer Laborato...
# Copyright (c) 2012-2016 Seafile Ltd. from django.conf.urls import url, include from django.views.generic import TemplateView urlpatterns = [ url(r'^$', TemplateView.as_view(template_name="help/introduction.html")), url(r'^introduction/$', TemplateView.as_view(template_name="help/introduction.html")), ur...
# pylint: disable=C0103 """lattedb URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, ...
"""Loading tests"""
from .telenium_process import TeleniumTestProcess from .common import skip_screen_checks from .common import ordered class TrashMessage(TeleniumTestProcess): """Trash Screen Functionality Testing""" @skip_screen_checks @ordered def test_delete_trash_message(self): """Delete Trash message perm...
# -*- coding: UTF-8 -*- ''' Created on 24.10.2010 @author: SIGIESEC ''' from base.basic_config_if import BasicConfig from base.dependency.generation_log_if import GenerationLogSupply from commons.configurator import Configurator from commons.scm_default import FallbackVersionDescriber from commons.scm_if import Versi...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'time_range.ui' # # Created by: PyQt5 UI code generator 5.10.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_TimeRange(object): def setupUi(self, TimeRange): TimeRan...
from fpdf import FPDF # Author: @NavonilDas class MyPdf(FPDF): def header(self): # Uncomment the line below to add logo if needed # self.image('somelogo.png',12,10,25,25) # Draw Image ar (12,10) with height = 25 and width = 25 self.set_font("Arial", "B", 18) self.text(27, 10, "Ge...
import json import sys from datetime import datetime import numpy as np import data_set_handler import forest_config import h2o import html_output import result_log import scikit_wrapper BIN_FOLDER = 'bin/' DEPENDENCIES_FOLDER = 'dependencies/' IMPLEMENTATIONS = {'h2o': h2o.H2OWrapper, 'scikit': ...
def get_query(): limit = 6 sql = f"SELEct speed from world where animal='dolphin' limit {limit}" return sql
"""Ultra simple data frames. """ def frame_from_iter(iterable, names): """Create data frame from records. """ frame = {name:[] for name in names} for rec in iterable: for i,name in enumerate(names): frame[name].append(rec[i]) return frame def iter_from_frame(frame, names): """Iterate through data frame ""...
# System Imports from typing import Union, NoReturn # Third-Party Imports # Local Source Imports from .context import Context __author__ = 'H.D. "Chip" McCullough IV' """ A Dictionary of values for creating a connection string. """ __settings__ = { 'drivername': '', 'host': '', 'port': 0, '...
class ModelName(enumerate): ''' Model names from tf.keras.applications, using version 2.6.0 https://www.tensorflow.org/api_docs/python/tf/keras/applications ''' # image classification MobileNetV1 = 'MobileNetV1' MobileNetV2 = 'MobileNetV2' MobileNetV3_Large = 'MobileNetV3_Large' Mobi...
import os import sys import math import random import numpy as np import cv2 # Root directory of the project ROOT_DIR = os.path.abspath("../../") # Import Mask RCNN sys.path.append(ROOT_DIR) # To find local version of the library from mrcnn.config import Config from mrcnn import utils import prepare_data class Pil...
# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the MIT License. See the LICENSE file in the root of this # repository for complete details. """ Structured logging for Python. """ from __future__ import absolute_import, division, print_function from structlog import dev, proce...
from django.db import transaction from rest_framework import generics, status from rest_framework.response import Response from rest_framework.views import APIView from drf_role.utils.url_utilities import get_urls from drf_role.models import Role, Permission, AccessControl from drf_role.permissions import IsAdminOrNoA...
__project_name__ = "textabstractor" # noqa: F401 __version__ = "0.1.1"
"""Тестирует функцию quick_sort со значением reverse=False""" import pytest from ..sort_func import quick_sort def test_empty(): srt_lst = [] quick_sort(srt_lst) assert srt_lst == [], "Ошибка с пустым списком" def test_one_element(): srt_lst = [1] quick_sort(srt_lst) assert srt_lst == [1], "...
from __future__ import unicode_literals from django.db import models from datetime import datetime from django.utils import timezone from django.db.models import Model, CharField, ForeignKey, IntegerField, DecimalField, BooleanField, DateTimeField from api.models.school_models import School from api.models.grade_model...
import os # Train undefended models command = 'python -m' train_type = 'train' models_directory = 'models/' models = {'modelA': '0', 'modelB': '1', 'modelC': '2', 'modelD':'3'} print('Training undefended models...') for name, type_ in models.items(): full_command = "{} {} {}{} --type={}".format(command, train_type,...
# coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from api.models.base_model_ import Model from api import util class LineNode(Model): """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-g...
/home/runner/.cache/pip/pool/bc/8a/30/3d82a41e4b09716563a874286bea08d62d83d12ee0b127721736432440
# Zmodyfikuj rozwiązanie zadania z poprzedniej lekcji wykorzystując w swojej implementacji bibliotekę Beautiful Soup from dataclasses import dataclass from enum import Enum import requests from bs4 import BeautifulSoup class CourseType(Enum): DAILY_CLASS = "kurs dzienny" EVENING_CLASS = "kurs wieczorowy" ...
import sys sys.path.append('./../') from q_learning.ql_mb import q_learning_model_based num_s = 6 a_spc = [4, 3, 1, 2, 2, 1] r_spc = [ [51, -5, -20, 50], [-5, -20, -1], [-20], [-2, 0], [-1, -2], [0], ] nxt_s_spc = [ [[0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0], [0, 0, 0, 0, ...
def menu(): from .gamemenu import SnakeGameMenu SnakeGameMenu().menu()
my_global_bool: bool = True my_global_list = [] def func(): my_nonlocal_bool: bool = True my_nonlocal_list = [] my_nonlocal_list.append(1) global my_global_bool global my_global_list my_global_bool.<warning descr="Unresolved attribute reference 'append' for class 'bool'">append</warning>(...
"""Setup.""" try: from setuptools import setup except: # pylint: disable=bare-except # noqa: E722 # NOLINT from distutils.core import setup # pylint: disable=wrong-import-order VERSION = '0.1.0' setup( author='Chris Reffett', name='tslim_usb', description='Experimental tool/library to get data...
# Generated by Django 3.2.9 on 2021-12-03 14:26 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="Address", fields=[ ( "name",...
#!coding: utf-8 """ Udacity - Airbus Artificial Intelligence Nanodegree Cédric Campguilhem - Mars 2020 """ # Future imports from __future__ import annotations # Standard library import argparse import sys from typing import Sequence import os # Project from model import FlowerClassifier def cmdline(argv: Sequence[s...
#! /usr/bin/python import random def isnan(x): if isinstance(x, int): return False if isinstance(x, float): return False if isinstance(x, complex): return False return True class Matrix(): def __init__(self, rows, cols): self.cols = cols self.rows = rows ...
import pandas as pd import numpy as np def fix_missing(file, fix_option): # file.rename(columns=lambda x: x.strip(), inplace=True) if fix_option == 'skip': print (fix_option) file.dropna(axis=0,inplace=True) elif fix_option == 'mean': print (fix_option) file.dropna(axis=0, ...
from clearml import Task task = Task.init(project_name="Rapids", task_name="kmeans") n_samples = 10**6 n_features = 2 n_clusters = 5 random_state = 23 """## Generate Data""" import cudf from cuml.datasets import make_blobs device_data, device_labels = make_blobs(n_samples=n_samples, ...
# -*- encoding: utf-8 -*- from shapely.wkt import loads as wkt_loads import dsl from . import FixtureTest class NormalizePlaceKind(FixtureTest): def test_state(self): # Node: California (671022) self.generate_fixtures(dsl.way(671022, wkt_loads('POINT (-118.755997317217 36.70146306433398)'), {u'nam...