index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
3,000 | 0233b46da3b9351f110ffc7f8622ca8f9ee9944d | import asyncio
import secrets
import pytest
from libp2p.host.ping import ID, PING_LENGTH
from libp2p.tools.factories import pair_of_connected_hosts
@pytest.mark.asyncio
async def test_ping_once():
async with pair_of_connected_hosts() as (host_a, host_b):
stream = await host_b.new_stream(host_a.get_id(),... |
3,001 | 89059915df8891efcbe742174bd468a1390598e3 | from unittest import TestCase
from utils.fileutils import is_empty_dir, clear_attributes
class FileUtilsTest(TestCase):
def test_is_empty_dir(self):
self.assertFalse(is_empty_dir(r'c:\Windows'))
def test_clear_attributes(self):
clear_attributes(__file__)
|
3,002 | 4a0d8e6b6205fa57b8614857e1462203a2a7d2c5 | from django.conf.urls import url
from ..views import (buildings_upload, keytype_upload, key_upload, keystatus_upload, keyissue_upload)
from django.contrib.auth.decorators import login_required
urlpatterns = [
url(r'^buildings_csv/$', # NOQA
buildings_upload,
name="buildings_upload"),
url(r'^ke... |
3,003 | 01b14da7d081a67bab6f9921bb1a6a4c3d5ac216 | from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.core.urlresolvers import reverse
import datetime
class Document(models.Model):
document = models.FileField(upload_to='documents/')
uploaded_at = models.DateTimeField(auto_now_add... |
3,004 | 1a7a28a2264ed0204184ab1dd273b0b114657fa7 | # -*- coding:utf-8 -*-
from spider.driver.base.driver import Driver
from spider.driver.base.mysql import Mysql
import time
from pyquery import PyQuery
from spider.driver.base.field import Field,FieldName,Fieldlist,FieldType
from spider.driver.base.page import Page
from spider.driver.base.listcssselector import ListCssS... |
3,005 | 5d618acc0962447554807cbb9d3546cd4e0b3572 | #Calculadora mediante el terminal
numero1 = 0
numero2 = 0
#Preguntamos los valores
operacion = input("¿Qué operación quiere realizar (Suma / Resta / Division / Multiplicacion)?: ").upper()
numero1 = int(input("Introduzca el valor 1: "))
numero2 = int(input("Introduzca el valor 2: "))
#Realizamos las operaciones
... |
3,006 | 9bbf0953d228c970764b8ba94675346820bc5d90 | #!../virtual_env/bin/python
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
from models.base import metadata
from sqlalchemy import create_engine
import os.path
engine = create_engine(SQLALCHEMY_DATABASE_URI)
metadata.create_all(engine)
if not... |
3,007 | 5d05351cd6cd6c0d216e8bc09308532605bfd26e | from sys import exit
def hard():
print("Nice! Let's try something harder")
print("Could you calculate this for me?")
print("4 * 35 + 18 / 2 = ")
aws = input(">")
while True:
if aws == "176":
print("Nice, you correctly answer all the questions")
exit(0)
els... |
3,008 | 4f870e0d86d9f9b8c620115a618ea32abc24c52d | # 只放置可执行文件
#
# from ..src import package
# data_dict = package.pack()
# from ..src.plugins import * #解释一遍全放入内存
# from ..src import plugins #导入这个文件夹(包,模块,类库),默认加载init文件到内存
#
#
# plugins.pack()
from ..src.script import run
if __name__ == '__main__':
run()
|
3,009 | f2c592a0ea38d800510323a1001c646cdbecefff | #!/usr/bin/env python
# -*- coding:utf-8 _*-
"""
@author:tom_tao626
@license: Apache Licence
@file: 17.列表中的元素统计.py
@time: 2020/12/09
@contact: tp320670258@gmail.com
@site: xxxx.suizhu.net
@software: PyCharm
"""
# collections.Counter()
from collections import Counter
list1 = ['a', 'b', 'b', 'c', 'd', 'e', 'a', ... |
3,010 | 1a72da7f436e6c5e73e396b771f8ce1a3affba1a | DEFAULT_LL_URL = "https://ll.thespacedevs.com"
DEFAULT_VERSION = "2.0.0"
DEFAULT_API_URL = "/".join([DEFAULT_LL_URL, DEFAULT_VERSION])
|
3,011 | 422a4945ebf453d3e09e9e7e76dd32b30488680e | import pandas as pd
df = pd.DataFrame({'col1':[1,2,3,4],'col2':[444,555,666,444],'col3':['abc','def','ghi','xyz']})
print(df.head())
#print(df['col2'].unique())
#print(df['col1'] > 2)
newdf = df[(df['col1']>0) & (df['col2'] == 444)]
print("========================")
print(newdf)
def times2(x):
return x*2
print("=... |
3,012 | 41f70cdfc9cbe5ec4560c1f3271a4636cca06d16 | #!/usr/bin/env python
''' export_claims -- export claims in CSV format
https://sfreeclaims.anvicare.com/docs/forms/Reference-CSV%20Specifications.txt
'''
import csv
from itertools import groupby
from operator import itemgetter
import wsgiref.handlers
import MySQLdb
import ocap
from hhtcb import Xataface, WSGI
def... |
3,013 | 06a721c12e3140d4d1cf544a598f512595c4ab66 | #!/usr/bin/env python3
"""(Optional) Test for GameDealer class."""
import unittest
import os, sys
from functools import reduce
sys.path.insert(0, os.path.join(os.path.split(__file__)[0], ".."))
import Lab19_Extending_Builtins.lab19_3 as game_dealer
WHOLE_DECK = sorted(game_dealer.Deck())
class ReportingDealer(... |
3,014 | 3efa5eb97af116929a7426ed3bfb5e4a170cfacd | import sys, math
nums = sys.stdin.readline().split(" ")
my_set = set()
my_list = []
for i in xrange(int(nums[1])):
inpt = int(sys.stdin.readline())
my_set.add(inpt)
my_list.append(inpt)
x = 0
for i in xrange(1, int(nums[0]) + 1):
if (i in my_set):
continue
while (x < len(my_list) and my_l... |
3,015 | d44f8a2dee35d76c152695d49d73f74e9c25bfa9 | #read file
my_file=open("file.txt","r")
#print(my_file.read())
#print(my_file.readline())
#print(my_file.read(3))#read 3 caracteres
"""
for line in my_file:
print(line)
my_file.close()
"""
print(my_file.readlines())#list
#close file
my_file.close()
#create new file and writing
new_file=open("newfile.txt",mode="w",... |
3,016 | 1b4a012f5b491c39c0abd139dd54f2095ea9d221 | import re
from captcha.fields import CaptchaField
from django import forms
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from news.models import News, Comment, Profile
class UserRegisterForm(Use... |
3,017 | 0f2d215a34758f85a29ef7ed8264fccd5e85b66f | #Peptide Encoding Problem: Find substrings of a genome encoding a given amino acid sequence.
# Input: A DNA string Text, an amino acid string Peptide, and the array GeneticCode.
# Output: All substrings of Text encoding Peptide (if any such substrings exist).
def reverse_string(seq):
return seq[::-1]
def compl... |
3,018 | 6f35c29f6f2dcc6c1dae3e9c1ddf595225748041 | #import cvxopt
from cvxopt import matrix, spmatrix, solvers
#import scipy
from scipy.special import expit
import numpy as np
import sys
import pandas as pd
import time
class KernelNC():
"""
distance based classifier for spectrum kernels
"""
def __init__(self, classes):
self.classes = class... |
3,019 | ac2edcd6ea71ebdc5b1df5fd4211632b5d8e2704 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 18 18:53:02 2020
@author: vinhe
I followed below tutorial to push newly created csv to google sheets:
https://medium.com/craftsmenltd/from-csv-to-google-sheet-using-python-ef097cb014f9
"""
import gspread
from oauth2client.service_account import ServiceAcc... |
3,020 | 14f7f31fa64799cdc08b1363b945da50841d16b5 |
class Component:
pass
class Entity:
def __init__(self, id):
self.id = id
self.components = {}
def add_component(self, component):
if type(component) in self.components:
raise Exception("This entity already has a component of that type")
# Since there is only ... |
3,021 | cb0be932813a144cfb51b3aa2f6e0792e49c4945 | # encoding=UTF-8
# This file serves the project in production
# See http://wsgi.readthedocs.org/en/latest/
from __future__ import unicode_literals
from moya.wsgi import Application
application = Application(
"./", ["local.ini", "production.ini"], server="main", logging="prodlogging.ini"
)
|
3,022 | 73d1129418711c35046a99c1972a413357079836 | ../../2.0.2/mpl_examples/axes_grid/simple_axesgrid2.py |
3,023 | b7d75c2523dba0baaf06ba270045a4a344b8156c | """A simple script to create a motion plan."""
import os
import json
import logging
from logging.config import dictConfig
import argparse
import numpy as np
from opentrons_hardware.hardware_control.motion_planning import move_manager
from opentrons_hardware.hardware_control.motion_planning.types import (
AxisConst... |
3,024 | 0c8eb90c1d8a58f54186a30ce98a67310955a367 | import pygame
import utils
from random import randint
class TileSurface():
tileGroup = pygame.sprite.Group()
tileGrid = []
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
self.surface = pygame.Surface((width, height))
def updatePos(self, x, y):
... |
3,025 | b147a22d6bd12a954c0d85c11e578a67f0a51332 | number = int(input("Enter a number, and I'll tell you if it's even or odd: "))
if number % 2 == 0:
print(f"{number} is an even number.")
else:
print(f"{number} is an odd number.") |
3,026 | a9531fb020428e573d189c377652692e301ea4d3 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
school = "Old boy"
def chang_name(name):
global school #声明全局变量
school = "Mage Linux"
print("Before change:", name, school)
name = 'Stack Cong'
age = 33
print("After change:", name)
print("School:", school)
name = "Stack"
chang_name(name)
print(na... |
3,027 | 4e5e1be289b32655736d8c6c02d354a85d4268b7 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""BatchNorm (BN) utility functions and custom batch-size BN implementations"""
from functools import partial
import torch
import torch.nn as nn
from pytorchvideo.layers.batch_norm import (
NaiveSyncBatchNorm1d,
Na... |
3,028 | f26dc3139413c4ed4b04484c095a433e53039cdb | import requests as r
import re
class web_scrap:
seed=""
result=""
tag_attr=[]
def __init__(self,seed):
self.seed=seed
self.set_tag()
self.set_attr()
self.fetch_web(self.seed)
self.crawl()
def fetch_web(self,link):
... |
3,029 | 9d0d4707cc9a654752dd0b98fe0fec6a0c1419a1 | # -*- coding: utf-8 -*-
from handlers.base import Base
class Home(Base):
def start(self):
from movuca import DataBase, User
from datamodel.article import Article, ContentType, Category
from datamodel.ads import Ads
self.db = DataBase([User, ContentType, Category, Article, Ads])
... |
3,030 | 886101e5d86daf6c2ac0fe92b361ccca6132b1aa | #!/usr/bin/env python
#_*_ coding:utf-8 _*_
'''
@author: tanglei
@contact: tanglei_0315@163.com
@file: index.py
@time: 2017/11/1 16:26
'''
#需求:
#1.每个客户端需要监控的服务不同
#2.每个服务的监控间隔不同
#3.允许模板的形式批量修改监控指标
#4.不同设备的监控阀值不同
#5.可自定义最近n分钟内hit\max\avg\last\... 指标超过阀值
#6.报警策略,报警等级,报警自动升级
#7.历史数据的存储和优化 时间越久数据越失真
#8.跨机房,跨区域代理服务器
#第三方的soc... |
3,031 | 5e17299e6a409e433e384935a815bab6ce178ff5 | import tkinter as tk # Import tkinker for GUI creation
from PIL import Image, ImageTk # Allow images to be used as backgrounds
import socket # Importing sockets for low level implementation of networks
import select # Importing select to poll between the user input and received message
import sys # Getting inp... |
3,032 | e7494104ab98df2b640f710fa69584802b3e1259 | class Solution:
def maximumTime(self, time: str) -> str:
ans = ''
for i in range(5):
if time[i] != '?':
ans += time[i]
continue
if i == 0:
if time[1] in ['0', '1', '2', '3', '?']:
ans += '2'
e... |
3,033 | a01783e3687278d1ec529c5123b9151721ba3364 | # coding=utf8
def InsertSort(array_a, n):
for i in range(1, n):
temp = array_a[i]
j = i - 1
while temp < array_a[j] and j >= 0:
array_a[j + 1] = array_a[j] # 如果小于其前驱,则从后往前寻找插入位置并后移。
j -= 1
array_a[j + 1] = temp
return array_a
def ShellSort(array_a, n):... |
3,034 | 024bc95f7255bb8be5c3c4ade9d212c9555a4f01 | string="Rutuja MaluSare"
print(string.casefold())
print(len(string))
"""string1=input("enter string 1")
print("string1")
print(len(string1))
string2=input("enter string 2")
print("string2")
print(len(string2))
string3=string1+string2
print(len(string3))"""
#lower case
print(string.lower())
#upper case
print(string... |
3,035 | 019e8d7159fe07adc245e6476ac1fed5e9c457b5 | import os, sys, string
import linecache, math
import numpy as np
import datetime , time
from pople import NFC
from pople import uniqatoms
from pople import orca_printbas
####### orca_run - S
def orca_run(method, basis,optfreq,custombasis, correlated, values, charge, multip, sym, R_coord):
"""
Runs orca
... |
3,036 | cd1ada2d7979fffc17f707ed113efde7aa134954 | # Copyright (c) 2023 Intel Corporation
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writ... |
3,037 | 807f0094a9736abdfa3f5b629615a80f1e0d13ef | class Rect():
def __init__(self, w, h):
self.w = w
self.h = h
def half(self):
return self.w / 2;
bricks = [Rect(40, 25), Rect(30, 25), Rect(28, 25), Rect(13, 25)]
def setup():
size(500, 500)
noLoop()
def draw():
posx = 0
posy = 0
i = 0
for... |
3,038 | 6c8f690e1b43d459535238e24cccc8aa118e2d57 | # pylint: disable=W0621,C0114,C0116,W0212,W0613
import io
import textwrap
from typing import cast, Any, Dict
import toml
import pytest
from dae.testing import convert_to_tab_separated
from dae.configuration.gpf_config_parser import GPFConfigParser
from dae.configuration.schemas.person_sets import person_set_collectio... |
3,039 | 0d1fda864edc73cc6a9853727228c6fa3dfb19a1 | """
Author : Gülşah Büyük
Date : 17.04.2021
"""
import numpy as np
A = np.array([[22, -41, 2], [61, 17, -18], [-9, 74, -13]])
# For a square matrix A the QR Decomposition converts into the product of an orthogonal matrix Q
# (Q.T)Q= I and an upper triangular matrix R.
def householder_reflection(A):
# A H... |
3,040 | d56c80b4822b1bd0f2d4d816ed29a4da9d19a625 | import collections
def solution(genres, plays):
answer = []
cache = collections.defaultdict(list) # 장르 : [고유번호, 재생횟수]
genre_order = collections.defaultdict(int) # 장르 : 전체재생횟수
order = collections.defaultdict() # 전체재생횟수 : 장르
# 첫번째 딕셔너리와 두번째 딕셔너리 생성
for i in range(len(genres)):
cache[ge... |
3,041 | 84a4a0a16aea08ee874b09de163fd777be925f18 | import numpy as np
import math
import matplotlib.pyplot as plt
def signif_conf(ts, p):
''' Given a timeseries (ts), and desired probability (p),
compute the standard deviation of ts (s) and use the
number of points in the ts (N), and the degrees of freedom (DOF)
to calculate chi. '''
s = np.std(ts... |
3,042 | 882d265f14c04b2f2f626504d18e2cd07dcc8637 | """
This module is used to extract features from the lines extracted from documents
using BERT encodings. This package leverages the bert-as-a-server package to create the
embeddings.
Example:
feature_extractor = FeatureExtractor(document) # document is of class Document
encoded_doc = feature_extracto... |
3,043 | 2e23225ec4cd693f5e9460a13d64206f184a86a0 | # -*- coding: utf-8 -*-
"""Code handling the concurrency of data analysis."""
|
3,044 | 836d712c811079f190eae9c2780131a844c9dddf | def twoSensorAvg(input_data, duration=1):
times = {}
for i in input_data:
data = i.split(',')
time = int(int(data[1]) / (duration * 1000))
if time not in times:
times[time] = [0, 0]
times[time][0] += int(data[2])
times[time][1] += 1
ans = []
for i, v i... |
3,045 | fbb081fd52b14336ab4537bb795105bcd6a03070 | from os import environ
from flask import Flask
from flask_restful import Api
from flask_migrate import Migrate
from applications.db import db
from applications.gamma_api import add_module_gamma
app = Flask(__name__)
app.config["DEBUG"] = True
app.config['SQLALCHEMY_DATABASE_URI'] = environ.get('DATABASE')
app.config... |
3,046 | 2de12085ddc73fed85dda8ce3d6908b42fdc4bcc | ## Import modules
import matplotlib, sys, datetime, time
matplotlib.use('TkAgg')
from math import *
from numpy import *
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
from matplotlib import dates
import matplotlib.pyplot as plt
from Tkinter ... |
3,047 | 4d68b663933070cb287689b70d6ded07958cef22 | # Should print 516
def final_frequency():
frequency = 0
with open('input') as f:
for line in f:
frequency += int(line)
return frequency
print(final_frequency())
|
3,048 | 32499688db51f701173ec0ea212c483bf902c109 | from django.db import models
# Create your models here.
class Tutorial(models.Model):
web_title = models.CharField(max_length=200)
web_content = models.TextField()
web_published = models.DateTimeField("date published")
def __str__(self):
return self.web_title
|
3,049 | 22e6616fb98ecfb256587c3767c7c289decc6bf6 | #Copyright (c) 2020 Ocado. All Rights Reserved.
import vptree, itertools
import numpy as np
class _ExtendedVPTree(vptree.VPTree):
"""
VPTree class extended to include the list of points within the tree
"""
def __init__(self, points, dist_fn):
"""
:param points: List of points to add t... |
3,050 | c69dcffc06146af610a7976e522b6e35cabde1aa | # class User:
# def __init__(self, name_parameter, email_parameter):
# self.nameofPerson = name_parameter
# self.emailofPerson = email_parameter
# self.account_balance = 0
# def depositMoney(self, amount);
# self.account_balance += amount
# return self
# def transfe... |
3,051 | a91d2f32afdc20516e56036c352cc267c728e886 | import numpy as np
import matplotlib.pyplot as plt
import csv
def save_cp_csvdata(reward, err, filename):
with open(filename, mode='w') as data_file:
data_writer = csv.writer(data_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
data_writer.writerow(['epoch', 'reward', 'error'])
... |
3,052 | eb403fbb307332c18ffdcdf52589c714f0719960 | import xarray as xr
def precip_stats_to_climatology(fili, start_year=1981, end_year=2015):
"""
Calculates average climatology for annual data - either Jan to Dec or accummulation period
"""
nyear = end_year - start_year + 1
ds = xr.open_dataset(fili)
year = ds['time'].dt.year
#dsMsk ... |
3,053 | e05dac901228e6972c1cb48ce2def3d248b4c167 | # # -*- coding: utf-8 -*-
#
# """
# Py40 PyQt5 tutorial
#
# This example shows three labels on a window
# using absolute positioning.
#
# author: Jan Bodnar
# website: py40.com
# last edited: January 2015
# """
#
# import sys
# from PyQt5.QtWidgets import QWidget, QLabel, QApplication
#
#
# class Example(QWidget):
#
# ... |
3,054 | f2c53efa4b7c2df592582e3093ff269b703be1e0 | # Generated by Django 3.2.5 on 2021-08-05 07:19
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('organization', '0010_aut... |
3,055 | 130f49028833bf57d7e4f9fbb0764801c3508c3b | print("n:",end="")
n=int(input())
print("a:",end="")
a=list(map(int,input().split()))
ans=0
for i in range(n):
for j in range(i+1,n):
for k in range(j+1,n):
ai,aj,ak=sorted([a[i],a[j],a[k]])
if(ai+aj>ak and ai+aj+ak>ans):
ans=ai+aj+ak
print(ans) |
3,056 | 5a181b0c22faa47c6c887daac675dd7374037f30 | from typing import List, Optional
from backend.domain.well import FacilityState, Well
from backend.repository.persistence.well import WellPersistenceSchema
class WellRepository:
schema = WellPersistenceSchema()
def __init__(self, db):
self._db = db
def list(self) -> List[Well]:
return [... |
3,057 | 22b6ea64cdb109e1c6b2536b50935d09d37a7e1a | from nmigen import *
class Top(Elaboratable):
def __init__(self):
self.counter = Signal(3)
self.led = Signal()
def elaborate(self, platform):
m = Module()
m.d.comb += self.led.eq(self.counter[2])
m.d.sync += self.counter.eq(self.counter + 1)
return m
|
3,058 | 4246773a8da61ff21d5faa8ab8ad2d7e75fafb60 | import sqlite3
def to_string(pessoa):
for linha in pessoa:
print('id: {}\nNome: {}'.format(linha[0], linha[1]))
if __name__ == '__main__':
con = sqlite3.connect('lab05-ex01.sqlite')
cursor = con.cursor()
cursor.execute("SELECT * FROM Pessoa")
print(cursor.fetchall())
nome = input(... |
3,059 | e652196f9c74be6f05c6148de152996e449670ea | import numpy as np
from input_parameters.program_constants import ITERATIONS_NUM, TIMESTEPS_NUMB
def init_zero_arrays():
radius_arr = np.zeros((ITERATIONS_NUM, TIMESTEPS_NUMB))
dot_radius_arr = np.zeros((ITERATIONS_NUM, TIMESTEPS_NUMB))
dotdot_radius_arr = np.zeros((ITERATIONS_NUM, TIMESTEPS_NUMB))
d... |
3,060 | 1e4d21998b9f8915167166e5965b0c8c87fcf61d | def search_way(adjacency_list, points):
use = [False for i in range(points.__len__())]
way = [0 for i in range(points.__len__())]
cost = [100000 for i in range(points.__len__())]
cost[0] = 0
checkVar = 0
test = True
while test:
min = 100000
for i in range(points.__len__()):
... |
3,061 | 052574be3f4a46bceefc0a54b1fe268a7cef18a9 | from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
"""
Using the django shell:
$ python manage.py shell
from django.contrib.auth.models import User
from accounts.models import Profile
from papers.models import Paper, Comment, Rating, UserSavedPaper
users = User... |
3,062 | 602a7676129721dbfd318407dd972f80d681146c | class CardHolder:
acctlen = 8
retireage = 59.5
def __init__(self, acct, name, age, addr):
self.acct = acct
self.name = name
self.age = age
self.addr = addr
def __getattribute__(self, item): # __getattribute__ intercepts calls for all
... |
3,063 | 9bb8e0f732eac474dbc01c374f9c74178f65dc36 | import sys
from bs4 import BeautifulSoup
def get_classes(html):
"""
returns a list of classes and titles, parsing through 'html'
"""
# elements = html.find_all("span", "code")
# titles = html.find_all("span", "title")
# classes = []
# for i in range(len(elements)):
# item = element... |
3,064 | fa271d3888dc60582fa0883eaf9f9ebbdffeed9d | # ELABORE UM PROGRAMA QUE CALCULE O A SER PAGO POR UM PRODUTO CONSIDERANDO O PRECO NORMAL E A FORMA DE PAGAMENTO
# a vista dinehiro ou cheque: 10%
# a vista no cartao: 5%
# 2x: preco normal
# 3x ou mais: 20% de juros |
3,065 | 7d3a33968a375141c1c451ecd531ce8d97906c7f | import FitImport as imp
import numpy as np
from math import *
from sklearn.kernel_ridge import KernelRidge
from sklearn.grid_search import GridSearchCV
from sklearn import cross_validation
from sklearn.cross_validation import train_test_split
from sklearn.metrics import mean_squared_error
GSFOLDS = 3
FOLDS = 5
NPTS = ... |
3,066 | 16d86c48c45ab0441046e968ea364d27f6dcfd12 | # -*- coding: utf-8 -*-
# 导入包
import matplotlib.pyplot as plt
import numpy as np
# 显示中文和显示负号
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# X轴和Y轴数据,票房单位亿
a = ["战狼2","速度与激情8","功夫瑜伽","西游伏妖篇","变形金刚5:最后的骑士","摔跤吧!爸爸","加勒比海盗5:死无对证","金刚:骷髅岛","极限特工:终极回归","生化危机6:终章","乘风破浪","神偷奶爸3","... |
3,067 | 6ca2a9040897e49c6407b9b0760240fec93b4df0 | from redstork import PageObject
class AnnotController:
def get_annotations(self, project, page_index):
page = project.doc[page_index]
yield from page.flat_iter()
|
3,068 | 9f0e286268732e8cabb028b7c84f5ba72a6e8528 | """
Python asyncio Protocol extension for TCP use.
"""
import asyncio
import logging
import socket
class TcpTestProtocol(asyncio.Protocol):
"""
Extension of asyncio protocol for TCP data
"""
def __init__(self, test_stream=None, no_delay=False, window=None, server=None):
"""
Initialize ... |
3,069 | 1438a268780217e647999ba031aa4a50a6912d2f | """ AuthService class module.
"""
from urllib.parse import urlencode
from http.client import HTTPConnection, HTTPResponse, HTTPException
from dms2021sensor.data.rest.exc import NotFoundError
class AuthService():
""" REST client to connect to the authentication service.
"""
def __init__(self, host: str, ... |
3,070 | 1e7789b154271eb8407a027c6ddf6c941cc69a41 | import json
import time
from keySender import PressKey,ReleaseKey,dk
config = {
"Up": "W",
"Down": "S",
"Left": "A",
"Right": "D",
"Grab": "LBRACKET",
"Drop": "RBRACKET"
}
### Commands
# Move
def Move(direction,delay=.2):
PressKey(dk[config[direction]])
time.sleep(delay) # Replace with a better condition
Rele... |
3,071 | 2101299d6f6bfcd4726591fc256317968373ca1f | REGION_LIST = [
'Центральный',
'Северо-Западный',
'Южный',
'Северо-Кавказский',
'Приволжский',
'Уральский',
'Сибирский',
'Дальневосточный',
]
CITY_LIST = {
'Абакан': 7,
'Альметьевск': 5,
'Ангарск': 7,
'Архангельск': 2,
'Астрахань': 3,
'Барнаул': 7,
'Батайск':... |
3,072 | b236abaa5e206a8244083ee7f9dcdb16741cb99d | from typing import List, Tuple
import pytest
def fit_transform(*args: str) -> List[Tuple[str, List[int]]]:
if len(args) == 0:
raise TypeError('expected at least 1 arguments, got 0')
categories = args if isinstance(args[0], str) else list(args[0])
uniq_categories = set(categories)
bi... |
3,073 | cc6f70e328b774972e272e9600274dfd9fca93ee | import cv2
import matplotlib.pyplot as plt
import numpy as np
ball = plt.imread('ball.png')
albedo = plt.imread('ball_albedo.png')
shading = cv2.cvtColor(plt.imread('ball_shading.png'), cv2.COLOR_GRAY2RGB)
x,y,z = np.where(albedo != 0)
print('Albedo:', albedo[x[0],y[0]])
print("Albedo in RGB space:", albedo[x[0],y[0]... |
3,074 | c6cbd4d18363f00b73fac873ba45d6063bee7e64 | # -*- encoding: utf-8 -*-
"""
views: vistas sistema recomendador
@author Camilo Ramírez
@contact camilolinchis@gmail.com
camilortte@hotmail.com
@camilortte on Twitter
@copyright Copyright 2014-2015, RecomendadorUD
@license GPL
@date 2014-10... |
3,075 | bf83556b8e8855a0e410fcfb3b42161fbc681830 |
b=int(input('enter anum '))
for a in range(1,11,1):
print(b,'x',a,'=',a*b) |
3,076 | 4aefabf064cdef963f9c62bd5c93892207c301d3 | # Generated by Django 2.1.4 on 2019-04-17 03:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('historiasClinicas', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='actualizacion',
name='valor... |
3,077 | 41013469e65e45f6c909d66c2a54eaf11dfd474c | """A number can be broken into different contiguous sub-subsequence parts.
Suppose, a number 3245 can be broken into parts like 3 2 4 5 32 24 45 324 245.
And this number is a COLORFUL number, since product of every digit of a contiguous subsequence is different
"""
def colorful(A):
sA = str(A)
len_sA = len(s... |
3,078 | 00afab442f56d364c785324f816b52b4a6be609d | '''
Take list of iam users in a csv file like
S_NO, IAM_User_Name,Programatic_Access,Console_Access,PolicyARN
1,XYZ, Yes,No,arn:aws:iam::aws:policy/AdministratorAccess
2.pqr,Yes,Yes,arn:aws:iam::aws:policy/AdministratorAccess
3.abc,No,Yes,arn:aws:iam::aws:policy/AmazonAPIGatewayInvokeFullAccess
'''
import boto3,s... |
3,079 | 088c77e090d444e7057a91cac606995fb523c8ef | print("Enter string:")
s=input()
a = s.lower()
vowels = "aeiou"
consonants = "bcdfghjklmnpqrstvwxyz"
digits = "1234567890"
whitespace = " "
c = 0
v = 0
d = 0
ws= 0
for i in a:
if i in vowels:
v+=1
elif i in consonants:
c+=1
elif i in digits:
d+=1
elif i in whitespace:
... |
3,080 | 226fc85dc8b6d549fddef0ca43ad629875ac0717 | from django.db import models
class Course(models.Model):
cid = models.CharField(max_length=100)
title = models.CharField(max_length=500)
link = models.CharField(max_length=300)
|
3,081 | 4fa9c00a07c8263a6a3afd460b84f21637a771ec |
'''
This file creates the model of Post, which maps to the post table in the mysql database.
The model Provider contains four attributes: author, title, content, and created time.
'''
from django.db import models
class Post(models.Model):
'''
The education post by provider database model
'''
author ... |
3,082 | 8ff9961c1415c04899bbc15ba64811a1b3ade262 | from keras.preprocessing.image import img_to_array
from keras.models import load_model
import tensorflow as tf
import numpy as np
import argparse
import imutils
import pickle
import cv2
# USAGE
# python classify.py --model output/fashion.model --categorybin output/category_lb.pickle
# --colorbin output/color_lb.pickle... |
3,083 | 4f8bc19bb113c9eac7c2ac774ac7b16f569d9704 | # operatorTest02.py
x = 5
x += 3 #복함 대입 연산자
print("x : ", x)
print("-"*30)
total = 0
total += 1
total |
3,084 | 339506777f5471ec99b39c67c28df8ec3d06ce19 | from django.shortcuts import render,redirect
from . import download_function
from django.http import HttpResponse
# Create your views here.
def download(request):
if request.method == "GET":
session = request.GET['session']
title = request.GET['download_title']
download_quality = request.GET... |
3,085 | 3b803850418638bf65528088044918e93ecabff6 | class BucketSort:
def __init__(self,a):
self.a = a
def result(self,bucketCount = 10):
buckets = [[] for i in range(bucketCount+1)]
maxElement = max(self.a)
minElement = min(self.a)
bucketRange = (maxElement-minElement+1)/bucketCount
for i in range(len(self.a)):
... |
3,086 | 82abed3a60829eeabf6b9e8b791085d130ec3dd4 | #Purpose: find the bonds, angles in Zr/GPTMS .xyz outpuf file from simulation
from Tkinter import Tk
from tkFileDialog import askopenfilename
Tk().withdraw()
from pylab import *
from scipy import *
from numpy import *
import numpy as np
import math
##################################################################... |
3,087 | 779445aa22145d5076940ea5b214c25ad233dd0e | """This module provides constants for locale-dependent providers."""
import typing as t
from mimesis.enums import Locale
from mimesis.exceptions import LocaleError
__all__ = ["Locale", "validate_locale"]
def validate_locale(locale: t.Union[Locale, str]) -> Locale:
if isinstance(locale, str):
try:
... |
3,088 | 74843dea00a88513c3a9237eb024e1e14e8b1ff8 | """
实战练习:
1.打开网页
https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable
2.操作窗口右侧页面,将元素1拖拽到元素2
3.这时候会有一个alert弹框,点击弹框中的‘确定’
3.然后再按’点击运行’
4.关闭网页
"""
import pytest
from selenium import webdriver
from time import sleep
from selenium.webdriver import ActionChains
class TestFrame:
def setup(self):
self... |
3,089 | 0f37baf3b08ecf7bd8db43ecc2f29c3ca6e00af0 | version https://git-lfs.github.com/spec/v1
oid sha256:26be7fc8be181fad8e821179cce6be14e37a5f303e532e6fb00f848d5f33fe41
size 752
|
3,090 | a95e64877a1fc9f8109f1293b4ae9176f4f64647 | import requests
import json
import pandas as pd
from sqlalchemy import create_engine
from sqlalchemy.types import VARCHAR,INT,FLOAT,BIGINT
import time
from tqdm import tqdm
#数据库联接设置
connect_info = 'mysql+pymysql://root:rootroot@localhost:3306/db1?charset=UTF8MB4'
engine = create_engine(connect_info)
sql = '''
s... |
3,091 | b9608208f71f25ae05ed9bd7bdf94b8882a26e06 | # Generated by Django 2.1.4 on 2019-04-23 23:37
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('mach... |
3,092 | 3f23a50f44ba17c9b0241a4e3b0e939afeb1f5f0 | from django import forms
class ListingForm(forms.Form):
text = forms.CharField(
max_length=50,
widget=forms.TextInput(
attrs={"class": "form-control", "placeholder": "Things to Buy"}
),
)
|
3,093 | 3e1ca6ed4668e75a62baa65ef44346dd86a16491 | import sqlite3
conn = sqlite3.connect("19-BD/prove.db")
cursor = conn.cursor()
dipendenti = [
("Sofia","commessa"),
("Diego","tecnico"),
("Lucia","cassiera"),
("Luca","Magazziniere"),
("Pablo","Capo reparto")
]
cursor.executemany("INSERT INTO persone VALUES (null,?,?)", dipendenti)
conn.commit()
... |
3,094 | 9a672c17ee22a05e77491bc1449c1c1678414a8c | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.animation as animation
import pylab
from mpl_toolkits import mplot3d
from mpl_toolkits.mplot3d import Axes3D
class Hexapod:
def __init__(self, axis):
"""
Инициализация начальных параметров системы
:par... |
3,095 | d4e62950f10efeb27d19c3d9c672969342ef8c7c | """------------------------------------------------------------------------
MODULE
FContactRegulatoryInfoBase -
DESCRIPTION:
This file provides the custom instance of RegulatoryInfo on the Contact which has all the RegulatoryInfo related methods
VERSION: 1.0.25(0.25.7)
RESTRICTIONS/ LIMITATIONS:
1. Any modi... |
3,096 | 4fb1ece28cd7c6e2ac3a479dcbf81ee09ba14223 | from farmfs.fs import Path, ensure_link, ensure_readonly, ensure_symlink, ensure_copy, ftype_selector, FILE, is_readonly
from func_prototypes import typed, returned
from farmfs.util import safetype, pipeline, fmap, first, compose, invert, partial, repeater
from os.path import sep
from s3lib import Connection as s3conn,... |
3,097 | 8a04447f12a9cb6ba31a21d43629d887a0d1f411 | """
Example 1:
Input: J = "aA", S = "aAAbbbb"
Output: 3
Example 2:
Input: J = "z", S = "ZZ"
Output: 0
Note:
S and J will consist of letters and have length at most 50.
The characters in J are distinct.
查找J中的每个字符在 S 出现的次数的总和。
改进:
J有可能有重复的数。
测试数据:
https://leetcode.com/problems/jewels-and-stones/description/
"""
c... |
3,098 | 20518302b6a67f8f1ac01f1adf4fe06ab2eaf280 | """
Package for haasplugin.
"""
|
3,099 | 09bf7460b2c928bf6e1346d9d1e2e1276540c080 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import versatileimagefield.fields
class Migration(migrations.Migration):
dependencies = [
('venue', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Images... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.