text stringlengths 8 6.05M |
|---|
num1 = int(input('Type your first number: '))
num2 = int(input('Type your second number: '))
print('Your numbers are: %d and %d' % (num1, num2))
num1 += 10
num2 += 20
print('After adding 10 to the first number and 20 to the second number, you get:', end=' ')
print('%d and %d' % (num1, num2))
print('Adding both numb... |
import os
import math
import time
import datetime
import cv2
import image_processing
import error_log
import session_log
import headsup
import db_query
DEFAULT_STACK = 22
def search_current_stack(screen_area, stack_collection, db):
try:
image_name = str(math.floor(time.time())) + ".png"
folder_na... |
"""
Создайте словарь:
{"city": "Москва", "temperature": "20"}
Выведите на экран значение ключа city
Уменьшите значение "temperature" на 5
Выведите на экран весь словарь
Проверьте, есть ли в словаре ключ country
Выведите значение по-умолчанию "Россия" для ключа country
Добавьте в словарь элемент date со значением '27.0... |
from flask import Flask, session, render_template, request, redirect, g, url_for
from flask import Blueprint
from werkzeug.utils import secure_filename
import os #operating system
from google.cloud import bigquery
import socket
from flask import flash
import sy... |
from tkinter import *
root = Tk()
root.title('Simple Calculator')
e = Entry(root, width=35, borderwidth=5)
e.grid(row=0, column=0, columnspan=3, padx=10, pady=10)
def button_click(number):
currentNumber = e.get()
e.delete(0, END)
e.insert(0, str(currentNumber) + str(number))
def add(operator):
glob... |
def main():
for i in range(1, 11):
for j in range(1, 11):
tulo = i * j
print("{:4d}".format(tulo), end="")
print()
main() |
# -*- encoding:utf-8 -*-
# __author__=='Gan'
# Sort a linked list using insertion sort.
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def insertionSortList(self, head):
"""
:type head... |
# Exercise 2: Using the contact list from Exercise 1 write a python function that prints
# all people whose name begins with a specific character. Your function will take two
# parameters – the character and the dictionary
def dict_print(in_dict, letter):
for key in in_dict:
if key[0].lower() == letter.low... |
# OS VALORES PODEM SER ESPECIFICADOS COMO UM INTERVALO COM INCIO, FIM E INCREMENTO, USANDO range
for x in range(10,0,-1):
print(x) |
from django.test import TestCase
from .models import Feature
from django.contrib.auth.models import User
class TestFeatureModel(TestCase):
def test_status_defaults_to_open(self):
user = User.objects.create_user(username='test_user', password='password')
feature = Feature(featureName='Test Feature',... |
from collections import defaultdict
import re
months = defaultdict(int)
keys = {}
keyValues = defaultdict(int)
expenses = open('expenses/2020 Expenses.txt')
expenses = [i.rstrip('\n') for i in expenses.readlines()]
title = expenses[0].rstrip('\n')
month = None
schoolAmount = 0
for i in expenses[3:expenses[3:].index(... |
print('hello')
class City:
def __init__(self, name):
self.name = name
self.numConnections = 0
self.childCities = []
def addconnection(self, City, distance):
self.childCities.append(City)
class Map:
def __init__(self):
self.initCities()
self.addConnections()... |
from django.urls import path
from . import views
urlpatterns = [
# path('insert_data',views.insert_data,name='insert_data'),
# path('register',views.register,name='register'),
# path('sendSimpleEmail',views.sendSimpleEmail,name='sendSimpleEmail'),
# path('home',views.login,name='login'),
path('main',views.main,na... |
class RxDrug:
def __init__(self, name, rx_ID):
self.name = name
self.rx_ID = rx_ID
self.interaction_list = []
def add_interaction(self, other_drug):
if other_drug == "*":
self.interaction_list = other_drug
else:
if other_drug not in self.interacti... |
import logging
from page_object.common_fun import Common
from page_object.desired_caps import appium_desired
from selenium.webdriver.common.by import By
class LoginView(Common):
username_type = (By.ID, 'com.tal.kaoyan:id/login_email_edittext')
password_type = (By.ID, 'com.tal.kaoyan:id/login_password_edittext'... |
#!/usr/bin/env python
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
#
# # Authors informations
#
# @author: HUC Stéphane
# @email: <[email protected]>
# @url: http://stephane-huc.net
#
# @license : BSD "Simplified" 2 clauses
#
''' Worker '''
import time
class Worker():
'''To ma... |
# create decision tree
import math
import pandas as pd
class DecisionTree:
# assigning data set to every node
def __init__(self, data_set):
self.data_set = data_set
self.visited_features = []
self.feature = [i for i in data_set.keys()]
self.target = self.feature[-1]
... |
import json
import os
import sys
import re
from http.server import BaseHTTPRequestHandler, HTTPServer
from os import curdir, sep
from urllib.parse import unquote
import active_passive_files
import search
from index import do_index, load_from_source
from spider import run_spider
hostName = "localhost"
hostPort = 9000
... |
'''
Flask-Notepad
this application store your memo using Flask
'''
# -*- coding: utf-8 -*-
from os import path
import click
from flask import redirect, url_for
from flask_login import LoginManager
from app import create_app
from model.tables import User, DB
from model.login_user_model import LoginUser
APP = create_a... |
from django.conf.urls import url
from django.urls import path, include
from django.views.generic import TemplateView
from post_app.views import *
from post_app import views
urlpatterns = [
path('', views.TextList.as_view()),
path('create/', views.create_post, name="create_post"),
path('texts/', views.tex... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
libs = {"mathplotlib", "pandas", "openpyxl"}
try:
for lib in libs:
os.system("pip install" + lib)
print("Successful")
except:
print("Failed pip install") |
#!/usr/bin/env python
# Copyright (c) 2014 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Ensure that ninja includes the .pdb as an output file from linking.
"""
import TestGyp
import os
import sys
if sys.platform == 'win32... |
import json
import pathlib
from typing import Any, Callable, List, Optional, Tuple
from urllib.parse import urlparse
from PIL import Image
from .utils import download_and_extract_archive, verify_str_arg
from .vision import VisionDataset
class CLEVRClassification(VisionDataset):
"""`CLEVR <https://cs.stanford.ed... |
from pipeline.compilers import CompilerBase
from django.core.files.base import ContentFile
from django.utils.encoding import smart_str
import scss
import os
def add_to_scss_path(path):
load_paths = scss.LOAD_PATHS.split(',') # split it up so we can a path check.
if path not in load_paths:
load_paths.append(... |
import sys
r = sys.stdin.readline
N = int(r())
arr = list(map(int, r().split()))
cnt = 0
for i in range(N) :
if arr[i] == 1 :
continue
pos = 0
num = arr[i]
j = 1
while j * j <= num :
if num % j == 0 :
if j > 1 :
pos = 1
break
j +=... |
# import sys
# import time
# sys.path.append('../vehicle')
# import odrive_manager
#
# #odrv0 = odrive_manager.OdriveManager(path=path, serial_number=serial_number).find_odrive()
# odrv0 = odrive_manager.OdriveManager(path='/dev/ttyACM0', serial_number='336B31643536').find_odrive()
#
# while(True):
# print(odrv0.ge... |
#!/usr/bin/env python
'''
Encodes the parse tree for a functional expression and provides relevant
utilities to build and evaluate the parse tree from an input string.
'''
__author__ = 'Aditya Viswanathan'
__email__ = '[email protected]'
from parse_tree_node import ParseTreeNode, ParseTreeNodeType
class ... |
#!/usr/bin/python3
from sys import argv, exit
if len(argv) == 2:
number = argv[1]
if (number.isdigit()):
number = int(number)
if number < 4:
print("N must be at least 4")
exit(1)
else:
print("N must be a number")
exit(1)
'''
1. Colocamos reina en 0... |
#!/usr/bin/env python3
import os
import pandas as pd
import numpy as np
from sklearn.feature_extraction import text
from sklearn.metrics.pairwise import cosine_similarity
transcripts = pd.read_csv("transcripts.csv")
transcripts['title']=transcripts['url'].map(lambda x:x.split("/")[-1])
def analyzeScripts():
scr... |
from django.contrib import messages
from django.contrib.auth import authenticate
from django.contrib.auth import login as auth_login, logout as auth_logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.mail import send_mail
from django.core.urlres... |
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from sklearn import metrics
import numpy as np
import pandas as pd
import jieba
from sklearn.feature_extraction.text import C... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: Spencer Caplan
# Department of Linguistics, University of Pennsylvania
# Contact: [email protected]
import sys, math, os, subprocess, glob, operator, collections
reload(sys)
sys.setdefaultencoding('utf-8')
import unicodedata
from unicodedata import n... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.jvm.resolve.jvm_tool import JvmToolBase
from pants.option.option_types import BoolOption, SkipOption
from pants.util.strutil import softwrap
class GoogleJavaFormatSubsystem(Jv... |
def owl_pic(text):
output = ""
plumage = "8WTYUIOAHXVM"
for x in text.upper():
if x in plumage:
output+=x
return "{}{}{}".format(output, "''0v0''", output[::-1])
'''
To pass the series of gates guarded by the owls, Kenneth needs to present them
each with a highly realistic portra... |
def salgan(numero):
a="salgan al sol, "
b=["revienten", "", "idiotas","paquetes"]
if numero == 1:
for i in range(2):
print (a + b[i])
print(a + b[3])
else:
for i in range(2):
print(a + b[i])
print(a + b[2])
|
# Copyright 2020 Pulser Development Team
#
# 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 i... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index),
url(r'post_response/$', views.post_response, name="post_response"),
url(r'^action?.*$', views.action),
url(r'^thanks?.*$', views.thanks),
url(r'^404$', views.error),
url(r'post_contact/$', views.post_c... |
from scipy.ndimage.morphology import binary_erosion
import numpy as np
def getQueryCount(ui,uc,qid, mm = 0):
# memory efficient
# mm: ignore value
if len(qid) == 0:
return []
ui_r = [ui[ui>mm].min(),max(ui.max(),qid.max())]
rl = mm * np.ones(1+int(ui_r[1]-ui_r[0]),uc.dtype)
rl[ui[ui>mm]... |
import requests
import json
from business import Business, Review
from privatekey import api_key
class ApiError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
# Takes in a query parameter, which should be a string with the address or place ... |
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import sys
def init():
glClearColor(1.0,1.0,1.0,0.0)
glColor3f(0.0,0.0,1.0)
glPointSize(3.0)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluOrtho2D(0.0,600.0,0.0,600.0)
def drawcircle(r,xc,yc):
pk=3-2*r
setpixel(0,r)
x,y=0,r
while(... |
import torch
import torch.nn as nn
from src.layers import *
class Generator(nn.Module):
def __init__(self):
super(Generator, self).__init__()
self.conv1 = nn.Conv1d(in_channels=128, out_channels=128,
kernel_size=15, stride=1,
padding=7)
self.conv1_gat... |
#i pledge my honor that i have abided by the Stevens Honor System - Rachel Flynn
import os
import csv
import matplotlib.pyplot as plt
def get_csv_file_path_list():
csv_dir = 'C:/Users/rayf1/Desktop/CS110project' #in zipfile
csv_file_path_list = []
for file_path in os.listdir(csv_dir):
csv_file_pat... |
import tkinter
import random
window = tkinter.Tk()
window.title("My window")
window.geometry("600x500")
label = tkinter.Label(text="0", fg="black", bg="red", font="Arial 22")
label.place(x=25, y=25)
def random_colors():
colors = ["red", "green", "blue", "gray"]
label["bg"] = random.choice(colors)
def count(... |
with open('input.txt', 'r') as f:
data = [line.strip('\n') for line in f]
mp = {}
for orbit in data:
inner, outer = orbit.split(')')
if outer not in mp:
mp[outer] = inner
def count_orbits(key):
v = mp[key]
counter = 1
while v in mp:
v = mp[v]
counter += 1
return c... |
from model.model import Cnn
from keras_segmentation.train import find_latest_checkpoint
import os
import json
from keras_segmentation.models import model_from_name
import cv2
import numpy as np
def constrastLimit(image):
img_hist_equalized = cv2.cvtColor(image, cv2.COLOR_BGR2YCrCb)
channels = cv2.split(img_hi... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-16 08:39
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('KawsWebEnter', '0003_testplanversion'),
]
operations = [
migrations.CreateM... |
机器学习分类:
有监督机器学习:给定数据集和标签X-y,训练模型,预测输出;y代表类别时是一个分类任务,y代表连续变量时是一个回归任务。
无监督机器学习:不关心有没有标签y,只是挖掘数据集X的一些内在规律。
强化学习:机器在环境(environment)中学习到策略(strategy),按策略选择一个动作(action)让对应的回报(reward)最大。
======================算法汇总===========================
----线性回归算法:
from sklearn.linear_model import *
Ridge() #岭回归
LASSO() #最小绝对值收缩和选择算法,俗... |
import unittest
import os
from visual_microphone.sound import Sound
class TestVisualMicrophone(unittest.TestCase):
def setUp(self):
pass
def test_sound_file_created(self):
s = Sound()
for i in range(0, 1000):
s.write(0.4)
self.assertTrue(os.path.isfile('sounds.wav'... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, with_statement
from tempfile import mkdtemp
from cuisine import dir_attribs as attributes
from cuisine import dir_ensure as ensure
from cuisine import dir_exists as exists
from cuisine import file_attribs_get as attributes_get
from cuisine imp... |
import ast
import datetime
import os
# returns a list with [child selection, game result, number of moves, total time of game, child_selection,...]
def get_headers():
headers = []
headers.append("subject_id")
for game in ['pre','post']:
for i in range(0, 10):
headers.append(game+'_sele... |
import os
import sys
with open("BkgFileNames.dat") as fs:
bkgnames = fs.readlines()
bkgnames = [x.strip() for x in bkgnames]
for a in bkgnames:
command="./GetWeightsBkg.sh %s %d"%(str(a),1)
os.system(command)
#command="./GetWeightsBkg.sh %s %d"%("WZTo3LNu.root",4.42965)
#command="./GetWeightsBkg.sh %s ... |
from __future__ import division
import numpy as np
import numpy.random as npr
from svae.hmm import hmm_inference
from svae.util import allclose
### parameter makers
def make_hmm_natparam(num_states, T):
row_normalize = lambda a: a / np.sum(a, axis=1, keepdims=True)
init_param = np.log(npr.rand(num_states))... |
import environement
import numpy as np
import time
def check(ave, st):
if st == 'Q':
name = 'Q-Table.npy'
elif st == 'S':
name = 'Q-Table-sarsa.npy'
evn2 = environement.Evironment_PaMaCup()
evn2.reset()
sl_dot2 = evn2.sldot
max_step2 = (evn2.r * evn2.c)
qtable2 ... |
from PyQt4 import QtGui
from PyQt4.uic.properties import QtCore
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtGui import *
from PyQt4.QtGui import *
from PyQt4 import QtGui
from PyQt4 import QtCore
from PyQt4 import QtCore, QtGui
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtGui ... |
# -*- coding: utf-8 -*-
__license__ = """
This file is part of **janitoo** project https://github.com/bibi21000/janitoo.
License : GPL(v3)
**janitoo** 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 vers... |
from django.shortcuts import render
def search(request):
return render(request, 'search/search.html', locals())
|
# Things you should be able to do.
animals = ['cat','dog', 'fish', 'gorilla', 'baloonicorn', 'monkey', 'cheese']
numbers = range(1,10)
# Write a function that takes a list and returns a new list with only the odd numbers.
def all_odd(some_list):
new_list = []
for i in range(len(some_list)):
if i % 2 ==... |
#this method directly raise an exception that remains unsolved to the user
def third_method(base_num):
raise Exception('An error hanppened when generating the class id!!!') |
from .dt import (
DatetimeDescription,
dtloc2pos,
)
from .generators import (
CustomCurve,
CustomTimedCurve,
timeseries,
)
from .search import (
closest,
previous,
)
from .tracking import trackedfunc
try:
import matplotlib
except ModuleNotFoundError:
pass
else:
from .plotting im... |
# This program says hello
print ("Hello")
print ("how many money you have?")
numberOfMoney = input()
print ("The number of money is " + numberOfMoney)
|
from flask import Flask, render_template, request, session
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
from flask_mail import Mail
from werkzeug.utils import secure_filename, redirect
import os
import random
import json
app = Flask(__name__)
with open('config.json') as c:
params = json.l... |
from django.urls import path
from .views import HomeView
from . import views
app_name = 'core'
urlpatterns = [
path('', HomeView, name='home'),
path('tutor/profile', views.TutorProfileView, name='tutorprofile'),
path('tutor/addlisting', views.AddListingView, name='addlisting'),
path('tutor/listings... |
import unittest
from katas.kyu_7.alternate_square_sum import alternate_sq_sum
class AlternateSquareSumTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(alternate_sq_sum([11, 12, 13, 14, 15]), 379)
def test_equals_2(self):
self.assertEqual(alternate_sq_sum([11, 5, 6, 11, 11... |
import numpy as np
import pandas as pd
import pytest
from prereise.gather.hydrodata.eia.helpers import scale_profile
def test_scale_profile_argument_type():
arg = ((pd.DataFrame(), [1] * 12), (pd.Series(dtype=np.float64), set([1] * 12)))
for a in arg:
with pytest.raises(TypeError):
scale_... |
from common.run_method import RunMethod
import allure
@allure.step("极数据/查询课时费")
def classFeeRating_queryClassFeeRating_get(params=None, header=None, return_json=True, **kwargs):
'''
:param: url地址后面的参数
:body: 请求体
:return_json: 是否返回json格式的响应(默认是)
:header: 请求的header
:host: 请求的环境
:return: 默认j... |
class Config:
def __init__(self):
self.image_size = (256, 256)
self.batch_size = 16
self.epochs = 3
self.classes = 31
self.base_model = 'vgg' # vgg or resnet
self.src_domain_name = 'amazon'
self.tgt_domain_name = 'dslr'
self.is_cuda = False
config = C... |
# ref : https://ai-inter1.com/python-stock_scraping/
# ref: stoop.com
""" toyota
https://stooq.com/q/d/?s=7203.jp&i=d&d1=20190601&d2=20200522&l=3
s=7203.jp:銘柄コード
d1=20190401:検索開始日付
d2=20190920:検索終了日付
l=3:ページ数
topix : https://stooq.com/t/?i=581
"""
import pandas as pd
import datetime as dt
import matplotlib.pyplo... |
"""Copyright 2008 Orbitz WorldWide
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... |
source = open("test.txt", 'r')
w_0 = open("test_0.txt", "w")
w_1 = open("test_1.txt", "w")
for x in source:
if int(x.split(" ")[-1]) == 0:
w_0.write(x)
elif int(x.split(" ")[-1]) == 1:
w_1.write(x)
|
# Implementing Different Layers
# ---------------------------------------
#
# We will illustrate how to use different types
# of layers in TensorFlow
#
# The layers of interest are:
# (1) Convolutional Layer
# (2) Activation Layer
# (3) Max-Pool Layer
# (4) Fully Connected Layer
#
# We will generate two different d... |
from django.db.models import Count
from django.shortcuts import get_object_or_404, render
from .models import Article, ArticleStatuses, NewsCategory
def home(request, category_id=None, slug=None):
category = None
if category_id:
category = get_object_or_404(NewsCategory, id=category_id)
if reque... |
# Generated by Django 3.0.5 on 2020-05-05 15:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('manageClasses', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='student',
name='afterSchool',
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 19 10:12:18 2018
@author: siva
"""
# creating dataset for voice acitivity detection
from extract_features import extract_features
import numpy as np
import os
from os.path import dirname, abspath, join
import scipy.io.wavfile as wav
import pandas a... |
class Person:
def __init__(self,firstname,lastname):
self.firstname = firstname
self.lastname = lastname
new_person = Person("Vivek","Khimani")
new_person.firstname = "Vivko"
print(new_person.firstname)
|
import os
from sv2.helpers import run_checkers
summary = "Check if coredumps are enabled"
class CoreDump:
def __init__(self, report):
self._report = report
def core_dump_enabled(self):
if os.popen("ulimit -c").read() != "0\n":
self._report.new_issue(
"It's reco... |
# Which starting number, under one million, produces the longest chain?
# Comments Section:
# - Straight forward algorithm using a cache
def collatz(x):
if x % 2 == 0:
return x/2
if x==1:
return 1
else:
return 1 + 3*x
def problem14():
cache = {}
maxn = 0
maxc = 0
f... |
"""Treadmill exceptions and utility functions.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import six
_LOGGER = logging.getLogger(__name__)
class TreadmillError(Exception):
"""Base class ... |
assignments = []
rows = 'ABCDEFGHI'
cols = '123456789'
def cross(a, b):
'''
Cross product of elements in A and elements in B.
Args:
a(list) - a list with 'ABCDEFGHI'
b(list) - a list with '123456789'
Returns:
(list) - a list consists of 'A1', 'A2', ..., 'I9'.
'''
return [s+t for s in a for t in b]
boxe... |
#!/usr/bin/env python3
import re
from blist import blist
with open('input.txt') as f:
inp = list(map(int, re.findall(r'\d+', f.read())))
circle = blist([0])
num = 1
score = [0] * inp[0]
curIndex = 0
while num <= inp[1]:
if num % 23 == 0:
curIndex = (curIndex - 7 + len(circle)) % len(circle)
p... |
# encoding: utf-8
from tastypie.paginator import * |
x = 12
print (type(x)) |
# Generated by Django 2.2.10 on 2020-03-04 16:09
import datetime
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('account', '0008_auto_20200304_0453'),
]
operations = [
migrations.AlterField(
... |
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision
from torch.autograd import Variable
from torch.utils import data
#graphs = ge... |
"""
Write a python lambda expression for calculating simple interest.
If simple interest is greater than 1000, display as “Platinum Member”, otherwise “Gold Member”.
Use the below formula to calculate the simple interest.
simple_interest=(principal_amount*duration in years*rate_of_interest)/100
Test your code by usin... |
import unittest
from katas.kyu_8.add_more_item_to_list import AddExtra
class AddExtraTestCase(unittest.TestCase):
def test_something(self):
self.assertEqual(len(AddExtra([1, 2])), 3)
def test_equals_2(self):
self.assertEqual(len(AddExtra([])), 1)
|
#multidimensional list
import random
import math
multiDlist = [[0] * 10 for i in range(10)]
multiDlist[0][1] = 10
print(multiDlist[1][1])
|
import os
import datetime, re
from flask import Flask, render_template, redirect, request
from flask_sqlalchemy import SQLAlchemy
project_dir = os.path.dirname(os.path.abspath(__file__))
database_file = "sqlite:///{}".format(os.path.join(project_dir, "contactdatabase.db"))
app = Flask(__name__)
app.config["SQLALCHE... |
# Empty dictionary
dic = {}
# user_1 = input('Enter your name :')
user_1 = 'Ankit'
# user_2 = input('Enter your name :')
user_2 = 'Anna'
# user_3 = input('Enter your name :')
user_3 = 'Ankita'
# user_4 = input('Enter your name :')
user_4 = 'Anmol'
# user_lang_1 = input('Enter your Favourite Programing Language :')
us... |
import os
from multiprocessing import Process, Queue
from sklearn.neighbors import NearestNeighbors
import pandas as pd
import seaborn as sns
os.putenv('CODA_DEFINITION', '/home/mmueller/hiwi/aeolus/')
import coda
from numpy import vstack, zeros
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matpl... |
# Generated by Django 3.2.7 on 2021-09-15 04:05
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='about',
fields=[
('id', models.BigAutoField... |
#!/usr/bin/env python
#from functions import print_f, fun
from sys import argv
import re
import numpy as np
from molecules import Cluster
def run_argparse():
import argparse
A1 = argparse.ArgumentParser()
A1.add_argument('-d', action="store_true", default=False)
A1.add_argument('-qm', dest='qm',
... |
import discord
import asyncio
from discord.ext.commands import Bot
from discord.ext import commands
import logging
logging.basicConfig(level=logging.INFO) # Helps with debugging issues
Client = discord.Client()
client = commands.Bot(command_prefix="@") #put command prefix in these quotes
@client.... |
list1 = ['1', '2', '3', '4', '5']
str2 = ".".join(list1)
print(str2) |
#Written by Roy Talman 16/8/2021
# for more support contact [email protected]
from __future__ import unicode_literals
import numpy as np
import pandas as pd
import os
import youtube_dl
from glob import glob
import librosa
import matplotlib.pyplot as plt
import pickle
import sys
CurrentFolder = os.getcwd()
# Finel r... |
def selectionsort(arr):
len_arr = len(arr)
for i in range(len_arr-1):
min_index=i
for j in range(i+1,len_arr):
if arr[min_index]>arr[j]:
min_index = j
arr[i],arr[min_index] = arr[min_index],arr[i]
arr= [72,50,10,44,8,20,100]
selectionsort(arr)
print(arr) |
#!/usr/bin/env python
import time
from math import atan, degrees, sqrt
import numpy as np
from copy import copy
# in mm
WHEEL_RADIUS = 40
ROBOT_RADIUS = 120
ROBOT_CIRCUMFERENCE = 2 * np.pi * ROBOT_RADIUS
# for 360 degrees
DISTANCE_PER_FLIP = 0.2 * np.pi * WHEEL_RADIUS
HALL_SENSOR_FLIPS = ROBOT_CIRCUMFERENCE / DISTAN... |
import numpy as np
x = np.load('x_data.npy')
y = np.load('y_data.npy')
print(x)
print(y)
print(x.shape) |
from __future__ import annotations
import os
from hypothesis import given
from hypothesis.strategies import integers
from typing import Tuple
from tm_trees import TMTree, FileSystemTree
EXAMPLE_PATH_10_FILES = ''
tree_10_file = FileSystemTree(EXAMPLE_PATH_10_FILES)
def is_valid_colour(colour: Tu... |
from pymol import cmd
def goto(pathname):
path_select = {
"drive": "D:\Users\Brahm Yachnin\Documents\Google Drive",
"design": "D:\Users\Brahm Yachnin\Documents\Google Drive\design",
"pdbs": "D:\Users\Brahm Yachnin\Documents\Google Drive\PDB Files",
"dropbox": "D:\Users\Brahm Yachnin... |
"""
Convert the raw sequence and the lables to hdf5 data/arrays for faster batch reading.
Split data into training, test and validation set. Save training and test set in same file.
Will store a .h5 file with the labels and sequences and a coord file per test/valid and train set
"""
# from __future__ import absolute_im... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.