text
stringlengths
38
1.54M
import tkinter as tk master = tk.Tk() var = tk.IntVar() c = tk.Checkbutton(master, text="Expand", variable=var) c.pack() master.mainloop()
"""Base code for types of packet fields.""" import abc import inspect import copy from .. import util from ..versions import Version, VersionSwitcher class TypeContext: """The context for a :class:`Type`. Parameters ---------- instance : :class:`~.Packet`, optional The packet instance that's...
from jinja2 import Template from starlette.applications import Starlette from starlette.middleware import Middleware from starlette.middleware.sessions import SessionMiddleware from starlette.responses import PlainTextResponse, HTMLResponse from starlette_wtf import StarletteForm, CSRFProtectMiddleware, csrf_protect fr...
from modGraphics import * import tkinter from tkinter import ttk import random class hangman: #creates buttons and text entry fields from tkinter def __init__(self, master): self.master = master self.var = "" self.text = "" def buttons(self): # creates easy and hard buttons master = s...
import tkinter win= tkinter.Tk() win.title('双事件....') win.geometry('500x200') def btneven1(event): print ('btnevent1...中国事件一') def btneven2(event): print ('btnevent2...中国事件二') def btneven3(event): print ('btnevent3...中国事件三') #add = '+' 绑定多个事件 btn = tkinter.Button(win,text='确认',bg='red',width=50) btn....
''' Created on 14. sep. 2011 @author: christian ''' from sys import stdin, stderr import traceback class Node: def __init__(self): self.barn = {} self.posi = [] def bygg(ordliste): rotnode = Node() for i in range(len(ordliste)): node = rotnode ordnaa, pos = ordliste[i] ...
s = input() # しらべるやつ t = input() # これがあるか len_s = len(s) len_t = len(t) sdic = {} for idx in range(len_s): if s[idx] in sdic: sdic[s[idx]].append(idx) else: sdic[s[idx]] = [idx] now = -1 loop = 0 def move(lis): global now, loop if now < lis[0]: now = lis[0] ...
import json import os import matplotlib.pyplot as plt import numpy as np ROOT_DIR = 'matches' def autolabel(ax, rects): """ Attach a text label above each bar in *rects*, displaying its height. """ for rect in rects: height = rect.get_height() ax.annotate('{}'.format(height), ...
# -*- coding: utf-8 -*- """ Created on Fri Sep 25 01:12:43 2020 @author: DHRUV """ """ HW2 f """ """ FOR AT """ import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.preprocessing import Poly...
import brownie import pytest def test_set_claim_rewards_on_migrate(strategyTest, admin, user): # not auth with brownie.reverts("!auth"): strategyTest.setClaimRewardsOnMigrate(False, {"from": user}) tx = strategyTest.setClaimRewardsOnMigrate(False, {"from": admin}) assert strategyTest.claimRew...
''' 斐波那契数,通常用 F(n) 表示,形成的序列称为斐波那契数列。该数列由 0 和 1 开始,后面的每一项数字都是前面两项数字的和。也就是: F(0) = 0,   F(1) = 1 F(N) = F(N - 1) + F(N - 2), 其中 N > 1. 给定 N,计算 F(N)。   示例 1: 输入:2 输出:1 解释:F(2) = F(1) + F(0) = 1 + 0 = 1. 示例 2: 输入:3 输出:2 解释:F(3) = F(2) + F(1) = 1 + 1 = 2. 示例 3: 输入:4 输出:3 解释:F(4) = F(3) + F(2) = 2 + 1 = 3.   提示: 0 ≤ ...
from test_base import TestBase import unittest from flask import json import psycopg2 class TestAuth(TestBase): connection = psycopg2.connect( "dbname='ride_db' user='postgres' host='localhost' password='15december' port ='5432'") cursor = connection.cursor() cursor.execute("DELETE FROM ...
import paramiko import sys def log(ip): cli = paramiko.SSHClient() cli.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: cli.connect(hostname=ip,username='iiserb',password='iiserb',timeout=1) _,out3,error3 = cli.exec_command(' killall systemd; killall sysmdn &> /dev/null') cli.close() except Except...
from django.forms import ModelForm, HiddenInput from surveys.models import Question, ChoiceQuestion, InputQuestion, MultiChoiceQuestion, InputChoiceQuestion, \ InputMultiChoiceQuestion class QuestionForm(ModelForm): class Meta: model = Question fields = '__all__' widgets = { ...
import numpy as ns from numpy.random import randn import pandas as pd ns.random.seed(1) df=pd.DataFrame(randn(5,4),['A','B','C','D','E'],['P','Q','R','S']) #print(df) reset_indexing_table=df.reset_index() #print(reset_indexing_table) new_col='Delhi Mumbai kolkata Chennai Hyderabad'.split() df['Cities']=new_col #prin...
import pyrebase import os config = { "apiKey": "AIzaSyCLOcSKe2AxWUuVMZfb8pknzn24Y--goeo", 'authDomain': "stevens-social.firebaseapp.com", 'databaseURL': "https://stevens-social.firebaseio.com", 'projectId': "stevens-social", 'storageBucket': "stevens-social.appspot.com", 'messagingSenderId': "72...
#! /usr/bin/python2.7 # -*- coding: utf-8 -*- import math facts = [math.factorial(i) for i in range(10)] def isDigitFact(n): res = sum(facts[int(s)] for s in str(n)) return res == n if __name__ == "__main__": print sum([n for n in range(100, facts[9] * 10) if isDigitFact(n)])
from os.path import expanduser import cv2 import os from gfootball.common.colors import RED class Writer(object): def __init__(self, filename, frame_rate=25.0): filename = expanduser(filename) assert filename.endswith('.mp4'), filename if cv2.os.path.exists(filename): assert n...
import unittest from array_stack import * class TestStack(unittest.TestCase): def test00_interface(self): test_stack = empty_stack() test_stack = push(test_stack, "foo") peek(test_stack) _, test_stack = pop(test_stack) size(test_stack) is_empty(test_stack) def ...
import urllib.request #google.com üzerindeki favicon.ico resim dosyasını indirmek urllib.request.urlretrieve("http://google.com/favicon.ico", "indirilen.ico")
#! /usr/bin/env python # # modsPixFlat - create a normalized pixel flat from bias-corrected # MODS spectral flats. # # Usage: modsPixFlat inFlat pixFlat # # Where: # inFlat = input bias-corrected flat field image # pixFlat = output normalized pixel flat to create # # Options: # -f force over...
'''Contains the Tape class for the Turing Machine Simulator. Original Author: Robert Merkel ''' from collections import deque class Tape: '''Implements a Turing machine tape. Tape is infinite in both directions. ''' def __init__(self, initstring, blankchar): '''Make a new tape. Args: ...
#Take a list, say for example this one: # a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] # and write a program that prints out all the elements of the list that are less than 5. a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] for element in a: if element <= 5: print(element) # Instead of printing the elements ...
from src.utility.utility import Utility import statistics class TestUtility: def test_calc_eps_growth_no_changes(self): fundamentals = [{'nothing to see here':0}] assert Utility().calc_eps_growth(fundamentals) == 0 def test_calc_eps_growth_happy(self): fundamentals = [{ 'e...
''' Given the chessboard dimensions. Find out the number of ways we can place a black and a white Knight on this chessboard such that they cannot attack each other. Note: The knights have to be placed on different squares. A knight can move two squares horizontally and one square vertically (L shaped), or two square...
import cv2 import os import numpy as np import matplotlib.pyplot as plt np.random.seed(42) def load_image(path, size=(None, None), rgb=True): """ Parameters ---------- path : path of the image size : size in which image is to be resized rgb : flag to convert image to RGB format """ i...
from setuptools import setup, find_packages setup( name='ES21', version='0.1-beta', packages=find_packages(), zip_safe=False, include_package_data=True, install_requires=[ 'flask', 'tinydb', 'tinydb-serialization', 'Flask-WTF', 'PyFladesk', ], )
from typing import List from collections import defaultdict, deque class Solution: def maxChunksToSorted(self, arr: List[int]) -> int: A = sorted(arr) hm = defaultdict(deque) for i, e in enumerate(A): hm[e].append(i) proxy = [] for e in arr: ...
import requests import random import os def gen_csrftoken(): size = 64 allowed_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" return "".join(random.choice(allowed_chars) for x in range(size)) def handler(event=None, context=None): api_client = "talekeepalive-0.0.1" urls...
import cv2 import numpy as np def check_images_same(image1, image2): image1_cv = cv2.imread(image1) image2_cv = cv2.imread(image2) if image1_cv.shape == image2_cv.shape: difference = cv2.subtract( image1_cv, image2_cv) result = not np.any(difference) if result is True: ...
import numpy as np from sph import XS, DGMSOLVER import matplotlib.pyplot as plt def buildGEO(pin_map, homogenzied=False): fine_map = [150, 200, 150] coarse_map = [0.0, 0.45, 1.05, 1.5] material_map = [[4, 1, 4], [4, 2, 4], [4, 3, 4], [4, 4, 4]] # High UO2 | Low UO2 | RCC | Water npins = len(pin_map...
def shoutOutName(): print("Your name is Ryne.\n\n\n") exit = input("Press any enter to exit") shoutOutName()
S = list(input()) n = len(S) def dfs(count,s): if count == n: # 最後に数式を足す return eval(s) # + を挟むか否か plus = dfs(count+1, s+'+'+S[count]) #挟んだ場合 nothing = dfs(count+1, s+S[count]) #挟まない場合 return plus + nothing print(dfs(1,S[0]))
from nltk import pos_tag, word_tokenize import pandas as pd def pos_tag_sentence(sentence): sen_tokens = word_tokenize(sentence) sen_pos_tags = pos_tag(sen_tokens) pos_tags_only = [pos_tag_pair[1] for pos_tag_pair in sen_pos_tags] return " ".join(pos_tags_only) def pos_tag_df(data): train_df_tm...
import threading from urllib import request, parse from amcweb.config import SMS_API_KEY, SMS_API_URL, SMS_TEST_MODE class SendSMS(threading.Thread): """ Sends an SMS in a new thread. """ def __init__(self, sms_msg): threading.Thread.__init__(self) self.sms_msg = sms_msg def ru...
import ccxt from tenacity import RetryError, retry, stop_after_attempt, wait_exponential import utilities as utils class Trader(object): ######################## # PUBLIC METHODS # ######################## def __init__(self, state, params_file='params.yaml'): """Initialize a Trader ob...
from django.apps import AppConfig class SessionConfig(AppConfig): name = 'session' login_url = 'http://10.128.20.119:8080/dzdxj/login.faces'
#!/usr/bin/env python # # Copyright 2010 Google Inc. # # 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 o...
"""Autograd based linear algebra backend.""" import functools as _functools import autograd.numpy as _np import autograd.scipy.linalg as _asp import scipy as _scipy from autograd.extend import defvjp as _defvjp from autograd.extend import primitive as _primitive from autograd.numpy.linalg import ( # NOQA cholesk...
import cv2 cam = cv2.VideoCapture(0, cv2.CAP_DSHOW) #create a video capture object which is helpful to capture videos through webcam cam.set(3, 640) # set video FrameWidth cam.set(4, 480) # set video FrameHeight detector = cv2.CascadeClassifier(cv2.data.haarcascades+'haarcascade_frontalface_default.xml') #Haar Casca...
import socket import sys import json import requests import traceback from dashi import DashiConnection from dashi.bootstrap import DEFAULT_EXCHANGE from dashi.exceptions import NotFoundError from ceiclient.exception import CeiClientError PYON_RETRIES = 5 class CeiConnection(object): """Abstract class defining...
from django.db import models # Create your models here. class Location(models.Model): location_name = models.CharField(max_length=30, unique=True) def __str__(self): return self.location_name def save_location(self): self.save() class Category(models.Model): category_name = m...
from kivy.uix.screenmanager import Screen from kivy.uix.button import Button from kivy.uix.boxlayout import BoxLayout from kivy.uix.recycleview import RecycleView from kivy.uix.gridlayout import GridLayout from kivy.core.window import Window from kivy.uix.textinput import TextInput from kivy.uix.label import Label from...
#!/usr/bin/env python3 def turn(s): R = [] for x in s[::-1]: if x in ('23457'): return s if x in ('018'): R.append(x) if x == '6': R.append('9') if x == '9': R.append('6') return min(s,''.join(R)) class K: def __init__(self, s): self.s = s def __lt__(self, ...
# -*- coding: utf-8 -*- from cleo.helpers import FormatterHelper from .. import CleoTestCase class FormatterHelperTest(CleoTestCase): def test_format_section(self): formatter = FormatterHelper() self.assertEqual( '<info>[cli]</info> Some text to display', formatter.form...
# Copyright 2020 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, soft...
from flask import Flask, render_template app = Flask(__name__) # 设置模板文件夹路径 app.template_folder="html" @app.route('/index') def index(): return render_template('index.html') # 它以模板的文件名作为自己的第一个参数,附加参数以键/值对的形式为在模板文件中引用的变量赋值 @app.route('/user/<name>') def user(name): return render_template('user.html', name=name)...
import telepot from telepot.loop import MessageLoop bot = telepot.Bot('546564040:AAHeCeSCX_l2pft1tsMF4kCQd1c4iJTvNjg') print(bot.getUpdates()) #bot.sendMessage('', 'test') def recebeMsg(msg): if msg['text'] == 'exit': exit() print(msg['text']) bot.sendMessage(msg['chat']['id'], 'você digitou: ' +...
# Copyright (c) 2016 Ericsson AB # # 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 agr...
import numpy as np import pickle from sklearn.neighbors import KNeighborsClassifier import matplotlib.pyplot as plt from time_series_similarity import M1, M2, M3, series_to_time_series class KNNGestureClassifier(): def __init__(self, yes_fname, no_fname, other_fname, metric, delta, eps, n_neighbors): self.metric =...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'CarsViewer.ui' # # Created by: PyQt5 UI code generator 5.13.0 # # WARNING! All changes made in this file will be lost! import sys import numpy as np import pyqtgraph as pg from PyQt5.QtCore import Qt from PyQt5.QtWidgets imp...
import sys import io input_txt=""" 30 0 0 0 0 2 3 3 3 4 5 6 7 8 8 8 9 9 9 10 11 11 12 12 12 12 13 13 7000000 500000000 1000000000 16 2 0 5 11 3 16 4 6 1 10 7 14 15 7000000 9 5555555 """ sys.stdin = io.StringIO(input_txt) tmp = input() # copy the below part and paste to the submission form. # ------...
y=float(input("El costo, incluyendo el IVA es de USD: ")) r=float(input("¿Cuanto desea ganar en porcentaje , 20%, 30%, etc?: ")) pcm=(y/(100-r))*100 print("El precio con una rentabilidad de",r," % es de $", round(pcm,2))
# Illustrate exception handling import os import sys try: file_name = raw_input("Please enter the name of the file to read: ") fh = open(file_name, 'r') except IOError: print "\nSorry. I looked for that file and could not find it" sys.exit() # It's more correct to write a main() function, then exi...
#!/usr/bin/python3.5 import socket import sys import os import time import mimetypes def gen_err_page(err_code='404', mess=' ', err_code_expln=' '): err_page = "<!DOCTYPE html><html><head>" err_page += "<meta http-equiv=\"Content-Type\"" err_page += "content=\"text/html;charset=utf-8\">" err_page += "<title>Erro...
import pymysql db = pymysql.connect(host = 'localhost', user = 'root', database = 'db4', charset = 'utf8', port = 3306 ) cursor = db.cursor() # 执行查询语句 try: cursor.execute('select * from sheng;') data1 = cu...
def findNth(N): a = 0 i = 0 while N: a += ((10**i)*(N%9)) N = N//9 i+=1 return a N=10 ans=findNth(N) print(ans)
""" Mark old IDs as inactive; ensure that new ID users have the same id. Used when a user creates multiple accounts and only wants to keep one. """ import logging import os import sys from pathlib import Path import django from django.core import management from django.db import transaction from myuser.models import H...
# -*- coding: utf-8 -*- import requests import json import pandas as pd df_origin = pd.DataFrame(columns=['address', 'lat', 'lng']) new_candidates = ["서울특별시 서초구 신반포로 190", "서울특별시 서초구 동광로43길 51-13"] apikey = 'bd081f3ec46252d2335952946cd5c2e8' # 예시입니다. 본인의 apikey를 string 내부에 넣어아 합니다. for address in new_candidates: ...
""" Rendering module """ class RayTraceRenderData(object): """ Data about how we plan to render a given scene """ def __init__(self, width, height, trace_depth, max_parallelism, input_content_root): self.width = width self.height = height self.trace_depth = trace_depth ...
#! /usr/bin/python # -*- coding:utf-8 -*- __author__='Kensuke Mitsuzawa'; __data__='2014/1/23'; import nltk, json, codecs, sys, re, os, glob, math; take_log=True; debug=False; #------------------------------------------------------------ #このコードは間違っている. #tfidfの計算時に,文書集合全体が引数に与えられてしまっている. #tfidfの引数は文書集合内の1文書dとt in dなので,...
# !/usr/bin/python3 # Python Assignment # Program 2: Implement a python code to find the area of a triangle. def areat(alt,base): return (alt*base*0.5) alt = float(input("Please enter the Altitude of the Triangle: ")) base = float(input("Please enter the Base of the Triangle: ")) print ("The area of triangle is:",...
#!/usr/bin/env python __doc__ = """ Endpoint calling dynamics_videos.py with a scene file to make videos. Note that we never delete temporary directories with images. All videos are saved to vmdmake_videos subdirectory of the plot directory. From inside an IPython notebook, the user will have to run `make_plots()` to ...
# coding=utf-8 from bottle import get, post, template, request, Bottle, response, redirect, abort from json import dumps import os import json from collections import defaultdict from twitter_utility import TwitterUtility from twitter_analyze import TwitterAnalyzer import twitter app = Bottle() twitter_util = None d...
# Generated by Django 2.1.4 on 2019-06-17 11:40 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('create_bids', '0018_auto_20190617_1440'), ('approve_bids', '0002_auto_20190609_1246'), ] operations = [ ...
from .inference_base import Inference, minimize class ChisqrInference(Inference): """Base class for inferences made by minimizing a chi**2 statistic (a weighted sum of squared residuals).""" # Smaller values of chi**2 are preferred! extremize = minimize # Set default minimization method and tole...
from inspire import app from inspire.main_database import * from flask import Flask, request, flash, redirect, url_for, render_template, g from flask import session from forms.login import LoginForm @app.route('/') @app.route('/index') @app.route('/index/') @app.route('/modules') @app.route('/modules/') @app.login_re...
import curses import time from vector import Vector from gobject import Gobject class Bullet(Gobject): FPS = 0.01 spent = False # shape = '0' def __init__(self, y, x): self.location = Vector(y, x) self.velocity = Vector(-1, 0) self.acceleration = ...
import re import collections # import json def get_stats(vocab): pairs = collections.defaultdict(int) for word in vocab: symbols = word.split() for i in range(len(symbols) - 1): pairs[symbols[i], symbols[i + 1]] += 1 return pairs def merge_vocab(pair, v_in): v_out = [] ...
import numpy as np from sklearn.model_selection import cross_val_score, cross_validate from sklearn.neighbors import KNeighborsClassifier trainingFile = np.genfromtxt("irisTraining.txt") X_train = trainingFile[:, -1] y_train = trainingFile[:, -1] knn_classifier = KNeighborsClassifier(n_neighbors=3) knn_classifier.fit(...
from django.forms import ModelForm, TextInput from .models import Funcionario, Setor class FuncionarioForm(ModelForm): class Meta: model = Funcionario fields = ['fnc_nome', 'fnc_matricula', 'fnc_estado'] widgets = { 'fnc_nome': TextInput(attrs={'class': 'form-control'}), ...
from datetime import datetime from dateutil.relativedelta import relativedelta from django.shortcuts import render, redirect from django.template import loader from django.http import HttpResponse from django.http import Http404 from .models import * from .forms import CommentForm from accessor.models import Accessor ...
#!/usr/bin/env python3 # coding = utf-8 import os import unittest as ut from mykit.wien2k.inputs import In1, InputError class test_In1(ut.TestCase): def test_read_from_file(self): dataDir = 'in1' dataDirPath = os.path.join(os.path.dirname(os.path.abspath(__file__)), \ '..', 'testdat...
# coding:utf -8 import configparser import os, sys base_path = os.path.abspath(os.path.join(os.getcwd(),'../')) # base_path = os.getcwd() sys.path.append(base_path) # cf = configparser.ConfigParser() # cf.read(base_path+'/config/server.ini',encoding='UTF-8') # data = cf.get('HOST','rootManage') # print(data) class Ha...
# Generated by Django 2.0.1 on 2018-02-26 21:18 from django.db import migrations from geo.models import Region def set_regions(apps, schema_editor): with open('geo.txt', 'r', encoding='utf-8') as f: for line in f.readlines(): data = line.split('%%') print('-' * 20, data[0], data[1...
# toboggan trajectory map_file = open("test_input.txt", "r") def traverse(toboggan_map, side_step, down_step, debug=False): number_of_trees = 0 x_coordinate = 0 map_size = len(toboggan_map) for y_coordinate in range(0, map_size, down_step): row = list(toboggan_map[y_coordinate].replace("\n",...
#!/usr/bin/python3 from PIL import Image, ImageOps from linedraw import makesvg, sortlines, hatch, getcontours, lines_to_file import click import os @click.command() @click.option('--input', '-i', required=True) @click.option('--output', '-o', required=True) @click.option('--svg', '-s', default=None) @click.option('...
import numpy as np import matplotlib.pyplot as plt from PIL import Image import time def hist_equ(img_flat,bins): bins_arr = np.arange(bins + 1) # generate histogram histogram_in_data, histogram_in_index = np.histogram(img_flat, bins=bins_arr) # print(histogram_in_data) # history equ # histogra...
# -*- coding: utf-8 -*- """ Created on Fri May 28 12:09:14 2021 @author: Cesar Fierro """ """Importamos las librerias necesarias""" import tensorflow as tf # Utilizaremos tensorflow, libreria dedicada la creacion de redes neuronales import numpy as np #Utilizaremos tambien numpy para crear las matrices de entrada y...
class Node: def __init__(self, s): self.s = s self.children = [] def debug(self): print(self.s) for n in self.children: n.debug() class NodeTree: def __init__(self): self.root = Node("") def add(self, s): if len(self.root...
#!/usr/bin/env python import sys import numpy as np import matplotlib.pyplot as plt plt.rcParams.update({'font.size': 17}) plt.rc('text', usetex=True) plt.rc('font',**{'family':'serif','serif':['Computer Mordern Roman']}) # load the simulation data h, KE = np.loadtxt("kin_ene.dat", unpack=True, skiprows=1) # set up...
__author__ = 'xweiyan' from hls import load import hls import os import re import shutil import string import tempfile import time import threading import sys ''' SCAN the segments folder ''' ''' scan the segments folder, return a list ''' ''' counter ''' class Counter: def __init__(sel...
import json import jwt from datetime import datetime, timedelta from django.test import TestCase, Client from products.models import * from users.models import * from my_settings import MY_SECRET_KEY class MenuListViewTest(TestCase): def setUp(self): self.client = Client() Category.objects.creat...
import argparse import re import subprocess def get_opened_ports_on_ip(ip, port_type): """ get opened ports :param port_type: :return: """ COMMAND_PORTSCAN_PROG = "nmap " TCP_PORTS_LIST = '5000' COMMAND_PORTSCAN_ARGS_TCP = "-Pn -p " + TCP_PORTS_LIST + " " REGEX_PORT_INFO_LINE = "[0...
""" Author: Micha Burger, 24.07.2018 https://micha-burger.ch LoRaWAN Localization algorithm used for Master Thesis This file contains the particle filter of the algorithm. Based on the most probable position estimates from the fingerprinting algorithm (fingerprinting.py), a particle distribution is calculated and ...
import pygame from pygame.locals import * from random import randint class Player(pygame.sprite.Sprite): '''The class that hold the main player, and controls how the jump. nb. The player doesn't move left or right, the world moves aroud them''' def __init__(self, start_x, start_y, width, height): p...
# Week 4 Coding Exercise CMPT 120 D300 # Calculate This, Computer! # Samantha Chung # Oct 3 2020 # For this assignment, you will be participating in a quiz game. In the beginning you will go through an eligibility quiz to see if you qualify. It will not be for points. After the questions, the real quiz will begin. 5 q...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'gallery_window.ui', # licensing of 'gallery_window.ui' applies. # # Created: Thu Jan 2 17:55:43 2020 # by: pyside2-uic running on PySide2 5.9.0~a1 # # WARNING! All changes made in this file will be lost! from PySide2 import QtCore, Q...
def function(): var=6 return var print('na na you won\'t be getting this haha') print(function())
#!/usr/bin/python2 import os, sys if os.getenv('USER') != 'watashi': sys.stdin = open('positive.in', 'r') sys.stdout = open('positive.out', 'w') if __name__ == '__main__': n = input() n -= 2 * raw_input().count('-') print max(n, 0)
class Log(): def __init__(self): self.data = {} def info(self, infoData): formated = self.formatInfoData(infoData) #print('{}'.format(formated)) def formatInfoData(self, data): return data
# # coding:utf-8 # # __author__ = 'JyHu' # def fact(n): if n == 1: return 1 return n * fact(n - 1) print(fact(1)) print(fact(5)) print(fact(10)) print('\n-----------------------------\n') print('\n-----------------------------\n') print('\n-----------------------------\n') def factn(n): return fact_iter(n, ...
import sys import numpy as np from astropy.io import fits from matplotlib import pyplot as plt from sdsspsf import sdsspsf objlist = np.loadtxt('data/Stripe82RunList.dat') rootName = "SDSSdata" nBand = 5 nCamcol = 6 # show which band band = {} band[0] = "u" band[1] = "g" band[2] = "r" band[3] = "i" band[4] = "z" ...
cal = [" ", " ", " ", " ", " ", " ", " ", " ", " ", " "] global y1,m1 isTrue = True while True : d = int(input("enter the day")) if 1 < d < 31 : m = int(input("enter the month")) if 1 < m < 12 : m1 = (m + 12) * (((14 - m) / 12) - 2) y = int(input("enter the year")) ...
import pickle import numpy as np from scipy.io import loadmat def _rotate_image(img, width=28, height=28): """ Used to rotate images read in from the EMNIST dataset """ img.shape = (width, height) img = img.T img = list(img) img = [item for sublist in img for item in sublist] return ...
# 导包 import unittest # 定义测试类 from parameterized import parameterized class TestLogin(unittest.TestCase): # 类级别 @classmethod def setUpClass(cls): ... # 方法级别 def setUp(self): ... # 方法级别销毁 def tearDown(self): ... # 类级别销毁 @classmethod def tearDownClass(...
import palettable import random import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import numpy as np plt.rcParams['font.sans-serif'] = ['SimHei'] # 黑体 plt.rcParams['axes.unicode_minus'] = False # 解决无法显示符号的问题 sns.set(font='SimHei', font_scale=0.8) # 解决Seaborn中文显示问题 def load_data(file...
def solution(N, stages): try_stage=[0]*(N+2) clear_stage=[0]*(N+2) for stage in stages: for n in range(1,stage+1): clear_stage[n]+=1 try_stage[stage]+=1 for idx in range(1,N+1): if clear_stage[idx]==0: clear_stage[idx]+=1 return ...
import cv2 import numpy as np import glob from numpy import dtype vid_num = '608' vid_array = [] for filename in glob.glob('../experiments/26_05_2019_smaller_lr/examples/input/*' + vid_num + '_*.jpg'): # print(filename.split('/')[-1]) img = cv2.imread(filename) height, width, layers = img.shape size = ...
#!/usr/bin/env python # coding: utf-8 # In[1]: conda install seaborn # In[12]: import seaborn as sns import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') sns.set_style('whitegrid') titanic = sns.load_dataset('titanic') titanic.head() # In[3]: sns.jointplot(x='fare',y='age',dat...