index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
13,000 | 538360299596b49893be605d6fb08f3a41a5ed88 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 23 15:26:26 2018
@author: NicholasWolczynski
"""
import setup
from sklearn import preprocessing
# Create lable encoder
class_y = ['Unreliable', 'Reliable']
le = preprocessing.LabelEncoder()
le.fit(class_y)
# Encode labels for both train and te... |
13,001 | b506b9887527c396d0828e182e58d0b231ddb58d | # Uses python3
import sys
def get_optimal_value(capacity, weights, values):
value = 0.
# write your code here
if capacity == 0:
return value
for i in range(len(weights)):
wi = -1
max = 0
for j in range(len(weights)):
if weights[j] > 0 and values[j] / weights[j] > max:
max = values[j] / weights[j]
... |
13,002 | 38f460115d5313d5c060cfb68e2a635f247efdac | class Solution:
def totalNQueens(self, n: int) -> int:
ans = 0
def dfs(i,col,dig1,dig2):
if i == n:
nonlocal ans
ans += 1
return
for j in range(n):
if j not in col and i+j not in dig1 and j-i no... |
13,003 | cf70648c2711e42e5cf51df7d89c9b1eed38f024 | #!/usr/bin/env python
import json
import os
from optparse import OptionParser
import random
import sys
import wave
try:
from tqdm import tqdm
except ImportError:
def tqdm(x):
return x
from longwave import Wav, OutputWav, ListLevelBackingStore
from reprowave import dual_carpet
OUTPUT_RATE = None
WAV... |
13,004 | 36e51a9ac1d6ad2434fc31f15f0360e67f5c67f2 | x = input()
visited = [0]*(len(x))
ans = 0
s = 0
t = 0
for i in range(len(x)):
if not visited[i]:
if x[i:i+2] == "ST":
ans += 2
visited[i+1] = 1
elif x[i] == "S":
s += 1
elif x[i] == "T" and s:
ans += 2
s -= 1
print(len(x)-ans) |
13,005 | 351c7a4f48300e0e518b44cfa16a605e694f2d0d | """
Homework target model
AlexNet
GoogLeNet
vgg16
resnet18
Must need ILSVRC2012 Validation set for evaluation
"""
import torch
import torchvision
from torchvision import transforms
from torch.utils.data import DataLoader
import scipy
from matplotlib import pyplot as plt
transform = transforms.Compose([
transform... |
13,006 | 2e14cd1d3d415bf4562cc12273f20e9343a09839 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-25 12:27
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('fullstackbooks', '0002_auto_20170725_0819'),
]
operations = [
migrations.RemoveFiel... |
13,007 | 0dba45e27d81cd77f98085fdb8ad445f74653186 | from pefile import PE
from pefile import *
import sys
def getPE(file):
if(PE(file)==True):
PEFileInstance = PE(file, data='module.dll')
yeet = PEFileInstance.dump_info().strip().split('\n')
pedata = []
keys = ['SizeOfOptionalHeader','Characteristics','MajorLinkerVersion','MinorLinke... |
13,008 | bcf111792c32fc63b77972b6b415aaecabd33702 | # -*- coding: cp1252 -*-
#UNIVERSIDADE DO ESTADO DO RIO DE JANEIRO - UERJ
#BRUNO BANDEIRA BRANDÃO
#LISTA 3: FUNDAMENTOS DA COMPURAÇÃO 2018/2
#EXERCÍCIO 5
soma = 0
for i in range (1, 26):
p = float (input ('Digite o Peso da caixa: ' ))
soma += p
print ' O peso total da carga é:',soma
|
13,009 | 188eac26d2384b8077acbb9767c5078c41083d56 | # -*- coding: utf-8 -*-
'''
https://leetcode.com/problems/evaluate-reverse-polish-notation/
'''
class Solution(object):
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
if not tokens:
return
stack = []
for ... |
13,010 | b9d7de226634b706f73913f502778a5369e086ac | '''
NowplayingMovieCrawler.py
功能:获取正在上映电影的id和名字
'''
import requests, random
from lxml import etree
from settings import USER_AGENTS, NOW_PLAYING_URL
# 从settings中获取正在上映电影的url
def UrlManager():
url = NOW_PLAYING_URL
return url
# 解析网页为HTML源代码
def HtmlDownloader(url):
try:
res = requests.get(u... |
13,011 | aab09158f7fb2164f55a44210ab43eeb16ab2685 | from django.contrib import admin
from django.urls import path
from solicitacao.views import *
urlpatterns = [
path('admin/', admin.site.urls),
path('', index, name="pagina_inicial"),
path('autenticar/', do_login, name="autenticar"),
path('veiculos/', lista_veiculos, name="lista_veiculos"),
path('v... |
13,012 | b087eafb86c1227eed85f6cd02c2f7341aac3e69 | import sys
import argparse
import networkx as nx
import json
import urllib2
from matplotlib import pyplot as plt
from matplotlib.colors import ColorConverter
from collections import defaultdict
def as_network(d):
G = nx.Graph()
for n in d['nodes']:
G.add_node(n['data']['id'],
{
'name': n['data']['orf'],
... |
13,013 | 1ce9f3da51759af71d012798bdfe68f65ac2c351 | from rest_framework import routers
from .api import LeaveViewSet
router = routers.DefaultRouter()
router.register('api/leaves', LeaveViewSet, 'leaves')
urlpatterns = router.urls |
13,014 | 07e1b03589c61cecf64b39df6003090d481c073d | import requests,re,pymysql,time
date = time.strftime('%Y-%m-%d')
def insert_mysql(sql):
conn = pymysql.connect(host='121.201.68.21', port=3307, user='jiang', passwd='jiangwenhui', db='daxiangzhanshi',
charset='UTF8')
cur = conn.cursor()
cur.execute(sql)
conn.commit()
for i... |
13,015 | 818b792c7b0c688e646d16ecc60f4382a4e9c4f8 | import blockchain_client as client
def main():
args = client.arg_parse()
client.run_app(client.setup(args))
if __name__ == "__main__":
main() |
13,016 | eab67ddf95ed283f4f66d1f93904c3726ea1d099 | class Solution:
def reverse(self, x: int) -> int:
negative = False
if (x < 0):
x = -x
negative = True
res = 0
while x != 0 :
remainder = x % 10
x = x // 10
res = res * 10 + remainder
if negative:
... |
13,017 | 1fdca4d60e7b3a8ca970d33fa9d9e8aa1e252cc6 | a, b, c = map(int, input().split())
print((a+b)%c)
print((a%c+b%c)%c)
print((a*b)%c)
print((a%c*b%c)%c) //세 수 A, B, C가 주어졌을 때, 위의 네 가지 값을 구하는 프로그램 |
13,018 | e76bd71b66a783c7e80dbd9eccb69cc20280efe8 | from os.path import exists, join
from os import makedirs
from sklearn.metrics import confusion_matrix
from helper_tool import DataProcessing as DP
import tensorflow as tf
import numpy as np
import helper_tf_util
import time
import math
from utils.sampling import tf_sampling
def log_out(out_str, f_out):
f_out.writ... |
13,019 | f78ee81141022d44754a8c2d03cddba9f428bcb5 | from rest_framework import serializers
from core.structures.company.models import Company
from enterprise.libs.base62 import base62_decode, base62_encode
from enterprise.libs.rest_module.exception import ErrorValidationException
from enterprise.structures.common.models import File
from api.company.serializers.address... |
13,020 | 35b0096138bc2062071c66af505824d1c1e185cd | import discord.ext.commands as dec
import database.song
from commands.common import *
class Song:
"""Song insertion, querying and manipulation"""
def __init__(self, bot):
self._bot = bot
self._db = database.song.SongInterface(bot.loop)
_help_messages = {
'group': 'Song informatio... |
13,021 | b87c156d420f357b740703541ad2a2dcff63c3d6 | from sklearn.model_selection import train_test_split
from sklearn.cluster import KMeans
from collections import Counter
from sklearn import metrics
import numpy as np
def KMeansTraining(X_train, Y_train, X_test, Y_test, folds=10):
results = []
for i in range(folds):
myset = set(Y_train[i]) # Cria um c... |
13,022 | 7a56eb78010bcdcc416a6bd161d76e6b4ee21a8e | import random
import pickle
class Graph:
def load(self, path):
with open(path, 'rb') as file:
pickled = pickle.load(file)
self.graph = pickled.graph
self.bidirectional = pickled.bidirectional
def save(self, path):
with open(path, 'wb') as file:
pic... |
13,023 | 8eef1bba5ef99a23b705220a7f8a1bd1e7c8bb89 | #!/usr/bin/python3
import os
import time
import multiprocessing as mp
import cv2
import mss
import numpy as np
import pykitml as pk
# Values shared between processess
A_val = mp.Value('d', 0)
left_val = mp.Value('d', 0)
def on_frame(server, frame, A_val, left_val):
# Toggle start button to ... |
13,024 | fffdb5eb1408f984e0e2498b21214aeb44f9bb84 | # -*- coding: utf-8 -*-
# from utils import FileUtil
# fileNameList = FileUtil.GetFileListFromFolderWithExtension("/Users/SeekMac/Code_Projects/study_python/python3_projects/stock_analyse/data",
# False, [".csv"])
# for fileName in fileNameList.values():
# print(fileName)
import sys
import os
current_fo... |
13,025 | 739622466fe39055f9a9f0141bb303dc0510ab9f | # Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
from servicecatalog_puppet import constants
from servicecatalog_puppet.workflow.stack import stack_for_task
class StackTask(stack_for_task.StackForTask):
def params_for_results_display(self):
... |
13,026 | 75b909849dac671cd0f597b9bc55936b50afb0bf | from app import app
from app.models import *
from flask import render_template, make_response, url_for, abort, request, flash, redirect
import openslide
from openslide import ImageSlide, open_slide
from openslide.deepzoom import DeepZoomGenerator
import re
from unicodedata import normalize
from io import BytesIO
impor... |
13,027 | 04cacfbae4a44add236f25a52273badb91ca3008 |
#~POUTINE~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# #
# It's a Web nano-framework in Python #
# #
#~Enjoy!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
import inspect
import sys
import os
import wsgiref.util as wsgi
from urlparse import urlparse, urlunparse, urlsplit
class Poutine:
environ = {}
r... |
13,028 | 5de1dc8338b33c8e409c7533c148dc36596ca27d | import glob
import os
from commands import *
user_folders = glob.glob('/Users/mihirkelkar/code/Text_Mining_Enron/Length_data/*')
for user in user_folders:
print user
user_sub_dirs = glob.glob(user + '/*')
print len(user_sub_dirs)
if user + '/sent_items' not in user_sub_dirs:
os.chdir(user)
if user + '... |
13,029 | 4e32d24bb04c450426f2a4e802261454f8261ae3 | from flask import render_template
from app import app, db
@app.errorhandler(404)
def not_found_error(error):
"""!
Обработчик ошибки 404 "File not found"
@param error - код ошибки
@return страницу с ошибкой (404.html)
"""
return render_template('404.html'), 404
@app.errorhandler(500)
def int... |
13,030 | 735f713eed63df62a4f2a5630d6bfdaaa976cb52 | import time
class node:
def __init__(self,item,next):
self.item=item
self.next=next
class linkedlist:
def __init__(self):
self.first=None
def traverse(self,callback):
current=self.first
while current is not None:
callback(current.item)
... |
13,031 | ca038afa62c88640ee16bb7391081d0bc84c6d7e | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-09-25 17:21
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('users', '0008_auto_20160925_1705'),
]... |
13,032 | 4e2f6b10bb2c0b2c272c31ab518714d4c5ee9223 | from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support.ui import Select
from selenium.webdriver.firefox.webdriver import WebDriver
from selenium.webdriver.common.keys import Keys
from selen... |
13,033 | e01c1fdc20f2b908d2a9193d70024ae515909dee | import datetime
import unittest
import pandas as pd
from QUANTAXIS import QUANTAXIS as QA
from QUANTAXIS.QAData import (QA_DataStruct_Index_day, QA_DataStruct_Index_min,
QA_DataStruct_Stock_block,
QA_DataStruct_Stock_day, QA_DataStruct_Stock_min,
... |
13,034 | ae2e56bc2c72a4d0c6d36084bfa83a565aae938f | #Reverse the elements of the list
def freverse(x):
y=x[::-1]
return y
x=(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16)
print(x)
print(" After the reverse ")
k = freverse(x)
print(k)
|
13,035 | fe85f628343f61afdefc13f45240bbd16b31a06c | import numpy as np
import pandas as pd
from tqdm.auto import tqdm as tqdm
import os, sys, time, pickle, argparse
sys.path.append('..')
import torch as torch
from torch.autograd import Variable
from torch.utils.data import Dataset, DataLoader
from sklearn.random_projection import johnson_lindenstrauss_min_dim
from skl... |
13,036 | d7630aa28d678316f061fd37b49e9747eda361e7 |
def read_data(filename="data/input1.data"):
with open(filename) as f:
return f.read()
def rot(l, i):
offset = len(l) // 2
pos = (i+offset) % len(l)
return l[pos] if l[pos] == l[i] else 0
if __name__ == "__main__":
captcha = [int(x) for x in read_data()]
captcha.append(captcha[0])
... |
13,037 | b63bd2d80f409d077fb2905202fe1d4d78a99132 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 4 11:30:49 2019
@author: Aditya Tanwar
"""
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#import dataset
dataset = pd.read_csv('tshirts.csv')
features = dataset.iloc[:,1: ].values
#Scatter all these data points on the... |
13,038 | 2046a74bb0d09852f40672d3f0eac7f19a31b9be | # Generated by Django 3.1.2 on 2020-12-04 07:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0002_user_role'),
]
operations = [
migrations.AlterField(
model_name='user',
name='picture',
fi... |
13,039 | 2fb8f5f57f57d974093a803ea8ed3035d4a84b47 | import _surface
import chimera
try:
import chimera.runCommand
except:
pass
from VolumePath import markerset as ms
try:
from VolumePath import Marker_Set, Link
new_marker_set=Marker_Set
except:
from VolumePath import volume_path_dialog
d= volume_path_dialog(True)
new_marker_set= d.new_marker_set
marker_set... |
13,040 | 0586713288864647fe1c71e9bc75079f540dffbe | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 15 16:56:19 2019
@author: madhu
"""
#importing the dataset
import keras
import theano
import os
import matplotlib.pyplot as plt
import numpy as np
from keras.datasets import cifar10
from keras.utils import np_utils
from matplotlib import pyplot as plt
im... |
13,041 | e3d11b1642ffa53ace20620b453192ff7467e219 | #!/usr/bin/env pytest -vs
"""Tests for foundry container."""
# Standard Python Libraries
import os
import time
# Third-Party Libraries
import pytest
READY_MESSAGE = "Server started and listening on port"
RELEASE_TAG = os.getenv("RELEASE_TAG")
VERSION_FILE = "src/_version.py"
def test_container_count(dockerc):
... |
13,042 | 47ec26bc18bcb4a47a1f401fe66d1272f33a9b42 | # Generated by Django 2.2.5 on 2019-10-15 04:56
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('garlic', '0008_auto_20191014_2234'),
]
operations = [
migrations.RenameField(
model_name='order',
old_name='item',
... |
13,043 | 60a7f61cf1eb9e4fa1d7274572a534a186541b6f | num1 = 1000
num2 = 200
num3 = 300
num4 = 400
num5 = 500
num6 = 666
over
|
13,044 | 897d89f7c20f69272426caba857e37c096e3b5d6 | from collections import defaultdict
import operator
from documents.scoretype import ScoreType
class TopDoc:
def __init__(self, doc):
self.doc = doc
self.scores = defaultdict(float)
self.score = 0
def get_doc(self):
return self.doc
def update_score(self, score_type, score... |
13,045 | c7592d2037e0cfd62f341aceae235ec104192b67 | import random
import sys
import timeit
import os
global arr, arrLen, ascending
compares, transpositions, timeSpent, comp, trans, arLen = 0, 0, [], [], [], []
filename = sys.argv[2]
def timer(func):
def tmr(*xs, **kws):
global time
start = timeit.default_timer()
func(*xs, **kws)
ti... |
13,046 | c166d48bf01490c72bfae353cc162b85f2869e88 | """
To check the password strength
It should contain at least
1 character,
1 digit
1 special character
Length should be greater than 8
"""
import re
import getpass
def checkstrength(pswd):
# checking length
flag= 1
if len(pswd) < 8:
flag = 0
# return "length is less than 8 characters"
... |
13,047 | 2eb19f0016cb7b558dd9ab5c4122202ad02dc777 | """
Simple client to the MetaLayer API.
Usage:
import metalayer
client = metalayer.Client()
# Run sentiment analysis over a string
client.data.sentiment("I love kittens")
# Retrieve keywords from a string
client.data.tagging("Kittens and puppies and bears")
# Extract geographic informa... |
13,048 | 2b01d0c58c660c21691601baaf7f4e981b950513 | from .subject import SubjectViewSet, TopicViewSet
from .level import LevelViewSet |
13,049 | 029e18c2b231fd6c836f80831e3e0b1c8c5336f3 | from django.db import connection
def sample_sql_query(params):
with connection.cursor() as cursor:
cursor.execute("SELECT * FROM numerico.track limit 1;")
rows = cursor.fetchall()
return rows |
13,050 | 8af7d268d3a0156bb713016e771d984850842514 | import logging.handlers
import os
import sys
from logging.handlers import RotatingFileHandler
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
def init_logger():
if not os.path.exists("logs"):
... |
13,051 | 0a36d8be551aaed8fa2d7bdd41f64b2b920c2fe8 | from flask import jsonify
from flask import Blueprint
from flask import request
upgrade = Blueprint("upgrade", __name__)
@upgrade.route('/check', methods=['GET'])
def check_upgrade():
version = request.args.get('version')
data = {
"data": {
"version": 1111,
"url": "aaaaaa"
... |
13,052 | ec2672ca22f75368a0e399cd58186bfb3369d9e9 | import firebase_admin
from firebase_admin import credentials
from firebase_admin import db
from pyfirmata import Arduino, util
from tkinter import *
from PIL import Image
from PIL import ImageTk
import time
cont=0
content=0
num=0
prom1=0
prom2=0
prom3=0
placa = Arduino ('COM7')
it = util.Iterator(placa)
it.start()
a_... |
13,053 | 42377ed48c1f58a52338bbeafca4bcfdb4936827 | import timeit
import random
from collections import Counter
def my_func(elems):
counter = dict()
for elem in elems:
if elem not in counter:
counter[elem] = 1
else:
counter[elem] += 1
return counter
def my_top(elems, n):
counter = my_func(elems)
return sort... |
13,054 | e2084649c101995c4ee7b0f0c6b84e281e6d1f3b | import unittest
from datetime import datetime, timedelta
import dateTime
class MyTestCase(unittest.TestCase):
def test_half_birthday(self):
date = datetime(2020, 8, 5)
self.assertEqual(dateTime.half_birthday(2020, 8, 5), date + timedelta(weeks=24))
if __name__ == '__main__':
unittest.main()
|
13,055 | 5422cf7c9fd6f213a886639dcc79912af305aeb1 | def func0(): return 0
print(func0())
def func1(arg): return arg
print(func1('A'))
def func2(arg='B'): return arg
print(func2())
def func3(a, b): return a + b
print(func3('A', 'B'))
def func4(a, b='b'): return a + b
print(func4('A', b='B'))
def func5(): print('func5')
r = func5()
print('func5 return is {}'.format(r... |
13,056 | 2d684640e0a14b912af0cd6230af235c4af4e167 | #This File is the old file that I actually used to improve on telnetid
#with this file I would insert a telnet session using the parameters on a function
#This will be fixed when I start building the real package
def respond(cmd,t,p):
"""takes a command, telnet session, and a prompt
and returns the output of the co... |
13,057 | 6188fb83c41bbc5edaac94eb47a5f7e4d76aa6d1 | import threading
from trade_engine import TradeEngine
class CommandCenter:
def __init__(self, trade_engine):
self._trade_engine = trade_engine
self._thread = threading.Thread(target=self.run)
self._thread.start()
def run(self):
while True:
input_console = input(">... |
13,058 | 345d88093c151b38b9576c0e26df73951a755759 | distancia=float(input('digite a distancia'))
if (distancia<200):
preco=0,5*(distancia)
print ('o preco é R${0:.2f}'.format(preco))
else:
preco=(distancia)*0,45
print('o preco é R${0:.2f}'.format(preco)) |
13,059 | f505ed47435d8e8af70feabd9c6a76235332c458 | from flask import (
Blueprint, make_response, send_from_directory
)
bp = Blueprint('pwa', __name__, url_prefix='')
@bp.route('/manifest.json')
def manifest():
return send_from_directory('static', 'manifest.json')
@bp.route('/sw.js')
def service_worker():
response = make_response(send_from_directory('st... |
13,060 | 32bf9cffbebad7f3f530cc128bf3ad90d818aa14 | from ui.ui import Ui
def main():
main_view = Ui()
main_view.main_loop()
if __name__ == "__main__":
main()
|
13,061 | 824b51fadfb6d3d7b39ac184aa7ba2682fec3789 | #!/usr/bin/env python3
import argparse
NULLDEV='/dev/null'
parser = argparse.ArgumentParser(description='Perform the fast unfolding algorithm over a bivariate distribution.')
parser.add_argument('input_file', metavar='INPUT', type=str,
help='the input file that contains the bivariate distribut... |
13,062 | caa0ad641c5a58397c68432ac4706e186ba8f3d0 |
#用参数做图法画出f(x) anti_f(x) 和 y = x
#f(x) = arcsin(x), x = t, y = arcsin(t)
#
#anti_f(x) = sin(x), x = t, y = sin(t)
def fx(t):
return t
def fy(t):
return arcsin(t)
def anti_fx(t):
return t
def anti_fy(t):
return sin(t)
def cx(t):
return t
def cy(t):
return t
t = linspace(0, 2*pi, 100)
x1 = fx... |
13,063 | dd3c090b77033b1143b1d1ab1ca4b3f972668f68 | import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "studservice.settings")
from django.contrib import admin
# Register your models here.
from studserviceapp.models import IzbornaGrupa
admin.site.register(IzbornaGrupa)
|
13,064 | a5f1566ae5713c17ee110e4e0a41837f2041c633 | #partner was Logan Zipp
fname = "mbox-short.txt"
handle = open(fname)
counter = dict()
for line in handle :
if line.startswith("From:") :
line = line.rstrip()
print (line)
words = line.split()
sender = words[1]
pos = sender.find("@")
email = sender[pos+1:]
print (email)
counter[email] = ... |
13,065 | 2e2d0505ae17e6071175c3ac15259122254d4fa1 | # Generated by Django 3.0.8 on 2020-08-28 13:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('account', '0005_auto_20200828_0150'),
]
operations = [
migrations.AddField(
model_name='order',
name='receive',
... |
13,066 | c126150924ffffe63fec267ecc2d805fa00fd9c7 | from random import randint
from Endereco import Endereco
class Pessoa:
fala = False
#O __init__ declara as variáveis usadas em toda a classe, em qualquer método que chamar o self.
def __init__ (self, nome, idade, sexo, fala=False, come=False, anda=True):
self.nome = nome
self.idade = ... |
13,067 | 319941ae42478a93b969099baff3999f77daf384 | from expungeservice.expunger import Expunger
from expungeservice.models.record import Record
class ExpungerFactory:
@staticmethod
def create():
return Expunger(Record([]))
|
13,068 | 508b862e874e1899dfa2d0c41f2236a2fd6938e8 | from Animal import Animal
class Dog(Animal):
@staticmethod
def speak():
print("woof")
# self = instanta curenta
# instanta = un obiect de acel tip
# obiect intr o variabila
|
13,069 | beccc97df880a57cce6bc65b4f59a7e1decd23de | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/11/9 23:57
# @Author : Liu jinxin
# @Github : liujinxinhen6
# @File : 异常处理.py
# @Function: 异常处理
# URLError是HTTPError的父类
# URLRrror出现的原因:
# 1 连不上服务器
# 2 远程url不存在
# 3 无网络
# 4 触发HTTPError
# ...
import urllib.request
import urllib.error
try:
data = ... |
13,070 | bada0f1bda1b65e58b6b4aa7d769aac2ac261f4e | import area
PEOPLE_AT_CONCERT_PER_SQUARE_METER = 2
FIELD_LENGTH = 240
FIELD_WIDTH = 45
PEOPLE_AT_CONCERT = area.rectangle(FIELD_LENGTH, FIELD_WIDTH)
print("Estão presentes no show aproximadamente", PEOPLE_AT_CONCERT, "pessoas")
|
13,071 | 330fad38fe219fb73e3da517d2e8a03c365ad65e | def SubArraySum(arr, n):
temp,result = 0,0
# Pick starting point
for i in range(0, n):
# Pick ending point
temp=0;
for j in range(i, n):
# sum subarray between
# current starting and
# ending points
temp+=arr[j]
result +=... |
13,072 | 2b5ee46cf68f08a9e25d46d76295bc9da82dd4aa | from __future__ import annotations
from typing import Iterable
from rich.console import Console, ConsoleOptions, RenderResult, RenderableType
from rich.segment import Segment
from rich.style import Style
# def add_vertical_bar(lines:list[list[Segment]], size:float, window_size:float, position:float) -> None
# b... |
13,073 | af8b4e9d7634f40971fbdf8d97d08bf75c2862c7 | for t in range(int(input())):
s = input()
lens = len(s)
if lens < 4:
print(0)
continue
ways = 0
for i in range(int((lens - 2) / 2)):
l = i + 1
i1 = 0
i2 = l
i3 = 2 * l
i4 = i3 + int((lens - i3) / 2)
i5 = lens
# print(i1, i2, i3,... |
13,074 | 9be4268e280fac6458cb9cdcfa33bf71ba2861ce | # 导入系统第三方模块
import datetime
import json
# 导入django自带的功能
from django.views.decorators.http import require_http_methods
from django.shortcuts import HttpResponse, render, redirect
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
# 导入自定义的功能
from Lib.Utils import *
from Lib.Model ... |
13,075 | 2d735aa0ea8cc0df96443b56e323eb1f6d7e11e4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = 'vladimirg'
__version__ = '1.2'
from zabbix_api import ZabbixAPI
import time
import json
import re
import sys
import getpass
import argparse
import os
execfile(os.path.dirname(os.path.realpath(__file__)) + '/../git_update.py')
#Try to get update from git
if git... |
13,076 | b1fe461dde4037f14699d13f0d4a9d7e6d066674 | import sys
from common import readFasta
from sss import shortestSuperString
if __name__ == '__main__':
dnas = readFasta(sys.argv[1])
print shortestSuperString(dnas)
|
13,077 | d1126bf28f8f45f966d82df3a863a84aadaf7151 | # import start
import numpy as np
### customer code start
def main(input_data, context):
IN1 = input_data["IN1"]
mv = IN1['mv']['value']
pv = IN1['pv']['value']
sp = IN1['sp']['value']
mvup = IN1['mvup']['value']
mvdown = IN1['mvdown']['value']
ff=IN1['ff']['value'] if 'ff' in IN1 else 0
... |
13,078 | c4cb9ee48a56ba4b1c9a15164dfe91a353a081b3 | import pygame
pygame.joystick.init()
def goo():
print(pygame.joystick.get_init())
print(pygame.joystick.get_count())
joysticks = [pygame.joystick.Joystick(x) for x in range(pygame.joystick.get_count())]
goo()
pygame.init()
while True:
pygame.time.Clock().tick(27)
for event in pygame.event.get():
... |
13,079 | 5cbefb1fc83d909bc5b79bdad39603f8c09899bd | class Queue(object):
def __init__(self):
self.queue = []
def is_empty(self):
return self.queue == []
def enqueue(self, data):
self.queue.append(data)
def dequeue(self):
if self.queue:
item = self.queue.pop(0)
print(item)
return item... |
13,080 | 9608e780e2d672c059d4b3fbb8fd27328579700a | for n in range(2, 10):
if n % 2 == 0:
print("found an even number ", n)
continue
else:
print("found a number", n) |
13,081 | 11b9bb2c2ebac97e7614190ff525fe91598f99a2 | # -*- coding: utf-8 -*-
"""Logistic_Breast_Cancer
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/18hSIk0waVp_GfrVvbhURVeNo5ql_8b-V
## Logistic Regression without Sklearn
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from ... |
13,082 | 56fa5ed9068ac18b0b2ed0b7d9dcc63f89dde5ce | """Vehicles Routing Problem (VRP) with Time Windows."""
from __future__ import print_function
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp
from random import randrange
import numpy as np
"""Random adjacency matrix of given size"""
def random_adjacency_matrix(... |
13,083 | e68c17932af32f2ee33fa51432fce247aba0b9dd | import json
from chalice import Chalice
from chalicelib import sql_service
from chalicelib import boto_rds_conn
from chalicelib import SqlQueries
app = Chalice(app_name='my_app_aurora')
columns = ["shoetype", "color"]
@app.route('/psycopg')
def index():
return sql_service.select_all()
@app.route('/boto')
def b... |
13,084 | 4cce7ff74b7ba14a561b9c8072b782f2db5c91e8 | import os
from time import sleep
import pytest
import requests
from datadog_checks.dev import docker_run, get_docker_hostname, get_here
BOOTSTRAP = {
'action': 'create_cluster',
'cluster': {'name': 'demo.local'},
'node': {'paths': {'persistent_path': '/var/opt/redislabs/persist', 'ephemeral_path': '/var/... |
13,085 | d562e7b1f132bf123de526808408a0c691d092ff | import os
import pygame
#redblobgames
pygame.init()
#Création de la fenetre
largeur = 1024
hauteur = 768
fenetre=pygame.display.set_mode((largeur,hauteur))
# lecture de l'image du perso
#Dico des images---------------------------------------------------------
#boneproj-----------------------------------... |
13,086 | 94d1007c5265a448375b89f696bce76ff17bcfe6 | n = int(input())
while(n > 0):
w = input()
l = len(w)
if l <= 10:
print(w)
else:
w = w[0:1] + str(l-2) + (w[l-1:l])
print(w)
n -= 1
|
13,087 | fb5ab3bd4f7e7bafd722cbb6493580e8ebfcc693 | import numpy as np
import glob
from keras.preprocessing import image
#input string img_path, returns tensors list of 6 slices of image
def get_tensors(file_name):
#tensor_stack = []
img = image.load_img(file_name, target_size=(260, 1344))
img_arr = np.array(img).astype('float32')/255
tensor_stack = np.... |
13,088 | d543be6f932b8e8f8e42c97ed7dc6b0b19122a70 | import unittest
from unittest.mock import patch
import sys
from .. import play
from ..utils import config
class Test(unittest.TestCase):
def setUp(self):
# Get config
play.conf = config.getConfig()
def test_showBank(self):
play.currentBank = 10
self.assertIsNone(play.showBan... |
13,089 | b630283137e8be909945e9d4c17ffda25bbaa1f0 | #!/usr/bin/env python
# -*- coding:utf-8 _*-
"""
@author: wangye(Wayne)
@license: Apache Licence
@file: Strictly Palindromic Number.py
@time: 2022/09/03
@contact: wang121ye@hotmail.com
@site:
@software: PyCharm
# code is far away from bugs.
"""
class Solution:
def isStrictlyPalindromic(self, n: int) -> ... |
13,090 | 507c63e2e7252a015945dcc07d4bc05c27bb7832 | # Problem: https://codeforces.com/problemset/problem/158/B
# Difficulty: 1100
# Trials: 6
# Time: 00:45:14
n = int(input())
r = 0
d = {i: 0 for i in range(1, 4)}
for s in map(int, input().split()):
if s == 4:
r += 1
else:
d[s] += 1
r += d[2] // 2
d[2] %= 2
if d[2] == 1:
r += 1
... |
13,091 | 0716b4c8ef691d044b0b473903ab841ddfc5dfa8 | # -- coding: UTF-8 --
"""
========================================
Deletion in many to many relationships
========================================
Explaining many to many relationships
"""
from sqlalchemy import Table, Column, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.dialects.mysql import INTE... |
13,092 | b52a0588f292871b389977e38ed1dcb03d697cb2 | p,q=map(int,raw_input().split())
b= p ^ q
a= p ^ q
p= p ^ q
print p,q
|
13,093 | d732073e4a83582ff85be8fc98f5b0592a5ee097 | import xml.etree.ElementTree as ET
class Configuration:
def __init__(self):
self.tree = ET.parse('config.xml')
self.root = self.tree.getroot()
def getUsernamePassword(self,user):
credentials = self.root.findall('login')
for entry in credentials:
if (entry.get('name'... |
13,094 | 4559ef6eb5f6209341007fea8cacc922a9cc36b8 | def test(str):
num=len(set(str))
b=set(list(str))
res=[]
temp=0
copy=[]
for i in b:
copy.append(i)
strr="".join(copy)
for i in range(len(str)-num+1):
j=i
temp=0
while(len(b)>0):
if(j>=len(str)):
break
temp+=1
... |
13,095 | 1c05fd98d8d447c4d43401bc991bb941c9e34623 | month = int(input("Enter the month as a number: "))
day = int(input("Enter the date: "))
if (month == 3 and day >= 20) or month in (4, 5) or (month == 6 and day < 20):
print("It is spring.")
elif (month == 6 and day >= 20) or month in (7, 8) or (month == 9 and day < 22):
print("It is summer")
elif (month == 9 ... |
13,096 | d6b58cfb2cf239545115b3819ac745e69bfc4480 |
class MyIter:
def __iter__(self):
arr = [1]
yield arr
prev = 0
cur = 1
while True:
s = prev + cur
arr.append(s)
yield arr
# 이터레이터 루프 본문 실행
prev = cur
cur = s
for arr in MyIter():
print(arr)
... |
13,097 | 53299575f756187a793d644964e26c35f3eb71ce | import sys
from os.path import join, exists
from css_html_js_minify import css_minify
from reportlib.utils.templating import template_loader
class StyleSheet:
def __init__(self):
self.styles = ['base/styles.css']
self.load()
def append(self, stylesheet):
self.styles.append(styl... |
13,098 | 5d5e33b2b6df173ceb6e39e95cf9d2410b02f77a | from django.urls import re_path
from . import consumers
websocket_urlpatterns = [
re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()),
re_path(r'ws/users/(?P<user_name>\w+)/$',consumers.UsersConsumer.as_asgi())
] |
13,099 | 6287df2a0696430fd2bd7e2fecc04e8dd171411b | #!/usr/bin/python
# -*- coding: utf-8 -*-
#=============================================================
#=============================================================
# Some imports
#=============================================================
import os
import argparse
import domoWebUser
import oneWireDevice
import... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.