text
stringlengths
8
6.05M
import sklearn.datasets import sklearn.ensemble import sklearn.model_selection import sklearn.svm class Objective(object): def __init__(self, iris): self.boston = boston def __call__(self, trial): x, y = self.boston.data, self.boston.target classifier_name = trial.suggest_categorical...
import math import matplotlib.pyplot as plt fname = 'test' f1 = open(fname, "r") temp = map(int, f1.read().split()) N = temp[0] Px = [] Py = [] for i in range(1, len(temp)): if i%2 == 1: Px.append(temp[i]) else: Py.append(temp[i]) f2 = open('circle', "r") tmp = map(float, f2.read().split()) N = len(tmp) / 3 C =...
#!/usr/bin/python # -*- coding: UTF-8 -*- import multiprocessing import time import os datalist=['+++'] # 我是 def adddata(): global datalist datalist.append(1) datalist.append(2) datalist.append(3) print("sub process",os.getpid(),datalist); if __name__=="__main__": p=multiprocessing.Process(tar...
n = map(str, sorted(map(int, list(input())), reverse=True)) print(''.join(n))
# -*- encoding:utf-8 -*- # __author__=='Gan' # Given a collection of distinct numbers, return all possible permutations. # # For example, # [1,2,3] have the following permutations: # [ # [1,2,3], # [1,3,2], # [2,1,3], # [2,3,1], # [3,1,2], # [3,2,1] # ] # 25 / 25 test cases passed. # Status: Accepted # ...
# interfaz, controlador y acceso a la base de datos print("Hola mundo")
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # File Name: insert_db.py # By: Daniel Lamothe # # Purpose: Inserts the demo data for the Dire TunaFish Creature for the first Prototype. Beginnings of the Data Access # Layer. #~~~~~~~~~~~~~~~~~~~~~...
import json a = json.dumps("[[a: 1, b: 2], [a: 4, b: 8]]") print(json.loads(lambda s: s['a']))
class Solution(object): def backspaceCompare(self, S, T): """ :type S: str :type T: str :rtype: bool """ return self.backspace(S) == self.backspace(T) def backspace(self, s): stack = [] for i in s: if stack and i == "#": ...
from django.urls import path from . import views urlpatterns = [ path('', views.index), path('', views.root_method), path('another_route', views.another_method), path('redirected_route', views.redirected_method) ]
from django.contrib import admin from .models import * # Register your models here. admin.site.register(Link_Section) admin.site.register(Pokraska) admin.site.register(Uteplenie) admin.site.register(Design) admin.site.register(Otoplenie) admin.site.register(Osteklenie_balkonov) admin.site.register(Redecorating) admin.s...
#!/usr/bin/env python from scapy.all import * import sys import argparse import gzip import dpkt def generate(args, pcap_filename): with gzip.open(pcap_filename, 'rb') if pcap_filename.endswith('.gz') else open(pcap_filename, 'rb') as pcap: pcap_reader = dpkt.pcap.Reader(pcap) packet_number = 0 ...
from tkinter import * root = Tk() root.title('SIMPLE CALCULATOR') frame = LabelFrame(root, text="CALCULATOR", padx=20, pady=10) frame.pack(padx=100, pady=50) def my_Click(): button0.configure(text = name.get()) button1.configure(text = name.get()) button2.configure(text=name.get()) button...
from functools import reduce import operator def multi(lst): return reduce(operator.mul, lst) def add(lst): return sum(lst) def reverse(string): return string[::-1] ''' here are three functions: Multiplication (x) Addition (+) and Reverse (!esreveR) first two use lists as input, last one a string. '''
import json import unittest import responses import pyyoutube class ApiCommentTest(unittest.TestCase): BASE_PATH = "testdata/apidata/comments/" BASE_URL = "https://www.googleapis.com/youtube/v3/comments" with open(BASE_PATH + "comments_single.json", "rb") as f: COMMENTS_INFO_SINGLE = json.loads...
t_api = '1272215182:AAHjwYdyiDyyW_rs4yuFIlRG_f5-ekK9O98' w_api = 'fdd26f8f1df5fc938fc402b59ee614c1'
import flask, flask.views import os import functools from flask import jsonify, request from pathlib import Path import librosa import numpy as np import pickle import shutil import socket import re import sys from statistics import mean from scipy.spatial.distance import euclidean from keras.models import model_from...
# Generated by Django 2.1.1 on 2018-09-27 09:22 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('products', '0009_remove_type_price_type'), ] operations = [ migrations.AlterField( model_name='product', name='slug_...
import os from dataloader import CIFAR10 from tqdm import tqdm import torch import torch.nn as nn import torch.optim as optim import torch.utils.data as datautil from model import network device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu:0') print(device) paths = ['./data/cifar-10-batches-py/data...
""" Tests of the neo.core.block.Block class """ from datetime import datetime from copy import deepcopy import unittest import numpy as np try: from IPython.lib.pretty import pretty except ImportError as err: HAVE_IPYTHON = False else: HAVE_IPYTHON = True from neo.core.block import Block from neo.core....
#!/usr/bin/env python # encoding: utf-8 """ Created by misaka-10032 (longqic@andrew.cmu.edu). All rights reserved. Get gadgets from asm """ __author__ = 'misaka-10032' import argparse import re import subprocess def get_bytes(line): try: return re.search('.*:\t(([0-9a-f]{2,} )*).*', line).group(1) e...
pref_cred = {}
from .abstract_repository_analyzer import AbstractRepositoryAnalyzer import subprocess import os import logging class MercurialRepositoryAnalyzer(AbstractRepositoryAnalyzer): """ Analysis plug-in for mercurial repositories. """ def count_repo_branches(self, repo_path: str, remote: str) -> None: ...
import requests import re import json import csv from bs4 import BeautifulSoup url = "http://catalog.gatech.edu/coursesaz/" base_url = "http://catalog.gatech.edu" def get_hrefs(): page = requests.get(url) soup = BeautifulSoup(page.content, 'html.parser') courses = soup.find('div', id="atozindex") link...
# -*- coding: utf-8 -*- # Copyright (c) 2017, Valiant Systems and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document from frappe.desk.reportview import get_match_cond, get_filters_cond class Exam(Document): p...
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not ...
""" Refer from https://github.com/statsu1990/yoto_class_balanced_loss """ from multiprocessing import Pool import random import numpy as np import torch import torchvision import torchvision.transforms as transforms from torch.utils.data import Dataset, DataLoader, Subset from sklearn.model_selection import train_test_...
# Author:ambiguoustexture # Date: 2020-03-04 import json from pymongo import MongoClient from bson.objectid import ObjectId def support_ObjectId(obj): """Since ObjectId cannot be json-encoded, convert it to a string type return: string converted from ObjectId """ if isinstance(obj, ObjectId): ...
#--------------------------------- IMPORTS ------------------------------------ import shapely #------------------------ FUNCTION DEFINITIONS ------------------------------ def generate_kitty_lines(kitty_img, n_pts=800, alpha_factor=0.3, show_plt = False): """ kitty_img is an image of a cat, with interior ...
import xlrd def add_space(val): return ' ' * val file_name = 'mon.xlsx' dir_name = 'D://Python_projects//tests//' out_file = 'out.sql' lst = [] s = ' ' tmp_table = 'tmp.lo_monetka_not_working' del_table = f'if OBJECT_ID(\'{tmp_table}\') is NOT NULL\ndrop table {tmp_table};\n\n' alter_table = f"""ALTER TABLE {tm...
class Node(): def __init__(self, e, n): self.element = e self.next = n def getElement(self): return self.element def getNext(self): return self.next def setElement(self, e): self.element = e def setNext(self, n): self.next = n class CircularList(): def __init__(self): self.cursor =...
# -*- coding: utf-8 -*- """ Created on Wed Apr 10 10:05:48 2019 @author: andrewbartels1 """ # packages to import here import numpy as np import matplotlib.pyplot as plt # functions here def make_phone_data(nphones, sound_speed, spacing, noise_pwr, signal_pwr, sampling_rate, samples, signal_hz, ...
from __future__ import print_function, division import os import logging from isochrones import StarModel from math import log10, sqrt from .data import dirname, STARMODELDIR class GaiaDR1_StarModel(StarModel): @property def corrected_parallax(self): if not hasattr(self, '_corrected_parallax'): ...
## Santosh Khadka # https://leetcode.com/problems/roman-to-integer/ ''' Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 For example, 2 is writt...
import numpy as np import scipy.sparse as sp from ..base_transforms import SparseTransform from ..transform import Transform from ..decorators import multiple __all__ = ['SparseAdjToEdge', 'sparse_adj_to_edge'] @Transform.register() class SparseAdjToEdge(SparseTransform): def __call__(self, adj_matrix: sp.csr_m...
#Classes & Objects "Like java python uses OOP" "To create a class use the class keyword" class Myclass: x=5 "To create an object we can use the class name assgining it to a new variable" p1 = Myclass() print(p1.x) "The __init__ function is like a constructor function in java, this is executed when the class is...
from .forms import UserProfileLoginForm class LoginFormMiddleware(object): """ The purpose of this middleware is to include the login form in every GET request """ def process_request(self, request): """Process the request if the method is Method is get, provide a login form""" ...
import argparse import resource import time from Puzzle import Puzzle from Solver import Solver def export(result: tuple, total_time: float): file = open('output.txt', 'w') file.write("path_to_goal: " + str(result[0])) file.write("\ncost_of_path: " + str(len(result[0]))) file.write("\nnodes_expanded:...
import numpy as np import cv2 as cv import matplotlib.pyplot as plt def convolution(img, filter): """ Convolving an image by a filter :param img: input image, uint8 :param filter: m*n filter with float values :return: result of convolving image """ if filter.shape[0] % 2 == 0 o...
import numpy as np from Utils import ArtificialNeuralNetwork from sklearn.neural_network import MLPClassifier from sklearn.preprocessing import StandardScaler from sklearn.model_selection import GridSearchCV from sklearn.neural_network import MLPRegressor from sklearn.preprocessing import MinMaxScaler def ANNTrain(fi...
from django.db import models class CheckIn(models.Model): class Meta: db_table = 'check_in' unique_together = ('booking_ref_num', 'passenger_first_name', 'passenger_last_name', 'departure_date') booking_ref_num = models.CharField('Booking reference number', max_length=10, null=False) pass...
#!/usr/bin/python import math, os, sys, argparse from random import randint as random from time import time as timer class Task: def __init__(self, id, time): self.id = id+1 self.time = time def __repr__(self): return "id=%d t=%d" % (self.id, self.time) def rec(tasks, lines): task = tasks[len(lines)-1] b...
from .. import Interpreter, adapter from ..interface import Block from typing import Optional import random, math class SubstringBlock(Block): def will_accept(self, ctx : Interpreter.Context) -> bool: dec = ctx.verb.declaration.lower() return any([dec=="substr",dec=="substring"]) def process(s...
import typing import pathlib import datetime # types # -------------------------------------------------------------------------------------- class Artifact: """Base class for all artifact types.""" class UnbuiltArtifact(Artifact, typing.NamedTuple): """The inputs needed to build an artifact. Attribu...
import json from decimal import Decimal from lib.domain.model.humouword_factory import HumouWordFactory from lib.domain.model.humouword import WordId from app.infrastructure.humouword import HumouWordDataSource from app.application.humouword import HumouWordRegisterService from app.application.humouword import HumouWo...
# -*- coding: utf-8 -*- from openprocurement.auction.esco.auctions import simple, multilot from openprocurement.auction.esco.tests.unit.constants import AUCTIONS def test_put_auction_data_without_dc(universal_auction, logger, mocker): # TODO: find out what actually '_type' field serves for if universal_auctio...
# Generated by Django 2.1.1 on 2018-09-30 09:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('products', '0010_auto_20180927_1222'), ] operations = [ migrations.RemoveField( model_name='photo', name='slide_phot...
import os class Leaderboard: def __init__(self): self.__score = 49 self.__username = "Hamzah" self.__filename = "leaderboard.txt" self.__listScores = [] self.__maxList = 10 self.__readLeaderboard = False def setScore(self, value): self.__score = value def getScore(self): return ...
# Define uma dependencia de um pra muitos entre os objetos, de modo que qualquer alteração sera notificada # aos dependentes de maneira automatica class CanalDeNoticia: def __init__(self): self.__inscritos = [] self.__noticia = '' def inscrever(self, inscrito): self.__inscritos.appen...
"""Write a class called Wordplay. It should have a field that holds a list of words. The user of the class should pass the list of words they want to use to the class. There should be the following methods: • words_with_length(length) — returns a list of all the words of length length • starts_with(s) — returns a list...
from sqlalchemy import Column, Integer, String, Float, ForeignKey, DateTime, Table, Boolean from sqlalchemy.orm import relationship from settings.database import Base import datetime class BaseMixin(object): id = Column(Integer, primary_key=True) deleted = Column(Boolean, default=False, nullable=False) cla...
''' Updates from events ''' import logging # Import salt libs import salt.utils log = logging.getLogger(__name__) try: HAS_LIBS = True except ImportError: HAS_LIBS = False # Define the module's virtual name __virtualname__ = 'checks' def __virtual__(): if HAS_LIBS: return __virtualname__ de...
import torch from torch import nn from torch import optim import torchvision from torchvision import datasets, transforms, models # LOADING DATA FUNCTION def load_data(data_dir): train_dir = data_dir + '/train' valid_dir = data_dir + '/valid' test_dir = data_dir + '/test' # Define your transforms fo...
import unittest from search.search import kmp_search, prepare_lps class TestSearch(unittest.TestCase): def test_prepare_lps(self): self.assertEqual( prepare_lps("ababd"), [0, 0, 0, 1, 2, 0] ) def test_search(self): string = """Lorem ipsum dodolor sit amet, consectetur adipiscing elit, sed...
#!/usr/bin/env python # -*- coding: utf-8 -*- from functools import wraps from base import smartpool def db_conn(db_name): def deco(old_handler): @wraps(old_handler) def new_handler(*args, **kwargs): kwargs[db_name] = smartpool.ConnectionProxy(db_name) return old_handler(...
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:hua with open("test4.txt","r",encoding="utf-8") as f: # s = f.read() s= f.readlines() for k in s: if "查看详情" not in k: # file = open('test5.txt', 'wb') file = open('test5.txt', 'a', encoding="utf-8") file.writel...
import requests # http://docs.python-requests.org/en/master/api/ import unittest import json from requests.status_codes import codes """ This is a python script for integration testing our sample app. Execution requirements: 1. Start Cytoscape from the command line with the -R option set to 1234 (normally './cyto...
from unittest import mock import pytest import keg_storage class TestStorage: def test_app_to_init_call_init(self): app = mock.MagicMock() app.config = { "KEG_STORAGE_PROFILES": [(keg_storage.backends.StorageBackend, {"name": "test"})] } storage = keg_storage.Storage(...
from django.contrib import admin from .models import Movie, Showing, Order class MovieAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'description', 'active',) list_filter = ('active',) search_fields = ('name',) ordering = ('id',) admin.site.register(Movie, MovieAdmin) class ShowingAdmin(ad...
from rest_framework import permissions, status from rest_framework.decorators import action from rest_framework.mixins import ListModelMixin, RetrieveModelMixin from rest_framework.response import Response from rest_framework.viewsets import GenericViewSet from .models import Test from .serializers import ResultPostSe...
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import dataclasses import logging import os import uuid from dataclasses import dataclass from enum import Enum from typing import Any from pants.backe...
# hard题还是一看就不会 # A*算法,头次看 class Solution: def cutOffTree(self, forest: List[List[int]]) -> int: def f(i, j, x, y): return abs(i - x) + abs(j - y) def bfs(i, j, x, y): q = [(f(i, j, x, y), i, j)] dist = {i * n + j: 0} while q: _, i, j =...
import sys import time import os import configparser from subprocess import call import logging from watchdog.observers import Observer from watchdog.events import LoggingEventHandler from watchdog.events import FileSystemEventHandler import matplotlib.pyplot as plt #import cv2 from skimage import io import matplotlib...
from flask import Flask from flask import render_template, flash from flask_bootstrap import Bootstrap from flask import request from flask_wtf import Form from wtforms import StringField , validators, SubmitField from flask_wtf.file import FileField, FileRequired from youtoplay import youtoplay class LinkForm(Form): ...
# -*- coding: utf-8 -*- from plsqldecoder.api.decoder.business import decode def test_db_connection(): assert decode() == "Senhafacil#16"
s = input() try: print(int(s)) except Exception as e: print(e) print("rest of the code")
from django.contrib import admin from miapp.models import Carro # Register your models here. admin.site.register(Carro)
import argparse import bz2 import ftplib try: import manhole except ModuleNotFoundError: pass import multiprocessing as mp import numpy as np import os import re import RSEntry as rse import SlimRSCollection as srsc from string import ascii_lowercase import sys import time import traceback import urllib.error i...
from extensions.extensions import db class RevokedToken(db.Model): __tablename__ = 'revoke_jwt' id = db.Column(db.Integer, primary_key=True) access_jti = db.Column(db.String, unique=True, nullable=False) refresh_jti = db.Column(db.String, unique=True, nullable=False) created_at = db.Column(db.Date...
import os import secrets from flask import render_template, flash, url_for, redirect, request, session from flask_login import login_user, current_user, login_required from PIL import Image from .. import create_app from .. import db from functools import wraps config_name = os.getenv('FLASK_CONFIG') app = create_ap...
# misc board functions import analogio import digitalio import time # set pins def setDigitalIn(pin, _pull): e = digitalio.DigitalInOut(pin) e.switch_to_input(pull=_pull) return e def setDigitalOut(pin): e = digitalio.DigitalInOut(pin) e.direction = digitalio.Direction.OUTPUT return e def set...
from selenium import webdriver import unittest import time #from pages.pageindex import * #from pages.pageitemlist import * #from pages.pageitem import * #clase donde van a estar los casos de prueba #hereda de unittest class Items(unittest.TestCase): def test_view_item_page(self): driver = webdriver.Chr...
import cv2 as cv # 톱니바퀴에서 unpinned mode #img = cv.imread("irene.jpg", cv.IMREAD_UNCHANGED) # 원본 그대로 읽겠다는 의미, 3차원으로 읽어짐 img = cv.imread("irene.jpg", cv.IMREAD_GRAYSCALE) # 2차원으로 읽어짐 == 색값이 하나니까 print(img) print(img.shape, img.dtype) # shape : 세로(행의 수), 가로(열의 수), 색(3가지) # ctrl + f5 누르면 이전에 실행했던 거 다시 실행
class Solution: def longestCommonSubstr(self, S1, S2, n, m): dp=[[0 for i in range(m+1)]for i in range(n+1)] result=0 for i in range(1,n+1): for j in range(1,m+1): if S1[i-1]==S2[j-1]: dp[i][j]=1+dp[i-1][j-1] result=max(resu...
#!/usr/bin/env python import pickle import io from lab_defs import teaching_length from lab_mc import experiments, tutorials experiments["LVT"] = tutorials["LVT"] from reportlab.lib.units import mm import csv from lab_mc import cohort from reportlab.graphics.barcode import code39 def process(filename): barcod...
import numpy as np class simplenet: def __init__(self): self.W = np.random.randn(2, 3) def predict(self, x): return np.dot(x, self.W) def loss(self, x, t): z = self.predict(x) y = softmax(z) loss = cross_entropy_error(y, t) return loss def numerical_grad...
#!/usr/bin/env python # Filename: stdin2clip.py # Author: Saphalon (aka Chaim) # Description: # Command-line tool to copy standard input (stdin) to clipboard # Required modules: # pygtk, gtk import sys import pygtk pygtk.require('2.0') import gtk try: buffer = ''.join(sys.stdin.readlines()) c = gtk.Clipboar...
#!/usr/bin/python # -*-coding: utf-8 -*- #################################################### ## Estructura de control #################################################### # Hagamos sólo una variable una_variable = 5 # Aquí está una declaración de un 'if'. ¡La indentación es importante en Python! # imprime "una_vari...
# Generated by Django 2.2.7 on 2019-12-09 20:52 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('info', '0012_whitelistemail'), ] operations = [ migrations.CreateModel( name='ValidatedStudent'...
# Copyright 2014 Google. # # 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 writing, softw...
'''competitive_nets.py Simulates various competitive networks CS443: Computational Neuroscience Alice Cole Ethan Project 3: Competitive Networks ''' import numpy as np from scipy import ndimage from scipy import signal def leaky_integrator(I, A, B, t_max, dt): '''A layer of leaky integrator neurons with shunting ...
from rubicon_ml.domain.utils.training_metadata import TrainingMetadata __all__ = ["TrainingMetadata"]
from typing import Union import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Output, Input, State from dash.exceptions import PreventUpdate from .dash_app import DashApp from .._vis_base import display_name REFRESH_INTERVAL = Input('playing-refresh-interval', 'n_inte...
#!usr/bin/env python3 """ Functional programming helpers """ # TODO: # Add docs import inspect, sys from functools import reduce def curry(f): """A function decorator that automaticly curries a function. Examples: >>> @curry >>> def add3(a,b,c): ... return a + b + c >>> a...
# -*- coding: utf-8 -*- """ Created on Fri Oct 16 14:18:38 2020 """ from google.cloud import storage import os import io import time from datetime import datetime as dt class StoreModel: def __init__(self): self.model_link = None return def store_model(self, local_file):...
#!/usr/bin/python # graphDist.py # by: Mike Pozulp # graph a plot of variance dependent # on network distance for all observations import matplotlib.pyplot as plt from matplotlib.ticker import MultipleLocator import pylab import csv import sys import numpy import math def printUsage(): print ('Usage: graphDist.py {...
""" Date: March 20 2019 @author: Dhynasah Cakir """ import pandas as pd import numpy as np from collections import defaultdict from pprint import pprint def addToDict(document,dict_index,word_dicts): ''' Parameters: 1. a single document 2. dict_index - imp...
#!/usr/bin/env python # coding: utf-8 # Copyright (c) Qotto, 2019 from .coffee_ordered import CoffeeOrdered from .coffee_served import CoffeeServed from .coffee_finished import CoffeeFinished __all__ = [ 'CoffeeOrdered', 'CoffeeServed', 'CoffeeFinished', ]
from unittest import TestCase from app import app from mock import patch class TestApp(TestCase): @patch("app.app.render_home") def test_home(self, render_home): render_home.return_value = 'success' self.assertEqual(app.home(), 'success') @patch("app.app.render_category") def test_ca...
# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import argparse import json import subprocess import sys from pathlib import Path from pants.backend.awslambda.python.target_types import PythonAwsLamb...
import numpy as np import cv2 img = cv2.imread('images/car.jpg', cv2.IMREAD_COLOR) img[55,55] = [255,255,255] px = img[55,55] img[100:150, 100:150] = [255,255,255] watch_face = img[37:111, 107:194] img[0:74, 0:87] = watch_face cv2.imshow('image', img) cv2.waitKey(0) cv2.destroyAllWindows
import os # Create folder if not created def create_project_dir(directory): if not os.path.exists(directory): print('Directory Created') os.makedirs(directory) # To crawl a page we need to provide a link to start, The crawler starts looking at all the links in the page and # craws them Two text ...
import pandas as pd import matplotlib.pyplot as plt import numpy as np from sklearn.cluster import KMeans, AgglomerativeClustering # contains count, median price for each quarter as cols, LGA in 2nd entry of # each row. def preprocess_house(fname): # reorganises the house price csv files into a more sta...
#!/usr/bin/python # -*- coding: utf-8 -*- from tkinter import * def onClickDraw(): plist=['Name1','Name2','Name3'] for item in plist: listBox.insert(END,item) root=Tk() listBox=Listbox(root) button=Button(root,text='Draw List',command=onClickDraw) button.pack() listBox.pack() root.mainloop()
num1 = float(input('Write your first number: ')) num2 = float(input('Write your second number: ')) if num1 < num2: print('Your first number is lower than second') elif num1 == num2: print('Your numbers are equal') else: print('Second number is lower than first')
# I THINK I AM GOING TO HAVE TO CHANGE THIS. COPIED AND PASTED FROM THE bootcamp/news/views.py FILE. from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpResponse, HttpResponseBadRequest, JsonResponse from django.template.loader ...
from matplotlib.pyplot import imread, show from numpy import copy, average, sqrt, arctan import os edge = imread("C:\Temp\Edge2.png") class lineObject: """ Line object that contains a line within a specific image """ def __init__(self, line): self.length = len(line) self.endPo...
def register(cls, *args, **kwarg): print(cls, args, kwarg, 'one') def detor(*args, **kw): print(args, kw, 'two') return detor class ooop(object): def __init__(self): register('123', '2345','2321', l = '2345')(self.fn) def fn(self): p...
# Parameters, Unpacking, Variables from sys import argv # read the WYSS section for how to run this script, first, second, third = argv # argv is the "argument variable" -> holds the arguments you pass to your # Python script when you run it. print("The script is called:", script) print("Your first variable is:", fir...
from . import token