text stringlengths 38 1.54M |
|---|
import sys
def fizz_buzz(limit):
for i in range(1, limit+1):
is_fizz = (i%3 == 0)
is_buzz = (i%5 == 0)
if is_fizz and not is_buzz:
print('fizz')
elif not is_fizz and is_buzz:
print('buzz')
elif is_fizz and is_buzz:
print('fizzbuzz')
else:
print(i)
def main():
fizz_buzz(int(sys.argv[1]))
... |
from binance.client import Client
import os
import config
client = Client(config.api_key, config.api_secret)
print(client.get_asset_balance(asset='BTC')) |
import os
import sys
import openpyxl
import pandas as pa
import re
def create(name,basename):
path=sys.path[0]
dbpath=path+'/base/'+basename+'/'
result=re.search('create table (.*) \((.*)\);$',name)
table_name=result.group(1)
if (not os.path.exists(dbpath+"tableinformation.xlsx")):
... |
# Copyright (c) 2020, NVIDIA CORPORATION. All 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 by appli... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 31 17:15:27 2018
@author: MAZimmermann
"""
import socket as sk
for port in range(1, 1024):
try:
s = sk.socket(sk.AF_INET, sk.SOCK_STREAM)
s.settimeout(1000)
s.connect(('127.0.0.1', port))
print('%d:***OPEN***'%port)
s.close
... |
// https://leetcode.com/problems/the-skyline-problem
from collections import defaultdict
from heapq import heappush, heappop
class Solution(object):
def getSkyline(self, buildings):
"""
:type buildings: List[List[int]]
:rtype: List[List[int]]
"""
if not buildings:
... |
from datetime import datetime
import requests
import json
# library for importing BLS statistics through the BLS.gov API: https://github.com/OliverSherouse/bls
import bls
import pandas as pd
import numpy as np
from google.cloud import bigquery
from google.oauth2 import service_account
# import ETL functions
import et... |
from django.contrib import admin
from .models import Seminar, Booking
# Register your models here.
class SeminarAdmin(admin.ModelAdmin):
list_display = ('id', 'semi_name', 'department', 'teach_name', 'mail', 'area_of_seminar', 'semi_schedule', 'seni_men_num', 'seni_women_num', 'juni_men_num', 'juni_women_nu... |
""" Python Tree abstract base class Implementation """
class Tree(object):
""" Abstract base class for tree Implementation """
class Position(object):
""" Abstract base class representing the location of a single point """
def element(self):
""" Return element stored at this Posit... |
import json
import os
class TestData:
@staticmethod
def read_test_data_file():
helper_path = os.path.abspath(
os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
test_data_file = os.path.join(helper_path, "commons", "test_data.json")
with open(test_d... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from itertools import izip
import unittest
from gaepermission import inspector
from tekton import router
class InspectorTests(unittest.TestCase):
def test_web_paths_generator(self):
generator = inspector.web_paths('routes')... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Redundant plotting functions to be removed from AC_tools
Notes
-------
- These functions are a mixture fo those made redundant by shift from matplotlib's basemap to cartopy and those that are now longer in use/years old/not useful/not pythonic
"""
import sys
# - Require... |
# property(fget=None, fset=None, fdel=None, doc=None)
# class이며, property attribute를 돌려준다.
# fget : attribute value를 가져오는 함수를 제공하면 된다.
# 기본값 = None
# fset : attribute value를 설정하는 함수를 제공하면 된다.
# 기본값 = None
# fdel : attribute value를 삭제하는 함수를 제공하면 된다.
# 기본값 = None
# doc : attribute에 대한 문서(docstring)이 ... |
#!/usr/bin/env python3
# Created by: Cameron Carter
# Created on May 2021
# This program loops to find factorial of a number
import string
def main():
# This function gets the factorial of a number
# Input
input_as_string = str(input("Enter a positive integer: "))
loop_counter = 0
total = 1
... |
# Generated by Django 2.2.11 on 2020-03-29 15:30
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sol', '0010_auto_20200329_2051'),
]
operations = [
migrations.RemoveField(
model_name='com_order_mapper',
... |
num = 16
ans = 2
step = 16000000
direct_0 = 1
count = 0
while num != ans ** 2:
if num > ans ** 2:
direct_1 = 1
else:
direct_1 = -1
if direct_0 != direct_1:
while ans <= step:
step //= 2
# step *= 2
if step == 1:
print('thats all')
break
ans += step * direct_1
print(f'num {num}\tans {ans}\tan... |
import numpy
import matplotlib.pyplot as pyplot
import pickle
import PIL
import PIL.Image as Image
from os import listdir
from os.path import isfile, join
# set a randomseed
numpy.random.seed(69)
def images_to_bmp(path, newpath):
onlyfiles = [fil for fil in listdir(path) if isfile(join(path, fil))]
# itera... |
from collections import Counter
new_data = "whitehatjunior"
data = Counter(new_data)
# print(data)
new_list = data.items()
print(new_list)
|
'''
name:
parabole_gradient.py
type:
script
'''
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return x**2
arguments = np.arange(-1, 1, 0.05)
plt.plot(arguments, f(arguments))
c = 0.4
E = 0.00001
epochs = 3
positions = np.zeros(epochs)
x = np.zeros(epochs)
y = np.zeros(epochs)
x[0] = 1.2
y[... |
from django.shortcuts import render,render_to_response
from NewPuppies.models import Pair,imagesPair
# Create your views here.
def weSharePuppies_view(request):
weHavePuppies = Pair.objects.filter(pairWanted=False).filter(pairIsPast=False)
weWaitPuppies = Pair.objects.filter(pairWanted=True).filter(pairIsPast=False... |
from django.shortcuts import render
from django.views.generic.base import View
from pure_pagination import Paginator, PageNotAnInteger
from django.http import JsonResponse
from django.db.models import Q
from apps.organizations.models import CourseOrg
from apps.organizations.models import City, Teacher
from apps.organi... |
from fastapi import FastAPI
from app.infra.sql_app import models
from app.infra.sql_app.db import Base, engine
async def connect_to_db() -> None:
models.Base.metadata.create_all(bind=engine)
return Base
async def close_db_connection(app: FastAPI) -> None:
await app.state.pool.close()
|
"""ToDo Model."""
import sqlite3
import datetime
from pathlib import Path
DATABASE = Path().home()/'.config'/'todo'/'_todo.sqlite3'
TABLES = """
create table tasks (
task_id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT,
description TEXT,
create_at TIMESTAMP,
update_at TIMESTAMP,
... |
from django.contrib import admin
from .models import Properties, Property_Applications, Property_Reviews, Schedule_Viewing, Property_Images
admin.site.register(Properties)
admin.site.register(Property_Applications)
admin.site.register(Property_Reviews)
admin.site.register(Schedule_Viewing)
admin.site.register(Propert... |
#!/usr/bin/env python
import os
import sys
import json
import shutil
import string
import time
import subprocess
import argparse
import re
import httplib
import tempfile
import zipfile
import shutil
from urllib import quote, unquote
from httplib import HTTPSConnection, HTTPConnection
BLACKLIST = [".hg"]
README = "REA... |
# 多轮对话的form码
form_ask = """
<link rel="shortcut icon" href="./statics/img/logo.ico" />
<script src="./statics/js/jquery-1.8.2.min.js"></script>
<script src="./statics/js/common.js"></script>
<link href="./statics/css/style.css" rel="stylesheet" type="text/css" />
<script language="javascript" src="./statics/search... |
#!python
"""
The series, 11 + 22 + 33 + ... + 1010 = 10405071317.
Find the last ten digits of the series, 11 + 22 + 33 + ... + 10001000.
"""
if __name__=="__main__":
n = 1000
print(str(sum([(i+1)**(i+1) for i in range(n)]))[-10:])
|
"""Graph Visualizer for the VH diagram."""
__authors__ = [
"Maxime Rambosson <Maxime.Rambosson@etu.unige.ch>",
]
from PyQt5.QtWidgets import (QWidget, QFrame, QHBoxLayout, QVBoxLayout,
QLabel, QGridLayout)
from PyQt5.QtCore import Qt, QPoint, QSize
from PyQt5.QtGui import QPainter, ... |
from django.conf.urls import url, include
from core.application import Application
from . import views
class BettingApplication(Application):
name = 'betting'
def get_urls(self):
urls = [
url(r'^statistics/$', views.StatisticsView.as_view(), name='statistics'),
url(r'^predict... |
import Pyro4
class Client:
def __init__(self):
self.nameserver = Pyro4.locateNS()
def get_messages(self):
server = self.get_server()
return server.get_messages()
def echo(self, message):
server = self.get_server()
server.add_message(message)
def get_server(s... |
from django.template import Library
register = Library()
@register.filter(name='ranged')
def ranged(number):
return range(number)
|
from domain.Produs import Produs
class Controller:
def __init__(self, repo):
"""
Contructor service
:param repo: Repository (instanta de repository)
"""
self.__repo = repo
self.__undo_list = []
def creeaza_produs(self, pid, nume, pret):
"""
Serv... |
#label: link/sort difficulty: medium
"""
思路:
新建链表,把输入链表的每一个节点依次插入到新链表对应的位置。
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
if not head or n... |
from aip import AipFace
import base64
# 用户信息查询
APP_ID = ''
API_KEY = ''
SECRET_KEY = ''
client = AipFace(APP_ID, API_KEY, SECRET_KEY)
groupId = "user_admin"
userId = "user1"
""" 调用获取用户人脸列表 """
res = client.faceGetlist(userId, groupId);
"""
{
'error_code': 0,
'error_msg': 'SUCCESS',
'log_id': 305486881649014192,
... |
#_author:leo gao
#encoding:utf-8
name_check_again_add_user_data_one = {
'serial_num': '1_name_check_again',
'name': 'namecheckname1',
'account': 'namecheck1'
}
name_check_again_add_user_data_two = {
'serial_num': '2_name_check_again',
'name': 'namecheckname2',
'account': 'namecheck2'
} |
fname = input("Insert file name: ")
if len(fname) < 1 :
fname = "email_data.txt"
fopen = open(fname)
count = dict()
for lines in fopen:
if lines.startswith("From:"):
data = lines.split()
email = data[1]
#print(email)
if email not in count :
count[emai... |
# https://blog.csdn.net/yangjingjing9/article/details/77069723
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def generateTrees(self, n: int) -> List[TreeNode]:
if n < 1:
... |
# Generated by Django 2.2.6 on 2021-03-06 08:44
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('posts', '0004_auto_20210129_1936'),
]
operations = [
migrations.AlterField(
model_name='group',... |
import datetime
from django.db import models
from django.utils import timezone # ne zaboravi import za was_published_recently
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.questio... |
import time
from common.dailys import Ninety
from text.del_txt import re_file_ninety
from util.data_deal import DateDeal
from util.fast import do_fast
from util.send_email_ninety import SendEN
b = Ninety()
mail = SendEN()
datedeal = DateDeal()
# 拿 城市编码 ,城市名称, 经度, 纬度
accucode, cityname, geolong, geolat = datedeal.chin... |
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(21, GPIO.OUT) #GREEN
GPIO.setup(20, GPIO.OUT) #RED
try:
while True:
GPIO.output(20,True) #RED ON
GPIO.output(21,False) #GREEN OFF
time.sleep(1)
GPIO.output(20,False) #RED OFF
GPIO.output(21... |
class LearningProblem(object):
"""Generic learning problem."""
def __init__(self):
pass
def init(self):
raise NotImplementedError()
def next(self, iteration=None):
raise NotImplementedError()
def update(self, update):
# Returns a list of new le... |
"""Test all ConfigStore implementations
"""
import getpass
import os
from copy import copy
import smif.data_layer.database.setup_database
from pytest import fixture, mark, param, raises
from smif.data_layer.database_interface import DbConfigStore
from smif.data_layer.file.file_config_store import YamlConfigStore
from ... |
image = [
list("...#######........"),
list("...#.....#........"),
list("...#.....#........"),
list("...#..######......"),
list("...#..#....#......"),
list("...####....######."),
list("....#...........#."),
list("....#############."),
list(".................."),
]
def print_image():... |
'''
스페이드 다이아 하트 클로버
1~13번까지 있음
같은 카드 나오면 error
각 카드 몇장이 더 필요한가?
input 받은 값 S01/D02/H03/H04 이런식으로 무늬와 번호가 주어짐
세개씩 잘라서 한 set에 넣어두고, len이 4가 아니라면 error!
'''
import sys
sys.stdin = open('input.txt','r')
T = int(input())
for tc in range(1,T+1):
c_list ={'S':13,'D':13,'H':13,'C':13}
card = input()
card_set = se... |
import os
import json
PROBLEM_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
DATA_DIR = f'{PROBLEM_DIR}/data'
RESULTS_DIR = f'{PROBLEM_DIR}/results'
from sklearn.cluster import AgglomerativeClustering
import numpy as np
def loadProblems(fn):
ret = {}
fp = open(fn, 'r')
num_test,... |
g,r=map(int,input().split())
for j in range(g+1,r):
ch=j
fnd=0
while (j>0):
s=j%10
fnd=fnd+(s**3)
j=j//10
if(fnd==ch):
print(fnd,end=" ")
|
#!/usr/bin/python3
from urllib.request import urlopen
import datetime
import sys
#Do a pass arguments thing
#URL
#Date/File format
#Path
#Default URL (Make this an Argument)
url = 'https://www.navcen.uscg.gov/?pageName=iipB12Out'
#Don't need (Is for testing)
file = 'garbagehtml.txt'
#Connection and download, s... |
import numpy as np
import tensorflow as tf
import sys
import time
class VaROpt:
def __init__(
self,
xdim,
zdim,
xbound,
# # n_func
# n_func,
# Let us focus on n_func = 1 for easier implementation of
# searching for the quantile
f, # return a... |
import requests
import re
subjective = [
' obvious ' ,
' certain ' ,
' abundant ' ,
' billions ' ,
' enough ' ,
' few ' ,
' full ' ,
' hundreds ' ,
' incalculable ' ,
' limited ' ,
' generally '
' little ' ,
' many ' ,
' most ' ,
' millions ' ,
' numerous... |
'''
Date: 25 June 2018
Purpose: Dedup files based on entity matching api
Data Integration Assignment 3
SUBMISSION BY: GROUP B
NAME: Abhishek Shrestha (Matr. Nummer: 390055)
Jia Jia (Matr. Nummer: 389917)
Syed Salman Ali (Matr. Nummer: 395898)
<git> https://gitlab.tu-berlin.de/mandir1... |
#create a list with 5 branches in SOIS.try to do append,insert,sort,reverse sort
list=['ewt','vir','vlsi','iot','bigdata']
print(list)
#to append
list.append('cloud')
print(list)
#to insert
list.insert(1,'aes')
print(list)
#t0 sort
list.sort()
print(list)
#to reverse sort
list.reverse()
print(list)
|
# builder pattern
from collections import OrderedDict
from string import Template
class RedshiftTable():
def __init__(self, name):
self.name = name
self.columns = OrderedDict()
self.distkey = None
self.sortkey = []
def add_column(self, column_name, definition):
... |
# encoding: utf-8
"""
To start MadGUI type at your terminal:
python -m madgui
or simply:
madgui
"""
from __future__ import unicode_literals
__title__ = 'MadGUI'
__summary__ = 'GUI for accelerator simulations using MAD-X.'
__uri__ = 'https://github.com/hibtc/madgui'
__version__ = '0.8.0'
__author__ = 'Tho... |
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
class A:
def ping(self):
print('ping:', self)
class B(A):
def pong(self):
print('pong:', self)
class C(A):
def pong(self):
print('PONG:', self)
class D(B, C):
def ping(self):
super().ping()
print('post-ping:'... |
from django.shortcuts import render,HttpResponse
import requests
from bs4 import BeautifulSoup
import collections
import json
import re
import datetime,time
import os
import copy
from django.views.decorators.cache import cache_page
SSC = collections.OrderedDict()
@cache_page(60 * 1)
def index(request):
now_time... |
from django.urls import path
from . import views
app_name = 'home'
urlpatterns = [
path('', views.home, name = 'home'),
path('about/', views.about, name = 'about'),
path('service/', views.service, name = 'service'),
path('blog/', views.blog, name = 'blog'),
path('contact/', views.contact, name = 'contact'),
pa... |
"""
Collect github projects by programming language
extract trace links between commits and issues
create doc string to source code relationship
"""
import calendar
import logging
import os
import time
from github import Github, \
RateLimitExceededException # pip install PyGithub. Lib operates on remote github to... |
import jax.numpy as np
from .clean_data import clean_adult_full
from sklearn import model_selection
def adult():
X, y = clean_adult_full(scale_and_center=True, normalize=True, intercept=True, sampling_rate=0.1)
X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.2)
X_train, X_... |
""" Tools related to reading time series data using GDAL / rasterio
"""
from functools import partial
import logging
import os
import numpy as np
import pandas as pd
import rasterio
from rasterio.coords import BoundingBox
import xarray as xr
logger = logging.getLogger(__name__)
def parse_dataset_file(input_file, da... |
def fib1(n):
if n==1:
return 1
if n==2:
return 1
else:
return fib1(n-1)+fib1(n-2)
print(fib1(10))
|
# This Python file uses the following encoding: utf-8
import sys
import os
import json
from PySide2.QtGui import QGuiApplication, QFontDatabase
from PySide2.QtQml import QQmlApplicationEngine, qmlRegisterType
from PySide2 import QtCore
from fontTools.ttLib import TTFont
class FontMapping(QtCore.QAbstractListModel):... |
from generic_online_ml_scoring.builder import ConsumerTransformerProducerLoop
from generic_online_ml_scoring.builder import GenericModel
class EmptyModel(GenericModel):
pass
config_path = "../data/testconfig.conf"
loop = ConsumerTransformerProducerLoop(config_path)
loop.submit_model(EmptyModel())
loop.start()
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import unittest
import onnxruntime # noqa
from test_models import TestModels
from test_pytorch_onnx_onnxruntime import run_model_test
def exportTest(self, model, inpu... |
"""
@version: python3.5
@author: jsdiuf
@contact: weichun713@foxmail.com
@time: 2018-9-19 16:42
Given a list of daily temperatures, produce a list that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 inste... |
import sys
def printer(card, is_reverse):
if card:
if not is_reverse:
tmp = '['
for i in card[:-1]:
tmp += (str(i) + ',')
tmp += (str(card[-1]) + ']')
else:
tmp = '['
for i in reversed(card[1:len(card)]):
... |
# forms.py defines class to represent our form. Add the field we need which will eventually be used with a form builder on the front end https://git.generalassemb.ly/sf-wdi-51/Flask-Models
# import the tools, fields we need
from flask_wtf import FlaskForm as Form
# from models import User
from wtforms import StringF... |
# -*- coding: utf-8 -*-
"""
@author: cordula eggerth (00750881)
aufgabe 2 / uebung 3: strategie 1 und strategie 2 mastermind
"""
import numpy as np
import matplotlib.pyplot as plt
from itertools import permutations
# ---------------------------------------------------------------------------------------------------... |
import numpy as np
def main():
# X and Y are n x n square matrices of equal size
# X = np.array([[1, 2], [3, 4]])
# Y = np.array([[5, 6], [7, 8]])
# result = strassen(X,Y)
# print(result)
X = np.array([[1,2,3], [4,5,6], [7,8,9]])
Y = np.array([[2,3,4], [5,6,7], [8,9,1]])
... |
#!/usr/bin/env python
from Point import Point
from BaseSpline import BaseSpline
class CatmullRom(BaseSpline):
def __init__(self):
super(CatmullRom, self).__init__()
def compute(self, userDefinedPoints):
self.points = [] #make sure our points to be ploted is empty
self.controlPoints = u... |
import openpyxl
from openpyxl.styles import *
from openpyxl.utils import get_column_letter
from openpyxl.utils.cell import column_index_from_string
import xlsxwriter
import xlsxwriter.utility
file1 = openpyxl.load_workbook('{blank} Timetable Planner TEST V1.xlsx')
sheetNam = file1.sheetnames
curSheet = file... |
import unittest
from datetime import datetime, timedelta
from nose.tools import eq_, raises, ok_, assert_not_equal as neq_
from sqlalchemy.exc import IntegrityError
from qkoubot.models import Info, Session, Base, engine
from .utils import insert_all, delete_all, query_to_dict
from static import INFO_MODEL_DATA_DICTS
... |
import seaborn as sns
titanic = sns.load_dataset('titanic')
df = titanic.loc[:, ['age', 'fare']]
df['ten'] = 10
print(df.head())
def add_10(n):
return n + 10
def add_two_obj(a, b):
return a + b
sr1 = df['age'].apply(add_10)
print(sr1.head())
print('\n')
sr2 = df['age'].apply(add_two_obj, b=10)
print(sr2... |
from datastructures import *
from Summary import Summary
from TrackedMonth import TrackedMonth
import copy
import numpy as np
from datetime import date
from pathlib import Path
import pandas as pd
import unittest
from unittest.mock import patch
class TestSummary(unittest.TestCase):
@classmethod
def setUpClas... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# File Name: start
# Description :
# Author : SanYapeng
# date: 2019-06-08
# Change Activity: 2019-06-08:
import os
import sys
import socketserver
base_dir = os.path.dirname(os.path.dirname((os.path.abspath(__file__))))
#print(b... |
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import pandas as pd
df = pd.read_csv('/var/www/FlaskApp/FlaskApp/data.csv')
colors = {'bg':'#000000'}
app = dash.Dash()
app.layout = html.Div([
html.Div([
html.H2('Analisis de Portafolios',... |
#!/usr/bin/env python
# coding:utf-8
# Copyright (C) dirlt
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
res = []
(i, j, v) = (0, 0, 1)
m = n
# print '---'
while True:
# print (i,... |
from django.apps import apps
from rest_framework import serializers
from rest_framework.generics import get_object_or_404
from rest_framework.permissions import BasePermission
object_level_permissions_in_thread = (
('can_add_post_in_this_thread', 'can add post of this thread'),
('can_delete_post_in_this_thread... |
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
# 将服务器执行成功的命令告诉数据库
import urllib
import urllib2
import socket
import config
import time, logging
logging.basicConfig(filename=config.log_path_server + time.strftime("%Y%m%d") + '.log', level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s")
class C... |
import heapq
arr = [5,7,9,1,3]
# arr = [(5,2), (7,3), (9,4), (1,3), (3,4)]
heapq.heapify(arr)
print(heapq.heappop(arr))
print(list(arr)) |
import datetime
import json
import re
from giotto import get_config
Base = get_config('Base')
from giotto.primitives import ALL_DATA
from giotto.exceptions import DataNotFound, InvalidInput
from giotto.utils import slugify
from sqlalchemy import Column, Integer, String, ForeignKey, Date, DateTime, Boolean, func, des... |
# Наиболее простой декоратор
def simple_decorator(func):
def wrapper():
print("Executing code before function")
func()
print("Executing code after function")
return wrapper
@simple_decorator
def simple_function():
print("Executing function")
# Данный декоратор передает аргументы ... |
"""
Homework 4 Problem 13.13
Develop a progrom using a programing or macro language to implement the
golden-section serach algorithm. Design teh program so that it is expressly
designed to locate a maximum or minimum based on user preference. The
subroutine should have the following features:
-iterate untill the ... |
from typing import List
class Solution:
# https://leetcode.com/problems/valid-palindrome
def valid(self, s) -> bool:
alphanumericOnlyChars = filter(lambda c: c.isalnum(), s)
lowercaseCharsList = list(map(lambda c: c.lower(), alphanumericOnlyChars))
reversedChars = lowercaseCharsL... |
total = 0
moduleArr = []
def calcFuel(n):
return (n / 3) -2
with open('data.txt') as list:
for line in list:
moduleTotal = 0
fuel = calcFuel(int(line))
while fuel > 0:
moduleTotal += fuel
fuel = calcFuel(fuel)
moduleArr.append(moduleTotal)
for module in moduleArr:
total += module
p... |
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 19 20:18:24 2020
@author: YUKTI_PC
"""
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 5, 11)
y = x ** 2
plt.plot(x, y, 'r') # 'r' is the color red
plt.xlabel('Number')
plt.ylabel('square')
plt.title('Demo Graph')
plt.show()
# plt... |
__author__ = 'Bharadwaj'
# This class helps in constructing the NASDAQ url from the main url and
# also retrieves the stock symbols and their respective urls.
# Input: Main url (http://finance.yahoo.com/)
# Output: Dictionary of stock symbols and their respective urls.
from bs4 import BeautifulSoup
import urllib.requ... |
from sympy import *
import time
#TODO instead of subbing Abs(), find sqrt(re(x)+im(x)) instead.
def mod_to_abs(eq):
eq_list=[str(x) for x in eq]
if '|' not in eq:
return eq
for x,char in enumerate(eq_list):
if char=='|':
eq_list[x]='Abs('
for y,char2 in reversed(list... |
#!/usr/bin/env python
# coding=gbk
"""
__title__ = '带参数和不带参数的timeStump for py3'
__author__ = 'pi'
__mtime__ = '2014.12.12'
"""
from contextlib import contextmanager
import datetime
import time
def time_process(func):
'''
program process time. 处理时间而非自然时间
:return:
'''
def wrapped_... |
#n, m, k = [x for x in open("testinput.txt", "r")]
import sys
# input file
f = open('questions.txt', 'r')
sys.stdin = f
n = int(input())
m = int(input())
k = input().split()
ans = False
for a in k:
for b in k:
for c in k:
for d in k:
if int(a)+int(b)+int(c)+int(d) == m:
... |
import sys
from PyQt5 import *
from weight.parameters_form_ui import Ui_Form
from weight.parameter_frame import *
class Parameters_Window(QtWidgets.QWidget,Ui_Form):
def __init__(self):
super(QtWidgets.QWidget,self).__init__()
self.frameHeight=0
self.frameCount=1
self.Parameter_frame... |
from django.db import models
# Create your models here.
class Member(models.Model):
firstname = models.CharField(max_length=40)
lastname = models.CharField(max_length=40)
email = models.EmailField(max_length=100, default="", editable=False)
mobile = models.CharField(max_length=12, default="", editable... |
''' test
'''
from unittest import TestCase
from super_sum import super_sum
class SuperSumTestCase(TestCase):
'''
test case for super sum.
'''
def setUp(self):
pass
def tearDown(self):
pass
def test_empty_input(self):
#test empty input
self.assertEqual(super_sum(), 0)
def test_sum_of_integers(self):
... |
import os
import pandas as pd
import docx
import xlrd
from docx import Document
from xlutils.copy import copy
import openpyxl
from openpyxl import load_workbook
import re
'''
#2014-2015
path_2014_2015_read_country='F:\奈园代码\本专科生国家奖学金\原始数据\p2014—2015学年度本专科生国家奖学金\中央高校'
path_2014_2015_read_city='F:\奈园代码\本专科生国... |
from django.db import models
class LinkVoteCountManager(models.Manager):
def get_queryset(self):
return super(LinkVoteCountManager, self).get_queryset().annotate(
votes=models.Count('vote')).order_by('-rank_score', '-votes')
|
def main():
n = int(input("Defina n: "))
n2 = n
s = 0
for i in range(1, n+1):
s += i / n2
print(f"{i}/{n2} + ")
n2 -= 1
print(f"S = {s}")
main() |
from django.contrib.auth import get_user_model
User = get_user_model()
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import permissions
class SignupView(APIView):
permission_classes = (permissions.AllowAny,)
def post(self,request,formate=None):
... |
command = input()
count_adults = 0
count_kids = 0
sum_toys = 0
sum_sweaters = 0
while command != "Christmas":
age = int(command)
if age > 16:
count_adults += 1
sum_sweaters += 15
else:
count_kids += 1
sum_toys += 5
command = input()
print(f"Number of adults: {count_adul... |
from django.shortcuts import render,redirect
from django.http import HttpResponse
from .models import *
# Create your views here.
def index(request):
quest_list = Questions.objects.all()
return render(request,'index.html',locals())
def detail(request,id):
quest_obj = Questions.objects.get(id=id)
answe... |
class Solution:
def maxArea(self, height: List[int]) -> int:
if not height or len(height) == 1:
return 0
left = 0
right = len(height) - 1
most = 0
while left < right:
for i in range(len(height)):
l = min(height[left], height[right])
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.