text
stringlengths
8
6.05M
''' Created on Sep 17, 2018 @author: MaxShapiro32@ibm.com Login restful end point handling ''' from flask import Blueprint, request from app.services.user import login_service login_v1_blueprint = Blueprint('login_v1_api', __name__) @login_v1_blueprint.route('/login', methods=['POST']) def login(): data = requ...
file = open("input.txt", "a") d = file.read() c = len(d) print(c)
#import sys #input = sys.stdin.readline Q = 10**9+7 def main(): S = input() N = len(S) dp = [[0]*13 for _ in range(N+1)] dp[0][0] = 1 for i in range(N): s = S[N-1-i] r = pow(10, i, 13) if s == '?': for k in range(10): t = k*r%13 ...
#!/usr/bin/env python """ Test Python script to run the R script TestR.R, using the 'subprocess' module """ __author__ = "Saul Moore sm5911@imperial.ac.uk" __version__ = "0.0.1" ########### Subprocess to run R ############ import subprocess subprocess.Popen("Rscript --verbose TestR.R > \ ../Results/TestR.Rout 2> ....
#!/usr/bin/env python # coding: utf-8 import sys import os sys.path.append(os.path.join(os.path.dirname(__file__), 'paver-minilib.zip')) from paver.easy import * @task def hello(): print 'hello' if __name__ == '__main__': tasks.main(['-f'] + sys.argv) # eof
#Project Euler Problem 12 #What is the value of the first triangle number to have over five hundred divisors? # We will go about finding the number of divisors by prime factorization. # What this means is that first we need a long list of primes. import math prime =0 primelist=[] n=2 while prime<=10000: score=0 for...
#!/usr/bin/python import re,sys if len(sys.argv) != 3: print print "Usage: %s inputfile outputfile"%sys.argv[0] print sys.exit(1) inputfile = sys.argv[1] outputfile = sys.argv[2] fr = open(inputfile) fw = open(outputfile, "w") def filmAndYear(string): string = string.strip() found = re.search(r'^\".+\"',stri...
#쉽게 설명한 선택정렬 #입력:리스트a #출력:정렬된 새 리스트 def find_min_idx(a): n=len(a) min_idx=0 for i in range(1,n): if a[i]<a[min_idx]: min_idx=i return min_idx def sel_sort(a): result=[] while a: min_idx=find_min_idx(a) value=a.pop(min_idx) result.append(value) re...
# vim:fileencoding=utf-8:noet from __future__ import (unicode_literals, division, absolute_import, print_function) import sys import json import logging from itertools import count try: import vim except ImportError: vim = object() from powerline.bindings.vim import vim_get_func, vim_getvar, get_vim_encoding, pyt...
words = ['cat', 'window', 'defenestrate'] for w in words: print(w, len(w)) # insert for w in words[:]: if len(w) > 6: words.insert(0, w) print(words) # range for i in range(5): print(i) for w in range(0, 21, 5): print(w) # range is not a list lists = range(5, 10) print(lists) print(list(l...
#!/usr/bin/env python import asyncio from async_timeout import timeout from typing import ( List, Optional, ) from hummingbot.core.event.event_listener cimport EventListener cdef class EventLogger(EventListener): def __init__(self, event_source: Optional[str] = None): super().__init__() ...
#from ROOT import * # 2014-01-24 replaced by the below (to protect isa_simplereader_class and munch import ROOT from array import * import random # gROOT.LoadMacro("/mn/kvant/u1/borgeg/scripts/sky_AtlasStyle.C") # SetAtlasStyle() from kilelib_ROOT import * from kilelib import safeGet import kilelib_physics as mypdg...
from flask import ( Blueprint, flash, g, redirect, render_template, request, url_for, session ) from werkzeug.exceptions import abort from flaskr.auth import login_required from flaskr.db import get_db from flaskr.wrappers import weatherWrapper from flaskr.objects.clothing import Clothing from flaskr.objects.clothi...
import sys from flask import Flask, request app = Flask(__name__) """ --------------------------- REST CALLS ----------------------------- """ """ Microservice commands: Use this area below as an example of how you can add your own REST commands. """ @app.route("/<command>") def index(command): # Serves as an ex...
try: a = int(input('Primeiro número: ')) b = int(input('egundo número: ')) r = a / b except Exception as erro: print(f'ERR: {erro.args[0]}') else: print(f'O resultado é {r:.1f}') finally: print('Divisão finalizada')
#!flask/bin/python from flask import Flask, jsonify from flask import abort from flask import make_response from flask import request from flask.ext.httpauth import HTTPBasicAuth auth = HTTPBasicAuth() app = Flask(__name__) users = { 'user':'pass', 'usuario':'senha', 'cliente':'s3nh@' } @auth.get_password def get_pa...
"""Определение класса с переменным числом арнументов""" class Var: def __init__(self, **kwargs): for attr in kwargs.keys(): self.__dict__[attr] = kwargs[attr] v = Var(name="Sam", age=22) print(v.__dict__) print(v.name) print(v.age) v2 = Var(name="Sam", age=22, x=34) print(v2.__dict__) print(v...
# -*- coding: utf-8 -*- from django.db import models from pygments.lexers import get_lexer_by_name from pygments.formatters.html import HtmlFormatter from pygments import highlight class Task(models.Model): """Model for task object.""" PRIORITIES = ((1, 'Niski'),(2, 'Normalny'),(3, 'Wysoki'),) name = mo...
from collections import deque import sys # sys.stdin = open("input.txt", "r") input = sys.stdin.readline ############ # 전역 변수 # ############ ############ # 함수 부분 # ############ def up(g): global N _g = [[g[i][j] for j in range(N)] for i in range(N)] # 땡기기 ans_g = [[0 for _ in range(N)] for _ in rang...
import sys sys.path.insert(0, "/home/machen/face_expr") import argparse from AU_rcnn.links.model.faster_rcnn.faster_rcnn_resnet101 import FasterRCNNResnet101 from AU_rcnn.links.model.faster_rcnn.faster_rcnn_vgg import FasterRCNNVGG16 from simple_graph_learning.dataset.AU_extractor_dataset import AUExtractorDataset from...
name = input("firstname") surname = input ("surname") exam_mark =float( input("exam_mark")) if (exam_mark >= 80) and (exam_mark<=100): print(name, surname, "grade A- Outstanding") elif (exam_mark >= 60) and (exam_mark<=79): print(name, surname, "grade B-Satisfactory") elif (exam_mark >= 50) and (exam_m...
#Checiking equation for straight line class Solution: def checkStraightLine(self, coordinates: List[List[int]]) -> bool: n = len(coordinates) x0,y0 = coordinates[0] x1,y1 = coordinates[1] for i in range(2,n): x,y = coordinates[i] if (y1-y0)*(...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from utils.init_weights import init_weights, normalized_columns_initializer class Cont...
from django.contrib import admin from .models import Student # Register your models here. @admin.register(Student) class StudentAdmin(admin.ModelAdmin): list_display = ['student','student_num','classes','is_student'] search_fields=('student__username','classes__name')
from django.contrib import admin from redirects.forms import RedirectForm from redirects.models import Redirect class RedirectAdmin(admin.ModelAdmin): list_display = ('source_path', 'redirect_code', 'target_path') form = RedirectForm admin.site.register(Redirect, RedirectAdmin)
from prettytable import PrettyTable class BasicMapping(object): def __init__(self, data): for attr, v in data.items(): setattr(self, attr, v) def __str__(self): return str(type(self)) + ' '.join(["{attr}:{val}".format(attr=v, val=getattr(self, v)) for v in self.__slots__]) __...
from django.db import models from django.utils import timezone class Customer(models.Model): id = models.IntegerField(primary_key=True, auto_created=True) name = models.CharField(max_length=255) surname = models.CharField(max_length=255) username = models.CharField(max_length=255) date = models.Da...
# Copyright 2017 Covata Limited or its affiliates # # 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...
# -*- coding: utf-8 -*- from irc3.compat import asyncio from irc3 import utils from collections import defaultdict import functools import venusian import fnmatch import logging import docopt import shlex import irc3 import sys import re __doc__ = ''' ========================================== :mod:`irc3.plugins.comman...
""" Application template for Clear Linux Cloud Native (CLCN) Solutions. """ import os import sys import logging import asyncio import threading LOG = logging.getLogger(__name__) class CLCNTask(threading.Thread): """ Threading based Task. In general, a cloud native app may consists several threading tasks...
#!/usr/bin/env python3 """ test for the Threadsafe module. """ import unittest from base_test import PschedTestBase from pscheduler.threadsafe import ThreadSafeSet from pscheduler.threadsafe import ThreadWithReturnValue class TestThreadsafe(PschedTestBase): """ Threadsafe tests. """ def test_safe_s...
# List Comprehensions are a unique way of quickly creating a list with Python mystring = 'hello' mylist = [] for letter in mystring: mylist.append(letter) print(mylist) mylist = [letter for letter in mystring] print(mylist) mylist = [letter for letter in 'Word'] print(mylist) mylist = [num for num in range(0,...
import re #pattern = r"ab*a" #pattern = r"ab+a" #pattern = r"ab?a" #pattern = r"ab{3}a" #pattern = r"ab{2,5}a" #string = "aa, aba, abba" #string = "aa, aba, abba, abbba, abbbba, abbbbba" #all_incusions = re.findall(pattern, string) #print(all_incusions) #pattern = r"a[ab]+a" pattern = r"a[ab]+?a" string = "abaaba" pr...
# Program for å bestemme farge på ruletten. # Steg 1, tester om tallet er gyldig. # Brukeren oppgir tall på ruletten. tall = int(input('Hva er tallet på ruletten? ')) # Tester på gyldig verdi if tall >= 0 and tall <= 36: # Ståle tester konsekvent nedre og øvre grense på intervallet. print('Tallet er',...
from django import forms from .models import Post class PostForm(forms.Form): title = forms.CharField(initial="title ") content = forms.CharField(initial="content ") def update(self, instance, validated_data): instance.title = validated_data.get('title',instance.title) instance.content = v...
# -*- coding: utf-8 -*- import sys from PyQt5.QtWidgets import QApplication from PyQt5.QtWidgets import QMainWindow from PyQt5.QtCore import QItemSelectionModel from PyQt5.QtCore import QAbstractItemModel from PyQt5.QtGui import QStandardItemModel from PyQt5.QtGui import QStandardItem # Form implementation generated ...
# Importing libraries from typing import Dict from pymongo import MongoClient import tweepy as tw import pandas as pd # Creating connection with MongoDB Atlas client = MongoClient("Your_MongoDB_Connection_String") # Creating a Database with the name Data-Mining mydb = client['Data-Mining'] # Creating T...
/home/ajitkumar/anaconda3/lib/python3.7/io.py
from sklearn import tree features = [[1,2,3,4],[8,11,12,10],[1,7,4,3],[10,9,12,8],[13,10,9,11],[1,3,5,6],[10,9,12,8],[13,10,9,11],[1,3,5,6],[5,2,3,4],[1,2,3,4],[8,11,12,10],[1,7,4,3],[10,9,12,8],[13,10,9,11],[1,3,5,6],[10,9,12,8],[13,10,9,11],[1,3,5,6],[5,2,3,4]] labels = ['backend', 'frontend', 'backend', 'frontend',...
#!/usr/bin/env python import os, re import numpy as np import pandas as pd import subprocess import tensorflow as tf from tensorflow.keras import optimizers from tensorflow.keras.callbacks import Callback, ModelCheckpoint from keras_tuner.engine.oracle import Objective from options import parse_command_line_argum...
# -*- coding: utf-8 -*- age = "22" age = int(age) print(type(age))
#!/usr/bin/env python3 import argparse import yaml import json from pathlib import Path def main(): parser = argparse.ArgumentParser(description="Creates config_biobb.json and config_biobb.yml files.", formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=999...
from ED6ScenarioHelper import * def main(): # 柏斯 CreateScenaFile( FileName = 'T1410 ._SN', MapName = 'Bose', Location = 'T1410.x', MapIndex = 1, MapDefaultBGM = "ed60016", Flags = 0, Ent...
from django.shortcuts import render from django.urls import reverse_lazy, reverse from django.views.generic import CreateView, ListView, DetailView, UpdateView from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib import messages from django.utils.decorators import method_decorator from django.v...
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- n=int(input()) x=y=1 for i in range(n,0,-1): x*=i print(x//((n//2)**2)//2)
""" Time Complexity = O(N) Space Complexity = O(1) """ from collections import Counter class Solution: def longestPalindrome(self, s: str) -> int: ch_dict = Counter(s) out = 0 for val in ch_dict.values(): if val % 2 == 0: out += val ...
import sys import time import numpy as np import scipy.stats import csv import math import matplotlib.pyplot as plt def gmmclassify(X,mu1,sigmasq1,wt1,mu2,sigmasq2,wt2,p1): output = np.zeros(len(X)) for idx, x in enumerate(X): p1 = -1; p2 = -1; for i in range(len(mu1)): tmp = wt1[i] * scipy.stats.norm(...
method overriding...same method name different no of parameters class Person: def printval(self,name): self.name=name print('inside person method',self.name) class Child(Person): def printval(self,class1): self.class1=class1 print('inside child method',self.class1) ch=Child() ch....
import pygame, sys from pygame.locals import * import random, time def main(): list_explosion = [] imageexplosion = [] list_enemies = [] list_enemy_bullet = [] list_bullet = [] list_score = [] list_ufo =[] pygame.init() #設置背景 screen = pygame.display.set_mode((480, 8...
from django.urls import path from django.contrib.auth import views as auth_views from .views import * urlpatterns = [ path('Sign up', UserSignup.as_view(), name='sign up'), path('successfull', SuccessView.as_view(), name='successfull'), path('login/', auth_views.login, {'template_name': 'registration/login...
import quopri import email from abc import ABC, abstractmethod class EmailBodyParser(ABC): @abstractmethod def text_from_body(self, msg) -> str: pass class PFEmailBodyParser(EmailBodyParser): def text_from_body(self, msg) -> str: text = self.__msg_to_text(msg) tex...
from django.db import models from django.db.models.fields import CharField # Create your models here. class Contact(models.Model): firstname=models.CharField(max_length=150) lastname=models.CharField(max_length=150) email=models.CharField(max_length=150) phone=models.CharField(max_length=12) city=...
import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg import os from PIL import Image as PImage from scipy import misc, signal from skimage import filters, color def applyFilter(full_image_path): image_path, image_name = os.path.split(full_image_path) #Divide path and image name ...
import csv username = raw_input("Enter your username: ") with open('schat.csv', 'rb') as csvfile: snapchat = csv.reader(csvfile) for row in snapchat: if row[1] == username: print row break else: print "You are safe from the leak" break
from rules.Rule import Rule from CalledRecordDiagnoseYr import CalledRecordDiagnoseYr import nltk import nltk.data import re import difflib class ImpressionRule(Rule): impressionLimit = 250 diagnosesLimit = 125 lowerLimit = 120 upperLimit = 120 msLimit = 25 years = [] def __init__(self, n...
# Mofidied work: # -------------------------------------------------------- # Copyright (c) 2017 Preferred Networks, Inc. # -------------------------------------------------------- # # Original works by: # -------------------------------------------------------- # Faster R-CNN implementation by Chainer # Copyright (c) ...
import math n=0 print('Degrees',' ', 'Sin', ' ', 'Cos',) for i in range (37): yC = math.cos(n/360*2*(math.pi)) yS = math.sin(n/360*2*(math.pi)) print(n, ' ', format(yS,'.4f'), ' ', format(yC,'.4f')) n = n + 10 continue
import re from .models import CspRule class CspRuleEvaluator(object): def __init__(self): self.rules = list(CspRule.objects.all()) def evaluate_directive(self, url, directive): """Evaluates a url and directive against all rules. Does not differentiate between general and element ...
from django.contrib import admin from .models import Kharj , Dakhl, Token # Register your models here. admin.site.register(Kharj) admin.site.register(Dakhl) admin.site.register(Token)
from django.db import models # Create your models here. class RolloutGroup(models.Model): name = models.CharField(max_length=50, unique=True) from_age = models.CharField(max_length=3) to_age = models.CharField(max_length=3) starting_date = models.CharField(max_length=50) vaccine_to_give = models.Fo...
# BOJ 1655번, 가운데를 말해요 # min 힙(왼쪽배열), max 힙(오른쪽배열)을 생성해 활용한다. # 중앙값은 max 힙의 첫번째 인덱스 값이 된다. import heapq import sys left, right = [], [] N = int(sys.stdin.readline().rstrip()) A = [] for _ in range(N): number = int(sys.stdin.readline().rstrip()) if len(left) == len(right): # max heap ...
import inspect if "rungame" not in inspect.getmodule(inspect.stack()[0])._filesbymodname["__main__"]: import rungame
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Author: zhangfang # @Email: thuzhf@gmail.com # @Date: 2016-03-07 18:12:12 # @Last Modified by: thuzhf import sys,os,re,json,gzip,math,time,datetime,functools,contextlib,itertools import multiprocessing as mp import subprocess as sp if sys.version_info < (3,): # ve...
import api import time eight = True api = api.api(True,True,False,False) api.setInk(0,200,0,4) ''' for i in range(8): for j in range(8): api.drawPixel(i,j) ''' time.sleep(2) api.setInk(0,0,200,4) if eight: #api.setSprite(1,0,8,[0b10111111,0b10000001,0b10000001,0b10000001,0b10000001,0b10000001,0b10000001,0b11...
#notepad import os def filedisp(name): try: f = open(name, 'r+') text = f.readlines() f.close() text = ''.join(text) print('Here are the contents ') print(text) except IOError: print('Cannot open file.....try again') def printmenu(): choice = '0' ...
# !/usr/bin/env python # -*- coding: utf-8 -*- ''' The front-end to DOUM Main server Using GIGA Genie 메인서버에 접근하기 위해 기가지니를 이용하는 프론트엔드 Lee Cheolju Kim Sangwon Park Jongkuk ''' from __future__ import print_function from __future__ import absolute_import import grpc import gigagenieRPC_pb2 import gigagenieRPC_pb2_grpc im...
from evernote.api.client import EvernoteClient # import evernote.edam.notestore.ttypes as Type dev_token = "S=s1:U=93de4:E=164ada01725:C=15d55eee978:P=1cd:A=en-devtoken:V=2:H=d76e98edf6389e9b479302d27ecc8195" client = EvernoteClient(token=dev_token) # user的名字 userStore = client.get_user_store() user = userStore.getU...
''' Author: twsec Date: 2021-03-22 16:25:38 LastEditors: twsec LastEditTime: 2021-04-03 17:12:17 Description: 判断是否存在CDN防护 ''' import socket import re import subprocess from bs4 import BeautifulSoup import requests import json import urllib.request import urllib.error import time import threading from fake_u...
def levelOrder(self, root: 'Node') -> List[List[int]]: """ 层次遍历,类似于BFS,使用队列辅助 O(n), O(n) """ if not root: return [] res = [] from collections import deque queue = deque() queue.append(root) while queue: cur_res = [] for _ in range(len(queue)): # the nod...
#!/usr/bin/env python # coding:utf-8 # vi:tabstop=4:shiftwidth=4:expandtab:sts=4 import os import sys import numpy as np from format import open_memmap as open_memmap_partial #https://github.com/jonovik/numpy/raw/offset_memmap/numpy/lib/format.py file2x={} def readnpy(paths,shape,a,fast=False,dtype='uint8',maxshape=...
class Solution(object): def isValidSudoku(self, board): row = [[0] * 9 for i in range(9)] col = [[0] * 9 for i in range(9)] cell = [[0] * 9 for i in range(9)] for i in xrange(9): for j in xrange(9): if board[i][j] == '.': continue idx = ...
name='zed A. shaw' age=35 #not a lie height=74#inches weight=180#lbs eyes='blue' teeth='white' hair='brown' print "let's talk about %s." % name print "He's %d inches tall." % height print "He's %d pounds heavy." % weight print "Actually that's not too heavy" print "He's got %s eyes and %s hair." % (eyes,h...
import tensorflow as tf def mlp_create(layer_create_funtions): if(layer_create_funtions is None or len(layer_create_funtions) == 0): return None mlp_out = layer_create_funtions.pop(0)() #取第一层函数并运行 for func in layer_create_funtions: mlp_out = func(mlp_out) return mlp_out
from . import res_users, res_partner
__author__ = 'RajivSubramanian'
from time import * import cherrypy from meatoodb import * class MyServer: """XML-RPC methods""" def __init__(self, config, debug, verbose): self.config = config self.debug = debug self.verbose = verbose def _parsePackages(self, pkgs): """Parse Packages into a list of l...
from flask import Blueprint from ..common.http_auth import HTTPTokenAuth api = Blueprint('api_v1_0', __name__) auth = HTTPTokenAuth() from app.api_v1_0 import authentication # Import any endpoints here to make them available # from . import dis_endpoint, dat_endpoint from app.api_v1_0 import strategy from app.api_v...
from django.contrib import admin from app.models import DogTag, DogProduct # Register your models here. @admin.register(DogTag) class DogTagAdmin(admin.ModelAdmin): pass @admin.register(DogProduct) class DogProductAdmin(admin.ModelAdmin): pass
# 200. Number of Islands # # Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is # formed by connecting adjacent lands horizontally or vertically. # You may assume all four edges of the grid are all surround# ed # by water. # # Example 1: # # 11...
import tensorflow as tf import numpy as np from dataset.AbstractDataset import AbstractDataset import config.baseConfig as baseConfig class MultilabelLargeDataset(AbstractDataset): def __init__(self, csvpath, config, batch_size, cache): def makeImage(img): shape = tf.shape(img) hei...
#binary from time import time import random def generate_binary(size): lst= [random.randint(0,1) for i in range(size)] return "".join(str(i) for i in lst ) def binary_value(s): start=time() l=len(s) ans=0 for i in s: if i=="1": ans+=pow(2,l-1) l-=1 end=time() ...
from . import deepMRInet from . import dagan from .common import *
def pre_compute(a,n,index,k): dp = [[0 for i in range(n)] for i in range(n)] for i in range(n): if a[i] > a[0]: dp[0][i] = a[i] + a[0] else: dp[0][i] = a[i] for i in range(1,n): for j in range(n): if a[j] > a[i] and j > i: if dp[i...
import time import turtle turtle.shape('classic') turtle.speed(10) def nyg(n): n=int(n) for i in range(60): turtle.forward(n) turtle.right(3) turtle.left(90) for i in range(20): nyg(2) nyg(1) time.sleep(2)
import chainer import numpy from chainer import Variable from chainer import cuda class MeanAbsError(object): def __init__(self, scaler=None): """Initializes the (scaled) mean absolute error metric object. Args: scaler: Standard label scaler. """ self.scaler = scaler ...
"""Build an index (DB table) of known GitHub repositories of Vim plugins.""" import argparse import collections import logging import re import rethinkdb as r import db.util from db.github_repos import PluginGithubRepos r_conn = db.util.r_conn # Matches eg. "github.com/scrooloose/syntastic", "github.com/kien/ctrl...
lista_vazia= list() numero = int(input("Digite um número: ")) while numero != 0: lista_vazia.append(numero) numero = int(input("Digite um número: ")) repetido = int(input("Digite um número repetido: ")) print(repetido, lista_vazia.count(repetido))
import configparser import os def validate(option, section, key): if option == '--INVALID--': raise configparser.Error('Found default invalid option in \'{}\' key in \'{}\' section!'.format(key, section)) return option APP_DIR = os.path.dirname(os.path.realpath(__file__)) config_file = os.path.join(A...
''' Created on Aug 25, 2016 @author: Dayo ''' class DeliveryReportRouter(object): """ A router to control all database operations on models in the reportng application. """ def db_for_read(self, model, **hints): if model._meta.app_label == 'reportng': return 'del...
number = input("Please enter a series of number, using any separators you like: ") separators = "" for char in number: if not char.isnumeric(): separators = separators + char # print(separators) values = "".join(char if char not in separators else " " for char in number).split() print(sum([int(val) for v...
test = dict() test[1] = [5, 4] test[2] = [2, 1] disc = dict() disc[1] = [17, 15] disc[2] = [3, 2] disc[3] = [19, 4] disc[4] = [13, 2] disc[5] = [7, 2] disc[6] = [5, 0] def disc_spin(disc, part): if part == 2: disc[7] = [11, 0] t = 0 count = 0 pos = dict() press = False ...
class A(): def __init__(self, first, last, nickname, job): self.first = first self.last = last self.nickname = nickname self.job = job
""" Test the routes that show dashboards """ import pytest from .conftest import check_for_docker DOCKER_RUNNING = check_for_docker() # use the testuser fixture to add a user to the database @pytest.mark.skipif(not DOCKER_RUNNING, reason="requires docker") def test_user(testuser): assert True @pytest.mark.ski...
""" I used TA Kimmo's slides to help me on this project. """ import asyncio import argparse import sys import re valid_server_names = {"Hill": 12120, "Jaquez": 12121, "Smith": 12122, "Campbell": 12123, "Singleton": 12124} localhost = '127.0.0.1' class Client: def __init__(self, ip='127.0.0.1', port=8888, name='c...
import unittest import datetime import icalendar import os class TestTime(unittest.TestCase): def setUp(self): icalendar.cal.types_factory.types_map['X-SOMETIME'] = 'time' def tearDown(self): icalendar.cal.types_factory.types_map.pop('X-SOMETIME') def test_create_from_ical(self): ...
import os import pandas as pd import ipynb from ipynb.fs.full.text_preprocess import preprocess from textblob import TextBlob import matplotlib.pyplot as plt import seaborn as sb from afinn import Afinn from ipynb.fs.full.text_preprocess import preprocess_stopwords from sklearn import preprocessing import numpy as np f...
from datetime import datetime from django import template from django.utils.timesince import timesince register = template.Library() @register.filter def age(value): now = datetime.now() print(value) try: difference = now.year - value.year except: return value # if difference <= ...
import numpy as np import cv2 as cv from matplotlib import pyplot as plt img = cv.imread('1.tif') gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY) ret, thresh = cv.threshold(gray,0,255,cv.THRESH_BINARY_INV+cv.THRESH_OTSU) # noise removal kernel = np.ones((3,3),np.uint8) opening = cv.morphologyEx(thresh,cv.MORPH_OPEN,kernel,...
from turtle import * # hash for random subdivs h = 4; up(); ht() # create random subdivs def r(n, l): global h h = hash(str(h)); s = n + (h&1) * (2**(l-7)) if not l == 6: s = [r(s, l+1), r(s, l+1), r(s, l+1), r(s, l+1)] #[r(s, l+1) for _ in range(4)] return s # convert string to tree def p(s, l): a = [] for c ...
a=int(input()) b=int(input()) n=int(input()) x=(100*a+b)*n r=x//100 k=x%100 print(r,k)