index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
16,100 | 8fc74d5c33cd7a5ee6cd3320ad7e6726fd7c5b71 | from django.urls import path
from .views import(
entry_list_view,
entry_create_view
)
app_name = 'entries'
urlpatterns = [
path('entries/', entry_list_view, name='entry-list'),
path('entries/create/', entry_create_view, name='entry-create')
] |
16,101 | a69426a7b2695d1ea5ff4e9b387ad148b2d28bcc | import numpy as np
from data import *
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset
from transformers import (
InputFeatures,
AdamW,
AutoConfig,
AutoTokenizer,
AutoModelForTokenClassification
)
model_name = '... |
16,102 | 3e2745d156b21819d6fd057676a39aa73383ba31 | # -*- coding: utf-8 -*-
from scrapy_redis.spiders import RedisSpider
from scrapy import FormRequest
from spiderframe.download import you_get_download
class VideoBaseSpider(RedisSpider):
name = 'video_base'
redis_key = 'video_bilibili_link'
# start_urls = ["https://v.qq.com/x/cover/24bvvcald9bq5kz/p0387cjm... |
16,103 | 5565f1e97b00da0f6c9fb0aa750cad4a762da7fc | # -*- coding: utf-8 -*-
"""Untitled16.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1w7qOuuGMSa-n9TVJkPg7PPUjpL2XBTl1
"""
import nltk
nltk.download('punkt')
from nltk.tokenize import sent_tokenize
text = "Hello, you are reading about Token... |
16,104 | 46bad0125c32ae4b8e907819e820ad46e382ff0b | t = input()
s = 0
for _ in xrange(t):
a = input()
if a > 0:
s += a
print s
|
16,105 | c2ddd0beeea4a71e1634dadd563c4fcaf3ee4b3a | def solution(name):
# 1. name 을 ascii 로 변경한 뒤 위 또는 아래로 몇번 움직여야 되는지 확인한다.
# min( ord(char) - ord('A'), ord('Z') - ord(char) + 1 ) # 위로 갈때는 Z 로 가는 1번의 횟수를 더해준다.
#
# 2. 좌우 이동 최소횟수
# A 를 만나면 정방향으로 가는게 이득인지 역방향으로 돌아가는게 이득인지 확인해야함
# A 가 연속해서 나올 수 있으니 A 가 나오면 다음 index 도 A 인지 확인해야함
# 정방향 = len(name... |
16,106 | 777b5d845afa6f30d145ae458a35b783d467eeb9 | from .city_info import dp
__all__ = ["dp"]
|
16,107 | 843295adf31d9f35df953b84a6371e32b943b121 | """
api pages related to events
"""
from . import log, db_conn
from . import utils
from datetime import datetime
#** Variables **#
_event_args = ['title', 'description', 'start_date', 'end_date']
#** Functions **#
def event_create(req):
"""PUT => create a event account or error"""
try:
utils.assert_k... |
16,108 | 309867959391ab7c2dc68bda034b11bb3821c625 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 10 11:36:26 2019
@author: fmna
"""
def fx(cx,x,cy,y,cz,z,cw,w,b):
return (b-(cy*y+cz*z+cw*w))/cx
def fy(cx,x,cy,y,cz,z,cw,w,b):
return (b-(cx*x+cz*z+cw*w))/cy
def fz(cx,x,cy,y,cz,z,cw,w,b):
return (b-(cy*y+cx*x+cw*w))/cz
def fw(cx,x,cy,y,cz... |
16,109 | 5bde2838ac2fb84017da842b35073183e8195376 | s=input()
a,b,c,d=map(int,input().split())
if(a!=0):
print(s[:a]+'"'+s[a:b]+'"'+s[b:c]+'"'+s[c:d]+'"'+s[d:])
else:
print('"'+s[:b]+'"'+s[b:c]+'"'+s[c:d]+'"'+s[d:]) |
16,110 | 92dd1185619ed6366271ecc9b4b5791d6f91c34b | import collections
def fillCommand(command):
return "|"+command+"|"
class Commands(object):
join = "|J|"
leave = "|L|"
chat = "|C|"
nick = "|N|"
setPos = "|P|"
setFrame = "|F|"
setAnim = "|A|"
setSpells = "|S|"
class HXeption(Exception):
def __init__(self, value):
self... |
16,111 | ef446cb7c01d4c54e4f475789259f3e1093b54fd | import numpy as np
from netCDF4 import Dataset
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import sys
import os
def filt1(X, yvals, xvals, ny, nx):
""" Spatially filters the first two dimensions of array X into windows of size nx*ny. I.E. nx+1 and ny+1 are the number of grid points containe... |
16,112 | a43a5679f1999e87f02bf98c3ac6b89ab7447601 | #!/usr/bin/env python3
import sys, utils, random # import the modules we will need
utils.check_version((3,7)) # make sure we are running at least Python 3.7
utils.clear() # clear the screen
print('Greetings!') # prints out "Greetings!" in the terminal.
colors = ['red','orang... |
16,113 | 73345fc83a8b3a2362559b4c0da3de7ee28a5b3c | from typing import List
class Solution:
def furthestBuilding(self, heights: List[int], bricks: int, ladders: int) -> int:
size = len(heights)
def go(now, brick, ladder):
# 尽可能地向前走
while now < size - 1 and heights[now] >= heights[now + 1]:
now += 1
... |
16,114 | 0ac3b42e8b044c4a091531ad94306de4e3a3ed99 | import numpy as np
import time
import pygame
from pygame.color import THECOLORS
from constants import *
import globals
from geometry import *
# ___ _ _
# | _ \___ _ _ __| |___ _ _(_)_ _ __ _
# | / -_) ' \/ _` / -_) '_| | ' \/ _` |
# |_|_\___|_||_\__,_\___|_| |_|_||_\__, |
# ... |
16,115 | d91ef47e5cb23abcc1ca40894d05fcb0aaaeba9d | from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.models import PermissionsMixin
from django.db import models
class UserManager(BaseUserManager):
def _create_user(
self, email, password, is_superuser=False, **extra_fields
):
email = self.norma... |
16,116 | 14d766c6de3decd0ebc48156845cb9db1d0533eb | # Code generated by `stubgen`. DO NOT EDIT.
from kubernetes.client.configuration import Configuration as Configuration
from typing import Any
class V1NodeSpec:
openapi_types: Any
attribute_map: Any
local_vars_configuration: Any
discriminator: Any
def __init__(self, config_source: Any | None = ..., ... |
16,117 | fc4f0c049f84070bec6be84a0870cb1f5134935d | # -*- coding:utf-8 -*-
'''
Created on 2017.7.7
@author: Administrator
'''
from framework.get_testsuite import TestSuites
from framework.excelparser import ExcelParser
from framework.get_teststeps import TestSteps
class KeyCases(object):
#最终执行关键字驱动列表,模板[(u'type', u'id=>kw'), (u'search', u"xpath=>//*[@id='... |
16,118 | d9460b40d7d2a6b8ffdc9a188e2914b454dfb76c | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 8 08:33:54 2016
@author: hedi
"""
import numpy as np
import sys
from time import time
import os
from sim_model import m_sim_mean
import theano
from itertools import product
import json
from joblib import Parallel, delayed
fwrite = sys.stdout.write
dtype = theano.config... |
16,119 | b457242f77b487f6d9eaeb8ea1d4d00b2f2caecc | import pandas as pd
import sys
sys.path.insert(1, sys.path[0] + '/../../../library')
import loglib
f1, f2, clumped, g1k, out = sys.argv[1:]
logger = loglib.get_logger(out)
logger.info(f"reading {f1}")
df1 = pd.read_csv(f1, sep='\s+')
logger.info(f"{len(df1)} snps read\n")
df_clumped = pd.read_csv(clumped, sep='\s+')
... |
16,120 | 9fbc9496c49a9a5105b42094f3bf4a21cb1f3cfa | import pandas as pd
from itertools import combinations
import requests
import json
from math import trunc
from datetime import datetime, timedelta
import re
from collections import Counter
from itertools import chain
from DatabaseAccess.Connector import Connector
import DatabaseAccess.sql_requests as sql
import bdd_ma... |
16,121 | a59d28c4c2337ab162839bfea6f03c4d28455259 | def fact(n):
if n==1:
return 1;
else:
return n*fact(n-1);
#ans=fact(5);
#print(ans)
def factorialList(a,b):
global l
l={};
for each in range(a,b):
l.setdefault(each,fact(each));
return l;
ans=factorialList(5,8)
print(ans)
print(ans[6]);
|
16,122 | 283c0034b92f0d7e0dd3d3e588d503253c820ab5 | def pandigital(n):
pan = False
if len(set(str(n))) == len(str(n)):
if int(max(list(str(n)))) == 9 and int(min(list(str(n)))) == 1:
pan = True
return pan
m = 0
for num in range(9, 10000):
s = ''
c = 1
while True:
s+=str(num*c)
c+=1
if len(s) >= 9:
... |
16,123 | 7d1e54a15e7bc5dfa5694aff647273a096d943ec | from urllib import parse
import requests
def get_fragments(reference):
""""
Returns fragments for a given reference. Uses the resolver service. See the API docs for the resolver service at:
https://alpha.nationalarchives.gov.uk/idresolver/apidocs/
The commit history for this file also has a version ... |
16,124 | 16d749522b785f1295eae22a0326061251af7aa1 | def unpack(tupple_list):
new_lst=[]
print("LIST OF TUPPLES")
print("----------------")
print(tupple_list)
print("-------------------------------------")
for tpple in tupple_list:
for ele in tpple:
new_lst.append(ele)
print("TUPPPLE IN LIST------------>... |
16,125 | 720e1e6b1ac65164220b4e5c1022789ebad5a245 | #mark counting with condition ( +=, *=, -=, /=) / 按照情況予分
bill = 0
size = input("plz choose a size,S,M,L").lower()
if size == 's':
bill += 15
elif size == 'm':
bill += 20
else:
bill += 25
print(bill)
|
16,126 | e8b0ea4899c6ef31b501952fe88f84f7a5934417 | """
Adapt some Python types to the core protocol.
"""
from core import call, primitive_vtables
def install():
primitive_vtables[type(None)] = {}
primitive_vtables[bool] = bool_vtable
for t in num_types: primitive_vtables[t] = num_vtable
for t in str_types: primitive_vtables[t] = str_vtable
primiti... |
16,127 | 9f872ff40bab805255e952694bf59a569b01aef7 | '''
This program should be able to define the search problem with clearly labeled components that point to the state, actions, transition function and goal test.
Define a problem in terms of state, actions, transition function, and goal test
TileProblem labels the components (variables, methods) that point to these e... |
16,128 | 28c5af28fdf75eede7a094a1780f2786a3c1f3cb | # Print the name of the module that's running
print(f"Running: {__name__}")
def pprint_dict(header, d):
print('\n--------------------------------------')
print(f'***** pprint_dict of {header} *****')
for k, v in d.items():
print("\t", k, v)
print('--------------------------------------\n')
# ... |
16,129 | 9d88563f4b9a9a17413fad19672ed151b19d4e17 | from pyecharts.charts import ThemeRiver
import pyecharts.options as opts
import pandas as pd
# 导入数据
data = pd.read_csv('E:\python\sale_amount.csv',index_col='date')
series = data.columns.values
data_list = []
for se in series:
for x,y in zip(data[se].index,data[se].values):
data_list.append([x,int(y),se])
... |
16,130 | bed7e853f5af9760e9a7ae435814779fb7006ec3 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Test model in other period than modcel uses
"""
import numpy as np
from prints import print_realtest_results
from user import backtesting_details
from matrix_manip import calc_min_variance_portfolio, calc_portfolio_stdev
from plots import plot_points
def realtest(r... |
16,131 | f38803bf6420bacc44ddfb31e86b72b1975f56d2 | import numpy as np
import pytest
import autocti as ac
from autocti import exc
def test__trail_size_to_array_edge():
layout = ac.Layout1D(shape_1d=(5,), region_list=[ac.Region1D(region=(0, 3))])
assert layout.trail_size_to_array_edge == 2
layout = ac.Layout1D(shape_1d=(7,), region_list=[ac.Reg... |
16,132 | 72890d3434795b96c76a1220653323230dd116fb | import argparse
import datetime
import os
from cryptography import x509
from cryptography.hazmat import backends
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
def create_rsa_private_key(key_size=204... |
16,133 | 177eb584d7f14c5c7e481a46f4407bd538badca8 | #!/usr/bin/python3
#-*-coding:UTF-8-*-
#__init__构造函数可以在对象创建后直接调用
class FooBar(object):
def __init__(self,value):
self.name=value
f=FooBar('xls')
print(f.name)
class Foobar(object):
def __init__(self,name):
self.name=name
def foo(self):
return self.name
... |
16,134 | af50ead0821965b6fe085b9f38588415a02461f4 | #!/usr/bin/env -S PATH="${PATH}:/usr/local/bin" python3
import requests
def ping():
requests.get('https://notion-heroku.herokuapp.com/')
|
16,135 | 6704e98a95dcfe554d1b0d203d06d66926134afa | class Pilha:
def __init__ (self):
self.items = []
def isVazio (self):
if (len(self._itens) == 0):
return "Vazio"
def push (self, item):
if item not in self.items:
self._itens.append(item)
def pop(self):
return self.items.pop()
... |
16,136 | f3a5cfd007a4251a26af66d5de6c4f151ba87b59 | """
@Author: Robbe Heirman
@Version: 0.01
@Description:
Main python module for SushiGo!
Contains the GameLoop and event handler.
"""
import os
import sys
from typing import List, Tuple
import pygame
from source.model.deck import Deck
from source.model.player import Player
from source.view.entity_view import EntityVi... |
16,137 | 3eb65e122b35b0cc763c9c0362390b39ef0a5da0 | import unittest
from unittest.mock import call
from gitopscli.git_api import GitProvider, GitRepoApi, GitRepoApiFactory
from gitopscli.commands.create_pr_preview import CreatePrPreviewCommand, CreatePreviewCommand
from .mock_mixin import MockMixin
DUMMY_GIT_HASH = "5f65cfa04c66444fcb756d6d7f39304d1c18b199"
class Cre... |
16,138 | 8fbc3f0142863bcf8ffd81bb112b571657253b96 | #!/usr/bin/python
import sys
from random import randint
sys.stderr.write("Started mapper.\n");
subject = "god"
max_timestamp = 24*7
def main(argv):
for line in sys.stdin:
try:
if line.startswith("@") and line.find(subject)!=-1:
print line.rstrip()+"#######"+str(randint(0,max_t... |
16,139 | 80ab1900db9c0269a0dd2f4a87dead55ef3ba729 | #!/usr/bin/env python
"""
hopefully doesn't mess anything up too badly
Significant inspiration was taken from:
https://github.com/python-poetry/poetry/blob/c967a4a5abc6a0edd29c57eca307894f6e1c4f16/install-poetry.py
Steps:
- Ensure dependencies (git)
- Download repository
- Run dotdrop from the repo... |
16,140 | 727a542bb1e407a1e5b3405a60a764b4e38fab8d | import os
import torch
import numpy as np
import wandb
from ..train import train
from ..evaluate import evaluate
from chemprop.data import MoleculeDataLoader
from chemprop.utils import save_checkpoint
from chemprop.bayes.swag import SWAG
from chemprop.bayes_utils import scheduler_const
from torch.optim.lr_s... |
16,141 | 0492f73c068f883596e4efdcd29ff77b5f3e5a5d | n = int(input())
arr = list(map(int, input().split()))
c = 0
h = set([])
for i in range(n):
for j in range(i+1,n):
for k in range(j+1,n):
t = [arr[i], arr[j],arr[k]]
t.sort()
if t[0] + t[1] > t[2]:
if t[0]!=t[1]!=t[2]:#if (i,j,k) not in h:
h.add((i,j,k))
c+=1
... |
16,142 | b95e80915a30ca78df088fbf928dbf9677bd8793 | import cv2
import time
from imutils.video import VideoStream
import imutils
#fuction that should be run as a thread and that interrupts when motion is detected
def MotionDetectionThread(thresholdBackground, minAreaToBeDetectedBackground,
thresholdMotion, minAreaToBeDetectedMotion,frameUpdateF... |
16,143 | 4352bcf96aa60b4631a75d398f9f59bbb8ce1463 | import os
print "uploading file %s" %_myfile.filename
"""
f = _myfile.file # file-like object
dest_name = os.path.basename(_myfile.filename)
out = open(dest_name,'wb')
import shutil
shutil.copyfileobj(f,out)
out.close()
"""
print ' <a href="mianshi.pih"> Back to Index</a>'
|
16,144 | 21755abec5bd088e6292c2758cc13dfb87fa1235 | from flask import Flask, jsonify
import mysql.connector as mysql
service = Flask (__name__)
IS_ALIVE = "yes"
DEBUG = True
PAGE_LIMIT = 4
MYSQL_SERVER = "database"
MYSQL_USER = "root"
MYSQL_PASS = "admin"
MYSQL_BANCO = "vencendochefes"
def getConnectionDb():
conenection = mysql.connect(
host=MYSQL_SERVER... |
16,145 | 48f3cd4f8e0db496367e9f1d91e8bd72f33e86b2 | import os
import h5py
import keras
from keras.models import Sequential, Model
from keras.layers import Dense, Flatten, Dropout, Input, merge, Activation
from keras.layers.convolutional import Convolution2D, MaxPooling2D, ZeroPadding2D
from keras.layers.recurrent import SimpleRNN, LSTM
from keras.layers.advanced_act... |
16,146 | 72154fb956bee8de6298214e4f9a56d98a0cbffb | # coding=utf-8
"""
功能:
1.个人中心
index、user与detail
2.消息
new
3.订单商品
order、goods与list
"""
from flask import Flask
# 导入蓝图对象
from E10_OrderGoods import api
app = Flask(__name__)
# 第三步:注册蓝图对象到程序实例上
app.register_blueprint(api)
@app.route('/')
def indedx():
return 'index'
@app.route('/user')
def user():
... |
16,147 | 26d355227957f21a3a7bcfb4c0e8321e14ee9956 | from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import numpy as np
from sklearn.metrics import classification_report, confusion_matrix
model = load_model("vgg16_1_acc0.90.h5")
model_loss = load_model("vgg16_1_bestloss.h5")
img_height, img_width = 150,1... |
16,148 | 540aca234b3ac84c561eea9a1098e2a2d3c734be |
words = []
highlow = []
numright = 0
with open("adventofcode/day02.txt") as inpt:
for line in inpt:
words = line.split(" ")
highlow = words[0].split("-")
lowestnumletters = int(highlow[0])
highestnumletters = int(highlow[1])
letters = words[1]
letter = letters[0]
... |
16,149 | be35d8206b48519bd21023667508b2b43256a319 | """
Author : HarperHao
TIME : 2020/12/9
FUNCTION: 表单的基类
"""
from wtforms import Form
class BaseForm(Form):
def get_error(self):
message = self.errors.popitem()[1][0]
return message
|
16,150 | 21d000b35d90d0e2ad789b55cf3108b665cf7e16 | """
1. 이중 for문으로 두개 뽑기
2. 뽑은 결과의 합이 <=200 이므로, 200짜리 배열 만들기
3. 배열에서 >=1 애들만 찾아서 넣기
"""
def solution(numbers) :
exists = [0] * 201
for i in range(len(numbers)) :
for j in range(i+1,len(numbers)) :
exists[numbers[i] + numbers[j]] += 1
answer = []
for i in range(0,201) :
if exi... |
16,151 | d0d6df38c7706361c5bb157a1ce8760c6651e58e | import pandas as pd
from twitter_get_data import query_str
import os
path=os.getcwd()
os.chdir(query_str)
data=pd.read_csv('Final_Results_FB.csv',encoding='ISO-8859-1')
data_pos=0
data_neg=0
data_neu=0
data_happiness=0
data_sad=0
data_worry=0
data_angry=0
data_relief=0
data_surprise=0
data_neutral=0
d... |
16,152 | ef25b654a855e2cafddcfe5719c442c5e637b49d | # -*- coding:utf-8 -*-
'''
https://www.nowcoder.com/practice/9e5e3c2603064829b0a0bbfca10594e9?tpId=117&&tqId=37846&&companyId=665&rp=1&ru=/company/home/code/665&qru=/ta/job-code-high/question-ranking
'''
'''
题目描述
假定你知道某只股票每一天价格的变动。
你最多可以同时持有一只股票。但你可以无限次的交易(买进和卖出均无手续费)。
请设计一个函数,计算你所能获得的最大收益。
示例1
输入
复制
[5,4,3,2,1]
返回值
... |
16,153 | e1f8424e0d08b91a96e8e8fa4e7271d7a13cf0a3 | import FWCore.ParameterSet.Config as cms
maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) )
readFiles = cms.untracked.vstring()
secFiles = cms.untracked.vstring()
source = cms.Source ("PoolSource",fileNames = readFiles, secondaryFileNames = secFiles)
readFiles.extend( [
'/store/mc/RunIISummer16Mi... |
16,154 | 35c1aacb601c8a57d39a11495044078d3908a198 | from django.shortcuts import render, redirect
from seller.models import Product, Category
from ShoppingApp.models import UserProfile
from .models import Cart
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.core.mail import send_mail
# Create your views here.
@l... |
16,155 | af752b3c391a1d0af023c22f211a476fc780e91a | # Usually you would have to create list to store the numbers
# Generators are good for large data
def gencubes(n):
for num in range(n):
yield num**3
for x in gencubes(10):
print(x)
def genfibon(n):
a = 1
b = 1
for i in range(n):
yield a
a, b = b, a + b
for num in genfibo... |
16,156 | b4acd1f20e22c6595661f873946cf5384b773419 | import mutable_attr
import unittest
class T(unittest.TestCase):
def test_foo(self):
mutable_attr.y = 3
|
16,157 | e3ffaff0b7d907b789a1b2583c36ebd76d3cc3f7 | def show_characters_v1(name):
for index in range(len(name)):
print(name[index], end=' ')
else:
print()
def show_characters_v2(name):
end_count = -1 * (len(name) + 1)
for index in range(-1, end_count, -1):
print(name[index], end=' ')
else:
print()
def show_reverse_... |
16,158 | 25cfb7b3b3db9c29a5634826424c7f372c2ff387 | # Generated by Django 2.0.5 on 2018-05-26 18:29
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0009_auto_20180526_1703'),
]
operations = [
migrations.CreateModel(
name='FlightNumber'... |
16,159 | 60bdf45624e27d27b344b3e5a637e27036fcda29 | from django.contrib import admin
from django.urls import path,include
import blog.views
import portfolio.views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('',blog.views.home,name='home'),
path('admin/', admin.site.urls),
path('blog/',include('b... |
16,160 | 0c21194637def469619988ab25ad681fa1d594ac | import serial
import crc16
import sys
# hex(intAddress)[2:].zfill(6).decode('hex')
# more intellegent
def convert(int_value):
encoded = format(int_value, 'x')
length = len(encoded)
encoded = encoded.zfill(length+length%2)
return encoded.decode('hex')
def oneRXTX(intAddress, strCmd):
rq = '\x00'+conver... |
16,161 | fc0f3b4d6cb96a5a6a217b7cb13e28b8fcb85277 | #CODING QUESTIONS:5
a=str(input())
b=set()
for x in a:
if x not in b:
b.add(x)
print(x,end="")
|
16,162 | 701275a903520147b79b559b7121b29824b96599 | #! /usr/bin/env python
import os
import sys
import xml.dom.minidom
import requests
def manifest_analysis(source):
#List of Android dangerous permissions
DangPer = ['android.permission.READ_CALENDAR','android.permission.WRITE_CALENDAR','android.permission.CAMERA','android.permission.READ_CONTACTS','android.per... |
16,163 | 4dd8073d316831ff645a6549703c1497e316d8e2 | from django.shortcuts import render,redirect
from django.contrib.auth.models import User,auth
from django.contrib import messages
# Create your views here.
def login(request):
if request.method == 'POST':
username=request.POST['username']
password=request.POST['password']
user = auth.auth... |
16,164 | 05cc64f0bbfbcc96688feab238e0c3f22ae25998 | import sys
import importlib
importlib.reload(sys) # Reload does the tricsys.setdefaultencoding('UTF8')
sys.path.insert(0, '../../../src/')
from models import Updatelog
sys.path.insert(0, '../')
from database_session import get_nex_session as get_session
from config import CREATED_BY
__author__ = 'sweng66'
file = "d... |
16,165 | f4fbd5fcb3201d748645f61db511bdeb497ad0d3 | class C:
def method(self):
print(r'foobar' f'{self}') |
16,166 | 0d6e36f22098d573a50f34b6fedc70da1be1ecfc | # -*- coding: utf-8 -*-
# Projeto 9 - Processamento de imagens
from __future__ import print_function
import cv2 as cv
import numpy as np
def imprime_imagem(tipo, imagem):
"""Monta a imagem novamente e imprime"""
cv.imshow(tipo, imagem)
cv.waitKey(0)
cv.destroyAllWindows()
def cria_nova_imagem(altura... |
16,167 | 7cc8dfbd0f3491bb6ad26ec32d6d24bf869ba9b9 | class Solution:
def numUniqueEmails(self, emails) -> int:
emails_modified = []
for email in emails:
at_index = email.index('@')
local_name = email[:at_index]
domain_name = email[at_index:]
# ignore everything after first plus sign in local name
... |
16,168 | ae4f8f72366c2bbf09ba0f1d622d638869803aa4 | #!/usr/bin/python
from pathlib import Path
from requests import get as req
from lxml import html
import re
import json
head = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36'}
root = Path(__file__).parent
scale_dump = root / 'scale_data.json'
p... |
16,169 | 8e44203a13dd7f5802e498c27328c54f3d6a833c | """@author: Bryan Silverthorn <bcs@cargo-cult.org>"""
import os.path
import csv
import numpy
import sklearn
import condor
import borg
import borg.experiments.simulate_runs
logger = borg.get_logger(__name__, default_level = "INFO")
def simulate_run(run, maker, all_data, train_mask, test_mask, instances, independent, ... |
16,170 | 830a0d362f7bde79dec14e3f61a723ac3fdf7185 | from django.contrib import admin
from .models import PostUser
# Register your models here.
class PostUserAdmin(admin.ModelAdmin):
readonly_fields = ('date_post', )
admin.site.register(PostUser, PostUserAdmin)
|
16,171 | 72f1610911e18acfa9b8fc49cd9c4473d24c069c | import sys, bz2, re, string
from collections import namedtuple
# # A language model scores sequences, and must account
# # for both beginning and end of each sequence. Example API usage:
# lm = LM(filename, n=6, verbose=False)
# sentence = "This is a test ."
# lm_state = lm.begin() # initial state is always <s>
# logp... |
16,172 | 0bfdc3e63bf8bac60401ef5d3dd86eae22d90e4b | import os
import sys
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
mail_host = "" # SMTP服务器 如:smtp.126.com
mail_user = "" # 用户名
mail_pass = "" # 授权密码,非登录密码
sender = '' # 发件人邮箱(最好写全, 不然会失败)
receivers = [''] ... |
16,173 | 82ace6ca6942104b85e7eb450b05033fff2247e7 | import discord
from discord.ext import commands
class Rules(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def rules(self, ctx):
embed=discord.Embed(
title="Here are the rules of the server",
colour=discord.Colour.blue()
)
... |
16,174 | 2f606f8ec6c537d20d4eedfd459308f64cd71580 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode:
a = []
cur = head
while (cur):
a.app... |
16,175 | 9510be848f075c5e2a81cc3bdb752c6b93caf9d6 | import matplotlib.pyplot as plt
import cv2
import numpy as np
from Kmean_color import Kmeans
def Figure_colors(path,n_clusters):
img = cv2.imread(path)
img_size= cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
X = img.reshape((img_size.shape[0]*img_size.shape[1],3))
plt.xlabel('x')
plt.ylabel('y')
plt.plot(... |
16,176 | b7a9ffbdf7d95f776f8a1a8d9fd184d0ab72cb4f | import sys
n=int(input())
for i in range(0,1000):
if 2**i==n:
print("yes")
sys.exit()
print("no")
|
16,177 | 39382c5793e50b438ed69cd74e72d561980c0644 | """Swap apirs of node in ll"""
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, val):
new_node = ListNode(val)
if not self.head:
self.head = new_node
... |
16,178 | fc628756f7fcced98dc6cb863e34b165724c2d94 | class FactorialDigitSum():
"""
n! means n × (n − 1) × ... × 3 × 2 × 1
For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
and the sum of the digits in the number 10! is
3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
"""
def factorial(self, input):
... |
16,179 | 56e9e35aeb8c5da4f852d2fd5f14bb0ffe5c5955 | #triangle
N = int(input())
a = []
for N in range(1,N+1):
a.append(N)
print(''.join(str(a))) |
16,180 | 19e2427aaf09a0c24ebcd623f755ebbda0be10bb | import puzzle
def checkSudoku(rows):
def isValidSet(s):
s = sorted(s)
for i in range (0, len(s)):
if s[i] != i+1:
return False
return True
for i in range(0, 9):
row = rows[i]
column = []
section = []
for j in range(0, 9):
rowMarker = ((i / 3) * 3) + j ... |
16,181 | d99bda52b761d09eb6616e161f09617ea6ac338e | from django.contrib import admin
from .models import Function, Collaborator, Apartament, Resident
# Register your models here.
admin.site.register(Function)
admin.site.register(Collaborator)
admin.site.register(Apartament)
admin.site.register(Resident) |
16,182 | be2b95cf4d7ad5dfa872c4f17990475939837398 | import kidney_ndds
from kidney_digraph import *
EPS = 0.00001
class KidneyOptimException(Exception):
pass
def check_validity(opt_result, digraph, ndds, max_cycle, max_chain, min_chain = None):
"""Check that the solution is valid.
This method checks that:
- all used edges exist
- no vertex or... |
16,183 | 8fdd11675915db6aaa6f21ed4e9de12907924ce8 | # 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 maxPathSum(self, root: TreeNode) -> int:
#res = [maxPathSum]
def dfs(cur, ... |
16,184 | 6feebb1d4344fdd70908dd8d5a564326c854a460 | import colorgram
import turtle as turtle_module
import random
'''extract color palette from image using colorgram'''
# colors = colorgram.extract('hirst.jpg', 10)
# rgb_colors = []
# for color in colors:
# r = color.rgb.r
# g = color.rgb.g
# b = color.rgb.b
# new_color = (r, g, b)
# rgb_colors.app... |
16,185 | 4d6cb54465f2b0a31accfc0037bf0ca5805d765f | n=int(input("Enter the limit:"))
a=[]
print("Enter the elements")
for i in range(n):
b=int(input())
a.append(b)
def mm():
min=a[0]
max=a[0]
for i in range(len(a)):
if min>a[i]:
min=a[i]
if max<a[i]:
max=a[i]
pr... |
16,186 | 39cc857a11ce44cd3bdfaeeea670fffe00052e67 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render,redirect
from django.contrib.auth.forms import UserCreationForm
from django.views.decorators.http import require_POST
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from ... |
16,187 | d6c4af0f5003f2cb002a55776b4154849dba254a | from decorators import do_twice
@do_twice
def say_whee():
print("Whee!")
say_whee() |
16,188 | 863d0dba5f0aa79b2270f7da35ba75e2bb7a0a2d | # Author: Eric Bezzam
# Date: Feb 1, 2016
"""Class for real-time STFT analysis and processing."""
from __future__ import division
import numpy as np
from .dft import DFT
class STFT(object):
"""
A class STFT processing.
Parameters
-----------
N : int
number of samples per frame
hop :... |
16,189 | 9fc9aecb0d02f2422d4b1e8c0b97c7d53d7db583 | #coding=utf-8
#author=Garfield
def ai_judge(board):
if board[1][1] == 0:
#无论如何优先抢占-1
return (1,1)
#判断每次计算后当前是否存在胜负状况
def if_win(board):
#棋盘共有8条线,每条线可以是O或X两种情况
win = 0
print board
if board[0][0] == board[0][1] and board[0][1] == board [0][2]:
#第一行
if board[0][0] == ... |
16,190 | 2a704dcaa1f07d3df88145da05e6b8072e1a652e | import os
import torch
import shutil
def create_path(path):
if not os.path.exists(path):
os.makedirs(path)
def save_checkpoint(state, is_best, model_path, name):
torch.save(state, '%s/%s_checkpoint.pth.tar' % (model_path, name))
if is_best:
shutil.copyfile('%s/%s_checkpoint.pth.tar' % (mod... |
16,191 | b89acf8c903476c2c7d161e4b6124e893663d31c | import gzip, pickle
import os
from ast import literal_eval
import pandas as pd
import natsort
import csv
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.preprocessing import LabelEncoder
from sklearn.decomposition import PCA
from sklearn import model_selection, naive_bayes, svm
import docx ... |
16,192 | 952220cf8d2db249d2bdf47f8edd0b20d6ad078a | import pygame
from pygame import mixer
screen = pygame.display.set_mode((800, 600))
pygame.init()
class Enemy:
def covid(self):
pass
def alien(self):
pass
class Player:
def __init__(self):
self.x = 370
self.y = 480
def move(self, xChange):
self.x -= xChang... |
16,193 | 9e6ef5fe756b6b175210a038acf834fc7ea80021 | def vowel_filter(function):
def wrapper():
letters = function()
return [l for l in letters if l.lower() in 'aoueiy']
return wrapper
@vowel_filter
def get_letters():
return ["a", "b", "c", "d", "e"]
print(get_letters())
|
16,194 | 4482cc3459b799efd123387a894f03ac9a38541e | import torch
from torch.utils.data import Dataset
from torchvision import datasets as datasets
from Keys import Keys
class VOCDataset(Dataset):
def __init__(self, root, year, image_set, transform=None):
self.dataset = datasets.VOCDetection(root=root, year=year, image_set=image_set, download=True)
... |
16,195 | 71d74d7e960bfa363fc42405301214766affe924 | import errori
class Persona:
def __init__(self, nome, cognome, numeroTelefonico, email):
if nome:
self.__nome = nome
else:
raise errori.ValoreObbligatorio
if cognome:
self.__cognome = cognome
else:
raise errori.ValoreObbliga... |
16,196 | b057986d9a1595c4e8f998e6550d591b4a81b5e0 | from spyne import Application, rpc, ServiceBase, Unicode, Iterable
from spyne.protocol.http import HttpRpc
from spyne.protocol.json import JsonDocument
from spyne.server.wsgi import WsgiApplication
import requests
import simplejson as json
import logging
import numpy
logging.basicConfig(level=logging.DEBUG)
class Fil... |
16,197 | d8bf71b31b37d15c6c4ee870d395a52f28bfab5e | iChange = 1
bRemove = False
bPython = True
bHideInactive = True
Activities = ["AWAKE", "HOLD", "SLEEP", "HEAL", "SENTRY", "INTERCEPT", "MISSION", "PATROL", "PLUNDER"]
iSetValue = 3
iWarValue = 0
iChangeType = 2
iPlotType = 2
iOwnerType = 0
bApplyAll = False
iSelectedPlayer = 0
iSelectedCiv = -1
iSelectedClass = -1 |
16,198 | e804a0af6b554c15fdd13dfc0579ad9bbe7d07a4 | """Submodule implementing baseline and optimal models."""
from .deep_enhancer import deep_enhancers
from .fixed_cnn import fixed_cnn
from .fixed_ffnn import fixed_ffnn
__all__ = [
"deep_enhancers",
"fixed_cnn",
"fixed_ffnn"
]
|
16,199 | ea932fb0e7a5956401f8514d00325147c0966a4c | # Digital Signal Processing by Paolo Prandoni and Martin Vetterli
# Coursera/EPFL
# Nabin Sharma
# Oct 09, 2013
import pylab
import scipy.io.wavfile
import time
def ks_loop(x, alpha=1, D=1):
# If x is 1d array, convert to list.
if (not isinstance(x, list)):
x = x.tolist()
# Length of the output... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.