index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
988,700
1bff28abb36886dfd87888cdb19228007ead5ed8
a = input('Введите числo: ') y = a.count('3') + a.count('4') + a.count('5') + a.count('6') + a.count('7') + a.count('8') print (y)
988,701
b3ef9c2fd69da3f6000578af075baec4c6ed0d05
from django.db import models # Create your models here. class Record(models.Model): record_number = models.CharField(max_length=50, default='python') title = models.CharField(max_length=50, default='python') expertise_status = models.CharField(max_length=50, default='python') payment_status = models.CharField(...
988,702
03cb5ea937bc37acff83ac6b0f07cb42f0d155cf
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys sys.setrecursionlimit(10 ** 9) n = int(input()) ng1 = int(input()) ng2 = int(input()) ng3 = int(input()) def dfs (n:int, c:int): print (n,c) if c <= 100 and n == 0: #100回以内に0にできた print ("YES") exit () if c == 100: #100回目に到達したので、101...
988,703
7b0fdcf42e5db4e330e12c635c59d4da12ab0c11
import logging from shlex import quote as cmd_quote import speedling.tasks from speedling import conf from speedling import facility from speedling import gitutils from speedling import localsh from speedling import usrgrp from speedling import util LOG = logging.getLogger(__name__) # user and endpoint creation is ...
988,704
735c57733cfd1ebb2171b58b579003c53790439b
# Generated by Django 2.1 on 2019-10-04 16:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('projects', '0006_projectpage'), ] operations = [ migrations.AddField( model_name='project', name='background_image', ...
988,705
c6a2279c00d1de390e032167070b401412ab1c45
from django.urls import path, include from . import views urlpatterns = [ path('incidencias/', include([ path('', views.events, name='evento_list'), path('<int:unidad_id>/', views.events, name='unidad-evento_list'), path('<int:unidad_id>/<int:trab_id>/', views.events, name='trab-evento_lis...
988,706
8a359413af62b277252f38a1a743244f6a31a081
from disyo.models import DSApplication from rest_framework import serializers class DSApplicationSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = DSApplication fields = ( 'name', 'crunchbaseURI', 'githubContributorsCount', 'githubLatestCommitDate', '...
988,707
ed5ea1acd9524690ab62ebaee66f594cbaa7c997
"""My_Shop URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-ba...
988,708
a46da7da804c6c42115b767c83166fae285036a0
sample = """Comet can fly 14 km/s for 10 seconds, but then must rest for 127 seconds. Dancer can fly 16 km/s for 11 seconds, but then must rest for 162 seconds. """.splitlines() def parsedeers(sample): deers = [] for line in sample: deer = line.strip().split() name = deer[0] speed = int(deer[3]) duration = i...
988,709
a8835262c1ae7567d50f1b12f0343accde1b2848
import unittest import experiment class TestExperiment(unittest.TestCase): def test_params_line_enable_batching(self): e = experiment.Experiment( max_batch_size=100, enable_batching=True, tensorflow_intra_op_parallelism=100, some_bullshit=500) self.assertTrue(e.enable_bat...
988,710
8a2a778c7de6d59b79401f03a0bd977c30256f1a
#autor: Jonatan Montenegro #Email: mrmontenegro@gmail.com #No estoy seguro del correcto funcionamiento de este ejercicio. no logre verificarlo, aguardo comentarios sobre alguna falla. import csv import sys def costo_camion(nombre_archivo): with open (nombre_archivo, 'rt') as f: headers=next(f) ...
988,711
5b584b6b209d55218064c86bbe4eafa8ac1a373b
# https://atcoder.jp/contests/abc181/tasks/abc181_c # import sys # # def input(): return sys.stdin.readline().rstrip() # # input = sys.stdin.readline # input = sys.stdin.buffer.readline # from numba import njit # from functools import lru_cache # sys.setrecursionlimit(10 ** 7) # @njit('(i8,i8[::1],i4[::1])', ...
988,712
0dff1aa299f2bc07c4f91b3708fd333f06899179
# Ex04a.py from ch.aplu.jgamegrid import GameGrid, Actor, Location from ch.aplu.util import X11Color import random # --------------------- class Hamster --------------------- class Hamster(Actor): def __init__(self): Actor.__init__(self, "sprites/hamster.gif"); def act(self): hazelnut = gg.getOne...
988,713
add09f4db13d8be882cec07d63e974d70e3cd980
# nlinvns # % Written and invented # % by Martin Uecker <muecker@gwdg.de> in 2008-09-22 # % # % Modifications by Tilman Sumpf 2012 <tsumpf@gwdg.de>: # % - removed fftshift during reconstruction (ns = "no shift") # % - added switch to return coil profiles # % - added switch to force the image estimate to be real ...
988,714
f8889d1a6417a7323e8195f91ffa958c52fc031f
######################################### # # # Created By: Nicholas Evans # # Project Start Date: May 19th, 2020 # # Backend Version 1.1.2 # # # ######################################### from flask import Flask f...
988,715
67205c4ffb96c65f94f6020c9479c226013de393
import math def counter(f): def inner_function(i,j): inner_function.counter += 1 return f(i,j) inner_function.counter = 0 return inner_function @counter def pyt(a,b): a = a b = b c = math.sqrt((a**2)+(b**2)) return c a = [3,4,5] b = [4,5,6] for a,b in zip(a,b): print pyt(a,b) print pyt.counter
988,716
a9ca21c9dcd3538a0cbf93b9358486ccd4f0df1f
import sys import random import math import operator from simulator import Marker class Policy(object): def __init__(self, color): super(Policy, self).__init__() self.color = color class RandomPolicy(Policy): def action(self, board): return random.choice(board.legal_actions) ...
988,717
683da31df6c21e0d3bef6be569412dd095aa3d93
from sqlalchemy import Column, Integer, String from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() metadata = Base.metadata class Customer(Base): __tablename__ = 'Customer' ID = Column(Integer, primary_key=True) Name = Column(String(255)) Address = Column(String(255)) ...
988,718
cc415e3cab17e500f645b4bd056ef519eb5aaae4
import sys import os import logging import numpy as np import pandas as pd import healpy as hp import fitsio as ft sys.path.insert(0, '/users/PHS0336/medirz90/github/LSSutils') from lssutils.stats.cl import get_cl sys.path.insert(0, '/users/PHS0336/medirz90/github/regressis') from regressis import PhotometricDataFram...
988,719
2fe7da8446088ed322c84d15c712caac19f360d1
#!/usr/bin/env python # This module adapted from: # https://gist.github.com/1108174.git import os import platform import shlex import struct import subprocess OS_NAME = platform.system() if OS_NAME == "Windows": import ctypes else: try: import fcntl except ImportError as e: fcntl = None ...
988,720
5816118e2189107946c289c2c36f95eb29b51e7b
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Mon Jan 16 11:33:50 2017 @author: stanleygan Project: Illuminating the diversity of pathogenic bacteria Borrelia Burgdorferi in tick samples """ from __future__ import division from collections import defaultdict, Counter from scipy.misc import comb from ...
988,721
de49820749cdbe62fd62084a6d1bca95ebe41461
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode: def bfs(node, low, high): ...
988,722
a9deddd9c156e494bc3fe1685dae76e50e69324f
from __future__ import print_function import numpy as np import extract def swave(h,name="SWAVE.OUT",rep=1): """Write the swave pairing of a Hamiltonian""" f1 = open("AMPLITUDE_"+name,"w") f2 = open("PHASE_"+name,"w") f3 = open(name,"w") if not h.has_spin: raise if not h.has_eh: raise ds = extract.swave...
988,723
e9719c49f82099bdd49f0ac274d7d540b85204d1
from tkinter import * from tkinter import messagebox def clickImage(event): messagebox.showinfo("마우스","사막에 마우스가 클릭됨") window = Tk() window.geometry("400x400") photo=PhotoImage(file="gif/1.gif") label1=Label(window,image=photo) label1.bind("<Button>",clickImage) label1.pack(expand=1,anchor=CENTER) window.mainl...
988,724
ff4c16822ced15ed90cf67983175a5ae6ee9b488
import datetime from flask import ( request, jsonify, Blueprint ) from flask_request_validator import( Param, PATH, GET, JSON, validate_params ) from decorator import login_required from connection import get_connection from internal_code_sheets import int...
988,725
d81a0dad717b2964134b46660ab7810dca1e000f
# 匿名函数 lambda 函数表达式 (语法糖) # lambda函数表达式用来创建一些简单的函数,是函数创建的又一种方式 # 语法:lambda 参数列表 : 返回值 # 匿名函数一般都是作为参数使用,其他地方一般不会使用 print((lambda a, b: a + b)(10, 20)) func = lambda a, b: a + b # 也可以将匿名函数赋值给一个变量,一般不会这么用 print(func(10, 20)) # ============================================ 匿名函数的应用 =================================...
988,726
bf7191c30e171e13681f895b4173ab1976d2cc13
s = input() s_1 = int(s[0:2]) s_2 = int(s[2:4]) if (s_1>12 or s_1<1) and (s_2>12 or s_2<1): print('NA') elif s_1<=12 and s_1>=1 and s_2<=12 and s_2>=1: print('AMBIGUOUS') elif s_1<=12 and s_1>=1: print('MMYY') else: print('YYMM')
988,727
b4ba63fab216ff011099ccad28271bad75fe2fb8
#! /usr/bin/env python # # This file is part of khmer, http://github.com/ged-lab/khmer/, and is # Copyright (C) Michigan State University, 2009-2013. It is licensed under # the three-clause BSD license; see doc/LICENSE.txt. Contact: ctb@msu.edu # import sys import math from screed.fasta import fasta_iter import khmer ...
988,728
8e5a69b47dc1fd2b2a5ba2f10f17cde35e607dcf
# -*- coding: utf-8 -*- # MNIST Images Extractor # Python code for extracting MNIST dataset images. # MNIST Dataset: # http://yann.lecun.com/exdb/mnist/ # Repository: # https://github.com/amir-saniyan/MNISTImagesExtractor import os import numpy as np from tensorflow.examples.tutorials.mnist import input_data import...
988,729
b96ae0c1a66773671c40f838cc9e99a03b35a9c9
""" CorporateActions:1.2.2 """ """---------------------------------------------------------------------------- MODULE FCAExecute - Module which executes the Corp Actions listed in the CorpAction table. (c) Copyright 2003 by Front Capital Systems AB. All rights reserved. DESCRIPTION This module execu...
988,730
bc336af7a7c9ce69ca81c5cfc7fa4df35334b713
import gzip import math import matplotlib.pyplot as plt from tqdm import tqdm def parse(x): new_x = [] for k in tqdm(x): new_x.append(k["helpful"][0]/(1.0*k["helpful"][1])) print len(new_x) return new_x def show_histogram(x, xlabel, ylabel, title = ""): plt.hist(x, bins = 30) plt.ylabel(ylabel) plt.xlabel(...
988,731
0b28811a5e0e9eff8d9d80e1ac4aaa0add27dbb0
import numpy as np import heapq from Model.Ant import Ant from Model.Sensor import Sensor def get_neighbors(c): return [(c[0] - 1, c[1]), (c[0] + 1, c[1]), (c[0], c[1] - 1), (c[0], c[1] + 1)] # calculate our H metric def heuristic_distance(a, b): return np.sqrt((b[0] - a[0]) ** 2 + (b[1] - a[1]) ** 2) d...
988,732
d4d3401d0afd28a828d2a869c442f01abf7f458c
from random_walk import * import time def main_serial(N, a, v, delta_t, t_simulasi, z_pusat, x_pusat, r): start = time.time() arr_r = bangkitkan_random() arr_particle = inisialisasi_partikel(N, a, v, arr_r) step = t_simulasi / delta_t lingkaran = Hole(x_pusat, z_pusat, r) # ada di dinding y=a, t...
988,733
bc062cfc4b883a4c39ab14a84ebdb4cf54768c49
print("Простий калькулятор") a = float(input("Введіть перше число: ")) b = float(input("Введіть друге число: ")) operation = input("ВВедіть необхідну операцію:") result = None if operation == "+": result = a + b elif operation == "-": result = a - b elif operation == "*": result = a * b elif operation == "/...
988,734
0272ffd4bb7e52e8b52e28388179a8eaf80e23ca
# Copyright 2021 Garena Online Private Limited # # 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 agr...
988,735
152cdd2f649d3594f6b2403ddfc8124655c5e592
import os import shutil def main(): try: path = 'C:\\Users\\ankan\\Desktop\\Datasets_Healthy_Older_People\\S1_dataset' files = os.listdir(path) path1 = 'C:\\Users\\ankan\\Desktop\\Datasets_Healthy_Older_People\\S2_dataset' files1 = os.listdir(path1) for index,...
988,736
322308ef3083a2d794d02a39fb6ba5b093afb248
from setuptools import setup import sys import aws_with install_requires = [ "boto3 >= 1.4.6", "pyyaml", ] if sys.version_info[:2] < (2, 7): install_requires += [ "argparse", ] setup( name=aws_with.__title__, version=aws_with.__version__, description=aws_with.__summary__, long...
988,737
82e9839f910d23791bb0c19470e02c0be2de39dd
import os import zipfile import tensorflow as tf from tensorflow import keras import tensorflow_addons as tfa from tensorflow.keras import layers import pprint import numpy as np print(tf.__version__) gdrive_data_directory = "/content/drive/My Drive/Data" data_tmp_directory = gdrive_data_directory data_tmp_training ...
988,738
ebc91fa75c4baa467a0842acc56c35195dfdebc6
#test import scrapy class DmozSpider(scrapy.spiders.Spider): name = "dmoz"
988,739
a1025224fff76aee836ecf09e5384f9e919891e0
from django.contrib.auth.hashers import make_password from django.contrib.auth.models import User from rest_framework import serializers def verification_password(value: str) -> str: """Check password""" if len(value) >= 8: if any((c in set('QAZWSXEDCRFVTGBYHNUJMIKOLP')) for c in value): ...
988,740
4955d98a1da3163fda2bbe65aa99e895fb45f702
from __future__ import print_function import sys def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) nCase = int(raw_input()) eprint("There are %d cases" % nCase) for caseI in range(1, nCase + 1): n, k = [int(s) for s in raw_input().split(" ") ] eprint("Input : n: {}, k: {}".format(n, k)...
988,741
e8834bf404c48ed7f9278fd9a9346ffe5e76f386
import numpy as np import matplotlib.pylab as plt unif = np.random.random(1000)*20 -10 fig0 = plt.figure(figsize=(8,4)) ax = fig0.add_subplot(111) ax.hist(unif, bins = 100) ax.set_xlabel('Números aleatorios') ax.set_ylabel('Repeticiones') ax.set_title('Distribución Uniforme de Números Aleatorios') plt.savefig('unifo...
988,742
f0c60fedf1bf8f79a98ae6b42962e4cc7f88ff52
""" Views fro dutch postalcodes """ from __future__ import absolute_import import json from django.http import HttpResponse from planner.nlpostalcode.models import Street def get_streets(fourpp, chars): return Street.objects.filter(postcode__fourpp=fourpp).filter(chars=chars).all() def get_info_on_postalcode(_, p...
988,743
cdf93628aa5432539fdb991a039b25a8cfa0e618
from dataclasses import dataclass import os import traceback from utils.ncbi_database import NCBIDatabase from utils.gene_util import get_opposite_dna from utils.str_util import StrConverter @dataclass class GeneExtract: data_path: str rna_path: str output_directory: str gene_extract_based: str = 'ge...
988,744
d71e9b38b8964336d750bcbc4071487a434db335
__author__ = 'nsonepa'
988,745
35b7f749766a2363b6cd815b1b2ec39c221c8be3
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2017-07-31 04:53 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Oneplus...
988,746
00dfcd11008f038c65499662362ceaead3cdf417
#Create a string and print its length using the len() function word = "Harrison" print(len(word)) #Create two strings, concatenate them (add them next to each other) and print #the combination of the two strings word1 = "Ha" word2 = "rry" word3 = word1 + word2 print(word3) #Create two string variables, then print one o...
988,747
11a1e06ddfb456bc086cf60e8faf6f64ae22ad26
import datetime import enum import os from itertools import chain from django.views.generic import TemplateView from django.shortcuts import render from django.db.models import Q from django.http import JsonResponse from django.http.response import HttpResponseBadRequest from rest_framework import status, generics fro...
988,748
30922b06ccf05d0831c3c4c89e2fc626312e2e59
"""Trivial example: minimize x**2 from any start value""" import lbfgs import sys from scipy.optimize import minimize, rosen, rosen_der import numpy as np x0 = np.array([1.3, 0.7]) def f(x, g): g[:] = rosen_der(x) print "one call" return rosen(x) def progress(x, g, f_x, xnorm, gnorm, step, k, ls): ...
988,749
eb0e24ce149891cbc81d4e3ea374fe1c99823312
import json import hmac import hashlib import requests def main(): with open("notifications.json", "rb") as fd: byt = fd.read() sig = hmac.new(b"1234", msg=byt, digestmod=hashlib.sha256).hexdigest() requests.post("http://localhost:5000/webhooks/", data=byt, headers={"X-Sqreen-I...
988,750
70da3e252e456f219e9bd4a0a5df5f88cb083378
import datetime from nt import replace from xml.etree.ElementTree import tostring import psycopg2 from flask import Flask, json, request from flask_restful import Resource, reqparse from sqlalchemy.dialects.postgresql import json from sqlalchemy.dialects.postgresql.dml import insert from storyboard_root.models.writer_m...
988,751
0e14d529ebe7c0479c307fcc87ae6b26ae0e3b5e
from django.conf.urls import url from . import api urlpatterns = [ url("convert/url/$", api.ConverterUrlAPI.as_view()), url("convert/file/$", api.ConverterFileAPI.as_view()), ]
988,752
1d04b5cb9c95891a499fb88d96de0012a1dd698b
# coding:utf-8 __author__ = '123woscc' __date__='2017/7/19' import os from multiprocessing.dummy import Pool import requests from bs4 import BeautifulSoup session = requests.session() domain_url = 'https://www.pixiv.net' headers = { 'Referer': 'https://www.pixiv.net/', 'User-Agent': 'Mozilla/5.0 (Win...
988,753
8fc95719ecaebb63f472eb327de1fecbf67f9c36
# -*- coding: utf8 -*- import dateparser from datetime import datetime from scrapy.http import Request from alascrapy.spiders.base_spiders.ala_spider import AlaSpider import alascrapy.lib.dao.incremental_scraping as incremental_utils from alascrapy.items import ProductItem, ReviewItem class Mobiltelefon_ruSpider(Al...
988,754
ff480f75d9b23bf4fe93810ba357f74b941bd435
# Generated by Django 3.0.7 on 2020-06-25 05:06 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('app', '0003_auto_20200622_0609'), ] operations = [ migrations.DeleteModel( name='Apply', ), ]
988,755
f06bfb4327fe1798bb7ee5f653c4985093aaf022
from django.contrib.auth.models import User from rest_framework import serializers from .models import Post class UserSerializer(serializers.ModelSerializer): posts = serializers.PrimaryKeyRelatedField(many=True, queryset=Post.objects.all()) class Meta: model = User fields = ('id', 'username'...
988,756
b1169ea1ad81d81ac5c4d89d31ee979d044761e5
from nets import alexnet_224 from nets import alexnet_cifar nets_map = { 'alexnet_224' : alexnet_224, 'alexnet_cifar' : alexnet_cifar, } def get_network(name): if name not in nets_map: raise ValueError('Name of net unkonw %s' % name) return nets_map[name]
988,757
fd31c4db53b972b9d9a84db2cc34c104361d1edd
#! /usr/bin/env python """ A helper executable for xgui; creates one GUI display window """ import sys from gui import gui if __name__ == "__main__": gui.display(sys.argv[1])
988,758
b245a429c86d223ab7b785ffa798e9a3071090b2
número = 0 contador = 0 soma = 0 while True: número=int(input('Digite um número:')) if número == 999: break contador = contador + 1 soma = soma + número print('Na lista existem {} números e a soma entre eles vale {}.'.format(contador,soma)) print('Fim! Até breve!')
988,759
7db7182cf93a0c5b96d702c2c60a8c84d9b32d5b
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Functional tests using WebTest.""" import datetime as dt from rest_framework import status as http_status import logging import unittest import markupsafe import mock import pytest from nose.tools import * # noqa: F403 import re from django.utils import timezone from...
988,760
f30d2d1c1cb18368a54ef6aa6920f0f6004c48ea
import os from setuptools import setup, find_packages NAME='mito_sims_py3' ROOT = os.path.abspath(os.path.dirname(__file__)) DESCRIPTION = "A tool for simulating apoptosis dynamics." try: with open(os.path.join(ROOT, 'README.md'), encoding='utf-8') as fid: LONG_DESCRIPT = fid.read() except FileNotFoundEr...
988,761
c7941d1cc5228302661356d9c7bc30754e60df3e
from pymysql import * # 创建数据库连接 conn = Connect(host='localhost', user='root', port=3306, password='itcast', db='mytestdb') print(conn) # 打开游标 cue = conn.cursor() # 执行sql语句 name = input('输入用户名:') passwd = input('输入密码:') sql = "select * from student_ where name='%s' and passwd='%s'" % (name, passwd) print(sql...
988,762
d9789bb2590d6938e0f6925c910be78d529dea3c
from prime import get_larger_prime from polynomials import get_random_coefs, produce_shares, interpolate """ Produces the shares in a t-out-of-n shamir sharing scheme of a message Parameters: message: The message to be encoded and shared. Must be an integer. t: The threshold of reconstruction n: ...
988,763
d3c4b6f3ccaf526884b4aa86cc8d3f798f89a90f
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # author: Maxime Raynal <maxime.raynal@protonmail.com> # LICENSE: MIT import sys from sudoku_solver import ( solution_from_dimacs_string, dimacs_string_from_constraints, constraints_from_grid, grid_from_file ) def main(args): if len(args) < 2: print(...
988,764
c036dc3e4fd6e4cd0e420c70fbb49c10adabf479
# -*- coding: cp1251 -*- import os logfile = open(ur'rezult-foto.txt', 'a') # Список файлов всех log = list(open(ur'foto-site.txt')) linkimg = [] for i in log: if i.count('src') == True: linkimg.append(i) else: pass for i in linkimg: logfile.write(i + '\n') logfile.close()
988,765
4bdddd94c8fb7b2d6fd2481b829a455f5e5e4ed6
"""Lambda entrypoint to handle API requests""" import json import os from generate_presigned_url import create_presigned_url_put, create_presigned_url_get, get_s3_image_list, create_multiple_presigned_urls from errors import BucketObjectError, ResourceNotFoundError ALLOWED_HEADERS = 'Content-Type' ALLOWED_ORIGINS = ...
988,766
9bdd673c28aee00f0c8755e684356c944cbfd24b
#!/usr/local/python3 import smtplib from smtplib import SMTP HOST="smtp.163.com" #定义smtp主机 SUBJECT="test email form python" #定义邮件主题 TO = "younglovesara@gmail.com" #定义邮件收件人 FROM="eryoung2@163.com" #定义邮件发件人 text="python is test smtp" #邮件内容,编码为ASCII范围内的字符或字节字符串,所以不能写中文 BODY = '\r\n'.join(( #组合sendmail方法的邮件主体内...
988,767
710af51315eb73a976d1b1489d59c41dc7123691
import numpy as np from usefulFuncs import predict, accuracy class Optimizer(object): def __init__(self, update_method = 'sgd'): #if we use momentum update, we need to store velocities value self.step_cache = {} def l_bfgs(self, X,y ): pass def train(self, X, y, X_val, y_val, ...
988,768
0e53cfc9db3eeb16dd8b39b69982035cc271eaa1
from random import randint success=0 attempts=10000 for ir in range (attempts): if randint(0,1)+randint(0,1)+randint(0,1)+randint(0,1)==3: success+=1 print("Number of attempts", attempts) print("Number of success",success)
988,769
88a809388fb1ef5e54b7b13074e16370eb7224d1
import doctest import importlib import unittest from shared import utils YEARS = [ 2020, ] def day_tests(tests): day = 0 for year in YEARS: while True: day += 1 try: mod = importlib.import_module('aoc%s.day%s' % (year, day)) tests.addTests(do...
988,770
0052ccd6e0505a9568f4ea92947c21635d9c367b
from selenium import
988,771
037d7f1bad5896ae1fa1d2495dfc336650a25846
# Created by Qingzhi Ma at 2019-07-24 # All right reserved # Department of Computer Science # the University of Warwick # Q.Ma.2@warwick.ac.uk import pandas as pd def convert_df_to_yx(df, x, y): return df[y].values, df[x].values.reshape(-1, 1) def get_group_count_from_df(df, group_attr, convert_to_str=True): ...
988,772
d313737e373e0f832bee1a3080ad5d93e0360f4c
# -*- coding:utf-8 -*- import numpy as np #State(Memory、Utilization、Reference Time) #Action (mp、dp、batch_size) # 为了简化运算,定义以下规则,此规则映射了每个状态可采取的动作: # Memory(M)-> mp # Utilization(U)-> dp # Reference_time(T)-> batch_size # 状态转移流程为 M->U->R # reward,col represent action,row represent state """ Action: mps = [1, 2, 4, 8...
988,773
153b3572fa2abed147495b94459434445fee3da8
from . import biote_allow_wiz from . import biote_unqualified_done_wiz
988,774
31027d43c726ba6caf538557e8291759a1c435f5
palavra = input('Digite uma palavra:') arvalap = '' counter = 0 counter1 = 1 funny_or_not = 0 limite = len(palavra) for i in range(limite-1,-1, -1): arvalap += palavra[i] while counter1 < limite: if ord(palavra[counter]) - ord(palavra[counter1]) == ord(arvalap[counter1]) - ord(arvalap[counter...
988,775
400aa8eda9b39636eddaf5a15f76c52c1eb8c93c
from operator import mul from functools import reduce def cmb(n, r): r = min(n - r, r) if r == 0: return 1 over = reduce(mul, range(n, n - r, -1)) under = reduce(mul, range(1, r + 1)) return over // under N, A, B, *v = map(int, open(0).read().split()) v.sort(reverse=True) answer = sum(v...
988,776
5ce603de5c2de1b83d415bdea948d18967f01a28
import os from flask import Flask VERSION = '1.3' app = Flask(__name__) @app.get('/') def hello(): return f'hi! version: {VERSION}' if __name__ == '__main__': port = int(os.environ.get("PORT")) app.run(host='0.0.0.0', port=port)
988,777
2443b0e15ffbbd7ea09e828bd9b40bde0bbcf16a
from tflearn.data_utils import build_hdf5_image_dataset import h5py path = '/home/suger/workspace/pig-face-recognition/raw_data/txt/' # filenum = 1 # filename = 'train_data' # files = [] # result = [] # for i in range(0, filenum): # files.append(path + filename + str(i) + '.txt') # result.append(filename + s...
988,778
0d5d93680b431551f375288e827f15a9d9bcbb53
import knn import svm import mlp import dt import boosting import learning_curve
988,779
78fc1ed8b03169cc41d8cb21f31094c01776c07d
from setuptools import setup setup( name="app", script=['manage'], )
988,780
23036b849e21c3eebe5764f33e31ab870054fa71
# -*- coding: utf-8 -*- """ Created on Wed Jan 15 20:35:15 2020 @author: shubham """ import math C=50 H=30 result=[] list1=[] D=input('Enter the value of d : ') list=[D for D in D.split(",")] list1 = [int(i) for i in list] i=0 for i in list1: S= ((2 * C * i)/H) Q= round(math.sqrt(S)) res...
988,781
1a6d1eab9eeb856b8e7729b6f0c9c1fce4e2b0e1
from __future__ import annotations from dataclasses import dataclass, field from travelport.models.account_code_1 import AccountCode1 __NAMESPACE__ = "http://www.travelport.com/schema/util_v52_0" @dataclass class AirUpsellOfferSearchCriteria: """ Search criteria for AirUpsellOffers. """ class Meta: ...
988,782
ca92a6f3818cabd023d481e4f10fbcfed8d5fb2b
# coding: utf-8 # In[1]: import numpy as np import cv2 import random from matplotlib import pyplot as plt UBIT ='manishre' np.random.seed(sum([ord(c) for c in UBIT])) # In[2]: def epipolarLines(left_image,right_image,lines,src_pts,des_pts): r,c = left_image.shape[:2] for r,pt1,pt2 in zip(lines,src_...
988,783
e8875b894b694ac5a8a255d0e43368c6640230c7
# 系统 ## ==================== import os import subprocess import sys ## ==================== # 定时 ## ==================== import schedule ## ==================== # 网络请求 ## ==================== import requests ## ==================== # 解析 ## ==================== import json import yaml try: from yaml import CLoade...
988,784
56a0f2e186004edd0cda23b7fb563c2e2a905c10
import numpy as np import sys sys.path.insert(0, './breast_segment/breast_segment') from breast_segment import breast_segment from matplotlib import pyplot as plt import PIL import cv2 import warnings from medpy.filter.smoothing import anisotropic_diffusion import math import random import statistics import os DEBUG =...
988,785
74a02a6b872066f70a887f886f4f3379d74e9181
""" Probabilty module """ def generate_cdf(token_dictionary, n_gram): count_tables = generate_count_tables(token_dictionary, n_gram) n_minus_one_count = count_tables[0]; ngram_count_table = count_tables[1]; #print(n_minus_one_count); #print(ngram_count_table); for key in ngram_cou...
988,786
acc0cb85d882f229dd0c0f31e1967c907fb2a4ff
import requests from bs4 import BeautifulSoup from re import sub from time import sleep from decimal import Decimal from Results import Results class USCEfficiency: base_url = 'https://www.urbansportsclub.com/en' login_url = 'https://urbansportsclub.com/en/login' get_headers = {'User-Agent': 'Mozilla/5.0'} d...
988,787
e1aa9fcd162ffe00b1067c6abdd5172f51903fdc
from django.db import models from django.contrib.auth.models import User # Create your models here. class bbs(models.Model): title = models.CharField(max_length=150,unique=True) category_option = ( ('linux','Linux BBS'), ('python','PY BBS')) category = models.CharField(max_length=50,choices=category_option) co...
988,788
bad6d5f365c1cd1bc1d9d2692e6407ea918f5923
def trans(S,L): for s in S: if L[s]=='0': L[s]='1' else: L[s]='0' return L def helper(L,p,times): if '1' not in L or times>10: Re.append(times) return else: for j in range(8): if p==7: return helper(trans([0, 6...
988,789
c5be537e0182985ed9bf428aed2f9a1d409ae1eb
odd = ['a','c','e','g'] column, row = input('please enter a position on the chess board ') row = int(row) if column in odd: if row%2 == 1: print('black') else: print('white') else: if row%2 == 1: print('white') else: print('black')
988,790
3fff8b617802a0a6b44f0155cd5a6d96cd8a2e63
from django.urls import path from . import views from django.contrib.auth import views as auth_views app_name = 'app' urlpatterns = [ path('', views.index, name="index"), path('login/', auth_views.LoginView.as_view(template_name='app/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_vi...
988,791
f62e5eaf7c7449473933bd0f2abd05f319e035e3
from bs4 import BeautifulSoup import requests import spotipy from spotipy.oauth2 import SpotifyOAuth import os # SPOTIFY AUTHENTICATION USING SPOTIPY CLIENT_ID = os.environ['SPOTIPY_CLIENT_ID'] CLIENT_SECRET = os.environ['SPOTIPY_CLIENT_SECRETS'] sp = spotipy.Spotify( auth_manager=SpotifyOAuth( scope="pla...
988,792
f9f8aced4aa81be7be0839ba7da9a334161e287d
import os import json from django.conf import settings from django.http.response import HttpResponse from django.shortcuts import render from rest_framework import viewsets import plotly import plotly.graph_objs as go from stocks.models import Stock from stocks.serializer import StockSerializer class StockViewSet(v...
988,793
8a2cc3371e67c085fafb7c344549918f67269de4
from scipy.spatial.distance import euclidean from sklearn.cluster import KMeans, AgglomerativeClustering from sklearn.metrics import silhouette_score from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler from sklearn.neighbors import kneighbors_graph import numpy as np import matplotlib...
988,794
11a9bc1f37ee7a74620d11069f2c450d1d7ed01b
n = int(input()) for _ in range(n): a, b = map(int, input().split()) if abs(a - b) == 1: if max(a, b) % 2 == 0: print("CHEF") else: print("CHEFINA") elif a > b: print("CHEF") elif b > a: print("CHEFINA") else: if a % 2 == 0: ...
988,795
b21dfd2d72e9ea1f0828543f3cbb8a5bd4711bce
from lab5 import student class PHD_student(student): def __init__(self,name,year,gpa,current_classes,advisor,numberOfResearchPapers): super(PHD_student,self).__init__(name,year,gpa,current_classes) self.advisor = advisor self.numberOfResearchPapers = numberOfResearchPapers def addYear(self): if(self.year < 6...
988,796
08aaf54e30e556517fa68b5252fd0dabd3da58a7
# mypy: allow-untyped-defs import abc import argparse import importlib import json import logging import multiprocessing import os import platform import subprocess import sys import threading import time import traceback import urllib import uuid from collections import defaultdict, OrderedDict from io import IOBase ...
988,797
45dd076e67e7b0aa3e828ae9f09e605be013a1f6
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @FileName: function_return.py @Function: python function return @Author: Zhihe An @Site: https://chegva.com @Time: 2021/7/4 """ """一、函数的定义之多个返回值""" """ 如果需要在调用函数后有多个返回值,可以在定义函数时在函数体内使用return语句返回由多个返回值组成的元组 """ # 把列表中的所有数分成奇数和偶数两类 de...
988,798
1889c46f33f9ecd02dfc6d50f96d51af9d47512a
# the difference between list and tuple : # tuple is constant type # tuple 可以作为函数的参数或者返回值来使用 # 系统处理tuple更快 # tuple 可以作为dict的key list不能做dict的key a = (1, 2, 3) print(type(a)) print(a) b = (1) print(type(b)) b = (1,) print(type(b)) a = 1, 2, 3 print(type(a)) print(a + b) print(a * 3) print(a.count(1)) print(a.index(3)) ...
988,799
8179ffa60cdec3c5b9e825826942fa85544f3074
import socket from app.controller import verify from app.models import Admin from flask import request, render_template, jsonify, session, redirect, url_for @verify def pass_change(): return render_template('pass_change.html') @verify def pass_change_submit(): user = Admin.query.filter(Admin.userid == session['use...