text stringlengths 38 1.54M |
|---|
import tkinter
import tkinter.messagebox
class MyGUI:
def __init__(self):
self.main_window = tkinter.Tk()
self.text_frame = tkinter.Frame(self.main_window)
self.services_frame = tkinter.Frame(self.main_window)
self.button_frame = tkinter.Frame(self.main_window)
self.cb_va... |
# coding: utf-8
# # Project: Visualizing Race and Gender Representation In American Movies
#
# In this project you'll use data visualization techniques to analyze how the top 50 movies of 2016 performed according to the <a href = "https://en.wikipedia.org/wiki/Bechdel_test" target="_blank"> Bechdel Test </a>and othe... |
# -*- coding: UTF-8 -*-
# Copyright 2012-2020 Rumma & Ko Ltd
# License: GNU Affero General Public License v3 (see file COPYING for details)
from django.db import models
from django.db.models import Q
from django.conf import settings
from django.utils.text import format_lazy
from lino.api import dd, rt, _
from lino i... |
class Toolkit:
"""
Python Toolkit for interacting with the IBM i via different transports.
"""
def __init__(self, connection):
self.connection = connection
self.payload = []
def add(self, o):
"""
Add an object to the payload that will be passed to the connection.
... |
# Copyright 2019 VMware, Inc.
# SPDX-License-Indentifier: Apache-2.0
import json
from collections import OrderedDict
from numbers import Number
from .exception import TemplateEngineException
from .tags.tag_base import TagBase
from .tag_resolver import TagResolver
from .string_resolver import StringResolver
class Ele... |
import math
vectorx=[]
vectory=[]
for i in range(3):
x=int(input("Ingrese las coordenadas x: "))
y=int(input("Ingrese las coordenadas y: "))
vectorx.append(x)
vectory.append(y)
base=vectorx[2]-vectorx[0]
altura=vectory[1]-vectory[0]
hip= math.sqrt(base**2+altura**2)
perimetro=base+altura+hip
area=base*a... |
from machine import I2C
import struct
import time
import utime
class Clock:
""" CLOCK is a HT1382 I2C/3-Wire Real Time Clock with a 32 kHz crystal """
def __init__(self, i2, a = 0x68):
self.i2 = i2
self.a = a
def set(self, tt = None):
""" tt is (year, month, mday, hour, min... |
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "Hei, verden!"
@app.route("/navn")
def navn():
return f"Hei, !"
|
"""
编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
示例 1:
输入: "hello"
输出: "holle"
示例 2:
输入: "leetcode"
输出: "leotcede"
说明:
元音字母不包含字母"y"。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-vowels-of-a-string
"""
class Solution:
def reverseVowels(self, s: str) -> str:
vowels = ["a","e","i","o","u"]
size = le... |
#!/usr/bin/env python
import sys
import json
import BaseHTTPServer
#sys.path.append('/Users/surendrashrestha/Projects/degree_planner/degree_planner')
from degree_planner.degree_parser import *
from degree_planner.handbook import *
from degree_planner.degree_planner import *
from bottle import template, request, redir... |
import requests
import extruct
import validators
from pathlib import Path
headers= {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.3'}
#method to check status of url
def is_url_ok(url):
try:
return 200 == requests.head(url).status_code
... |
def get_transaction_info(sms):
credit = ['credit','credited']
debit = ['debit','debited']
transaction_type = 'none'
company = 'none'
amount = 0
if any([word in sms for word in credit]):
transaction_type = 'CREDIT'
amount = extract_amount(sms)
elif any([word in s... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 29 11:40:32 2018
@author: huyn
"""
try:
from queue import Queue as q
except:
from multiprocessing import Queue as q
# given n nodes, and edges, find the number of connected components
def bfsConnectedComponents(n,edges):
neighbors = {}
... |
import pytest
import FredMD as fmd
def test_maxfactor():
# Model should estimate the maximum number of factors as IC chooses 7 normally
x = fmd.FredMD(Nfactor=None, vintage=None, maxfactor=8, standard_method=2, ic_method=2)
assert hasattr(x, 'rawseries')
x.estimate_factors()
assert x.factors.shape... |
#!/usr/bin/env python
import argparse
import subprocess
import gzip
import time
import logging
import nltk
import pickle
import random
from nltk.tokenize.punkt import PunktWordTokenizer
def sequences(corpus):
result = []
for sentence in corpus:
result.append([(part, '') for part in sentence])
ret... |
import pytest
from unittest.mock import MagicMock
from homieclient import Device
def test_ready_no_nodes():
d = get_device_after_msgs('test-device', {
'$name': 'Test Device',
'$nodes': '',
'$state': 'ready'
})
assert d.is_ready()
def test_nodelist_no_nodes():
d = get_device_... |
"""
给你一个字符串 s 和一个字符规律 p,请你来实现一个支持 '.' 和 '*' 的正则表达式匹配。
'.' 匹配任意单个字符
'*' 匹配零个或多个前面的那一个元素
所谓匹配,是要涵盖 整个 字符串 s的,而不是部分字符串。
说明:
s 可能为空,且只包含从 a-z 的小写字母。
p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 *。
示例 1:
输入:
s = "aa"
p = "a"
输出: false
解释: "a" 无法匹配 "aa" 整个字符串。
示例 2:
输入:
s = "aa"
p = "a*"
输出: true
解释: 因为 '*' 代表可以匹配零个或多个前面的那一个元素, 在这里前... |
"""
Implement Merge Sort
*Reference: Algorithms in Python (Michael T. Goodrich)
"""
def merge(left, right, sorted_array):
i = j = 0 # i points to first index of left and j to right
# traverse, compare left array & right array value & copy into sorted_array
# There are total 4 cases:
# A) Cases when... |
def sequential_search(a_list, item):
length = len(a_list)
pos = 0
while pos < length:
if a_list[pos] == item:
return True
pos = pos + 1
return False
def ordered_sequential_search(a_list, item):
length = len(a_list)
pos = 0
while pos < length:
if a_list[po... |
#!/usr/bin/env python
##Author: rsalem
##Purpose: Model to train car to clone behavior
import tensorflow as tf
import numpy as np
import processData
import json
import h5py
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
from keras.layers import Activation, Dense, Dropout, ELU,... |
import diff
def diff_wordMode(text1, text2):
dmp = diff.diff_match_patch()
a = dmp.diff_linesToWords(text1, text2)
lineText1 = a[0]
lineText2 = a[1]
lineArray = a[2]
diffs = dmp.diff_main(lineText1, lineText2)
dmp.diff_charsToLines(diffs, lineArray)
dmp.diff_cleanupSemantic(diffs)
... |
# This file is part of Timetracker.
#
# Timetracker is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Timetracker is distributed in t... |
import mlflow
import torch
mlflow.set_experiment("Sample Model")
def train_model(hyperparam1=42, hyperparam2=9801):
with mlflow.start_run():
mlflow.log_param("hyperparam1", hyperparam1)
mlflow.log_param("hyperparam2", hyperparam2)
mlflow.log_metric("loss", 100)
print(f'training model with hyperparams ({hyperp... |
from tkinter import *
from random import randint
root = Tk()
root.title('Strong Password Generator')
root.iconbitmap('')
root.geometry("600x400")
def new_rand():
pw_entry.delete(0, END)
pw_length = int(my_entry.get())
my_password = ''
for x in range(pw_length):
my_password += chr(randint(33... |
#######################################################################################################################
#
# xyBalance
#
# We'll say that a String is xy-balanced if for all the 'x' chars in the string,
# there exists a 'y' char somewhere later in the string. So "xxy" is balanced, but "xyx" is no... |
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
import requests
from parladata.models import Person, Membership, Organization
from datetime import datetime
sklici = {'6':{'start_time': datetime(day=21, month=12, year=2011),
'end_time': datetime(day=1, month=8, year=2014),
'nep_wo': d... |
# -*- coding: utf-8 -*-
from .. import utils
class BubbleSort():
def __init__(self, array):
self.array = array
def sort(self):
sorted = self.array.copy()
swapped = True
while swapped:
swapped = False
for i in range(1, len(sorted)):
if sor... |
import logging
import threading
import sys
from libs import Leap
from core.listeners import LeapListener
class LeapMotionListenerThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
# set this thread as a daemon to terminate when the
# main program terminates.
... |
import torch
import torch.nn as nn
import torchvision.models as models
from torchvision import transforms
from torch.autograd import Variable
from PIL import Image
import numpy as np
class Model(nn.Module):
def __init__(self, params=None):
super(Model, self).__init__()
self.model1 = models.resnext101_32x8d(pretra... |
class student:
def __init__(self,name,roll):
self.name=name
self.roll=roll
self.lap = self.laptop()
def show(self):
print(self.name,self.roll)
self.lap.show()
class laptop:
def __init__(self):
self.brand='hp'
self.cpu='i5'
... |
tabela_combustivel, comando = {"1": 0, "2": 0, "3": 0}, 0
while comando != "4":
comando = input()
if comando in tabela_combustivel.keys():
tabela_combustivel[comando] += 1
print("MUITO OBRIGADO\nAlcool: {}\nGasolina: {}\nDiesel: {}".format(tabela_combustivel["1"], tabela_combustivel["2"],
... |
#!/usr/bin/env python
# encoding: utf-8
from django.urls import path
from . import views
app_name = 'comment'
urlpatterns = [
path('<int:song_id>.html', views.comment_view, name='comment_view'),
]
|
import numpy as np
import cv2
import urllib.request
# Sets up the webcam and connects to it and initalizes a variable we use for it
stream=urllib.request.urlopen('http://192.168.0.90/mjpg/video.mjpg')
bytes=b''
while True:
try:
# Takes frames from the camera that we can use
bytes+=stream.read(1638... |
## open the file 'mbox-short.txt', find the lines containing
## "X-DSPAM-Confidence:" and slice the numeric value from the end.
## convert the values to floats and give back an average
fname = input('Enter file name: ')
fh = open(fname)
count = 0
tot = 0
fin = 0
for line in fh:
if not line.startswith("X-DSPAM-Conf... |
import math, copy, sys
import numpy as np
class Map(object):
def __init__(self, size_x, size_y, offset_x, offset_y, resolution, data):
self.size_x_ = size_x
self.size_y_ = size_y
self.offset_x_ = offset_x
self.offset_y_ = offset_y
self.resolution_ = resolution
self.data_ = data
def world2m... |
# Author: Mayuri Gujja
# Functional test on a greenkart ( e-commerce application) that performs the following tasks
# 1. Searches for a keyword
# 2. Adds veggies to the cart
# 3. Proceeds to checkout
# 4. Applies promos
# 5. Does all validations in these two pages
import time
from selenium import webdriver
from selen... |
from django.urls import path, include
from file.views import *
from api.views import *
urlpatterns = [
path('filedownload', FileDownload.as_view()),
path('upfile', UpFile.as_view()),
path('getfilebytime', GetFileByTime.as_view()),
path('insertcoffer', InsertCoffer.as_view()),
path('createnote',Crea... |
import numpy as np
import copy
import numpy.random as npr
npr.seed(0)
class crp_hawkes(object):
def __init__(self, b_prior_mu, b_prior_sigma, zeta_prior_mu, zeta_prior_sigma, eta_prior_mu, eta_prior_sigma,
observation_list, max_b, particle_num = 100, c_max=20,
d_num ... |
from random import shuffle, randint, choice
from collections import deque
import card_data
import logging
from time import strftime, gmtime
class Game():
def __init__(self, hero1, hero2, deck1, deck2):
# weirdly cyclic dependency with player, game and deck
self.player1 = Player(hero=hero1, deck=No... |
import io
from .messages import Message
from .midifiles_meta import tempo2bpm, bpm2tempo
from .midifiles import MidiTrack, MetaMessage, MidiFile
MESSAGES = [
Message('program_change', channel=0, program=12, time=0),
Message('note_on', channel=0, note=64, velocity=64, time=32),
Message('note_off', channel=... |
def happy_numbers(n):
sum=0
p=[]
while True:
for i in n:
sum=sum+i**2
if sum==1:
print('Happy number')
break
elif sum in p:
print('Not A happy number')
break
else:
p.append(sum)
... |
import socket
import struct
import hashlib
import json
import blng.LogHandler as LogHandler
"""
This class provides a nice interface to read data from a multicast
socket. The payload is a dictionary in json format padded to exactly
1200 bytes.
"""
class Multicast:
DISABLE_CHECKSUM = True
CHECKSUM = "ABFJDS... |
#!/usr/bin/python
import os
from sys import argv as args
# Default settings
EPOCHS = 5
MB_SIZE = 16
ETA = .9
HIDDEN_LAYER = 30
if len(args) > 1:
if args[1] != '.': EPOCHS = int(args[1])
if len(args) > 2:
if args[2] != '.': MB_SIZE = int(args[2])
if len(args) > 3:
if args[3] != '.': ETA = float(args[3])
i... |
# Copyright (c) Yuta Saito, Yusuke Narita, and ZOZO Technologies, Inc. All rights reserved.
# Licensed under the Apache 2.0 License.
"""Off-Policy Estimators."""
from abc import ABCMeta
from abc import abstractmethod
from dataclasses import dataclass
from typing import Dict
from typing import Optional
import numpy as... |
'''
Created on 25 Oct 2016
This is a prototype piece of software that can be run on the command line that attempts to solve the issue of
deleting different elastic search contexts. It requires elastic search 2.3.0 especially the reindex API.
1. Check database to retrieve current contexts
2. Work out current (sourc... |
# Generated by Django 3.1 on 2020-09-01 01:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0006_contact'),
]
operations = [
migrations.CreateModel(
name='Order',
fields=[
('order_id', m... |
# Generated by Django 2.2.13 on 2020-10-19 08:40
import datetime
import django.core.validators
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('backManage', '0005_auto_20201019_1415'),
]
operations = [
... |
#!/usr/bin/env python
from copy import deepcopy
from unittest import TestCase, main
from wiki_nodes.http.cache import WikiCache
from wiki_nodes.testing import wiki_cache
class CacheTest(TestCase):
def test_deepcopy_cache(self):
with wiki_cache('', 12345, base_dir=':memory:') as cache:
clone ... |
import os
import unittest
from shutil import rmtree
import numpy as np
import z5py
class TestUtil(unittest.TestCase):
tmp_dir = './tmp_dir'
shape = (100, 100, 100)
chunks = (10, 10, 10)
def setUp(self):
if not os.path.exists(self.tmp_dir):
os.mkdir(self.tmp_dir)
def tearDown... |
# Generated by Django 2.0.4 on 2018-04-23 12:36
from django.contrib.gis.geos import Point
from django.db import migrations
def forwards_func(apps, schema_editor):
change_region_center(apps, schema_editor, True)
def reverse_func(apps, schema_editor):
change_region_center(apps, schema_editor, False)
class ... |
import csv
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
canada_gold_hockey = 0
usa_gold_hockey = 0
norway_gold_hockey = 0
with open('OlympicsWinter.csv') as csvfile:
reader = csv.reader(csvfile)
line = 0
for row in reader:
if line != 0:
if (row[7] == "Gold") and (row[4] == "CAN") and... |
import os
import json
author_map = {}
author_list = []
baseurl='http://dl.acm.org/'
with open('aff.json1','r') as outfile:
data_dict = json.load(outfile)
datas = data_dict['authors']
for data in datas:
record = {'link' : baseurl+data[0], 'FName' : data[4], 'MName':data[5], 'LName': data[3], 'FULL Name':data[6]}
... |
from django.conf.urls import url
import views
urlpatterns = [
url(r'^$', views.index),
url(r'^login/$', views.login, name='thewall-login'),
url(r'^register/$', views.register, name='thewall-register'),
url(r'^dashboard/$', views.dashboard, name='thewall-dashboard'),
# url(r'^login/$', views.login, ... |
error = 0
def crear_error():
error = 0
return
def add(a, b):
try:
if(a[1]==b[1]):
x = a[0]+b[0]
y = a[1]
else:
x = a[0]*b[1]+a[1]*b[0]
y = a[1]*b[1]
return (x,y)
except:
error+=1
return(None, None)
def mul(a, b):
... |
import cv2
import os
import sys
from string import Template
# first argument is the haarcascades path
face_cascade_path = sys.argv[1]
face_cascade = cv2.CascadeClassifier(os.path.expanduser(face_cascade_path))
scale_factor = 1.1
min_neighbors = 3
min_size = (30, 30)
flags = cv2.cv.CV_HAAR_SCALE_IMAGE
for filename... |
# Copyright (c) 2021 Qualcomm Technologies, Inc.
# All rights reserved.
import torch
import trimesh
def compute_normals_edges_from_mesh(data):
mesh = trimesh.Trimesh(vertices=data.pos.numpy(), faces=data.face.numpy().T, process=False)
data.normal = torch.tensor(
mesh.vertex_normals.copy(), dtype=data.... |
import numpy as np
from qtpy.QtCore import QPointF, Slot
from pymodaq.daq_utils import daq_utils as utils
from pymodaq.daq_utils.managers.roi_manager import ROIManager
from pymodaq.daq_utils.plotting.items.crosshair import Crosshair
from pymodaq.daq_utils.plotting.items.image import UniformImageItem
class Filter:
... |
from pyspark.context import SparkContext
from pyspark.sql.session import SparkSession
sc = SparkContext('local')
spark = SparkSession(sc)
'''lines = sc.textFile('mapreduce/words.txt')
lines.count()
lines.first()
'''
lines = sc.textFile('mapreduce/words.txt')
lines.count()
lines.first() |
from django.contrib.auth.models import User, Group
from rest_framework import serializers
from appmovie.models import Movie, MovieRaiting
class MovieSerializer(serializers.Serializer):
title= serializers.CharField()
duration_q = serializers.IntegerField()
director = serializers.CharField()
actor = ser... |
import os.path
def absolute_href(in_href, in_source_file_path, root_path):
# Make sure the in_source_file_path is an absolute path
assert (os.path.abspath(in_source_file_path) == os.path.normpath(in_source_file_path))
# Link is already absolute
if in_href.startswith("/"):
return in_href
#... |
#!/usr/bin/env python3
import sys
import os
import random
class FileBuffer:
def __init__(self, f):
self.f = f
self.buf = []
def __call__(self, l):
self.buf.append(l)
if len(self.buf) == 10000 :
for b in self.buf :
print(b, file = self.f)
... |
from rest_framework import serializers
from music.models import Claims
from music.models import Messages
from music.models import ChatSession
class ClaimsSerializer(serializers.ModelSerializer):
class Meta:
model = Claims
fields = ("name", "goal", "iam", "lookfor", "lat", "lon", "esttime", "wholik... |
from typing import List
import bisect
class Solution:
def maxSumSubmatrix(self, matrix: List[List[int]], k: int) -> int:
"""
https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/discuss/445540/Python-bisect-solution-(960ms-beat-71.25)
"""
def maxSumSubarray(arr: List... |
import numpy as np
import scipy.signal as signal
import matplotlib.pyplot as plt
### Constants #####
Max_puls = 196 #https://www.ntnu.no/cerg/hfmax 16.03.21
Min_puls = 35
N_fft =40248
window = 51
fps = 40
#######
raw_data = np.loadtxt("trans_2_ex/jonas_puls2_1.txt")
#raw_data = np.loadtxt("extracted/jonas4.txt")
... |
'''
Created on Nov 12, 2013
@author: rriehle
'''
#import numpy as np
#import pandas as pd
import datetime as dt
import logging
import pandas as pd
from querystring import GenerateQueryString
from tradeseries import TradeSeries
# from tradeset import TradeSet
def consolidate_tradeset(myts):
'''Return a consolida... |
# encoding: utf-8
from config import PARAMS_TYPE
# 把function的__doc__字符串转换为字典
def trans_str_to_dict(do_str):
result = {"param_explain":{}}
if not do_str:
return result
tem_list = do_str.split('\n')
for x in tem_list:
if ":description" in x:
result["description"] = x.split(":d... |
'''
4.3 列表数值练习
'''
'''
4-3 数列20
'''
for number in range(1,21):
print(number)
'''
4-4 一百万
'''
number02 = [n for n in range(1,1000001)]
print(number02)
'''
4-5 计算1~1000000的总和
'''
number = list(range(1,1000001))
print(min(number))
print(max(number))
print(sum(number))
'''
4-6 奇数
'''
ji = list(range(1,21,2))
for j... |
#!/usr/bin/env python3
import sys # imports go at the top of the file
fruits = ["Apples", "Pears", "Oranges", "Peaches"]
prompt = "\n".join(("Welcome to the fruit stand!",
"Please choose from below options:",
"1 - View all fruits",
"2 - Add a fruit",
... |
# Just a Guess Game
import random
print('Hello. What is Your name?')
name = input()
secretNumber = random.randint(1,100)
print('Well, ' + name + ', I am thinking of a number between 1 to 100')
for guessTaken in range(1,10):
print('Take a Guess.')
guess = int(input())
if guess < secretNumber:
... |
from flask import render_template, request
from jobs_flask import app
from sqlalchemy import create_engine
from sqlalchemy_utils import database_exists, create_database
import random
import re
import ast
import pandas as pd
import psycopg2
from utilities import remember_viewed_jobs
user = 'ubuntu'
host =... |
# Imports ###########################################################
import logging
from django.conf import settings
from django.http import HttpResponse
from django.views.generic.base import View
from utils.json import JSONResponseMixin
# Logging ###########################################################
logg... |
# -*- coding: utf-8 -*-
import re
import datetime
import random
from flask import render_template, flash, redirect, session, url_for, request, g, jsonify, make_response
from flask.ext.babel import gettext
from app import app, db, babel
from config import COMMUNICATIONS, LANGUAGES, CURRENCIES, IsDebug, IsDeepDebug, d... |
import math
import random
import numpy as np
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
from pytorch_msssim import ms_ssim, ssim
def quantize_per_tensor(t, bit=8, axis=-1):
if axis == -1:
t_valid = t!=0
t_min, t_max = t[t_valid].min(), t[t_... |
print('=' * 80)
print('Programa para diagnostico de pacientes con sintomas compatibles con COVID-19. ')
print('=' * 80)
edad = int(input('Ingrese la edad del paciente: '))
temperaturaCorporal = int(input('ingrese la temperatura del paciente: '))
print('Presione la tecla "s" si el paciente tiene neumonia evidenciada o... |
import matplotlib.pyplot as plt
#
## Figure
#
### Plot timelines for ALL panel and ground data, with one line in one panel
#
def FIG_all_timelines(gpta, adta, output, field_data, fignum):
fig_title = 'Figure '+str(fignum)+': '+field_data[0]+' '+field_data[1]+' '+field_data[2]+' '+field_data[3]
fig, axes = p... |
#-*coding:utf-8-*-
from flaskone import Flask,json,jsonify
from flaskone import redirect
from flaskone import url_for
app = Flask(__name__)
@app.route("/")
def index():
return "index"
# @app.route("/json")
# def demo4():
# temp_dict={
# "name":"laowang",
# "age":18
# }
# return jsonify(t... |
import rospy
import numpy as np
from nav_msgs.msg import Path
from geometry_msgs.msg import PoseStamped
from geometry_msgs.msg import Point
from interactive_markers.interactive_marker_server import *
from visualization_msgs.msg import *
import math
from tkinter import messagebox
from tkinter import filedialog
import t... |
from django.http import HttpResponse
from django.shortcuts import render
def temp(Re):
return render(Re,"home.html",{"Req":str(Re)})
def cont(Re):
orgwords=Re.GET["fulltext"]
words=orgwords.lower()
num=int()
wordlist=words.split()
num=len(wordlist)
numword=dict()
for w in wordli... |
class Solution(object):
f =
def climbStairs(self, n):
if n < 2: return 1
return self.climbStairs(n-1) + self.climbStairs(n-2)
sol = Solution()
n = 3
print sol.climbStairs(100)
|
# Define the variables
msg = input('Please write the message here: ')
n = input('How many times would you like to repeat?: ')
# Conversion
n = int(n)
# For loop for printing multiple lines
for i in range(n):
print(msg)
|
# coding=utf-8
from __future__ import unicode_literals
import os
from django.forms import widgets
from django.utils.safestring import mark_safe
from django.core.urlresolvers import reverse
from django.conf import settings
HTML = (
'<div class="s3direct" data-url="{policy_url}">'
' <div class="link-controls">... |
import unittest
from .. import TEST_DTYPES
from pytorch_metric_learning.utils import loss_and_miner_utils as lmu
import torch
class TestLossAndMinerUtils(unittest.TestCase):
@classmethod
def setUpClass(self):
self.device = torch.device('cuda')
def test_logsumexp(self):
for dtyp... |
import sys
a = " ".join(sys.argv[1:]) + " "
lines = sys.stdin.readlines()
i = 0
while i < len(lines):
line = lines[i]
details = line.split()
name = " ".join(details)
if name[12:21] == a:
print name
i = i + 1
|
#all messages are (subject, body)
from constants import CONF_NAME
account_verification = ('Please verify your account','Dear {name},\
Thank you for activating your account, we look forward to recieving.\
your presentations. To complete the process please activ... |
from googleplaces import GooglePlaces, types
def hospitalfind(my_input) :
YOUR_API_KEY = 'AIzaSyDuy19nMwHBvLvgkg9upGZkex9jqriWkQ0'
google_places = GooglePlaces(YOUR_API_KEY)
query_result = google_places.nearby_search(
location=my_input, keyword='hospital',
radius=2000, types=[t... |
# -*- coding: utf-8 -*-
# @TIME : 2021/3/28 16:11
# @AUTHOR : Xu Bai
# @FILE : __init__.py.py
# @DESCRIPTION :
from .alexnet import AlexNet
from .resnet34 import ResNet34
from .squeezenet import SqueezeNet
# 加上这两行就可以在主函数里写from models import AlexNet了
# from torchvision.models import InceptinV3
# from torchvision.models... |
from flask import Flask, session, request
from flask_restplus import fields, Resource, Api, reqparse
import re
import datetime
import os
from Helper import *
from TopicModel import *
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret key'
api = Api(app)
helper = Helper()
tm = TopicModel('model/model.p', 'model/d... |
from django.db import models
from django.db.models import permalink
# Create your models here.
class Blogpost(models.Model):
"""docstring for ClassName"""
title = models.CharField(max_length=100, unique=True)
author = models.CharField(max_length=100,unique=True)
slug = models.SlugField(max_length=100,unique=True... |
"""
Problem 5
Smallest multiple
"""
from utility.decorators import timeit, printit
from utility import math_f
def convert(l):
out = {}
for i in l:
if i in out:
out[i] += 1
else:
out[i] = 1
return out
def redu(d):
total = 1
for i in d:
tota... |
from tqdm import tqdm
import torch
import config
def train_fn(model,dataloader,optimizer):
model.train()
fin_loss = 0
tk = tqdm(dataloader,total = len(dataloader))
for data in tk:
for k,v in data.items():
data[k] = v.to(config.DEVICE)
optimizer.zero_grad()
_,loss = m... |
# from PIL import Image
import glob
import cv2
import os
import sys
input_folder = sys.argv[1] # first commandline argument sets the original images folder
for input_mask in sys.argv[2:]: # rest of command line input is list of mask images
os.makedirs(input_folder + "\\" + input_mask.split(".")[0], exist_ok=True... |
import numpy as np
import torch
from torch.utils.data.dataset import Dataset
from torchvision import transforms
from PIL import Image
from PIL import ImageOps
use_cuda = torch.cuda.is_available()
device = torch.device("cuda:0" if use_cuda else "cpu")
class CaltechBirds(Dataset):
"""Caltech-UCSD 200 Birds dataset.... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""=================================================
@Project -> File :PycharmProjects -> user
@IDE :PyCharm
@Author :Mr. toiler
@Date :1/10/2020 3:15 PM
@Desc :
=================================================="""
from web.dao.db import DB
from web.dto.user impor... |
from django.db import models
from django.urls import reverse
# Create your models here.
class TodoItem(models.Model):
title = models.CharField(max_length=50, null=True)
content = models.TextField(null=False)
def get_detail_url(self):
return reverse('detail', kwargs={'my_item':self.id})
|
# FastAPI
from fastapi import APIRouter, HTTPException, Request, Depends, status, BackgroundTasks
# SQLAlchemy
from sqlalchemy.orm import Session
# Types
from typing import List, Optional
# Custom Modules
from .. import schemas, crud
from ..dependencies import get_db, get_current_user
from ..background_functions.ema... |
#! /usr/bin/env python
# vim:sw=4 ts=4 et:
#
# Copyright (c) 2015, 2016 Torchbox Ltd.
# 2015-04-02 ft: created
# 2016-05-10 ft: modified for TS
#
from flask import Flask, request, make_response
app = Flask(__name__)
import os
from kyotocabinet import DB
import settings
def text_response(text, code = 200):
respon... |
import unittest
# import pdb; pdb.set_trace()
def digits(x):
""" Convert an Integer into list of digits .
Args : x - the number of digits we want.
Returns : A list of digits, in order, of ''x''.
>>> digits(4586378)
[4,58,6,3,7,8]
"""
digs = []
while x!= 0:
div, ... |
#!/usr/bin/env python
""" FCDR harmonisation modules
Project: H2020 FIDUCEO
Author: Arta Dilo \NPL MM
Reviewer: Peter Harris \NPL MM, Sam Hunt \NPL ECO
Date created: 12-12-2016
Last update: 02-05-2017
Version: 12.0
Perform harmonisation of a satellite... |
#!/usr/bin/python
import os
import sys
import time
import datetime
import RPi.GPIO
import RPiI2C
import socket
import struct
# DS1307 Constants.
DS1307_CTRL_OUT = 0x80
DS1307_CTRL_SQWE = 0x10
DS1307_CTRL_RATE_0 = 0x00
DS1307_CTRL_RATE_1 = 0x01
DS1307_CTRL_RATE_1HZ = 0x00
DS1307_CTRL_RATE_4KHZ = 0x01
DS1307_CTRL_RATE_... |
import time
import busio
import board
class ESPNEW:
def __init__(self, baud=115200):
self.s=busio.UART(board.TX, board.RX, baudrate=baud)
time.sleep(0.1)
self.reset()
self.s.read(self.s.in_waiting)
time.sleep(0.1)
def buildJSON(self, func, data):
toSend=b'${"f":... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.