text
stringlengths
38
1.54M
#!/usr/bin/env python # Copyright (c) 2012 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 struct import sys import threading # On Windows, the default I/O mode is O_TEXT. Set this to O_BINARY # to avoid unwanted...
#-*- coding: utf-8 -*- ##3. Να καταχωρήσετε σε λίστες τα ονόματα 20 μαθητών και τη βαθμολογία τους όπως προκύπτει ##από το άθροισμα των βαθμών τους σε 4 μαθήματα πανελλαδικής εξέτασης. ##Δηλαδή για κάθε μαθητή θα εισάγετε 4 βαθμούς αλλά στη λίστα της βαθμολογίας θα εισάγετε το ##άθροισμά τους. ##Να εμφανίσ...
''' Created on Jan 21, 2013 @author: PaymahnMoghadasian ''' DESIRED_AMOUNT = 10000 denominations = [1, 2, 5, 10, 20, 50, 100, 200] cache = [[0 for i in range(DESIRED_AMOUNT + 1)] for j in range(len(denominations))] def count(remaining_amount, curr_denom): if remaining_amount == 0 or curr_denom <= 0: ret...
import albumentations as A import torch import numpy as np from PIL import Image from PIL import ImageFile ImageFile.LOAD_TRUNCATED_IMAGES = True class Classification: def __init__(self, image_paths, targets, resize=None): self.image_paths = image_paths self.targets = targets self.resize...
#!/usr/bin/python27all import serial import picamera import time import json camera = picamera.PiCamera() ser = serial.Serial('/dev/ttyACM0',9600) s = [0] time.sleep(5) #Read serial values from arduino while True: read_serial = ser.readline() read_list = read_serial.split(",") if (len(read_list) ==4): mois...
# MODULES IMPORT import os, sys import argparse import serial from time import sleep import multiprocessing import sys import requests import json # CONST DEFINITION REQ_ENDPOINT = "http://localhost:5000" ser = None route_path = None max_n_byte = None # FUNCTIONS def sendCommand(s, debug=True): """ Par...
"""Student name: Juanwei Hu UCIntelID: juanweih Student ID: 43376858 Assignment 1: text processing PartB.py""" from PartA import * def find_common(dictA, dictB): """This functions takes two dictionaries and output the number of common words""" #runtime complexity is O(N log N)+O(N) #becaus...
from dev.Day2 import day2 def test_example(): raw_pswd = """1-3 a: abcde 1-3 b: cdefg 2-9 c: ccccccccc""".splitlines() rules, pswds = day2.parse_rules_and_pswds(raw_pswd) assert 1 == day2.count_valid_passwords(rules, pswds)
import gym import os import numpy as np from time import sleep from config import get_paths from models import DDQNLearner,DDQNPlayer from utils import make_atari,wrap_deepmind,parse_args from utils import Logger,Plotter args = parse_args() # for arg in vars(args): # print(arg, getattr(args, arg)) ENV...
import copy import logging import math from typing import Any, Dict, List, Optional import numpy as np import tree # pip install dm_tree from gymnasium.spaces import Space from ray.rllib.policy.sample_batch import SampleBatch from ray.rllib.policy.view_requirement import ViewRequirement from ray.rllib.utils.framewor...
# -*- coding: utf-8 -*- from collections import Counter n, d = map(int, raw_input().split()) result = [] o = 0 for i in xrange(d): enemies = raw_input() if enemies.count('1') == n: o += 1 else: result.append(o) if result: print(Counter(result).most_common(1)[0][1]) else: print(0...
lista = [] for x in range(0, 101): lista.append(x) #print(lista) #nos permitiran generar estructuras de datos, ya sea una lista, tupla o diccionario estructura = [x for x in range(0, 101) ] #list comprenhension tupla = tuple( (x for x in range(0, 101)) ) #tuple comprenhension tuplaPares = tuple( (x for x in rang...
# Generated by Django 2.2 on 2020-04-01 07:00 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('givebook', '0006_auto_20200331_0132'), ] operations = [ migrations.AddField( model_name='bookadd', name='reqname', ...
from app import app import pandas as pd from flask import request,jsonify import csv import math @app.route('/get-industry-graph') def get_industry_graph(): industry = request.args.get('industry') industry = industry.replace(' ', '_').lower() metric = request.args.get('metric', 'pearson') metric = m...
from ga_functions import * from fs_peptidefeatures import * import numpy as np def initial_population(imp_features): print("total number of features is ") print(len(imp_features)) print("enter number of features") k=input() k=int(k) population_dihedral = [] m=0 while m < len(imp_features)-k: popula...
# -*- coding: utf-8 -*- """ Defines: The Project, Cell and Ticket class, to handle interaction between the models and the grid. The TicketMover helper class. The Color type. """ from __future__ import annotations from datetime import datetime from typing import Optional, Dict, List, Tuple, Set import peewee...
import abc class SlackObject(metaclass=abc.ABCMeta): @classmethod @abc.abstractmethod def from_dict(cls, message_dict): pass @abc.abstractmethod def as_dict(self): pass
import os from django.core.files import File from django.db import models from django.conf import settings from django.dispatch import receiver from medcat.cdb import CDB from polymorphic.models import PolymorphicModel STATUS_CHOICES = [ (0, 'Not Validated'), (1, 'Validated'), ] BOOL_CHOICES...
''' @Descripttion: 分段函数求值 3x - 5 (x > 1) f(x) = x + 2 (-1 <= x <= 1) 5x + 3 (x < -1) @version: 0.1 @Author: 沈洁 @Date: 2019-08-16 11:24:02 @LastEditors: 沈洁 @LastEditTime: 2019-10-12 10:36:37 ''' x = float(input('x=')) if x > 1: y = 3 * x - 5 elif -1 <= x and x <= 1: y = x + 2 else: y = ...
import threading import socket ''' connect like this, ssh into pi first: > sudo nc 127.0.1.1 3000 commands: set 77.4 - sets the temperature clr - clears perviously set temperature ''' class UIServer(threading.Thread): def __init__(self, debug = False): threading.Thread.__init__(self) self.cmd = None self....
import random from random import randint numerating = random.randrange(0, 100) enum = enumerate(int(numerating)) for i in enumerate(int(numerating)): print(i) print(list(enum))
n = int(input("Digite m numero inteiro: ")) if n % 2 != 0 and n % 3 != 0 and n % 5 != 0 and n % 7 != 0: print("primo") elif n == 2 or n == 3 or n == 5 or n == 7: print("primo") else: print("não primo")
from math import ceil, sqrt def is_harshad(number): """ return if a number is harshad number or not """ sum_of_his_digits = sum([int(digit) for digit in str(number)]) try: if number % sum_of_his_digits == 0: return number % sum_of_his_digits except ZeroDivisionErro...
from model.device import deserialize from model import device from server.respond import respond from server.sns.sns_credentials import region_name, aws_access_key_id, aws_secret_access_key import boto3 import json from server.endpoints import arn_device_put_endpoint from server.sns.sns_interface import create_endpoint...
from config_parser import Config from plan2scene.common.trainer.save_reason import SaveReason import os import os.path as osp import torch from torchvision import models from torch import nn, optim import logging def save_checkpoint(output_path: str, model, optim, reason: SaveReason, epoch: int, val_total_correct, v...
# -*- coding: utf-8 -*- """ List of physical constants (SI, CGS and solar) Many constants are taken from NIST (http://physics.nist.gov/cuu/Constants/index.html) Others have their explicit reference listed. See also L{ivs.units.conversions} for advanced options, such as change the base units are changing the values o...
from Move import Move class Player: def __init__(self): self.playerID = '' self.charClass = '' # EXP = level. Calculated based on how much experience your character has, gain more exp from failed rolls (6 or less) # Level 1 = 5exp, 2 = 5+10xp (15xp), 3=5+10+15xp (30xp), etc. lvl 2...
""" extract_perfect_chroma.py Computes "perfect" chroma vectors based on the ground truth chord annotations of a file. Usage: extract_perfect_chroma.py [options] <fps> <dirs>... Arguments: <fps> frames per second <dirs> directories containing ground truth and audio files. audio fil...
""" @filename: build_dict.py @author: Matthew Mayo @modified: 2014-04-25 @description: Computes sentiment scores for tweet words *not* appearing in the existing sentiment dictionary file; optional (and recommended) redirector (>) and <newsent_fi...
# Copyright 2018 dhtech # # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file import lib def generate(host, *args): root_ca = lib.read_secret('ca-pki/cert/ca') return {'system': {'ca': root_ca['certificate']}} # vim: ts=4: sts=4: sw=4: expandtab
#!/usr/bin/env python3 # ^3^coding: utf8 # # author: superzyx # date: 2019/08/05 # usage: study #sd = input("input :") # for i in range(20): # for j in range(20): # if j >=13: # continue # print(j) # print("i=", i) # for i in range(1,201): # if i % 2 == 1 and i % 3 == 2 an...
#!/usr/bin/env python import urllib2 import time import random while True: a = urllib2.urlopen("http://hackme.builds.cc/about.php").read() if "KEY" in a: print a time.sleep(random.random()/2)
from datetime import date DOB = date(2000, 6, 12) t1 = date.today() age = t1.year - DOB.year - ((t1.month,t1.day) < (DOB.month, DOB.day)) print(age)
import configparser import os def load_config(): config = configparser.ConfigParser() script_loc = os.path.dirname(__file__) conf_file = os.path.join(script_loc, 'config.ini') config.read(conf_file) return config config = load_config() from .station_config import locations, stations
import math import torch from torch import nn from smoke.config import cfg def _make_conv_level(in_channels, out_channels, num_convs, norm_func, stride=1, dilation=1): """ make conv layers based on its number. """ modules = [] for i in range(num_convs): modules.exten...
# 121 Read both ways is the same pip = pip in both ways etc a = input("Enter a string : ") def palindrome(a): i = 0 while i <= len(a): if a[i] == a[-1-i]: i = i+1 return True return False if palindrome(a) == True: print('YES PALIN') else: print('NO PALIN')
import FWCore.ParameterSet.Config as cms TrackAssociatorByChi2ESProducer = cms.ESProducer("TrackAssociatorByChi2ESProducer", chi2cut = cms.double(25.0), beamSpot = cms.InputTag("offlineBeamSpot"), onlyDiagonal = cms.bool(False), ComponentName = cms.string('TrackAssociatorByChi2') )
from django.views.generic.base import View from product_management.forms import CategoryForm, ProductForm from product_management.models import Category, Product from django.shortcuts import render, redirect, get_object_or_404 class HomeView(View): def get(self,request): return render(request,"index.html") ...
#!/usr/bin/env python3 # # 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 # ...
class Solution(object): def angleClock(self, hour, minutes): """ :type hour: int :type minutes: int :rtype: float """ angleHour = (hour * 30 + minutes * 30.0 / 60) % 360 angleMinutes = minutes * 6 diff = abs(angleHour - angleMinutes) if diff > ...
from numpy import random import sys from Model import Model, State, load_model START = "@START" END = "~END" def main(): params = "<model_dir> <length> <output_file>" if len(sys.argv)-1 < len(params.split(" ")): print(len(sys.argv)) print(len(params.split(" "))) print("Need " + str(len...
import os import tempfile os.environ['MPLCONFIGDIR'] = tempfile.mkdtemp() from datetime import datetime from datetime import timedelta from sets import Set from matplotlib import pyplot as plt import numpy as np from collections import deque import os.path base_dir = '/data/www/quotes/' def load_quotes(dt, end=datetim...
# A sieve could be better at this, but requires a good estimate on the upper bound of the nth prime which I didn't know off hand primes = [2,3,5,7,11,13,17,19,23,29] sprimes = [2,3,5] # primes up to the square root of the biggest prime in primes n = primes[-1] while len(primes) < 10001: n += 2 if n ** 0.5 ...
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Docente' db.create_table(u'saed_docente', ( (...
#!/usr/bin/env python # coding: utf-8 # In[2]: import numpy as np import pandas as pd from sklearn import datasets from IPython.display import display, Latex, Markdown from sklearn.model_selection import train_test_split # In[6]: iris = datasets.load_iris() print(iris) # In[5]: iris_frame = pd.DataFrame(iris...
""" Desafio 026 Problema: Faça um programa que leia uma frase pelo teclado e mostre quantas vezes aparece a letra "A", em que posição ela aparece a primeira vez e em que posição ela aparece a última vez. Resolução do problema: """ frase = input('Digite uma frase: ').strip() print('Quant...
import os from pytube import YouTube path="D:\\Users\\Ali\\Downloads" url = input("Enter the link: ") try: youtube_object = YouTube(url) except: print(f"Error: Unable to open {url} YouTube object") else: print("Title: ", youtube_object.title) print(youtube_object.title[0:25]) print("Number of view...
#!/usr/bin/python # -*- coding: utf-8 -*- # note:序列与反序列化pickle import pickle import pprint import urllib2 urls='http://www.pythonchallenge.com/pc/def/banner.p' fp=urllib2.urlopen(urls) cont=pickle.load(fp) """ #方法一 def makestring(line): s='' for char,num in line: s+=char*num retur...
import tensorflow as tf def accuracy(logits, labels, batch_size): equal_pixels = tf.reduce_sum(tf.to_float(tf.equal(logits, labels))) total_pixels = batch_size * 224 * 224 * 3 return equal_pixels / total_pixels def loss(logits, labels): cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits, labels) ...
import os import numpy as np def load_digit_dataset(*args): x_train = [] y_train = [] x_test = [] y_test = [] for path in args: mnist_out = np.load(path) mnist_x_train, mnist_y_train, mnist_x_test, mnist_y_test = mnist_out['x_train'], \ ...
from django.contrib import admin from manageVideos.models import Video # Register your models here. admin.site.register(Video)
from cartesian_explorer import get_example_explorer import numpy as np import xarray import matplotlib.pyplot as plt def test_xarray_out(): ex = get_example_explorer() xar = ex.get_variables_xarray("Mass", isotope=["Pb187", "Pb186"], time_sec=np.linspace(0, 10, 100)) assert xar.shape == (2, 100) ass...
#!/usr/bin/python3 import os import math import requests def generator(text, sep=" ", option=None): try: words = text.split(sep) if option == "shuffle": __shuffle(words) elif option == "unique": # Starting from Python 3.6+, dictionares are # insertion o...
import pickle as p import numpy as np import os import matplotlib.pyplot as ply import pylab CIFAR_DIR = "D:/user/Download/cifar-10-batches-py" print(os.listdir(CIFAR_DIR)) with open(os.path.join(CIFAR_DIR,"data_batch_1"), 'rb') as f: data = p.load(f,encoding='iso-8859-1') print(type(data)) print(data.keys(...
#!/usr/bin/env python import csv import unirest SCOPUS_API_KEY = 'b3a71de2bde04544495881ed9d2f9c5b' # '6dab753e3a22e58c28b719f039cc5f45' list_of_requests = [] def remove_text_inside_brackets(text, brackets="()[]"): count = [0] * (len(brackets) // 2) # count open/close brackets saved_chars = [] for ch...
#!/usr/bin/env python lista1 = [x**2 for x in range(1,101)] lista2 = [x**3 for x in range(1,51)] #informujemy o dlugosci listy print("dlugosc listy pierwszej to {}, a drugiej to {}".format(len(lista1),len(lista2))) print("dlugosc listy pierwszej to ", len(lista1), ", a drugiej to", len(lista2) ) wpsolne = [] #to j...
#fileencoding=utf-8 #!/usr/bin/env python3 """ Demo Client for netstrings. Must be used with echo server. """ # Example 1. import socket import netstrings as ns SERVER_ADDR = '127.0.0.1' SERVER_TCP_PORT = 9000 client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_sock.connect((SERVER_ADDR, SERVER_TCP_...
import time import requests import progressbar def read(url): return requests.get(url).text class Hacker: def __init__(self, name, team): self.name = name self.team = team self.motivation = 0 self.crying = True self.progressbar = progressbar.ProgressBar(100) sel...
# -*- coding: utf-8 -*- #This example largely adapted from Flaskr, #https://github.com/mitsuhiko/flask/blob/master/examples/flaskr/flaskr.py from __future__ import with_statement from sqlite3 import dbapi2 as sqlite3 from flask import Flask, request, session, g, redirect, url_for, abort, \ render_template, flash...
from tkinter import * from PIL import Image, ImageTk ventana = Tk() ventana.geometry("700x500") Label(ventana, text="Hola, soy Andres").pack(anchor=W) imagen= Image.open('./21-tkinter/imagenes/portada.jpg') render= ImageTk.PhotoImage(imagen) Label(ventana, image=render).pack() ventana.mainloop()
# import matplotlib # matplotlib.use('Agg') from fileRead import filereader import matplotlib.pyplot as plt def DoubleHashM(): flowMap = filereader(1) plot_points = dict() with open('dhmOut.txt', 'w') as outFile: for flow in flowMap.keys(): estimated = len(flowMap[flow]) actual = estimated plot_points[...
#!/usr/bin/python import numpy as np import pandas as pd import xlsxwriter import boto3 elbdata=[] client = boto3.client('elb') res1=client.describe_load_balancers() list2=res1['LoadBalancerDescriptions'] elbit=iter(list2) for i in elbit: elbdata.append([i['LoadBalancerName'],i['DNSName'],len(i['Instances'])]) df1=...
#!/usr/bin/env python import time import serial from math import sin, cos, asin, acos, atan, sqrt, pi #angles are expressed as follows: #a0: rotation angle from straight towards controller #a1: shoulder angle where -pi/2 is flat back and 0 is straight up #a2: elbow angle where 0 folds into shoulder, pi is straight co...
''' Copyright 2015, EMC, Inc. Author(s): George Paulos This wrapper script installs OnRack into the selected stack and runs the stack init routine, no tests ''' import os import sys import subprocess # set path to common libraries sys.path.append(subprocess.check_output("git rev-parse --show-toplevel", shell=True).r...
__author__ = 'chamathsilva' for i in range(int(input())): print(["NO", "YES"][set(input()).intersection(set(input())) != set()])
from __future__ import print_function import sys import os.path import math import collections if os.path.isfile("test.inp"): sys.stdin = open("test.inp", "r") sys.stdout = open("test.out", "w") elif os.path.isfile("simplebool.inp"): sys.stdin = open("simplebool.inp", "r") sys.stdin = open("simplebool.o...
# https://atcoder.jp/contests/abc138/tasks/abc138_b N = int(input()) A = list(map(int, input().split())) bunbo = 0.0 for i in range(N): bunbo += 1/A[i] ans = 1/bunbo print(ans)
import cv2 import numpy as np clicked = False def onMouse(event,x,y,flags,param): global clicked if event == cv2.EVENT_LBUTTONUP: clicked = True cameraCapture = cv2.VideoCapture(0) cv2.namedWindow('MyWindow') cv2.setMouseCallback('MyWindow', onMouse) print('Showing camera feed. Click window or press...
import numpy from numpy import genfromtxt import pandas from scipy.spatial import distance_matrix from hub_toolbox.HubnessAnalysis import HubnessAnalysis # Dexter ana = HubnessAnalysis() ana.analyze_hubness() import hub_toolbox # load the DEXTER example dataset D, labels, vectors = hub_toolbox.IO.load_dexter() #...
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html import json # import pandas import logging import sqlite3 class BaiduPipeline(object): def __init__(self): #self.f ...
""" Rien de très intéressant à modifier ici. Va plutôt voir transforms.py """ from random import random from math import sqrt from kivy.graphics import Color, Point, GraphicException def calculate_points(x1, y1, x2, y2, steps=5): dx = x2 - x1 dy = y2 - y1 dist = sqrt(dx * dx + dy * dy) i...
from jiekou.add import add_school import requests import random s = requests.session() def test_add_school_success(): name = random.randint(100, 10000) result = add_school(name, 2, 1, "test") return result def test_add_school_remark_null(): name = random.randint(100, 10000) result = add_school(na...
import csv class Demog(object): name = "" advisor = "" year = 0 inst = "" def makeDemog(name,year,field,inst,advisor): demog = Demog() demog.name = name demog.advisor = advisor demog.year = year if inst not in ["Columbia","Cornell","Chicago","Wisconsin","Michigan","Penn", "Minn...
import json import uuid from os.path import join, isdir, dirname import shutil import tempfile import os import numpy as np import click import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import fastai from fastai.vision import ( get_annotations, ObjectItemList, get_transforms, bb_pad_coll...
import random import numpy as np from numpy import pi import pandas as pd import matplotlib.pyplot as plt ''' The point here is to show a simpler model might do better out-of-sample. Even though the complex model (linear) has a lower bias (see graph), the variance turns out to be much higher compared to the simple mo...
from .models import Final_Year_Projects from rest_framework import viewsets, permissions, generics from .serializers import FYPSerializer from django.db.models.functions import Concat from django.db.models import Value # CognitiveViewSet class FYPViewSet(viewsets.ModelViewSet): permission_classes = [perm...
import os from pathlib import Path from hypergol.cli.create_task import create_task from hypergol.hypergol_project import HypergolProject from tests.hypergol_test_case import TestRepoManager from tests.cli.hypergol_create_test_case import HypergolCreateTestCase TEST_SOURCE = """ from hypergol import Job from hypergo...
import requests r = requests.get('https://api.github.com/user', auth=('Hcque', '278696369db!')) print(r.status_code)
def validation(valid_array,data_for_validation): ''' :param valid_array: json object's key :param data_for_validation: json object :return: true(if key is present in both data_for_validation & validate_array), missing(if key is missing in valid_array) ''' for key in data_for_validation: ...
from tornado import web from model import meta, Post from handlers.base import BaseHandler class BlogPost(BaseHandler): """Blog servlet """ _path = '/post/(.+)' def get(self, alias): post = Post.by_alias(unicode(alias)) if not post: raise web.HTTPError(404) header = self.load_header() self.render('p...
import os import sys import json import gzip class ID2name_converter: """Converts gene IDs to gene names. A gtf file is required to create the mapping between gene IDs and gene names.""" def __init__(self, gtfFile): filelocation=os.path.dirname(sys.argv[0]) +"/../data/id2name.json" #Only pars...
import sys, inspect, logging from lib.releasedefinition import ReleaseDefinition from lib.release_model import ReleaseStatusSummary from collections import defaultdict logging.basicConfig(level=logging.INFO, format='%(message)s') def set_connection (project, personal_access_token, organization_url): connection = ...
# dttwitter.py import sys import requests from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream import tweepy import subprocess import sqlite3 import json import re from datetime import datetime, timedelta from secrets import * from hashids import Hashids ...
#Import libraries required for modelling import numpy as np from scipy import integrate import matplotlib.pyplot as plt # Setting up step function for power change # Note that for the purposes of DRL this could be any signal def del_p_L_func(t): if (t < 1): del_p_L = 0.00 else: del_p_L = 0.2 ...
# -*- coding: cp936 -*- __author__ = 'naivego' ''' 2017.1.17 gengx ''' import pandas as pd import numpy as np import matplotlib.pyplot as plt import csv import datetime #--------------------------------------------- gpath=r'D:\py\futs\csvf' wpath=r'D:\pythonfs\profut\csvf' symbol="IFC1.ZJ" # "CU01.SQ" # "RB.S...
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: # # Copyright 2021 The NiPreps Developers <nipreps@gmail.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may...
file5 = open("File2/Seasons.txt",'r') #file5.write("August is Autumn, May is summer ") # a - EOF -32 print(file5.seekable()) print(file5.seek(16)) print(file5.tell())
import mongoengine as mg from db.user import Users from db.book import Books from db.wants import Wants from db.order import Order from db.message import Message from mongoengine.queryset.visitor import Q from flask import jsonify class MongoDB(): def __init__(self): mg.connect('bookstore') # functi...
from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ path("", views.home, name="home"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), #url(r'^order/add...
import logging import uuid from datetime import timedelta from typing import List from fastapi import APIRouter, Depends, HTTPException, Response, status from tortoise.query_utils import Q from market.core import config from market.core.security import ( APIKEY_HEADER_NAME, authenticate_admin_user, create...
"""Combination Network for ACN""" import torch.nn as nn from utils.misc import * class BottleneckCombine(nn.Module): """Combination Network""" def __init__(self, inplanes, middleplanes, outplanes, stride=1): super(BottleneckCombine, self).__init__() self.conv1 = nn.Conv2d(inplanes, mi...
#################### ## Heat Converter ## ## By YV31 ## #################### import sys import decimal from decimal import Decimal, getcontext getcontext().rounding = decimal.ROUND_DOWN argv = sys.argv[1:] arg1, arg2, value = None, None, None """ Heat types """ # Celsius class Celsius: def __init__(se...
# import libraries from __future__ import print_function from __future__ import division import tsahelper as tsa import numpy as np import pandas as pd import os import re import tensorflow as tf import tflearn from tflearn.layers.conv import conv_2d, max_pool_2d from tflearn.layers.core import input_data, dropout, f...
import pandas as pd import numpy as np from pandas.io.parsers import * import matplotlib.pyplot as plt # pd.options.display.mpl_style = 'defaut' xl = pd.ExcelFile("C:\Users\oskar\Documents\GitHub\oo_eclipse\my_stuff\Data\Retail_turnover.xls") x = xl.parse("Sheet1") # x=pd.DataFrame(x) "Seasonally adjust...
# encoding: utf-8 # module Autodesk.Revit.UI.Events calls itself Events # from RevitAPIUI, Version=17.0.0.0, Culture=neutral, PublicKeyToken=null # by generator 1.145 # no doc # no imports # no functions # classes class ApplicationClosingEventArgs(RevitAPIPreEventArgs, IDisposable): """ The event argum...
from tempfile import NamedTemporaryFile import numpy import pandas from mfr.extensions.tabular.utilities import header_population, strip_comments, sav_to_csv def csv_pandas(fp): """Read and convert a csv file to JSON format using the pandas library :param fp: File pointer object :return: tuple of table ...
#!/usr/bin/env python3 """ Scripts to test 1 image Usage: manage.py drive [--model=<model>] [--type=(linear|categorical|tflite_linear)] Options: -h --help Show this screen. """ from docopt import docopt import donkeycar as dk from donkeycar.parts.tub_v2 import TubWriter from donkeycar.parts.datasto...
import user class Admin(user.User): """Represent aspects of user, specific to admin.""" def __init__(self, first_name, last_name, age, gender): super().__init__(first_name, last_name, age, gender) self.privileges = Privileges() def greet_user(self): """To overrride the method of parent class.""" me...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('media', '0006_auto_20151230_1426'), ] operations = [ migrations.RemoveField( model_name='flickralbum', ...
import cv2 as cv2 from pygame import mixer # Load the required library def capture_image(camId, image_nums, save_path): cam = cv2.VideoCapture(camId) count = 0 mixer.init() mixer.music.load('resources/beep-07.mp3') while count < image_nums + 1: valid, image = cam.read() if valid: ...