text
stringlengths
38
1.54M
# -*- coding: utf-8 -*- import scrapy from bs4 import BeautifulSoup from cars.items import CarsParamItem class CarParamSpiderSpider(scrapy.Spider): name = 'car_param_spider' allowed_domains = ['16888.com'] start_urls = ['https://xl.16888.com/style.html'] def parse(self, response): prev_url = ...
def solution(n, words): answer = [] stack = [] count = 0 for w in words: if w in stack: break if stack and stack[-1][-1] != w[0]: break if w not in stack: stack.append(w) count += 1 print(len(words)) print(count) if co...
from django.db import models # Create your models here. class total(models.Model): title = models.CharField(max_length=200) problem = models.CharField(max_length=200) link = models.CharField(max_length=200) class easy(models.Model): title = models.CharField(max_length=200) problem = models.CharField(max_lengt...
""" Exercise 6: Rewrite your pay computation with time-and-a-half for overtime and create a function called computepay which takes two parameters (hours and rate). Enter Hours: 45 Enter Rate: 10 Pay: 475.0 """ def computepay(hours,rate): pay = 0.0 if hours < 40: pay = rate* hours else: ex...
def is_even(number): """ Returns True if **number** is even or False if it is odd. """ return number % 2
import sys from Bio import SeqIO from Bio.Seq import Seq MAX_READ_LENGTH = 100 MAX_Q = 100 def ErrorCal(fastqfile): f = open(fastqfile) prob_sums = [0 for i in range(MAX_READ_LENGTH)] basecount = prob_sums[:] logQs = [10 ** (float(-Q) / 10) for Q in range(MAX_Q + 1)] for record in SeqIO.parse(f, "fastq"): ...
import sys for line in open(sys.argv[1]): if line != '\n': lst = line.strip().split('\t') rt = lst[2] print('(id-conll_root', lst[0], rt, ')')
#!/usr/bin/env python # pip3 install google-cloud-secret-manager import argparse def create_secret(project_id, secret_id): from google.cloud import secretmanager client = secretmanager.SecretManagerServiceClient() parent = f"projects/woven-honor-229707" # Create the secret. response = client....
import sys def main(): if len(sys.argv) < 2: print("Please specify an input file") sys.exit() with open(sys.argv[1], "r") as file: contents = file.read() ram = [0] index = 0 instruction = 0 inloop = False loopstack = [] loopstart =...
# coding=utf-8 """ Module containing evaluation functions suitable for judging the performance of a fitted LightFM model. """ import numpy as np from ._lightfm_fast import CSRMatrix, calculate_auc_from_rank __all__ = ["precision_at_k", "recall_at_k", "auc_score", "reciprocal_rank"] def precision_at_k( model, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @File : NewsSrv.py # @Time : 2020-3-20 9:47 # @Software: PyCharm # @Author : Taoz # @contact : xie-hong-tao@qq.com import requests, re from lxml import etree from urllib.parse import urlencode, urljoin class NewsSrv(object): @classmethod def news_list(cls...
# -*- coding: utf-8 -*- ''' Created on 25 July 2016 @author: kylez,dgrossman ''' import json import logging from urllib.parse import urljoin from poseidon.controllers.bcf.cookieauth import CookieAuthControllerProxy from poseidon.controllers.bcf.jsonmixin import JsonMixin class BcfProxy(JsonMixin, CookieAuthControlle...
import tempfile import os import shutil import pytest import photomosaic as pm from skimage.data import chelsea @pytest.fixture(scope='module') def pool(): tempdirname = tempfile.mkdtemp() pm.rainbow_of_squares(tempdirname, range_params=(0, 256, 30)) pool = pm.make_pool(os.path.join(tempdirname, '*.png'))...
import tkinter as tk from tkinter import * from PIL import Image from PIL import ImageTk from datetime import date import shortuuid import multiprocessing import time ### This Function is used to detect censor words ### def censor(listOfWords): listOfWords=listOfWords.split(",") ## This list contains dataset of cu...
# find the kth smallest element in an array def quickSelect(lst, left, right, k): if k > right - left + 1 or k < 0: return 'not found' pos = partition(lst, left, right) if pos - left == k - 1: return lst[pos] elif pos - left > k - 1: return quickSelect(lst, left, pos-1, k) else: ...
from rest_framework import viewsets from rest_framework.permissions import AllowAny from .serializers import UserSerializer from django.http import JsonResponse from django.contrib.auth import get_user_model from .models import CustomUser from django.views.decorators.csrf import csrf_exempt from django.contrib.auth imp...
from math import * def g(x): y=0.5*sqrt(10-x**3) print y return y p0=1 tol=0.001 n0=50 i=1 while i<=n0: p=g(p0) if abs(p-p0)<tol: print "El punto fijo es",p,"despues de",i,"iteraciones" break i=i+1 p0=p if i>n0: print "El metodo no converge"
import sys import xml.etree.ElementTree as etree def get_attr_number(node): # your code goes here a = 0 # if node.attrib: # print(node.tag, node.attrib) # a += len(node.attrib) for child in node.iter(): print(child.tag, child.attrib) a += len(child.attrib) ...
from sklearn.externals import joblib import cv2 from sklearn.cluster import KMeans import os import itertools # Find and return descriptors for given image def descriptors(image): print(type(image)) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) sift = cv2.xfeatures2d.SIFT_create() kp, des = sift.detectAndCompute(...
# -*- coding: utf-8 -* from __future__ import unicode_literals import logging, os, re, urllib, urllib2, glob, style, time, click, sys import spotipy, youtube_dl, mutagen, musicbrainzngs from tinydb import TinyDB, Query from bs4 import BeautifulSoup from subprocess import call from spotipy.oauth2 import SpotifyClientCr...
import cv2 img = cv2.imread('images/input.jpg') img_scaled = cv2.resize(img,None,fx=1.2, fy=1.2, interpolation = cv2.INTER_LINEAR) # imagen,tamano imagen de salida none=default, # fx= factor de escala en el eje x fy en el y # ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: Alex # @Date: 2015-12-20 22:05:42 # @Last Modified by: Alex # @Last Modified time: 2016-01-02 18:57:39 from django.db import models from Inventationery.core.models import TimeStampedModel # Create your models here. # Class: Model for payment catalog # ----...
import json class MessageParser(): def __init__(self): self.possible_responses = { 'error': self.parse_error, 'info': self.parse_info, 'message': self.parse_message, 'history': self.parse_history, 'help': self.parse_help } def parse(...
# coding: utf-8 #Copyright (c) 2018 Shotaro Ishigami import cv2 import numpy as np import random from PIL import Image, ImageDraw, ImageFilter #ターゲット切り取り def ImageTrim(img): th1=Binarize(245,img) # 輪郭を抽出 # contours : [領域][Point No][0][x=0, y=1] # cv2.CHAIN_APPROX_NONE: 中間点も保持する # cv2...
from loman.computeengine import ( Computation, States, MapException, LoopDetectedException, NonExistentNodeException, node, C)
#!/usr/bin/python # Script number: 1.1 # File: 1 of 1 # Prerequisite script(s): # Prerequisite file(s): bacteria_accessions.txt # Description: Downloads genomes from EMBL using accessions provided import os import sys import imp import urllib2 import HTMLParser import time from datetime import timedelta ###...
#!/usr/bin/env python from __future__ import print_function import sqlite3 import gzip import bz2 import sys import argparse import datetime as D def logTime(chkpoint): print('*** Checkpoint: {} at \x1b[31m{}\x1b[0m'.format(chkpoint, D.datetime.now())) sys.stdout.flush() argParser = argparse.ArgumentParser() ...
from django.conf.urls import url from django.views.defaults import page_not_found from restaurant.menu.views import IndexView, MenusView, DishesPerMenuView urlpatterns = [ url(r'^$', IndexView.as_view(), name='menu-index'), ] apipatterns = [ url(r'^$', page_not_found, name='menu-api'), url(r'^list$', Me...
# Lesson3, Task1 # Create list of even numbers even = range(2, 100, 2) # Define variables a, b, c, *d = even # Print variables print ("a = %i\nb = %i\nc = %i\nd = " % (a,b,c) + str(d)) print () # Redefine variables a, b, c, *_ = even # Print variables print ("a = %i\nb = %i\nc = %i\n_ = " % (a,b,c) + str(_)) print...
import re from typing import List import numpy as np import os from pprint import pprint from models import LottoNum class NumPool: def __init__(self, num_ls: List[LottoNum]): self.num_ls: List[LottoNum] = num_ls self.pool: np.array = np.empty(shape=(20, 10), dtype=object) self.size = 0 ...
from gsi_handlers.gameplay_archiver import GameplayArchiver from sims4.gsi.dispatcher import GsiHandler from sims4.gsi.schema import GsiGridSchema, GsiFieldVisualizers import date_and_time import enum import services conditional_layer_service_schema = GsiGridSchema(label='Conditional Layers/Conditional Layer Service') ...
#!/usr/bin/env /usr/anim/modsquad/bin/dmgpython """ wavhead - print wav header information """ import sys import wave import struct for fn in sys.argv[1:]: print fn ii=wave.open(fn,'r') print " getnchannels",ii.getnchannels() print " getsampwidth",ii.getsampwidth() print " getframerate",i...
import cv2 import numpy as np class Solver(object): def __init__(self, size, start, goal, map): self.lows = size[0] self.cols = size[1] self.start = start self.goal = goal self.distance = np.zeros((self.lows, self.cols,4), np.uint16) # current, remain, total self.vi...
from selenium import webdriver from selenium.webdriver.common.keys import Keys # from selenium import FirefoxDriver; # user = "test@test.com" #These will not log in. # pwd = "testtest" #These will not log in. # FB Test Account. user = "microdwaynedev@gmail.com" pwd = "Faceraigi1!" # driver = webdriver.Firefox(...
import socket SERVER_HOST = "0.0.0.0" SERVER_PORT = 5003 # send 1024 (1kb) a time (as buffer size) BUFFER_SIZE = 1024 # create a socket object s = socket.socket() s.bind((SERVER_HOST, SERVER_PORT)) s.listen(5) get_host = socket.gethostname() print(get_host) print(f"Waiting for connection ...") # accept any connections ...
import urllib from exceptions import QuakeAPIException, QuakeClientException, QueryNotFoundException, DuplicateQueryException def get_query(quake, query_id): assert isinstance(query_id, (int,long)), "Argument to get_query must be an integer" url = '/api/queries/%d' % query_id status_code, query_respons...
from django.contrib import admin from passcode.models import PassRequest admin.site.register(PassRequest)
import json from django.shortcuts import render, redirect, get_object_or_404 from django.urls import reverse from django.http import HttpResponse, JsonResponse, HttpRequest from django.contrib.auth import authenticate, login from django.contrib.auth.views import (LoginView, PasswordChangeView, ...
from gym.envs.registration import register # 2D Navigation # ---------------------------------------- register( '2DNavigation-v0', entry_point='envs.navigation:Navigation2DEnv', max_episode_steps=100 )
import cx_Oracle conn = cx_Oracle.connect('HLLP_SCISP_ADMIN', 'HLLPSCISPADMIN', 'DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=ollrptdbqa)(PORT=1521)))(CONNECT_DATA=(SID=ollrptqa))') cursor = conn.cursor() cursor.execute('select * from dual') row = cursor.fetchone() print(row[0]) cursor.close() conn...
import gammalib import ctools import cscripts import numpy as np from ebltable.tau_from_model import OptDepth from random import randint, uniform import xml_generator as xml from astropy.io import fits from xml.dom import minidom tau = OptDepth.readmodel(model = 'dominguez') input_model='3e-9_all.out.alert' imin = ...
from socket import socket, AF_INET, SOCK_STREAM from threading import Thread try: import tkinter as tk #python3 except ImportError: import Tkinter as tk #python2 def send_message(event=None): # event is passed by binders. msg = txt1.get() msg1 = name + ": " + msg chat_field.insert(tk.E...
import urllib.request import json import dml import prov.model import datetime import uuid class schoolrestaurant(dml.Algorithm): contributor = 'cici_fyl' reads = [] writes = ['school', 'restaurant'] @staticmethod def execute(trial = False): '''Retrieve some data sets (not using the API h...
"""App DataBase Interface """ from os.path import join import logging import sqlite3 import pandas as pd import geopandas as gpd from shapely import wkb from utilities import cwd logging.basicConfig(level=logging.INFO) log = logging.getLogger(__name__) DATABASE_PATH = join(cwd(), 'data', 'covid19.sqlite3') TRACING ...
class Locator(object): link_by_text = "//*[self::a or self::span or self::button][contains(text(),'{link_text}')]" input_by_placeholder = "//input[@placeholder='{placeholder_text}']" input_by_section_and_label = "//h3[text()='{section_text}']/following-sibling::form[1]//label[text()='{" \ ...
#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Simple Message feedback publisher. The server waits for connection and then starts publishing roboto feedback information. """ from __future__ import print_function from sys import stdout from twisted.python.log import...
import os import torch from torch import nn import torch.nn.functional as F from torch.utils.data import DataLoader, random_split import pytorch_lightning as pl from pytorch_lightning.callbacks import ModelCheckpoint from pytorch_lightning.loggers import CSVLogger import numpy as np from fairseq.modules import LayerN...
def postfixEval(postfixexp): opStack = [] tokenlist = postfixexp.split() for token in tokenlist: if token in "0123456789": opStack.append(int(token)) else: op2 = opStack.pop() op1 = opStack.pop() result = doMath(token,op1,op2) opSt...
#!/usr/bin/python import sys import os.path import ConfigParser from Response import GetResponse from Geocode import GetGeocode def main(argv): """Main function to drive the program. """ if argv is None: argv = sys.argv if len(argv) != 1: print "usage: {0} <filename>".format(__file__) exit(1) e...
from wtforms import Form, StringField, PasswordField, validators, HiddenField def length_honeypot(form,field): if len(field.data) > 0: raise validators.ValidationError('El campo debe de estar vacio') class Login(Form): userName = StringField('', [ ...
from Crypto.PublicKey import RSA from Crypto.Signature import PKCS1_v1_5 from Crypto.Hash import SHA256 import Crypto.Random import binascii from transaction import Transaction class Wallet: def __init__(self, node_id): self.private_key = None self.public_key = None self.node_id = node_id...
#/usr/bin/env python3 # -*- coding: utf-8 -*- # 2011.06.10th try def gen_from_regex( regex ): lim = 5 for i in range(0, len(regex)+1): c = regex[i] if c is '?':
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Aug 17 23:37:45 2019 @author: anthonywa """ ## TO-DO: Query 1: Give me the artist, song title and song's length in the music app history that was heard during \ ## sessionId = 338, and itemInSession = 4 query_1="SELECT artist, song, length FROM query...
from django.urls import path from . import views from django.conf.urls import patterns, url from app_name.views import * urlpatterns = patterns('', url(r'^$', IndexView.as_view()), ) urlpatterns = [ path('', views.index, name='index'), ]
from functools import wraps import inspect ######################################################################## def store_parameters( constructor ): '''Decorator for automatically storing arguments passed to a constructor. I.e. any args passed to constructor via test_object = TestObject( *args, **kwargs ...
import sqlite3 ''' CREATE define, DROP borra, ''' try: connection = sqlite3.connect("Company.db") cursor = connection.cursor() sql_command = """ CREATE TABLE IF NOT EXISTS office( id INTEGER PRIMARY KEY, name VARCHAR(20) );""" cursor.execute(sql_command) sql_command = """...
from django import forms #from django.contrib.auth.models import Portfolio #from django.contrib.auth.forms import PortfolioCreationForm """class PortfolioRegisterForm(UserCreationForm): class Meta: model = Portfolio fields = ['username','primary_email','recovery_email','date_of_bir...
from glob import glob import joblib from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer from sklearn.metrics import f1_score from sklearn.model_selection import train_test_split from sklearn.naive_bayes import MultinomialNB from sklearn.preprocessing import LabelEncoder txt_files = glob("da...
import logging from django.db.models import QuerySet from app.BatchValueOperations import BatchValueOperations from app.DatabaseServices.DeviceService import DeviceService from app.Repositories.DeviceRepository import DeviceRepository from app.Repositories.FunctionRepository import FunctionRepository from app.Reposit...
print("Your function is 8n^2+3n+3") print ("g(n) = n^2 ") print("Assuming c as 7") for i in range (30): a1 = 8*(i**2)+3*i+3 a2 = 7*(i**2) if (a1>=a2): n0 = i break print("Value of n0: ", n0) print ("Value\t\tF(n)\t\tc*G(n)") for i in range (10,31): print (i,"\t\t",8*(i**2)+3*i+3,"\t\t",7*(i**2))
"""Printa emails encontrados em um arquivo de texto. Módulo que verifica a existência do arquivo inserido e, caso exista, printa os emails encontrados nele (Caso haja algum email). """ import re def verificar_arquivo(arquivo_user: str) -> str: """Verifica existência do arquivo de texto. Args: a...
import demistomock as demisto # noqa: F401 from CommonServerPython import * # noqa: F401 from typing import Tuple, Iterable from netaddr import IPSet, IPRange import re CIDR_RE = re.compile(ipv4cidrRegex) IP_RE = re.compile(ipv4Regex) def extract_list_from_args(args: dict, list_key: str) -> List[str]: ioc_lis...
class Curve(GeometryObject,IDisposable): """ A parametric curve. """ def Clone(self): """ Clone(self: Curve) -> Curve Returns a copy of this curve. Returns: A copy of this curve. """ pass def ComputeDerivatives(self,parameter,normalized): """ ComputeDerivatives(self: Curve,para...
import csv from ._common import ExDataLoader class CSV(ExDataLoader): def exec_module(self, mod): mod.data = [] with open(mod.__spec__.origin, newline="") as f: reader = csv.reader(f) mod.raw_data = reader for row in reader: mod.data.append(row)
import numpy as np from keras.models import Model from keras.layers import TimeDistributed,Conv1D,Dense,Embedding,Input,Dropout,LSTM,Bidirectional,MaxPooling1D,Flatten,concatenate from prepro import readfile,createBatches,createMatrices,iterate_minibatches,addCharInformatioin,padding from keras.utils import Progbar fr...
""" Code for deep Q-learning as described in: Playing Atari with Deep Reinforcement Learning NIPS Deep Learning Workshop 2013 and Human-level control through deep reinforcement learning. Nature, 518(7540):529-533, February 2015 Author of Lasagne port: Nissan Pow Modifications: Nathan Sprague """ import re import l...
class Queue: # base structure is list def __init__(self): self.__struct = [] def is_empty(self) -> bool: return len(self.__struct) > 0 def front(self): return (None, self.__struct[0])[self.is_empty()] def rear(self): return (None, self.__struct[-1])[self.is_empty()...
# Import libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Import dataset dataset = pd.read_csv('Position_Salaries.csv') X = dataset.iloc[:, :-1].values Y = dataset.iloc[:, -1].values print(f"X = {X}") print(f"Y = {Y}") print() # Split Dataset: Training Set and Test Set X_train = X[:...
import argparse import parse import math parser = parse.Parser('''{:g} {:d} {:d} {:g} ''') def parse(filename): with open(filename) as file: data = file.read() return parser.parse(data) def validate(fa, fb): a = parse(fa) if a is None: return False, f'Failed to parse {fa!r}' b ...
#-*- coding: utf-8 -* vowels = ('a', 'e', 'i', 'o', 'u') letter = raw_input('Introduce una letra: ') if letter in vowels: type = 'vocal' else: type = 'consonante' print '%s es letra %s' %(letter, type)
import EleDiscordLib import EleAuditLog import discord import TicketFunctions import CommandCooldown import asyncio import datetime async def ModCmd_Audit(bot, ctx, AuditMember: discord.Member, FromDate = '1111/11/11', ToDate = '1111/11/12', AllMode = 'A'): print(bot, ctx, AuditMem...
from django.db import models from django.contrib.auth.models import User class Directory(models.Model): name = models.CharField(max_length=200) description = models.CharField(max_length=3000, blank=True, null=True) owner = models.ForeignKey(User, on_delete=models.SET_NULL, ...
Even Sum or Factors The program must accept two integers M and N as the input. If M is even then the program must print the integers from 1 to N whose sum of the last two digits is even. Else the program must print all the integers from 1 to N having even number of factors as the output. Boundary Condition(s): 1 <= M,...
from django.urls import path from .views import register, logout_view app_name = 'accounts' urlpatterns = [ # path('logout/', logout_view, name='logout'), path('signup/', register, name='signup') ]
# Generated by Django 3.2.4 on 2021-07-09 11:54 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('car', '0008_alter_car_color'), ] operations = [ migrations.AddField( model_name='carcolor', ...
# -*- coding: utf-8 -*- """ Base ~~~~~ Base Test case for use with all unittests :copyright: (c) 2015 by Thomas O'Donnell. :license: MIT, see LICENSE for more details. """ from __future__ import unicode_literals import unittest from app import app, db class BaseTestCase(unittest.TestCase): ""...
import tkinter as tk from tkinter import messagebox class Application(tk.Tk): def __init__(self, master=None): tk.Tk.__init__(self, master) self.title("Text Book Price Calculator") self.create() def create(self): self.tbLabel = tk.Label(self, text="Number of textbooks ordered:...
from selenium import webdriver url = 'https://weibo.com/' username = '' password = '' text = """#随手赚钱# #掌赚宝-手机赚钱# #微博赚钱季# #躺着赚钱,卧床不起# #随手赚钱# 投吧问卷调查,就是在网上做问卷调查,手机电脑都可以做,注册个账号就可以了,每天有时间的时候点点,回答一些特别简单的问题, 满10元就可以支付宝提现哦,一天150-200左右,感兴趣的朋友可以来试试。http://www.votebar.com/r.aspx?r=54082904119156 """ driver = webdriver.Chrome()...
from src.team import build_all_teams, setup_game_input import src.default_parameters as default import datetime import numpy as np import pandas as pd import os def rank_teams(dataset, date=datetime.datetime.now(), rank_algo='lin_regress'): """ """ season = date.year if date.month >= 9 else date.year-1 teams = [t...
import MapReduce import sys """ Word Count Example in the Simple Python MapReduce Framework """ mr = MapReduce.MapReduce() # ============================= # Do not modify above this line def mapper(record): seq_id = record[0] seq = record[1] trimmed_sec = record[1][0:len(record[1])-10] mr.emit_intermediat...
""" Copyright (c) 2019 Intel Corporation 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 wri...
'''迭代器''' '''可直接作用于for循环的数据类型: 1.集合数据类型:list、tuple、dict、set、str等 2.generator,包括生成器和带yield的generator function 这些可直接作用于for循环的对象统称为可迭代对象:Iterable''' '''可用isinstance()判断一个对象是否是Iterable对象''' from collections import Iterable print(isinstance([],Iterable)) #list print(isinstance({},Iterable)) #tuple print(isinstance('abx',...
#!/usr/bin/env python # -*- coding: utf-8 -*- from bqpipeline.bqpipeline import BQPipeline import sys if __name__ == "__main__": JOB_NAME = sys.argv[1] PROJECT = sys.argv[2] DATASET = sys.argv[3] bq = BQPipeline(job_name=JOB_NAME, query_project=PROJECT, default_p...
""" written by David Sommer (david.sommer at inf.ethz.ch) and Liwei Song (liweis at princeton.edu) in 2020, 2021. This file generates some of the empirical plots shown in the paper. This file is part of the code repository to reproduce the results in the publication "Athena: Probabilistic Verification of Machine Unl...
import requests from bs4 import BeautifulSoup def get_keywords(url='https://baike.baidu.com/item/%E4%BF%AE%E7%9C%9F%E8%81%8A%E5%A4%A9%E7%BE%A4/18768294', page_encoding='iso-8859-1'): s = requests.Session() s.headers['User-Agent'] = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome...
""" Custom widgets used in the app's windows. """ from itertools import count import os import tkinter as tk from PIL import Image, ImageTk from kana_teacher.kana import KANA FONT = ("Helvetica", 20) KANA_CHART_HIGH_BG = "green" class KanaChart(tk.Frame): """Build a tkinter frame that displays a chart of eithe...
# -*- coding: utf-8 -*- """ Created on Wed Jan 20 11:04:01 2021 @author: core i5 """ import AppMenu as am import sqlite3 as sql3 import sys from PyQt5.QtWidgets import (QMessageBox, QPushButton, QApplication, QWidget, QLineEdit, QDesktopWidget, QLabel, QListWidget, ...
#coding: utf-8 from datetime import datetime, date from dateutil.relativedelta import relativedelta class Semestre(object): _ID = 1 def _semestre_nome(self, datetime): mes = datetime.month if mes < 6: return '1' else: return '1' def __init__(self): self.id = self._ID; self.__class__._ID += 1 ...
from enum import IntEnum import wpilib from networktables import NetworkTables class Field: def execute(self): robot_table = NetworkTables.getTable('robot') robot_table.putValue('time', wpilib.Timer.getMatchTime())
import numpy as np import os import pandas as pd import statistics ### Set your path to the folder containing the .csv files PATH = './' # Use your path ### Fetch all files in path fileNames = os.listdir(PATH) ### Filter file name list for files ending with .csv fileNames = [file for file in fileNames if '.csv' in f...
# MAKE A CUSTOM VECTOR CLASS from math import hypot class Vector: def __init__(self, x = 0, y = 0): self.x = x self.y = y def __repr__(self): return 'VECTOR : (%r, %r)' % (self.x, self.y) def __abs__(self): ...
import pickle PICKLE_FILE = 'data/onekm/aurora_cases.pkl' with open(PICKLE_FILE, 'rb') as fh: aurora_cases = pickle.load(fh) print(len(aurora_cases)) # Length of the individual entries problem_description = aurora_cases.problem_description.values evaluation_summary = aurora_cases.evaluation_summary.values case_s...
# https://atcoder.jp/contests/abc203/tasks/abc203_b from typing import * def solve(n: int, k: int) -> int: a = [] for i in range(1,n+1): for j in range(1,k+1): a.append(100*i + j) ans = sum(a) return ans def main() -> None: n, k = map(int, input().split()) ans = solve(n...
from django.test import TestCase from friendcard.models import FriendCard from django.contrib.auth.models import User # Create your tests here. class FriendCardTestCase(TestCase): def test_true_is_true(self): self.assertEqual(True, True) def test_create_card(self): user = User() user.s...
#!/usr/bin/env python3 # usage: # echo $input | ./1b.py # OR # ./1b.py input.txt # # test with: # python3 -m doctest 1b.py import fileinput import sys def process(line, floor=0, pos=0): """Return the position of the first character ine line that causes floor to become negative. >>> process(')') 1 >>>...
""" Suits: * d - diamonds (♦) * c - clubs (♣) * h - hearts (♥) * s - spades (♠) """ SUITS = ('d', 'c', 'h', 's') class Card: def __init__(self, number, suit): if suit not in SUITS: raise BaseException(f'suit: "{suit} not in a {SUITS}') self.suit = suit if not 1 <= number <= ...
# -*- coding: utf-8 -*- import unittest from common.utils import twitter as twitter_util class TestTwitter(unittest.TestCase): def test_truncate_linked_tweet(self): original = "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890abcdefg http://www.snsanalytics.com/6...
import os import csv csvpath=os.path.join('..','PyPoll','election_data.csv') with open(csvpath, newline='') as csvfile: csvreader = csv.reader(csvfile,delimiter=',') csv_header = next(csvreader) totalVotes = 0 candidateVotes = {} voteWinner = "" for rows in csvreader: ...
import hashlib import importlib import string from collections import OrderedDict from django.utils import six from django.utils.six.moves.urllib.parse import urlsplit def create_avatar_url(email, size=100, default='identicon', rating='g'): url = 'http://www.gravatar.com/avatar' hash = hashlib.md5(email.enco...
# https://www.codewars.com/kata/regex-like-a-boss-number-3-different-number-formats/train/python # tested beta kata REGEX = r'''^(0{1}|((0(?=\.)\.\d*[1-9])|([1-9]\d{,2}(?<=\d)([,]\d{3})*(\.\d*[1-9])?))|((0(?=,),\d*[1-9])|([1-9]\d{,2}(?<=\d)([\s]\d{3})*(\,\d*[1-9])?)))$'''