text
stringlengths
38
1.54M
from tkinter import * root = Tk() root.title("File Handling") root.geometry("500x300") def open_file(): global text1 text1.set("") if entry_window.get(): file = open(entry_window.get(),'r') for each in file: text1.set(each) def create_file(): global text1...
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-01-12 15:32 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('logsys', '0010_auto_20170112_1741'), ] operations = [ migrations.AlterField...
class Solution: def largestSumOfAverages(self, A: List[int], K: int) -> float: """ dp[i][j] = dp[i0][j-1] + cal(i0, j) """ n = len(A) pre_sum = [0] * n pre_sum[0] = A[0] for i in range(1, n): pre_sum[i] = pre_sum[i - 1] + A[i] def cal(i, j...
from flask import request from flask_restful import Resource from http import HTTPStatus from flask_jwt_extended import get_jwt_identity, jwt_required, jwt_optional from models.reservation import Reservation from schemas.reservation import ReservationSchema reservation_schema = ReservationSchema() reservation_list_sch...
# -*- coding: utf-8 -*- import tensorflow as tf import pandas as pd import numpy as np import os import sys import csv sys.path.append('../utils') import segmentation_dataset import input_generator from loss import loss from quantization import QG from deeplab_v3 import Deeplab_v3 import scipy.misc as misc note = "std...
import time, pygame pygame.init() pygame.mixer.init() n = input("Enter time in seconds ") def main(): pygame.mixer.music.load("0897.wav") time.sleep(n) pygame.mixer.music.play() time.sleep(5) if __name__ == '__main__': main()
<<<<<<< HEAD #to create database and collection from pymongo import MongoClient import pymongo import time class database: client = MongoClient('localhost',27017) DB = client.libdb book = DB.book; user = DB.user lend = DB.lend @staticmethod def indexc(): database.book.create_index([("bkid",pymongo.ASCENDING)],...
from helpers.data_source_fixture import DataSourceFixture def test_pandas_df(data_source_fixture: DataSourceFixture): import duckdb import pandas as pd con = duckdb.connect(database=":memory:") test_df = pd.DataFrame.from_dict({"i": [1, 2, 3, 4], "j": ["one", "two", "three", "four"]}) scan = dat...
from twisted.words.protocols import irc from twisted.internet import reactor, protocol import sys from collections import deque, defaultdict from subprocess import Popen, PIPE from twisted.python import log def getQueue(): return deque([], 50) class SedBot(irc.IRCClient): nickname = 'sedbot' channels = ['#avo', '#...
from margot import Symbol, MargotDataFrame, Ratio, BaseAlgo, Position, BackTest from margot import finance, cboe, alphavantage as av # def test_algo(): # class Index(Symbol): # close = cboe.Column(time_series='close') # class VXBasis(MargotDataFrame): # vixm = Index(symbol='VIX', trading_cal...
odd_even = int(input('Enter a number: ')) a = odd_even % 2 b = odd_even % 4 if a != 0: print('The number is odd') if a == 0 and b != 0: print('The number is even') elif a == 0 and b == 0: print('The number is a multiple of 4 and it is also even')
# Generated by Django 2.1.1 on 2018-09-06 19:38 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('api', '0001_initial'), ] operations = [ migrations.RenameField( model_name='topic', old_name='flag', new_name='a...
import math n=2 primes = [] while len(primes)<10001: i = 2 check = True while (i<=math.sqrt(n)): if(n%i==0): check = False break i +=1 if(check): primes.append(n) n+=1 print primes[-1] print primes[10002] #Put a number to check if it is prime: ...
from flask import Flask, render_template, request, url_for, redirect, flash import datetime import csv from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker, session import os from werkzeug.utils import secure_filename import os.path UPLOAD_FOLDER = 'd:/cs50/flask/static/uploads'...
from rest_framework import serializers from .models import User, Rol from rest_framework.validators import UniqueValidator from django.utils.crypto import get_random_string from django.core.mail import EmailMessage from django.http import HttpResponseRedirect class UserSerializer(serializers.ModelSerializer): user...
from collections import deque from itertools import combinations def find_subarray(data, target): curr_sum = data[0] start, idx = 0, 1 size = len(data) while idx <= size: while curr_sum > target and start < idx - 1: curr_sum = curr_sum - data[start] start += 1 ...
# -*- coding: utf-8 -*- """ A few utility methods used by various other files. Created on Sat May 3 12:33:42 2014 @author: brian """ from datetime import datetime import math program_start = datetime.now() #A convenient print statement for long runs - also includes a timestamp at the beginning of the message #Argum...
#!/usr/bin/python3 # Description: gives the sum of 2 numbers # Author: Paul hivert # Date: 15/10/2018 import sys print("choisi un nombre") value1 = input() try: value1 = int(value1) except: sys.exit("please enter a number") print("choisi un autre nombre") value2 = input() try: value2 = int(value2) except: ...
from tests.admin_test import AdminTestCase from tests.bass_test import BassTestCase from tests.user_test import UserTestCase class TestAnonAdminView(BassTestCase): def test_denied(self): for url in '', 'users/', 'users/edit/1', 'files/', 'files/a': rv = self.app.get('/admin/{}'.format(url)) ...
from tkinter import * from tkinter import ttk from datetime import datetime, timedelta class Input_Popup: def __init__(self, type, parent=None, data=None): #type options: new_meal, new_ingredient, new_instruction, edit_meal, edit_ingredient, edit_instruction self.done = False self.rv_dat...
# Copyright Contributors to the Amundsen project. # SPDX-License-Identifier: Apache-2.0 from typing import Optional import attr from marshmallow3_annotations.ext.attrs import AttrsSchema @attr.s(auto_attribs=True, kw_only=True) class DashboardQuery: name: Optional[str] = attr.ib(default=None) url: Optional[...
from picamera.array import PiRGBArray from picamera import PiCamera import time import numpy as np import cv2 import sys, pygame from modules2 import * import csv import math from PIL import Image #generate a list of hex center locations in the hex coordinate sytem def generateCubicHex(BOARD_SIZE): zone_list_hex...
import sys sys.stdin = open("D1_6243_input.txt", "r") # data = ','.join(sorted(list(set(list(map(str, input().split())))))) # print(data) print(','.join(sorted(list(set(list(map(str, input().split())))))))
from naive_bayes.tokenizer import Tokenizer from naive_bayes.email_object import EmailObject from naive_bayes.spam_trainer import SpamTrainer __all__ = [ "tokenizer" ]
########### Python 3.5 ############# import http.client, urllib.request, urllib.parse, urllib.error, base64, json, pickle apiFile = open('secrets.txt', 'r') apiKey = apiFile.readline().replace("\n", "") headers = { # Request headers 'Ocp-Apim-Subscription-Key': apiKey, } # 12 Months of the year months = ['J...
""" This tests all requests made by the pyvesync library with pytest. All tests inherit from the TestBase class which contains the fixtures and methods needed to run the tests. The `helpers.call_api` method is patched to return a mock response. The method, endpoint, headers and json arguments are recorded in YAML fil...
import sys import time # Initialize debugMode = False # Set to true to switch on debug mode n = 0 allPersons = [] #array menPrefs = [] #array womenPrefs = [] #array # Functions def isInt(i): try: int(i) return True except ValueError: return False # Read parameters if ((len(sys.argv) ...
from django.shortcuts import render from os.path import isdir, dirname, join from os import mkdir from .settings import BASE_DIR import pandas as pd def home(request): context = {} return render(request, 'index.html', context) def upload(request): if request.method == 'POST': uploadDir = BASE_DIR+...
# Generated by Django 3.1.4 on 2021-02-28 17:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('toys', '0002_auto_20210228_2220'), ] operations = [ migrations.RemoveField( model_name='company', name='employee', ...
s = input() a = [] for i in range(len(s)): if s[i:i+10] in s[i+10:]: a.append(s[i:i+10]) print(a)
''' This file computes the k size required to tolerate against an adversary who joins his mining power to fill the queue of an honest miner. ''' import sys import math import numpy as np import matplotlib.pyplot as plt from decimal import * getcontext().prec = 400 ''' Results from Previous Runs 0. 1x Scalabili...
import cv2 from darkflow.net.build import TFNet import numpy as np import time option1 = { 'model': 'cfg/tiny-yolo-voc-nofight.cfg', 'load': 16500, 'threshold': 0.1, 'gpu': 1.0 } option2 = { 'model': 'cfg/tiny-yolo-voc-1c.cfg', 'load': 35250, 'threshold': 0.15, 'gpu': ...
"""Ontology converter.""" import logging from dataclasses import dataclass, field from pathlib import Path from typing import Dict, List, Optional from linkml_runtime import SchemaView from linkml_runtime.utils.formatutils import camelcase from oaklib.datamodels.obograph import Graph from oaklib.datamodels.vocabulary ...
# # Copyright (c) 2023 Airbyte, Inc., all rights reserved. # from abc import ABC from typing import Any, Iterable, List, Mapping, MutableMapping, Optional, Tuple import pendulum import requests from airbyte_cdk.sources import AbstractSource from airbyte_cdk.sources.streams import Stream from airbyte_cdk.sources.stre...
import sys input = sys.stdin.readline N, K = map(int, input().split()) multitap = list(map(int, input().split())) plugs = [] count = 0 for i in range(K): if multitap[i] in plugs: continue if len(plugs) < N: plugs.append(multitap[i]) continue multitap_idxs = [] hasplug = True for j in ...
#!/pkg/qct/software/python/3.5.2/bin/python ################################################################################### # Filename: emailDiskAbusers.py # Author: cskebriti # Description: Standalone program, does NOT require setup/config.py # ''' Takes the argument passed from command line and runs a check to f...
# wbite - pokazać import numpy as np # #- pewny pełny # .- pewny pusty # ?- nierozpatrzony def all_arrangements(len_row, ch): def h(len_row, ch): sum_ch = sum(ch) len_ch = len(ch) if len_ch == 0: yield '.'*len_row else: for start in range(len_row-sum_ch-len...
""" This module deals with authorizing users for access via HTTP simple authentication. When the password is received it is hashed using SHA-256 and compared against the hash in the database for that user.""" from functools import wraps import hashlib from flask import request, Response from chkphrase.models import Use...
import vtk import numpy as np import pydicom as dicom import platform import os import time import vtk.util.numpy_support as vtknp import glob import re minValGr = 0.0 # Skalierung der Grauwerte maxValGr = 255.0 diffValGr = maxValGr - minValGr countList = [] count = -1 # # # # # # # # # # # # # # # # # # # # # # #...
class Config(): images_folder = './data/RSICD/RSICD_images/' annotations_name = './data/RSICD/dataset_rsicd.json' # pretrain model config pre_train_model = 'mobilenet' fix_pretrain_model = False feature_size = 1280 # pretrain model's feature map number in final layer # Attention l...
#!/usr/bin/python import griddb_python as griddb import sys factory = griddb.StoreFactory.get_instance() argv = sys.argv NumContainer = 10 NumRow = 2 try: gridstore = factory.get_store(host=argv[1], port=int(argv[2]), cluster_name=argv[3], username=argv[4], password=argv[5]) print("[MultiGet S]") predEntry = ...
import torch import torch.nn as nn from torch.autograd import Variable import random class ImagePool(): def __init__(self, pool_size): self.pool_size = pool_size if self.pool_size > 0: self.num_imgs = 0 self.images = [] def query(self, images): if self.pool_size...
# Program to gather your followers and people who you follow, difference them and find out the people who you follow but dont follow you back. # Youtube Tutorial link: https://www.youtube.com/watch?v=BGU2X5lrz9M # Requirements: # - Gecko # - Selenium # - Python 3.6 or above """ Importing the requi...
# -*- coding: utf-8 -*- from odoo import models, fields, api class velo_pop_pipeline(models.Model): _name = 'pop.pipeline.test' _description = 'Model Menu POP Pipeline' _rec_name = 'name' name = fields.Char(string="Name") description = fields.Char(string="Description") class velo_pop_pipeline_ma...
""" Даны два целочисленных списка A и B, упорядоченных по неубыванию. Объедините их в один упорядоченный список С (то есть он должен содержать len(A)+len(B) элементов). Решение оформите в виде функции merge(A, B), возвращающей новый список. Алгоритм должен иметь сложность O(len(A)+len(B)). Модифицировать исходные списк...
import pygame import math class Ship: ''' Coords: 4: back points 4: front points 3: top wing 1: front tip 2: tip wings ''' verticies = \ (-3, -1, 1), ( -3, 1, 1), (-3, -1, -1), (-3, 1, -1), \ (3, -1, 1), (3, 1, 1), (3, -1, -1), (3, 1, -1),...
# -*- coding: utf-8 -*- # 隐语义模型 import pickle import pandas as pd import numpy as np from math import exp def loadDataFrom2PKL(pklName1 ,pklName2): f1 = open(pklName1,'rb') UserMovieDict = pickle.load(f1) f1.close() f2 = open(pklName2,'rb') MovieUserDict = pickle.load(f2) f2.close()...
from sqlalchemy import Boolean, Column, Date, Integer, String from app.api.db.baseClass import Base class User(Base): id = Column(Integer, primary_key=True, index=True) username = Column(String(32), unique=True, index=True, nullable=False) nickname = Column(String(32)) sex = Column(String(8), doc="性别...
''' Copyright 2011, 2012 Timothy Hunter <tjhunter@eecs.berkeley.edu> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3. This lib...
import csv, smtplib, ssl, xlrd, openpyxl, datetime, subprocess, argparse, n2w, warnings import pandas as pd to_address = "tripdirector@kandalore.com" import gmailapppassword from_address = gmailapppassword.username password = gmailapppassword.password my_parser = argparse.ArgumentParser() my_parser.add_argument('-t...
import os products = [] if os.path.isfile("products2.csv"): #检查档案是否存在 print("找到档案了!") with open("products2.csv", "r", encoding = "gb2312") as f: for line in f: if "商品,价格" in line: continue name, price = line.strip().split(",") products.append([name, price]) print(products) else: print("找不到档案.") #让使...
#1059-pares-e-impares # entrada N = int(input()) impar = [] par = [] for i in range(N): numero = int(input()) if (False == (numero % 2 == 0)): impar.append(numero) elif (True): par.append(numero) impar.sort(reverse=True) par.sort(reverse=False) for i in range(len(par)): print(par[i]) f...
import sys sys.stdin=open('다솔이.txt','r') n=int(input()) for tc in range(1,n+1): string=input() if len(string)==1: dia=[[0]*5 for i in range(5)] for y in range(5): if y==0 or y==4: dia[y]=['.','.','#','.','.'] elif y==1 or y==3: dia[y]=['.',...
import unittest from player import Player from throw import Throw class TestPlayer(unittest.TestCase): def test_player_name_is_set(self): player = Player('Phil', 100) self.assertEqual('Phil', player.name) def test_player_score_is_set(self): player = Player('Phil', 100) self.assertEqual(100, playe...
import pandas as pd import numpy as np import os import sys from collections import defaultdict DEBUG =1 def process_input_file(filename, sep='|'): fin=open(filename,'r') degree_dict=defaultdict(lambda: defaultdict(int)) first=0 for each in fin: lst=each.split(sep) hour=lst[0].split(' ')[-1].split(':')[0]...
# Copyright 2012 OpenStack Foundation # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2011 - 2012 Justin Santa Barbara # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may #...
import math def iss(n): s=0 if n==0 or n==1: s=1 else: di={} while n%2==0: if 2 in di: di[2]+=1 else: di[2]=1 n=n//2 for i in range(3,int(math.sqrt(n))+1,2): while n%i==0: n=n//i if i in di: di[i]+=1 else: di[i]=1 if n>2: if n in di: di[n]+=1 else: di...
from . import factory_rst_test from . import scc from pylat import get_config class Test_BLE_Device(factory_rst_test.Coap_Request_Tests): available_endpoints = [] @classmethod def setUpClass(cls): """Set up the class variables. Call well-known/core endpoint, create a list of available endp...
#Escribir un programa que muestre por pantalla la tabla de multiplicar # del 1 al 10. for i in range(1, 11): for j in range(1, 11): print(i*j, end = "\t") print("")
#!/usr/bin/python import subprocess import os import numpy as np import math import matplotlib.pyplot as plt import analyzer as stats import operator import matplotlib.ticker as mticker from pylab import * import time from matplotlib.backends.backend_pdf import PdfPages import pickle class BWACaller(): def __init__(...
"""CoinGecko model""" __docformat__ = "numpy" import json import logging import os from typing import List import pandas as pd from pycoingecko import CoinGeckoAPI from openbb_terminal.decorators import log_start_end logger = logging.getLogger(__name__) COINS_COLUMNS_MAP = { "Symbol": "symbol", "Name": "na...
from django.contrib.auth.models import Group, User from django.test import TestCase from tally_ho.libs.permissions.groups import create_permission_groups, \ create_demo_users_with_groups class TestGroups(TestCase): number_of_groups = 14 def setUp(self): pass def test_create_permission_group...
import fileinput ## Write all results into a txt file f = open("E:/ArcGIS/ACS/national/A_python_scripts - Copy/final_US.txt", "r") i = 1 fout = open("output0.txt","wb") for line in f: fout.write(line) i += 1 if i%60000 == 0: fout.close() fout = open("output%d.txt"%(i/60000),"wb") fout.close()
# -*- coding: utf-8 -*- """ Program: lab1_1.py Author: Alejandro Romero Calcular la tasa de impuesto de un alimento 1. Declaracion de variables tax tasa de impuesto tax_one tasa de impuesto adicional 2. Entradas Valor del alimento Numero de alimentos 3. Computaciones: tasa de entrada = suma de numero de alimento...
""" Creating credentials for Mitto instance. """ import os import sys import uuid from dotenv import load_dotenv from mitto_sdk import Mitto load_dotenv() UUID = str(uuid.uuid4()) NAME = f"creds_{UUID}".replace("-", "_") TYPE = "sql" BASE_URL = os.getenv("MITTO_BASE_URL") API_KEY = os.getenv("MITTO_API_KEY") NEW_C...
from django.conf.urls import url from ColorBlind_App import views urlpatterns = [ url(r'^$',views.colors,name='colors'), url(r'^result', views.results, name='results'), ]
from collections import defaultdict, Counter from itertools import permutations as p def factorize(n): d = defaultdict(int) for i in range(2, int(n**0.5)+1): while n%i==0: d[i] += 1 n //= i if not n: break if n>1: d[n] += 1 return d N = int(i...
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 3: (080) is the area code for fixe...
# uncompyle6 version 3.3.5 # Python bytecode 3.7 (3394) # Decompiled from: Python 3.7.3 (default, Jun 24 2019, 04:54:02) # [GCC 9.1.0] # Embedded file name: .\Disturbance.py # Size of source mod 2**32: 56 bytes class Disturbance: def __init__(self): pass
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-04-09 16:21 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 = [ ('laboratorio', '0004_bodega...
import argparse import os import fnmatch __description__ = 'add template' def main(): parser = argparse.ArgumentParser(description=__description__) parser.add_argument('-p', '--path', type=str, default="src", help=('path to where will add file' '(default...
__author__ = "Costas Bakas" __copyright__ = "Copyright 2018, http request" from PyQt4.QtCore import * from PyQt4.QtGui import * import sys import urllib.request import codecs import os import operator import requests import json import createRequest_ui class GetTrans(QDialog, createRequest_ui.Ui_window01): ...
import asyncio async def tick(): print('Tick') await asyncio.sleep(1) print('Tock') return 'tick-tock' async def main(): t1 = asyncio.create_task(tick(), name='tick1') t2 = asyncio.ensure_future(tick()) # Аналогично t1. # await t1 # await t2 # Когда мы работаем с набором таско...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse class AlipayCommerceOperationDcsMerchantqrcodeQueryResponse(AlipayResponse): def __init__(self): super(AlipayCommerceOperationDcsMerchantqrcodeQueryResponse, self).__init__() ...
import os import pandas as pd def find_outdir(): # get the correct directories dirs = ["./output/"] for d in dirs: if os.path.exists(d): outdir = d return(outdir) def summarize_train_test_split(): # from utils.organization import find_outdir # def table_1_demos(): try:...
from __future__ import print_function def num_bit_swap(a, b): count = 0 c = a ^ b # Bits that are different are 1s while c != 0: count += c & 1 # `count` increments upon a different bit c >>= 1 # Right shift `c` by one bit so that LSB can be got return count def num_bit_swap2(a, b...
# -*- coding:utf-8 -*- class Solution: def FirstNotRepeatingChar(self, s): s_dic = dict() res = '' for i in s[::-1]: if i not in s_dic: res = i s_dic[i] = 1 else: s_dic[i] += 1 return res if __name__ == '__main_...
from buildrzapi.viewsets import ParcelleViewset from rest_framework import routers router = routers.DefaultRouter() router.register('parcelle',ParcelleViewset) # localhost:p/api/employee/5 # GET, POST, PUT, DELETE # list , retrive
for i in range(int(input())): ar = input().split() x = int(ar[0]) y = int(ar[1]) z = y - x if z > 0: if z % 4 == 0: print(3) elif z % 2 == 0: print(2) else: print(1) elif z < 0: print(1 if abs(z) % 2 == 0 else 2) ...
from math import sqrt import pandas as pd new_user_profiles = pd.read_csv('new_user_profiles.csv') def pearson_correlation(person1_id, person2_id): person1_profile = None person2_profile = None # get user profiles for index, profile in new_user_profiles.iterrows(): if profile['user id'] == ...
import folium as fo #pip install folium map=fo.Map() x=fo.FeatureGroup(name="My Map") x.add_child(fo.Marker(location=[8.407449,77.709568],popup='My point',icon=fo.Icon(color='Black'))) map.add_child(x)
# 测试代码 # https://zhuanlan.zhihu.com/p/37086409 import tensorflow as tf import cv2 # Creates a graph. a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a') b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b') c = tf.matmul(a, b) # Creates a session with log_device_placement set to T...
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2019-02-27 07:11 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('wildlifecompliance', '0122_merge_20190227_1507'), ] operations = [ migratio...
from .models import Post from django.contrib import admin @admin.register(Post) class postAdmin(admin.ModelAdmin): icon = '<i class="material-icons">chat_bubble_outline</i>'
from flask_restful import Resource from flask_restful import reqparse, fields, marshal_with from datetime import datetime from model import challenge_datasource as datasource import date_util as dateutil # marshaller day_field = { 'day': fields.DateTime(dt_format='rfc822'), 'done': fields.Boolean } challenge_f...
x=20 y=45 z=23 if x>y and x>z : print("x is greater") else: if z>y : print("z is greater") else: print("y is greater")
food_and_drinks = [['jafa', 'bananica', 'plazma'], ['sarma', 'pasulj', 'riba'], ['vino', 'sok', 'pivo', 'rakija']] print(food_and_drinks[0][2]) print(food_and_drinks[0][0]) print(food_and_drinks[2][1]) print(food_and_drinks[1][0])
from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer import json from .models import MessageBody, ChatRoom from django.contrib.auth.models import User from datetime import datetime class ChatCustomer(WebsocketConsumer): def connect(self): self.room_name =...
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 import random import time class WindTurbine(object): """ Represents virtually and graphically a wind turbine It uses the raw data collected from a Wind Turbine in a circular buffer to simulate the ...
#!/bin/env python """ More or Less generic python code for image analysis. functions: property: is_new_image returns True\False if there is new image method: get_image return 4,X,Y image where 0 - R, 1 - G, 2 - B, 3 - K - colors Valentyn Stadnytskyi created: Feb 29 2018 last updated: July 2, 2018 Microscope Camera ...
''' AAA lllllll lllllll iiii A:::A l:::::l l:::::l i::::i A:::::A l:::::l l:::::l iiii A:::::::A l:::::l l:::::l ...
import unittest import lazy_dataset from lazy_dataset.database import DictDatabase class IteratorTest(unittest.TestCase): def setUp(self): self.json = dict( datasets=dict( train=dict( a=dict(example_id='a'), b=dict(example_id='b') ...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'welcome.ui' # # Created: Thu Nov 1 16:25:46 2012 # by: PyQt4 UI code generator 4.9.3 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except Attribu...
import scipy.stats as st import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import numpy as np # class Distribution: # Check which distribution this attribute follows so that we can do transformation before performing regression. def check_dist(x): fig = plt.figure(figsize=(20,...
import re from pprint import pprint import itertools def Main(): ingredients={} combinations = [] result={} with open('input.txt',mode='r') as data: for line in data: line=line.rstrip() nums = re.findall(r'([+-]?[0-9]{1,})',line) nums = [int(n) for n in nums] ingredients[line.split(":")[0]]={ "ca...
import pandas import tensorflow as tf from tensorflow import keras from keras.models import Sequential from keras.layers import Dense import matplotlib.pyplot as plt def ourDNN(inputdims): # create model model = Sequential() model.add(Dense(inputdims, input_dim=inputdims, activation='relu')) model.add(Dense(8, act...
import pandas as pd import pickle # d = pd.read_csv("data/spoilers/train.csv") # # list_set = set(d['page']) # print(len(list_set)) # # # with open('movie_rating_test_dump.pickle','rb') as rating_file: # dump = pickle.load(rating_file) # train_rating = dump[0] # print(len(train_rating)) feature_list = [] ...
# Generated by Django 3.0.6 on 2020-06-07 14:08 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...
import humanfriendly import logging import psutil # https://code.google.com/p/modwsgi/wiki/RegisteringCleanupCode class Generator2: def __init__(self, iterable, callback, environ): self.__iterable = iterable self.__callback = callback self.__environ = environ def __iter__(self): ...
import platform import sys import os import re import subprocess def get_lsb_information(): distinfo = {} if os.path.exists('/etc/lsb-release'): try: with open('/etc/lsb-release') as lsb_release_file: for line in lsb_release_file: line = line.strip() ...