text
stringlengths
8
6.05M
#this is boilerplate for making a flask app - flask is downloaded previously with the console "sudo pip3 install flask" command #the below takes the libraries flask and request from flask import Flask, request, render_template import os import datetime #the right below creates an app based in flask app = Flask(__name_...
def jumping_number(number): num = str(number) for i, n in enumerate(num[:-1]): subt = int(n)-int(num[i+1]) if subt!=1 and subt!=-1: return "Not!!" return "Jumping!!" ''' Definition Jumping number is the number that All adjacent digits in it differ by 1. Task Given a number, Fi...
""" Test script """ import os import copy import collections from time import time import torch import numpy as np import pandas as pd import scipy.ndimage as ndimage import SimpleITK as sitk import skimage.measure as measure import skimage.morphology as morphology from net.ResUNet import ResUNet from utilities.calc...
""" Module with handy utilities for plotting genomic signal """ from itertools import groupby import matplotlib from matplotlib import pyplot as plt import numpy as np from scipy import stats from statsmodels.sandbox.stats.multicomp import fdrcorrection0 def nice_log(x): """ Uses a log scale but with negative...
import os from datetime import timedelta from django.core.management.base import BaseCommand from django.utils import timezone from pdfwebsite.models import File class Command(BaseCommand): help = 'Removes files that are more than an hour old' def handle(self, *args, **kwargs): time_threshold = tim...
from Site import * class magiccardmarket(Site): def nextPage(): return "" def extract(self): print self.html.encode('utf-8') return ' ' ourTable = [] #State we keep track of inURL = False #debut d'une balise image tagStart = self.html.find("<img", 0) while( tagStart != -1)...
import logging import time import io from . import projection from . import simple_downloader from PIL import Image class TimeMachine(object): def __init__(self, dm_map): self._dm_map = dm_map # self.dynmap = dynmap.DynMap(url) def capture_single(self, map, t_loc, size, pause=0.25): ...
from flask_restful import Resource class HealthcheckResource(Resource): def get(self): """ This is a helthcheck endpoint --- responses: 200: description: healthcolor """ return {"status": "green"}, 200
#!/usr/bin/env python from fsevents import Observer from fsevents import Stream from googlestorage import Googlestorage """ Bit Description IN_ACCESS File was accessed (read) (*) IN_ATTRIB Metadata changed (permissions, timestamps, extended attributes, etc.) (*) IN_CLOSE_WRITE ...
def creer_pile(): '''pour crťer une pile''' return [] def empiler(ma_pile,valeur): '''ajoute une valeur √† la pile''' ma_pile.append(valeur) def depiler(ma_pile): '''retire le dernier √©l√©ment de la pile''' assert len(ma_pile)>0 return ma_pile.pop() def sommet(ma_pil...
''' File name: convert_coords_wExons.py Author: Patrick Monnahan Date created: 09/01/18 Python Version: 3.6 Project: Split Genes Downstream of: get_boundary_exons.py Upstream of: make_psuedo_annotation.py Description: For first/last exon pairs in the provided bed file, this script conver...
from django.test import TestCase from django.contrib.auth.models import User import mock from projects.models import ( ProjectBuild, ProjectDependency, ProjectBuildDependency) from projects.helpers import ( build_project, build_dependency, archive_projectbuild, get_transport_for_projectbuild) from .factori...
from django.template import loader from django.http import HttpResponse, HttpResponseRedirect from forms import BlogEntry from models import blog from markdown2 import Markdown def index(request): if 'username' not in request.session: return HttpResponseRedirect('../login') temp = loader.get_template(...
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Build a .gyp that depends on 2 gyp files with the same name. """ import TestGyp test = TestGyp.TestGyp() test.run_gyp('all.gyp', chdi...
# -*- coding: utf-8 -*- """ It's a parser which find connection between abbreviation and full name of dictionary DONE: - Input/Output - Go to every dictionary and find full name and abbreviation TO DO: - All is already done, you should only run the spider - Maybe rewrite code for use Pandas as table engine instea...
# -*- coding: utf-8 -*- import itertools class Solution: def maxProduct(self, words): lengths = [len(word) for word in words] bits = [0] * len(words) for i, word in enumerate(words): for c in word: bits[i] |= 1 << (ord(c) - ord("a")) result = 0 ...
# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import json from textwrap import dedent import pytest from pants.backend.javascript import package_json from pants.backend.javascript.dependency_infere...
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2015 Bitergia # # 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 3 of the License, or # (at your option) any later versio...
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-03-18 21:00 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('common', '0005_prescription...
import os.path as path import pickle as pkl from bibpdf.config import config __author__ = 'Keji Li' def find_folder(full_path): folder, sub_folder = path.split(full_path) if sub_folder != "Paper": return find_folder(folder) + [sub_folder] else: return [] data = pkl.load(open(config['pa...
import logging # # def func(self, filename="text_logs_help_links.log", name="logs.log"): # # logging.basicConfig(filename=filename, # level=logging.INFO, format='%(asctime)s %(levelname)-8s %(message)s') # logger = logging.getLogger(name) # console = logging.StreamHandler() # lo...
# 10870번 피보나치수 5 # https://www.acmicpc.net/problem/10870 def star(x, y): for n in range(x): for m in range(y): i = int(n/3) if i==1: if n%3==1 and m%3==1: print(" ") else: print("*") else : ...
# Python Imports from xml.dom import minidom from threading import Thread, Timer import time # Local Imports import globals from helpers import * from yamaha_xml import * def send_any(self, value, action): if action == "Put": put_xml(self, value) else: #now find param #to do this, pars...
import pygame from engine.gameobject import GameObject class CardInfo(GameObject): def __init__(self, card, parent, app): GameObject.__init__(self, None, (55, 140), parent, app) self.card = card self.last_power = card.power self.text_power = self.app.font.render(f"{self.card.power}...
import eventClass import tweepy import auth import database api1 = tweepy.API(auth.auth) #print(api1.direct_messages(count=100)[0].text)x #print(api1.direct_messages(count=100, since_id=0)[1].text) numDM = len(api1.direct_messages()) #print("Number of DMs: ", numDM) ###print(api1.direct_messages(count=200)[i].sender_...
""" Model objects for mimic flavors. """ from __future__ import absolute_import, division, unicode_literals import attr @attr.s class Flavor(object): """ A Flavor object """ flavor_id = attr.ib() tenant_id = attr.ib() name = attr.ib() ram = attr.ib() vcpus = attr.ib() rxtx = attr...
# hard # bfs + 剪枝 class Solution: def minJump(self, jump: List[int]) -> int: n = len(jump) step = 0 # mx表示其左边弹簧都已经访问过了 # 0为初始访问,所以从1开始 mx = 1 q = deque([0]) while q: # 每一次循环表示在step下能到达的弹簧 tempSize = len(q) for i in range(te...
## Santosh Khadka # two.py import one def func(): print("Func() in two.py") one.func() if __name__ == "__main__": # runs the code here if this file/program is being run directly - not called in another script print("two.py is being run directly!") else: print("two.py has been imported!")
import csv import sys #type into command line on Biowulf: #python compilation_filter.py ref_seq_with_IUPAC allele_table_1 ... allele_table_n # #ref_seq_with_IUPAC = reference sequence with IUPAC # (to account for heterozygous SNPs unique to a specific macaque) #allele_table_n = alleles frequency ta...
import os import sys def convert_bytes(num): for size in ['bytes', 'KB', 'MB', 'GB', 'TB']: if num < 1024.0: return "%3.1f %s" % (num, size) num /= 1024.0 def file_size(file_path): if os.path.isfile(file_path): print("This is file") file_info = os.stat(file_path) ...
#!/usr/bin/env python """ Customised serilier """ import os import marshal import ujson as json ser_type = os.environ["ser_type"] def load(ser_file_handle): if ser_type == "marshal": return marshal.load(ser_file_handle) else: return json.load(ser_file_handle) def dump(obj, ser_file_handl...
from .basic_nodes import DerivedCSVProcessingNode, DerivedJSONProcessingNode, \ OriginalProcessingNode from .view_nodes import DerivedPreviewProcessingNode from .output_nodes import OutputToZipProcessingNode from .report_nodes import ReportProcessingNode ORDERED_NODE_CLASSES = [ ReportProcessingNode, Deri...
#! /usr/bin/python import pandas as pd import matplotlib.pyplot as plt import numpy as np raw_data = {'graph': ['Youtube', 'LiveJournal', 'Pokec', 'RMAT-19-32', 'RMAT-21-32'], 'cache': [16.1344/16.1344, 90.5813/90.5813, 32.1934/32.1934, 12.6965/12.6965, 50.7354/50.7354], 'hash': [16.1344/5.5074, 90.58...
# -*- coding: utf-8 -*- # @Time : 2018/4/5 12:22 # @Author : Andywei # @Email : andycfa2@163.com # @File : pandas 1.py # @Software: PyCharm # pandas 绘图练习 import matplotlib.pyplot as plt #显示图片 import pandas as pd import numpy as np from pylab import mpl #解决中文显示乱码 import seaborn as sns #设置中文字体 mpl.rcParams['f...
class TleParser: CELESTRAK = 1 # Describe a TLE structure CELESTRAK_BP = { 0: { 'name': { 'start': 0, 'end': 23, } }, 1: { 'line_number': { 'start': 0, 'end': 1, }, ...
from page.base import Base import logging from runlog import testLog class Contact(Base): """联系人应用的所有页面操作类,此类中的d可以直接使用u2的所有方法""" def __init__(self): self.contact_info = self.get_data('contact.yaml') def click_add_bt(self): """点出联系人新建按钮""" self.mclick(resourceId=self.contact_info...
a = input("Enter a string:") b = input("Enter a char:") i=0 m=0 x = len(a) while (i<x): if(b == a[i]): m+=1 i+=1 print(m)
import random from functools import reduce import torch from torch.utils import data from torch.autograd import Variable from util import * from harry import HarryPotterText class HarryPotterTextDataset(data.Dataset): def __init__(self, root="data", num_copies=10): self.harry = HarryPotterText(book_dir=...
def b_search(arr, zero, lenghtOfArr, mynum): while zero <= lenghtOfArr: middle = zero + (lenghtOfArr - zero) // 2; if arr[middle] == mynum: return middle else: if arr[middle] < mynum: zero=middle+1 else: ...
# 区间dp,之前刷csp时都只做过几题类似的... # 模板,O(n^3),不出意外的超时了 class Solution: def stoneGameV(self, stoneValue: List[int]) -> int: n = len(stoneValue) presum = [0]*(n+1) for i in range(n): presum[i+1] = presum[i] + stoneValue[i] f = [[0] * n for _ in range(n)] # 先枚举长度,再枚举起点,最...
import uuid from unittest.mock import patch import pytest import s3fs from rubicon_ml import domain from rubicon_ml.repository import S3Repository from rubicon_ml.repository.utils import slugify def test_initialization(): s3_repo = S3Repository(root_dir="s3://bucket/root") assert s3_repo.PROTOCOL == "s3" ...
import os, re, hmac, random, string, webapp2, logging, jinja2, hashlib, json, logging from google.appengine.ext import db ### template helpers template_dir = os.path.join(os.path.dirname(__file__), 'templates') jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape=True) ### Main ha...
import pytest from belt import get_belt @pytest.mark.parametrize("input_argument, expected_return", [ (0, None), (9, None), (10, 'white'), (48, 'white'), (50, 'yellow'), (101, 'orange'), (249, 'green'), (250, 'blue'), (251, 'blue'), (400, 'brown'), (599, 'b...
#!/usr/bin/python from kestrelcli import cli if __name__ == '__main__': cli.main()
''' Created on 2017年2月28日 @author: admin ''' #!D:\python35\python.exe #encoding=UTF-8 print ('Content-type: text/html\n') from os.path import join, abspath import cgi, sys BASE_DIR = abspath('data') form = cgi.FieldStorage() filename = form.getvalue('filename') if not filename: print('Please enter a file name')...
#<Point 클래스의 메쏘드 (연산자 오버로딩 포함)> """메쏘드에는 __init__,__str__,__len__ 등과 같이 magic method라 불리는 특별한 메쏘드와 일반 메쏘드로 구분할 수 있다 magic method의 이름은 두 개의 underscore로 메쏘드 이름을 감싼 형태이다. """ class Point: def __init__(self, x=0, y=0): self.x = x self.y = y def __str__(self): return f"({self.x}, {self.y})...
#导入所有依赖包 import flask import werkzeug import os import getConfig import numpy as np import execute from PIL import Image #初始化一个字典,用于存放从配置文件中获取的配置参数 gConfig = {} #使用get_config方法从配置文件中获取配置参数 gConfig = getConfig.get_config(config_file='config.ini') #创建一个flask wen应用,名称为imgClassifierWeb app = flask.Flask("imgClassifierWeb"...
################################################################################## # This file searches nature journal for the the date published, the article title, # and the journal it was published in ################################################################################## from bs4 import BeautifulSoup im...
from charm.schemes.dabe_aw11 import Dabe from charm.adapters.dabenc_adapt_hybrid import HybridABEncMA from charm.toolbox.pairinggroup import PairingGroup, GT import unittest debug = False class DabeTest(unittest.TestCase): def testDabe(self): groupObj = PairingGroup('SS512') dabe = Dabe(groupObj)...
from marshmallow import Schema, validate, fields class VideoSchema(Schema): id = fields.Integer(dump_only=True) user_id = fields.Integer(dump_only=True) name = fields.String(required=True, validate=validate.Length(max=250)) description = fields.String(required=True, validate=validate.Length(max=500)) ...
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2019-01-21 09:58 from __future__ import unicode_literals from datetime import date from django.db import migrations class Migration(migrations.Migration): def calculate_age(apps, schema_editor): Profile = apps.get_model('registration', 'Profile') for prof...
import cv2 import numpy as np import json import os import pandas as pd # 이미지읽기 img = cv2.imread('../0706_data/dog.jpg') c_img = cv2.imread('../0706_data/cat.jpg') # 너비, 높이, RGB(색상) print(img.shape) # 이미지 저장 # cv2.imwrite('copy_img.jpg',img) # cv2.imshow('dog',img) # cv2.waitKey() # 색 변화 컨버터 c...
#!/usr/bin/env python3 from ev3dev2.motor import MoveSteering, MoveTank, MediumMotor, LargeMotor, OUTPUT_A, OUTPUT_B, OUTPUT_C, OUTPUT_D from ev3dev2.sensor.lego import TouchSensor, ColorSensor, GyroSensor from ev3dev2.sensor import INPUT_1, INPUT_2, INPUT_3, INPUT_4 import xml.etree.ElementTree as ET import threading ...
# Generated by Django 3.1.3 on 2020-11-17 13:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('library', '0002_auto_20201117_1850'), ] operations = [ migrations.AddField( model_name='profile', name='adhar_card',...
from pymongo import MongoClient # connect to database connection = MongoClient('localhost', 27017) db = connection.school # handle to names collection students = db.students1 cursor = students.find() hws = {} # name : [{"_id": score}] import sys for s in cursor: score = sys.maxint _id = s["_id"] hw =...
import matplotlib.pyplot as plt import numpy as np max_iters = 10000 precision = 0.0001 gammas = np.linspace(0.001, 0.01, 10) fct = lambda x: 4 * x**3 - 9 * x**2 def gradient(gamma): iters = 0 cur_x = 6 previous_step_size = 1 x = [] while (previous_step_size > precision) &...
def tableMulti(base, debut, fin): print('fragment de la table de multiplication par', base, ":") n= debut while n <= fin : print(n, "x" , base, "=" , n * base) n= n + 1 def table(base): resultat = [] n = 1 while n< 11: b = n * base resultat.append(b) n=...
import urllib.parse import requests def run(): url='https://maps.googleapis.com/maps/api/geocode/json?address=Alfredo+mendiola+3540,+CA&key=AIzaSyC5guRUsYSgt9ADNt5LCOOoHc9p48oG2io' json_data = requests.get(url).json() country = json_data['results'][0]['address_components'][5]['long_name'] print(...
from pymongo import MongoClient from flask import Flask, render_template, request, session from random import randint app = Flask(__name__) client = MongoClient('mongodb+srv://admin:<password>@cluster0-w1ulm.mongodb.net/test?retryWrites=true&w=majority') db = client['hackathon'] playerScores = db['playerScore...
from selenium import webdriver import time # 크롬창(웹드라이버) 열기 driver = webdriver.Chrome("./chromedriver.exe") # 구글 지도 접속하기 driver.get("https://www.google.com/maps/") # 검색창에 "카페" 입력하기 searchbox = driver.find_element_by_css_selector("input#searchboxinput") searchbox.send_keys("카페") # 검색버튼 누르기 searchbutton = driver.find_...
from flask import Flask from flask import request from namegen import NameGenerator app = Flask(__name__) namegen = NameGenerator() @app.route('/post', methods=['POST']) def get_name(): sourceCode = request.form['source'] print(sourceCode) name, attention = namegen.get_name_and_attention_for(sourceCode...
""" интерполяция функции на таблице значений с помощью полинома Ньютона (с учетом экстраполяции) """ from math import sin, pi, factorial, cos, exp def f(x): return exp(x) def generate_table(start, end, step): table = [] table.append([]) table.append([]) x = start while(x < end + step): ...
import turtle, math def square(t,length): angle = 90 #degrees in square for i in range(4): t.fd(length) t.lt(angle) def polygon(t,length,sides): angle = 360 / sides for i in range(sides): t.fd(length) t.lt(angle) def circle(t,radius): sides = 100 angle = 360 / sides circumference = 2 * math.pi * ...
class Student: def __init__(self, name, school): self.name = name self.school = school self.mark = [] def average(self): return sum(self.mark) / len(self.mark) class WorkingStudent(Student): def __init__(self, name, school, salary): super(WorkingStudent, self).__ini...
#!/usr/bin/env python """ npy.py ======= Demonstrates sending and receiving NPY arrays and dict/json metadata over TCP socket. To test serialization/deserialization:: npy.py --test In one session start the server:: npy.py --server In the other run the client:: npy.py --client The client sends an arr...
from django.db import models from django.utils.timezone import now #当前时间 from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth.models import User GENDER = { ('m','man'), ('w','woman'), ('s','secret') } class BlogUser(models.Model): user = models...
""" 剑指 Offer 52. 两个链表的第一个公共节点 输入两个链表,找出它们的第一个公共节点。 """ class ListNode: def __init__(self, x): self.val = x self.next = None """ 思路其实很简单,大概是有两个方法,先说第一种,就是让两个链表尾端对齐,然后从头向后一起捋,就能找到了,大概时间复杂度是2n,其实就是n。 """ def getIntersectionNode(headA: ListNode, headB: ListNode) -> ListNode: ahead, bhead = headA, headB ...
# -*- coding: utf-8 -*- BASE_INDENT_SIZE = 4
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np import matplotlib.pyplot as plt import pandas as pd import math import sklearn.preprocessing as sk import seaborn as sns from sklearn import metrics from sklearn.feature_selection import VarianceThreshold ...
n = int(input()) a = [None]*n ans = 1 for x in range(n): a[x] = list(input()) for x in range(n-1): if(a[x][1] == a[x+1][0]): ans += 1 print(ans)
array = [1, 2, 3, 4] new_array = [] new_array = [None] * len(array) for i in range(len(array)): new_array[i] = array[len(array) - 1 - i] print(new_array)
# Generated by Django 2.2.10 on 2020-02-23 03:07 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), ('cou...
from pyfa_ng_backend import create_app app = create_app()
#!/usr/bin/env python import pickle import io from lab_defs import teaching_length from lab_mc import experiments, tutorials, null_experiment experiments["LVT"] = tutorials["LVT"] from print_student import get_styles, swansea_logo from assign_students import get_students, match_students from loadstore import load_pa...
import numpy as np import pandas as pd data = pd.read_csv("./data/test0822.csv", delimiter=",") row_per_col = 50 x = data.iloc[:3113, 1:9] x = np.array(x) print(x.shape) test = data.iloc[3113-row_per_col:3113, 1:9] print(test.shape) x_len = 50 y_len = 5 sequence_length = x_len + y_len size = row_per_col + 5 re...
import time import threading from queue import Queue class Producer(threading.Thread): def run(self): global queue count=0 while True: if queue.qsize()<1000: for i in range(101): count+=1 msg='生成产品'+str(count) ...
import pygame pygame.init() win = pygame.display.set_mode((800,600)) pygame.display.set_caption("first game") x = 50 y = 50 width = 40 height = 60 vol = 5 run = True while run: pygame.time.delay(100) for event in pygame.event.get(): if event.type ==pygame.QUIT: run = False pygame.draw.rect(win,(255,0,0), (...
""" THIS module is for indexing the on page features of a URL here a collection is formed and each word is treated as document. Each document has a id from which it can be accessed. With each word a posting list is associated which has two attributes first the id of the URL and 2nd count of the number of times a wo...
import telepot import pandas as pd import csv import requests import json import time from collections import defaultdict token = 'TOKEN' chat_id = 'CHAT_ID' api_key = 'AIzaSyAVJcQ0549l7BnK62jvf3EnITtgeMJXuww' def gettelegram(): data=defaultdict(list) bot = telepot.Bot(token) count = 1 # p = 1 print(...
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-08-28 18:32 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('user_input', '0001_initial'), ] operations = [ migrations.RenameField( ...
import numpy.polynomial.polynomial as poly def lagrange(k,n): p = poly.Polynomial([1]) for i in range(1, n+1): if i != k: p = p*poly.Polynomial([-i,1]) / (k-i) return p def interp(l): p = poly.Polynomial([0]) for i, elem in enumerate(l): p += lagrange(i+1, len(l)) * ele...
#!/usr/bin/python # -*- coding: utf-8 -*- # generic speech driver from threading import Thread, Lock from queue import Queue, Empty import shlex from subprocess import Popen import time class speakQueue(Queue): def clear(self): try: while True: self.get_nowait() except...
import json from logging import Logger import core from core.schema import S1 class DataCopy: def __init__(self, log, data, data_d=None): """ @type log: Logger @type data: core.Data @type data_d: core.Data """ self.data = data self.data_d = data_d se...
# Copyright (C) 2017 Cuckoo Foundation. # This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org # See the file 'docs/LICENSE' for copying permission. from lib.api.process import Process from lib.core.ioctl import zer0m0n def dump_memory(pid): """Dump process memory using zer0m0n if available, otherwi...
from slack_sdk.models.dialoags import DialogBuilder # noqa from slack import deprecation deprecation.show_message(__name__, "slack_sdk.models.dialogs")
# Copyright (C) 2010-2013 Claudio Guarnieri. # Copyright (C) 2014-2016 Cuckoo Foundation. # This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org # See the file 'docs/LICENSE' for copying permission. import logging import os from _winreg import HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER from lib.common.abstr...
import args import z z.getp.quick_list = False import buy import os from sortedcontainers import SortedSet import gbuy_old import math date = "2000-01-01" dates = z.getp("dates") import delstock def process(astock, one_at_a_time = True): global problems try: problems = [] print("date: {}".for...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import tensorflow as tf #https://jalammar.github.io/visual-interactive-guide-basics-neural-networks/ ##load the data #dataset has different attributes of the houses that are sold data=pd.read_csv('data1.csv') #now we will classify the house whet...
# -*- coding: utf-8 -*- """Functions for simulations. """ import numpy as np __all__ = ['shepp_logan'] def shepp_logan(shape, dtype=np.complex): """Generates a Shepp Logan phantom with a given shape and dtype. Args: shape (tuple of ints): shape, can be of length 2 or 3. dtype (Dtype): data ...
# Курс Python: основы и применение # Задача 3, блок 2.1. Ошибки и исключения ''' Алиса владеет интересной информацией, которую хочет заполучить Боб. Алиса умна, поэтому она хранит свою информацию в зашифрованном файле. У Алисы плохая память, поэтому она хранит все свои пароли в открытом виде в текстовом файле. Бобу ...
#!/usr/bin/python3 from datetime import datetime from faker import Faker import psycopg2 import time import os BATCH_SIZE = 20 UPDATE_FREQUENCY = 10 ITERATION = 100 HOSTNAME = 'localhost' fake = Faker() Faker.seed(datetime.now()) def insert_user_record(connection, cursor): print("inserting records to user tab...
#converte o byte lido no PLC para seu respectivo tipo from model.Measur import MS import logging def loadMeasur(tags): try: mss = {} mss['G01'] = MS("G01",5) mss['G02'] = MS("G02",5) mss['G03'] = MS("G03",10) mss['G04'] = MS("G04",10) for ms in mss.values(): ...
# Generated by Django 2.2.1 on 2019-07-28 14:01 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('notice', '0014_auto_20190728_2258'), ] operations = [ migrations.AlterModelOptions( name='notice', options={'ordering': ['-i...
def balancedBrackets(string): # Write your code here # Space: O(n) n = length of string # The worst case scenario: All of the string would be brackets that are unmatched and stack would be length n. # Time: O(n) n = length of string # This dictionary's purpose is to make it easier to check fo...
import face_recognition import cv2 import os import smtplib from email.message import EmailMessage import imghdr import datetime EMAIL_ADDDRESS = os.environ.get("EMAIL_ADDRESS") EMAIL_PASSWORD = os.environ.get("EMAIL_PASSWORD") Time = datetime.datetime.now() KNOWN_FACE_DIR = "Known_faces" Known_faces_encoding = [] Kno...
# Given the array nums consisting of 2n elements in the form # # [x1,x2,...,xn,y1,y2,...,yn]. # # Return the array in the form [x1,y1,x2,y2,...,xn,yn]. class Solution: def shuffle(self, nums, n): return nums if [nums.insert((n - i), nums.pop()) for i in range(n)] != 0 else...
def main(): incomes = [] number_of_months = int(input("How many months? ")) # user enters number of months they want to calculate. for month in range(1, number_of_months + 1): income = float( input("Enter income for month {}: ".format(month))) incomes.append(income) # user can i...
import os import re import psycopg2 import logging import datetime import itertools from flask import Blueprint, render_template, redirect, request, \ g, url_for, abort, config, current_app, session, flash, jsonify, Response from models import * from auth import * from utils import * from resources import * from...
from setuptools import setup __version__ = '1.0.0' setup( name='putils', version=__version__, description='Python2.7 utilities frequently used ', author='Dongwon Kim', author_email='dkim010@gmail.com', url='https://github.com/dkim010/putils', license='Apache-2.0', packages=['putils'], ...
import requests hello = "https://www.googleapis.com/youtube/v3/channels?part=statistics&id=UCpNooCUr-Q01rjgqxzjvztg&key=AIzaSyC4ucWTSN3s7d4KrqJ9ZOYZ-ezvzwTSGsg"; request = requests.get(hello); reallist = ['\"','{','}','\n',']'] data = request.content; sdata = data; for character in reallist: sdata = sd...