text stringlengths 38 1.54M |
|---|
from unittest import TestCase
from ladder import Ladder
class TestLadder(TestCase):
def test_not_implemented(self):
self.assertRaises(NotImplementedError, Ladder)
|
from numpy import mean
from scipy.stats import kendalltau, spearmanr, rankdata
from operator import itemgetter
from recsys.evaluation import ROUND_FLOAT
from recsys.evaluation.baseclass import Evaluation
def _compute(f, ground_truth, test):
elems = len(list(set(map(itemgetter(0), ground_truth)) & set(map(itemgett... |
# 문제 : https://programmers.co.kr/learn/courses/30/lessons/42746?language=python3
# compare override 참고 : https://velog.io/@sparkbosing/python-%EB%82%B4-%EB%A7%88%EC%9D%8C%EB%8C%80%EB%A1%9C-%EC%A0%95%EB%A0%ACsort
from functools import cmp_to_key
def compare(x,y):
if(str(x) + str(y) > str(y) + str(x)):
ret... |
a = input()
b = input()
op = 0
if a == b:
print(op)
elif a!=b:
op = len(a)//len(b)
print(op)
elif b!=a:
op = len(b)+len(a)
print(op)
|
"""empty message
Revision ID: 0028_fix_reg_template_history
Revises: 0027_update_provider_rates
Create Date: 2016-06-13 11:04:15.888017
"""
# revision identifiers, used by Alembic.
from datetime import datetime
revision = "0028_fix_reg_template_history"
down_revision = "0027_update_provider_rates"
import sqlalchem... |
# Copyright (c) 2016, Konstantinos Kamnitsas
# All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the BSD license. See the accompanying LICENSE file
# or read the terms at https://opensource.org/licenses/BSD-3-Clause.
'''
This script parses training lo... |
from __future__ import absolute_import, division, print_function
from six.moves import xrange # pylint: disable=redefined-builtin
import tensorflow as tf
#-----------------------------------------------------------------------------------------------------------#
# Random Seed
#------------------------------------... |
import webbrowser
import datetime
import pywhatkit as whatsapp
def open_facebook():
webbrowser.open("http://facebook.com")
def open_google():
webbrowser.open("http://google.com")
def open_ezzy_int():
webbrowser.open("https://ezzyint.com")
def open_youtube_video(ytv):
webbrowser.open("https://w... |
def distance(num1, num2, num3):
return (abs(num1 - num2) <= 1 or abs(num1 - num3) <= 1) and ((abs(num2 - num1) >= 2 and abs(num2 - num3) >= 2) or (abs(num3 - num1) >= 2 and abs(num3 - num2) >= 2))
print(distance(4, 5, 3)) |
from django.forms import Widget, FileField
from django.core.exceptions import ValidationError
from multiplefilefield.widgets import MultipleFileInput
class MultipleFileField(FileField):
widget = MultipleFileInput
def valid_error(self, file_name, file_size, file_count):
# Validate max length in avera... |
from autofix.util.version.BaseVersion import BaseVersion
class VersionDistance(BaseVersion):
def __init__(self, index: int, differ: int, reference: BaseVersion):
self._index = index
self._differ = differ
self._reference = reference
self._version = str(reference)
@property
... |
#coding=utf-8
__author__ = 'LittleYou'
import os
if __name__=='__main__':
rs='D:/shixin/Unit/Results/'
dirlist=os.listdir(rs)
fw=open('D:/shixin/Unit/失信企业整理.txt','a')
for dirr in dirlist:
f=open(rs+dirr,'r')
for line in f.readlines():fw.write(line)
f.close()
fw.close() |
s = input()
alpha = [0 for i in range(26)]
for i in s:
alpha[ord(i)-ord('a')] += 1
for i in alpha:
print(i, end=" ")
|
import numpy as np
#Iold = Integral f(x) dari x = a to b dihitung berdasarkan trapezoidal rule dengan 2^(k-1) panels.
def trapezoid(f,a,b,Iold,k):
if k == 1:Inew = (f(a) + f(b))*(b - a)/2.0
else:
n = 2**(k -2 ) # Number of new points
h = (b - a)/n # Spacing of new points
X = a... |
from time import sleep
from random import choice
print('\033[30m{} DESAFIO 45 {}\033[m\n'.format('='*10, '='*10))
sleep(1)
print('\033[31m-\033[30m=\033[m'*5, end='')
sleep(1)
print(' \033[36mJO\033[31m-\033[m', end='')
sleep(1)
print('\033[35mKEN\033[31m-\033[m', end='')
sleep(1)
print('\033[33mPÔ\033[30m!\033[m ', en... |
#!/usr/bin/python3
"""This Module holds a funtion to read and count
the lines of a txt file
"""
def number_of_lines(filename=""):
"""Funtion to count the lines of a file
Keyword Arguments:
filename {str} -- Name of the file (default: {""})
Returns:
[int] -- Number of lines counte... |
#!/usr/bin/env python2.7
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), "core/src"))
from src.core.src.core.docker import *
from urlparse import urlparse
import argparse
import subprocess
def _clean(images):
for image in images:
dockerRmi(image, ["-f"], failOnError=False)
def... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from ..modeldb import CommonService_pb2 as modeldb_dot_CommonService__pb2
from ..modeldb import ExperimentService_pb2 as modeldb_dot_ExperimentService__pb2
class ExperimentServiceStub(object):
# missing associated documentation comme... |
import numpy as np
import pysal
import time
import imp
import maxpls4_lck
import sys
np.random.seed(100)
w = pysal.lat2W(20,20)
z = np.random.random_sample((w.n,2))
p = np.ones((w.n,1), float)
floor = 100
maxpls2 = imp.reload(maxpls2)
start_time = time.time()
if __name__ == '__main__':
solution = ma... |
from google.appengine.ext import ndb
class Message(ndb.Model):
channel = ndb.StringProperty(required=True)
date_time = ndb.DateTimeProperty(required=True)
count = ndb.IntegerProperty(required=True)
class Channel(ndb.Model):
name = ndb.StringProperty(required=True)
# Repeated strings/list of keys
# Rep... |
# Author: Jim Mainprice
#
# -*- coding: utf-8 -*-
from numpy import *
'''Basic XYZ rotation
Input: 1x3 array of rotations about x, y, and z
Output: 3x3 rotation matrix'''
def xyz_rotation(r):
Sx = sin(r[0]);
Cx = cos(r[0]);
Sy = sin(r[1]);
Cy = cos(r[1]);
Sz = sin(r[2]);
Cz = cos(r[2]);
S... |
from django.urls import path
from .views import Overview,CreatePizza,ListPizza,SpecificList
urlpatterns = [
path('',Overview.as_view(), name="overview"),
path('create-pizza/',CreatePizza.as_view(), name="CreatePizza"),
path('list-pizza=<int:i>',ListPizza.as_view(), name="ListPizza"),
path('list-pizza-<s... |
"""
The following code was produced for the Journal paper
"Automatic crack classification and segmentation on masonry surfaces using convolutional neural networks and transfer learning"
by D. Dais, İ. E. Bal, E. Smyrou, and V. Sarhosis published in "Automation in Construction"
in order to apply Deep Learning and Compu... |
points = [
[5, 1, 3 ,1 ,5],
[1, 2, 1, 2, 1],
[3, 1, 9, 1, 3],
[1, 2, 1, 2, 1],
[5, 1, 3, 1, 5]
]
def heuristic_2(game, player = 'X', oponent = 'O'):
res = 0
for i_row in range(len(game.board)):
for i_column in range(len(game.board[i_row])):
value = game.board[i_row][i_column].symbol_to_show()
... |
import os
import matplotlib.pyplot as plot
from scipy.io import wavfile
#This file converts the .wav files in Test and Train folders to .png files
def createSpec(num):
#num= The digit which we are converting from .wav to .png
wavPath = "Train/" + str(num) + "/"
pngPath = "Trainimg/" + str(num) + "/"
... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
### Traversing Linked List Items ###
def traverse_list(self):
if self.head is None:
print('list has no element')
retur... |
import numpy as np
from scipy.special import lambertw
## QUARTERBACK MODEL
qb_params = np.load('adp_points_models/qb_model.npy')
[qba, qbb, qbc] = list(qb_params)
def qb(adp):
return qba * (adp ** qbb) * np.exp(qbc * adp)
## RUNNING BACK MODEL
rb_params = np.load('adp_points_models/rb_model.npy')
[rba, rbb, rbc]... |
import sys
zeefile = open(sys.argv[1], 'r')
for x in zeefile:
words = x.strip().split()
mystring = ''
for x in reversed(words):
mystring = mystring + x + ' '
print mystring[:-1]
|
# coding: utf-8
"""
CloudCheckr API
CloudCheckr API # noqa: E501
OpenAPI spec version: v1
Contact: support@cloudcheckr.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility ... |
Igrac1= input ('Unesi skare,papir,stijena,guster ili spock')
Igrac2= input ('Unesi skare,papir,stijena,guster ili spock')
if Igrac1=='skare' and Igrac2=='papir':
print('Skare režu papir. Igrac1 je pobijedio!')
elif Igrac1=='papir' and Igrac2=='skare':
print('Skare režu papir. Igrac2 je pobijedio!')
elif... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/9/29 4:11 PM
# @Author : ZhangHao
# @File : test_textcnn.py
# @Desc :
import logging
import os
import paddle.fluid as F
import paddle.fluid.dygraph as D
import sys
import unittest
from sklearn.model_selection import train_test_split
_cur_dir = os.pa... |
from tlp.models import (Group, TextParameter, CompositeGroup, Subparameter,
NumericParameter, DiskParameter, get_disks)
class DisksAndControllersController:
def __init__(self):
self.disks = get_disks()
self._create_groups()
def _create_groups(self):
children = ... |
#!/bin/python
#Creates a graph for all data in a given CSV, using the first column as the x-values, and all other columns as the y-values for the plots. Change the sizing and plotting to suit your needs.
import sys,re,os
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import csv
import argparse
c... |
# credit : https://ianlondon.github.io/blog/web-scraping-discovering-hidden-apis/
# scrape in public home page
#import library
from bs4 import BeautifulSoup
import urllib, json
import pandas as pd
import sys ,re,time
url="https://app.bluemove.es/api/public/locations/list?cityId=100&accountId=1"
def extract_data():
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import io
import time
from pytracing import TraceProfiler
def function_a(x):
print('sleeping {}'.format(x))
time.slee... |
#coding:utf-8
#情况:某班学生期末考试成绩语文数学英文分别存储在3个列表中,同时迭代三个列表,计算每个学生的总分(并行)
#某年级有4个班,某次开始每班英语成绩分别存储在4个列表中,依次迭代每个列表,统计全学年成绩高于90分的人数 (串行)
from random import randint
chines = [randint(60,100) for _ in xrange(40)]
math = [randint(60,100) for _ in xrange(40)]
eglishe = [randint(60,100) for _ in xrange(40)]
for i in xrange(len(math)... |
import pandas
class OperationExcel:
def __init__(self, file_path):
self.table = pandas.read_excel(file_path)
def get_data_info(self):
"""获取表格详细信息"""
data = []
for v in self.table.index.values:
data_dict = self.table.loc[v].to_dict()
data.append(data_dic... |
import cv2
img = cv2.imread("limiar.png", 0)
limiar, imgLimiar = cv2.threshold(img, 128, 255, cv2.THRESH_TOZERO_INV)
cv2.imshow("Limiar", imgLimiar)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
from __future__ import absolute_import
import logging
from gevent.lock import Semaphore
from .holder import TreeHolder
from .watcher import TreeWatcher
logger = logging.getLogger(__name__)
class TreeHub(object):
"""The hub for holding multiple trees."""
def __init__(self, huskar_client, startup_max_conc... |
#!/usr/bin/env python3
""" Module of Index views
"""
from flask import jsonify, abort, request
from api.v1.views import app_views
from models.user import User
from os import getenv
@app_views.route('/auth_session/login', methods=['POST'], strict_slashes=False)
def session_login():
""" POST /api/v1/auth_session/lo... |
from flask import Flask, render_template, jsonify
from datetime import datetime
from bs4 import BeautifulSoup
from flask_sqlalchemy import SQLAlchemy
import requests
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] =... |
# __author__ == 'jakey'
from django.db import models
from django.contrib.auth.models import User
class CommentScenic(models.Model):
scenic_id = models.ForeignKey("scenic.ScenicDescribe", verbose_name="景点ID", on_delete=models.CASCADE)
user_id = models.ForeignKey(User, verbose_name="用户ID", on_delete=models.CAS... |
import os
import jinja2
import webapp2
HTML_PATH = "templates"
JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(os.path.dirname(__file__), HTML_PATH)
),
extensions=['jinja2.ext.autoescape'])
class MainPage(webapp2.RequestHandler):
def get(self, base_href):
... |
import pandas as pd
import numpy as np
import json
from scipy.spatial.distance import pdist, squareform
from util.old_read_data_utils import subsample_data, read_data, clean_data
# Function that subsamples a given dataset and writes: a subsampled dataset, along with all pairs distances in the sample
# Input:
# df:... |
from pymongo import MongoClient
from pprint import pprint
MONGODB_URL = "YOUR MONGODB URL"
client = MongoClient(MONGODB_URL)
db = client.business
ASingleReview = db.reviews.find_one({})
print('A sample document:')
pprint(ASingleReview)
result = db.reviews.update_one({'_id': ASingleReview.get('_id')}, {'$i... |
# Generated by Django 3.0.6 on 2020-07-12 15:21
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0002_auto_20200712_1116'),
]
operations = [
migrations.AlterField(
model_name='producto',
nam... |
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions
# browser exposes an executable file
# through selenium test involve the executable which will invoke actual browser
driver = w... |
import tkinter
import tkinter.font
counter = 1
def button1():
global counter
print("button clicked %d times")
label1.config(text='button clicked %d times' % counter)
counter += 1
counters = [1]
def button2():
label2.config(text='button clicked %d times' % counters[0])
counters[0] += 1
to... |
from flask import Flask, jsonify, request
import pymongo
from flask_cors import CORS
from os import environ
from bson.json_util import dumps
import json
app = Flask(__name__)
client = pymongo.MongoClient(
"mongodb+srv://iotadmin:iotadminpassword@cluster0.cowqf.mongodb.net/iotTest?retryWrites=true&w=majority&ssl=t... |
import importlib
import logging
import os
import sys
# Add imports that cause a cyclic dependency in a not taken branch to make code completion work
if False:
from .CraftCompiler import CraftCompiler
from .CraftConfig import CraftConfig
from .CraftDebug import CraftDebug
from .CraftStandardDirs import ... |
def printInfo(arg1,*arg):
"打印任何传入的参数"
print(arg1)
for var in arg:
print("test",end = "-")
print(var)
printInfo(10)
printInfo(20,30,40)
|
"""Module for various helper functions needed for py2/3 compatibility."""
import base64
import binascii
def _ensure_unicode(data):
"""Ensures that bytes are decoded.
Args:
data: The data to decode if not already decoded.
Returns:
The decoded data.
"""
if isinstance(data, bytes):... |
import struct
def bytesToScalar(data_bytes, sign='f', bytes_per_data=4):
data = struct.unpack("{}{}".format(len(data_bytes) // bytes_per_data, sign), data_bytes)
return data
def read(file, bytes_per_data=4, sign='f'):
"""Read binary data from file
Arguments:
file {file or str} -- File... |
year = int(input())
if year%100 == 0:
if year%400 == 0:
print("Leap")
else:
print("Not leap")
elif year%4==0:
print("Leap")
|
# Generated by Django 2.2.6 on 2020-06-04 15:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('studentmanagement', '0002_attendance_attendancereport_feedbackstaffs_feedbackstudent_leavereportstaffs_leavereportstudent_noti'),
]
operations = [
... |
import numpy as np
grid = [[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2, 8, 0],
[0, 0, 0, 4, 1, 9, 0, 0, 5],
[0, 0, 0, 0, 8, 0, 0, 0, 0]]
de... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from game import Game, GameResult
def get_user_request():
try:
res = ""
while res == "":
res = input("> ").strip()
return res
except:
exit(5)
if __name__ == '__main__':
game = Game()
game.draw_logo()
gam... |
"""
Пользователь вводит месяц в виде целого числа от 1 до 12.
Сообщить к какому времени года относится месяц (зима, весна,
лето, осень). Напишите решения через list и через dict.
"""
month = int(input("введите номер месяца: "))
list_month = [["зима", 1, 2, 12], ["весна", 3, 4, 5], ["лето", 6, 7, 8], ["осень",... |
# System
from datetime import date, timedelta
# Flask
from sqlalchemy import and_, asc, desc, func
# RIP
from config import RESULTS_COUNT
from models.memorial import Memorial
from models.media import Media
def init():
# The process running Flask needs write access to this directory:
#store = FilesystemSt... |
# Generated by Django 3.0.8 on 2020-09-25 00:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0004_auto_20200924_2146'),
('authentication', '0001_initial'),
]
operations = [
migrations.AddField(
model_name=... |
from ursina import *
import sys
sys.path.append('../Parkour/')
from block import *
normalSpeed = 2
boostSpeed = 3
normalJump = 0.3
# Level10
class Level10(Entity):
def __init__(self):
super().__init__()
self.block_10_1 = NormalBlock(position = (0, 1, 13))
self.block_10_2 = SpeedBlock(pos... |
import json
num = json.load(open("./numeros.json"))
a = 4000
keys = list(num['NIVELES'].keys())
print(list(keys))
include = []
for key in num['NIVELES']:
level = num['NIVELES'][key]
include.append(level)
if not a > int(key):
print(level)
print({key:include})
break
|
#ler um salario de um funcionario e mostrar seu novo salario com 15% de aumento
salario = float(input('Informe o salario: '))
print('Salario com 15% de aumento: {}'.format(salario*1.15)) |
import os
import sys
import configparser
import argparse
import platform
CONFIG = "setting.ini"
def get_parameters():
osc = platform.system()
current_path = os.getcwd()
project = os.path.basename(os.path.abspath(os.path.join(current_path, '..')))
extra = None
tmp = configparser.ConfigParser()
... |
#!/usr/bin/env python3
import socket
import _thread as thread
#HOST = '127.0.0.1'
HOST = '192.168.15.56' # Endereco IP do Servidor
PORT = 5000 # Porta que o Servidor esta
# Dict com status
Player1 = {
'name' : '',
'score' : 0,
'level' : 0,
'lines' : 0,
'fallingPiece': ... |
from django.shortcuts import render
from django.contrib.auth.models import User, Group
#Importar clase de rest_framework
from rest_framework import viewsets
#Importamos las cases de serializers.py
from servidorapi.serializers import UserSerializer, GroupSerializer, UserApiSerializer
#Cosas a importar
from rest_framewo... |
import math
def func2(typ,x):
if typ ==1:
chad = math.log(math.exp(x)+math.exp(1)-1)
if typ ==2:
chad = -1+math.sqrt(x*x+2*x+6)
if typ ==3:
chad = (x-2+math.sqrt(2)*math.exp(1-0.5*x))
chad = chad*chad
if typ ==4:
chad = (4+math.cos(2)-math.cos(2*x))... |
usernames = ['harry', 'eliott', 'roberto', 'katy', 'amiee', 'sarah', 'admin']
if usernames:
for user in usernames:
if 'admin' in user:
print("Hello Admin, would you like to see a status report?")
else:
print("Welcome back "+ user.title() +", thankyou for logging in again.")
else:
print("Great Scott, We nee... |
# coding: utf-8
if __name__ == '__main__':
import sys
sys.path.insert(0, '..')
from flask import Flask, Blueprint
from tango.ui.tables.utils import SortedDict
class Tango(Flask):
#TODO:
pass
class Page(Blueprint):
#TODO:
pass
class AutoIncrDict(dict):
'''
Used by :: [demjson.... |
import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
class stuff(GridLayout):
def __init__(self):
super().__init__()
self.cols = 1
self.words = GridLayout()
self.words.cols = ... |
from selenium import webdriver
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
# ## 第一步:创建一个FirefoxProfile实例
profile = FirefoxProfile()
# # Firefox浏览器1
# ## 第二步:开启“手动设置代理”
# profile.set_preference('network.proxy.type', 1)
# ## 第三步:设置代理IP
# profile.set_preference('network.proxy.http', '39.108... |
#!/usr/bin/env python
from __future__ import print_function
import copy
import os
import re
import requests
from requests.auth import HTTPBasicAuth
import sys
from time import time
import MySQLdb
try:
import ConfigParser
except ImportError:
import configparser as ConfigParser
try:
import json
except Imp... |
def count_intervals(value, intervals):
result = 0
for interval in intervals:
if value in xrange(interval[0],interval[1]+1):
result += 1
return result
if __name__ == '__main__':
testcases = int(raw_input())
for testcase in xrange(1, testcases+1):
... |
__all__ = ["EXPLICIT_NULL"]
# this object is a sentinel value used to disambiguate values which are being
# intentionally nulled from values which are incidentally `None` because no
# argument was provided
EXPLICIT_NULL = object()
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def splitListToParts(self, root: ListNode, k: int) -> List[ListNode]:
new_list = [None] * k
if not root:
return new_list... |
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 7 13:40:07 2018
@author: esteban struve
"""
import matplotlib.pyplot as plt
from sklearn.datasets import load_wine
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.neural_network im... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
#loops
#average
n=int(input('enter a number:'))
sum=0
for n in range(1,n+1):
sum+=n
avg=sum/n
print(avg)
# In[2]:
#factorial
n=int(input('enter a number:'))
fact=1
for n in range(1,n+1):
fact*=n
print(fact)
# In[18]:
#prime or composite
n=int(input(... |
solution3=[5,4,4,4,3,3,3,3,4,4,6,6,2,2,2,2,5,5,6,5,5,3,3,3,6,6,6,6,1,7,8,1,5,5,5,3,3,3,3,3,3,3,3,3,3,3,3,3,6,6,7,5,5,5,5,4,7,6,6,6,8,1,1,1,5,4,4,4,4,3,3,3,3,3,3,3,3,3,3,3,6,6,5,5,5,5,4,4,6,6,6,6,2,2,8,2,5,5,5,5,5,4,4,4,5,5,5,5,3,3,3,3,6,6,5,5,5,5,5,5,7,6,6,6,8,7,8,9]
for i in range(128):
x=i
array=""
wh... |
# Problema 4.3: Escreva um algoritmo que dados um número inteiro positivo n, imprime na tela todos os números de 1 a n.
n = int(input(" Digite a quantidade de números: "))
num = 1
while num <= n:
print(num)
num = num + 1
print(" Fim ")
|
"""
1. Faça um programa que leia uma matriz 2x3 (2 linhas, 3 colunas). Apresenta os elementos da matriz e seus respectivos índices.
"""
matriz = [] # ................................................... Lendo a matriz
for lin in range(2): # lin corresponde ao índice das linhas
vet_linha = []
for col in range(3)... |
import sys
from abc import ABC, abstractmethod
import sqlite3
import datetime
from PIL import Image, ImageFont, ImageDraw
from PyQt5.QtCore import pyqtSignal, QMimeData
from PyQt5.QtGui import QDrag
from PyQt5.QtWidgets import QWidget, QListWidget, QLineEdit, QPushButton, QApplication, QLabel, QTableWidget, \
QTabl... |
# -*- coding: utf-8 -*-
"""OAuth forms."""
from __future__ import absolute_import, division, print_function, unicode_literals
from flask_babel import lazy_gettext as _
from flask_wtf import FlaskForm
from wtforms import HiddenField
class AuthorizeForm(FlaskForm):
"""OAuth2'orize form."""
scope = HiddenFiel... |
# coding: utf-8
import json
from collections import OrderedDict
import torch
def _args2config(args, keys, json_keys):
if json_keys is None:
json_keys = []
args = vars(args)
config = OrderedDict()
for key in keys:
value = args[key]
if value is None:
continue
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import Flask, flash, redirect, render_template, request, session, abort, Response, send_from_directory, url_for
from flask_security import Security, login_required, \
SQLAlchemySessionUserDatastore, current_user, roles_required, \
logout_user
from flask... |
from django.db import models
# Create your models here.
class Tablero(models.Model):
nombre_tablero = models.CharField(max_length=50)
class Lista(models.Model):
nombre_lista = models.CharField(max_length=50)
fk_tablero = models.ForeignKey(Tablero, on_delete = models.CASCADE)
class Tarea(models.Model):
... |
# Bigger is Greater
# hackerrank.com
# Marco Botros
from itertools import permutations
T = int(input())
for i in range(T):
seq = input()
sortedPermSeq = sorted(list(set(permutations(seq))))
result = ()
for i,v in enumerate(sortedPermSeq):
if (tuple(seq) == v):
if(i == len(sorted... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from models import City
from rest_framework import viewsets
from serializers import UserSerializer,MessageSerializer,CitySerializer
from models import User,City
from datetime import datetime,timedelta
from rest_framework.response import Response
from rest_... |
# Filename: test_normalisation_fuc.py
# Description: test script on normalisation function RIM, OMRI, ISOCOV
# Authors: Loucif ghr.
import numpy as np
import normalisation_fuc as nrm
# performances of the alternatives
x = np.array([ [8, 7, 2, 1, 7],
[5, 3, 7, 5 , 1],
[7, 5, 6, 4 , 1... |
# import necessary libraries
from flask import (
Flask,
render_template,
jsonify,
request)
import pandas as pd
from flask_sqlalchemy import SQLAlchemy
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine
app = Flask... |
from pymediainfo import MediaInfo
import os
def video_analysis(file):
mediainfo = {"v_encoder": None, "res_width": None, "res_height": None, "v_framerate": None, "v_bitrate": None,
"v_during": None, "a_encoder": None, "a_channel": None, "a_samplerate": None, "a_bitrate": None,
"i... |
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
import ast
def test_module(client, base_url):
params = {'name': 'paloaltonetworks.com',
'type': 'A'}
result = client._http_request('GET', full_url=base_url, params=params)
if result:
return 'ok... |
from multiprocessing import Pool
import os, time, random
def pp(num):
print("I'm {} process ({})".format(num, os.getpid()))
time.sleep(random.random())
print("{} sleep".format(num))
if __name__ == '__main__':
print("The main process is {}".format(os.getpid()))
p = Pool(4)
for i in range(10):
... |
import numpy as np
import pickle
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
df_std= pickle.load(open('./model/scaled_data.pkl', 'rb'))
names = pickle.load(open('./model/names.pkl', 'rb'))
pca_flask = PCA(n_components=100)
data_flask=pca_flask.fit_transform(df_std)
k... |
import configparser
cf = configparser.ConfigParser(allow_no_value=True)
cf.read('my.cnf')
print("sections = ", cf.sections())
print(cf.has_section('client'))
print(cf.options('client'))
print(cf.get('client', 'port'))
print(cf.items('client'))
cf.remove_section('client')
cf.add_section('newline')
cf.set('newl... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
import os
import io, json
import pandas
import id_generator
def run(cancer_types, long_names, mongo_tool_ids, tool_contact, out_dir):
last_challenge = "0000000"
last_tool = "0000008"
last_assessment_dataset = "000008R"
last_challenge_dataset = "00000OB"
last_ref_dataset = "000007S"
IDGenerat... |
import pandas as pd
import numpy as np
df_cars = pd.read_csv('cars.csv')
df_cars.head()
print(df_cars.columns)
print(df_cars.pivot_table(values='(kW)',index='YEAR',columns='Make',aggfunc=[np.mean,np.max]))
|
from pyecharts import options as opts
from pyecharts.charts import Bar
from pyecharts.render import make_snapshot
from snapshot_selenium import snapshot
times = 'image://data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAiZSURBVHhe7... |
import torch
def init_weight(net):
for i in range(len(net.rnn.blstm.lstm.all_weights)):
for j in range(len(net.rnn.blstm.lstm.all_weights[0])):
torch.nn.init.normal_(net.rnn.blstm.lstm.all_weights[i][j], std=0.01)
torch.nn.init.normal_(net.FC.weight, mean=0, std=0.01)
torch.nn.ini... |
from django.db import models
from django.core.exceptions import ValidationError
class Course(models.Model):
title = models.CharField(unique=True, max_length=255)
start_date = models.DateField()
end_date = models.DateField()
lecture_count = models.IntegerField()
def clean(self):
if self.st... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.