text
stringlengths
8
6.05M
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/3/6 21:37 # @Author : cunyu # @Site : cunyu1943.github.io # @File : seventeen.py # @Software: PyCharm import string s = input('请输入字符串:\n') num_letter = 0 num_space = 0 num_digit = 0 num_other = 0 for i in range(len(s)): if s[i]....
"""Unit test for DPTControlStepCode objects.""" import pytest from xknx.dpt import ( DPTControlStartStop, DPTControlStartStopBlinds, DPTControlStartStopDimming, DPTControlStepCode, DPTControlStepwise, ) from xknx.exceptions import ConversionError class TestDPTControlStepCode: """Test class for...
#1<N<10**7 arasındaki sayıların bölenlerinin sayısını bir listeye yazan algoritma bolenler = [1, 1] #1 ve kendisini tuttuk for p in range(2,10**7): bs = 2 for n in range(2, p//2+1): if(p//n*n==p): bs += 1 bolenler.append(bs) print(p) print(bolenler)
# Main starter app from test_cases import login_page_test as lpt from pages import profile_page_object as ppo class Main: def startTestsWithCases(self): loginPageTest = lpt.LoginPageTestCase() print "Starting 1st test case . . ." print loginPageTest.testCase1() print "\n" ...
import json from urllib import request from urllib.error import HTTPError from random import * import pickle import asyncio import Types_for_metis import Dara def Test_token(secretToken): return len(secretToken) == 59 def read_last(): file = open("last_new.txt",'r') content = file.read() file.close() content =...
''' Contains the L{Generator} class for building collections of fuzzed values @author: Rob Waaser @contact: robwaaser@gmail.com @organization: Carnegie Mellon University @since: October 30, 2011 ''' import random import struct import logging class Generator(object): ''' Used to generate lists ...
import pickle from typing import Any, Optional from .errors import MissingFieldError, DuplicateError from .tools import NA_VALUES, isnull class FuzzyField: """Abstract base class. :param bool required: If False, return default if value is "" or "N/A". If True, ensure that this field has a val...
""" """ import phantom.rules as phantom import json from datetime import datetime, timedelta ############################## # Start - Global Code Block def comment_and_debug(msg): phantom.comment(comment=msg); phantom.debug(msg); def nested_dict_check(dictionary, *keys): from functools import r...
"""empty message Revision ID: d24761a4ddc4 Revises: 55c8b26bbd43 Create Date: 2020-05-31 11:42:28.211676 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'd24761a4ddc4' down_revision = '55c8b26bbd43' branch_labels = None depends_on = None def upgrade(): # ...
#!/usr/bin/env python3 import re import sys import subprocess class bsc: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' BOLD = '\033[1m' UNDERLINE = '\033[4m' END = '\033[0m' if __name__ == "__main__": if not re.match(r'^[a-zA...
# calculating the degree of a number a = float(input()) a > 0 n = int(input()) n >= 0 def power(a, n): if n == 0: return 1 return a * power(a, n - 1) print(power(a, n))
from __future__ import division import pandas from numpy import ndarray import os from ITSframework import ITS from ipdb import set_trace as debug # NOQA # We store files relative to this directory package_directory = os.path.dirname(os.path.abspath(__file__)) def StringOrFloat(incoming): """ Return float if e...
import random import torch from NeuralNet.NeuralNet import * class BrainSnake: def __init__(self, _id, gen=-1, width=500, height=500, pvp=False, network_layout=None): self.MaxWidth = width self.MaxHeight = height self.head = [50, 50] self.body = [[50, 50], [40, 50], [30, 50]] ...
# Visualizing a Categorical and a Quantitative Variable # Categorical variables are present in nearly every dataset, but they are especially prominent in survey data. In this chapter, you will learn how to create and customize categorical plots such as box plots, bar plots, count plots, and point plots. Along the way, ...
import os, pyclbr instrumentsRootDir='lab/instruments' def findInstrumentModule(instrumentModuleName): found = None for (dirpath, dirnames, filenames) in os.walk(instrumentsRootDir): print dirpath, dirnames, filenames # builds a list of all python file names (except _init__.py) pyFilenames = [filename for filen...
#!starterbot/bin/python from migrate.versioning import api from sqlalchemy import create_engine from sqlalchemy_utils import database_exists, create_database import os from config import SQLALCHEMY_DATABASE_URI from config import SQLALCHEMY_MIGRATE_REPO engine = create_engine(SQLALCHEMY_DATABASE_URI) if not database_e...
#!/usr/bin/env python # -*- coding: utf-8 -*- from behavioral_patterns.chain_of_responsibility.lazy_supporter import LazySupporter from behavioral_patterns.chain_of_responsibility.moody_supporter import MoodySupporter from behavioral_patterns.chain_of_responsibility.special_supporter import SpecialSupporter from behavi...
# a simple parser for python. use get_number() and get_word() to read def parser(): while 1: data = list(input().split(' ')) for number in data: if len(number) > 0: yield(number) input_parser = parser() def get_word(): global input_parser return next(input_pa...
import nltk # import spacy import os import json from collections import Counter corpus = {} with open('corpus_data/preprocessedf_corpus.json') as infile: corpus = json.loads(infile.read().encode('utf-8')) featurecounts = {} for artist,songlist in corpus.items(): features = {"pos_counts":Counter()} numwor...
import json import requests import pytz from decimal import Decimal from datetime import datetime, timedelta, date from django.utils import timezone from django.core import serializers from django.http import JsonResponse from django.shortcuts import render, HttpResponse, render_to_response, get_object_or_404, redire...
import math, csv, json from collections import defaultdict from nltk import FreqDist,word_tokenize from nltk.corpus import reuters, stopwords # from nltk.stem.snowball import SnowballStemmer import nltk nltk.download('punkt') nltk.download('reuters') nltk.download('stopwords') from gensim.models import KeyedVectors ...
#coding:utf-8 import time import requests title = "这是标题_%s" % str(int(time.time())) content = "正文内容_%s" % str(int(time.time())) url = "https://i.cnblogs.com/EditPosts.aspx?opt=1" s = requests.session() print("更新之前的cookies:%s" % s.cookies) c = requests.cookies.RequestsCookieJar() c.set(".CNBlogsCookie", "5F1D0B9...
def every_other(array): for i in range(len(array)): if i % 2 == 0: for j in array: print(array[i] + j) every_other([1,2,3,4])
''' utils.py ======== General-purpose utilities that are not categorized by any other module. ''' import struct from io import BytesIO def pack_as_string(string): 'Returns the bytes object after packing the string' if not string: return struct.pack('>h', -1) string_len = len(string) return s...
import json from tanserver import * # API: register def register(json_obj): user = json_obj.get('username') pwd = json_obj.get('password') if user == None or pwd == None: # Send {"status":-1,"message":"missing username or password","result":{}} return json_append_status('{}', -1, 'missin...
import os import sys import socket, select import time import json import struct import re import base64 from hashlib import sha1, md5 from util import * IOTYPE = ['select', 'pool', 'async'] class MS(WSSocket): def __init__(self, addr, port, ioType = 'select'): #本地初始化 if ioType not in IOTYPE: ...
import time; localtime = time.localtime(time.time()) print( "Local current time :", localtime) import time; localtime = time.asctime( time.localtime(time.time()) ) print( "Local current time :", localtime) import calendar cal = calendar.month(2019, 9) print(cal) from datetime import date ...
#coding:utf-8 ''' cookie操作 ''' import tornado.web import tornado.ioloop class CookieHandle(tornado.web.RequestHandler): def get(self): if self.get_cookie('a'): self.write('your cookies is set') else: self.write('error cookie not') self.set_secu...
#!/usr/bin/env python # -*-coding:utf-8 -*- # author:罗徐 time:2019/8/2 # 视频人脸识别 import cv2 as cv import numpy as np def face_dectect_demo(image): gray=cv.cvtColor(image,cv.COLOR_BGR2GRAY) face_dectector=cv.CascadeClassifier("D:/opencv-4.0.1-vc14_vc15/opencv/build/etc/haarcascades/haarcascade_frontalfac...
# Creating a list using a for loop list1 = [] n = int(input("Enter the list size : ")) for i in range(0, n): print("Enter item at location", i, ":") item = input() list1.append(item) print("User List is ", list1) # for numbers numberList = [] n = int(input("Enter the list size : ")) for i in ...
import hashlib print(hashlib.sha384(raw_input()).hexdigest())
#!/usr/bin/env python # -*- coding: utf-8 -*- from src.librecatastro.domain.reform import Reform class Construction: """ Class that stores constructions / reforms of a property""" def __init__(self, construction): self.use = construction[u'uso'] self.doorway = construction[u'escalera'] ...
## 1.) Go to the end line and add the new line: if app.ENABLE_DROP_RENEWAL: class DropRenewalDialog(ui.ScriptWindow): def __init__(self): ui.ScriptWindow.__init__(self) self.__CreateDialog() def __del__(self): ui.ScriptWindow.__del__(self) def __CreateDialog(self): pyScrLoader = ui.Pytho...
import numpy as np def calc_out_shape(input_matrix_shape, out_channels, kernel_size, stride, padding): hout = int((input_matrix_shape[2] + 2 * padding - 1 * (kernel_size - 1) - 1) / stride + 1) wout = int((input_matrix_shape[3] + 2 * padding - 1 * (kernel_size - 1) - 1) / stride + 1) return [input_matrix_...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 11 18:10:16 2020 @author: kodiuser """ import PySimpleGUI as sg sg.theme('DarkAmber') # Add a touch of color # All the stuff inside your window. layout = [ [sg.Text('Attacker Dice')], [sg.Checkbox('One Die', enable_events=True),sg.Che...
import cv2 import numpy as np import matplotlib.pyplot as plt # Read image img = cv2.imread("imori.jpg").astype(np.float32) / 255. # RGB > HSV max_v = np.max(img, axis=2).copy() min_v = np.min(img, axis=2).copy() min_arg = np.argmin(img, axis=2) H = np.zeros_like(max_v) H[np.where(max_v == min_v)] = 0 ## if min ==...
# -*- coding: utf-8 -*- # Author:benjamin # Date: #使用celery实现异步执行任务 #我们将耗时任务放到后台异步执行。 #不会影响用户其他操作。除了注册功能,例如上传,图形处理等等耗时的任务 from celery import Celery from django.conf import settings from django.core.mail import send_mail#发送邮件配置 from apps.goods.models import * from django.shortcuts import render,HttpResponse from django....
def format_currency(value, places=2, show_zero=True): """ Formats value currency format like: $1,500.25 :param places: number of decimal places to show. :param show_zero: When true, zero should be formatted. When false, zero should be empty string. """ if value in (0, No...
import random import os import pandas import numpy data_latih = pandas.read_csv('D:\Dokumen dan Tugas Kuliah\Tugas Kuliah\Kecerdasan Buatan\Tugas2\data_latih.csv') data_test = pandas.read_csv('D:\Dokumen dan Tugas Kuliah\Tugas Kuliah\Kecerdasan Buatan\Tugas2\data_test.txt') gen_size = 15 list_dat...
from django.db import models class Info(models.Model): user_email = models.EmailField(max_length=20) user_name = models.CharField(max_length=20) user_phone = models.CharField(max_length=20)
import re import Paragraph import word import essay class Sentence: #This is a class that contains a single sentence words = [] endPunctuation = "" fanboys = [] markers = [] commas = [] add_commas = [] def __init__(self, plain_text_sentence, punctuation_mark): self.words = re.split(r"\s", plain_text_sent...
# Atividade Contínua 01 # Aluno 01: Anna Beatriz Moraes Santos # Aluno 02: Everton de Souza Siqueira def incluir_pessoa(agenda, nome, telefone): if nome not in agenda: agenda[nome] = telefone return agenda def excluir_pessoa(agenda, nome): if nome in agenda: agenda.pop(nome) return a...
import numpy as np import cv2 from matplotlib import pyplot as plt img=cv2.imread('rajat.jpg',0) plt.imshow(img,cmap='gray',interpolation='bicubic') plt.xticks([]), plt.yticks([]) #to hide tick values on X and Y axis plt.show() #color image loaded by opencv is in BGR mode. but matplotlib displays in RGB mode. So colo...
from parsing import cool_ast from lark import Token class Scope: def __init__(self, parent=None, inside=None): self.inside = inside self.locals = {} self.methods = [] self.parent = parent self.children = [] self.self_type = [] self.types = [] if not ...
import time import io import picamera import picamera.array import numpy as np import cv2 import socket import sys width=640 height=480 w_led=32 h_led=32 sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) server_address=('localhost',5080) sock.connect(server_address) #Initialise camera with picamera.PiCamera() a...
from pwn import * def new_fmtstr_payload(offset, writes, numbwritten=0, write_size='byte', bits=context.bits): from math import pow def get_payload(offset, chunk_list, numbwritten, write_size): format_n = { 4: 'n', 2: 'hn', 1: 'hhn' }[write_size] wr...
from apispec import APISpec from apispec.ext.marshmallow import MarshmallowPlugin from apispec_webframeworks.flask import FlaskPlugin spec = APISpec( title="Shared DB Channel API", version="1.0.0", openapi_version="3.0.2", plugins=[ FlaskPlugin(), MarshmallowPlugin() ], )
#!/usr/bin/env python ''' Computer the factorial of a number ''' def factorial(x): total = 1 if int(x) == 0: total = 1 else: while x > 0: total = total * x x -= 1 return total print('9 factorial: ' + str(factorial(9))) print('5 factorial: ' + str(factorial(5))...
from flask import Flask from flask import render_template, request from SearchTweets import buildquerydataforsearch from UserTimeline import buildquerydataforusertimeline from Friendships_create import buildquerydataforfriendshipscreate from Friendships_update import buildquerydataforfriendshipsupdate from Tweet import...
f = open("test.txt", "w") for i in range(0, 1546, 2): f.write("data/ts/" + str(i) + ".jpg\n") f.close() f = open("train.txt", "w") for i in range(1, 1546, 2): f.write("data/ts/" + str(i) + ".jpg\n") f.close()
import matplotlib.pyplot as plt import sys import string import numpy from matplotlib.backends.backend_pdf import PdfPages from itertools import chain SEQ = "_MQKLVFFAEDVGSNKGAIIGLMVGGVVIATVIVITLVMLKKK" NSEQ = [e[1]+str(e[0]) for e in enumerate(SEQ, 1)] PERPAGE = 5 NCcorr = [1, 1 ] def kk(ss): s = ss[0] ai...
# TweetBox by Gary Grossi # Created 06/04/2014 # Updated 06/09/2014 # Version 0.4 # library imports import time import twitter # Twitter authentication and setup keys = twitter.Api(consumer_key="Enter consumer key here", consumer_secret="Enter consumer secret here", access_token_...
#!/home/cchandlc/virtualenv/python34/3.4/bin/python3 import lxml.html from urllib.request import urlopen import mysql.connector def connect(): return mysql.connector.connect(user='cchandlc_seniorP', password='supersecretPASSWORD', host='localhost', database='cchandlc_Senior_Project_CARD$') def getURL(site, cardID):...
""" Example Client to be implemented by android and the pi """ import socket from PiCom.Data import Payload, send_payload, receive_payload class LANClientHandler: def received(self, req_payload: Payload, res_payload: Payload): pass class Client: def __init__(self, host: str, port: int, handler: LA...
# coding: utf-8 from django.conf.urls import url from rest_framework.urlpatterns import format_suffix_patterns # importação das classes do arquivo views.py from portfolios.views import FuncionarioListAndPost, FuncionarioById, CargoListAndPost, CargoById, \ MarcaListAndPost, MarcaById, ProdutoListAndPost, ProdutoBy...
#!/usr/bin/env python # encoding: utf-8 from abc import ABCMeta, abstractmethod import datetime import random import time import unittest class Singleton(type): def __init__(self, name, bases, namespace): self._obj = type(name, bases, namespace)() def __call__(self): return self._obj class PRNG: ...
# Generated by Django 3.0.7 on 2020-09-07 23:30 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('containers', '0001_initial'), ] operations = [ migrations.CreateModel( name='Item', fields=[ ('id', ...
import threading import liblo as lo import numpy as np from bluepy.btle import Scanner, Peripheral, DefaultDelegate import sys import time import bitstring from time import time, sleep from datetime import datetime class Muse(): def __init__(self, callback=None, address=None, museName=None, port=None): #specify callb...
#CSCI 1133 Homework 6 #Sid Lin #Problem 6 Bonus import turtle class Insect: def __init__(self, radius = 50, bodyColor = "black", legColor = "black"): self.size = radius self.body = bodyColor self.leg = legColor self.tur = turtle.Turtle() self.tur.speed(0) #default c...
import sys import json if len(sys.argv)!=6: print "script.py <sample> <base_dir> <chrom> <start> <end>" quit() script,sample,base_dir,chrom,start,end = sys.argv start = int(start) end = int(end) indel_file = base_dir+"/"+sample+".indels" indels = json.load(open(indel_file)) for indel in indels: if indel["chr"]...
from nltk.lm import Vocabulary import os import pickle NONSPAM_DIR = "data/nonspam-train" SPAM_DIR = "data/spam-train" #Precondition: numDocs must be less than or equal to the number of training docs in the train folders def buildVocab(trainFolders, numDocs): print('Number of training documents:', str(numDocs)) ...
# ================================================================================================== # Copyright 2013 Twitter, Inc. # -------------------------------------------------------------------------------------------------- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use thi...
import matplotlib.pyplot as plt import numpy as np import os PI=3.14159265358979323 x2=[] y2=[] x3=[] y3=[] x2 , y2 = np.loadtxt('corrections.txt', delimiter=' ', unpack=True) x3 , y3 = np.loadtxt('no_corrections.txt', delimiter=' ', unpack=True) T_c = np.loadtxt('temp_c.txt'); T_nc =np.loadtxt('temp_nc.txt'); fig...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Nov 29 11:10:41 2019 @author: ros """ import cv2 class Display: def __init__(self, name): """ Creates a window with name = 'name' """ self.name = name cv2.namedWindow(self.name, cv2.WINDOW_NORMAL) def update(self, ima...
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2021 Gramps developers, Kari Kujansuu # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # ...
../../../python/geometry/splines/cubic_hermite_spline.py
# Generated by Django 2.0.2 on 2018-03-10 17:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('galerie_photo', '0009_auto_20180306_1611'), ('visite_virtuelle', '0004_auto_20180306_1624'), ('gestion_table', '0007_remove_table_galerie'), ...
""" Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1. first thought: can it be thought as a permutation of s1? No! second thought: can we use a tree to represent it? or more general way to do that simulation? special case: if s1 == s2, true or false? """ class Solution: ...
# ================================================================================================== # Copyright 2012 Twitter, Inc. # -------------------------------------------------------------------------------------------------- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use thi...
import sys, re CommTypeA = 'A' CommTypeC = 'C' CommTypeL = 'L' class SymbolTable: preSymbols = {'SP': 0, 'LCL': 1, 'ARG': 2, 'THIS': 3, 'THAT': 4, 'R0': 0, 'R1': 1, 'R2': 2, 'R3': 3, 'R4': 4, 'R5': 5, 'R6': 6, 'R7': 7, 'R8': 8, 'R9': 9,' R10': 10, 'R11': 11, 'R12': 12, 'R13': 1...
import yfinance as yf import streamlit as st import pandas as pd import numpy as np import time def local_css(file_name): with open(file_name) as f: st.markdown(f'<style>{f.read()}</style>', unsafe_allow_html=True) local_css("style.css") from PIL import Image image = Image.open('codepth2.jpg...
class Solution: def nextPermutation(self, nums): last = nums[len(nums)-1] first = len(nums) for i in range(len(nums)-1,-1,-1): if nums[i]>=last: last = nums[i] continue else: first = i break if fi...
#!/usr/bin/env python from bhmm import BHMM from utility import parse_args if __name__ == "__main__": args = parse_args() bhmm = BHMM(args) bhmm.run()
#!/usr/bin/python3 """class Square""" class Square: """class square""" def __init__(self, size=0, position=(0, 0)): """square initialization""" self.size = size self.position = position @property def size(self): """returns current size of the square""" return (...
import logging from aiogram.dispatcher.filters import Command, Text from aiogram.types import Message, CallbackQuery from states.request_states import RequestGroup from keyboards.inline.menu_keyboard import shell_keyboard, shell_callback from middlewares import rate_limit from loader import dp, bot @dp...
import spacy from datetime import datetime # Load English tokenizer, tagger, parser, NER and word vectors nlp = spacy.load("en_core_web_sm") def log(txt): print(datetime.utcnow(), txt) def create_doc(filename): log("Started create doc") # load text file = open(filename, 'rt', encoding="UTF8") # rt =...
import numpy as np import time import argparse # initial = np.array([[1,2,3],[4,0,5],[7,8,6]], dtype=np.int8) initial = np.array([[1,0,3],[4,2,5],[7,8,6]], dtype=np.int8) ##3 # initial = np.array([[4,5,0],[2,3,8],[1,7,6]], dtype=np.int8) ###16 final = np.array([[1,2,3],[4,5,6],[7,8,0]], dtype=np.int8) class PuzzleSol...
#!/usr/bin/env python """ VanillaCondorPlugin BossAir plugin for vanilla condor """ import os.path import logging from WMCore.BossAir.Plugins.CondorPlugin import CondorPlugin from WMCore.Credential.Proxy import Proxy class VanillaCondorPlugin(CondorPlugin): """ _VanillaCondorPlugin_ Minor ...
""" Pushpull websocket server """ import logging import asyncio import random import aiohttp import aiohttp.web from ..amqp.gateway.driver_aioamqp import Exchanger from .. import config from ..amqp import auth from .auth import decode_auth_querystring_param logger = logging.getLogger(__name__) async def websocket_...
''' * ler o exif dos arquivos de uma pasta * filtrar por data * criar uma pasta de acordo com a data dos exif * mover arquivos para as pastas de acordo com as datas ''' import os def nomeArquivos (): nome = os.listdir() for f in nome: print(f) nomeArquivos()
from django.conf.urls import url, include from . import views urlpatterns = [ url(r"^$", views.index, name="index"), url(r"add$", views.addbook, name="addbook"), url(r"addbook$", views.addbookreview, name="addbookreview"), url(r"^(?P<id>\d+)", views.viewbook, name="viewbook"), url(r"users/(?P<id>\d+)", v...
# -*- coding:utf-8 -*- import urllib2 import urllib from pyquery import PyQuery from BeautifulSoup import BeautifulSoup import re import os from os import listdir from os.path import isfile, join from InstagramAPI import InstagramAPI from resizeimage import resizeimage import PIL PhotoPath = "/home/user/image" # Chan...
#!/usr/bin/env python import velocity import atexit import datetime import math DB_NAME = r'vscDatabase' DB_USER = 'script' DB_PASS = 'script' # if workstation DB_PATH = r'/Velocity/Databases/vscDatabase' # if grid DB_IP = '127.0.0.1' DB_PORT = 57000 # requires "OPT 3, CBCT adaptive" data IMPORT_DIR = "C:\demodata\O...
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def removeDuplicateNodes(self, head: ListNode) -> ListNode: has_set = set() orghead = head father = None while (head): if head.val in has_set: head...
# -*- coding: utf-8 -*- # Nox Obscura Guildpage # --------------------- from Servlet.Database import AbstractData class DataUser(AbstractData): """ Creates, maintaines and retrives the User-specific Datastructures. """ def __init__(self): # Inheritance Stuff AbstractData.__init__(self...
metadatapath = "./LIDC/LIDC-IDRI_MetaData.csv" list32path = "./LIDC/list3.2.csv" DOIfolderpath = './LIDC/LIDC-IDRI/' datafolder = './processeddata' import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import pydicom import os import scipy.ndimage import matplotli...
from typing import Any import json, logging, csv, sys import config as cn import udf as udf from models import models as db import env_vars import viewschema as vw import sqlalchemy_utils from sqlalchemy_utils import create_database from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, relation...
def save_to_file(sess, resp): filename = resp.request.path_url.split("/", 1)[1] with open('/tmp/%s' % filename, 'wb') as fd: for chunk in resp.iter_content(chunk_size=128): fd.write(chunk)
from blog.models import Blog from rest_framework import serializers from django.contrib.auth.hashers import make_password class BlogSerializer(serializers.ModelSerializer): class Meta: model = Blog exclude = []
import os from pathlib import Path import config as cfg def base_dir() -> str: return Path(os.path.abspath(os.path.dirname(__file__))).parent def app_root_dir(pvd: str) -> str: return os.path.join(base_dir(), cfg.DIR_APP_ROOT, pvd) def doc_root_dir() -> str: return os.path.join(base_dir(), cfg.DIR_DO...
# Function to create Encoder model def create_resnet_encoder(): inputs = Input(shape=(256, 256, 3)) t = BatchNormalization()(inputs) t = Conv2D(kernel_size=3, strides=1, filters=64, padding="same")(t) t = relu_bn(t) num_blocks_list ...
# coding: utf-8 # 1st Case study: # # The case study is about identifying a bank which wishes to use dimensions of the bank note to identify if it is fake or not. Data were extracted from images that were taken from genuine and forged banknote-like specimens. For digitization, an industrial camera usually used for p...
import csv import datetime from StudyBlock import StudyBlock import time def main(): studySub = input("Please enter the subject of study: ") input("Please enter when you start: ") startTime = datetime.datetime.now() print(startTime) input("Please enter when your are finished:") finishTime = d...
from mock_github_api.core import app from mock_github_api.helpers import response_from_fixture @app.route('/users') def users(): return response_from_fixture('user', True, paginate=True) @app.route('/users/<login>') def get_user(login): fixture = 'user' if login == 'alejandrogomez': fixture = 'u...
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index), url(r'^addshow$', views.addshow), url(r'^shows/(?P<id>\d+)$', views.showdetails), url(r'^shows$', views.mainshowpage), url(r'^shows/(?P<id>\d+)/destroy$', views.destroy), url(r'^shows/(?P<id>\d+)/edit$...
################################################################################ # Drive motors for rotor control # 2018 M. Tossaint ################################################################################ from gpiozero import Motor from time import sleep # Motor A, az Side GPIO CONSTANTS PWM_FORWARD_az_PIN =...
total = 0 num = int(input('Digite um numero: ')) for c in range(1, num +1): if num % c == 0:# vai ser testado se é divisivel de 1 até a num digitado. total += 1 #soma a quantidade de vezes que foi dividido com resposta 0 if total == 2: # apenas quando dividido 2 vezes é considerado um numero primo print...
#!/usr/bin/env python from os.path import join, realpath from hummingbot.strategy.market_trading_pair_tuple import MarketTradingPairTuple from decimal import Decimal import logging; logging.basicConfig(level=logging.ERROR) import pandas as pd from typing import List import unittest from hummingsim.backtest.backtest_ma...
class Solution: def minimumTotal(self, triangle): m = len(triangle) if m == 0: return 0 for i in range(m - 2, -1, -1): for j in range(len(triangle[i])): triangle[i][j] += min(triangle[i+1][j], triangle[i+1][j+1]) return triangle[0][0]
from django.contrib.auth.models import User from rest_framework import permissions from rest_framework import generics from apiv1.models import Car from apiv1.serializers import CarSerializer from apiv1.permissions import IsOwnerOrReadOnly, IsOwner class CarDetail(generics.RetrieveDestroyAPIView): '''Only user a...