text
stringlengths
38
1.54M
from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.debug = True app.config.from_object('config') db = SQLAlchemy(app) #if not app.debug: # import logging # from logging.handlers import RotatingFileHandler # error = RotatingFileHandler('tmp/error.log', 'a', 1 * 1024 ...
#!/usr/bin/env python3 """ Python typing annotations """ from typing import Sequence, Union, Any, TypeVar, Mapping T = TypeVar('T', bound=Any) def safely_get_value(dct: Mapping, key: Any, default: Union[T, None] = None) -> Union[Any, T]: """ Generics """ if key in...
class SwaggerDocumentationError(Exception): """ Custom exception raised when package tests fail. """ pass class CaseError(Exception): """ Custom exception raised when items are not cased correctly. """ pass class OpenAPISchemaError(Exception): """ Custom exception raised fo...
import numpy as np import glob import pandas as pd import os import time from tqdm.auto import tqdm from .misc import dfMirror ######################################################################################################################## # it's best to use asciiToDfMulti() (which exploits this asciiToDf())...
from datetime import datetime import os #reinvertimos la fecha def inv_fecha(fech): fechn = datetime.strptime(fech,'%d/%m/%Y') return datetime.strftime(fechn,'%Y-%m-%d') #se hace el calculo del Bono1 y Bono2 def pagar(basesueldo,h,v1,v2): if int(h) <= 5: SuelNu= float(basesueldo) + float(b...
import sys import numpy as np import cv2 import qnn_utils from enum import Enum from termcolor import colored, cprint np.set_printoptions(threshold=sys.maxsize) NUMBER_LINE = 'โ”œโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”ค' # Option use_ReLU = True class Inference(Enum): FP32 = 1 INT8 =...
from googlesearch import search from threading import Thread from bs4 import BeautifulSoup from clint.textui import progress import urllib2 import requests import sys import os import time import itertools flag = 0 def progess(): global flag sys.stdout.write("Searching...") for c in itertools.cycle('/-\...
import sys from PyQt5.QtWidgets import QApplication,QMainWindow from handn import * class HanyuForm(QMainWindow,Ui_MainWindow): def __init__(self,parent = None): super(HanyuForm,self).__init__(parent) self.setupUi(self) if __name__ == '__main__': QtCore.QCoreApplication.setAttribute(...
# -*- coding: utf-8 -*- # @PRODUCTION MODULE __author__ = "radek.augustyn@email.cz" import time import psycopg2 import pygeotoolbox.sharedtools.log as log import pygeotoolbox.sharedtools.config as config from pygeotoolbox.sharedtools import setParameters, Container from base import DatabaseTemplate config.registe...
from __future__ import unicode_literals from django.db import models from django.contrib import admin # Create your models here. class Description(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=100) def __unicode__(self): return self.name class Education(models.M...
from PIL import Image import matplotlib.pyplot as plt import numpy as np import os path = "/home/feng/darknet/data/cele_A/ac/img_celeba/" #ๆ–‡ไปถๅคน็›ฎๅฝ• files= os.listdir(path) #ๅพ—ๅˆฐๆ–‡ไปถๅคนไธ‹็š„ๆ‰€ๆœ‰ๆ–‡ไปถๅ็งฐ s = [[],[],[]] count = 0 for file in files: s[0].append(file) img=Image.open(path + file) s[1].append(img.size[0]) s[...
from dec_tree import * from pre_processor import * import sys # Names of the two datasets we are using bank_attr_names = ['age', 'job', 'marital', 'education', 'default', 'balance', 'housing', 'loan', 'contact', 'day', 'month', 'duration', 'campaign', 'pdays', 'previous', 'poutcome', 'y'] car...
# import funkcji z innego moduล‚u from Zadanie7ocenyfun import drukuj, srednia, mediana, odchylenie przedmioty = set() #definicja pustego zbioru oceny = [] #definicja pustej listy ocen drukuj(przedmioty, "Lista przedmiotรณw: ") #wprowadzanie przedmiotรณw przez uzytkownika print("\nWciล›niฤ™cie Enter powoduje przerwanie wp...
# -*- coding:utf-8 -*- """ OKEx Future Trade module. https://www.okex.me/docs/zh/ NOTE: Only Cross Margin Mode is supported in Trade module currently. Please change Margin Mode to `Cross`, not `Fixed`! Author: HuangTao Date: 2019/01/19 Email: huangtao@ifclover.com """ import time import zlib import json import c...
# allows to import own functions import sys import os import re root_project = re.findall(r'(^\S*TFM)', os.getcwd())[0] sys.path.append(root_project) from src.utils.help_func import results_searchcv,plot_predictions,\ errors_distribution, plot_visualizations, get_model_data from sklearn.model_selection import Grid...
import FileUtil import FeatureExtractor import math ################## Notes ##################### # What is tq_0, t_q, and t_i? # How do you obtan the desired output vectors? ############################################## sigma = 3.5 #d_max numOfFeatureVectors = 0 def getAverageVector(author): x = [] artic...
from PIL import Image import numpy as np import scipy.misc """ AUTHOR: Himanshu Sharma TITLE: Bit Plane Generator ========================== """ def generateGray(bit): ''' Returns white or black value depending on the bit plane. ''' bit = str(bit) if bit == '1': ...
import numpy as np def gen(): vals = [100, 50, 30, 20] results = [1, 5, 3, 2] x_train = [] y_train = [] cnt = 0 for val in vals: for addval in vals: x_set = [] y_set = [] x_set.append(val) x_set.append(val) x_set.append(addval...
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Function import numpy as np import soft_renderer.cuda.standard_rasterize as standard_rasterize_cuda def standard_rasterize(face_vertices, image_size=256): if face_vertices.device == "cpu": raise TypeError('Raster...
from ipaddress import ip_network from random import choice def genv6(n): print('generating {} addresses...'.format(n)) current_net = ip_network('1234:1234::/30') i = 0 output = [] for net in current_net.subnets(new_prefix=56): if choice(range(30)) > 10: output.append(net) ...
## Heap Sort def heapsort(alist): # Convert the list into heap: # each node is lower than each of its parent i.e max-heap # the tree is pertectly balanced # all leaves are in the leftmost position available. length = len(alist) - 1 leastParent = length / 2 for i in range(leastParent, -1, -1): moveDown(alist...
from __future__ import generators import config.package class Configure(config.package.Package): def __init__(self, framework): config.package.Package.__init__(self, framework) self.includes = ['cusp/version.h'] self.includedir = ['','include'] self.forceLanguage = 'CUDA' self.cxx ...
# ๆ–‡ๆœฌ้ขœ่‰ฒ่ฎพ็ฝฎ print('\033[1;31m') print('*'*10) print('hello world๏ผ') print('*'*10) print('\033[0m') # ็ปฟ่‰ฒๅญ—ไฝ“ print('\033[1;32m'+'green'+'\033[0m') # ่“่‰ฒๅญ—ไฝ“ print('\033[1;34m'+'blue'+'\033[0m') # ้ป„ๅญ—ไธ‹ๅˆ’็บฟ print('\033[4;33m'+'yellow'+'\033[0m') # ็บขๅบ•้ป‘ๅญ— print('\033[1;30;41m'+'black'+'\033[0m') # ็™ฝๅบ•้ป‘ๅญ— print('\033[1;30;47m'+'white...
from django.shortcuts import render from django.template import Context, loader, Template from django.http import HttpResponse from backend import collect from analyse import analyse,build_markers from .models import * import threading,time from django.db import connection cursor = connection.cursor() class collectTh...
# https://hwwong168.wordpress.com/2019/09/25/esp32-micropython-implementation-of-cryptographic/ import uos from ucryptolib import aes, MODE_CBC g_iv1 = b"1234567812345678" g_iv2 = bytes("1234567812345678", "utf8") def p_example1_hard_coded1(key, data): cipher = aes(key, MODE_CBC, b"1234567812345678") cipher_...
import csv def prob_dist(int1, int2, n): #int1 is a pair or list [a1, b1] of integers #int2 is a pair or list [a2, b2] of integers #n is the resolution #we calculate the probability that randomly #chosen numbers from int1 and int2 are at least #distance n apart. a1 = int1[0] a2 = int2[...
S=[] print("Welcome to the bubble sort algorithm") i=1 while i<8: num=input("Please enter a number:") if num!=int: print("Invalid entry try again.") break else: S.append(num) i=i+1 N=len(S) swapped=True while swapped==True: swapped=False for x in rang...
#!/usr/bin/python3 import subprocess import sys CLIENTS_PROP = "clientsnode" SERVERS_PROP = "serversnode" def run_with_log_and_exit(cmd): print(f"RUNNING | {cmd}") ret = subprocess.run(cmd, shell=True) if ret.returncode != 0: print(f"{cmd} returned {ret.returncode}") exit(ret.returncode) ...
''' ่ฃ…้ฅฐๅ™จ ็”ฑไบŽๅ‡ฝๆ•ฐไนŸๆ˜ฏไธ€ไธชๅฏน่ฑก๏ผŒ่€Œไธ”ๅ‡ฝๆ•ฐๅฏน่ฑกๅฏไปฅ่ขซ่ต‹ๅ€ผ็ป™ๅ˜้‡๏ผŒๆ‰€ไปฅ๏ผŒ้€š่ฟ‡ๅ˜้‡ไนŸ่ƒฝ่ฐƒ็”จ่ฏฅๅ‡ฝๆ•ฐใ€‚ ๅ‡ฝๆ•ฐๅฏน่ฑกๆœ‰ไธ€ไธช__name__ๅฑžๆ€ง๏ผŒๅฏไปฅๆ‹ฟๅˆฐๅ‡ฝๆ•ฐ็š„ๅๅญ—๏ผš ็Žฐๅœจ๏ผŒๅ‡่ฎพๆˆ‘ไปฌ่ฆๅขžๅผบnow()ๅ‡ฝๆ•ฐ็š„ๅŠŸ่ƒฝ๏ผŒๆฏ”ๅฆ‚๏ผŒๅœจๅ‡ฝๆ•ฐ่ฐƒ็”จๅ‰ๅŽ่‡ชๅŠจๆ‰“ๅฐๆ—ฅๅฟ—๏ผŒไฝ†ๅˆไธๅธŒๆœ›ไฟฎๆ”นnow()ๅ‡ฝๆ•ฐ็š„ๅฎšไน‰๏ผŒ่ฟ™็งๅœจไปฃ็ ่ฟ่กŒๆœŸ้—ดๅŠจๆ€ๅขžๅŠ ๅŠŸ่ƒฝ็š„ๆ–นๅผ๏ผŒ็งฐไน‹ไธบโ€œ่ฃ…้ฅฐๅ™จโ€๏ผˆDecorator๏ผ‰ใ€‚ ๆœฌ่ดจไธŠ๏ผŒdecoratorๅฐฑๆ˜ฏไธ€ไธช่ฟ”ๅ›žๅ‡ฝๆ•ฐ็š„้ซ˜้˜ถๅ‡ฝๆ•ฐใ€‚ๆ‰€ไปฅ๏ผŒๆˆ‘ไปฌ่ฆๅฎšไน‰ไธ€ไธช่ƒฝๆ‰“ๅฐๆ—ฅๅฟ—็š„decorator๏ผŒๅฏไปฅๅฎšไน‰ๅฆ‚ไธ‹๏ผš ''' def log(func): def wrapper(*args, **kw): print(...
# Generated by Django 3.1 on 2020-11-28 20:20 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('classrooms', '0002_classroom_creator'), ('users', '0004_auto_20201128_1628'), ] operations = [ migrations.RemoveField( mod...
import numpy as np from .Base_Automaton import Base_Automaton class F3_Fly(object): def __init__(self, garden, id_no, gender, orientation): self.G = garden # the F3_Garden object self.id_no = id_no # a reference number to identify this fly self.gender ...
import torch.nn as nn import torch.utils.model_zoo as model_zoo from CA import CoordAtt model_urls = { 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth', 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth', 'resnet50': 'https://download.pytorch.org/models/resnet50-...
import re from typing import List, Union, Optional, Generator, TypeVar, Iterable, Iterator from . import LineInterface, Comment as oldComment, LineError, NoOptionError, UnitBase class NoSectionError(Exception): """ะ˜ัะบะปัŽั‡ะตะฝะธะต, ะฒะพะทะฝะธะบะฐัŽั‰ะตะต ะฟั€ะธ ะพั‚ััƒั‚ัั‚ะฒัƒัŽั‰ะตะน ัะตะบั†ะธะธ.""" def __init__(self, section: str): ...
#!/usr/bin/env python """ This is a basic example of how to use the swiftradio library to fetch radio telemetry information from a SWIFT-SDR and print the information to the console. The SwiftRadioClient class is used to connect to a Swift-SDR unit, execute the 'sysstat' command and then process and print the received ...
# -*- coding: utf-8 -*- # snapshottest: v1 - https://goo.gl/zC4yUc from __future__ import unicode_literals from snapshottest import Snapshot snapshots = Snapshot() snapshots['test_BatchCompiler_1 1'] = { 'b/c/base': '''head: base - head body: base - body ''', 'b/f2': '''f2 -- BBB There out her child sir...
from cascade.input_data.configuration.form import Configuration from flask import Blueprint, abort, jsonify, request bp = Blueprint("service", __name__) @bp.route("/", methods=("POST",)) def validate(): if not request.is_json: abort(406) raw_settings = request.get_json() settings = Configuration(...
# 5. Lambda Functions - Anonymous function # simple function def func(x): return x + 5 # lambda inside function def func3(x): func4 = lambda x: x + 10 return func4(20) func2 = lambda x: x + 5 # simple lambda func5 = lambda x, y: x + y # lambda with 2 variables func6 = lambda x, y=5: x * y # lambda w...
''' @author: Necro ''' import tensorflow as tf import numpy as np xdata = np.random.rand(100).astype(np.float32) ydata=0.3*xdata+0.1 weight=tf.Variable([0.]) bias=tf.Variable([0.]) y=weight*xdata+bias #loss=tf.reduce_mean(tf.square(y-ydata)) loss=tf.losses.mean_squared_error(y, ydata) # optimizer=tf.train.GradientD...
from django.conf.urls import url from . import views urlpatterns = [ #login START url(r'^$', views.index), url(r'^home$', views.home), url(r'^login$', views.login), url(r'^create$', views.create), url(r'^success$', views.success), url(r'^logout$', views.logout), #login END url(r'^ad...
#!/usr/bin/env python3 # # # +type xyc # # - x are strings correspondig to centers of the violins (as if individual bars in a barplot) # # - y is the y-axis placement # # - c is [0-1] value indicating the shade # cat xyc.txt | mplot sina +type xyc # snv 10 0.5 # snv 100 1 # sn...
import utils as u import QUtils as qu import numpy as np import multiprocessing as mp import scipy.fftpack as sp import time import matplotlib.pyplot as plt import pickle from numpy import linalg as LA import scipy.stats as st import sys import yt; yt.enable_parallelism() import sys simName = "Gr_r2" decimate = 2...
count = 0 maxcount = 0 def prime(n): if n % 2 == 0 and n > 2: return False for i in range(3, int(n/2 + 1), 2): if n % i == 0: return False return True def getFactor(n,factors): i = 2 while i * i <= n: if n % i: i += 1 else: n //=...
def isPalindrome(s): """ :type s: str :rtype: bool """ abc = 'asdfghjklqwertyuiopzxcvbnm' t='' t=t+x for x in s.lower() if x in abc return t[::-1] == t st="A man, a plan, a canal: Panama" print(isPalindrome(st))
from rest_framework import serializers from computerapp.models import Product,Manufacturer,Category,UserProfile,DeliveryAddress,Order from django.contrib.auth.models import User class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('id','user','mobile_phone','n...
from django.shortcuts import render from first_app import models,forms #from django.http import HttpResponse # Create your views here. word="" wordscount={} def home(request): #return HttpResponse("hello") return render(request,"html/home.html") def wordcounthome(request): #return HttpResponse("hello") return rende...
from django.shortcuts import render from .models import Pixel from django.db import models def home(request): pixels = Pixel.objects.all() context = { 'pixels':pixels } return render(request, 'pixels/home.html', context) def search_results(request): if 'pixel' in request.GET and request....
from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker SQLALCHEMY_DATABASE_URI = "sqlite:///./DB.db" engine = create_engine(SQLALCHEMY_DATABASE_URI) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) Base = declara...
f = open('/home/sezim/zadachi/rabota_s_files/users.txt', 'w') name = input("Vedite login: ") password = input("Vvedite password: ") f.write(f"login: {name} \nPassword: {password}") f.close()
# -*- coding: utf-8 -*- """ Created on Thu Apr 3 18:49:26 2014 @author: anneubuntu """ # -*- coding: utf-8 -*- """ Created on Wed Apr 2 00:32:11 2014 @author: anneubuntu """ import pygame import math from pygame.locals import * import random import time from abc import ABCMeta, abstractmethod import planes from p...
# Generated by Django 3.0.3 on 2020-04-14 09:01 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('competition_calendar', '0001_initial'), ] operations = [ migrations.AlterField( model_name='distance', name='distanc...
from abc import ABC, abstractmethod from data.field import Field import numpy as np class Predictor(ABC): @abstractmethod def train(self, features: [Field], responses: [Field], **kwargs): pass @abstractmethod def predict(self, features: [Field]) -> np.array: pass @abstractmethod...
from ga_init import * maxgen = 5 npool = 5 pmut = 0.15 ncross = 2 t1 = initialize_GA_calc(npool,ncross,pmut,maxgen)
# -*- coding: utf-8 -*- """ Created on Wed May 10 10:52:00 2017 @author: kkonudul """ from random import randint, random import matplotlib.pyplot as plt def individual(length, min, max): return [randint(min, max) for x in range(length)] #individual(5, 0,100) def population(count, length, min, max): # Creat...
from django import forms class FilterForm(forms.Form): filter = forms.ChoiceField(choices=[(1, "True pairs"), (0, "Not pairs"), (-1, "No Filter")], widget=forms.RadioSelect( attrs={'onchange': 'form.submit()', ...
# ClearML - Fastai example code, automatic logging the model and scalars # import argparse from clearml import Task import fastai try: from fastai.vision import untar_data, URLs, ImageDataBunch, rand_pad, imagenet_stats, cnn_learner, models, accuracy except ImportError: raise ImportError("FastAI version %s i...
''' Script to get events information from CATALOG obspy (https://docs.obspy.org/packages/autogen/obspy.clients.fdsn.client.Client.get_events.html) ''' import numpy as np from obspy import UTCDateTime import os import json from obspy import read_events from obspy.clients.fdsn import Client from parameters_py.config im...
import cv2 import sys import os import sys sys.path.insert(0, 'Yolo') from yolo import use_yolo path = "Annotator/Videos/" # set path for video directory selection = [] def check_file(vid, class_name): try: with open(path+class_name+"_log.txt", "r") as f: for line in f: li...
@cherrypy.expose def connect(self): return """<html> <head><title>Connect Server</title></head> <body> <form method="get" action="connecting"> server:<br> <input type="text" name="_server"><br> port:<br> <input type="text" name="_port"><br> <...
import pygame from pygame.locals import (K_DOWN, K_LEFT, K_RIGHT, K_UP) class Player(pygame.sprite.Sprite): def __init__(self, x: int, y: int, width: int, height: int, color: (int, int, int), vel: int = 3): super(Player, ...
# Code for beta-VAE # Paper: https://openreview.net/forum?id=Sy2fzU9gl from abc import ABC import torch from torch import Tensor from torch import nn from torch.nn import functional as F from . import ConvNet, GaussianLayer, GenerativeAE, UpsampledConvNet, FCBlock, DittadiConvNet, DittadiUpsampledConv from .utils imp...
class words_filter(): def __init__(self, str1): self.lis3 = "" for i in str1: if i != '\n' and i != '\t': self.lis3 = self.lis3 + i else: pass def output(self): return self.lis3
"""Path utilities based on :mod:`posixpath`. :func:`normpath` has been modified not to allow relative paths. :mod:`posixpath` is part of the Python standard library, and is licensed under the `Python Software Foundation License <http://docs.python.org/license.html>`_, which can be linked with libraries of other licen...
''' CS370 Assignment 8 Solves ProjectEuler #82 Taylor He, Jacob Manzelmann, Tommy Osterman I pledge my honor that I have abided by the Stevens Honor System ''' import sys def backtrack(matrix, dp_matrix, row): '''Backtracks the matrix, starting at the given row''' col = len(matrix) - 1 path = [] while ...
from django.db import models from django.utils.timezone import now # Create your models here. class Template(models.Model): docfile = models.FileField(upload_to='templateuri/%Y/%m/%d/') filename = models.CharField(max_length=100, null=True, blank=True) created_on = models.DateTimeField(blank=False, defa...
class WrongDocumentUpdateStrategy(Exception): pass class DocumentNotFound(Exception): pass class DocumentAlreadyCreated(Exception): pass class DocumentWasNotSaved(Exception): pass
import xml.etree.cElementTree as ET import codecs import pprint import json import re import audit #local *.py file import os #Set the proper current working directory os.getcwd() os.chdir('C:/Users/sheethal/Desktop/DWMDB') lower = re.compile(r'^([a-z]|_)*$') lower_colon = re.compile(r'^([a-z]|_)*:([a-z]...
from gym.envs.registration import register register( id='{{cookiecutter.env_name}}-v0', entry_point='gym_{{cookiecutter.env_name.lower()}}.envs:{{cookiecutter.env_name}}Env', )
#! /usr/bin/python import naive_bayes_EM import os,sys,getopt,random,csv import numpy as np from data_utilities import countData,readData,random_gen DATAPATH="/home/wei/data_processing/data/car/car.data" DATAPATHS=['data/car/car.unacc.data','data/car/car.acc.data','data/car/car.good.data','data/car/car.vgood.data']...
import mlconf nested = {'a':{'c': 1, 'd': (2, {'a': 3}), 'e': {'f': 3, 'g': 4}}, 'b': 5} flat = {'a.c': 1, 'a.d': (2, {'a': 3}), 'a.e.f': 3, 'a.e.g': 4, 'b': 5} def test_to_flat_dict(): f = mlconf.to_flat_dict(nested) assert(f == flat) def test_to_flat_on_flat(): f = mlconf.to_flat_dict(flat) asser...
# -*- coding: utf-8 -*- """ ------------------------------------------------- File Name๏ผš bullet Description : Author : zhengbin date๏ผš 2019/11/11 ------------------------------------------------- Change Activity: 2019/11/11: -------------------------------------------...
import copy import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches class Simulator: def __init__(self, world_map, robots): """ Inputs: map_gt: The map to be explored robot: the Robot object from RobotClass.py """ self.map = copy.deep...
print("Substraction of two integers!!!\n") x = int(input("Please enter the first number: ")) y = int(input("please enter the second number: ")) z = x-y print("Substraction is: ",z)
# coding=utf-8 """ @author: mirrorChen @license: (C) Copyright 2011-2018, mirror personal Limited. @contact: chenjingxu3@dafycredit.com @software: JY_Android_AT @file: add.py @time: 2019/6/26 19:34 @desc: """ import time, datetime import pymysql.cursors import random from excel_pub import ExcelUtil mysql_info = {"ho...
import numpy as np # constants for strategies SELL = 0 BUY = 1 # annual average market return (expected) RISK_FREE_RATE = 0.07 #################################### # Strategies # #################################### # Contract: # each strategy function must produce a # tuple of buys and sells ...
from rest_framework import serializers from sale.models import Sale, SaleProduct from user.models import User class SaleSerializer(serializers.ModelSerializer): class Meta: model = Sale fields = '__all__' class SaleProductSerializer(serializers.ModelSerializer): class Meta: model = ...
#------------------------------------------------------------------------------- # Name: hangman # Purpose: # # Author: D.Kiselevsky # # Created: 26.05.2020 # Copyright: (c) D.Kiselevsky 2020 # Licence: GPL #------------------------------------------------------------------------------- def main(...
import json import os import numpy from datetime import datetime from shutil import rmtree import keras import keras_applications keras_applications.set_keras_submodules( backend=keras.backend, engine=keras.engine, layers=keras.layers, models=keras.models, utils=keras.utils) from keras_applicatio...
import logging import re import ipaddress import datetime import broker import broker.bro from select import select from enum import Enum, unique logger = logging.getLogger(__name__) def convertRecord(name, m): if not isinstance(m, list): logger.error("Got non record element") rec = m elements =...
import pygame import sys from settings import Settings from board import Board class ChessGame: def __init__(self): pygame.init() self.settings = Settings() self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height)) pygame.display.set_caption...
from HTTPServer.httpserver import * from HTTPServer.httpserver_thread import * from SA.Tree import * if __name__ == '__main__': # Iniciando o diretorio raiz e o conteudo do arquivo snake = Tree('snake', 'rarararororoelatemehumaso') # Iniciando o server no localhost na porta 8888 # se quiser outra port...
import re import os import json import socket from subprocess import Popen, PIPE, check_output, CalledProcessError import base64 HOST, PORT = '', 8080 #https://docs.python.org/fr/3/howto/sockets.html #INET:IPV4, STREAM:TCP #By default, sockets are always created in blocking mode listen_socket = socket.socket(socket.A...
from scipy import stats from sklearn.feature_extraction.text import CountVectorizer import numpy as np import pickle import os import random from matplotlib import pyplot as plt from sklearn.feature_extraction.text import TfidfTransformer from sklearn.svm import SVC, LinearSVC from sklearn.feature_extraction.text impor...
--- setup.py Mon Oct 4 05:39:34 2004 +++ setup.py.new Tue Oct 5 09:22:31 2004 @@ -29,7 +29,7 @@ ], packages = ['cfgparse'], data_files = [ - ('share/doc/cfgparse-%s' % VERSION, ['README', 'LICENSE-PSF', + ('share/doc/py-cfgparse', ['README', 'LICENSE-PSF', ...
from django.http import HttpResponse from django.shortcuts import redirect,render from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from techquiz.models import user from django.contrib import auth from django.template.context_processors import csrf from django.views import gen...
__author__ = 'Bill' class Board: """ Class for the Connect 5 Game Board. The Board is always a 7 long by 9 high. A board always remembers the last move made. """ # Class Constants BLANK_SPACE = "_" # Blank Space PLAYER_ONE = "R" # Red Chip PLAYER_TWO = "B" # Black Chip BOARD_HE...
import json import os import asyncio import discord from discord import Permissions from discord.ext import commands from datetime import datetime import utils import io from utils.Utility import clean_code, Pag import contextlib from traceback import format_exception import ast import importlib import te...
from pandas import DataFrame from typing import Callable, List from snapshottest.pytest import PyTestSnapshotTest from tests.model.lib import helper_descriptive_stats_groupby, helper_filesnapshot, helper_descriptive_stats from saitama_data.datasetup.models.info import ClassIdSchoolId, City, SchoolQestionInfo from saita...
def recursive_x(x, caminho): if caminho > x: pass else: print(caminho) caminho += 2 recursive_x(x, caminho) def main(): x = int(input()) recursive_x(x, 1) main()
from random import randint from time import sleep n = int(input('Digite um valor entre [1 e 5]: ')) s = randint(1, 5) print('Processando!') sleep(3) if n >= 1 and n <= 5: if n == s: print('Parabens! Nยบ Sorteado {} / Nยบ Escolhido {}'.format(s, n)) else: print('Infelizmente nรฃo deu! Nยบ Sorteado...
#!/usr/bin/env python __coding__ = "utf-8" __author__ = " Ng WaiMing " from pandas import DataFrame, Series import pandas as pd import numpy as np import statsmodels.api as sm from matplotlib import pyplot as plt def peak_to_peak(arr): return arr.max() - arr.min() def demean(arr): return arr - arr.mean() ...
import random import turtle import time lifespan = 200 #This is how long each rocket will live popSize = 10 #This is how many rockets is there speed = 10 #This will be how fast the rocket will be, it can move in a 20 pix radius screen = turtle.Screen...
#!/usr/bin/env python # encoding: utf-8 """ @author: Wayne @contact: wangye.hope@gmail.com @software: PyCharm @file: Find the Smallest Divisor Given a Threshold @time: 2019/12/9 15:46 """ class Solution: def smallestDivisor(self, nums, threshold): l, r = 1, max(nums) while l < r: m = ...
import socket, sys, time, platform, struct from PyQt4 import QtGui, QtCore def ip(self, packet, extractedAttIndex, printKey): # Header lengths. ethHeaderLength = 14 ip_hlen = 20 # Get IP header using begin and end. # Specific Linux and Windows calibration is needed. if self.os == self.windows: begin ...
from aws_parsecf.parser import Parser import boto3 import json import yaml def load_json(stream, default_region=boto3.Session().region_name, parameters={}): return _load(json.load(stream), default_region, parameters) def loads_json(string, default_region=boto3.Session().region_name, parameters={}): return _lo...
from django.urls import path from . import views urlpatterns = [ path("buyerHome", views.buyerHome, name="buyerHome"), path("bidderHome", views.bidderHome, name="bidderHome"), path("help", views.help, name="help"), ]
import json from flask import jsonify, request, abort from marshmallow import ValidationError from api.db import db from api.utils.utils import SUBSECTIONS_GAME from api.views.validate import validate from api.db.model import PageSchema, FilterSchema from api.utils.authorizers import require_api_key def _process_res...
#This program is to calculate the Area of a Cylinder from math import pi radius = float(input("Enter a value for radius: ")) height = float(input("Enter a value for heigh: ")) Area = (2*pi*radius**2)+height*(2*pi*radius) print("Area of the Cylinder is ", round(Area,4))
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings import django.utils.timezone class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations ...
import requests ## 2015 - 2016 : https://www.liberty.edu/media/1270/dcps/1516/ ## 2016 - 2019 : https://www.liberty.edu/media/1270/ base_url = "https://www.liberty.edu/media/1270/" pdf = '.pdf' def download_pdf(my_url, file_name): r = requests.get(my_url, stream=True) with open('PDF/DCP 2018 - 2019/' +...
# Napisz program, ktรณry przyjmie od uลผytkownika dwie liczby (a i b). # Wypisz informacjฤ™ ktรณra z nich jest wiฤ™ksza w postaci: # # a jest wiฤ™ksze! print(" w tym cwiczeniu bedziemy porownywac liczby") a = int(input("prosze podaj liczbe a")) b = int(input("prosze podaj liczbe b")) if a > b: print(" a jest wi...