text stringlengths 8 6.05M |
|---|
from telebot.types import InlineKeyboardButton, InlineKeyboardMarkup
from smiles import smiles
import json
import config
# Create keyboard
def make_kb(text_1, text_2, text_3):
button_1 = InlineKeyboardButton(text_1, callback_data=smiles["xd"])
button_2 = InlineKeyboardButton(
text_2, callback_data=smi... |
print ("Questao 2")
print ("Digite os dados do retangulo")
x = input ("Base ")
x_int = int(x)
y = input ("altura ")
y_int = int(y)
soma = x_int * y_int
print ("Resultado:", x, "*", y, "=", soma)
|
"""Mock Skybell Device Activities Response."""
import datetime
import skybellpy.helpers.constants as CONST
import tests.mock.device as DEVICE
EMPTY_ACTIVITIES_RESPONSE = '[]'
def get_response_ok(dev_id=DEVICE.DEVID,
event=CONST.EVENT_BUTTON,
state=CONST.STATE_READY,
... |
# ==================================================================================================
# Copyright 2012 Twitter, Inc.
# --------------------------------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi... |
import os
import glob
import json
import itertools
from copy import deepcopy
from shutil import copyfile
from typing import List, Dict, Any, Tuple, Set, Union
def read_json_file(path: str) -> List[Dict[str, Any]]:
"""Read a JSON format output file and return a list of results.
Args:
path (str): path ... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 4 13:10:18 2021
@author: cristinarusso
"""
"""
This script is used to evaluate and compare model and in situ current direction and strength by plotting current roses.
The script compares in situ observations to the model output at a certain location.
Scripts ... |
# -*- coding: utf-8 -*-
# Copyright: (C) 2018-2020 Lovac42
# Support: https://github.com/lovac42/HoochieMama
# License: GNU GPL, version 3 or later; http://www.gnu.org/copyleft/gpl.html
import aqt
import aqt.preferences
from aqt.qt import *
from anki.lang import _
from anki.hooks import wrap
from .sort import CUSTOM... |
class Observer:
"观察者的基类"
def update(self, observer, object):
pass
class Observable:
"被观察者的基类"
def __init__(self):
self.__observers = []
def add_observer(self, observer):
self.__observers.append(observer)
def remove_observer(self, observer):
self.__observers.... |
# -*- coding: UTF-8 -*-
from enum import Enum
class User(Enum):
Twoater = 98
Liangdianshui = 30
Tom = 12
twoater = User.Twoater
liandianshui = User.Liangdianshui
print twoater == liandianshui, twoater == User.Twoater
print twoater is liandianshui, twoater is User.Twoater |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from ceasiompy.utils.moduleinterfaces import CPACSInOut
# ===== RCE integration =====
RCE = {
"name": "ModuleTemplate",
"description": "This is a template module",
"exec": "pwd\npython moduletemplate.py",
"author": "Neil Armstrong",
"email": "neil@na... |
import sys
n = int(sys.stdin.readline())
x = None
y = None
for ix in range(n):
a, b = map(int, sys.stdin.readline().split(' '))
if x is None or a < x:
x = a
if y is None or b < y:
y = b
print x * y
|
import cv2
import numpy as np
img = cv2.imread("../Resources/Lenna.png") #imread 读取图片
cv2.imshow("img_output", img) #显示图片
cv2.waitKey(1000)#延时函数 1000 表示 1000ms 设为零则无限延时
def main():
pass
if __name__ == '__main__':
main()
|
#lst=[1,0,7,5,9,2,3,5,7,2,0,1,10]
#duplist=[]
# i in lst:
# if i not in duplist:
# duplist.append(i)
#print(duplist)
lst=[1,0,7,5,9,2,3,5,7,2,0,1,10]
print(list(set(lst))) |
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base
SAModel = declarative_base()
class FirewallAddressModel(SAModel):
__tablename__ = 'firewall_address'
id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column(sa.String(255), nullable=False, unique=True)
type = sa.Co... |
# -*- coding:utf-8 -*-
import os
import time
import requests
class Cache(object):
def __init__(self, url):
self.url = url
self.name = url[:50].replace('/', '%')
self.__check_exist_cache_dir()
def is_cache_exist(self):
'''
检测缓存是否存在
'''
if os.path.exist... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 27 18:02:10 2019
@author: johns
"""
import numpy as np #importa libreria
a = np.zeros(3) #crea un arreglo de 3 ceros
print a #imprime variable
z = np.zeros(10) #crea arreglo con 10 ceros
print z.shape #imprime las dimenciones de z
z.shape = (1... |
import os
import weather_handler
import mail_bot
import time
import utils
# logging configuration
logger = utils.make_console_logger("Weather_Monitor")
class Weather_Monitor:
def __init__(self, config):
self.api_key = os.environ.get('API_WEATHER')
self.receiver = os.environ.get('MY_MAIL')
... |
def area(x,y=3.14):
a=y*x*x
print(a)
return a |
import numpy as np
from pylab import *
# 创建一个 8 * 8 点(point)的图,并设置分辨率为 80
figure(figsize=(8, 8), dpi=80)
# 创建一个新的 1 * 1 的子图,接下来的图样绘制在其中的第 1 块(也是唯一的一块)
subplot(1, 1, 1)
# 设置坐标轴
ax = gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].... |
#!/usr/bin/python
## -*- coding: utf-8 -*-
#
import json
#import db_conf
import cgi
import sys
import sqlite3
# Open database (will be created if not exists)
conn = sqlite3.connect('sqlite/hemap_portrait.db')
conn.text_factory = str
c = conn.cursor()
qform = cgi.FieldStorage()
inparam = "CellLine_Lymphoma_TCL_CTCL_SS_... |
temp = lambda x,y:x+y
print(temp(2,8)) |
import re
print(bool(re.match(r'[IVXLCDM]+', input())))
|
class Solution(object):
def validTree(self, n, edges):
root = [i for i in range(n)]
for edge in edges:
root1 = self.find(root, edge[0])
root2 = self.find(root, edge[1])
if root1 == root2: return False
else: root[root1] = root2
return len(edges)... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pathlib import Path
from typing import Callable, Type
import pytest
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy_mptt.mixins import BaseNestedSets
from smorest_sfs.extensions.sqla import Model, SurrogatePK
from smorest_sfs.plugins.hierachy_xlsx.parsers im... |
# Generated by Django 2.2.4 on 2019-12-03 10:27
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('QualiaII', '0013_tblusuario'),
]
operations = [
migrations.DeleteModel(
name='tblUsuario',
),
]
|
##########################
#Operateurs mathématiques#
#Auteur: Marlene Marchena#
##########################
#affectation
x, y, z = 7, 2, 2.5
#operateurs
op1 = x + y #addition
op2 = x - y #soustraction
op3 =x * y #multiplication
op4 =x ** y #puissence
op5 = y / z #division
... |
# coding: utf-8
# UNFINISHED
class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
# https://leetcode.com/discuss/87865/how-from-o-n-to-o-1
n= len(nums)
result = [1]*n
left = right = 1
for ... |
from flask import Blueprint, request, Response, make_response
from schema import Schema, SchemaError
from createbson import user_bson
from request_schemas import user_schema
from errors import UserAlreadyExistsError, UserDoesNotExistError, IncorrectUsernamePasswordError
user_api = Blueprint('user_api', __name__)
fro... |
# encoding: utf-8
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
# cap = cv2.VideoCapture("d:/18.jpg")
# 畫面大小設定
Width =320
Height = 240
_ = cap.set(3,Width)
_ = cap.set(4,Height)
r1=0;g1=180;b1=127
while(1):
lower_color=np.array([b1,g1,r1])
upper_color=np.array([255,255,255])
# get a frame and ... |
from matplotlib import pyplot as plt
import cv2 as cv
import numpy as np
import BasicGeometry as bg
print("Locating center of the record...")
bw = cv.imread('ymmly1.jpg', cv.IMREAD_GRAYSCALE)
# Enhance edges
# parameters are all magic numbers
print("Applying filter...")
filter_window_size = 5
filter_colour_smear = ... |
import os, sys
import tensorflow as tf
class MySaver():
def __init__(self, sess, config, doRestore = True):
self.saver = tf.train.Saver()
self.sess = sess
self.modelFile = config.modelFile
if doRestore and os.path.exists(self.modelFile+".data-00000-of-00001") and os.path.exists(self... |
import unittest
from entidades.ambiente import *
class TestAmbiente(unittest.TestCase):
def setUp(self) -> None:
self._ambiente = Ambiente()
self._ambiente.temperatura_deseada = 24
self._ambiente.temperatura_ambiente = 19
self._ambiente.temperatura_a_mostrar = "deseada"
def t... |
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional
import data_video
from data_video import MSVDDatasetMultiModal
from vocabulary import Vocabulary
from torch.utils.data.dataloader import DataLoader
device = torch.device('cuda' if torch.cuda.is_available() else 'cp... |
from gtnlplib import tagger_base, constants
from collections import defaultdict
def sp_update(tokens,tags,weights,feat_func,tagger,all_tags):
"""compute the structure perceptron update for a single instance
:param tokens: tokens to tag
:param tags: gold tags
:param weights: weights
:param feat_fu... |
from game.items.item import Log
from game.skills import SkillTypes
class MagicLog(Log):
name = 'Magic Log'
value = 97
xp = {SkillTypes.firemaking: 303.8, SkillTypes.fletching: 1}
skill_requirement = {SkillTypes.firemaking: 75, SkillTypes.fletching: 1} |
"""
Install file for SciTokens project.
"""
import os.path
import re
import setuptools
# read the contents of your README file
from pathlib import Path
this_directory = Path(__file__).parent
long_description = (this_directory / "README.rst").read_text()
def find_version(path, varname="__version__"):
"""Parse ... |
#!/usr/bin/env python
from socket import getfqdn
from stat import *
import getopt
from fnmatch import fnmatch
import mutex
import os
import re
import sys
import thread
import time
from Tkinter import *
from tkMessageBox import askyesno, showerror, showinfo, showwarning
from tkSimpleDialog import askinteger, askstring... |
class Settings:
def __init__(self,file):
self.__file=file
self.__repo=None
self.__BookFile=None
self.__ClientFile=None
self.__RentalFile=None
self.__loadSettings()
def __loadSettings(self):
try:
f=open(self.__file,'r')
except ... |
class ShortInputException(Exception):
"""User exception class"""
def __init__(self, length, atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast
try:
text = input('Enter something: ')
if len(text) < 3:
raise ShortInputException(len(text), 3)
ex... |
#!/home/dave/anaconda2/bin/python
import sys
sys.path.append('/home/dave/OneDrive/Research/By Project/Dissertation/experiments/private/')
import pandas as pd
import numpy as np
import os
from awsKeys import aws_access_key_id
from awsKeys import aws_secret_access_key
import boto3
args = sys.argv[1:]
if len(args) > 1 o... |
import os
import base64
import zlib
import glob
import numpy
import pandas
import matplotlib.pyplot as plt
from hpacellseg.utils import label_cell
from pycocotools import _mask as coco_mask
import multiprocessing
from joblib import Parallel, delayed
from tqdm import tqdm
num_cores = multiprocessing.cpu_count()
de... |
#input
#35 51 236 154 498 410 178 199 436 499 481 237 403 537 435 38 79 106 545 401 477 562 295 41 437 203 514 196 106 392 352 392 411 557 515 308
def fahrenheit_to_celsius(f):
return ((f - 32.0) * (5.0/9.0))
temps = input().split()
for i in range(1, int(temps[0]) + 1):
print(round(fahrenheit_to_celsius(int(... |
"""
Dateien:
- Kurse: Die Liste der Kurse
- Personen -> importiert aus ldap
- Teilnehmer: repräsentiert die Anmeldungen mit referenz zu
Personen und Durchführungen
- Ausführungen: die Listen der Durchführungen.
Verlinkungen
- Teilnehmer.TEILNEHMER_ID is ForeignKey für Personen.OBJ_ID
Im folgenden eine Beschreibu... |
"""Author Arianna Delgado
Created on June 18, 2020
"""
#Defines a function inside another function.
def display():
#This function message() will only be ablalible to access inside the function display().
def message():
return "Hello"
return message
fun = display()
print(fun())
|
import cv2
from matplotlib import pyplot as plt
imageFile = '.\OpenCV_Python/data/lena.jpg'
imgGray = cv2.imread(imageFile, cv2.IMREAD_GRAYSCALE)
plt.figure(figsize=(6,6))
plt.subplots_adjust(left=0, right=1, bottom = 0, top = 1)
plt.imshow(imgGray, cmap='gray')
plt.axis('off')
plt.savefig('./OpenCV_Python/data/2011... |
from collections import deque
from logging import Logger
from queue import Queue
from .hardware.channel import Channel
from .hardware.command.stm_command_definition import commands_from_stm
from .hardware.command.stm_command_factory import StmCommand
from ..d3_network.client_network_controller import ClientNetworkCont... |
# Valor com 5% de desconto
desconto = 5
valor = float(input('Digite o valor do produto: '))
print('Esse produto com desconto de {}% custará R$ {:.2f}'.format(desconto, valor - (valor * desconto / 100)))
|
from .CrawlerAosfatos import CrawlerAosfatos
from .ScraperAosfatos import ScraperAosfatos
from ..Interfaces.ICollector import ICollector
class CollectorAosfatos(ICollector):
def __init__(self, url):
self.url = url
def get_news(self):
scraper = CrawlerAosfatos(self.url)
list_pages = sc... |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 19 02:52:52 2017
@author: Yam
"""
#parse massflow
import pandas as pd
import numpy as np
def process_outfile(run_dir, outfile):
times=[]
pos=[]
co2_sim=False
with open(run_dir+outfile,'r') as fo:
line=fo.readline()
... |
# -*- coding: utf-8 -*-
import nysol._nysolshell_core as n_core
from nysol.mcmd.nysollib.core import NysolMOD_CORE
from nysol.mcmd.nysollib import nysolutil as nutil
class Nysol_Mmvstats(NysolMOD_CORE):
_kwd ,_inkwd,_outkwd = n_core.getparalist("mmvstats",3)
def __init__(self,*args, **kw_args) :
super(Nysol_Mmvs... |
from typing import Tuple
from cgshop2021_pyutils.instance import Instance
class InvalidSolutionError(RuntimeError):
def __init__(self, instance, solution, message):
super().__init__(message)
self.instance = instance
self.solution = solution
class RobotCollisionError(InvalidSolutionError)... |
from challenges.insertion_sort.insertion_sort import insertion_sort
def test_insertion_sort():
arr = [8,4,23,42,16,15]
actual = insertion_sort(arr)
expected = [4,8,15,16,23,42]
assert actual == expected
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
——————————————
Autor: Alvaro Peris Zaragoza
Ano: 2017
Descripción:
Constantes del dispositivo
———————————————
'''
#Nombre del dispositivo
#------------------------
DEVICE_NAME = 'Emulador de comunicaciones vía App'
AUTHOR = 'Alvaro Peris'
SERVER_KEY = 'XK3451'
#R... |
import requests
import sys
import argparse
import csv
import json
def createParser ():
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--config', default='config.json')
return parser
parser = createParser()
namespace = parser.parse_args (sys.argv[1:])
with open(namespa... |
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import MinMaxScaler
def main():
# Faz a leitura do arquivo
input_file = 'dataset/imports-85Clear.data'
names = ['symboling','normalized-losses','make','fuel-type','aspiration','num-of-doors',... |
#!/usr/bin/python
# Given: Positive integers n≤40 and k≤5.
# Return: The total number of rabbit pairs that will be present after n months if
# we begin with 1 pair and in each generation, every pair of reproduction-age
# rabbits produces a litter of k rabbit pairs (instead of only 1 pair).
with open('rosalind_fib.txt... |
import json
json_data = open(r"./ResultsSmallData.json").read()
print(json_data) |
import argparse
import getpass
import requests
import logging
import os
import time
class MobileApi(object):
def __init__(self, language):
self.url = "https://courses.edx.org"
self.mobile_api_url = '{}/api/mobile/v0.5/video_outlines/courses'.\
format(self.url)
self.sess = requ... |
#### -*- coding:utf-8 -*- #######
from tulip import get_event_loop, tasks, futures
import functools
from . import EventLoop
def in_loop_call(loop):
print("IN LOOP")
def print_msg(msg):
return lambda msg=msg: print(msg)
loop.call_soon(print_msg('SOON 1'))
loop.call_later(0.6, print_msg('LATER ... |
from hashlib import blake2s
blake = lambda x: blake2s(x).digest()
from rlp.sedes import big_endian_int, Binary, binary, CountableList, BigEndianInt, Binary
int256 = BigEndianInt(256)
hash32 = Binary.fixed_length(32)
import rlp
import bls
import random
privkeys = [int.from_bytes(blake(str(i).encode('utf-8')), 'big') fo... |
import sys,pygame
from pygame import gfxdraw
pygame.init()
screen = pygame.display.set_mode((400,400))
screen.fill((255,255,255))
pygame.display.flip()
red=(255,0,0)
def ROUND(n):
return int(n+0.5)
def directLine(x1,y1,x2,y2):
#x,y = x1,y1
x=x1
y=y1
m=float((y2-y1)/(x2-x1))
b=float(y1-m*x1)
... |
# import myfuncs as mf
from myfuncs import hello
def my_new_hello():
hello()
print("Done")
def hello():
print("New hello here") |
from sklearn.model_selection import train_test_split, KFold, cross_val_predict
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import confusion_matrix, classification_report,accuracy_score
import pandas as pd
filename = 'Data.csv'
# Remember to remove the header in this case!
# otherwise, you ... |
import numpy as np
import torch
from meta_learn.util import get_logger, _handle_input_dimensionality
from config import device
class RegressionModel:
def __init__(self, normalize_data=True, random_seed=None):
self.normalize_data = normalize_data
self.logger = get_logger()
self.input_dim =... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('investigator', '0004_auto_20170530_0923'),
]
operations = [
migrations.AlterField(
model_name='investigatorrates... |
from flask_frozen import Freezer
from app import app
freezer = Freezer(app)
if __name__ == '__main__':
freezer.freeze() |
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
from django import forms
from .models import User
from datetime import datetime
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
class UserCreateForm(forms.ModelForm):
BIRTH_YEAR_CHOICES = [x for x in range(int(datetime.now().year), int(datetime.now().year... |
from odoo import models, api, fields
class WhatsappSendMessage(models.TransientModel):
_name = 'whatsapp.message.wizard'
_description = 'send whatsapp message to opportunity'
user_id = fields.Char(string="Recipient", required=True)
phone = fields.Char(string="Phone", required=True)
message = fie... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2020-03-28 08:06
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... |
from flask_wtf import FlaskForm
from wtforms import PasswordField,StringField
from wtforms.validators import DataRequired, InputRequired, Length, Email
class LoginForm(FlaskForm):
"""Login form."""
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', valid... |
import csv,sys,argparse
from mongo_repo import Repository
class RepoInfo:
repo = None
def __init__(self):
self.repo = Repository()
def getCounts(self):
items = []
item = {'Name':'Urls', 'Count':self.repo.countUrls(None)}
items.append(item)
item = {'Name':'Data', 'Cou... |
#!/usr/bin/env python
from __future__ import print_function
from argparse import ArgumentParser
from progressbar import ProgressBar
import concurrent.futures
import h5py
import ipdb
import numpy as np
from tasks import TaskPatchesCached
def extract_patches(args, task):
X = np.zeros((args.n_examples, 3, args.p... |
import itertools as itr
import causaldag as cd
from utils.poset import Poset
def mag2sparsity(mag):
return mag.num_edges, mag.num_bidirected
def mag2skellsparsity(mag):
return (mag.num_edges,)
def mag2poset(mag):
d = cd.DAG(nodes=mag.nodes, arcs=mag.directed)
p = Poset.from_dag(d)
return p
... |
"""
EXERcIcE LISTES ET VARIABLES
prix = int(input("quel est le prix ?"))
nb = int(input("combiens d'articles avez-vous ?"))
tva = (prix*nb)*0.2
total = prix*nb+tva
print("le prix de votre article est de",prix,"€","vous en avez:", nb,"ce qui vous fait",total,"€","dont", tva,"€ de TVA")
liste= [4,5]
print(lis... |
class ConnectionTable(object):
def __init__(self):
self.zombies = [] # list of socket.socket
self.connected = [] # list of socket.socket
|
# módulo destinaod a crear un objeto que guarde las estadísticas y trabaje
# con ellas
from collections import namedtuple, defaultdict
from cargar_archivos import load_attractions
EstadisticasIteracion = namedtuple(
"EstadisticasIteracion_type",
["esperas_en_fila", "llantos", "personas_retiradas", "energia_re... |
from __future__ import unicode_literals
from django.db import models
class BookedTicket(models.Model):
name = models.CharField(max_length=250)
age = models.IntegerField()
gender = models.CharField(max_length=250)
berth_preference = models.CharField(max_length=250, blank=True)
coach = models.CharFi... |
__author__ = 'rakesh.varma'
import cx_Oracle
import sys, os
import time, platform
class OracleFactory:
config = None
pool = None
def __init__(self, config):
self.config = config
self.pool = cx_Oracle.SessionPool(config.username, config.password, config.database, 1, int(config.poolsize),1, ... |
import torch
import numpy as np
def train_model(model, optim, loss_func, num_epoch, train_dl, test_dl, batch_size, path_to_save_model, verbose_every=1000):
loss_hist = []
train_acc_hist = []
test_acc_hist = []
for epoch in range(num_epoch):
for step, batch in enumerate(train_dl, 1):
... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x,nextNode=None):
self.val = x
self.next = nextNode
class Solution:
def removeNthFromEnd(self, head, n):
preNode = ListNode(0)
preNode.next = head
first = preNode
second = preNode
f... |
print('Enter a Number:')
number=int(input())
print(number)
print(number*2)
import sys
sys.version
print('Enter a Float Number')
number=float(input())
print(number)
print('Enter your name:')
#nameis=raw_input()
nameis=input()
print ("Name is "+ nameis )
print('Enter your name:')
nameis=input()... |
from unittest import TestCase
import unittest
import sys
sys.path.append('../')
from leetCodeUtil import TreeNode
from kth_smallest_BST import Solution
class TestSolution(TestCase):
def test_kthSmallestBinTreeCase1(self):
sol = Solution()
"""
Given binary tree [1, null, 2],
... |
def solution(A):
number_occurances = {}
for i in A:
if i in number_occurances:
number_occurances[i] += 1
else:
number_occurances[i] = 1
for key, value in number_occurances.items():
if (value % 2 == 1):
return key
return 0
print(solution([9,3,... |
from selenium import webdriver
import urllib2
from pyvirtualdisplay import Display
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
import time
import re
import smtplib
import gtk.gdk
import os
from time import sleep
def intialize():
options ... |
import random, os
people = int(input("Please enter total of employee: "))
cf = open("sales-report.txt", "w")
name=[]
state=[]
sales=[]
country = ["Johor","Kuala Lumpur","Melaka","Selangor","Kedah","Pahang","Perlis","Sarawak","Sabah","Perak","Penang","Terrengganu"]
for x in range (0,people):
name.append("emp-name" + s... |
class stack:
maxSize = 100
def __init__(self):
self.topIndex = -1
self.stackstorage = []
def getstackdata(self):
''' return stack data as list '''
return self.stackstorage
def push(self,element):
''' push element to stack
push(element)
... |
# Opdracht 4 -- if-statement
# Maak een functie met daarin een if-statement
# deze functie moet de parameter returnen mits deze even is. de functie hoeft geen vaste returnvalue te hebben, want als het niet even is kan je 'None' returnen.
# in deze opdracht zit veel meer problem-solving, dus als je er niet uit k... |
from django.urls import path
from ticketSales import views
urlpatterns = [
path('concert/list', views.concertListView),
path('location/list', views.locationListView),
path('concert/<int:concert_id>', views.concertDetailsView),
path('time/list', views.timeView),
path('concertEdit/<int:concert_id>',... |
# /bin/env python3
# ==============================================================================
# Copyright (c) Moises Martinez by Fictizia. 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 ... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Author: shoumuzyq@gmail.com
# https://shoumu.github.io
# Created on 2015/11/6 13:26
# Definition for binary tree with next pointer.
class TreeLinkNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
... |
from django.shortcuts import render, redirect
from django.core.files.storage import FileSystemStorage
from django.urls import reverse_lazy
from django.views.generic import ListView, CreateView
from .forms import BookForm
from .models import Book
def index(request):
return render(request, 'core/index.html')
def... |
# File_name: lambda_function.py
# Purpose: Lambda function to transform apache log to elasticsearch format.
# Author: Søren Wandrup-Bendixen
# Email: soren.wandrup-Bendixen@cybercom.com
# Created: 2019-07-01
# Called from Kinesis firehose
import base64
import json
import re
import os
import logging
import datetim... |
#!/usr/bin/env python2.5
# $Header: /opt/cvs/CADD/bin/runCADD.py,v 1.2 2011/01/18 00:56:07 nadya Exp $
# $Id: runCADD.py,v 1.2 2011/01/18 00:56:07 nadya Exp $
# vision can be launched from a python shell like this:
#import Vision; Vision.runVision()
import sys
import CADD
if '__IP' in dir(): # ipython
... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from rfcomm_server import RFCOMMServer
btserver = RFCOMMServer()
btserver.wait_for_connection()
while True:
data = btserver.wait_for_data()
btserver.close() |
'''
간단한 게임으로 deep q learning 구현해보기
10 x 10 크기의 격자세상에서 Enemy, Food, Player가 존재.
'''
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
(train_images, train_labels), (test_images, test_labels) = datasets.mni... |
import time
import timeit
import functools
def time_call(timesToRun):
def _time_call(func):
@functools.wraps(func)
def __time_call(*args, **kwargs):
start = timeit.default_timer()
for run in xrange(timesToRun):
ret = func(*args, **kwargs)
... |
from tkinter import *
def login():
u=e1.get()
p=e2.get()
if(u=='admin' and p=='admin'):
root.destroy()
import welcome
else:
l4.configure(text='Invalid Username/Password',fg='red')
def exit():
root.destroy()
root=Tk()
root.state('zoomed')
root.resizable(width=False,height=False)
root.c... |
# -*- encoding: utf-8 -*-
from typing import TextIO, List, Union, Tuple
from . import logger
from .mtypes import Function, Class, Method, Property, Enum
from .utils import Settings
class Writer:
_output: TextIO
_settings: Settings
def __init__(self, output: TextIO, settings: Settings):
self._o... |
import tkinter as tk
import threading
from grid import Grid
def draw_cell_bbox(canvas, bbox):
return canvas.create_rectangle(*bbox)
def draw_red_ball(canvas, bbox):
return canvas.create_oval(*bbox, fill='red')
def draw_gray_box(canvas, bbox):
return canvas.create_rectangle(*bbox, fill='gray')
def draw_yellow_st... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.