text
stringlengths
8
6.05M
#!/usr/bin/env python3 import requests import os import hashlib import io URL_BASE = "https://cse6040.gatech.edu/datasets/" def on_vocareum(): return os.path.exists('.voc') def localize_file(filebase): if on_vocareum(): local_dir = "../resource/asnlib/publicdata/" else: local_dir = "" ...
filename='programming.txt' #写入方式写入文件 #with open(filename,'w') as file: #追加方式写入文件 with open(filename,'a') as file: file.write("\nI also love finding meaning in large datasets.\n") file.write("I love creating apps that can run in a browser.\n")
from collections import OrderedDict def clean_list(list_to_clean): return list(OrderedDict.fromkeys(list_to_clean)) if __name__ == '__main__': print(clean_list([32, 32.1, 32.0, -123]))
import cv2 import sys import numpy as np import os if len(sys.argv) < 3: print "Usage : " + sys.argv[0] + " <classifier> <image path>" sys.exit() if not os.path.exists("output"): os.makedirs("output") def getAdaptiveIndices(ar, loc, mAr, mLoc): # Make it adaptive l1, l2, a1, a2 = 0.6, 2.0, 0.6, 2...
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.neural_network import MLPClassifier from sklearn.metrics import accuracy_score # Preprocessing the dataset df = pd.read_csv('../iris.csv') X = df.drop(['variety'], axis=1).values y = df['variety'].values X_train, X...
# -*- coding: utf-8 -*- """ Created on Tue Feb 20 16:44:24 2018 @author: XuL """ import re import pandas as pd from nltk import tokenize def find_case(x): try: st = re.search(r'Bankr\.|Bank\.', x).span()[0] end = re.search(r'Case No + \d\d_\d\d\d\d\d|\d_\d\d\d\d\d', x).span()[1] ...
# BSD 3-Clause License. # # Copyright (c) 2019-2023 Robert A. Milton. 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 notic...
from wtforms_alchemy import ModelForm, ModelFieldList import wtforms as wtf
from eos import SourceManager, JsonDataHandler, JsonCacheHandler from eos.data.exception import ExistingSourceError from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy from flask_cache import Cache db = SQLAlchemy() migrate = Migrate() cache = Cache() def configure_extensions(app): """R...
from nose.tools import assert_raises, eq_ from eelbrain.plot import _base from eelbrain.plot._base import Layout class InfoObj: "Dummy object to stand in for objects with an info dictionary" def __init__(self, **info): self.info = info def assert_layout_ok(*args, **kwargs): error = None l =...
import unittest, platform, sys, os import platform from selenium import webdriver from selenium.webdriver.common.keys import Keys from main.activity.desktop_v3.activity_register import registerActivity from main.page.base import * from main.page.desktop_v3.header import * from utils.function.setup import * from utils....
import redis client = redis.Redis() client.set('visitor:home', 1) for i in range(0,10): client.incr('visitor:home') print(client.get('visitor:home').decode('utf-8')) print("=======") for i in range(0,10): client.decr('visitor:home') print(client.get('visitor:home').decode('utf-8')) client.delete('...
#!/bin/python2 """ openssl enc -d -a -aes-128-cbc -K 41414141414141414141414141414141 -iv 00000000000000000000000000000000 -in <(echo -e $(python2 challenge9.py)) """ import binascii import base64 from Crypto.Cipher import AES from base64 import * def xor(msg, key): ret = bytearray() for i in ran...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from default.models import ContentTemplates # Create your views here. def index(request): template_data = ContentTemplates.objects.get(template_name='index') return render(request, 'index.html', {'template_data':temp...
# Generated by Django 2.2.1 on 2019-05-17 23:54 from django.db import migrations import tinymce.models class Migration(migrations.Migration): dependencies = [ ('partners', '0002_partner_partner_logo'), ] operations = [ migrations.AddField( model_name='partner', n...
import unittest from katas.kyu_7.remove_duplicates import unique class UniqueTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(unique([]), []) def test_equals_2(self): self.assertEqual(unique([5, 2, 1, 3]), [5, 2, 1, 3]) def test_equals_3(self): self.assertEqu...
import Mumble_pb2, socket, ssl, struct, sys, select from datetime import datetime from threading import Thread class Mumbot: ca_file = 'mumble-ca.crt' payloads = { 0: Mumble_pb2.Version, 1: Mumble_pb2.UDPTunnel, 2: Mumble_pb2.Authenticate, 3: Mumble_pb2.Ping, 4: Mumble_pb2.Reject, 5: Mumble_pb2.ServerSyn...
"""ChanLun URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-ba...
'''server.py -- A simple tornado server 2014.May : Mendez ''' import os import sys import tornado.web import tornado.ioloop import weather import reddit from datetime import datetime HOSTNAME = 'localhost' PORT = 5555 # TODO: create a scheduler to run updates at specific times w = weather.Weather() w.update() r = r...
lines = [] for _ in range(100): try: line = input() lines.append(line) except EOFError: break [print(line) for line in lines]
# -*- coding: utf-8 -*- """asyncio unit tests with Django transactional support.""" # :copyright: (c) 2015 Alex Hayes and individual contributors, # All rights reserved. # :license: MIT License, see LICENSE for more details. from collections import namedtuple version_info_t = namedtuple( 'versi...
# -*- coding: utf-8 -*- from django.contrib.auth import login from django.shortcuts import redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from django.contrib.auth.decorators import user_passes_test from annoying.decorators import render_to from django.contrib.auth.models import...
import csv import spacy import pandas as pd from gensim.models import word2vec import os import csv import sys import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data import DataLoader import pickle TEST_X_PATH = sys.argv[1] test_data = pd...
data = "" elf_counter = {} with open("inputData.txt", "r") as infile: """ Process inputData.txt and put it into the data array. """ for line in infile: data = int(line) def get_factors(number): """ Note: Taken from Stack Overflow http://stackoverflow.com/a/6800214 :param numbe...
# -*- python -*- # Insertion Sort # # Build an algorithm for insertion sort. Please watch the video here to understand how insertion sort works and implement the code. The following gif also shows how insertion sort is done. # # Again, write the pseudo-code first and test your base cases before you build your code nex...
import os import re import sys import shutil import logging SPARK_VERSIONS_FILE_PATTERN = "spark-(.*)-bin-(?:hadoop)?(.*)" SPARK_VERSIONS_URL = "https://raw.githubusercontent.com/rstudio/spark-install/master/common/versions.json" WINUTILS_URL = "https://github.com/steveloughran/winutils/archive/master.zip" NL = os.li...
# 練習問題1 # from tkinter import * # # # def triangle(x, y, w, h): # canvas.create_line(x, y, x + w, y) # canvas.create_line(x + w, y, x, y + h) # canvas.create_line(x, y + h, x, y) # # # tk = Tk() # canvas = Canvas(tk, width=500, height=500) # canvas.pack() # triangle(100, 100, 200, 300) # canvas.mainloop() ...
# 3. Найти самое длинное слово в введенном предложении. # Учтите что в предложении есть знаки препинания. # Подсказки: my_string.split([chars]) возвращает список строк. # len(list) - количество элементов в списке # каждый проходи цикла сохраняес в c самое длинное слово, # без знаков препинания, если слово короче преды...
from random import randint, choice repeticiones = 10 informantes = 20 respuestas_min = 0 respuestas_max = 100 for n in range(0, repeticiones): for respuestas in range(respuestas_min, respuestas_max): caso = [] for x in range(0, respuestas): opinion = randint(1, informantes), randint(1,...
# Define a function def say_hello(): # block belonging to the function. print('Hello World') # End of function say_hello() # call the function say_hello() # call the function again # OUTPUT # python functions_basics.py # Hello World # Hello World
''' Created on Dec 3, 2015 @author: Benjamin Jakubowski (buj201) ''' import unittest import pandas as pd from get_and_clean_data import * from graph_grades_over_time import * from test_grades import * class Test(unittest.TestCase): def test_clean_Grade(self): bad_grades = pd.DataFrame.from_dict({1:{'GRAD...
#Import streamlit import streamlit as st #Import NumPy and Pandas for data manipulation import pandas as pd import numpy as np from fbprophet import Prophet from fbprophet.diagnostics import performance_metrics from fbprophet.diagnostics import cross_validation from fbprophet.plot import plot_cross_validation_...
from fitnessCalc import FitnessCalc from population import Population from algorithm import Algorithm from time import time start = time() FitnessCalc.set_solution("1111000000000000000000000000000000000000000000000000000000001111") my_pop = Population(50, True) generation_count = 0 while my_pop.fitness_of_the_fitt...
# -*- coding: utf-8 -*- class Queue(object): def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def enqueue(self,item): self.items.insert(0,item) def dequeue(self): return self.items.pop() def peek(self...
# Created by Elivelton S. from selenium import webdriver from selenium.webdriver.common.keys import Keys import argparse import os import sys import time parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-p', '--password') parser.add_argument('-t', '--tag') args = parser.par...
class Super: def method(self): print('in Super.method') class Sub(Super): def method(self): # Override method print('starting Sub.method') # Add actions here Super.method(self) # Run default action print('ending Sub.method') x = Super() x.method() y = Sub() y.method()
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-04-09 23:08:50 # @Author : Fallen (xdd043@qq.com) # @Link : https://github.com/fallencrasher/python-learning # @Version : $Id$ #判断对象是否是迭代器 with open('file1',encoding='utf-8',mode='w') as f1: print(('__iter__' in dir(f1)) and ('__next__' in dir(f1))) ...
import csv import os from typing import Any, Dict, Optional from parseridge.parser.evaluation.callbacks.base_eval_callback import EvalCallback class EvalCSVReporter(EvalCallback): _order = 10 def __init__(self, csv_path: Optional[str] = None): self.csv_path = csv_path if self.csv_path: ...
#import multiprocessing import socket import time from downloader import Downloader import asyncio import redis from beletag_callback import BeletagCallback from redis_cache import RedisCache SLEEP_TIME = 1 socket.setdefaulttimeout(60) class Beletag: def __init__(self): self.cb = BeletagCallback() ...
""" Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array. Example 1: Input: 3 / \ 9 20 / \ 15 7 Output: [3, 14.5, 11] Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11]. ...
import traceback import time import pdb GRID_SIZE = 15 WINNING_LENGTH = 5 X = 1 O = -1 def whoWonRow(row): streak = 0 for value in row: if streak >= 0 and value == 1: streak += 1 elif streak <= 0 and value == -1: streak -= 1 else: streak = value ...
# simulated_data.py import itertools import numpy as np import matplotlib.pyplot as plt from sklearn.cluster import KMeans if __name__ == "__main__": np.random.seed(1) # Set the number of samples, the means and # variances of each of the three simulated clusters samples = 100 mu = [(7, 5), (8,...
""" 4. Faça um Programa que peça as 4 notas bimestrais e mostre a média. """ nota1 = int(input("Digite a primeira nota do bimestre: ")) nota2 = int(input("Digite a segunda nota do bimestre: ")) nota3 = int(input("Digite a terceira nota do bimestre: ")) nota4 = int(input("Digite a quarta nota do bimestre: ")) media = ...
import os import hashlib from torrent_parser import flatten_list, rread_dir from constants import DEF_BLOCK_LENGTH, DEF_PIECE_LENGTH import math def pieces_gen(fpath, piece_length=DEF_PIECE_LENGTH): # Dividir multiples archivos en bloques/piezas pieces = [] pieces_hash = [] piece = b"" if os.path....
import sys import glob import argparse import re import os parser = argparse.ArgumentParser(description='Convert cachegrind to csv') parser.add_argument('--cap', default="0", type=int, help="exclude function calls below this threshold (microseconds)") parser.add_argument("--i", default=".", help="directory containing...
print("{:^80}".format("Python Shop")) print("{:<6}{:<30} ".format("NO.",": 1078718855")) print("{:<6}{:<30} ".format("Addr.",": 서울시 종로구 종로3가")) print("{:<6}{:<30} ".format("Name",": 김사장")) print("{:<6}{:<30} ".format("H.P",": 070-1234-5678")) print("{:-^80}".format("-")) print("{:^20}{:^20}{:^20}{:^20}".format("Items",...
# Generated by Django 3.2.7 on 2021-09-07 03:53 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('stock', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='category', options={'ordering': ['id']...
suku=int(input()) print(suku*(suku-1)//2)
from itertools import permutations M, N = list(map(int, input().split())) Result = [] for i in range(1, M + 1): Result.append(i) for i in list(permutations(Result, N)): for j in range(len(i)): print(i[j], end=' ') print()
import random import socket import string from sys import path path.append('liblsl-Python\\') from pylsl import StreamOutlet, StreamInfo tcpport = int(raw_input('TCP Port: ')) tcpaddress = raw_input('TCP Address (default: 127.0.0.1): ') or '127.0.0.1' # opening socket sock = socket.socket(sock...
class linknode: def __init__(self, key=None, value=None,next=None): self.key = key self.value = value; self.next = next; class lrucache: def __init__(self, capacity): self.head = linknode() self.tail = self.head self.capacity = capacity self.hash = {} ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Aug 14 21:59:46 2020 @author: thomas """ import numpy as np import pandas as pd import os, sys import time as t import subprocess from shutil import copyfile import pathlib #CONSTANTS cwd_PYTHON = os.getcwd() + '/' # constructs a filepath for the pos...
import unittest from katas.beta.sum_of_values_from_1_to_n_inclusive import total class SumFromOneToNTestCase(unittest.TestCase): def test_equal_1(self): self.assertEqual(total(10), 55) def test_equal_2(self): self.assertEqual(total(123), 7626) def test_equal_3(self): self.assert...
import argparse import numpy as np from algorithm import Surfing parser = argparse.ArgumentParser() parser.add_argument('dataset_path', help='Path to where the dataset is located') parser.add_argument('-d', '--delimiter', default=',', help='Change dataset parser delimiter definition') parser.add_argument('-s', '...
for x in xrange(1,10): print x for chx in 'ABC': print chx from collections import Iterable bool = isinstance('abc', Iterable) print bool for i, value in enumerate(['A', 'B', 'C']): print i, value for x, y in [(1,2), (2,4), (3,9)]: print x, y d = {'a':1, 'b':2, 'c':3} for k in d.keys(): print k for v in d.val...
import ujson as json from celery import shared_task from django.dispatch import receiver from django.db.models.signals import pre_save, post_save from annoying.functions import get_object_or_None from .signals import create_message from .models import Room, Notification, Message, MessageChart from speakifyit.users.mode...
#!/usr/bin/env python # https://github.com/anishathalye/dotbot/wiki/Tips-and-Tricks#uninstall-script import yaml import os import logging import glob logging.basicConfig() logging.getLogger().setLevel(logging.INFO) dotfile_groups = os.getenv("DOTFILE_GROUPS") groups = dotfile_groups.split(",") if dotfile_groups else...
import sys have_numpy = True try: import numpy except ImportError: have_numpy = False raise have_gdcm = True try: import gdcm except ImportError: have_gdcm = False raise can_use_gdcm = have_gdcm and have_numpy def supports_transfer_syntax(dicom_dataset): return True def get_pixeldata(di...
import matplotlib.pyplot as plt hfont = {'fontname' : 'Karla'} years = [1900, 1950, 1955, 1960, 1965, 1970, 1975, 1980, 1985, 1990, 1995, 2000, 2005, 2010, 2015] pops = [1.6, 2.5, 2.6, 3.0, 3.3, 3.6, 4.2, 4.4, 4.8, 5.3, 5.7, 6.1, 6.5, 6.9, 7.3] plt.plot(years, pops, color=(255/255, 100/255, 100/255), linewidth=6.0)...
#!/usr/bin/env python ROOT_DATA = "/home/conrad/Downloads/data/" # ---- DO NOT CHANGE BELOW THIS LINE ---- # import os import re from lxml import etree legit_path = re.compile("(?P<course_id>\d+)/User/(?P<username>[a-zA-Z0-9]+)/\d+") # ROOT/Forum/{{ course_id }}/User/{{ username }}/{{ readlist_file }} def list_rea...
from .budget.budget import Budget from .budget.budget_doc import BudgetDoc from .grant.grant import Grant from .grant.financing_agency import FinancingAgency from .grant.grant_domain import Grantdomain from .costcenter.costcenter import CostCenter from .project.project import Project from .project.expense_code import...
""" 25-Mile Marathon Mary wants to run a 25-mile marathon. When she attempts to sign up for the marathon, she notices the sign-up sheet doesn't directly state the marathon's length. Instead, the marathon's length is listed in small, different portions. Help Mary find out how long the marathon actually is. Return True...
from django.contrib import admin from .models import Question, Choice # Register your models here. class ChoiceAdmin(admin.ModelAdmin): list_display = ['__str__','choice','vote_count'] class Meta: model = Choice admin.site.register(Question) admin.site.register(Choice,ChoiceAdmin)
from flask import Blueprint, request, jsonify, current_app as app import uuid from werkzeug.security import generate_password_hash, check_password_hash import jwt import datetime from functools import wraps from emailer import send import random import math authentication_bp = Blueprint('authentication_bp', __name__) ...
# coding: utf-8 from __future__ import unicode_literals import os import platform from itertools import imap def get_A_B(x1, y1, x2, y2): if x1 == x2: return 'undf', 'undf' x1 = float(x1) x2 = float(x2) y1 = float(y1) y2 = float(y2) if not x1: b = y1 a = (y2-b)/x2 ...
#cd d:05learn/python_learn/selflearning # print(r) # print(1 == 2) # print(1==2) # print(1!=2) # print("a" in "basic") #import random #r = random.randrange(1,10000) #if r%2 == 0: # print(r,'is even.') #else: # print(r,'is odd.') #for i in range(10): # if i%2 !=0: # print(i) #for n in range(2,100): # if n == 2: # pr...
# Verifizierung der Zertifikate... openssl verify -CAfile rootcrt.pem servercrt.pem from cryptography.hazmat.primitives import serialization from ..Config import Config from pathlib import Path from flask import current_app from cryptography.x509.base import rsa, Certificate class FileSystemProvider(): ...
""" Project functionality. """ from ace import config from ace import client import json import sys def dump_project(args): """ Dumps the project to standard out. """ if not config.get_active_project(args): raise ValueError('Must specify project.') project_resource = client.get_resou...
import _thread import pickle import socket from game import Game server = "192.168.0.102" # Local IP address of the server port = 5555 # Port to listen # Instantiate server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Setup server try: s.bind((server, port)) except socket.error as ...
# linux: curl https://raw.githubusercontent.com/CrazyVideoGamer/auto-backup/main/get_auto_backup.py | python3 <-- not yet tested # windows cmd: curl https://raw.githubusercontent.com/CrazyVideoGamer/auto-backup/main/get_auto_backup.py | python <-- not yet tested from pathlib import Path import argparse import sy...
class Event: def __init__(self, eventName, eventDate, eventDesc, eventWeb, eventCategory, eventFood): self.eventName = eventName self.eventDate = eventDate self.eventDesc = eventDesc self.eventWeb = eventWeb self.eventCategory = eventCategory self.eventFood = eventFoo...
import A A.txt_line("D://hello.txt","D://hello2.txt")
# -*- coding: utf-8 -*- """ Created on Thu Jun 7 20:15:16 2018 @author: user 質數 """ def compute(x): i=2 while i < x: if (x%i)==0: return False i+=1 return True x=int(input()) if x <= 1: print("Not Prime") elif x == 2: print("Prime") else: r=compute(x) i...
#!/usr/bin/env python import unittest from main.activity.activity_login import * from main.activity.activity_logout import * from main.activity.activity_myshop_editor import * from main.lib.user_data import * from main.function.setup import * class Test_add_etalase(unittest.TestCase): _site = "live" def s...
#!/usr/bin/python import numpy as np import pandas as pd import random import sys import csv def create_data(self): data_frame = pd.read_csv(sys.argv[1]) #sluzi na vygenerovanie testovacieho datasetu o velkosti 250 zaznamov, zaznamy #zmaze z povodneho suboru,vo vysledku ostane dataset o velkosti 1315 zaznamov #na...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'IpTracker.ui' # # Created by: PyQt5 UI code generator 5.13.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): Main...
from enum import Enum, IntEnum from typing import Dict, List from spectree import BaseFile, ExternalDocs, SecurityScheme, SecuritySchemeData, Tag from spectree._pydantic import BaseModel, Field, root_validator from spectree.utils import hash_module_path api_tag = Tag( name="API", description="🐱", externalDocs=Ex...
def findNumbers(num): if(num%5==0): return None f = num*5 for i in range(f,f+5): print(i) num = 2 findNumbers(24)
from django.http import HttpResponse from django.shortcuts import render from .models import Animal, AnimalPhoto, Seviye def home(request): return HttpResponse(render(request, 'giris.html')) def oyun(request): seviyes = Seviye.objects.all() animals = Animal.objects.all() animalPh = AnimalPhoto.objec...
import numpy as np import warnings class CorrectionWarning(Warning): """ Warning type used when something fishy is detected in our correction steps to use: >>> import warnings >>> warnings.warn('message', category=CorrectionWarning) By default, only one identical warning will be shown originati...
from bs4 import BeautifulSoup import urllib2 import csv import random import time import os ## setting working directory ------------------------------------------------ os.chdir("C:/Users/wooki/Documents/GitHub/pythoncourse2018/homeworks/hw2") with open('hw2_lim.csv', 'wb') as f: w = csv.DictWriter(f, fieldname...
""" This program includes methods used to simulate basic battle simulations for the game StarCraft II """ import random from sim_units import get_Units Units = get_Units() def combat_sim(army_comp1, army_comp2, MAX_ROUNDS=200): """ Army 1 is enemy, Army 2 is test Input two army compositi...
''' imputationflask.views ------------------- Define routes render by flask ''' # external imports from flask import render_template, request, current_app, Blueprint from werkzeug.exceptions import HTTPException from matplotlib import cm import json frontend = Blueprint('frontend', __name__) def make_graph_data(pr...
import sys #http://www.scipy.org/ try: from numpy import dot from numpy.linalg import norm except: print "Error: Requires numpy from http://www.scipy.org/. Have you installed scipy?" sys.exit() def removeDuplicates(list): """ remove duplicates from a list """ return set((item for item in list)) def cosine(ve...
from django.shortcuts import render from django.core import serializers from features.models import Feature from tickets.models import Ticket from features.forms import featureForm from cart.views import add_to_cart from django.utils import timezone from django.http import JsonResponse import json # Create your view...
#!/usr/bin/python3 if __name__ == "__main__": import sys sum = 0 count = len(sys.argv) for nums in range(1, count): sum = sum + int(sys.argv[nums]) print("{}".format(sum))
import os from datetime import datetime import pandas # python3 -m pip install pandas import progressbar # python3 -m pip install progressbar2 import DiffMon class DiffMonTest: def __init__(self, outputDir, diffDataset, diffDatasetPath, chkptSize, maxDiffDrop, maxWaitTime, waitTimeEnable, rest...
import datetime ano = datetime.date.today().year r = input ('A confederação do brazil precisa de um atleta \n para você se cadastrar primeiro digite seu nome : ') r1 = int (input ('Agora digite seu ano de nascimento: ')) r4 = r.upper() r2 = ano - r1 # saber a idade do mesmo. if r2 <= 9 : print ('MIRIN'...
from django import forms from .models import song, album, vocalist, hashtag, language, mood import django_filters class addSong(forms.ModelForm): class Meta: model = song exclude = ['isDeleted'] class updateSong(forms.ModelForm): class Meta: model = song fields = ['title'] ...
import os import json class DecryptorOptions(): def __init__(self): configurationOptions = self.configurationOptions() self.decryptorApplicationPath = configurationOptions['decryptorApplicationPath'] self.decryptorSlots = int(configurationOptions['decryptorSlots']) def allKeys(self): return ['decryptorAppli...
# pylint: disable=E1101 """This module sends requests to a Borda server in order to create an election, register candidates and voters, and issue votes on behalf of the voters.""" import argparse import json import sys import logging import requests def resource(path): """Append a path to an entrypoint to form a...
#-*- encoding:utf-8 -*- from hello import Major,db f= open('major.txt', 'rt',encoding="utf-8") for x in f: db.session.add(Major(mname=x[:-1])) db.session.commit() f.close()
# variables 了解变量 import keyword print(keyword.kwlist) keyWord = input("pls input a string:") flag = keyword.iskeyword(keyWord) if flag: print("true") else : print("false")
# Using text2 from the nltk book corpa, create your own version of the # MadLib program. # Requirements: # 1) Only use the first 150 tokens # 2) Pick 5 parts of speech to prompt for, including nouns # 3) Replace nouns 15% of the time, everything else 10% ## # Deliverables: # 1) Print the orginal text (150 tokens) # ...
from django.urls import path from . import views from .engine.hier_deploy import views as hier_deploy_views app_name = 'inventory' urlpatterns = [ path('v1', views.InventoryListView.as_view(), name='inventory_list'), path('v1/inventory-create', hier_deploy_views.InventoryCreateView.a...
# tboz203 # 2015-05-12 # reyna_tests/models.py from decimal import Decimal from django.db import models class Test(models.Model): ''' A collection of questions ''' name = models.CharField(max_length=64) def __str__(self): return self.name class Meta: ordering = ('name',) ...
""" Given the triangle of consecutive odd numbers: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 ... Calculate the row sums of this triangle from the row index (starting at index 1) e.g.: row_sum_odd_numbers(1); # 1 row_sum_odd_numbers(2); # 3 + 5 = 8 """ ...
""" Minutiae Extractor to get Minutia from files (fingerprint templates) """ from Minutia import MinutiaNBIS class MinutiaeExtractor: NBIS_FORMAT = 1 def __init__(self, extractor_format=NBIS_FORMAT): self.extractor_type = extractor_format def extract_minutiae_from_xyt(self, file_path): ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri May 3 00:36:08 2019 @author: leiyuan """ #colors reference guide #https://matplotlib.org/api/colors_api.html ''' https://matplotlib.org/examples/color/colormaps_reference.html Sequential: These colormaps are approximately monochromatic colorma...
import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import tensorflow as tf import argparse if __name__ == "__main__": parser = argparse.ArgumentParser('Plot Evaluation') parser.add_argument('--patterns', type=str, nargs...