text stringlengths 38 1.54M |
|---|
'''
Solve each of the problem using Python Scripts. Make sure you use appropriate variable names and comments. When
there is a final answer have Python print it to the screen.
A person's body mass index (BMI) is defined as:
BMI = mass in kg / (height in m)**2
'''
mass= int(input('Enter the mass'))
height= int(input('E... |
"""
Runtime: 32 ms, faster than 82.10% of Python3 online submissions for Rotate Image.
Memory Usage: 14.3 MB, less than 51.10% of Python3 online submissions for Rotate Image.
"""
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place ins... |
# 9.2 Functions
#def my_function():
# indent four spaces
# function code here
def my_sq(x):
return(x**2)
my_sq(3) # testable example
def avg_2(x,y):
return((x+y)/2)
avg_2(5,9) # that works!
# 9.3 Apply (Basics)
import pandas as pd
df = pd.DataFrame({'a': [10, 20, 30],
'b': [20,... |
"""
"""
# option 1.
score1 = 85
score2 = 78
score3 = 96
score4 = 85
score5 = 73
score6 = 59
score7 = 45
score8 = 80 # 1
total_score = 0
# total_score = score1 + score2 + score3 + score4+ score5+ score6+ score7
total_score = score1 + score2 + score3 + score4+ score5+ score6+ score7 + score8 # 2
# num_of_stu ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AnttechBlockchainFinanceAssetIssueSubmitModel(object):
def __init__(self):
self._asset_id = None
self._pub_key = None
self._sign_algorithm = None
self._sign_data =... |
# Generated by Django 2.0.7 on 2018-08-16 07:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('MediaAdmin', '0037_auto_20180815_1356'),
]
operations = [
migrations.AddField(
model_name='digonalstyle',
name='seco... |
from tensorflow.python.lib.io import file_io
import os
import subprocess
def download_file_from_gcs(source, destination):
if not os.path.exists(destination):
subprocess.check_call([
'gsutil',
'cp',
source, destination])
else:
print('File %s already present locally, not downloading' % destination)
#... |
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from database_connection import engine
Base = declarative_base()
class Customers(Base):
__tablename__ = 'books'
id = Column(Integer, primary_key=True)
name = Column(String(30))
address = Column(S... |
def golf(r):
s=p=0
c=int(-(-r//1))
for i in range(c):
y=max(r**2-(i+1)**2,0)**0.5
s+=y//1
p+=c-y//1
c=-(-y//1)
return s*4,p*4
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
assert isinstance(golf(1), (list, tuple))
assert list(golf(2)) ... |
from django.db import models
from rest_example.settings import MEDIA_ROOT
from django.contrib.auth.models import User
# Create your models here.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,related_name="profile")
dob = models.DateField(blank=True,null=... |
"""
dbriver (database interface module)
===================================
Defines the base classes used to define
database drivers.
Includes a general ``TaskDBDriver`` class
plus ``TaskAppender`` for output collection
and ``TaskAggregator`` for output postprocessing.
A csv-based implementation of ``TaskAggregator`... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
from conjure import views
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'conjure.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^$', views.index, name='index'),
url(r'^membres/', in... |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 30 15:00:48 2018
@author: ly
"""
data1=pd.read_csv(r"F:\python\python\Credit\LoanStats_2016Q1\train_two.csv",encoding="gbk",index_col =0,low_memory=False)
object_iv=pd.read_csv(r"F:\python\python\Credit\LoanStats_2016Q1\object_iv.csv",encoding="gbk",index_col =0,... |
'''
Burrows-Wheeler transform is a text transformation used to improve compression in bzip2 to outperform other state-of-the-art techniques [at the time].
The idea is to use advantage of frequently occurring bigrams. he, the, there, her, where are all frequent words containing bigram he. BWT permutes the text so that h... |
from django.db import models
from django.contrib.auth.models import User
from cart.models import Cart
from profiles.models import Address
STATUS_CHOICES = (
('Started', 'Started'),
('Abandoned', 'Abandoned'),
('Collected', 'Collected'),
)
class Order(models.Model):
user = models.ForeignKey(User)
cart = models.F... |
import pytest
import config
from DISClib.ADT import graph as g
from DISClib.ADT import stack
from DISClib.Algorithms.Graphs import dfo
assert config
@pytest.fixture
def graph():
graph = g.newGraph(size=10, directed=True, comparefunction=compareVertices)
g.insertVertex(graph, 'Calculo1')
g.insertVertex(gra... |
import copy
import random
from colored import fg
class GameBoard(object):
"""
An object representing a game board.
Consists of NxN matrix where each element represents a color
"""
def __init__(self, board_size, game_colors, colors_color):
self._board_size = board_size
self._game_... |
# This is a guessing game.
import random
print('Hello there, What is your name ?')
name = input()
print('Hello ' + name + ', I am thinking of a number between 1 and 5')
number = random.randint(1, 5) # random number is generated
# Ask the player for 3 guesses
for guessTaken in range(1, 4): # guess conditions
p... |
from site_handlers import BaseHandler
# Kontroler skrito stevilo aplikacija
class SteviloHandler(BaseHandler):
def get(self):
return self.render_template("skrito_stevilo.html")
def post(self):
vnos_error = "Obvezno vnesi stevilo preden pritisnes gumb!"
try:
vneseno_stevilo ... |
# Django
from django.urls import path
# Apps.menus
from apps.menus import views
app_name='menus'
urlpatterns = [
path('add/ingredient', views.create_ingredient, name='add-ingredient'),
path('list/ingredient', views.list_ingredient, name='list-ingredient'),
path('add/menu', views.create_menu, name='add-m... |
# Python imports
from __future__ import absolute_import
import logging
import operator
from collections import OrderedDict
# SRP MD imports
from . import learn
from .factor_learners import FreqFactorLearner, FACTOR_LEARNERS, SklearnFactorLearner
import srp_md
class FactorGraphLearner(learn.BaseLearner):
def __in... |
# -*- coding: utf-8 -*-
# © 2017 Ibrohim Binladin | ibradiiin@gmail.com | +62-838-7190-9782
import datetime as dt
from odoo import api, fields, models, _
from datetime import datetime
from odoo.osv import expression
import odoo.addons.decimal_precision as dp
from odoo.exceptions import UserError
from odoo.tools import ... |
# -*- encoding:utf-8 -*-
"""买入因子类装饰器模块"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from ..CoreBu.ABuFixes import six
from ..TLineBu.ABuTL import AbuTLine
__author__ = '阿布'
__weixin__ = 'abu_quant'
class AbuLeastPolyWrap(object):
"""示例做为买入因子策略装... |
from __future__ import division
# import RPi.GPIO as GPIO
from dotstar import Adafruit_DotStar
from colorsys import hsv_to_rgb
from itertools import cycle
import time
from math import sin
from signal_processing import Stream
NUM_LEDS = 300
# class Button(object):
# PIN = 17
# def __init__(self):
# ... |
# Generated by Django 3.1.7 on 2021-04-03 05:00
from django.db import migrations, models
import main.models
class Migration(migrations.Migration):
dependencies = [
('main', '0006_auto_20210327_0612'),
]
operations = [
migrations.AlterField(
model_name='book',
nam... |
import pytest
from brownie_tokens import MintableForkToken
from abi.ERC20 import ERC20
class _MintableTestToken(MintableForkToken):
def __init__(self, address):
super().__init__(address)
@pytest.fixture(scope="session")
def MintableTestToken():
yield _MintableTestToken
@pytest.fixture(scope="modu... |
from django.shortcuts import render, render_to_response
from django.template.loader import render_to_string
from django.http import HttpResponse, HttpResponseRedirect
from django.template.loader import get_template
from django.template import Context, Template, RequestContext
import datetime
import hashlib
from random ... |
# -*- coding: utf-8 -*-
# *********************************************
# * Author : Zhefeng Wang
# * Email : wangzhefengr@163.com
# * Date : 2021.01.01
# * Version : 1.0.0
# * Description : 图算法
# * 1.最短路径问题(shortest-path problem)
# * - 广度优先搜索算法
# * ... |
import time
import json
from flask import Flask, Response, redirect, request, url_for
from kafka import KafkaConsumer
app = Flask(__name__)
class TweetConsumer:
def __init__(self):
self.consumer = KafkaConsumer('wordcloud_output',
group_id='flask_wordcloud',
... |
import cv2
print(cv2.__version__)
# Cam properties
fps = 30.
frame_width = 1920
frame_height = 1080
dispW=640
dispH=480
flip=2
#Uncomment These next Two Line for Pi Camera
camSet = ('videotestsrc ! videoconvert ! appsink')
cam= cv2.VideoCapture(camSet)
while True:
ret, frame = cam.read()
cv2... |
from alias_decoder import AliasDecoder
from flask import Flask
from query_parser import QueryParser
from query_handler import QueryHandler
from settings import Settings
app = Flask(__name__)
aliases = AliasDecoder(Settings.getSetting('ALIASES_FILE_NAME')).aliases
@app.route('/alias/<string:query>', methods=['GET'])
d... |
from django.apps import AppConfig
class QuaddictedPackagesConfig(AppConfig):
name = 'quaddicted.packages'
label = 'quaddicted_packages'
|
import pathlib as pl
import click
import toml
import logging
import sys
from lvs.video_streamer import dataclass_objects as do
from lvs.video_streamer import video_streamer as vs
from lvs.stream_server import run_server
from lvs.view_ext import run_client
from lvs.http_ext import run_flask
from lvs.save_ext import sa... |
from rest_framework import serializers
from koalixcrm.crm.product.tax import Tax
class OptionTaxJSONSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.IntegerField(required=False)
description = serializers.CharField(source='name', read_only=True)
class Meta:
model = Tax
... |
#!/usr/bin/env python3
# *******************************************************
# Copyright (c) VMware, Inc. 2020-2021. All Rights Reserved.
# SPDX-License-Identifier: MIT
# *******************************************************
# *
# * DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT
# * WARRANTIES OR CO... |
#!/usr/bin/env python
__author__ = 'Manuel Velasco'
import requests
def astronaut_info():
astronauts_names = requests.get("http://api.open-notify.org/astros.json")
list_name = astronauts_names.json()["people"]
print(f'number of astronaut {len(list_name)}')
for value in list_name:
print(f"... |
from django.contrib import admin
from django.db import models
from django.forms import CheckboxSelectMultiple
from .models import Item
class ItemAdmin(admin.ModelAdmin):
formfield_overrides = {
models.ManyToManyField: {'widget': CheckboxSelectMultiple},
}
admin.site.register(Item, ItemAdmin)
|
token = '435437415:AAEdmHWbMwNOa87X-8EAnhkn1nsJJ7NWTsQ'
str_connect_to_db = "dbname='money_manager' user='goods_deliver' host='localhost' password='86429731' port='5430'"
|
from common.okfpgaservers.pulser.pulse_sequences.pulse_sequence import pulse_sequence
from RabiExcitation import rabi_excitation, rabi_excitation_no_offset
from EmptySequence import empty_sequence
from treedict import TreeDict
from labrad.units import WithUnit
class ramsey_excitation(pulse_sequence):
required... |
# imports
import argparse
########################################################################
# Class template
########################################################################
class MyClass:
def __init__(self, string):
self.mystring = string
def f(self):
return self.mystring
... |
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
import math
import time
'''
Programming Assignment 2
In this assignment you will implement one or more algorithms for the traveling
salesman problem, such as the dynamic programming algorithm covered in the video
lectures.
Here is a data file... |
import pywikibot
from pywikibot import pagegenerators as pg
import sys
import time
import codecs
site=pywikibot.Site('wikidata','wikidata')
repo=site.data_repository()
query1='SELECT * WHERE {?item schema:description "Wikinews članak"@bs ; wdt:P31 wd:Q17633526}'
query2='SELECT * WHERE {?item schema:descriptio... |
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import contrib
tf.enable_eager_execution()
print("Tensorflow version: {}".format(tf.__version__))
print("Eager execution: {}".format(tf.executing_eager... |
# Created by MechAviv
# Color Pop Damage Skin (30 Day) | (2436644)
if sm.addDamageSkin(2436644):
sm.chat("'Color Pop Damage Skin (30 Day)' Damage Skin has been added to your account's damage skin collection.")
sm.consumeItem() |
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__version__ = "0.0.1"
from .models.category import Category
from .models.message import Message
from .models.word import Word
from .managers.category_manager import CategoryManager
from .managers.message_manager import MessageManager
from .managers.word_manager import Wo... |
#!/usr/bin/env python
# coding: utf-8
# In[35]:
#summon pandas as pd
import pandas as pd
# In[52]:
#using pd.read_html i convert the url into a pandas dataframe
df_toronto = pd.read_html("https://en.wikipedia.org/wiki/List_of_postal_codes_of_Canada:_M")[0]
df_toronto
# In[53]:
df_toronto.head()
# In[55]:
... |
import os
from django.contrib import admin
from models import *
from external_apps.categories.admin import BaseCategoryAdmin
from external_apps.pages.admin import BasePageAdmin
from external_apps.products.admin import BaseProductAdmin
from external_apps.recipes.admin import BaseRecipeAdmin
class ArticleAdmin(admin.M... |
from django.test.testcases import TestCase
from django.urls import reverse
from parsifal.apps.authentication.tests.factories import UserFactory
from parsifal.utils.test import login_redirect_url
class TestPictureView(TestCase):
@classmethod
def setUpTestData(cls):
cls.user = UserFactory()
cls... |
def get_formatted_name(first_name, last_name):
#返回整洁的名字
full_name = first_name + ' ' + last_name
return full_name.title()
def get_formatted_name2(first_name, last_name, middle_name=''): #让实参变得可选
if middle_name:
full_name = first_name + ' ' + middle_name + ' ' + last_name
else:
full_... |
###
# Copyright (c) 2012, Clint Savage
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions,... |
#!/usr/bin/env python
import os
import os.path
# http://answers.ros.org/question/12434/using-roslaunch-to-run-distributed-systems-over-ssh/
# http://answers.ros.org/question/36600/how-to-tell-remote-machines-not-to-start-separate-roscores-when-using-roslaunch-fuerte-regression/
#http://answers.ros.org/question/10725/... |
from django.conf.urls import url, include
from rest_framework import routers
from .viewsets.asistencia import AsistenciaViewSet
from .viewsets.evento import EventoViewSet
from .viewsets.evento_programado import EventoProgramadoViewSet
from .viewsets.matricula import MatriculaViewSet
from .viewsets.mensaje import Mensa... |
class Solution:
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
def cal(f, op, s):
if op == '+':
return f+s
elif op == '-':
return f-s
elif op == '*':
return f*s
... |
maths = int(input("maths = "))
physics = int(input("physics = "))
chemistry = int(input(" chemistry = "))
x = maths + physics + chemistry
y = maths + physics
flag = 0
if (maths >= 65) and (physics >= 55) and (chemistry >= 55):
flag = 1
if flag and (x >= 190 or y >= 140):
print("yes")
else:
pr... |
import numpy as np
import pybert as pb
import pygimli as pg
pg.verbose = print # Temporary fix
import pygimli.meshtools as mt
from fpinv import FourPhaseModel, NN_interpolate
from pybert.manager import ERTManager
from pygimli.physics import Refraction
from settings import *
#need ertData, rstData, a mesh and phi to ... |
from flask_wtf import Form
from wtforms import StringField, PasswordField, SubmitField, TextAreaField, SelectField, BooleanField, RadioField
from wtforms.validators import DataRequired, Email, Length
user_id = [0]
user_name = ["Test username"]
user_rtitle = ["Test title"]
user_rbody = ["Test review"]
user_rating = [5]... |
import pygame
from choixNiveau import choixNiveau
pygame.init()
pygame.mixer.init()
height = 768
width = 1024
windows = pygame.display.set_mode((width, height))
clock = pygame.time.Clock()
run = True
background = pygame.image.load('sprite/spriteMenu/backgroundmenu.png')
background = pygame.transform.scale(backgroun... |
from django.urls import path
from . import views
app_name = 'signup4'
urlpatterns = [
path('signup_page4/', views.signup_page4, name="signup_page4"),
path('signup_user4/', views.signup_user4, name="signup_user4"),
] |
import requests
import re
from cores.utils import *
from cores import validate
from cores import controller
from enum import Enum
class XCheck(Enum):
not_vulnerable = -1
vulnerable = 0
payload_not_found = 1
payload_is_blocked = 2
payload_encoded = 3
payload_filtered = 4
def gen_rand_payload(... |
from itertools import product
from nltk.stem import PorterStemmer as ps
from collections import defaultdict
import shlex
import re
class Search(object):
#WS -- Word Search
#PS -- Phrase Search
#BS -- Boolean Search
#PYS -- Proximity Search
def __init__(self,service):
self._service = servi... |
H, W = map(int, input().split())
dw = [[0]*W for _ in range(H)]
dh = [[0]*W for _ in range(H)]
maze = [[0]*W for _ in range(H)]
for h in range(H):
s = input()
c = 0
for w, ss in enumerate(s):
maze[h][w] = ss
if ss == ".":
c += 1
dw[h][w] = c
else:
... |
# Main file that gets executed
import os
import machine
from time import sleep, time
from system import System
#for i in range(1):
#s = System()
#sleep(1)
#s.turn_off_pump()
#s.lights_off()
#sleep(5)
#s.run()
System().run()
#System().close_solenoids()
#System().open_solenoids()
#System().turn_on_pump()
... |
import threading, time, sys
import cv2
import os
from os import path
import requests
import base64
import json
from multiprocessing.pool import ThreadPool
#country = 'us'
# us: USA
# in: India
Res = []
#--------------------------------recogimg------------------------------------------
def recogimg(n... |
#coding: utf-8
import httplib2
import json
import random
import re
import string
import time
from conf.parameter_website import pro_prefix
from conf.parameter_website import test_prefix
from conf.parameter_website import pro_header
from conf.parameter_website import test_header
from conf.api_link import vi... |
from django.core.management.base import BaseCommand
from openhumans.models import OpenHumansMember
class Command(BaseCommand):
help = 'Delete data for user id'
# meant to be used mostly for local development
# and/or as the nuclear option if inconsistent state has been reached somehow
def add_argumen... |
'''
Created on Aug 14, 2019
@author: paepcke
'''
import filecmp
import os
import shutil
import tempfile
import unittest
from convert_queries import QueryConverter
class QueryConverterTester(unittest.TestCase):
#-------------------------
# setUp
#--------------
def setUp(self):
unittest.Te... |
#coding=utf-8
import xlrd
import math
from xlrd import XL_CELL_EMPTY, XL_CELL_TEXT, XL_CELL_NUMBER, \
XL_CELL_DATE, XL_CELL_BOOLEAN, XL_CELL_ERROR, XL_CELL_BLANK
'''
XL_CELL_EMPTY 0 empty string u''
XL_CELL_TEXT 1 a Unicode string
XL_CELL_NUMBER 2 float
XL_CELL_DATE 3 float
XL_CELL_BOOLEAN 4 int; 1 means TRUE, 0... |
# changing string to list
myString = "Arizona"
mysteryWord = list(myString)
print(mysteryWord)
guessList = []
# how to make a list with _ for characters
for letter in mysteryWord:
guessList.append("_")
print(guessList)
# how to replace a specific index in a list
guessList[3] = "z"
print(guessLis... |
#!/usr/bin/env python3
from time import sleep, strftime
import RPi.GPIO as GPIO
import configparser
import dht11
config = configparser.ConfigParser()
seccion = config.sections()
GPIO.setmode(GPIO.BCM)
GPIO.setup(27, GPIO.OUT)
try:
while True:
#Establece fecha
config.read('/home/pi/Python/TempHumd/medicion.c... |
import random
import sys
from mingus.containers.note import Note
import mingus.core.scales as scales
from mingus.containers.bar import Bar
class Progression(object):
def __init__(self, note_count, chord):
self.note_count = note_count
self.chord = chord
self._generated_note_count = 0
... |
import json
from datetime import datetime, timedelta
from flask import make_response, jsonify
from flask_sqlalchemy import SQLAlchemy # Database
from app import db
# Setup database
def db_init():
db.drop_all()
db.create_all()
db.session.commit()
class User(db.Model):
__tablename__ = "users"
id = ... |
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.ensemble import RandomForestClassifier
from sklearn.cross_validation import train_test_split
from sklearn import metrics
from sklearn.grid_search import GridSearchCV
scores1=[]
scores2=[]
scores3=[]
data=pd.read_csv('C:/Users/mandar/Desktop/Kaggle... |
import twitter
import csv
import json
import urllib
import peewee
from peewee import *
def createQuery(file):
query = 'q='
first_line = file.readline().replace('#', '%23').strip('\n')
query += first_line
for hashtag in file:
query += '%2C%20OR%20' + hashtag.replace('#', '%23').strip('\n')
... |
import numpy as np
import sys
import time
import momo
from momo.learning.max_ent.compute_cummulated import *
from math import *
def learn( feature_module, convert, frame_data, ids, radius, h ):
feature_length = feature_module.FEATURE_LENGTH
compute_costs = feature_module.compute_costs( convert )
planner = momo.... |
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
path('', views.index, name='index'),
path('<int:question_id>/', views.detail, name='detail'),
path('<int:question_id>/results/', views.results, name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
... |
#Eliminates the punctuation from a text file
filename = r'essays.txt'
import string
numlines = 0
textfile = open(filename, 'r')
txtfile= open ("output.txt", 'w')# creating a file called output.txt
for line in textfile:
out = line.translate(string.maketrans("",""), string.punctuation)
txtfile.write(out)
txtfile.cl... |
import qrcode
import cv2
import numpy as np
import os
import PIL
from PIL import Image
message=["D0","D1","D2","A0","A1","A2","A3","A4","A5","B0","B1","B2","B3","B4","B5","C0","C1","C2"]
def generate(data, QRcode):
img = qrcode.make(data) #generate QRcode
img.save(QRcode)
return img
for... |
import os
import sys
import uuid
from src.tss import get_parent_directory
def get_default_parameters():
try:
import ConfigParser
Config = ConfigParser.ConfigParser()
init_cfg = os.path.join(get_parent_directory(__file__, 2), "config/params.ini")
updated_cfg = os.path.join(get_pare... |
from ngrambuild.pyngram import voters
from common.f_cg import transer
from common.readdata import *
from Data_base.Data_redis.redis_deal import redis_deal
from Config.ve_strategy import ve_strategy
from common.Converter.word_converter import word_convert
from common.Converter.base_convert import Converter
from ngrambui... |
import random
from Sorter import divide,merge
import time
def choosepivot(data, l, r):
# index = random.randint(l, r)
# index = r
# index = l
third_num = (l + r)//2
pivotlist = [data[l],data[r],data[third_num]]
pivotlist.sort()
if pivotlist[1] == data[l]:
return l
... |
#!/usr/bin/env python
# vim: set fileencoding=utf-8
import tkinter
from tkinter import ttk
import sys
root = tkinter.Tk()
number = tkinter.IntVar()
spinbox = tkinter.Spinbox(root, from_=100, to=120, width=10, textvariable=number)
showButton = ttk.Button(root, text="Show var", command=lambda: print(number.get()))
... |
# coding = utf-8
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def kthLargest(self, root: TreeNode, k: int) -> int:
# 修改中序遍历定义:先右,中根,最后左
if not root:
... |
# Generated by Django 3.1 on 2020-08-15 16:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('prototipo', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='tweets',
name='name',
),
... |
from django.shortcuts import render_to_response, render
from django.contrib import messages
from django.http import HttpResponseRedirect, Http404, HttpResponse
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from register.models import (CarRegistration,
... |
#-*- encoding: utf-8 -*-
from app import app
from sync.base import *
from SocketServer import StreamRequestHandler, ThreadingTCPServer
import pprint
import socket
import ssl
class SyncRequestHandler(StreamRequestHandler):
def _handler(self):
print 'Connected from ', self.client_address
request = s... |
#!/usr/bin/python
import sys
import re
import csv
import traceback
import operator
import cutil.cutil
from amfi.amfi import *
class Demat(Amfi):
def __init__(self):
super(Demat, self).__init__()
self.company_name = {}
self.demat_txn_last_type = {}
self.demat_txn_buy_qty = {}
... |
# 5622: 다이얼
# https://www.acmicpc.net/problem/5622
s = input().lower()
alpha = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']
time = 0
for c in s:
for i, a in enumerate(alpha):
if c in a:
time += i + 3
print(time)
|
# --------------------------------------------------------
# (c) Copyright 2014, 2020 by Jason DeLaat.
# Licensed under BSD 3-clause licence.
# --------------------------------------------------------
import unittest
import pymonad.monoid as monoid
class MZero_Tests(unittest.TestCase):
def test_left_identity(self... |
import os
class Config():
DEBUG = False
class DevelopmentConfig(Config):
DEBUG = True
DATABASE_CONNECTION_URL = os.getenv('DATABASE_URL')
class TestingConfig(Config):
TESTING = True
DEBUG = True
DATABASE_CONNECTION_URL = os.getenv('DATABASE_URL')
class ProductionConfig(Config):
DEBUG... |
# Copyright 2016 The TensorFlow Authors. 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 applicable ... |
from django.forms import forms, ModelForm, TextInput, Textarea, Select, CharField, PasswordInput, NumberInput
from django.contrib.auth.password_validation import validate_password
from eadmin.models import User
from . models import DeliveryStaff
class NewStaffForm(ModelForm):
class Meta:
model = DeliveryS... |
# coding = utf-8
import sys, argparse, os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname('__file__'), os.path.pardir)))
from src.DialogueSystem.world import World
def parse():
parser = argparse.ArgumentParser()
parser.add_argument("--model_setting", default=None, type=str)
parser.add_ar... |
import click
from click_didyoumean import DYMGroup
import cogctl
import cogctl.api
from cogctl.cli import table
def validate_new_permission_name(context, param, value):
"""
Validates uniqueness of new permission name and requires the bundle to be
"site" if included in the full name of the permission.
... |
#!/usr/bin/env python2
import sys, os
import logging
BatteryInfoDir = '/sys/class/power_supply'
def TimeLeft(BatterySysPath):
if not os.path.isdir(BatterySysPath):
raise RuntimeError("No battery information at '%s'" % BatterySysPath)
CurrentChargeFile = os.path.join(BatterySysPath, 'charge_now')... |
# NUMBERS
#===========================================
# Integers
num_int = 3
print( type(num_int) )
# Floats
num_float = 5.35
# Type conversion
str1 = "Marcel"
print(type(str))
str_int = int("5")
print( type(str_int) )
str_float = float("3.25")
print( type(str_float) )
str_float = float("3")
int_str = str(3)
... |
import tensorflow as tf
import tensorflow_ranking as tfr
from practice import myhead
from collections import Counter
tf.enable_eager_execution()
tf.executing_eagerly()
# Store the paths to files containing training and test instances.
# As noted above, we will assume the data is in the LibSVM format
# and that the c... |
# Choose the right settings, development is excluded from the repo so its only loaded locally
try:
from development import *
except ImportError:
from production import *
|
import time
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
from netmiko import ConnectHandler
from my_devices import device_list
def ssh_conn(device):
net_connect = ConnectHandler(**device)
return net_connect.find_prompt()
if __name__ == "__main__":
start_time = datetim... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.28 on 2020-07-14 12:04
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pig', '0001_initial'),
]
operations = [
migrations.AlterField(
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.