text
stringlengths
38
1.54M
d1={ 101:"RaviKumar", 102:"Vishnu"} print(d1[101]) for i in d1: print(d1[i]) print(i,"\t",d1[i])
import json with open("C:\\Users\\Administrator\\PycharmProjects\\untitled\\data_file\\user_info.json","r")as f: data=f.read() user_list=json.loads(data) print(user_list)
file_open = open("C:\\Users\\Ramya\\QAdata_as_of_Feb172011\\python_problems\\other_python_prob\\agedata.csv", 'r') dict = {} for i in file_open: print i x = i.rstrip('\n').split(',') print "x", x key = x[0] value = x[1] # print key, value if dict.has_key(key): dict[key]...
""" Named Entity Recognition """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import torch from .common.hparams import HParams from .data.conll import conll2003_dataset from .data.nyt import nyt_ingredients_ner_dataset from .tasks.sequence_tagging impor...
import numpy as np import pandas as pd #import matplotlib.pyplot as plt import re from tqdm import tqdm import time import os,sys from collections import Counter import punctuation import codecs import pyIO import datetime import tools import tools import fasttext def get_word_by_filename(filename): for i in rang...
class Edge: def __init__(self): """nothing to initialize, assume set gets called right after""" def print_state(self): print "edge:", "[", self.i, self.j, "] -> c:", self.c, " f: ", self.f def set(self, i, j, c=0, f=0): self.i = i self.j = j self.c = c self...
# -*- coding: utf-8 -*- from z3 import * q1, q2, q3, q4 = Reals('q1 q2 q3 q4') p = Real('p') R, T, S, P = Reals('R T S P') f0 = -P*p + P + T*p f1 = (P*p - P + R*p**2 - R*p - S*p**2 + 2*S*p - S - T*p)/(p - 2) f2 = (-P*p + P + R*p**2 - S*p**2 + S*p + T*p)/(p + 1) f3 = -P*p/2 + P/2 + R*p/2 - S*p/2 + S/2 + T*p/2 f4 =...
from unittest.mock import patch import pytest from app.dao import DAO from app.models.aluno import Aluno def test_get(): dao = DAO(Aluno()) dao.get() assert isinstance(dao, DAO) def test_insert(): aluno = DAO(Aluno(nome="Teste")).insert() assert isinstance(aluno, Aluno) assert aluno.nome =...
########## #Question# ########## ''' URL: https://leetcode.com/problems/sort-array-by-increasing-frequency/ Given an array of integers nums, sort the array in increasing order based on the frequency of the values. If multiple values have the same frequency, sort them in decreasing order. Return the sorted array. ...
from django.contrib.contenttypes.models import ContentType from django.db import models from django.urls import reverse from mptt.fields import TreeForeignKey from mptt.models import MPTTModel from django.utils.translation import ugettext_lazy as _ from django_comments.abstracts import CommentAbstractModel class OmsC...
Given a string of both uppercase and lowercase alphabets, the task is to print the string with alternate occurrences of any character dropped(including space and consider upper and lowercase as same). Input: First line consists of T test cases. First line of every test case consists of String S. Output: Single line o...
def welcome(): print("You are welcome!") welcome() def Salutation(name): print('Welcome ' + name + " !") Salutation(input('what is your name: '))
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlCollectionReceiveBaseInfoDTO(object): def __init__(self): self._collection_title = None self._memo = None self._order_id = None self._source_sys = None s...
class Person(object): __count = 0 @staticmethod def how_many(): return Person.__count def __init__(self, name): self.name = name Person.__count = Person.__count + 1 print(Person.how_many()) p1 = Person('Bob') print(Person.how_many())
import logging import os import boto3 from botocore.exceptions import ClientError from ask_sdk_core.handler_input import HandlerInput from ask_sdk_dynamodb.adapter import DynamoDbAdapter ddb_region = os.environ.get('DYNAMODB_PERSISTENCE_REGION') ddb_table_name = os.environ.get('DYNAMODB_PERSISTENCE_TABLE_NAME') ddb_...
# Generated by Django 3.2 on 2021-04-20 09:03 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('articles', '0006_comment_article'), ] operations = [ migrations.AlterField( model_name='comment', name='body', ...
from qt import * from kdeui import * from kdecore import * from kfile import * from KPyBTMain.Forms import KPyBTCfgPageGlobalsBase class KPyBTCfgPageGlobals(KPyBTCfgPageGlobalsBase): def __init__(self,parent,config): KPyBTCfgPageGlobalsBase.__init__(self,parent) self.connect(self.btnTorrentDir,...
# Generated by Django 2.1.3 on 2018-12-04 09:25 import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('messenger', '0002_auto_20181204_1447'), ] operations = [ migrations.AlterField( ...
from dfa import DFARuleBook, DFADesign class FARule(object): def __init__(self, state, character, new_state): self.state = state self.character = character self.new_state = new_state def applies_to(self, state, character): return self.state == state and self.character == char...
from django.conf.urls import patterns, include, url from rest_framework import routers from users import views as users_view from couples import views as couples_view # from django.contrib import admin # admin.autodiscover() router = routers.SimpleRouter(trailing_slash=False) router.register(r'users', users_view.Us...
import pychromecast import requests import random from time import sleep from requests.auth import HTTPBasicAuth LFM_API_KEY = '57ee3318536b23ee81d6b27e36997cde' SPOTIFY_API_CLIENT = 'b5c1e08b7d2846edb40ad73eadcbce95' SPOTIFY_API_SECRET = '6f92952220eb4b36975d14e928226db2' def getTopArtists(username): request = r...
# -*- coding: utf-8 -*- import logging from utils import mongo from utils import config from utils import entity_resolver class ParseMeetings(): def __init__(self, **kwargs): self._logger = logging.getLogger('spud') self.db = mongo.MongoInterface() self.resolver = entity_resolver.MasterEnt...
# from datetime import date, datetime # from unittest import skip # from unittest.mock import MagicMock, patch # from dateutil.relativedelta import relativedelta # from django.test import TestCase # from balances.models import PeriodBalance # from balances.strategies.periods import (BaseStrategy, ChangedAccountStrate...
import numpy as np import random # normalize all data def normalize(data): print("Data normalization...") shape = data.shape data = np.reshape(data, (shape[0], -1)) # scaling data = data.astype('float32') / 255. # normalizing data = data - np.mean(data, axis=0) print("Done.") retu...
def matchResultat(match_id, cursor): goal_list = cursor.execute( "select home_team_goal, away_team_goal from 'Match' where id =" + str(match_id) + ";").fetchall() if goal_list[0][0] > goal_list[0][1]: result = 0 elif goal_list[0][0] < goal_list[0][1]: result = 2 else: re...
''' DiscoAtThePanic - Robin Han, Vincent Chi SoftDev2 pd7 K #17: PPFTLCW 2019-04-14 ''' import math a = [0,1,2,3,4] b = [0,1,2] not_primes = [] def q1_loop(): temp = [] for i in range(5): temp.append(i*22) print(temp) def q1_list(): print ([x*22 for x in a]) def q2_loop(): temp = [] ...
import geojson import requests geojsonurl = 'https://raw.githubusercontent.com/jtweddle89/proj-mapping/master/test/map.geojson' r = requests.get(geojsonurl) mydata = r.json() print(mydata.keys()) #print out keys and values of every item in every properties dictionary, skipping items that have value of "" ix = len(my...
from core import app from markupsafe import escape from http import HTTPStatus from flask import abort, request from flask.wrappers import Response from datetime import datetime from models import db from models import User @app.route("/hello/<username>", methods=['GET']) def get_username(username): sanitized_us...
from random import* firstavg = 0 randavg = 0 leastavg = 0 zeroten = 0 for a in range(100000): # number of flips for each of 100 coins tenFlips = range(1000) # total flips tenthousand = range(10000) for i in range(10000): tenthousand[i] = randint(0, 1) for j in range(1000): ten...
name=" Pratiksha " print(name) #Strip remove the blank Spaces print(name.strip()) print(len(name)) Last_name="Sawandkar" print(Last_name[2:5]) print(Last_name) var=Last_name.lower() print(var) var2=Last_name.replace("r" , "t") print(var2) var3=Last_name.lower() print(var3) #Remove , Using The replace method frie...
import numpy as np def encode_16bit(wave: np.ndarray): encoded = ((wave + 1) * 2 ** 15).astype(np.int32) encoded[encoded == 2 ** 16] = 2 ** 16 - 1 coarse = encoded // 256 fine = encoded % 256 return coarse, fine def encode_single(wave: np.ndarray, bit: int = 8): if 8 < bit: wave = wa...
import sys, os import pandas as pd from specter import Spec, expect from timezone import Timezone sys.path.append(os.path.join(os.path.dirname(__file__), '../', 'code')) class TimezoneSpec(Spec): class to_standard(Spec): def should_convert_to_standard(self): tz = Timezone('Abu Dhabi') ...
import pygame as pg from services.resources import ResourcesService class GameObject: image_path = None def __init__(self, screen): self._screen = screen self._image = pg.image.load(ResourcesService(self.get_image_path()).path).convert_alpha() self._rect = self._image.get_rect() ...
#! /usr/bin/env python import numpy as np import torch import torch.nn as nn import math import rospy from std_msgs.msg import String, Int8 from geometry_msgs. msg import Vector3 from collections import OrderedDict from Algs.AutoDecompose import Decompose from Tasks.decomposeTask import DecomposeTask from Algs.d...
# coding: utf-8 import floppyforms.__future__ as forms_ from django import forms from django.conf import settings from django.contrib.auth import get_user_model from django.utils.safestring import mark_safe from django.utils.translation import ugettext_lazy as _ from scoop.core.util.shortcuts import get_website_name fr...
import datetime from flask_jwt_extended import JWTManager from app.utils.env_utils import EnvUtils jwt = JWTManager() def configure_security(app): access_token_expires = datetime.timedelta(seconds=int(EnvUtils.get_env('APP_SECURITY_ACCESS_TOKEN_EXPIRES'))) refresh_token_expires = datetime.timedelta(seconds...
from django.apps import AppConfig class ServiceProductConfig(AppConfig): name = 'service_product'
""" 找出100~999之间的所有水仙花数 水仙花数是各位立方和等于这个数本身的数 如: 153 = 1**3 + 5**3 + 3**3 @Author:jyang @Date:5/10/2019 """ import math l = [] for i in range(100, 1000): a = int(i/100) b = int(i%100/10) c = int(i%100%10) if i == math.pow(a, 3) + math.pow(b, 3) + math.pow(c, 3): l.append(i) print(l)
#!/usr/bin/python3.4 # coding: utf-8 """ Programme (classe) : thread_p2_arret.py version 1.0 Date : 17-03-2018 Auteur : Hervé Dugast source : https://python.developpez.com/faq/?page=Thread Fonctionnement : Affiche exécution de 3 threads (compteur infini). Demande l'arrêt de chacun des threads et montre l'a...
# SMALLEST MULTIPLE # Get all prime numbers and their powers a = 2**4 * 3**2 * 5 * 7 * 11 * 13 * 17 * 19 print(a)
import plotly.graph_objs as go import plotly import math plotly.tools.set_credentials_file(username='ltknow', api_key='Lg7qlfduhEolzJYMyEdk') class MapDrawer(object): def __init__(self, as_graph): self.as_graph = as_graph def draw_map(self, filename): colorscale = [[0.0, 'rgb(254,224,144)'...
import maya.cmds as cmds cmds.polyCylinder(n='TourBase',r=3,h=6) cmds.xform(ws=True, piv=(0,3,0)) cmds.move(0,-3,0) for i in range(2): cmds.polyCylinder(n='Tour1',r=3.2+(.1*i),h=0.3,sa=30) cmds.move(0,0.3*i,0) cmds.group('Tour*',n='GroupTour') cmds.select('GroupTour') cmds.xform(ws=True, piv=(0,0.75,0)) ...
import numpy as np import pandas as pd import gdal import gdalconst def rcs_trihedral_cr(cr_len, wavelength, inc_angle, tilt_angle, azimuth_angle): tilt_angle = np.deg2rad(tilt_angle) azimuth_angle = np.deg2rad(azimuth_angle) theta = inc_angle + tilt_angle t1 = (4 * np.pi * (cr_len ** 4)) / (wavelen...
try: pasw=input("please enter your password: ") assert len(pasw)>8, "you have entered wrong lenght" except AssertionError as obj: print("you have enter wrong lenght of password") finally: print("Program terminated")
"""empty message Revision ID: a15584bf7905 Revises: f8ab52be12f8 Create Date: 2019-11-22 17:03:02.655881 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = 'a15584bf7905' down_revision = 'f8ab52be12f8' branch_labels = None...
import time from tkinter import TclError from snake.controller import Controller, UserControl class View: def __init__(self): self.bound = False self.ai_high_score = 0 self.player_high_score = 0 try: self.controller = Controller(load_population=True) ...
import os, sys, json import argparse from copy import deepcopy from gi.repository import Gtk, Gdk def sort_name (model, a, b, data): na = model.get_value (a, 0) nb = model.get_value (b, 0) if na > nb: return 1 else: return -1 def sort_valid (model, a, b, data): va = model.get_value (a, 1) vb = model.get_...
import unittest import tkinter as tk from Logic.GameState import GameState from Logic.Hand import Hand from Logic.Card import Card class UnitTests(unittest.TestCase): def test_someone_has_blackjack_3(self): root = tk.Tk() gameState = GameState() gameState.player_hand = Hand() gam...
# coding: utf-8 import pandas from numpy import isnan country = "us" spider = "gpmn_parks" _type = "pollution" source_name = "https://www.nps.gov" in_file_name = "{0}_{1}_{2}_stations.txt".format(country, spider, _type) out_file_name = "add_station_{0}_{1}_{2}.sql".format(country, spider, _type) data_frame = panda...
#!/Library/Frameworks/Python.framework/Versions/3.7/bin/python3 # To compile: python ./name.py import sys, os from tkinter import * from tkinter import messagebox import subprocess #####------------------------------------------------(Constants) #arguments= #name= #path= #version=1.0 program_name="template" def sep(...
#!/usr/bin/python3 # include required libraries import csv import xml.etree.ElementTree as ET import sys import re # get file objects from cl if len(sys.argv) == 3: teixml_input_file = open(sys.argv[1]) csv_input_file = open(sys.argv[2]) else: sys.exit("Must include files with TEI and reference URIs") ...
class Solution: def solve(self, A): my_map = {} running_sum = 0 for i in A: running_sum += i if my_map.get(running_sum) is not None or running_sum == 0: return 1 else: my_map[running_sum]=running_sum return -1 pri...
import tensorflow as tf from PIL import Image import os # os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # os.environ["CUDA_VISIBLE_DEVICES"] = "-1" from network import encoder, decoder from ops import * from utils import * class main: def __init__(self): self.content = tf.placeholder("float...
from requests.packages.urllib3 import disable_warnings from requests.packages.urllib3.exceptions import InsecureRequestWarning from sampledata import getyaml from src import loginOS, snmp, system disable_warnings(InsecureRequestWarning) # Login to Switch data = getyaml.readyaml('data-device-mgmt.yaml') # Iterate thr...
from recommenders.cb_recommender import CBRecommender from recommenders.cbf_recommender import CBFRecommender from utils.recommendations_helper import RecommendationsHelper class WeightedHybridRecommender: def __init__(self): self.MIN_NUM_OF_ITEMS = 20 self.MAIN_RECOMMENDER_WEIGHT = .8 sel...
# Generated by Django 2.1.7 on 2019-03-18 08:18 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('utils', '0001_initial'),...
class Solution(object): def subdomainVisits(self, cpdomains): """ 一个网站域名,如"discuss.leetcode.com",包含了多个子域名。 作为顶级域名,常用的有"com",下一级则有"leetcode.com",最低的一级为"discuss.leetcode.com"。 当我们访问域名"discuss.leetcode.com"时,也同时访问了其父域名"leetcode.com"以及顶级域名 "com"。 给定一个带访问次数和域名的组合,要求分别计算每个域名被访问的次数。其格式为访问次数+空格+地址, 例如:"9001 discus...
import glob import os import sys INPUT_DIR = sys.argv[0] out_filename = "combined_seizure_reports.csv" if os.path.exists(out_filename): os.remove(out_filename) read_files = glob.glob("INPUT_DIR/*.csv") with open(out_filename, "w") as outfile: for filename in read_files: with open(filename) as infile:...
# Hae ubuntun manuaalisivuilta monikielistä dataa ja tee niistä käännösmuisti from clusters import MultiLangDocu MyDocu = MultiLangDocu(["fi","en","de","fr","ru","sv"]) for theme in ["net-wireless","files","clock","prefs-language","prefs-display","media","accounts","shell-overview","tips","a11y","printing","bluetooth...
from .util import load_image, terminate from .settings import FPS import pygame class Pause: def __init__(self, game): self.game = game self.surface = self.game.surface self.init_images() self.resume = self.resume_images[0] self.exit = self.exit_images[0] self.ma...
""" Course : CST205 Title : botcommands.py Authors: Javar Alexander, Honorio Vega Abstract : This contains the possible commands that the bot can do. It can be made to repeat what a user said. It can also be made to fetch pictures and gif's from Getty and Giffy respectively. Date : 03/15/2017 W...
#!python3 # binary2decimal.py - program to convert binary value to decimal def bin2dec(binary): output = 0 binary = list(binary) for i in range(len(binary)): output += (2 ** i) * int(binary.pop()) print(f'decimal value {output}\n') while True: value = input("Enter Binary value: ") if v...
num=int(input('enter the value')) if num<0: print('no factorial for _ve numbers') elif num==0: print('the factorial of 0 is 1') else: fact=1 for i in range(1,num+1): fact= fact*i print("the factorial of", num,"is",fact)
from flask import Flask, render_template, request import urllib3.request import requests from VH import predict import numpy as np app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/', methods=['POST']) def form(): X_pred = [] for i in range(1, 16): ...
import numpy as np import pandas as pd from typing import List from geo.math import num_haversine, vec_haversine # Both methods below were taken from # https://medium.com/unit8-machine-learning-publication/ # from-pandas-wan-to-pandas-master-4860cf0ce442 def mem_usage(df: pd.DataFrame) -> str: """ This met...
# Create your views here. from rest_framework import viewsets, permissions from rest_framework.decorators import action from rest_framework.response import Response from . import models from . import serializers class DebugtalksViewSet(viewsets.ModelViewSet): """ list: 获取结果集 update: 全字段更新 ...
# https://selenium-python.readthedocs.io/installation.html from selenium import webdriver from selenium.webdriver.common.keys import Keys from PIL import Image from io import BytesIO import time with open('wards.txt', 'r') as f: c = [line.strip() for line in f] driver = webdriver.Firefox() def open_m...
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from models import Category, Base, CategoryItem, User engine = create_engine('sqlite:///catalog.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() # Create dummy user user = User( name="Sports ...
``` tesorflow 1.14.0 run in colab. dataset:fashion_mnist consisting of a training set of 60,000 examples and a test set of 10,000 examples. Each example is a 28x28 grayscale image, associated with a label from 10 classes. ``` import tesorflow as tf print(tf.__version__) # tensorflow版本信息 ...
from rest_framework import status from rest_framework import generics, permissions from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework.authentication import TokenAuthentication from .models import User from users.serializers import RegistrationSerializer, User...
from django.contrib.auth.decorators import login_required from django.shortcuts import render from Mini_CMS.models import Categoria @login_required() def Index(request): if Categoria.objects.all().count() == 0: Categoria.objects.create(nombre='Epmty') return render(request, 'index.html')
#!/usr/bin/env python2 from journal_loader import JournalLoader from view_controller import ViewController from mood_engine import MoodEngine import mood_time def main(): mood_time.TEST_TIMING = True tickSpeedMs = 100 fadeSpeedMs = 10000 xLen = 30 yLen = 60 zLen = 1 journalCsv = 'tempMarnsJournal.csv' j...
import sys sys.path.insert(0, '../API') from alarm_controller import AlarmController sys.path.insert(0, '../hl7parser') from hl7parser import patient, measure, channel from Queue import Queue from threading import Lock from controller import Controller from PyQt4.QtGui import QPixmap class MonitorController(Controller...
#! -*- coding: utf-8 -*- # Una jerarquia de clases class Vehiculo(object): def desplazarse(self): pass # Otra jerarquia que no tiene nada que ver class Activo(object): def calcular_depreciacion_anual(self): pass # Quizas en una empresa un vehiculo se tiene # que dep...
#!/usr/bin/env python # -*- coding: utf-8 -*- from htdp_pt_br.universe import * ''' JOGO DO ARKANOID''' '''=============================================================''' ''' PREPARAÇÃO DE TELA E CONSTANTES''' FREQUENCIA = 60 LARGURA,ALTURA = 800,800 TELA = criar_tela_base(LARGURA,ALTURA) IMG_BARRA = carregar_i...
import numpy as np import matplotlib.pyplot as plt from matplotlib import animation import matplotlib.patches as patches from LucasKanade import * # write your script here, we recommend the above libraries for making your animation frames = np.load('../data/carseq.npy') rect = [59, 116, 145, 151] width = rect[3] - rec...
import glob import csv import sys # change float to int for series lunch files path = sys.argv[1] for fname in glob.glob(path): # print fname with open(fname) as csvfile: readCSV = csv.reader(csvfile, delimiter=',') print fname # n = len(readCSV[0]) rows=[] current = 0 current=0 count2=0 count=0 ...
import math import os import random import numpy import pygame # Стандартная функция загрузки изображнения def load_image(name, colorkey=None): fullname = os.path.join('data', name) image = pygame.image.load(fullname) if colorkey is not None: if colorkey == -1: colorke...
#! /usr/bin/env python import urllib def read_text(): quotes = open('/home/rodrigo/Documentos/python/doc') contents_of_file = quotes.read() # print(contents_of_file) quotes.close() check_profanity_function(contents_of_file) def check_profanity_function(text): connection = urllib.urlopen('http://www.wdylike.apps...
from lib.dateutil.relativedelta import relativedelta import hashlib import time # Time convert usage # date(relativedelta(seconds=1207509)) attrs = ['years', 'months', 'days', 'hours', 'minutes', 'seconds'] date = lambda delta: [ '%d %s' % ( getattr(delta, attr), getattr(delta, attr) > 1 and attr ...
import argparse import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data def load_graph(frozen_graph_filename): # We load the protobuf file from the disk and parse it to retrieve the # unserialized graph_def with tf.gfile.GFile(frozen_graph_filename, "rb") as f: graph_d...
def solution(): N, K = input().split() K = int(K) mArr = input().split() count = 1 for i in range(K): mArr.pop() while True: if len(mArr) >= K-1: count += 1 for j in range(K-1): mArr.pop() elif len(mArr) == 0: break ...
print('##############') print('# D #') print('# I #') print('# L #') print('# U #') print('# X #') print('##############') print('\n') name = 'Diluxshan' print('My name is '+name+ '. Hello '+name+'.') name = 'Pavi' print('My name is '+name+ '. Hello '+name+'.') capital=...
from Tkinter import * class Demo(Frame): def __init__(self,parent): Frame.__init__(self) self.frameParent=parent self.frame1=Frame( self.frameParent, ) self.frame1.grid( row=0, column=0, ) self...
import game, socket, threading, collections, pygame, extentions, logging, json module_logger=logging.getLogger("jt3.server") debug, info, warning, error, critical = module_logger.debug, module_logger.info, module_logger.warning, module_logger.error, module_logger.critical class ServerGame(game.Game): def start_connec...
import pytest from helpers.cluster import ClickHouseCluster from helpers.mock_servers import start_mock_servers import os METADATA_SERVER_HOSTNAME = "resolver" METADATA_SERVER_PORT = 8080 cluster = ClickHouseCluster(__file__) node = cluster.add_instance( "node", with_minio=True, main_configs=["configs/us...
import time nazev=input("Zadejte nazev knihy (bez pripony)\n") start=time.time() kniha=open(nazev+".txt","r") slova2=kniha.read().split(" ") kniha.close() dalsi,slova,Slovo=[],[],None for i in range(len(slova2)): a=slova2[i].split("\n") for i in range(len(a)): dalsi.append(a.pop(0)) for i in range(...
# -*- coding: utf-8 -*- ''' Created on Jun 19, 2017 @author: dzh ''' from ..model.constant import YP_USER_HOST, APIKEY, VERSION_V1, USER, VERSION_V2 from .ypapi import YunpianApi, CommonResultHandler class UserApi(YunpianApi): '''用户接口 https://www.yunpian.com/api2.0/user.html''' def _init(self, clnt): ...
characters = "Bste!hetsi ogEAxpelrt x " document = "AlgoExpert is the Best!" def generateDocument(characters, document): for character in document: doc_freq = count_char_freq(character, document) char_freq = count_char_freq(character, characters) if doc_freq > char_freq: return...
from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ class User(AbstractUser): GENDER = [ ('M', 'Male'), ('F', 'Female') ] USER_TYPE = [ ('B', 'Basic'), ('P', 'Premium') ] secur...
from sys import maxsize class Contact: def __init__(self, id=None, fname=None, mname=None, lname=None, nname=None, photo=None, title=None, company=None, addr=None, home=None, mobile=None, work=None, fax=None, email=None, email2=None, email3=None, homepage=None, bmonth=None, bday=None, amonth=None, aday=None, byea...
first_name = 'Dušan' last_name = 'Tanasić' output = 'Hello ' + first_name + ' ' + last_name output = 'Hello {} {}'.format(first_name, last_name) output = 'Hello {0} {1}'.format(first_name, last_name) # Only in python 3.X output = f'Hello {first_name} {last_name}' print(output)
import urllib.request from time import sleep from http.client import IncompleteRead from config import * URL = "http://cube.rider.biz/visualcube.php" def replace_at_index(string, index, letter): return string[:index] + letter + string[index + 1:] vcube_skel = { 'outer': "wwwwwwtttwwtttwwtttwwwwww"*3 + "ssss...
# Generadores: #De numeros primos: from math import sqrt def primos(ini, fin, salto=1): def esPrimo(numero): for i in range(2, round(sqrt(numero))+1): if numero % i == 0: return False return True # Codigo principal del generador: i = ini while i < fin: if esPrimo(i): yield i ...
""" The :mod:`classifier` is a high-level interface to train a short-text data. Members of :mod:`classifier` include :class:`TextModel` and its utility functions. :class:`TextModel` is obtained in training and then used in prediction. The standard method to get a :class:`TextModel` instance is via function :func:`t...
# Generated by Django 3.0.7 on 2020-06-18 06:37 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='actor', fields=[ ('id', models.AutoField(au...
"""Admin error classes.""" from ..core.error import BaseError class AdminError(BaseError): """Base class for Admin-related errors.""" class AdminSetupError(AdminError): """Admin server setup or configuration error."""
# https://www.codewars.com/kata/568d0dd208ee69389d000016 # # After a hard quarter in the office you decide to get some rest on a vacation. # So you will book a flight for you and your girlfriend and try to leave all # the mess behind you. # # You will need a rental car in order for you to get around in your vacation. #...
# -*- coding: utf-8 -*- from google.appengine.ext import db from google.appengine.api import memcache from utils import FrontendHandler, need_auth from models import Account, AccountOperation from filters import do_label_for_acc_oper class HistoryController(FrontendHandler): @need_auth() def account_ops(self, ...
cnt = 0 for i in range(3,1000000,2): in_cnt = 0 for j in range(2,i): if i % j == 0: in_cnt += 1 break if in_cnt == 0: cnt += 1 if cnt >= 10001-1: break print(i)