text
stringlengths
38
1.54M
__author__ = 'Michal' from string import Template import subprocess, shutil, logging, os, time, datetime, glob #interface between generator and the speacilist #drives the application under test #be able to drive application videoLAN #provide several conversion options #convert a song to a specified format #convert it...
#!/usr/bin/env python """ .. code:: python publisher = PubsubPublisher('project_id', 'path/to/sa.json', 'topic_name') publisher.publish_message('hello') """ import logging from collections import defaultdict from collections.abc import Mapping from time import time from . import QueuePublisher try: from...
import torch.nn as nn import torch.nn.functional as F class ResNet(nn.Module): def __init__(self, channels, layers, same_shape=True): super(ResNet, self).__init__() self.resnet = nn.ModuleList([]) self.resnet.append(Residual(channels, same_shape=same_shape)) for it in range(layers-1...
import numpy as np import time class Timer(object): def __init__(self, name=None): self.name = name self.tstart = time.time() self.tlast = self.tstart self.firstCall = True def getElapseTime(self, isStr=True): totalElapsed = time.time() - self.tstart # elapsed t...
import itertools import pandas as pd def generateSubset(list_kombinasi): lhs = [] rhs = [] for el in list_kombinasi: for i in range (1,len(el)): comb = list(itertools.combinations(el, i)) for row in comb: lhs.append(list(row)) rhs.append(list(set(el).difference(row...
#!/usr/bin/python # Date: 2018-09-03 # # Description: # 1. issubclass(class-1, class-2) -> Checks if class-1 is derived from class-2 or # in other words is class-2 base class of class-1 or not. # # 2. isinstance(object, class-name) -> Checks if object is instance of # class-name or not. class base: pass cl...
import random moves = ['r', 'p', 's'] player_wins = ['pr', 'sp', 'rs'] while True: player_move = input("your move: ") if player_move == 'q': break computer_move = random.choice(moves) print ("You: ", player_move) print ("Me: ", computer_move) if player_move == computer...
import tkinter as tk from tkinter import * import pytesseract from PIL import Image, ImageTk #mainclass class MainApp(Frame): def __init__(self): super().__init__() self.appGUI() def appGUI(self): #title of the gui self.master.title("Simple Demonstration ...
import sys import urllib2 import json from AppInfo import AppInfo import abc class AppCrawler(object): def __init__(self, appUrl): self.appUrl = appUrl self.appInfo = None @abc.abstractmethod def crawl(self): pass def getAppInfo(self): if not self.appInfo: ...
# -*- coding: utf-8 -*- """ Created on Fri Oct 18 02:57:09 2019 @author: Ashima """ import time import cv2 import pickle import pandas as pd import config import os import numpy as np from skimage.feature import hog class Data: def __init__(self): self.dataX = None self.dataY = None self.s...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.CreditPayMoneyVO import CreditPayMoneyVO class MybankCreditLoantradeGuarletterInvoiceApplyModel(object): def __init__(self): self._address = None self._apply_...
import numpy as np import os from dataset.mnist import load_mnist from ch5.multi_layer import MultiNet import matplotlib.pyplot as plt dataset_dir = os.path.dirname(os.path.abspath('__file__')) save_file = dataset_dir + "/mnist.pkl" (x_train, t_train), (x_test, t_test) = load_mnist(dataset_dir, save_file, normalize=T...
# -*- coding: utf-8 -*- """ Created on Thu Mar 9 11:44:04 2017 @author: River """ import sys def print_lol(the_list,level=0,indent=False,fn=sys.stdout): for each_item in the_list: if isinstance(each_item,list): print_lol(each_item,indent,level+1,fn) else: if(indent): ...
from django.db import models from billing.models import BillingProfile class Address(models.Model): billing_profile = models.ForeignKey(BillingProfile, on_delete=models.CASCADE) first_name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) company = models.CharField(max_len...
# -- Server -- FLASK_HOST = '0.0.0.0' FLASK_PORT = 8080 ROUTE_PORT_MAPPING = { 8001: '/radare1/', 8002: '/radare2/', 8003: '/radare3/', 8004: '/radare4/', } # -- Scheduler -- RADARE_TIMEOUT = 600 RADARE_PORTS = list(ROUTE_PORT_MAPPING.keys()) QUEUE_BLOCK_TIMEOUT = 1
# -*- coding: utf-8 -*- """ Created on Wed Jan 23 21:05:23 2019 @author: user """ from core.preprocessing.tweet_preprocessing import( preprocess, translate_to_telugu, translate_to_english, telugu_tweet_to_english) from core.extraction.tweet_extraction import ( twitte...
import os, glob import argparse import numpy as np import librosa import soundfile as sf import torch # utils from tqdm import tqdm from multiprocessing import Pool, cpu_count # Due to 'PySoundFile failed. Trying audioread instead' import warnings warnings.filterwarnings('ignore') # param parser = argparse.Argumen...
import json from datetime import timedelta from typing import List, Tuple from django.db import transaction from django.db.models import Max, Q from django.db.models.functions import Greatest from django.dispatch import receiver from django.utils.timezone import now from django.utils.translation import gettext_lazy as...
## DecisionTreeClassifier for multi-classification from sklearn import tree from sklearn.datasets import load_iris iris = load_iris() clf = tree.DecisionTreeClassifier() clf = clf.fit(iris.data, iris.target) from sklearn.externals.six import StringIO with open("iris.dot", 'w') as f: f = tree.export_graphviz(...
from __future__ import annotations import logging import os from contextlib import suppress from datetime import date from pathlib import Path from . import _types as _t from ._run_cmd import CompletedProcess as _CompletedProcess from ._run_cmd import require_command from ._run_cmd import run as _run from .git import...
from django.contrib import admin from shop.models import * # registers the models into the admin page admin.site.register(Game) admin.site.register(State) admin.site.register(Score) admin.site.register(Category) admin.site.register(GamesCategory) admin.site.register(Purchase)
from django.shortcuts import get_object_or_404, redirect, render from managementapp import forms from managementapp.models import Project from managementapp.utils import setProjectPriority, setProjectDeadline def projectList(request): setProjectPriority() setProjectDeadline() return render(request, 'cli...
from fastapi import APIRouter from fastapi import Depends, status from blog import schemas, database, oauth2 from blog.repository import blog_repository from sqlalchemy.orm import Session from typing import List router = APIRouter( prefix='/blog', tags=['blog'] ) @router.post('/', status_code=status.HTTP_20...
import json import os import sys import itertools import random from urllib.request import urlopen BASE_URL = os.environ.get('BASE_URL', 'http://localhost:9000') region_ids = ['little-yoho', 'banff-yoho-kootenay', 'northwest-coastal', 'northwest-inland', 'sea-to-sky', 'south-coast-inland', 'south-coast', ...
# RECUERDEN NO IGNORAR ESTE ARCHIVO, O NO LES PODREMOS CORREGIR. POPULARIDAD_MINIMA_DELEGACION = 0 PROBABILIDAD_ACCIDENTARSE_GIMNASIA = 0.3 # COMPLETAR... INICIADOR_LOOP = True NIVEL_IMPLEMENTOS = 0 MORAL_MINIMA = 20 DIAS_COMPETENCIA = 6 #### ENTRENAR #### COSTO_ENTRENAR = 30 PUNTOS_ENTRENAMIENTO = 12 BONIFICACION_IE...
from common import create_directory from data_source import get_labelled_tweets import timeit def get_dataset_time(time, repetitions): """ time to predict the full dataset """ svm_time_dataset = time / repetitions return svm_time_dataset def get_record_time(time, num_tweets): """ time to predict 1 rec...
list_numbers = input('Введите числа через запятую: ').split(',') integer_nmbrs = list(map(int, list_numbers)) def get_minimal_positive(): min_ = [] for i in integer_nmbrs: if i + 1 not in integer_nmbrs and i >= 0: min_.append(i+1) return min(min_) elif i <= 0: ...
from django.db import IntegrityError from django.contrib.auth.models import Group from django_odesk.core.clients import DefaultClient from django_odesk.conf import settings def get_odesk_permissions(auth_token): """ Gets oDesk team roles/permissions for the authenticated user """ client = DefaultClien...
def load_instructions(): with open("./input.txt", "r") as f: return f.read().splitlines() def format_instructions(raw_instructions): res = [] for raw_instruction in raw_instructions: splits = raw_instruction.split(" ") operation = splits[0] argument = int(splits[1]) ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/9/28 11:59 # @Author : shursulei # @Site : # @File : BostonHousePricing.py # @Software: PyCharm import numpy as np from sklearn.datasets import load_boston from sklearn.linear_model import LinearRegression import matplotlib.pyplot as plt boston...
import copy class Model: def __init__(self): self.turn = 1 self.board = [[False for i in range(8)] for j in range(8)] self.lastEvent = 0 self.events = [] self.initBoard() def initBoard(self): cid = 0 ids = 'abcdefghijklmnopqrstuwxy' for i in ra...
import os import json import time import math import matplotlib.pyplot as plt from core.data_processor import DataLoader from core.model import Model def main(): configs = json.load(open('config.json', 'r')) if not os.path.exists(configs['model']['save_dir']): os.makedirs(configs['model']['save_dir']) dat...
#ordenar una lista por la longitud de sus cadenas L=["zzz","a","x","23xxx","aaaa""vfg"] L2=["zzz","a","x","23xxx","aaaa""vfg"] print ("L:", L) L.sort() print ("L.sort: ", L) print ("\n") print ("L2:", L2) L2.sort(key=len) print ("L2.sort: ", L2)
import os from os.path import join, getsize, expanduser import re import fileinput import numpy as np import matplotlib.pylab as plt from scipy.interpolate import UnivariateSpline from scipy.integrate import quad from StringIO import StringIO import pyfits import scipy # If you input a light curve, it figures out th...
from graphviz import Graph, nohtml from enum import Enum, auto, Flag from math import sqrt from sys import argv class NodeType(Enum): START = auto() ROUTER = auto() END = auto() class Direction(Flag): UPSTREAM = auto() DOWNSTREAM = auto() ROOT = UPSTREAM | DOWNSTREAM class Node: __slots__ = ['nodeType'...
from rest_framework import serializers from .models import ServiceModel class ServiceSerializer(serializers.ModelSerializer): username = serializers.CharField(source='createBy.username') class Meta: model = ServiceModel fields = '__all__' class ServiceNameSerializer(serializers.ModelSeriali...
import streamlit as st import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import statsmodels.formula.api as sm import altair as alt from load_data import data_prep_by_school # pip uninstall protobuf python3-protobuf # pip install --upgrade pip # pip install --upgrade protobuf ...
from k5test import * realm = K5Realm(create_kdb=False) realm.run(['./t_stringattr']) success('String attribute unit tests')
import numpy as np def log_loss(AL, Y): """ Computes the logistic loss of our predictions. """ m = Y.shape[1] cost = (- 1 / m) * (np.dot(Y, np.log(AL.T)) + np.dot(1 - Y, np.log(1 - AL.T))) # Ensure the single dimension cost value cost = np.squeeze(cost) return...
import luigi import random import logging from logging.config import dictConfig import yaml from liker.tasks import LikeLatest, GetFollowers from liker import credentials_file logger = logging.getLogger(__name__) class RandomBatchFromAuthorities(luigi.WrapperTask): authority_profiles = luigi.Parameter() cr...
from pprint import pprint from collections import OrderedDict from XwingDataDevTools.normalize.base import SingleDataAnalyticalNormalizer class OrderNormalizer(SingleDataAnalyticalNormalizer): def analise(self): fields = set() for model in self.data: fields.update(model.keys()) ...
import mysql.connector #Create the connection object myconn = mysql.connector.connect(host = "localhost", user = "root", password = "test", database = "nit_kit") #printing the connection object print(myconn) #creating the cursor object cur = myconn.cursor() def insert_item(itemname, itempictu...
from datetime import datetime from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions from selenium.common.exceptions import TimeoutException from selenium.webdriver.support import e...
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! """Client and server classes corresponding to protobuf-defined services.""" import grpc from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 from ... import serializer as jina__pb2 class JinaDataRequestRPCStub(object): "...
# Generated by Django 3.0.1 on 2020-06-07 12:08 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('survey', '0003_uploadsurvey_additionaldetails'), ] operations = [ migrations.RemoveField( model_name='uploadsurvey', name='a...
""" This is a proof that intcode is still Turing-complete with only immediate adressing (mode 1) allowed for non-output parameters """ from intcode import Machine mode_pos = 0 mode_imm = 1 mode_rel = 2 DUMMY = 0 def flatten(xss): return [x for xs in xss for x in xs] def opcode(op, mode1=0, mode2=0, mode3=0): ...
from datetime import datetime from opengever.maintenance.debughelpers import setup_app from opengever.maintenance.debughelpers import setup_option_parser from opengever.maintenance.debughelpers import setup_plone from plone import api from Products.CMFPlone.CatalogTool import MAX_SORTABLE_TITLE import logging import re...
# -*- coding: utf-8 -*- import re import sys from nltk.stem import WordNetLemmatizer reload(sys) sys.setdefaultencoding('utf-8') import random import imp import jsonlines import io imp.reload(sys) res = dict() def getargvdic(argv): optd = {} while argv: if argv[0][0] == '-': optd[argv[0]] =argv[1] argv...
import tensorflow as tf import cv2 import numpy as np from imageio import imread import base64 import io class Predictor: model = "OMR/Config/agnostic_model_homophonic" model_meta = "OMR/Config/agnostic_model_homophonic.meta" dictionary_path = "OMR/vocab/agnostic_vocabulary_homophonic.txt" def __ini...
from rest_framework import generics from rest_framework.views import APIView from .models import Poll, Choice from .serializers import PollSerializer, ChoiceSerializer, VoteSerializer,UserSerializer from django.contrib.auth import authenticate class LoginView(APIView): permission_classes = () def post(self, ...
import time from datetime import datetime, timedelta from decimal import Decimal from http import HTTPStatus from logging import getLogger from typing import Optional import requests from django.conf import settings from requests import Response from receipt_tracker.lib import ReceiptParams from receipt_tracker.lib.r...
from itertools import accumulate def leastBricks(wall): asum =[list(accumulate(row)) for row in wall] nums = {} for row in asum: for x in row: nums[x] = nums.get(x, 0) +1 a = sorted(nums.values(), reverse= True) return len(wall) -a[1] wall = [[1,2,2,1], [3,1,2], ...
#importing proper libraries import time import sys import os import subprocess import telnetlib #get modules needed to run monkeyrunner from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice def telnet_call(number, text): print "send sms: " + number + " " + text tn = telnetlib.Telnet("localhost...
# -*- coding: utf-8 -*- """ Created on Thu Nov 4 16:40:50 2021 @author: YOO """ # 라이브러리 불러오기 import pandas as pd import seaborn as sns # titanic 데이터셋에서 age, sex 등 5개 열을 선택하여 데이터프레임 만들기 titanic = sns.load_dataset('titanic') df = titanic.loc[:, ['age', 'sex', 'class', 'fare', 'survived']] # class 열을 기준으로 분할 grouped ...
from random import randint values = [] for x in range(6): value = int(input(f'Enter a number ({x})')) assert 1 <= value <= 49 assert value not in values values.append(value) new_values = [] while True: if len(new_values) == 6: break new_value = randint(1, 49) if new_value not in n...
from keras.preprocessing import image from skimage.color import rgb2gray from skimage.feature import hog import tensorflow as tf import numpy as np import svm import os # Flask from flask import Flask, redirect, url_for, request, render_template from werkzeug.utils import secure_filename # Загрузка приложения app =...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Oct 22 2020 @author: Carolin Brunn """ """ PLOT SIMULATED MATCHING DATA IN ONE GRID """ ################################################################################################ """IMPORT""" import pandas as pd # for using dataframes from matp...
#Definition of inputs and outputs #================================== ##[Mes scripts GEOL]=group ##strati=vector ##dip_dir=field strati ##dip=field strati ##schisto=vector ##dip_dir2=field schisto ##dip2=field schisto #Algorithm body from qgis.core import * from apsg import * layer = processing.getObject(strati) dipd...
import psycopg2 as ps2 from configparser import ConfigParser class DataBase: def __init__(self, db_user, password, host, port, database): self.db_user = db_user self.password = password self.host = host self.port = port self.database = database self.connection = ps2...
__author__ = 'etseng@pacb.com' #import fire from Bio import SeqIO from cupcake.io.BLASRRecord import BLASRM5Reader from cupcake.ice.ice_align_core import eval_blasr_alignment, alignment_has_large_nonmatch #id length is_fl stat pbid def is_a_hit(r, is_fl, max_missed_qstart=50, max_missed_qend=50, max_mis...
""" This file is the main file. The interaction with the recommender service starts here. """ __author__ = "Aitor De Blas Granja" __email__ = "aitor.deblas@ugent.be" import sugestio from sugestio import Consumption, Item, User from numpy import mean, median, unique import data import utils # ACCOUNT = 'sandbox' # S...
# -*- coding: utf-8 -*- # @Time : 2018/6/6 17:01 # @Author : Inkky # @Email : yingyang_chen@163.com ''' error vs tpaa,paa ''' import numpy as np import matplotlib.pyplot as plt paa = np.loadtxt('PAAresult/error_paa.txt', delimiter='\n') bt = np.loadtxt('PAAresult/error_btpaa.txt', delimiter='\n') s...
import tempfile import panda3d.core as p3d from .cli import convert from .common import Settings class BlendLoader: # Loader metadata name = 'Blend' extensions = ['blend'] supports_compressed = False # Global loader options global_settings = Settings() @staticmethod def load_file(pa...
#!/usr/bin/env python3 # Copyright 2011 David Coles. 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 notice, # this list o...
from beem import Steem from beem.blockchain import Blockchain from beem.nodelist import NodeList import time import re def hour_active(chain): nodelist = NodeList() nodelist.update_nodes() if chain=='steem': s = Steem(node=nodelist.get_steem_nodes()) else: ...
# i = 0 #most base loop code # while i < 10: # print(i) # i += 1 # num = 2 # max_num = 120 # while num < max_num: #as long as this true run the While code block!!! # print(num) # num += num # j = 0 # while j < 0: this is an infinite loop will crasht the computer if j # print(j) ...
def most_spoken_languages(): languages = ['English', 'Chinese', 'Hindi', 'Spanish', 'French', 'Standard Arabic', 'Bengali', 'Russian', 'Portuguese', 'Indonesian'] print('Ranking Languages Speak: ') for p, i in enumerate(languages): print(p+1, i) def most_world_population(): cou...
# 可以直接给asyncio传递一些参数去执行 # call_soon # 表示即刻执行,等到队列的下一循环的时刻 比call_later快 # call_later # # call_cat #指定时间运行 # call_soon_threadsafe 线程安全 import asyncio # def callback(sleep_times): # print(f"sleep {sleep_times} success") def callback(sleep_times, loop): print(f"sleep {sleep_times} success {loop.time()}") d...
import functools import logging import time from concurrent.futures import ThreadPoolExecutor from datetime import datetime, timedelta from multiprocessing.pool import ThreadPool from typing import Union, IO import pandas as pd from fuzzy_pandas import fuzzy_merge FORMAT = "%(asctime)-15s %(clientip)s %(us...
import webapp2 import os import jinja2 import datetime import re import hashlib import logging from google.appengine.ext import db template_dir = os.path.join(os.path.dirname(__file__), 'templates') jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape = True) class Handler(webapp...
""" Package for mapping strings describing insurance plans into Ribbon Health taxonomy. This package was built for a 3-week consulting project with Ribbon Health (ribbonhealth.com) as part of the Insight Data Science program. Modules: planmapper.py Defines PlanComparisonModel class. A model (i.e. an instance of this c...
from Tkinter import * import ttk import tkFont root = Tk() # Make it cover the entire screen w, h = root.winfo_screenwidth(), root.winfo_screenheight() root.overrideredirect(1) root.geometry("%dx%d+0+0" % (w, h)) root.focus_set() myFont = tkFont.Font(family='Helvetica', size=18, weight='bold') # Creating labels for...
s = float(input('Qual é o salário do funcionário ? R$')) aumento = float(input('Quanto foi o aumento dele em porcentagem ?(apenas número)')) conta = s * aumento/100 final = s + conta print('O funcionário que ganhava R${:.2f}, com {:.2f}% de aumento, passará a receber R${:.2f}'.format(s, aumento, final))
#!/usr/bin/env python # -*- coding: utf-8 -*- """Assignemnt Week 13 - Flask App""" from flask import Flask, request, session, g, redirect, url_for, \ abort, render_template, flash import re import sqlite3 as lite from contextlib import closing DATABASE = 'hw13.db' DEBUG = True SECRET_KEY = 'development key' USER...
#!/usr/bin/env python3 # -*- coding: ascii -*- import sys, os, re, inspect import cgi import weakref, contextlib import threading import websocket_server try: from Queue import Queue except ImportError: from queue import Queue THIS_DIR = os.path.dirname(os.path.abspath(inspect.getfile(lambda: None))) class Stream: ...
import torch import torch.nn as nn from disent.criterions import MMDWAELoss from disent.utils import eval_str_list from . import BaseTask, register_task @register_task('mmd_wae') class MMDWAETask(BaseTask): hparams = ('beta',) @staticmethod def add_args(parser): parser.add_argument('--data-dir',...
from __future__ import unicode_literals from django.apps import AppConfig class MainStreetGymConfig(AppConfig): name = 'main_street_gym'
import os import sys from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import create_engine # Importing is done Base = declarative_base() class User(Base): __tablename__ = 'user' id = Colu...
from functools import reduce qol = 0 for i in range(int(input())): qol += reduce(lambda q, y: q*y, [float(_) for _ in input().split(" ")]) print(qol)
#연결 요소의 개수 #https://www.acmicpc.net/problem/11724 import sys sys.stdin = open("input.txt","r") input=sys.stdin.readline sys.setrecursionlimit(10**8) def DFS(v): #v가 시작이 됨 visited[v]=1 for i in range(1,n+1): #둘다 연결되어 있고 아직 방문안했을 때 if board[v][i]==1 and board[i][v]==1 and visited[i]==0 : ...
""" Desafio 068 Problema: Faça um programa que jogue PAR ou ÍMPAR com o computador. O jogo só será interrompido quando o jogador perder, mostrando o total de vitórias consecutivas que ele consquistou no fim do jogo. Resolução do problema: """ from random import randint print('-' * 30) pr...
# -*- coding: utf-8 -*- """ Created on Mon May 29 17:06:16 2017 @author: dubey """ # -*- coding: utf-8 -*- """ Created on Mon May 29 15:58:41 2017 @author: dubey """ import matplotlib.pyplot as plt import matplotlib.animation as animation from matplotlib import style from wordcloud import WordCloud,STOPWORDS style...
# Copyright 2018 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 appl...
from numpy import * from numpy.linalg import * m_tabela=array(eval(input("valores: "))) linha=shape(m_tabela)[0] for i in range(linha): print(max(m_tabela[i,:]))#dar as saidas dos valores maximos
from ant_miner import AntMinerSA def main(): # INPUT: USER-DEFINED PARAMETERS: no_of_ants = 3000 min_cases_per_rule = 3 max_uncovered_cases = 10 no_rules_converg = 10 # ANT-MINER ALGORITHM: list of rules generator ant_miner = AntMinerSA(no_of_ants, min_cases_per_rule, max_uncovered_cases...
from suitebot3.ai.bot_ai import BotAi from suitebot3.game.game_setup import GameSetup from suitebot3.game.game_state import GameState from suitebot3.game.moves import Moves class SampleBotAi(BotAi): def __init__(self, game_setup: GameSetup): ''' Called before each new game ''' def make_moves(self, ga...
from Models.location import Location class RuralArea(Location): quantity_ra = 0 def __init__(self, rural_area, types): self.__class__.quantity_ra += 1 super().__init__(rural_area, types) def __str__(self): string = '| {} | {} |'.format(RuralArea.quantity_ra, self.type...
# ROPGenerator - Cond.py module # Implements the data structure useful for the representation of a gadget using graph theory # Provides primitives to extract dependencies from a given graph from ropgenerator.Expr import ConstExpr, SSAExpr, MEMExpr, Op, SSAReg, Cat, Extr, Convert, strToReg from ropgenerator.Cond imp...
import numpy as np import cv2 # events = [i for i in dir(cv2) if 'EVENT' in i] # print(events) def click_event(event, x, y, flags, param): if event == cv2.EVENT_LBUTTONDOWN: img[y:y+60,x:x+60] = ball cv2.imshow('image', img) img = cv2.imread('10 - messi5.jpg') ball = img[280:340,330:390] cv2.ims...
# -*- coding: utf-8 -*- import argparse from lib.io_utils import * from lib.math_utils import * from matplotlib import pyplot as plt import os import numpy as np from pprint import pprint import sys # input parser = argparse.ArgumentParser() parser.add_argument('-in', dest="INPUT_FILE", default="tmp/samples.csv", hel...
# coidng=utf-8 import unittest, os, time, sys sys.path.append(os.path.dirname(os.getcwd())) import HTMLTestRunner from app.common.sendMail import sendmail case_path = os.path.join(os.getcwd(), 'case') report_path = os.path.join(os.getcwd(), 'report') def all_case(): discover = unittest.defaultTestLoader.discover(ca...
import math import rl import rooms import actors import const import graphics from graphics import Tile import monsters import util class Level: def __init__(self, width, height): self.tiles = rl.Array(width, height) self.blocked = rl.Array(width, height) self.visited_tiles = rl.Array(widt...
# total features = 20620 + 12000 = 32620 # total instances = 1075 import pandas as pd import numpy as np import csv from mlxtend.classifier import EnsembleVoteClassifier from mlxtend.feature_selection import ColumnSelector from sklearn.pipeline import make_pipeline # importing the required classifiers from sklearn ...
import warnings warnings.filterwarnings('ignore') import numpy as np import matplotlib.pyplot as plt from scipy import linalg as lg from scipy import stats n = 100 mu = 0 sigma = 0.2 X = np.array(np.random.normal(mu,sigma,size=n)) Y = np.cumsum(X) Y[0] = 0 Z = np.exp(Y) sum_z = np.cumsum(Z) mu_n = sum_z/n plt.pl...
#!/usr/bin/python3 import math f = open('input', 'r') masses = [int(x) for x in f.readlines()] f.close() i = [math.floor(x/3) - 2 for x in masses] def total_mass(mass): fuel = math.floor(mass/3) - 2 return mass + (0 if fuel <= 0 else total_mass(fuel)) print("Part 1 answer: {}".format(sum(i))) print("Part 2 a...
from flask_restplus import Namespace, Resource, fields from model._init_ import db from model.user import User from model.event import Event from service.auth_service import admin_only from controller.user_controller import user_dto from controller.event_controller import event_dto api = Namespace(name='Admin API', pa...
import os import getpass import re import sys import smtplib from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText SMTP_SERVER = 'smtp.gmail.com' SMTP_PORT = 587 def send_email(sender, recipient): """ sends email message """ msg = MIMEMulti...
s = set([1,2,3]) print(s) s.add(0) print(s) a = [ 1,2,3,4,5 ] print(a[4:100]) for a in range(3): print(a) a = [1,2,3,None,(),[],] print(len(a))
import pytest from my_module import square @pytest.mark.parametrize( 'inputs', [2, 3, 4.5] # The last test will fail ) def test_square_return_value_is_int(inputs): # When subject = square(inputs) # Then assert isinstance(subject, int)
""" 1、学习目标 掌握 定位超链接的方法: xpath 2、操作步骤(语法) 1、xpath dirver.find_element_by_xpath("xpath路径") 2、xpath表达式 2.1、绝对路径 从根节点开始一层一层进行查找 /表示绝对路径 /html/body/div/div/div/form/div/div[2]/div/input 2.2、相对路径(重点) //表示相对路径 1、使用标签+属性定位 ...