text
stringlengths
38
1.54M
from sqlalchemy import ( Boolean, cast, Column, DateTime, ForeignKey, func, Integer, JSON, String, text ) from sqlalchemy.orm import backref, relationship from sqlalchemy.dialects.postgresql import JSONB from gam.database import Base, Fixed, SoftDelete from .hasher import verify_password class Permission(Base, So...
''' 给定一个字符串S,通过将字符串S中的每个字母转变大小写,我们可以获得一个新的字符串。返回所有可能得到的字符串集合。 示例: 输入: S = "a1b2" 输出: ["a1b2", "a1B2", "A1b2", "A1B2"] 输入: S = "3z4" 输出: ["3z4", "3Z4"] 输入: S = "12345" 输出: ["12345"] ''' # 全排列类型 class Solution: def letterCasePermutation(self, S: str): def transWord(word): if word.isalpha: ...
# python.exe # python -m pip install pyserial # IDLE -------------------------------- import serial s = serial.Serial("COM*") print( s.readline() ) input = s.readline() -------------------------------- # process the input # chunks = input.split(";") # for x in chunk: x.split(",") # each x represents
# Write a program that finds the shortest path from a source # vertex (0) to all other vertices. Following is a sample # input and output files. # Sample Input: # 8 # 15 # 4 5 0.35 # 5 4 0.35 # 4 7 0.37 # 5 7 0.28 # 7 5 0.28 # 5 1 0.32 # 0 4 0.38 # 0 2 0.26 # 7 3 0.39 # 1 3 0.29 # 2 7 0.34 # 6 2 0.40 # 3 6 0.52 # 6 ...
class DepthAreaCreator: count = 1 def __init__(self, count): super().__init__() self.count = count class DepthArea: pos_x = 0 pos_y = 0 w = 0 h = 0 def __init__(self, pos_x, pos_y, w, h): super().__init__() self.pos_x = pos_x self.pos_y = pos_y ...
N = int(input()) while N > 0: entry = input().split(' ') planeta = entry[0] ano = int(entry[1]) - int(entry[2]) for i in range(1, N): entry = input().split(' ') if (int(entry[1]) - int(entry[2])) < ano: ano = int(entry[1]) - int(entry[2]) planeta = entry[0] p...
from enum import Enum class Grammar(Enum): ERR = -2, #Erro #PALAVRAS CHAVE INSERT = 300 #Palavra Chave INSERT em caixa alta ou baixa UPDATE = 301 #Palavra Chave UPDATE em caixa alta ou baixa DELETE = 302 #Palavra Chave DELETE em caixa alta ou baixa INTO = 303 #Palavra Chave INTO em caixa ...
# Write a Python program to clone or copy a list def input_list(count): #function to take list from user as input a = list() while count != 0: elem = int(input("Enter Number : ")) a.append(elem) count -= 1 return a def copy(l): #new empty list n = list() #iterate over list and append elements in new l...
import sys from dictionary import alpha def main(): ascinput = str(input("Write your text: \n>>> ")) if ascinput == "": sys.exit() try: for row in range(len(alpha["a"])): for word in ascinput: print((alpha[word][row]), end=" ") print() except KeyEr...
#!/usr/bin/env python3 import os from flask import Flask # from flask_login import login_required, current_user, login_manager, user_loader # import flask_login from flask_bootstrap import Bootstrap from core.controllers.cleanlist import melisty from core.controllers.all_listed import all_listedmez from core.controlle...
# Angeline Hidalgo # February 2, 2020 name = input('Enter your name: ') # Program prompts user to enter their name. print('Hello,', name) # Prints out 'Hello' and the user's name.
import pkg_resources import sys from pyramid_skins.zcml import skins from pyramid.asset import resolve_asset_spec from pyramid.path import caller_path from zope.configuration.config import ConfigurationMachine def register_path(config, spec, discovery=False, indexes=[], request_type=None): """ Add a skin path to...
from django.conf.urls import url from django.urls import include, path from django.urls import reverse from . import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns app_name = 'logout' urlpatterns = [ path('', views.logout, name='logout'), ] urlpatterns += staticfiles_urlpatterns()
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-12-11 06:05 from __future__ import unicode_literals import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0014_auto_20171210_2144'), ] operations = [ migrati...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import datetime class Migration(migrations.Migration): dependencies = [ ('authors', '0098_auto_20160123_1539'), ] operations = [ migrations.AlterField( model_name='abstra...
import demistomock as demisto from IAMApiModule import * from Salesforce_IAM import Client, IAMUserProfile, get_user_command, create_user_command, update_user_command def mock_client(): client = Client( demisto_params={}, base_url='base_url', conn_client_id="client_id", conn_client...
### # Design # Time Complexity: O(1) # Space Complexity: O(n) ### class PhoneDirectory(object): def __init__(self, maxNumbers): """ Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory. :type maxNumbers: int ""...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('content', '0007_auto_20150314_0114'), ] operations = [ migrations.AlterField( model_name='resource', ...
import tensorflow as tf from tensorflow import keras from ProteinEnv import NPProtein # CONFIG OPTIONS N = 20 def make_model(): inp = keras.Input((4, N)) net = keras.layers.Flatten()(inp) policy = keras.layers.Dense(4)(net) value = keras.layers.Dense(1)(net) return keras.Model(inp, [policy, val...
# -*- coding: utf-8 -*- from openprocurement.tender.core.utils import optendersresource from openprocurement.tender.openeu.views.lot import TenderEULotResource @optendersresource(name='frameworkagreement:Tender Lots', collection_path='/tenders/{tender_id}/lots', path='/tenders/{t...
# coding: GBK #file you will to read, you can change it to test test_file_number = 300 #data_directory = 'E:\TextClassificationData\SogouC.mini\Sample' data_directory = 'E:\TextClassificationData\SogouC.reduced\Reduced' # training data directory training_data_directory = data_directory # test data directory test_da...
import ys_bypass as bp import time import arrow, random import requests from bs4 import BeautifulSoup import json, threading, traceback from multiprocessing import Pool, Queue ''' 初始设置 ''' # 设置要购买的鞋子名称 SEARCH_NAME = 'yeezy-boost-350-v2-glow-soon-so' # 设置购买尺码 buy_size = ['L', 'M'] # 访问延迟时间 PAY_DELAY = 1 # 设置超时时间 TIM...
# pbcore/io/dataset/_pbsample.py # -*- coding: utf-8 -*- # PyXB bindings for NM:a7c0866985dba806fe3112e9fbc4707c9f978443 # Generated 2016-12-06 17:03:07.509788 by PyXB version 1.2.4 using Python 2.7.9.final.0 # Namespace http://pacificbiosciences.com/PacBioSampleInfo.xsd [xmlns:pbsample] from __future__ import unicode...
""" Project Generator Universidad del Valle de Guatemala Saul Contreras Michele Benvenuto Jennifer """ from kivy.app import App from kivy.uix.widget import Widget from Models import * from ProjectGenerator import ProjectGenerator from kivy.uix.textinput import TextInput from kivy.uix.screenmanager import ScreenManager,...
# -*- coding: utf-8 -*- """ Created on 2019/5/7 10:35 @author: WangYuhang @function: 字典相关的 操作 """ # 最大值标准化 def dict_min_max(dic): dic_max = dic[max(dic, key=dic.get)] for i in dic: dic[i] = dic[i]/dic_max return dic if __name__ == "__main__": dogdistance = {'dog-dog': 33, 'dog-cat': 36, 'd...
import rclpy import RPi.GPIO as GPIO import time import cv2 import numpy as np import math as math from rclpy.node import Node from std_msgs.msg import String from std_msgs.msg import Float64 from sensor_msgs.msg import LaserScan from geometry_msgs.msg import * from nav_msgs.msg import * import matplotlib.pyplot as pl...
import tensorflow as tf import skflow from sklearn.metrics import accuracy_score import numpy # Data x_train = numpy.array([ [3,3,2,15,4], [2,0,2,13,3], [3,1,3,12,3], [0,3,3,12,4], [1,2,4,10,4], [3,3,5,9,3], [3,2,4,13,4], [1,2,2,15,4], [1,2,4,11,4], [3,2,5,8,4], [0,1,1,16,4], [4,4,3...
import time from nonebot import on_command from nonebot.adapters import Bot, Event from nonebot.rule import to_me img = on_command('赞赏', priority=1) group = {'833258227':"1",'783384299':'2',"519036865":'3',"87629913":'4',"908326662":'5'} @img.handle() async def _(bot: Bot, event: Event): img_path = f'/root/Alic...
from django.contrib import admin # Register your models here. from .models import PhoneNumber from .models import Patron admin.site.register(PhoneNumber) admin.site.register(Patron)
def main(): infile1 = "MimUGTPrimary.txt" infile2 = "PspgID.txt" outfile1= "Mim.UGT.v1.fasta" outfile2= "Mim.UGT.v2.fasta" #dont acutaully need? # infile3 = "" # outfile3 = "Mim.UGT.v3.fasta" infile4 = "MimUGTPrimary2.txt" outfile4 = "Mim.UGT.v4.fasta" #infile3 = "HMMERuniqRFEP.txt...
from tornado.options import logging from tornado import web import private from model import Article, Commit, Review, Tweet import app_urls class RegisterableClass(type): def __new__(meta, classname, bases, class_dict): constructed = type.__new__(meta, classname, bases, class_dict) if constructe...
''' Brief: Correct an error I made where all winding numbers were multiplied by 3 File name: plot_winding.py Author: Simon Rydell Python Version: 3.7 ''' import re import numpy as np import matplotlib.pyplot as plt from matplotlib import rc import helpers.calc as calc import ...
# Generated by Django 2.1.4 on 2019-01-17 12:08 import datetime from django.db import migrations, models import django.db.models.deletion from django.utils.timezone import utc import uuid class Migration(migrations.Migration): dependencies = [ ('core', '0014_auto_20190117_1048'), ] operations =...
import re loop = True base_de_conhecimento = {} while loop: sentenca = input().rstrip() if sentenca != 'END': output_regex = re.search(r'(.*?)\((.*)\)', sentenca) assinatura_funcao = output_regex.group(1) if assinatura_funcao not in base_de_conhecimento: base_de_conhecimento...
"""Config flow for BOM.""" import logging import homeassistant.helpers.config_validation as cv import voluptuous as vol from homeassistant import config_entries, exceptions from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE from homeassistant.core import HomeAssistant, callback from .const import ( CON...
import socket import sys s = socket.socket() s.connect(("localhost",8000)) f=open ("demo.txt", "rb") l = f.read(1024) while (l): s.send(l) l = f.read(1024) s.close()
# -*- coding: utf-8 -*- from PyQt4 import QtCore, QtGui from ui_chooseCfgFile import Ui_DialogChooseCfgFile try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): ...
import psycopg2 import pandas import threading # read configuration file import configparser config = configparser.ConfigParser() config.read('config.ini') host = config['Postgres']['host'] port = config['Postgres']['port'] database = config['Postgres']['database'] user = config['Postgres']['user'] pas...
from Modo import Modo class Perezoso (Modo): #duerme al bicho perezoso def dormir (self): print ("Bicho PEREZOSO usa DORMIR") print ("ZZZ ZZZ") #despierta al bicho perezoso def despertar (self): print ("Bicho PEREZOSO se despertó") #ataque del bicho perezoso def...
# 1. Даний об'єкт A1 типу Node, що має відкриті властивості Data (цілого типу), Left і Right (типу Node). # Властивості Left і Right цього об'єкта (кореня дерева) містять посилання на ліву і праву дочірні вершини # (того ж типу Node). Вивести значення властивостей Data кореня, # його лівої і правої дочірніх вершин, а т...
import numpy as numpy import matplotlib.pyplot as plt import pandas as pd from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.neural_network import MLPClassifier data = pd.read_csv("train.csv").values testData = pd.read_csv("test.csv").values clf = MLPCla...
def main(): # 先下载歌曲 download_music() # 在播放音乐 play_music() if __name__ == '__main__': main()
"""Syntax highlighter for the programming language Python.""" from __future__ import annotations from prettyqt import core, gui, syntaxhighlighters KEYWORDS = [ "and", "assert", "break", "continue", "class", "def", "del", "elif", "else", "except", "exec", "finally", ...
import numpy as np import pandas as pd def divisible_by(arr, int1, int2): '''Returns an array of the integers in arr that are divisible without remainder by both int1 and int2. Parameters ---------- arr: NumPy array int1, int2: int, int Returns ------- NumPy array >>>divisibl...
import cv2 as cv import argparse import numpy as np import sys backends = (cv.dnn.DNN_BACKEND_DEFAULT, cv.dnn.DNN_BACKEND_HALIDE, cv.dnn.DNN_BACKEND_INFERENCE_ENGINE) targets = (cv.dnn.DNN_TARGET_CPU, cv.dnn.DNN_TARGET_OPENCL) parser = argparse.ArgumentParser(description='Use this script to run classification deep le...
## Pre-processing File import pandas as pd import numpy as np from sklearn.preprocessing import StandardScaler from sklearn import preprocessing from sklearn.model_selection import train_test_split def Preprocessing(classes,columns2,Wx,dx,data): drivers =[] for c in classes: drivers.append(da...
class Solution(object): def trailingZeroes(self, n): """ :type n: int :rtype: int """ ans=0 x=5 while n>=x: ans += n / x x *= 5 return ans
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from catalogDB_setup import Base, Category, Item engine = create_engine('sqlite:///categoryitem.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() #seed database with categories FruiteCategory = Ca...
switches = input() position = [1, 0, 0] for i in range(len(switches)): if switches[i] == "A": positiontemp = position[0] position[0] = position[1] position[1] = positiontemp elif switches[i] == "B": positiontemp = position[1] position[1] = position[2] position[2]...
from optparse import OptionParser, OptionGroup import logging, sys, os, random import xml.etree.ElementTree as ET import traci, sumolib from traci.vehicle import DEPART_NOW #looks up on ../lib to import Guilherme's implementation of Dijkstra algorithm path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'...
import shopify import json from test.test_helper import TestCase class MarketingEventTest(TestCase): def test_get_marketing_event(self): self.fake("marketing_events/1", method="GET", body=self.load_fixture("marketing_event")) marketing_event = shopify.MarketingEvent.find(1) self.assertEqua...
'''Mix read sets. TODO: Make this script "pipable" so we can add e.g. a truncate script in step 2. Given a json fomatted file of file paths to fasta files with associated weight, this script creates a fasta file with the specified read proportions. Note that this creates a bias if the read length distribution of the ...
x = int(input()) y = int(input()) a = int(input()) b = int(input()) if (x - 1 == a or x + 1 == a or x == a) and\ (y - 1 == b or y + 1 == b or y == b): print("YES") else: print("NO")
# -*- coding: utf-8 -*- """Simple HTTP Honeycomb Service.""" import os import requests from six.moves.socketserver import ThreadingMixIn from six.moves.BaseHTTPServer import HTTPServer from six.moves.SimpleHTTPServer import SimpleHTTPRequestHandler from base_service import ServerCustomService DEFAULT_PORT = 8888 EVE...
from db import db class UserModel(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80),unique=True) password = db.Column(db.String(80)) invest_amt = db.Column(db.Integer) lend_amt = db.Column(db.Integer) borrow_amt = db.Column...
import os import shutil folders = os.listdir() for folder in folders: if not os.path.isdir(folder): continue files = os.listdir(folder) for file in files: if file.split('.')[-1] == 'txt': continue src = os.path.join(folder,file) batch = file.split('_')[0] dir = os.path.join('..','packed',batch) if no...
from django.db import models from django.conf import settings User = settings.AUTH_USER_MODEL class Contact(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) email = models.EmailField() order_code = models.CharField(max_length=25) subject = models.CharField(max_length=25) mes...
""" Gau2grid base init """ from . import generator from . import python_reference as ref from . import RSH from . import order
# This code picks a random food item: from random import choice # DON'T CHANGE! food = choice(["cheese pizza", "quiche", "morning bun", "gummy bear", "tea cake"]) # DON'T CHANGE! # DON'T CHANGE THIS DICTIONARY EITHER! bakery_stock = { "almond croissant": 12, "toffee cookie": 3, "morning bu...
# Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import contextlib from recipe_engine import recipe_api class InfraSystemApi(recipe_api.RecipeApi): """API for interacting with a provisioned infrastruct...
import socket import sys HOST = '127.0.0.1' PORT = 8888 s = socket.socket(socket.AF_INET , socket.SOCK_STREAM) try: s.bind((HOST , PORT)) except socket.error , msg: sys.exit() s.listen(10) conn,addr = s.accept() print addr path = conn.recv(1024) print path fd = open(path , 'wb') data = conn.recv(1024) while data...
#Write a Python program to test whether a passed letter is a vowel or not letter=input("Enter a alphabet:") if letter=='a': print("The given letter is vowel.") elif letter=='e': print("The given letter is vowel.") elif letter=='i': print("The given letter is vowel.") elif letter=='o': print...
IMAGE_URL = "https://morvanzhou.github.io/static/img/description/learning_step_flowchart.png" def urllib_download(): from urllib.request import urlretrieve urlretrieve(IMAGE_URL, './images/image1.png') # whole document def request_download(): import requests r = requests.get(IMAGE_URL) with...
# FYP2017 # Program to send battery status to ThingSpeak channel # Author: Kunal Jagadeesh # License: Public Domain import time import sys from ubidots import ApiClient f = open('Ubidots_APIkey.txt', 'r') apikey = f.readline().strip() f.close() api = ApiClient(token = apikey) try: variable1 = api.get_variable("5...
# coding: utf-8 import kivy kivy.require('1.10.1') from tasks import TasksApp if __name__ == "__main__": TasksApp().run()
class IApplicationDal: @classmethod def add_row(cls, value): raise NotImplementedError() @classmethod def delete_row(cls, row_id): raise NotImplementedError() @classmethod def get_row(cls, value): raise NotImplementedError() @classmethod def get_row_list(cls, o...
# Copyright 2019 NEC 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 writi...
class Config(object): DATABASE_CONFIG = { 'host': 'localhost', 'db_name': 'user_akhil', 'user': 'root', 'password': 'PassWord1.' }
# test_check_args_6.py # This should pass. # This should terminate. def use(i: object) -> object: return i # We edited the next line. `/, ` is removed because we don't support this # kind of argument specification. # def outer(x: int, /, y: str) -> object: def outer(x: int, y: str) -> object: def inner() -> ...
import math as mt def getnormf(tensor): n1, n2, n3 = tensor.shape value_norm = 0 for i in range(n1): for j in range(n2): for k in range(n3): value_norm += tensor[i][j][k] * tensor[i][j][k] value_norm = mt.sqrt(value_norm) return value_norm
#!/usr/bin/python3 # import Relevant Librares import blynklib import os import smbus import threading import RPi.GPIO as GPIO import time import spidev # To communicate with SPI devices from numpy import interp from threading import Thread ########################################################### # VAR...
""" Project Euler Problem 28: Number spiral diagonals Answer: 669171001 """ def numberSpiralDiagonalSum(n): """ The sum of the numbers on the diagonals in a (n x n) spiral. """ summ = 1 diff = 2 curNum = 1 for i in xrange(n / 2): for j in xrange(4): curNum += diff summ += curNum diff += 2 return sum...
"""" author :tomlin time: 2019-9-09 23:11 email: rain_day01@163.com conetnt: serialzier study """ from rest_framework import serializers from .models import Book class BookSerializer(serializers.Serializer): nid = serializers.CharField(max_length=255,allow_blank=False,required=False) title = serializers.CharF...
import logging import re from pathlib import Path import numpy as np import spacy # load pre-trained vectors from gensim.models import KeyedVectors from sklearn.decomposition import PCA from tqdm import tqdm, trange from db.events import get_documents_from_event, get_documents_from_event2 def gen_discourse(event_na...
# Generated by Django 2.2.6 on 2019-10-21 17:03 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
''' Eager execution is an imperative, define-by-run interface where operations are executed immediately as they are called from Python. This makes it easier to get started with TensorFlow, and can make research and development more intuitive. ''' from __future__ import division, absolute_import, print_function im...
from __future__ import print_function, division, generators import pytest from ..__main__ import * import math def test_case_1(): assert fib( 10 ) == 10 def test_case_2(): assert fib( 100 ) == 44 # Test for runtime errors for largest input def test_edge_large_n(): assert fib( 4 * math.pow(10, 6) )
# coding: utf-8 # ## Face detection # The goal of this notebook is to detect faces in all the images associated to the set of ads provided for the CP1 during the MEMEX Winter QPR 2017. # # ### Inputs # 1. image_url_sha1.csv # This is a mapping of the URLs images to their SHA1, the images in this file have been downl...
# Generated by Django 3.0.14 on 2021-05-03 22:14 from django.db import migrations from bpp.migration_util import load_custom_sql class Migration(migrations.Migration): dependencies = [ ("rozbieznosci_dyscyplin", "0007_recreate"), ("bpp", "0265_rekord_mat_doi"), ] operations = [ ...
from rest_framework import viewsets from users.models import User from users.serializers import UserSerializer class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer def get_queryset(self): return User.objects.filter(pk=self.request.user.pk)
#class used to help deploy alerts easily class Slack_alerts(): def __init__(self): pass
import zlib f = open('D:\\Dropbox\\Python\\git_blob_decoder\\a_blob_object', 'rb') decompressed_data = zlib.decompress(f.read()) print(decompressed_data.decode('utf-8'))
# -*- coding: utf-8 -*- """The APFS file entry implementation.""" from dfdatetime import apfs_time as dfdatetime_apfs_time from dfvfs.lib import definitions from dfvfs.lib import errors from dfvfs.path import apfs_path_spec from dfvfs.vfs import attribute from dfvfs.vfs import apfs_attribute from dfvfs.vfs import apf...
from calculator import subtract def test_subtract(): results = subtract(16, 6) #changing the value of substract assert results == 10
from django.shortcuts import render from profiles.models import Profile from itertools import chain # Create your views here. def posts_of_following_profiles(request): #get logged in user profile profile=Profile.objects.get(user=request.user) #check who we are following users=[user for user in profile...
from typing import Union from pyrogram.parser import Parser from pyrogram.raw import types from pyrogram.types import InlineQueryResult, InlineKeyboardMarkup, InputMessageContent class InlineQueryResultVoice(InlineQueryResult): def __init__( self, voice_url: str, title: str, ...
##Write a function that calculates and returns the monthly payments for a loan. This function accepts three parameters in the exact order (principal, annual_interest_rate, duration): ##principal: The total amount of loan. Assume that the principal is a positive floating point number. ##annual_interest_rate: This is th...
import asyncio from api.client import Client async def main(): c = Client.create('http://testapi.ru') await c.authorize(username='test', password='12345') data = await c.get_user(username='test') del data['status'] del data['created_at'] data.update(name='Petr Petrovich', blo...
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.OUT) GPIO.output(17,0) print "LED OFF"
from rest_framework import serializers from filters.models import Filter, Criteria class FilterSerializer(serializers.ModelSerializer): class Meta: model = Filter fields = ('id', 'name', 'user', 'description', 'subscribed', 'criteria') class CriteriaSerializer(serializers.Mode...
import cv2 import numpy as np import sys def convert2BinaryImage(img, mode=0): height = img.shape[0] width = img.shape[1] #convert grayscale into binary image, threshold is 128 value = 255 if mode == 1: value = 1 for row in range(height): for col in range(width): pix...
import random modelo = [5,5,2,2,2,3,2,2,2,5,5] largo = 11 num = 11 pressure = 5 mutation_chance = 0.5 print("\n\Modelo: %s\n"%(modelo)) def individual(min,max): return[random.randint(min, max) for i in range(largo)] def crearPoblacion(): return[individual(1,9) for i in range(num)] def calcularFitness(indiv...
print("Let's see how cost effective getting a large pizza vs a smaller size is:") pizzaSize1 = input("how many inches is the smaller pizza?") pizzaPrice1 = float(input("how much is that size?")) pizzaSqin1 = 3.1415926 * (int(pizzaSize1)/2)**2 pizzaPPSqIn1 = int(pizzaPrice1) / int(pizzaSqin1) print("That pizza is " + ...
''' Created on 25-Dec-2012 @author: rohith ''' from urllib2 import urlopen import BeautifulSoup from django.utils.html import strip_tags import re from urllib import urlencode from nltk.tokenize import sent_tokenize from Parser.StanfordParser import StanfordParser from PreProcessing.PreFunctions import stemWords def...
from django.urls import path from .views import ListEmployeesView, ListEmployeesName, CreateEmployee, \ UpdateEmployee, DeleteEmployee urlpatterns = [ path('Employees/', ListEmployeesName.as_view(), name="all-employees"), path('EmployeeDetails/', ListEmployeesView.as_view(), name="employees-names"), path('CreateEm...
#!/usr/bin/python # -*- coding: utf-8 -*- from flask import jsonify def make_error(status, status_code, message): '''Function to create the error response in proper format ''' response = jsonify({'status': status, 'reason': message}) response.status_code = status_code return response
from matplotlib import pyplot as plt def draw_graph(graph): print("start drawing graph (this can take several seconds) ....") for vertex in graph.vertices: for ady_vertex in graph.ady(vertex): x_values = [vertex.x, ady_vertex.x] y_values = [vertex.y, ady_vertex.y] ...
from frameworkrequests.rutetider import Timetable, Subscribers, CurrentDates, UserPosition, Statistics from rest_framework.views import APIView from django.http import JsonResponse import datetime def is_url_out(data, url): if url not in data: return True # Timetable class TimetableApplication(APIView):...
#!/usr/bin/env python2 import numpy as np import cv2 class DetectedObject: def __init__(self, contour): self.contour = cv2.convexHull(contour) self.moments = cv2.moments(self.contour) @property def area(self): return self.moments['m00'] @property def centroid(self): ...
from StochasticModels.ClosedFormModels.CGenericOptionBlackScholesModel import calculate_d1 as __parent_calculate_d1 from StochasticModels.ClosedFormModels.CGenericOptionBlackScholesModel import calculate_d2 as __parent_calculate_d2 from StochasticModels.ClosedFormModels.CGenericOptionBlackScholesModel import calculate_...