text
stringlengths
38
1.54M
from bmb.source.SQLiteDB import SQLiteDB from bmb.source.util.enums import AliasType, Infoset from bmb.source.util.exceptions import * from bmb.source.util.sql_queries import Query from bmb.source.webscraping.tmdb_api import * fr...
import cv2 as cv import numpy as np import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt img = cv.imread('goat.jpeg',0) plt.hist(img.ravel(),256,[0,256]) plt.show() cap = cv.VideoCapture(0) while(True): ret, frame = cap.read() color = ('b', 'g', 'r') for i, col in enumerate(color): ...
# This is the code from the tutorial at https://github.com/iver56/image-regression/wiki/Tutorial import numpy as np image = [[0, 130, 255], [40, 170, 255], [80, 210, 255]] image = np.array(image) image = np.divide(image, 255.0) image_width, image_height = image.shape print("Image with shape {0}:".format(image.shape)) ...
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2017-08-26 13:40 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('registration_app', '0004_userprofile'), ] operations...
import numpy as np import scipy.spatial # Inspired by wradlib library's ipol and togrid functions. def ipol_nearest(src, trg, data): tree = scipy.spatial.cKDTree(src) dists, ix = tree.query(trg, k=1) return data[ix] def togrid(polar, x, y, gridsize=1024, lim=460): src = np.column_stack((x.ravel(), y.r...
from socket import * import threading from pyodbc import * from flask import request, jsonify # Global variables USERNAME = "" # LOGIN_NAME = "" PASSWORD = "" IP = "" CLIENTSTATUS = {} # IP : 0|1 LIST_ONLINING = {} # IP : {LoginName, UserName} USERNAME_DICT = {} # LoginName : {LoginPass , UserName, St...
# coding: utf-8 import argparse def get_config(): parser = argparse.ArgumentParser() parser.add_argument("--modelName", default="ResNet18", type=str) # 这里没有改 parser.add_argument('--batch_size', default=200, type=int) parser.add_argument('--batch_size_val', default=1, type=int) parser.add_argume...
from django.urls import path,include from django.conf.urls import url from webapp import views from .views import BlogUpdateView,BlogDeleteView app_name = 'webapp' urlpatterns = [ url(r'^blog/', views.DashBoard.as_view(),), url(r'^edit_delete_blogs/', views.AllBlogChangeView.as_view(),name="edit_delete_blogs"...
# file_compressor/file_compressor/__init__.py from .celery import celery_app __all__ = ('celery_app',)
from django.apps import apps from . import dbg_data_db ############################################ # # all base # ############################################ def del_model(model): #info_model(model) # https://docs.djangoproject.com/en/1.11/ref/models/querysets/ q = model.objects.all() q_lng = len...
import pygame as pg from random import randint window_width = 1275 window_height = 690 pg.init() win = pg.display.set_mode((window_width, window_height)) pg.display.set_caption("Kovalets Kirill IU7-23B") mario = pg.image.load('mario.png') mario2 = pg.image.load('mario2.png') background = pg.image.load(...
# Update a record in Database from tkinter import * import sqlite3 from tkinter import messagebox as msg # Functions def query(): mydb = sqlite3.connect("address_book.db") cursor = mydb.cursor() # Query the DataBase cursor.execute("SELECT *, oid FROM addresses") records = cursor....
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome("../chromedriver.exe") driver.implicitly_w...
def takeDigit(N : int) -> (int, int, int): H = N // 100 N = N % 100 T = N // 10 N = N % 10 O = N return H,T,O N = int(input()) count = 0 if (N >= 100): count = 99 for i in range(100, N+1): a,b,c = takeDigit(i) # print(str(a)+str(b)+str(c)) CD1 = a-b CD2...
import torch import hashlib import pickle from . import util class Variable(): def __init__(self, distribution=None, value=None, address_base=None, address=None, instance=None, log_prob=None, log_importance_weight=None, control=False, constants={}, name=None, obs...
import unittest class Test(unittest.TestCase): def test_true(self): self.assertTrue(1 == 1)
import unittest, sys sys.path.append('..') from serialdeserialbst import Codec, TreeNode class TestSerializeDeserializeBST(unittest.TestCase): def setUp(self): self.c = Codec() ''' 2 / \ 1 3 ''' self.tree_one = TreeNode(2, ...
from rest_framework import serializers from models import Product, Photo class ProductSerializer(serializers.ModelSerializer): photos = serializers.HyperlinkedIdentityField('photos', view_name='productphoto-list') thumb_photo = serializers.SerializerMethodField('getThumbPhoto') ingredients = serializers.CharField(r...
from django.contrib.admin.templatetags.admin_modify import * from django.contrib.admin.templatetags.admin_modify import submit_row as original_submit_row from singlemodeladmin import SingleModelAdmin from django.contrib import messages from django.db import transaction from License import bf from web import settings im...
species( label = '[CH2]OC1[CH]CC=CCC1(8457)', structure = SMILES('[CH2]OC1[CH]CC=CCC1'), E0 = (208.771,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([3000,3100,440,815,1455,1000,2750,2794.44,2838.89,2883.33,2927.78,2972.22,3016.67,3061.11,3105.56,3150,900,922.222,944.444,966.667,988.889,1...
# coding: utf-8 # flake8: noqa from __future__ import absolute_import # import models into model package from swagger_server.models.all_clinical_entity import AllClinicalEntity from swagger_server.models.all_clinical_entity_inner import AllClinicalEntityInner from swagger_server.models.approx_findby_name import Approx...
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (c) 2011 ZestyBeanz Technologies Pvt. Ltd. # (http://wwww.zbeanztech.com) # contact@zbeanztech.com # # This program is free software: you can redistribute it and/or modify # it under the...
from unittest import TestCase from pylamarck.algorithms.differential_evolution import DifferentialEvolution from pylamarck.termination import MaxSteps from pylamarck.spaces.euclidean.production import DifferentialRecombination,\ BoxConstraint from pylamarck.spaces.euclidean.production import RandomUniformSearch imp...
import os import re import mlflow import pandas as pd import fire from restaurant_reviews_allergy.dataset.base_data import create_base_data, _select_open_restaurants from restaurant_reviews_allergy.utils.mlflow_ import MlflowArtifactLogger def main(n_rows): base_data = create_base_data(n_rows) mlflow.set_ex...
nums = [] with open("input.txt") as f: nums = [int(x.strip()) for x in f.readlines()] print(nums) for a in nums: for b in nums: if a + b == 2020: print(a, b, a * b) # 279 1741 485739 # 1741 279 485739 # part2 for a in nums: for b in nums: for c in nums:...
from __future__ import absolute_import import attr from .. import Konfig class FlaskKonfig(object): __slots__ = ("konfig", "kwargs") def __init__(self, app=None, konfig=None, **kwargs): self.konfig = konfig or Konfig(strict_override=False) self.kwargs = kwargs if app: se...
# A simple parser that holds for a week import datetime import Agents.Environment from Agents.AgentException import AgentException from Helpers.stock_info import get_quote_FMP # An internal ID for use with the profiles, so as to link them AGENT_ID = "week_holder" DISPLAY_NAME = "Hold Over Week" def get_orders(new_ti...
# 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, software # distributed under the Li...
#!/usr/bin/env python import rospy import json from sensor_msgs.msg import Imu, MagneticField from std_msgs.msg import String class Filter: def __init__(self, b, a=None, k=1): """ Creates a filter object :param b: numerator coefficients of the transfer function (coeffs of X) :par...
""" Copyright (c) 2017-2022 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. """ import re from unittest.mock import patch from atomic_reactor.inner import DockerBuildWorkflow from atomic_reactor.plugin import PluginF...
import traceback import math def print_term(degree, factor): if degree == 0: # constant return str(factor) else: # degree != 0 if factor == 0: return '0' term_str = '' term_str += str(factor) if abs(factor) != 1 else '-' if factor == -1 else '' if type(degre...
from datetime import date from flask import render_template, url_for, redirect, flash, request from flask_login import current_user, login_user, logout_user from werkzeug.urls import url_parse from webapp.auth.email import send_password_reset_email from webapp.gestibank.models import User from webapp import db from w...
ORIGINAL_SCALE_NAME = '--ORIGINAL--' def slider_settings_css(settings): """ defined here because then it can be used in the widget and view that use the same .pt """ return """ .slider-container, .slider, .slider li.slide { width: %(width)ipx; height: %(height)ipx; ...
from flask import current_app from flask.ext.mail import Mail, Message __author__ = 'cankemik' def Fmail(data): user = current_app.config.get("MAIL_USER") passwd = current_app.config.get("MAIL_PASSWORD") from_addr = current_app.config.get("MAIL_USER") to_addr = data.get("from_mail") mail = Mail(...
# -*- coding: utf-8 -*- import socket from uuid import getnode as get_mac from threading import * from configreader import * from collections import deque class NetworkSender(Thread): # mac = get_mac() config = ConfigReader() cs = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server_address = (conf...
class Solution: def reconstructQueue(self, people): """ :type people: List[List[int]] :rtype: List[List[int]] """ people.sort(key=lambda p: (-p[0], p[1])) blocks = [[]] for p in people: cnt = 0 height, index = p[0], p[1] f...
import tensorflow as tf # Load MNIST data from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', one_hot=True) # Define placeholders x = tf.placeholder(tf.float32, shape=[None, 784]) y_ = tf.placeholder(tf.float32, shape=[None, 10]) # Define Variables W = tf.Variab...
import string from contextlib import suppress from datetime import timedelta from decimal import Decimal from operator import attrgetter from django.conf import settings from django.core.cache import cache from django.core.exceptions import FieldDoesNotExist from django.core.validators import MaxValueValidator, MinVal...
from django.shortcuts import render from django.conf import settings import requests from .forms import SubmitEmbed from .serializer import EmbedSerializer def save_embed(request): if request.method == "POST": form = SubmitEmbed(request.POST) print 'hola' if form.is_valid(): ...
from ray_on_aml.core import Ray_On_AML import yaml from ray.tune.tune import run_experiments from utils import callbacks import argparse if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--config', help='Path to yaml configuration file') args = parser.parse_args() ray...
#!/usr/bin/env python ############################################################################# # An implementation of the classical fib routine # with memoization added for drastic improvements # in running time. # # As demonstrated the running time goes from linear to constant in just a few # runs, compared to...
import dataclasses from dataclasses import dataclass, field import datetime import functools import pickle import pprint import subprocess import sys from collections import OrderedDict from pathlib import Path from typing import Dict, List, Union import cnmodel import numpy as np from pylibrary.tools import cprint as...
#!/usr/bin/python3 class MyInt(int): """ class MyInt inherited from int """ def __ne__(self, other): """Redefines != to mean ==""" return MyInt == MyInt def __eq__(self, other): """Redefines == to mean !=""" return MyInt != MyInt
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy class GuaziItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() sourceSite = scrapy.Field() carCityZhId = s...
class Person: def show(self,name): self.name=name print(self.name) class Student(Person): def show(self,name,age,roll): self.name=name self.age=age self.roll=roll print(self.name,self.roll,self.age) o=Student() o.show("Hari")
# Repo: https://github.com/SergheiMihailov/competitive-prog # Link to problem: https://open.kattis.com/problems/conundrum # Language: Python 2.7 s = raw_input() days = 0 for i in range(len(s)): z = len(s) - 1 - i if i % 3 == 2: if s[z ] == 'p' or s[z ] == 'P': pass else: ...
# platform: python2 MacOS import math import random import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt time = numb = 0 landa = 20.0 / 3600 * -1 while 1: data = random.random() time += math.log(data, 2) / landa numb += 1 if time > 3600: break test = str(int(time / 3600)).zfill(2) + ':' + ...
import vim # check whether the xp module is available try: import xp print 'xp module ok' except: print 'xp python module not found' # check whether xp is in the path vim.command('![[ $(type -P "xp") ]] && echo "xp is in PATH" || { echo "xp is NOT in PATH" 1>&2; exit 1; }')
import pgzrun WIDTH = 600 HEIGHT = 300 alien = Actor("alien.png") alien.pos = (WIDTH/2, HEIGHT/2) speed = 1 # nombre de pixels par update def draw(): screen.fill("white") alien.draw() def on_mouse_move(pos): alien.pos = pos pgzrun.go()
''' 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10. ''' # -*- coding:utf-8 -*- class Solution: # matrix类型为二维列表,需要返回列表 def printMatrix(self, matrix): rows=len(matrix) cols=len(matrix[0]) r...
from billy import utils from billy.utils import popularity from billy.core import db from nose.tools import with_setup def drop_everything(): db.metadata.drop() db.legislators.drop() db.bills.drop() db.committees.drop() @with_setup(drop_everything) def test_find_bill(): # simplest case db.b...
import keras from keras.layers import Dense, Conv1D, BatchNormalization, MaxPooling1D, Dropout, ELU, TimeDistributed from keras.layers import Flatten, Bidirectional, Input, LSTM, GRU from keras.models import Sequential from keras.optimizers import Adam from keras.callbacks import ModelCheckpoint, LearningRateScheduler ...
# This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe from plugcli.params import NOT_PARSED from openfecli.utils import import_thing def import_parameter(import_str: str): """Return object from a qualname, or NOT_PARSED if not valid. ...
# -*-coding:utf-8-*- import select import socket import signal import cPickle import struct SERVER_HOST = '0.0.0.0' CHAT_SERVER_NAME = 'server' def send(channel, *args): buffer = cPickle.dumps(args) value = socket.htonl(len(buffer)) size = struct.pack('L', value) channel.send(size) channel.send(...
import os import time import slackclient from slackclient import SlackClient import thorcast_utils as utils BOT_TOKEN = os.getenv('SLACK_API_TOKEN') def thorcast_slack(): sc = SlackClient(BOT_TOKEN) sc.rtm_connect(with_team_state=False) thorcast_id = sc.api_call('auth.test')['user_id'] while True: ...
"""Tests for the strided rolling class""" import numpy as np import pandas as pd import pytest from .utils import dummy_data from tsflex.features.segmenter.strided_rolling import ( TimeStridedRolling, SequenceStridedRolling, TimeIndexSampleStridedRolling, StridedRolling, ) from tsflex.features import ...
# Array1 = [1, 4, 9] + 1 will result in [1, 5, 0] # Array2 = [9, 9, 9] + 1 will result in [1, 0, 0, 0] def plus_one(arr): arr[-1] += 1 for i in reversed(range(1, len(arr))): if arr[i] != 10: break arr[i] = 0 arr[i-1] += 1 if arr[0] == 10: arr[0] = 1 arr.a...
# coding: utf-8 """ @brief test log(time=2s) """ import unittest import warnings from pyquickhelper.pycode import ExtTestCase from csharpy.csnative import start, get_clr_path class TestCsNative(ExtTestCase): def setUp(self): start() def test_get_clr_path(self): path = get_clr_path() ...
import textract import re import regex import unicodedata #PDF To Text Extraction def convert_pdf_to_txt_v2(path): try: text = textract.process(path) text=text.decode("ascii", "ignore") return text except Exception as e: print(e) pass outputDictionary={} claim=conver...
# # One-liner implementation of cPickle # from pickle import * from pickle import __doc__, __version__, format_version, compatible_formats try: from __pypy__ import builtinify except ImportError: builtinify = lambda f: f BadPickleGet = KeyError UnpickleableError = PicklingError # __________________________________...
import os import sys import json x = { 'config': os.path.dirname(os.path.realpath(__file__))+'/config/' } def warning(msg): print "Warning: "+msg def error(msg): print "Error: "+msg quit() def which(cmds): for cmd in cmds: if not os.popen("which "+cmd).read(): error("comman...
#https://www.youtube.com/watch?v=PJ4t2U15ACo&list=PLeo1K3hjS3uub3PRhdoCTY8BxMKSW7RjN&index=2&t=0s #multi threading in python '''Design a food ordering system where your python program will run two threads, Place Order: This thread will be placing an order and inserting that into a queue. This thread places new order e...
""" Pincer Search: An algorithm for Maximal Frequent Itemset (MFI) mining References: 1. Data Mining - Arjun K Pujari 2. Pincer Search: A New Algorithm for Discovering the Maximum Frequent Set - Dao-I-Lin, Zvi M. Kedem """ from itertools import combinations def generateMFCS(MFCS, infrequent_itemsets): """ Gen...
from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes from mpl_toolkits.axes_grid1.inset_locator import mark_inset import numpy as np import os base_dir = os.path.expanduser('~') path_data_save=base_dir+'/Dropbox/Monash_Uni/SO/MAC/...
import os from ..exceptions import ConfigError from .processing import mfcc, compute_vad, calc_cmvn from ..config import BaseConfig def make_safe(value): if isinstance(value, bool): return str(value).lower() return str(value) class FeatureConfig(BaseConfig): """ Class to store configuration ...
############################################################################## # CEED - Unified CEGUI asset editor # # Copyright (C) 2011-2012 Martin Preisler <martin@preisler.me> # and contributing authors (see AUTHORS file) # # This program is free software: you can redistribute it...
# -*- coding: utf-8 -*- def convert_seconds_to_time(seconds): m, s = divmod(seconds, 60) h, m = divmod(m, 60) return "%d:%02d:%02d" % (h, m, s) def make_slice(count): i = 2 slices = [0] if count >= 100000: sl = count // i while sl > 100000: i += 1 sl ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Author: Chao Huang (huangchao.cpp@gmail.com) Date: Sun Feb 25 11:40:24 2018 Brief: https://leetcode.com/problems/jump-game/description/ Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array re...
# for i in range(int(input())): # row_of_cards = input() # row = [row_of_cards[i] for i in range(len(row_of_cards))] # for j in range() for i in range(int(input())): row_of_cards = input() count = 0 row = [int(row_of_cards[i]) for i in range(len(row_of_cards))] for j in range(len(row)): ...
def printName(name, studentNumber): for count in range(5): print(name + " " + studentNumber) def givePresent(): present = input("What would you like for your birthday?") numTimes = input("How many of those would you like?") for count in range(int(numTimes)): print(" You get " + present...
# -*- coding: utf-8 -*- """ Created on Sat Jul 25 23:17:06 2020 @author: EDUTRA """ from airflow.exceptions import AirflowException from airflow.hooks.http_hook import HttpHook from airflow.models import BaseOperator from airflow.utils.decorators import apply_defaults import time class PentahoApiO...
import pytest from flopt import Variable, CustomExpression from flopt.expression import Expression @pytest.fixture(scope='function') def a(): return Variable('a', lowBound=1, upBound=3, iniValue=2, cat='Integer') @pytest.fixture(scope='function') def b(): return Variable('b', lowBound=1, upBound=3, iniValue=...
# flask calendar event posting site from flask import Flask, redirect, url_for, render_template, request, jsonify, flash import datetime from calendar import Calendar, month_name,monthrange from wtforms import Form, TextField, validators, TextAreaField from wtforms.ext.dateutil.fields import DateTimeField from flask.ex...
#!/usr/bin/env python import os, sys, string, types, re import gzip import dp_utils, ticker_lib # Regular variable names are strings. So we'll use a non-string for some # special, internal codes. This `var' holds the constructor of the chosen # Ticker*_t CTOR = ("special var", "constructor") def identity(x, *args, **...
class Response(): def __init__(self, header=False, body=False): self.header = { 'Content-Type': 'text/html' } if header: for k, v in header.iteritems(): self.header[k] = v self.body = body
#!/usr/bin/env python3 """ This module contains the Poisson class. """ class Poisson: """ Class that represents a poisson distribution. """ e = 2.7182818285 def __init__(self, data=None, lambtha=1.): """ Constructor of the class. Sets the instance attribute lambtha as float. data...
import sys with open(sys.argv[1]) as f: contents = f.read() contents = contents.replace("SPAM","1") contents = contents.replace("HAM","-1") with open(sys.argv[1],"w+") as f1: f1.write(contents)
__author__ = "Sergi Sancho, Adriana Fernandez, Eric Lopez y Gerard Marti" __credits__ = ['Sergi Sancho', 'Adriana Fernandez', 'Eric Lopez', 'Gerard Marti'] __license__ = "GPL" __version__ = "1.0"
# -*- coding: utf-8 -*- ''' Created on Nov 4, 2014 @author: lifenbo ''' '存储模板名称的标题' template_title_map = { 'ask':u'发布问题', 'settings':u'设置', }
import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl import sys, os #import pylab as P import matplotlib.cm as mplcm import matplotlib.colors as colors if len(sys.argv)>2: filenames = sys.argv[1:] else: filenames = [sys.argv[1]] Estand = 220.e9 nustand = 0.27 Fn0 = 0.1 nupeb = 0.24 Epebbulk ...
#----------------------------------------------------------------------------# # Imports #----------------------------------------------------------------------------# import json import dateutil.parser import babel from flask import Flask, render_template, request, Response, flash, redirect, url_for from flas...
''' 问题0000 图片右上角加上数字 ''' from PIL import Image,ImageFont,ImageDraw im = Image.open("./file/favicon.jpg") # 设置字体,大小 font = ImageFont.truetype('../file/MONACO.TTF',16,encoding='utf-8') w,h = im.size draw = ImageDraw.Draw(im) draw.text((w-30,0),u'180',fill=(255,4,9),font=font) im.show() try: im.save('./file/result...
age = 35 if age<30: print('Гуляй, пока молодой!') elif age>=30: print('Седена в бороду, бес в ребро!')
import lmdb import caffe import numpy as np import scipy.io as sio import matplotlib.pyplot as plt import sys which_val = sys.argv[1] # blurring_bottom, blurring_top, ft_ LMDB_path = '/home/ifsdata/scratch/cooperlab/irene/CNN_48_images/LMDB/' mean_blob = caffe.io.caffe_pb2.BlobProto() with open(LMDB_path+'40_mean.bi...
# Copyright 2017 AT&T Intellectual Property. All other rights reserved. # # 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...
from allauth.socialaccount.providers.facebook.views import FacebookOAuth2Adapter from rest_auth.registration.views import SocialLoginView class FacebookLogin(SocialLoginView): adapter_class = FacebookOAuth2Adapter def post(self, request, *args, **kwargs): result = super(FacebookLogin, self).post(requ...
#!/u/sciteam/hu2/anaconda3/bin/python import numpy as np nt = 1000 nx = 6320 ny = 4200 #sx = np.fromfile('SX', dtype='float32').reshape( f = open('SX', 'rb') v_max = 0 for i in range(nt): for j in range(nx): buf = f.read(ny * 4) dat = np.frombuffer(buf, dtype='float32') v_max = np.max(...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2016 Shunta Saito from chainer import optimizers from lib.models.faster_rcnn import FasterRCNN from lib.models.vgg16 import VGG16 import chainer import numpy as np import unittest class TestFasterRCNN(unittest.TestCase): def setUp(self): ch...
from django.shortcuts import render, redirect from django.views.generic import View from django.shortcuts import get_object_or_404 from django.urls import reverse from django.http import HttpResponse from django.core.mail import send_mail, BadHeaderError from .models import Product, Category from .utils import * from...
import select import sys import time from subprocess import Popen, PIPE if __name__ == "__main__": print("Test Passed")
import os from collections import defaultdict from functools import partial from typing import List import numpy as np import tensorflow as tf from evals.basic_func import get_acc_prec_recall from explain.nli_common import save_fn_factory from explain.pairing.lms_model import LMSModel from explain.pairing.match_predi...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from django.utils.timezone import now # Create your models here. class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default="") name = ...
4# -*- coding: utf-8 -*- """ Created on Wed Jul 29 19:52:57 2020 @author: WufeiNewPC """ #ex19 #Create the function c_a_c so we can call it later #it takes two arguements, c_c and b_o_c. def cheese_and_crackers(cheese_count, boxes_of_crackers): print(f"You have {cheese_count} cheeses!") #Print c_C...
import numpy as np import cv2 # Identify pixels above the threshold # Threshold of RGB > 160 does a nice job of identifying ground pixels only def color_thresh(img, rgb_thresh=(160, 160, 160)): # Create an array of zeros same xy size as img, but single channel color_select = np.zeros_like(img[:,:,0]) # Req...
from math import pi def area(r): area = pi*r**2 return area print(area(1)) """ map() applies a function to an iterable""" radii = [2,4,6,8,10] for r in radii: print(area(r)) print(list(map(area, radii))) elevations_ft = [('Seatte',520),('San Francisco',52),('Los Angeles',285),('Anchorage',102)] #...
class Car: def __init__(self,car_id): self.xPosition = 0 self.yPosition = 0 self.car_id = car_id self.xPositionPassenger = 0 self.yPositionPassenger = 0 self.xPositionDestination = 0 self.yPositionDestination = 0 self.goToPassenger = False self...
import json from InstaBot.path import path_top from selenium.common.exceptions import NoSuchElementException from selenium import webdriver from time import sleep from InstaBot.path import path_web_driver, path_top_10 from InstaBot.functions import login_inst, smart_sleep, scroll, check_users, exception from datetime i...
# This is an example on how to read and display an image, convert between colour spaces. # This file does not need to be included in the submission. import os.path as path import numpy as np import scipy as sp import matplotlib.pyplot as plt import skimage.io as io import skimage.color as color import skimage.util as...
from .environment_dicts import Environments class FlyParameters: def __init__(self, wind_speed, altitude, line, env_name): self.wind_speed = wind_speed self.altitude = altitude self.line = line # TODO : Payload self.env = Environments[env_name]
[]# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def recoverTree(self, root): """ :type root: TreeNode :rtype: None...