text stringlengths 8 6.05M |
|---|
# Codewars.com
# If we list all the natural numbers below
# 10 that are multiples of 3 or 5,
# we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Finish the solution so that it returns the
# sum of all the multiples of 3 or 5 below the number passed in.
# Note: If the number is a multiple of both 3 and 5,
# only... |
from Tkinter import *
from ucasts import ID12LA
import Tkinter as tk
import threading
import RPi.GPIO as GPIO
class App(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
#Main Window
self.start()
self.root = tk.Tk()
self.root.wm_title("Republic Poly Direction Kiosk")
... |
#!/usr/bin/env python3
"""
The standard Cartesian axes used for most ProPlot figures.
"""
import matplotlib.dates as mdates
import matplotlib.ticker as mticker
import numpy as np
from .. import constructor
from .. import scale as pscale
from .. import ticker as pticker
from ..config import _parse_format, rc
from ..int... |
__author__ = 'Justin'
import os
import geojson
import networkx as nx
import DefaultRoadSpeed as DRS
from geopy.distance import vincenty as latlondist
# DESCRIPTION:
# This script converts geojson road geometry files to a tractable networkx object (.gexf)
# Geojson map data such as node positions, edge connections, ed... |
#!/usr/bin/env python
""" Do a couple tasks needed for Debosscher paper tables (20101118)
"""
import os, sys
import pprint
import MySQLdb
import cPickle
import gzip
import analysis_deboss_tcp_source_compare
import glob
sys.path.append(os.path.abspath(os.environ.get("TCP_DIR") + \
'Algor... |
import subprocess
def brightness(value):
"""
Control screen brightness
@value : int
"""
try:
assert 0 <= int(value) <= 100
except AssertionError:
return 1
subprocess.call(["xbacklight", "-set", value], shell=False)
return 0
def volume(value):
"""
Control so... |
"""
@author: David
inspired by Telmo Menezes's work : telmomenezes.com
"""
import sys
import numpy as np
import network_evaluation as ne
from draw import genetic_algorithm as ga
np.seterr('ignore')
'''
This is the main file of the program :
it stores datas from the real network necessary to the chosen evaluation met... |
TABLE_SCHEMA = (
'IDKEY:STRING, '
'FECHA:STRING, '
'CREDITO_NRO:STRING, '
'NIT:STRING, '
'FECHA_GESTION:STRING, '
'GRABADOR:STRING, '
'ESTADO_DE_COBRO:STRING, '
'TELEFONO:STRING, '
'ESTADO_CARTERA:STRING, '
'DIAS_DE_MORA:STRING, '
'NOTA:STRING '
) |
import numpy as np
from LSTM import LSTM
from BiLSTM import BiLSTM
def save_model_parameters_theano(model, folder, status):
outfile = folder+'/'+ model.__class__.__name__+status
np.savez(outfile,
W=model.W.get_value(),
U=model.U.get_value(),
V=model.V.get_value(),
... |
from time import sleep
from random import random, randint
from selenium.webdriver import Firefox
def init_driver(logger, options):
driver = Firefox()
driver.get("https://visa.vfsglobal.com/blr/en/pol/login")
logger.info("open site")
sleep(randint(5, 8) + random())
driver.find_element_by_css_selec... |
from skimage import io
from skimage.transform import downscale_local_mean
from skimage.filters import threshold_sauvola as threshold
from skimage.segmentation import clear_border, random_walker
from skimage.measure import label, regionprops
from skimage.morphology import binary_opening, square, remove_small_objects
fr... |
# coding:utf8
#用sklearn吧,贝叶斯假设了变量之间相互独立
|
turno=input("Digite abreviado qual turno você estuda: ")
if (turno == "M"):
print("Bom Dia")
if(turno == "N"):
print("Boa Noite")
if (turno == "V"):
print("Boa Tarde")
if(turno != "V")and(turno != "N")and (turno != "M"):
print("Valor Invalido")
|
from yabadaba import databasemanager
from .IprPyDatabase import IprPyDatabase
# Extend the yabadaba MongoDatabase to include IprPyDatabase operations
class MongoDatabase(databasemanager.get_class('mongo'), IprPyDatabase):
def check_records(self, record_style=None):
"""
Counts the number ... |
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 20 00:29:39 2019
@author: acrobat
"""
import os
import sys
import argparse
from datetime import datetime
import matplotlib.pyplot as plt
from torchvision import utils
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
impo... |
import sys
sys.path.append("..")
from services.manipulation import *
class Format1:
"""
Type 1 -> Text on the top of the image.
Type 2 -> Text in the bottom of the image.
Type 3 -> Text on top and bottom of the image.
"""
def __init__(
self,
image_path,
... |
#Copyright (c) 2019 Natan Nascimento Oliveira Matos <natanascimentom@outlook.com>
#Clock using Tkinter
from tkinter import *
from time import strftime
#For make the clock function
def clock():
def clock_main():
main_structure["text"] = strftime("%H:%M:%S")
def counter():
clock_main()
... |
#!/usr/bin/env python3
"""
Analysis utilities for jet analysis with track dataframe.
Authors:
James Mulligan (james.mulligan@berkeley.edu)
Ezra Lesser (elesser@berkeley.edu)
"""
from __future__ import print_function
# General
import os
import sys
import math
# Data analysis and plotting
import uproot
imp... |
import itertools
from sympy import sieve
from math import sqrt, ceil
import numpy as np
from datetime import datetime
# def timer(func):
# def wrapper(*args, **kwargs):
# start = datetime.now()
# result = list(func(*args, **kwargs))
# # result = func(*args, **kwargs)
# end = date... |
from uc.itm import UCWrappedProtocol, MSG
from math import ceil, floor
from uc.utils import wait_for, waits
from collections import defaultdict
from numpy.polynomial.polynomial import Polynomial
import logging
log = logging.getLogger(__name__)
class Syn_Bracha_Protocol(UCWrappedProtocol):
#def __init__(self, sid,... |
#!/bin/python3
import math
import os
import random
import re
import sys
class Stack:
def __init__(self):
self.bracket_list = []
def push(self, item):
self.bracket_list.append(item)
def pop(self, item):
if len(self.bracket_list) != 0:
if (item == ')' and self.b... |
"""
Created by hzwangjian1
On 2017-08-31
"""
import traceback
def read_write(input_path, output_path, label):
with open(output_path, 'w') as whandler:
with open(input_path, 'r') as rhandler:
str = rhandler.readline()
while str:
try:
sub_strs = str.... |
import random
r = [99, 49]
for j in r:
l = random.sample(range(1, j+1), 10)
for i in l:
n = 0
while i != n:
n = int(input("Enter an integer from 1 to %s: " % j))
if n < i:
print("guess is low")
elif n > i:
print("guess is high")... |
#!/usr/bin/python3
'''
for
'''
exampleList = [1,2,314,413,6,8,9,10,20]
for i in exampleList:
print(i)
print("continue")
print(exampleList)
length = len(exampleList)
for i in range(0,length):
exampleList[i] = exampleList[i] + 1
print(exampleList)
emptyList = []
emptyList.append(1)
emptyList.append(12)
pr... |
import load
import args
import data
import model
import batch
import optimizer
import numpy as np
import os
def train_gaussian_naive_bayes(
train_x,
train_y,
prefix,
validation):
# Make sure the save pathes are valid
# check model save path
if os.path.is... |
import numpy as np
import imutils
import cv2
import argparse
image = cv2.imread("image/picasso.jpg")
cv2.imshow("Original",image)
cv2.waitKey(0)
M = np.float32([[1,0,25],[0,1,50]])
shifted = cv2.warpAffine(image,M,(image.shape[1],image.shape[0]))
cv2.imshow("Shifted Down and Right",shifted)
cv2.waitKey(0)
M = np.f... |
from django.shortcuts import render, get_object_or_404
from .models import Product
from cart.models import Cart
def index(request):
cart = Cart.objects.all()
cart_count = len(cart)
products = Product.objects.all()
return render(request, 'products/index.html', {'products': products, 'cart_count': cart_... |
import requests
from semantic_version import Version
from semver import satisfies
# TODO: AWS Lambda default endpoint timeout is smaller than 30 seconds
EXTERNAL_SERVICE_TIMEOUT = 3
EXTERNAL_SERVICE_MAXRETRY = 5
NODE_INDEX = 'http://npm.taobao.org/mirrors/node/index.json'
NODE_ADDR = 'http://npm.taobao.org/mirrors/no... |
#!/usr/bin/env python
import configparser as _configparser
from os import getenv as _getenv
from os import path as _path
config_dir = _path.dirname(__file__)
env = _getenv('DBENV', 'development')
env = (env if env != "" else 'development')
Config = _configparser.ConfigParser()
Config.read(_path.join(config_dir, env... |
#Menu creation and coding to call each option
import create_attributes
import player_actions
import game_actions
ca=create_attributes
pa=player_actions
ga=game_actions
main_menu={": :":"MAIN MENU : : :",1:"New Game",2:"Resume Game",3:"View Character Attributes",4:"View Class Attributes",5:"View Species Attributes",6... |
#https://www.hackerrank.com/challenges/arrays-ds/problem
#DAY 1
n = input()
n = int(n)
arr = input().split()
for i in range(n-1, -1, -1):
print(arr[i], end=" ")
|
def sumDigit(n):
s = 0
while (n > 0):
s += n % 10
n = n//10
return s
t = int(input())
while(t):
t -= 1
n = int(input())
n *= 10
while (sumDigit(n) % 10 != 0):
n += 1
print(n)
|
import persistence
import logging.config
import os
import json
from protocol_support import *
logging.config.fileConfig(os.path.join(os.path.dirname(__file__), "logger.config"))
ROOM_MESSAGE_NEW_USER_CONNECTED = 'SERVER: {0} is connected.\n'
def kick_user_from_room(target_u_thread, room_pool):
kick_from_default... |
__author__: str = "Eric Mesa"
__version__: str = "0.8.1"
__license__: str = "GNU GPL v3.0"
__copyright__: str = "(c) 2020 Eric Mesa"
__email__: str = "eric@ericmesa.com"
|
#!/usr/bin/env python3
import logging
def main(parsed_args):
import os, os.path, re, shutil, sqlite3, subprocess, sys, textwrap, urllib.parse, urllib.request
if not parsed_args.poco_html_docs_folder:
logging.info("Checking pocoproject.org/documentation ...")
website_index_html = urllib.reques... |
import pytest
from pyfa_ng_backend import create_app
@pytest.fixture
def app():
app = create_app()
return app
@pytest.fixture
def full_fit():
return {
'ship': 32311,
'high_slots': [
{'id': 2929, 'state': 'online', 'charge': 12779},
{'id': 2929, 'state': 'offlin... |
def es8(n):
if n < 5: # Casi base
return True if n != 1 and n != 3 else False
strategia_vincente = [False for _ in range(n + 1)]
strategia_vincente[0] = True
strategia_vincente[2] = True
strategia_vincente[4] = True
for i in range(5, n + 1):
strategia_vincente[i] = not strateg... |
from functools import total_ordering
from amath.Computation.num_properties import digits, digitsafterdecimal
from amath.Computation.relationship import gcd
from ..Errors import Indeterminate
@total_ordering
class _Fraction(object):
__slots__ = ['numerator', 'denominator', 'whole']
"""
Fraction Class. Use... |
import boto3
import os
REGION = os.getenv('AWS_REGION', 'us-west-2')
client = boto3.client('cloudwatch', REGION)
def divide_chunks(l, n):
# looping till length l
for i in range(0, len(l), n):
yield l[i:i + n]
with open('bad-alarms.csv') as infile:
alarms = [a.strip() for a in infile.... |
from sage.misc.latex import latex
from riordan_utils import *
def enhanced_latex(order, row_template):
def coefficient_handler(row_index, col_index, coeff):
return '' if coeff is 0 and col_index > row_index else str(coeff)
def row_handler(row_index, coefficients):
#matrix_rows.append(row_te... |
import json
from chalice.config import Config
from chalice.local import LocalGateway
from app import app
class ResquesterUtil:
@staticmethod
def do_request(method, path, body, headers):
lg = LocalGateway(app, Config(chalice_stage='homolog'))
return lg.handle_request(method=method,
... |
# -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'testKlasyfikatora.ui'
##
## Created by: Qt User Interface Compiler version 5.14.2
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
########... |
"""
Mailgun object storage
"""
from __future__ import absolute_import, division, unicode_literals
import attr
import time
@attr.s
class Message(object):
"""
A :obj:`Message` is a representation of an email in Mailgun.
It can produce JSON-serializable objects for various pieces of
state that are requ... |
#!/usr/local/bin/python
# Filename: demo.py
# More info: http://www.zhihu.com/question/20899988
# -*- coding:utf-8 -*-
import urllib
import urllib2
import re
#page = 1
url = 'http://cctv.cntv.cn/lm/xinwenlianbo'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = { 'User-Agent' : user_agent }
try:... |
import os
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.keras.layers import Dense, SimpleRNN
input_word = 'abcde'
w_to_id = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4}
id_to_onehot = {0: [1., 0., 0., 0., 0.], 1: [0., 1., 0., 0., 0.], 2: [0., 0., 1., 0., 0.], 3: [0., 0., 0., 1.... |
# coding=utf-8
# Copyright 2016 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import pytest
from ... |
import os
import sys, inspect
import tempfile
import pytest
myPath = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, myPath + '/../')
sys.path.insert(0, myPath + '/../light_controller')
from light_controller.server import app
@pytest.fixture
def client():
app.config['TESTING'] = True
client =... |
def find_spaceship(astromap):
for a, row in enumerate(reversed(astromap.split('\n'))):
for b, col in enumerate(row):
if col == 'X':
return [b, a]
return 'Spaceship lost forever.'
|
# 1、字符串:序列操作、编写字符串的其他方法、模式匹配
S='abcd'
print(len(S))
S[0] # 'a'
S[1] # 'b'
S[-1] # 'd'
S[1:2] # bc
S[1:] # bcd
S[:2] # abc
S[:-1] # abc
S[:] # abcd
S + 'efg' #abcdefg
S * 3 # abcdefg abcdefg abcdefg
# 特定函数
# find函数 没有找到时返回-1
S.find('b') # 1
# replace()
S.replace('a','XYZ')
# upper() 大写
S.upper()
# isalpha(... |
#! /usr/bin/python3
import unittest
import auto
class TestJakis(unittest.TestCase):
def test_f0(self):
self.assertTrue(True)
def test_f1__1(self):
w = auto.f1(0)
self.assertEqual(w,0)
def test_f1_2(self):
c = auto.f1(1)
self.assertEqual(c,1)
def test_f1_3(self):
... |
# Generated by Django 2.0.3 on 2018-11-05 07:35
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('orders', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='pizza',
name='pizzaToppings',
),
... |
import numpy as np
from torch.utils.data import Dataset
import os
from torchvision import transforms
from dataloaders import custom_transforms as tr
from abc import ABC, abstractmethod
import cv2
from PIL import Image, ImageFile
import scipy.io as scio
ImageFile.LOAD_TRUNCATED_IMAGES = True
def pil_loader(filename, l... |
#To identify the integer
num=input("Enter number: ")
if num<0:
print "It is negative"
elif num>0:
print"It is positive"
elif num==0:
print"It is zero"
else:
print"MIND----->BOOM!",exit()
#To check if it's a prime number
prime=True
if num==1:
print "It is neither prime nor composite"
el... |
def howMany(aDict):
'''
aDict: A dictionary, where all the values are lists.
returns: int, how many values are in the dictionary.
'''
# Your Code Here
i=0
for e in aDict:
print e
i+=1
return i
animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']}
print howMany(... |
from django.forms import ModelForm
from .models import Guest
class GuestForm(ModelForm):
class Meta:
model = Guest
fields = (
'first_name',
'last_name',
'baby_menu',
'baby_chair',
'diet_restrictions',
)
|
from datetime import date
from django.test import TestCase
from elections.models import (
ElectedRole,
Election,
ElectionSubType,
ElectionType,
)
from organisations.models import Organisation
from organisations.tests.factories import (
DivisionGeographyFactory,
OrganisationDivisionFactory,
... |
import re, calendar, time
from datetime import datetime, date, timedelta
from genshi.builder import tag
from trac.core import *
from trac.web import IRequestHandler
from trac.web.chrome import INavigationContributor, ITemplateProvider
from trac.util.datefmt import to_datetime, utc
class TicketCalendarPlugin(Componen... |
#!/usr/bin/python
# -*- coding: cp936 -*-
import sqlite3
import csv
import xlrd
import xlwt
def getSheet3FromSQLite():
# 打开数据库连接以及需要使用的表格文档
# open('sheet3_baseline.csv', 'rt',
# encoding='utf-8', newline='') as src,
with sqlite3.connect('C:\sqlite\db\hxdata.db') as db:
... |
PAGE_URL = "https://www.kickstarter.com/discover/advanced?category_id=16&woe_id=0&sort=magic&seed=2569455&page="
CELL_URL_STYLE = "soft-black.mb3"
DEFAULT_NUM = 300
"""
Get all links from single webpage of results
"""
def get_links_from_page(driver, link_style=CELL_URL_STYLE):
return [project.get_attribute('href'... |
n = int(input("Ingrese un numero: "))
if n==0:
print("No aplica")
elif n%2==0:
print("Es par")
else:
print("Es impar")
|
from typing import List
import pymorphy2
from nltk import ToktokTokenizer
from kts_linguistics.chars import RUSSIAN_ALPHABET
from kts_linguistics.corpora.corpora import Corpora
from kts_linguistics.phonetics.phonetize import phonetize_word, phonetize
def normalize_corpora(corpora: Corpora) -> Corpora:
new_corpo... |
import abc
import random
from copy import deepcopy
from library import POST
from library import Mining
class POST_UDCC(POST):
def __init__(self, state, mur, reduce=False):
super().__init__(state)
self._ur = dict() # key: role - values: users assigned to key
self._mur = mur # maximum user... |
import smtplib
from email.message import EmailMessage
from pathlib import Path # this is similar to os.path -- allows us to access files
from string import Template # string Template allows you to substitute variables inside of texts
# html = Path('index.html').read_text()
html = Template(Path('index.html').read_text... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 16/4/23 下午2:50
# @Author : ZHZ
# @Description : 根据num_days去划分数据集,默认值是14
import pandas as pd
import numpy as np
import datetime
num_days = 14
days_20141009 = datetime.datetime(2014, 10, 9)
#filtered_outlier_if = pd.read_csv("/Users/zhuohaizhen/PycharmProject... |
# -*- coding:utf-8 -*-
'''
Created on 2016骞�4鏈�1鏃�
@author: huke
'''
def listComprehensions(L=[]):
print(L)
print([s.lower() for s in L if isinstance(s,str)])
if __name__ == '__main__':
L1 = ['Hello', 'World', 18, 'Apple', None]
listComprehensions(L1)
|
def binary_search(givenList, value):
listSize = len(givenList) - 1
first_element_index = 0
last_element_index = listSize
while first_element_index <= last_element_index:
midpoint = (first_element_index + last_element_index) // 2
if givenList[midpoint] == value:
return midpoint
elif givenList[midpoint] <... |
from django.db import models
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)
from django.contrib.auth.models import Group
from .managers import CustomUserManager
class CustomUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length... |
import csv
import sys
class CSV_Tool:
def __init__ (self, source_file):
self.source_file = source_file
self.headers = {
'roll' : 0, 'name' : 1, 'dob' : 2,
'city' : 3, 'state': 4, 'cgpa' : 5 }
self.operations = dict()
self... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from appium_auto.three.page.base_page import BasePage
# from appium_auto.three.page.memberinvitepage import MemberInvitePage
class AddressListPage(BasePage):
def click_addmember(self):
from appium_auto.three.page.memberinvitepage import MemberInvitePage
... |
def merge(u, v):
bu, eu = 0, len(u)
bv, ev = 0, len(v)
result = []
while bu < eu and bv < ev:
if u[bu] < v[bv]:
result.append(u[bu])
bu += 1
else:
result.append(v[bv])
bv += 1
result += u[bu:]
result += v[bv:]
assert(len(result... |
import pygame
import sys
import random
import math
from rules import get_legal_moves, in_check
pygame.init()
pygame.display.set_caption("Chess")
screenx = 640
screeny = 640
screen = pygame.display.set_mode((screenx, screeny))
bgcolor = (250, 250, 250)
clock = pygame.time.Clock()
DARK_SQUARE = (120, 60, 40)
LIGHT_SQ... |
#!/usr/bin/python3
#Handle Parameters sending from php
import sys
titleList = []
i=1
while i<len(sys.argv):
titleList.append(sys.argv[i])
i += 1
title = " ".join(titleList)
#print (title)
#Access to mySQL search database
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="username",... |
# Generated by Django 2.2.6 on 2019-12-07 18:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('work', '0061_historicaldprqty_historicallog_historicalprogressqty_historicalprogressqtyextra_historicalshiftedqty'),
]
operations = [
migrat... |
tempPath = '/directory/to/folder
#Add the temp folder directory here please merci thank you
#make sure it doesn't end with a /
tempPath += '/e6tagimage'
import json
import requests
import random
import urllib.request
import PySimpleGUI as sg
import os
from PIL import Image
import tkinter
def download_progress_hook(c... |
import random
def randInt(min=0, max=100):
num = random.random()*max
return num
print(randInt())
#print(randInt(max=50))
import random
def randInt(min=0, max=100):
num = random.random()*max
return num
print(randInt(max=50))
#print(randInt(min=50))
import random
def randInt(min=0, max=100):
... |
from django.db import models
# Create your models here.
class Company(models.Model):
name = models.CharField(max_length=200)
description = models.TextField(default='')
city = models.CharField(max_length=300)
address = models.TextField(default='')
class Meta:
verbose_name = 'Company'
... |
from classes.model.package import Package
import json
from pathlib import Path
from typing import Any, IO, List
class JsonParser:
@staticmethod
def get_names(path: Path) -> List[str]:
names: List[str] = []
data: Any = JsonParser.get_data(path)
groups: List[str] = ["require", "require-... |
from django.shortcuts import render
from django.http import HttpResponse
from django.http import JsonResponse
from main.models import *
import json
from json import JSONEncoder
from django.core.serializers import serialize
from rest_framework import serializers
from django.conf import settings
from django.http import F... |
from turtle import *
import turtle
import random
class Ball(Turtle):
def __init__(self,x,y,dx,dy,radius,colour):
Turtle.__init__(self)
self.x=x
self.y=y
self.penup()
self.setposition(x,y) #each time we use this we relocate
self.dx = dx
self.dy = dy
self.radius = radius
self.shape("circle")
self.s... |
def port_channel(ip_address,dev=0):
import time
import ssh
if dev != 0:
print("[[DEV:] Getting port-channel information]")
for retries in range(0,3):
try:
show_port_channel_sum = ssh.connect_silent('show etherchannel summary',"show port-channel summary",ip_address=ip_address,... |
import xlrd
kml = '<?xml version="1.0" encoding="UTF-8"?>\n \
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">\n \
<Document>'
workbook = xlrd.open_workbook('collections.xlsx')
worksheet = wor... |
import unittest
from katas.beta.no_duplicates_here import list_de_dup
class ListDeDuplicateTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(list_de_dup(['g', 3, 'a', 'a']), [3, 'a', 'g'])
def test_equals_2(self):
self.assertEqual(list_de_dup([1, 2, 3, 4, 1, 2, 3, 4]), [1,... |
import tkinter
import tadretangulo
import time
def movimentar(retangulo, cv, dx, dy, cor):
cv.create_rectangle(retangulo, fill= cor,outline="black")
tadretangulo.move(retangulo, dx, dy)
#~ cv.update()
cv.create_rectangle(retangulo, fill=cor,outline="black")
cv.update()
#~ return None
#
def main():
w ... |
import bisect
def partition(array, a, b):
x = array[a]
j = a
for i in range(a + 1, b):
if array[i] <= x:
j += 1
c = array[i]
array[i] = array[j]
array[j] = c
c = array[a]
array[a] = array[j]
array[j] = c
return j
def quick_sort(arra... |
#!/usr/local/bin/python3
# -*- conding: utf-8 -*-
from ..utils import db
class Auth(db.Model):
__tablename__ = 'auth'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
username = db.Column(db.String(255))
password = db.Column(db.String(255))
is_active = db.Column(db.Boolean, defau... |
import argparse
import matplotlib.pyplot as plt
import pandas as pd
from PROJECT import *
def show(data):
plt.figure(figsize=(8, 6))
col = [0, 0, 0, 1]
plt.plot(data[:, 1], data[:, 0], 'o', markerfacecolor=tuple(col), markeredgecolor=tuple(col), markersize=4)
# plt.xlim(116.28, 116.33)
# plt.y... |
class Load_synops():
def __init__(self, fname):
self.synops = {}
with open(fname, 'r') as data_file:
for fline in data_file:
line = fline.strip()
if self.line_valid(line):
self.process_line(line)
def line_valid(self, line):
if line[:3] != '333':
return True
return False
def proc... |
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
num_map = {}
for i,n in enumerate(nums):
num_map[n] = i
for i in range(len(nums)):
s = target-nums[i]
if s in num_map and i != num_map[s]:
return([i,num_map[s]]) |
from GameManager import GameManager
import socket
client = socket.socket()
client.connect(('127.0.0.1', 8820))
gameManager = GameManager('x', 'o')
board = GameManager.StartingPosition
print "Connected - Waiting for move"
while( True ):
if (board != GameManager.StartingPosition):
client.sen... |
""" File: fug.py
Author: Abraham Aruguete
Purpose: To create a grid drawing such that it emulates pixels on a screen
or something. Graphics. Woo.
"""
import sys
def terminal():
""" This is a function which takes in the user input, and then checks it
among a list of valid terminal commands. """
... |
#!/usr/bin/env python3
import os
import signal
from subprocess import check_output, PIPE, Popen, STDOUT
from addCrontab import add as addCron
from shlex import quote
from livePrintStdout import livePrintStdout
from certbot import run
from generateEnvFile import generate as generateEnvFile
from printSubprocessStdout imp... |
import matplotlib.colors
import numpy as np
import xarray as xr
from cartopy import crs as ccrs
from matplotlib import pyplot as plt
import matplotlib.patches as mpatches
from confusion_matrix import plot_confusion_matrix
from crop import crop_center, crop_2d
def plot_results(x, y_true, y_pred, name, in_size, date,... |
import requests
f = true
while (f):
login = input("Введите логин: ")
message = input("Введите текст сообщения: ")
req = requests.get("http://192.168.1.178:4567/message?login=" + login + "&text=" + message)
|
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 24 19:04:32 2018
@author: Rafael Rocha
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
import time
import keras
import numpy as np
import matplotlib.pyplot as plt
from skle... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('wherecoffee', '0003_auto_20150618_1708'),
]
operations = [
migrations.AddField(
model_name='coffee',
... |
# Generated by Django 3.1.5 on 2021-01-26 11:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('task', '0004_task_error'),
]
operations = [
migrations.AlterField(
model_name='task',
name='status',
fie... |
db_file = './db/moleskine.db' |
from vector import Vector3D
import struct
import sys as sys
sys.setcheckinterval(10000)
# Globals vars
canvas = None
scene = None
lightsgrid = None
origin = None
invorigin = None
guidelines = []
# Inital scene bounds
max_x = -1
max_y = -1
max_z = -1
min_x = float('inf')
min_y = float('inf')
min_z = float('inf')
# G... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2017-01-10 13:25
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("elections", "0017_election_election_title")]
operations = [
migrations.AddField(
... |
def house_numbers_sum(inp):
return sum(inp[:inp.index(0)])
'''
Task
A boy is walking a long way from school to his home. To make the walk more fun
he decides to add up all the numbers of the houses that he passes by during his
walk. Unfortunately, not all of the houses have numbers written on them, and on
top ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.