text
stringlengths
38
1.54M
import parser as dsp import csv import argparse import copy from collections import UserDict class DefDict(UserDict): def __getitem__(self,k): if k not in self.data: self[k]=(k,"NONE") return self.data[k] parser = argparse.ArgumentParser(description="Reads DiscordScript files") parser.add_argument("script",ty...
from django.db import models class repair_cmpt(models.Model): class_room = models.CharField(max_length=255) #ห้องเรียน name_aj = models.CharField(max_length=255) slug_repair = models.SlugField(max_length=255) #ห้องที่ซ่อม No_cmpt = models.CharField(max_length=2) #หมายเลขเครื่อง img_cmpt = models.Ch...
import torch import torch.nn as nn import copy import torch.quantization.quantize_fx as quantize_fx from torch.utils.mobile_optimizer import optimize_for_mobile class Net(nn.Module): def __init__(self): super(Net, self).__init__() repo = 'alantess/vigilant-driving:main/1.0.75' self.model =...
from django.db import models from django.utils import timezone # Create your models here. class Product(models.Model): title = models.CharField(max_length=64) description = models.TextField() price = models.DecimalField(max_digits=6, decimal_places=2) # ruleid:use-decimalfield-for-money old_price ...
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import gae_ts_mon import webapp2 from handlers.login import Login from handlers.query import Query handlers = [ (r'/login', Login), (r'/query(/.*)?', Q...
import os import glob from skimage import io, color, transform import urllib.request import tarfile import numpy as np def download_extract_data(): url = "http://vis-www.cs.umass.edu/lfw/lfw-funneled.tgz" if not os.path.isfile("lfw-funneled.tgz"): print("Downloading: " + url) urllib.request.ur...
from euler_lib import prime_factorization def ans(): n = 600851475143 table = prime_factorization(n) return str(table[-1]) if __name__ == '__main__': print ans()
print('\033[30m=+'*10, ' GERADOR DE PA 2.0 ', '+='*10) ptermo = int(input('Primeiro termo: ')) razao = int(input('Razão da PA: ')) pa = ptermo contagem = 1 resposta = 10 tot = 0 print(f'PA do número {ptermo}(10 termos): \nINÍCIO -> ', end='') while resposta != 0: tot += resposta while contagem <= tot: p...
#CSC687 Data Trip Project import RPi.GPIO as GPIO import spidev import time import json import websocket import random from datetime import datetime GPIO.setmode(GPIO.BOARD) GPIO.setup(11, GPIO.OUT) GPIO.output(11, False) #Set Threshold for irrigation system threshold = 100 #Open SPI bus spi = spidev.SpiDev() spi.o...
from torchvision import transforms import torch from typing import List, Tuple from PIL import Image from torch.utils.data import Dataset from enum import Enum, unique import json import os import random BASE_IMAGE_DIR = "/home/pdoyle/ssd/datasets/plant_disease/PlantVillage" STDDEV = [0.192966, 0.170431, 0.207222] MEA...
import torch import torch.nn as nn import pytorch_lightning as pl import torch.nn.functional as F import torch.optim as optim from models.ae.ConvLSTMCell import ConvLSTMCell class deepSWE(pl.LightningModule): def __init__(self, nf, in_chan, out_chan, future_frames=1, image_size=256): super(deepSWE, self)....
# Raspberry PI GoPro Pano No WiFi option Python file. # Make sure your GoPro has autoexec.ash import time def set(property, value): try: f = open("/sys/class/rpi-pwm/pwm0/" + property, 'w') f.write(value) f.close() except: print("Error writing to: " + property + " value: " + value) def setServo(angle): set("ser...
import os import json import re from config import DATA_DIR, LEAGUE def get_item_info(item_category, item_name): with open(os.path.join(DATA_DIR, 'uniques.json')) as uniques_file: uniques = json.load(uniques_file) return uniques[item_category][item_name] def get_mods_mask(item_info): explici...
"""The cnumber module.""" from .cnumber import ComplexNumber from .exception import DisisionByNullException __version__ = "0.0.1"
# coding: utf-8 # classmethod 与 staticmethod 的区别 """ 静态方法和类方法都可以通过 类名.方法名 或 实例.方法名 的形式来访问 其中静态方法没有常规方法的特殊行为 如绑定/非绑定/隐式参数等规则 而类方法的调用使用类本身作为其隐含参数,但调用本身并不需要显示提供该参数 """ class A(object): def instance_method(self, x): print("calling instance_method instance_method(%s, %s)" % (self, x)) @classmethod def class_method(...
# -*- coding: utf-8 -*- import time import os import socket import configparser from data_common.configure import constant from data_common.designs.singleton import SingletonType class Configure(metaclass=SingletonType): CONFIG_FILE_PATH = os.path.dirname(__file__) + '/setting.ini' def __init__(self): ...
import numpy as np import scipy.stats as stats def calc(): n = 36 alpha = 0.005 mean_1 = 4.51 mean_2 = 6.28 std_1 = 1.98 std_2 = 2.54 t = (mean_1 - mean_2)/np.sqrt(std_1**2/n + std_2**2/n) # хотим альтернативу mean_1 < mean_2 q_val = stats.t.ppf(q=alpha, df=n+n-1) print('t_val...
from flask import Flask, request, url_for, redirect, flash, render_template, jsonify, session from flask_login.utils import login_user from forms import TaskForm, loginForm, signUpForm from models import User, taskDB from flask_sqlalchemy import SQLAlchemy from datetime import datetime from werkzeug.security import gen...
# import torch # from torch.optim.lr_scheduler import _LRScheduler import math class LR_Scheduler(object): """Learning Rate Scheduler Step mode: ``lr = baselr * 0.1 ^ {floor(epoch-1 / lr_step)}`` Cosine mode: ``lr = baselr * 0.5 * (1 + cos(iter/maxiter))`` Poly mode: ``lr = baselr * (1 - iter/maxite...
import personclass as pc class Student(pc.Person): def __init__(self): pc.Person.__init__(self) self.studentID = 0 self.favBooks = [] self.awards = [] self.subjects = [] def GetStudentID(self): return self.GetStudentID def GetAwards(self): ...
import itertools import collections import functools import re from flex.exceptions import MultiplePathsFound from flex.error_messages import MESSAGES from flex.constants import ( PATH, REQUEST_METHODS, ) from flex.parameters import ( find_parameter, merge_parameter_lists, dereference_parameter_lis...
import sys import argparse parser = argparse.ArgumentParser(); parser.add_argument("filename") args = parser.parse_args(); filename = args.filename data = open(filename,"r") total = 0 for line in data: line = (int(line) // 3) - 2 print line total = total + line print("the total fuel required is {}".forma...
import json import sys if __name__ == "__main__": myjson = sys.stdin.read() sys.stdin.close() jsond = json.loads(myjson) author = None if "username" in jsond[0]: author = jsond[0]["username"] else: author = jsond[0]["user"]["username"] if not author: sys.stderr.wr...
import redis import time import traceback # How to publish a START: # Start a redis client and publish START # # >redis-cli # PUBLISH startScripts START # # OR by another startScripts # r.publish('startScripts', 'START') print "PlugInMaster.py STARTED" def RedisCheck(): i = 0 try: r = redis.Strict...
from utils.utils import * if __name__ == '__main__': command = input("请输入命令(wc.exe [parameter] {file_name}):\n") parse_command(command)
import asyncio async def print_count(x): for number in range(x): print(number) await asyncio.sleep(.5) #спать 5 сек async def start(x): coroutines = [] for number in range(x): coroutines.append( asyncio.create_task(print_count(x)) ) await async...
""" The number of inversions in a disordered list is the number of pairs of elements that are inverted (out of order) in the list. [0,1] has 0 inversions [2,1] has 1 inversion (2,1) [3, 1, 2, 4] has 2 inversions (3, 2), (3, 1) [7, 5, 3, 1] has 6 inversions (7, 5), (3, 1), (5, 1), (7, 1), (5, 3), (7, 3) Given an array...
def part_one(): step = 314 buf = [0] pos = 0 val = 1 for i in range(1, 2018): pos = (pos + (step % i)) % i if pos + 1 == i: buf.append(val) else: buf.insert(pos + 1, val) pos += 1 assert buf[pos] == val, buf[pos] va...
from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.models import User, auth from django.http import HttpResponse from .models import video import os.path # Create your views here. def home1(request): if request.method == 'POST': search = request.POS...
import os,sys import requests def is_pythonista(): if 'Pythonista' in sys.executable: return True else: return False pythonista = is_pythonista() if pythonista: import console import editor def to_abs_path(*value): import os, sys if 'Pythonista' in sys.executable: abs_path = os.path.join(os.path.expan...
# -*- coding: utf-8 -*- ################################################################################################################ # @file: jjwxcbbscomments.py # @author: HuBorui # @date: 2016/12/05 # @version: Ver0.0.0.100 # @note: # @修改日志 # @author:yongjicao # @date:2017/9/12 # @note:修改评论存储方式为mysql ###########...
__version__ = "$Id$" # # SVG Graphics # import svgtypes import svgpath class SVGGraphics: def __init__(self): # current point self.cpoint = 0, 0 # current path self.cpath = svgpath.Path() # current transformation matrix (CTM) self.ctm = svgtypes.TM() ...
# -*- coding: utf-8 -*- import ast from pathlib import Path class Index(object): def indexation(self, file): raise NotImplementedError() def getTfsForDoc(self, doc): raise NotImplementedError() def getTfsForStem(self, stem): raise NotImplementedError() def getStrDoc(self, d...
import re from Context.Events.BaseEvent import BaseEvent from Context.Util.Map.Map import Map from Context.Events.EventMaps.TextCommandsMap import TextCommandsMap from Context.Database.Repository.AdminRepository import AdminRepository from Context.Util.ArgumentParser.ArgumentParser import ArgumentParser from Context....
# Generated by Django 3.1.5 on 2021-01-28 18:50 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('carwashapp', '0017_auto_20210128_2244'), ] operations = [ migrations.RemoveField( model_name='employee', ...
#!/usr/bin/env python import os import sedna import sys PROJECT_ROOT = "/simulation_data" LOG_PATH = "/simulation_data/data/log" XQUERY_LIB_PATH = "/simulation_data/glooper/lib/python" DATA_PATH = "/simulation_data/data/db" try: #configuration file must provide the value for simid, version_string and query_label...
# def lin(): # print("-="*20) # lin() # def msg(msg): # print("-="*30) # print(f"{msg:^60}") # print("-="*30) # msg("Bill") # msg("Estudando Python") # def soma(a, b): # s = a + b # print(f"{a} + {b} = {s}") # soma(2, 3) # soma(b=2, a=3) # def contador(*n): # parâmetro empacotado # ...
#!/usr/bin/python3 import sys from math import sqrt def update(existingAggregate, newValue): (count, mean, M2) = existingAggregate count += 1 delta = newValue - mean mean += delta / count delta2 = newValue - mean M2 += delta * delta2 return (count, mean, M2) (last_key, last_val) = (None,...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
# -*- coding: utf-8 -*- """ Created on Thu Dec 20 10:48:10 2018 @author: bcheung """ import pandas as pd from keras.layers import Input, Dense from keras.models import Model from keras.callbacks import TensorBoard from sklearn.model_selection import train_test_split from sklearn.preprocessing import minmax_scale clas...
class EvenNumbers: def __init__(self): self.number = 0 def __next__(self): self.number += 2 if self.number > 100: # najwyraźniej, nie chcemy liczb parzystych większych niż 100 :) raise StopIteration return self.number def __iter__(self): return self ...
# -*- coding: utf-8 -*- """ """ __author__ = "Jon-Mikkel Korsvik & Petter Bøe Hørtvedt" __email__ = "jonkors@nmbu.no & petterho@nmbu.no" from .island import Island from .visualization import Visuals from .landscape import ( Jungle, Ocean, Savanna, Mountain, Desert ) from .animals import Herbivore, Carnivore imp...
# Generated by Django 3.1.6 on 2021-03-23 20:49 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('weallcode', '0007_auto_20201229_1542'), ] operations = [ migrations.AddField( model_name='associateboardmember',...
"""Wrapper that makes an algorithm warm-starteable by observing trials from different tasks. The wrapper adds a `task_id` dimension to the search space, and uses the value of `task_id` to differentiate between the current "target" experiment (`task_id==0`) and the other experiments from the knowledge base (`task_id>0`...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Registration', fields=[ ('id', models.AutoField...
import convert from convert import lbs_to_kg out=lbs_to_kg(78) print(out) #print(convert.lbs_to_kg(78))
import pandas as pd import sys ## need change #sys.path.append(r"C:\Users\NUC Accounting\PycharmProjects\pythonProject\AUTOPROCESSOR\library\\") sys.path.append(r"C:\Users\admin\PycharmProjects\open_cv\Eccang\\") #"https://eccang.yuque.com/books/share/df2ca396-46f5-4a51-a33e-73794059bb1d" import credential import requ...
""" 问题: 行交换,然后取反 解法: class Solution(object): def flipAndInvertImage(self, A): for row in A: for i in xrange((len(row) + 1) / 2): In Python, the shortcut row[~i] = row[-i-1] = row[len(row) - 1 - i] helps us find the i-th value of the row, counting from the right. ...
#!/usr/bin/python3 # в QTDesigner создаем clock.ui # pyuic5 clock.ui -o clock.py # pip3 install -r requirements.txt import sys, json, requests, os from datetime import datetime import paho.mqtt.client as mqtt from PyQt5 import QtWidgets, QtCore, QtGui import psycopg2 as DB import clock clPRESSURE = '#B8860B' clHUMIDI...
import utils import numpy as np from plot_utils import color_abundance_map, plot_error, save_image, plot_endmembers import matplotlib.pyplot as plt def unmix_segments(X_img, segments, seg_labels, n_endmembers): X = np.empty((len(seg_labels), X_img.shape[2])) for seg in seg_labels: X[seg,:] = X_img[segm...
'''Owner commands''' import modules.commands as commands import os import json import git import sys import discord import asyncio with open("database/adminweenie.json","r") as infile: admin = json.loads(infile.read()) with open("database/storage.json", "r") as infile: storage = json.loads(infile.read()) wit...
import numpy as np from PSF_tools.gaussian_kernel_3D import gaussian_kernel_3D from PSF_tools.apply_PSFvar3Dz import apply_PSFvar3Dz def blur_alt_z(I, Nh, Nx, Ny, Sx, Sy, Sz, Phiy, Phiz, sigma, z): h_z = gaussian_kernel_3D(((Nh-1)/2).astype(int), [Sx[z], Sy[z], Sz[z]], [Phiy[z],Phiz[z]]) Iblurz = apply_PSFvar...
from datetime import timedelta from django.conf import settings from django.core.management.base import BaseCommand from django.db.models import F from cart.models import Cart class Command(BaseCommand): help = 'Deletes old carts of anonymous users' def handle(self, *args, **options): ''' O...
def IsPenta(x): if ((24*x+1)**(1/2) + 1 )%6 ==0: return True return False def Pentagon(n): return n*(3*n-1)/2 i = 1 while True: for j in range (1,i): summ = Pentagon(i) + Pentagon(j) subs = abs(Pentagon(i)- Pentagon(j)) if IsPenta(summ)==True and IsPenta(subs) == True...
#** Functions **# def assert_keys(form, keys): """assert keys exists in the form""" assert isinstance(form, dict) and isinstance(keys, list) # ensure all keys are valid for key in keys: if key not in form: raise KeyError('invalid fields') # error if number of keys is off if...
# Generated by Django 2.2.7 on 2019-12-02 23:02 from django.db import migrations, models import lab.models class Migration(migrations.Migration): dependencies = [ ('lab', '0003_auto_20191202_1826'), ] operations = [ migrations.AlterField( model_name='persona', na...
from collections import defaultdict from typing import List class MostCommonWord: def mostCommonWord(self, paragraph: str, banned: List[str]) -> str: for c in paragraph: if c in "!?',;.": paragraph=paragraph.replace(c, ' ') counts=defaultdict(int) for word in p...
from datetime import datetime import math from math import pi, sin, cos, sqrt from matplotlib.lines import Line2D import matplotlib.patches as mpatches from matplotlib.patches import Arc, Circle, Ellipse, Polygon, Wedge import matplotlib.pyplot as plt import numpy as np from typing import List PI = math.pi # DEFINE...
# Calculate Information Gain import logging import numpy as np logger = logging.getLogger(__name__) def calculate_differential_entropy_norm(sigma, base=2) -> float: """ Differential entropy of a normal distribution with standard deviation sigma is: 0.5log(2*pi*e*sigma*sigma) :param sigma: standard deviati...
""" Sets all the parameter for training and evaluation. For the datasettings see data/data_config.py """ import torch import os import numpy as np import data.prepare_data as prepare_data #In dataconfig some other important configurations are done import data.data_config as dc import re import __main__ main_file = _...
################################################################### #Akshay Chekuri (andrewid: achekuri) #driver.py #README #This file is the front end. It handles events and creates hitboxes #for all the components of the circuit. This also calculates the #colors of the voltages, etc. It basically handles user input #...
import curses, curses.panel import time from enum import Enum import audio # ----------------------------------------- # Types # ----------------------------------------- class MainPanelMode(Enum): HELP = 1 DETAILS = 2 # ----------------------------------------- # Global constants # ----------------------...
# transformation between polar and cartesian coordinates import numpy as np import jax.numpy as jnp from jax import jit, partial import dynamics # initialize random polar coordinates with dimension dim # TODO @Mathias please check if this is fine like that for random process _rng = np.random.RandomState(1293...
#!/usr/bin/env python3 from src.secretshare import SecretSharer def main(): # instantiate a secret sharer s = SecretSharer() choice = input('What would you like to do?\n(1) Share a secret\n(2) Recover one\n') if choice == '1': n = int(input('\nEnter the number of desired shares: ...
guess = str(input()) ListOfNames = [] namecount = 0 Name = input('-->') tf = True while namecount < 10: ListOfNames.append(Name) print(ListOfNames) Name = input('-->') namecount += 1 ListOfNames = sorted(ListOfNames) print(ListOfNames) print("Enter a name to search for or 'End' to en...
#!/usr/bin/python ''' Calculate the mean and standard deviation of the following list: Numbers = [1,2,3,5,88,99,55,33,41,52] ''' Numbers = [1,2,3,5,88,99,55,33,41,52] mean = sum(Numbers) / len(Numbers) print(f"Mean = {mean}") standardDeviation = (sum([(x - mean) ** 2 for x in Numbers]) / len(Numbers)) ** (1 / 2...
''' Copyright 2017 Bio-Rad Laboratories, 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 or agreed to in writi...
#!/usr/bin/env python3 import sys import socket import selectors import types import mysql.connector as mysql db = mysql.connect( host = "localhost", user = "cida", passwd = "cida", database = "cida" ) cursor = db.cursor() sel = selectors.DefaultSelector() def accept_wrapper(sock): conn, addr = ...
import numpy as np from numpy import pi from scipy.constants import h class Line(object): def __init__(self, line_dictionary,channel=10, noise_figure=6,distance_amp=80e3,b2= 21.27e-27): """ :param line_dictionary: """ self._label = line_dictionary['label'] self._length = line...
class Rectangle: def __init__(self, length=0, width=0): self.length = length self.width = width def getArea(self): return(self.length*self.width) def getPerimeter(self): return(2*(self.length+self.width)) r1 = Rectangle() r2 = Rectangle(3,4) print("Area:",r1.getArea(),"|Perimeter:",r1.getPerimeter()) print(...
from django.conf.urls import url from . import views urlpatterns = [ url(r'^scheme/$', views.SchemeView.as_view()), ]
from setuptools import setup from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='blocksec2go-ethereum', version='0.2.0', description='Wrapper for blocksec2go allowing easy hardware-bas...
#!/usr/bin/env python3 def eval_input_float(prompt): user_entry = input(prompt) try: parsed_float = float(eval(user_entry)) q_sig = False except: parsed_float = None q_sig = True return parsed_float, q_sig def prompt_user(): d = { 'working_years': 'Enter t...
from datadog import initialize, api options = { 'api_key': '8b61d94149b2d8718b1487ae2d76e6ba', 'app_key': '9d72fc44a77f1394ef465e290f08141699579e19' } # Create Monitor with thresholds initialize(**options) options = { "thresholds": { "critical": 800, "warning": 500 }, "notify_no_data": True, "n...
# Generated by Django 2.2.13 on 2021-03-29 14:39 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('schedules', '0005_auto_20210324_0222'), ] operations = [ migrations.AlterField( model_name='schedules', name='event...
################################################################################# # FOQUS Copyright (c) 2012 - 2023, by the software owners: Oak Ridge Institute # for Science and Education (ORISE), TRIAD National Security, LLC., Lawrence # Livermore National Security, LLC., The Regents of the University of # California...
def my_function(parameter): calculation = parameter * parameter return calculation print my_function(5)
#!/System/Library/Frameworks/Python.framework/Versions/Current/bin/python # -*- coding: utf-8 -*- # # Copyright 2019 Glynn Lane (primalcurve) import sys sys.path = [p for p in sys.path if p[1:6] != "Users" and p[1:8] != "Library"] # Make sure sys.path includes the necessary paths to import the various # modules needed...
import os import io import uuid import sys import cv2 import base64 import logging import glob import numpy as np from PIL import Image from io import BytesIO from flask import Flask, render_template, make_response, flash import flask import paddlehub as hub app = Flask(__name__) #run_with_ngrok(app) #starts ngrok ...
import numpy as np from sklearn.impute import KNNImputer def get_pop_steel_grad(df): pop_grade = df.groupby('МАРКА')[['произв количество плавок (цел)']].agg(sum).idxmax().values[0] return pop_grade def nul_cols(df_in): nuls = df_in.isnull().mean().to_frame().sort_values(by=0, ascending=False) nuls.c...
import demistomock as demisto from CommonServerPython import * # The script uses the Python yara library to scan a file or files ''' IMPORTS ''' import yara ''' GLOBAL VARIABLES ''' yaraLogo = "iVBORw0KGgoAAAANSUhEUgAAAR0AAABgCAYAAAAgoabQAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAC9VJREFUeNrsnW1sVFUax59pp7RQ...
from django.db import models from django.contrib.auth.models import AbstractUser import uuid from enum import Enum # Create your models here. class User(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) pass class Ingredient(models.Model): name = models.CharFiel...
class Movie(): """ This class provides a way to store movie related information Atributes: title (str) : The name of the Movie. storyline (str): All the information about the movie. running_time (str): The duration of the movie. genre (str): The type of movie. poster_im...
# Code taken and modified from: # https://mpi4py.readthedocs.io/en/stable/tutorial.html from sys import argv, exit import numpy as np import pandas as pd from hashlib import md5 # For troubleshooting import time # Global variable for now printAll = True printAll = False size = int( argv[3] ) print('input data: %...
from flask_restful import Resource, reqparse from flask_pymongo import ObjectId from datetime import datetime from werkzeug.security import generate_password_hash, check_password_hash from flask import g from .. import mongo class UserResource(Resource): def options(self, user_id): pass def get(self...
def divide_conquer(arr,p,q,r): n1 = q-p +1 n2 = r-q n3 = r-p+ 1 #print(n1,n2,n3) left = [] right = [] for i in range(n1): print(i) #print(i,p+i) #print(left[i],arr[0]) left.append(arr[p+i]) print(left) for i in range(n2): #right[i...
#coding=gbk import cv2 import numpy as np K = np.array([[414.22607, 0., 381.76500], [0., 424.64700, 276.82032], [0., 0., 1.]]) D = np.array([[0.23918, -0.23275, -0.01125, 0.01405]]) DIM = (800, 600) left_camera_matrix = np.array([[414.37962, 0., 286.74291], ...
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: n = len(nums) visited=set() l=0 r=n-1 while l<=r: sum =nums[l]+nums[r] if sum==target: return [l+1,r+1] elif sum<target: l+=1 ...
import logging, json from flask import Blueprint from flask_restful import Api, Resource, reqparse, marshal from blueprint import db from flask_jwt_extended import jwt_required, get_jwt_claims import datetime from . import * bp_kontakkami = Blueprint('kontakkami', __name__) api = Api(bp_kontakkami) class TestimoniRes...
import os, sys os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"]="" import pandas as pd import numpy as np eps = 0.004 desired = { 0: 0.36239782, 1: 0.043841336, 2: 0.075268817, 3: 0.059322034, 4: 0.075268817, 5: 0.075268817, 6: 0.043841336, 7: 0.07526881...
from ipaddress import IPv4Address, IPv6Address from next_hop import NextHop def test_next_hop_str(): nhop = NextHop(False, None, None, None) assert str(nhop) == "" nhop = NextHop(False, "if1", None, None) assert str(nhop) == "if1" nhop = NextHop(False, "if2", IPv4Address("1.2.3.4"), None) asse...
# -*- coding: utf-8 -*- # This file is part of Site Workshop, a "site object model" implementation of # content management system for small sites (eg. weblogs). # # Copyright: (c) 2005, Jarek Zgoda <jzgoda@o2.pl> # # Site Workshop is free software; you can redistribute it and/or modify it # under the terms of the GNU...
#!/usr/bin/env python """ Copyright (c) 2021 Erin Morelli. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge,...
#!/cygdrive/d/canopy/User/Scripts/python from flask import Flask, render_template, request, jsonify #from pymysql.cursors import DictCursor import pymysql as mdb import cPickle as pickle import re from load_db import DB app = Flask(__name__) @app.route('/') @app.route('/index') def index(): db = DB() cur = db.curso...
# Homework 03 part B PyPoll by Dan Boulden (main.py) # 12/2018 # Create file paths across operating systems import os # read CSV module import csv # set the path and file for the data #csvpath = os.path.relpath.join("/Resources", "election_data.csv") # this woudl use the relative patt... if I coudl get th...
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2016-12-31 19:15 from __future__ import unicode_literals import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('librecoach', '0002_auto_20161231_1614'), ] operations = [ m...
# Imports import math # Function def split_check(total, num_people): # cost_per_person = math.ceil(total / num_people) # return cost_per_person # Raise exception if num_people < 1: raise ValueError("More than one person is required to split a check.") return math.ceil(total / num_people) #...
from django.contrib import admin from .models import Book, BookNumber, Category from .models import Borrow, BorrowItem, Fine # Register your models here. class BorrowAdmin(admin.ModelAdmin): list_display = ('borrower', 'slug', 'borrow_date', 'return_date', 'is_borrowed') list_filter = ('bo...
# creates a dictionary to be used as a grid (coordinates). Stored with plain string keys. Values are empty. lX = 0 cDict = {} while lX <= 35: lY = 0 while lY <= 11: lC = str(lX) + ", " + str(lY) cDict[lC] = [] lY += 1 lX += 1 eX = 0 cDictEvents = {} while eX <= 35: eY = 0 wh...
# %load q01_plot_corr/build.py # Default imports import pandas as pd from matplotlib.pyplot import yticks, xticks, subplots, set_cmap import matplotlib.pyplot as plt plt.switch_backend('agg') data = pd.read_csv('data/house_prices_multivariate.csv') #Write your solution here: def plot_corr(data, size=11): corr = ...