index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
9,900 | 58efaad41d02bb5dffbf71c478c7fad12af68e5b | # 自定义购物车项类
class CartItem():
def __init__(self, book, amount):
self.book = book
self.amount = int(amount)
# 自定义购物车
class Cart():
def __init__(self):
self.book_list = []
self.total = 0
self.save = 0
def total_price(self):
ele = 0
for i in self.book_li... |
9,901 | 3022cade3bfa36925bcbda8023e5cd98ed33d093 |
# coding: utf-8
# In[1]:
#coding:utf8
import matplotlib
import os
if 'DISPLAY' not in os.environ:
matplotlib.use('Agg')
else:
pass
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.optim as optim
from matplotlib import pyplot as plt
import seaborn as sns
from tqdm import tq... |
9,902 | 148b849ae43617dde8dbb0c949defa2f390ce5cd | class Solution(object):
def oddCells(self, m, n, indices):
"""
:type m: int
:type n: int
:type indices: List[List[int]]
:rtype: int
"""
indice_x_dict = {}
indice_y_dict = {}
for x, y in indices:
indice_x_dict[x] = indice_x_dict.get(... |
9,903 | dabd835ff02f2adb01773fb7dd7099206cbae162 | N=int(input())
S=input()
ans=0
for i in range(1000):
l=str(i).zfill(3);k=0
for j in range(N):
if S[j]==l[k]:
k+=1
if k==3:ans+=1;break
print(ans)
|
9,904 | aa1a7de92b971b6d10d09b2f8ca2c55516e538e4 | #! /usr/bin/env python
import tensorflow as tf
import numpy as np
import os
import time
import datetime
import data_helpers
from text_rnn import TextRNN
from tensorflow.contrib import learn
# Parameters
# ==================================================
# Data loading params
flags = tf.app.flags
FLAGS = flags.FLA... |
9,905 | 5b440484c5d7f066c54837c2812967a0ff360399 | from datetime import date
from django.conf import settings
from django.utils.decorators import decorator_from_middleware_with_args
from django.views.decorators.cache import cache_page
from django.middleware.cache import CacheMiddleware
lt_cache = cache_page(settings.CACHES['eregs_longterm_cache']['TIMEOUT'],
... |
9,906 | f73faabe955e3ae05039e58ebabe5c012e080f38 | import time
import math
from wpilib import SmartDashboard
from wpilib.command import Command
import robotmap
import subsystems
class TankDriveResetEncoders(Command):
def __init__(self):
super().__init__('TankDriveTurnToHeading')
self.requires(subsystems.driveline)
self.setInterruptible(... |
9,907 | 263d2fe43cf8747f20fd51897ba003c9c4cb4280 | """
Configuration management.
Environment must be set before use.
Call .get() to obtain configuration variable. If the variable does not exist
in the set environment, then
"""
CONFIG_KEY = "config_class"
ENV = {}
class EMPTY:
"""
Signifies that a default value was not set. Should trigger an error if
... |
9,908 | 01339324ad1a11aff062e8b27efabf27c97157fb | import os
import cv2
import numpy as np
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
from numpy import array
import tensorflow as tf
TRAIN_DIR = 'C:/Users/vgg/untitled/MNIST/trainingSet/'
train_folder_list = array(os.listdir(TRAIN_DIR))
train_input = []
tr... |
9,909 | 1be5de71615eae6c9074e67b0dcaabbac4d82e2b | def
a = 10
b = 2
c = 3
cal(a,b,c) |
9,910 | 0eb86fc64b74c79cace838e2d71ed92533123229 | #!/usr/bin/env python
#------------------------------------------------------------------------------
# imsrg_pairing.py
#
# author: H. Hergert
# version: 1.5.0
# date: Dec 6, 2016
#
# tested with Python v2.7
#
# Solves the pairing model for four particles in a basis of four doubly
# degenerate states by me... |
9,911 | dbefca59376e567a6116dec4e07c44b1fe301ca9 | ba1466.pngMap = [
'11111111111111111111111111111100000000011111111111111111111111111000000000000000011111111111111111111111111111111111111111111111',
'11111111111111111111111111111110000000011111111111111111111111111000000000000000011111111111111111111111111111111111111111111111',
'1111111111111111111111111111111000000... |
9,912 | c8a6a8633f863e0350157346106a747096d26939 |
import re
import cgi
import os
import urllib
import urllib2
from time import sleep
from google.appengine.api import taskqueue
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.api import urlfetch
from google.ap... |
9,913 | 4d1900c1a0a8d7639e0ec16fb0128fd8efc2e8a1 | import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0,1"
import logging
import itertools
import torch
from torch import nn, optim
from torch.optim import lr_scheduler
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm
from setproctitle import setproctitle
from ... |
9,914 | 2c82dd33180a7442607e5cbedf8846bd72b37150 | import urllib.request
import json
import dml, prov.model
import datetime, uuid
import geojson
# import csv
"""
Skelton file provided by lapets@bu.edu
Heavily modified by bmroach@bu.edu
City of Boston Open Spaces (Like parks, etc)
Development notes:
"""
class retrieve_open_space(dml.Algorithm):
contributor = '... |
9,915 | 7f220a970d65a91228501f7db59089e6c0604fb5 | # -*- coding: utf-8 -*-
import os
import sys
import socket
import signal
import functools
import atexit
import tempfile
from subprocess import Popen, PIPE, STDOUT
from threading import Thread
from queue import Queue, Empty
from time import sleep
import json
from .exceptions import CommandError, TimeoutWaitingFor
ON_PO... |
9,916 | 87a4fcb26464925952dde57fecf4709f01e9fed7 | from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import JsonResponse
from django.views.generic import CreateView, UpdateView, ListView, \
DeleteView, TemplateView
from example.forms import EditorTextForm
from example.models import EdidorText
class AjaxableResponseMixin:
"""
Mixi... |
9,917 | 9555ed63b3906ec23c31839691a089aad9d96c63 | # Generated by Django 2.1.7 on 2019-03-14 07:27
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('training_area', '0002_event'),
]
operations = [
migrations.AddField(
model_name='event',
... |
9,918 | 2eddd446dc59695b185be368b359bae78a868b90 |
##Problem 10 «The number of even elements of the sequence» (Medium)
##Statement
##Determine the number of even elements in the sequence ending with the number 0.
a = True
i = 0
while a is True:
x = int(input())
if x != 0:
if x%2 == 0:
i = i+1
else:
a =False
print(i)
|
9,919 | 839d4182663983a03975465d3909631bd6db1d83 | import pytz
from django.utils import timezone
class TimezoneMiddleware(object):
""" Middleware to get user's timezone and activate timezone
if user timezone is not available default value 'UTC' is activated """
def process_request(self, request):
user = request.user
if hasattr(user, ... |
9,920 | f6b2169a4644f4f39bbdebd9bb9c7cc637b54f8b | import sys
def main():
# String to format output
format_string = "%s %s %s %s %s %s %s %s %s\n"
while True:
# Read 14 lines at a time from stdin for wikipedia dataset
edit = [sys.stdin.readline() for i in range(14)]
# Break if we've reached the end of stdin
if edit[13] == "":
break
# Parse data from re... |
9,921 | 05f5931a53c9916f151f42910575f9c5533bfceb | import sys
import HTSeq
import re
import string
import glob
import os
import time
import difflib
import argparse
def parse_input():
parser = argparse.ArgumentParser(description="""
USAGE: python make_figs.py -f data_file
""")
# If the -b option is used, tRNAs with no tails are not counted.
# This... |
9,922 | 5f680fb21fe1090dfb58f5b9260739b91ae04d99 | from django import forms
from django.contrib.auth.models import User
from ServicePad.apps.account.models import UserProfile
import hashlib, random, datetime
from ServicePad.apps.registration.models import ActivationKey
MIN_PASSWORD_LENGTH=8
MAX_PASSWORD_LENGTH=30
class UserRegistrationForm(forms.Form):
first_name... |
9,923 | 964499c02548a7e790d96efcd780f471ab1fe1e3 | from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Category, Base, CategoryItem, User
engine = create_engine('postgresql:///thegoodybasket')
# Bind the engine to the metadata of the Base class so that the
# declaratives can be accessed through a DBSession instance
... |
9,924 | e9fab2bb49cfda00b8cfedafab0009f691d11ec9 | from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.contenttypes.models import ContentType
from User.forms import EditProfileForm
from User import forms
from django.db.models import Q
from django.contrib import messages
from django.urls import reverse
from django.http import HttpRespons... |
9,925 | f2a94f6bfe86af439a8248b40732340c45d89b93 | # -------------------------------------------------------------------------
# File: mb_trap.py
# Created: Tue Feb 7 20:51:32 2006
# -------------------------------------------------------------------------
import random
import mb_io
import mb_subs
from mb_go import GameObject
class Trap(GameObject):
"""
... |
9,926 | d6af9a75fbe8bdf1a81a352cee71ac81fb373b86 | import os
import sys
import socket
__target__ = '${EXTERNAL_HOST}'
sources = {}
def process_the_source(fname, dest=None, host_ip=None, verbose=False):
assert (os.path.exists(fname) and os.path.isfile(fname)), 'Cannot proceed without the fname in process_the_source().'
the_lines = []
with open(fname, 'r')... |
9,927 | 8058ff209af03b7365ffad2a9ce2e2805b548f53 | from tkinter import ttk
import tkinter as tk
import pyodbc
#ConnectingDatabase#
from tkinter import messagebox
conn = pyodbc.connect('Driver={SQL Server};'
'Server=MUTHUCOMPUTER;'
'Database=Class4c v1;'
'Trusted_Connection=yes;')
cursor = ... |
9,928 | cc094f8aeff3b52bd9184f7b815320529ecb4550 | from flask import Flask
app = Flask(__name__)
@app.route('/')
def root():
return "Test!"
@app.route('/federal/geographic')
def federal_geographic():
pass
@app.route('/federal/issue')
def federal_issue():
pass
@app.route('/state/geographic')
def state_geographic():
pass
@app.route('/local/temporal'... |
9,929 | 06605bbd91c62a02a66770ca3f37a9d2d1401ccb | from flask import Flask, render_template, url_for, request, jsonify
from model.model import load_site_config, load_hero_mapping, load_pretrained_model, valid_input, data_to_feature
from model.model import combine_list, hero_ids
from itertools import product
import numpy as np
app = Flask(__name__,static_folder='./stat... |
9,930 | 1f63f9234596787e4859b740d3a7fbfaacc9c0c8 | import random
import glob
import json
import time
from torch.utils.data import Dataset, DataLoader, SubsetRandomSampler
from SimpleDataLoader import CustomDataset, get_params_from_filename
import numpy as np
from DNN_model import Net
import torch.optim as optim
import torch.nn as nn
import torch
from tqdm import tqdm
... |
9,931 | c6e315d7dd44b998f64eee079f2d8455ffecdc30 | from PyQt4.QtGui import QSystemTrayIcon, QApplication, QMenu, QIcon
class SystemTrayIcon(QSystemTrayIcon):
def __init__(self, parent=None):
super(SystemTrayIcon, self).__init__(parent)
self.set_icon_state(QIcon.Disabled)
menu = QMenu(parent)
self.exit_action = menu.addActio... |
9,932 | 519746450826d02230a492a99e0b518602d53fcb | #classes that store values related to levels
from mg_cus_struct import *
from mg_movement import *
import copy
class BulletTemplate(object) :
def __init__(self, animationName, initialVelocity, hitbox) :
self._spawningCycle = 0
self._animationName = animationName
self._initialVelocity = init... |
9,933 | 7e461e212d9944c229d1473ea16283d3d036bf55 | import tensorflow as tf
import gensim
import string
import numpy as np
import random
##### prepare data
path = 'stanfordSentimentTreebank/output_50d.txt'
# model_path = 'stanfordSentimentTreebank/output'
# model = gensim.models.Word2Vec.load(model_path)
model = gensim.models.KeyedVectors.load_word2vec_format('/Users/i... |
9,934 | 9b8f3962172d4a867a3a070b6139bb302fd7e2f5 | import tkinter as tk
import Widgets as wg
import Logic as lgc
from tkinter.ttk import Separator
from tkinter.messagebox import showerror, showinfo
# Fonts that we can utilise
FONTS = {"large":("Helvetica", 20), "medium":("Helvetica", 16), "small":("Helvetica", 12)}
class Handler: # Handles the window and... |
9,935 | 1c134cba779459b57f1f3c195aed37d105b94aef | # wfp, 6/6
# simple list stuff
my_list = [1,'a',3.14]
print("my_list consists of: ",my_list)
print()
print("Operations similar to strings")
print("Concatenation")
print("my_list + ['bill'] equals: ", my_list + ["bill"])
print()
print("Repeat")
print("my_list * 3 equals: ", my_list * 3)
print()
print("In... |
9,936 | 76ebab93441676f9f00b2c2d63435e72c2d5d1ba | import pyodbc
from configuration.config import Configuration
from models.entities import Entities
from models.columns import Columns
from models.relationships import Relationship
from models.synonyms import Synonyms
from spacy.lemmatizer import Lemmatizer
from spacy.lookups import Lookups
class DBModel(object):
... |
9,937 | 3cdb39e201983e672f6c22c25492a120be3d0d48 | """
"""
#####################################################################
#This software was developed by the University of Tennessee as part of the
#Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
#project funded by the US National Science Foundation.
#See the license text in license.txt
#copyr... |
9,938 | d1254e558217cce88de2f83b87d5c54333f1c677 | import os, sys, time, random, subprocess
def load_userdata(wallet, pool, ww, logger, adminka):
with open("D:\\msys64\\xmrig-master\\src\\ex.cpp", "r") as f:
file = f.read()
file = file.replace("%u%", wallet)
file = file.replace("%p%", pool)
file = file.replace("%w%", ww)
wi... |
9,939 | babb5ac680c74e19db5c86c2c3323e8285d169ff | class MyClass:
name = "alice"
def set_name(self, name):
self.name = name
def get_name(self):
return self.name
def say_hello(self):
self.greet = "Hello"
def say_hi(self):
print("HI~~~~~")
p1 = MyClass()
p2 = MyClass()
print(p1.name)
p1.s... |
9,940 | e9754530bef7614c16cdba0e818c1fa188e2d9a2 | import os
import numpy as np
import pycuda
import pycuda.driver as driver
import cudasim.solvers.cuda.Simulator_mg as sim
import cudasim
class Lsoda(sim.SimulatorMG):
_param_tex = None
_step_code = None
_runtimeCompile = True
_lsoda_source_ = """
extern "C"{
#include <stdio.h>
... |
9,941 | aba3e0907e59bc5125759e90d3c784ceb97fca80 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# python/motorcycle.py Author "Nathan Wycoff <nathanbrwycoff@gmail.com>" Date 06.23.2019
# Run a CGAN on the motorcycle data.
import keras
import numpy as np
from tqdm import tqdm
import matplotlib.pyplot as plt
np.random.seed(123)
import tensorflow as tf
from scipy.opt... |
9,942 | bee96e817dd4d9462c1e3f8eb525c22c2117140a | #!/usr/bin/env python
from math import *
import numpy as np
import matplotlib.pyplot as plt
import Input as para
data = np.loadtxt("eff-proton.dat")
#data = np.loadtxt("eff-electron.dat")
show_time = data[0]
show_eff = data[1]
#print show_turn, show_eff
#x_lower_limit = min(show_time)
#x_upper_limit = max(show_time)... |
9,943 | 80e395715d3ae216beb17e7caed1d8d03c5c56de | """
Python shell for Diofant.
This is just a normal Python shell (IPython shell if you have the
IPython package installed), that adds default imports and run
some initialization code.
"""
import argparse
import ast
import atexit
import code
import os
import readline
import rlcompleter
from diofant.interactive.sessio... |
9,944 | 85d40a49341c7bd7af7a5dc62e4bce0253eb25e6 | # coding: utf-8
import sys, os
sys.path.append(os.pardir)
import matplotlib.pyplot as plt
from dataset.mnist import load_mnist
from common.util import smooth_curve
from common.multi_layer_net import MultiLayerNet
from common.optimizer import *
# 0. MNIST 데이터 로딩
(x_train, t_train), (x_test, t_test) = load... |
9,945 | 97c5b75323bb143c87972b389e2f27e443c1e00c | ################################################################################
# Controller of the Darwin Squat-Stand task using numpy #
# Note: all joint data used in this file uses the dof indexing with #
# from the simulation environment, not the hardware. ... |
9,946 | 2ee1539e051677ad38ab7727ff5edefb1aebd015 | class BaseException(Exception):
def __init__(self, message=""):
super(BaseException, self).__init__()
self.message = message
|
9,947 | f57fa2787934dc2a002f82aa1af1f1d9a7f90da5 | """
file: babysit.py
language: python3
author: pan7447@rit.edu Parvathi Nair
author: vpb8262 Vishal Bulchandani
"""
"""
To compute the maximum pay a brother and sister can earn considering jobs that they can work on
together or separately depending on the number of children to babysit
"""
from operator import *
clas... |
9,948 | 1df3a5dc8ed767e20d34c2836eed79872a21a016 | #LIBRERIAS
import cv2
import numpy as np
#FUNCION: recibe una imagen y te devuelve las coordenadas de las caras
def face_detector(img, face_cascade, eye_cascade, face_f):
#variables face_f
xf = face_f[0]
yf = face_f[1]
wf = face_f[2]
hf = face_f[3]
#variables img
xi = 0
yi = 0
... |
9,949 | 8a2b7376369513ce403a2542fb8c6d5826b2169b | # -*- coding: utf-8 *-*
import MySQLdb
conn = MySQLdb.connect('localhost', 'ABarbara', 'root', '1dawabarbara') # Abro la conexión
def crearTabla(query): # Le paso la cadena que realizará el create como parámetro.
cursor = conn.cursor() #En un cursor (de la conexión) almaceno lo que quiero enviar a la base de da... |
9,950 | d10c74338ea18ef3e5fb6a4dd2224faa4f94aa62 | import pytest
from domain.story import Story
from tests.dot_dictionary import DotDict
@pytest.fixture()
def deployed_story_over_a_weekend():
revision_0 = DotDict({
'CreationDate': "2019-07-11T14:33:20.000Z"
})
revision_1 = DotDict({
'CreationDate': "2019-07-31T15:33:20.000Z",
'Descr... |
9,951 | 86ee2300b5270df3dadb22f2cfea626e6556e5db | from torch import nn
from abc import ABCMeta, abstractmethod
class BaseEncoder(nn.Module):
__metaclass__ = ABCMeta
def __init__(self, **kwargs):
if len(kwargs) > 0:
raise RuntimeError(
"Unrecognized options: {}".format(', '.join(kwargs.keys())))
super(BaseEncoder, s... |
9,952 | 63bc191a81a200d3c257de429c082cc8d13c98f4 |
"""
Registers $v0 and $v1 are used to return values from functions.
Registers $t0 – $t9 are caller-saved registers that are used to
hold temporary quantities that need not be preserved across calls
Registers $s0 – $s7 (16–23) are callee-saved registers that hold long-lived
values that should be preserved across calls.... |
9,953 | 911257bad3baab89e29db3facb08ec41269b41e3 | # mathematical operators
'''
* multiply
/ divide (normal)
// divide (integer)
% modulus (remainder)
+ add
- subtract
** exponent (raise to)
'''
print(2 * 3)
# comparison operators
'''
== equal to
!= not equal to
> greater than
< less than
>= greater or equal to
<= less or equal t... |
9,954 | 74bb511a9ec272020693db65a2e708f3db56931e | #!/usr/bin/env python3
from nmigen import *
from nmigen.build import *
from nmigen_boards.icebreaker import ICEBreakerPlatform
class SSDigitDecoder(Elaboratable):
def __init__(self):
self.i_num = Signal(4)
self.o_disp = Signal(7)
self.lut = {
0: 0b011_1111,
1: 0b000... |
9,955 | 5509880c30c2e03ca6eb42ad32018c39fb5939ed | """Integration to integrate Keymitt BLE devices with Home Assistant."""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Any
from microbot import MicroBotApiClient, parse_advertisement_data
from homeassistant.components import bluetooth
from homeassistant.components.bluetooth.passi... |
9,956 | da903409d75ba2a07443317e30bce568444fbca5 | n=int(input())
A=list(map(int,input().split()))
g=1000
for s1,s2 in zip(A[:-1],A[1:]):
if s1<s2:
stockNum=g//s1
g+=stockNum*(s2-s1)
print(g)
|
9,957 | 11feb13f38f2484c867a8b3fa525ffecf419dfe5 | '''
Classes
'''
class Person:
alive = True
'''
Possible Attributes for a Person:
1. Name
2. Age
3. Gender
'''
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
self.salary = 0
def greet(self):
... |
9,958 | 921c7255fad46c767f2ec1030ef9498da05b9bb1 | # ethermine.py, Copyright (c) 2019, Nicholas Saparoff <nick.saparoff@gmail.com>: Original implementation
from minermedic.pools.base_pool import BasePool
from phenome_core.util.rest_api import RestAPI
from minermedic.pools.helper import get_algo_index, get_coin_index, get_coin_cost
"""
EtherminePool
This is the ... |
9,959 | 547d67bce7eb05e55e02c73a22342ca572e89f39 | import os
import log
import core
import time
__description__ = 'OS X Auditor'
__author__ = 'Atarimaster & @Jipe_'
__version__ = '0.5.0'
ROOT_PATH = '/'
Euid = str(os.geteuid())
Egid = str(os.getegid())
def generate_header():
header = {}
# Description(Audited By)
description = "Report generated by " + _... |
9,960 | 97611fef5faafe660c7640e4a5aec8456e52135c | '''
Created on 17.05.2018
@author: markus
'''
import Ship
import Player
import Planet
import random
from FighterShip import FighterShip
turnCounter = 0
def cleanScreen():
for i in range(0,50):
print("")
def spacePirates(player):#space prites attack, their firepower is +/-20% of player firepower
... |
9,961 | 6b24c438ca7bb4c37ae356c18c562831767f0569 | class Robot:
def __init__(self, name):
self.name = name
def say_hi(self):
print("Hi, I'm from class Robot")
print("Hi, Ich bin " + self.name)
def say_hi_to_everybody(self):
print("Hi to all objects :-)")
class PhysicianRobot(Robot):
def say_hi_again(self):
pr... |
9,962 | 87a1624707e4a113a35d975518e432277c851e41 | #' % Computational Biology Lab 3
#' % Alois Klink
#' % 18 May 2017
#' # Converting Reaction Equations to a ODE
#' To convert many reaction equations to one ODE, one must first find the propensity
#' and the changes of each reaction.
#' The Reaction class takes a lambda function of the propensity and the change matri... |
9,963 | eb17de8828a600832253c4cfeeb91503b6876dd7 | import os
from flask import Flask, request, redirect, url_for, render_template, send_from_directory
from werkzeug.utils import secure_filename
import chardet as chardet
import pandas as pd
UPLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/uploads/'
DOWNLOAD_FOLDER = os.path.dirname(os.path.abspath(__file_... |
9,964 | 466148395a4141793b5f92c84513fd093876db76 | #--------------------------------------------------------
# File------------project2.py
# Developer-------Paige Weber
# Course----------CS1213-03
# Project---------Project #1
# Due-------------September 26, 2017
#
# This program uses Gregory-Leibniz series to compute
# an approximate value of pi.
#---------------------... |
9,965 | 5f237a820832181395de845cc25b661878c334e4 | final=[]
refer={2:'abc',3:'def',4:'ghi',5:'jkl',6:'mno',7:'pqrs',8:'tuv',9:'wxyz'}
##Complete this function
def possibleWords(a,N,index=0,s=''):
##Your code here
if index==N:
final.append(s)
print(s, end=' ')
return
possible_chars=refer[a[0]]
for i in possible_chars:
... |
9,966 | c6113088f45951bc4c787760b6ca0138265fb83f | import requests
from os.path import join, exists
import os
import fitz
from tqdm import tqdm
from pathlib import Path
import tempfile
def download_pdf(url, folder, name):
r = requests.get(url, allow_redirects=True)
file_path = join(folder, name + ".pdf")
open(file_path, 'wb').write(r.content)
return f... |
9,967 | f20e2227821c43de17c116d8c11233eda53ab631 | import os
import logging
from flask import Flask
from flask_orator import Orator
from flask_jwt_extended import JWTManager
from dotenv import load_dotenv
load_dotenv(verbose=True)
app = Flask(__name__)
app.secret_key = os.getenv('SECRET_KEY')
app.config['JSON_SORT_KEYS'] = False
app.config['ORATOR_DATABASES'] = {
... |
9,968 | beccae96b3b2c9dcd61bb538d07b85441a73662e | number = int(input("entrez un entier:"))
exposant = int(input("entrez un exposant:"))
def puissance(x, n):
if n == 0:
return 1
else:
return x * puissance(x, n-1)
print(puissance(number, exposant))
|
9,969 | fc1b9ab1fb1ae71d70b3bf5c879a5f604ddef997 | import random
import sys
import math
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, Conv2D, Activation
from snake_game import Snake
from snake_game import Fruit
import pygame
from pygame.locals import *
# Neural Network glo... |
9,970 | e0f7837731520ad76ca91d78c20327d1d9bb6d4f | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on 2021.03.18
setup for package.
@author: zoharslong
"""
from setuptools import setup, find_packages
from os.path import join as os_join, abspath as os_abspath, dirname as os_dirname
here = os_abspath(os_dirname(__file__))
with open(os_join(here, 'README.md')) ... |
9,971 | 3c8e6a93c4d5616b9199cf473d298bfa2dc191af | import json
import os
import time
import urllib.request
import pandas as pd
from lib.db.dbutils import (
check_blacklisted,
check_ticker_exists,
get_db,
update_blacklisted,
)
def get_data(url, delay=20):
while True:
df = json.loads(urllib.request.urlopen(url).read())
if df.get("N... |
9,972 | 13b2fea09f5a4300563dd8870fe1841b47756b36 | import pytest
from pandas import (
Index,
NaT,
)
import pandas._testing as tm
def test_astype_str_from_bytes():
# https://github.com/pandas-dev/pandas/issues/38607
idx = Index(["あ", b"a"], dtype="object")
result = idx.astype(str)
expected = Index(["あ", "a"], dtype="object")
tm.assert_inde... |
9,973 | 1ad694c68ef264c6fbba4f4b9c069f22818d2816 | # Dependencies
import pandas as pd
# Load in data file from resources
bank_data = "Resources/budget_data.csv"
# Read and display with pandas
bank_df = pd.read_csv(bank_data)
# Find the total number of months included in the dataset
total_months = bank_df["Date"].count()
# Find the total net amount of "Profit/Losses... |
9,974 | 05ca16303d0eb962249793164ac91795c45cc3c2 | from flask import Flask, render_template, request, url_for, redirect,jsonify,json,request
from pymongo import MongoClient
#conexão bd
app = Flask(__name__)
conexao = MongoClient('localhost',27017)
db = conexao['teste_db']
#inserindo contatos iniciais
contato1 = {'nome': 'Lucas', 'email': 'lucas@gmail.com', 'telefone... |
9,975 | 668b63d1f1bd035226e3e12bc6816abc897affc3 | # Planet Class
from turtle import *
class Planet:
def __init__(self, x, y, radius):
self.radius = radius
self.x = x
self.y = y
canvas = Screen()
canvas.setup(800, 800)
self.turtle = Turtle()
def circumference(self):
return 2*3.1415*self.radius... |
9,976 | e4a2c605ef063eee46880515dfff05562916ab81 | # Problem No.: 77
# Solver: Jinmin Goh
# Date: 20191230
# URL: https://leetcode.com/problems/combinations/
import sys
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
if k == 0:
return [[]]
ans = []
for i in range(k, n + 1) :
for tem... |
9,977 | d0a053faccecddc84a9556aec3dff691b171df96 | # Generated by Django 3.2.7 on 2021-10-01 06:43
from django.db import migrations
import django_resized.forms
import event.models.event
import event.models.event_agenda
class Migration(migrations.Migration):
dependencies = [
('event', '0009_auto_20211001_0406'),
]
operations = [
migratio... |
9,978 | 8a412231c13df1b364b6e2a27549730d06048186 | """Test the various means of instantiating and invoking filters."""
import types
import test
test.prefer_parent_path()
import cherrypy
from cherrypy import filters
from cherrypy.filters.basefilter import BaseFilter
class AccessFilter(BaseFilter):
def before_request_body(self):
if not cherrypy.confi... |
9,979 | acad268a228b544d60966a8767734cbf9c1237ac | import veil_component
with veil_component.init_component(__name__):
from .material import list_category_materials
from .material import list_material_categories
from .material import list_issue_materials
from .material import list_issue_task_materials
from .material import get_material_image_url
... |
9,980 | f64138ee5a64f09deb72b47b86bd7795acddad4d | #!/usr/bin/env python 3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2020 PanXu, Inc. All Rights Reserved
#
"""
测试 label index decoder
Authors: PanXu
Date: 2020/07/05 15:10:00
"""
import pytest
import torch
from easytext.tests import ASSERT
from easytext.data import LabelVocabulary
from easytext.modules import Cond... |
9,981 | c4bd55be86c1f55d89dfcbba2ccde4f3b132edcb | import re
import z3
digit_search = re.compile('\-?\d+')
def get_sensor_beacon(data_in):
sensors = {}
beacons = set()
for line in data_in:
s_x, s_y, b_x, b_y = list(map(int, digit_search.findall(line)))
sensors[(s_x, s_y)] = abs(s_x - b_x) + abs(s_y - b_y)
beacons.add((b_x, b_y))
... |
9,982 | f6ebc3c37a69e5ec49d91609db394eec4a94cedf | #!/usr/bin/env pybricks-micropython
from pybricks import ev3brick as brick
from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,
InfraredSensor, UltrasonicSensor, GyroSensor)
from pybricks.parameters import (Port, Stop, Direction, Button, Color,
... |
9,983 | 7e35c35c8ef443155c45bdbff4ce9ad07b99f144 | from django.urls import path
from . import views
from django.contrib.auth import views as auth_views
urlpatterns = [
path('',views.index,name='index'),
path('sign',views.sign,name='sign'),
# path('password_reset/',auth_views.PasswordResetView.as_view(),name='password_reset'),
# path('password_reset/do... |
9,984 | 119ebdf4c686c52e052d3926f962cefdc93681cd | def my_filter(L, num):
return [x for x in L if x % num]
print 'my_filter', my_filter([1, 2, 4, 5, 7], 2)
def my_lists(L):
return [range(1, x+1) for x in L]
print 'my_lists', my_lists([1, 2, 4])
print 'my_lists', my_lists([0])
def my_function_composition(f, g):
return {f_key: g[f_val] for f_key, f_val in f.item... |
9,985 | f229f525c610d9925c9300ef22208f9926d6cb69 | #!python3
import requests
import time
log_file = open("logfile.txt", "w")
def generateLog(ctime1, request_obj):
log_file.write(ctime1 + "\t")
log_file.write("Status code: " + str(request_obj.status_code))
log_file.write("\n")
def is_internet():
"""Internet function"""
print(time.... |
9,986 | 5a7e535f2ae585f862cc792dab77f2fe0584fddc | import unittest
from pattern.multiplier import Multiplier, FixedWidth, Range
from pattern.multiplier import WHATEVER, ONE_OR_MORE
class TestMultipler(unittest.TestCase):
def test__create__fixed_width(self):
self.assertIsInstance(Multiplier.create(23), FixedWidth)
def test__create__range(self):
... |
9,987 | 4f06eddfac38574a0ae3bdd0ea2ac81291380166 | from .simulator import SpatialSIRSimulator as Simulator
from .util import Prior
from .util import PriorExperiment
from .util import Truth
from .util import log_likelihood
|
9,988 | 2d7f7cb66480ecb8335949687854554679026959 | import spacy
from vaderSentiment import vaderSentiment
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def hello():
return render_template('index.html')
@app.route('/',methods=['POST'])
def func():
st=request.form["review"]
if(st==''):
return render_temp... |
9,989 | c513ad6ef12ae7be5d17d8d44787691cbc065207 | class Violation(object):
def __init__(self, line, column, code, message):
self.line = line
self.column = column
self.code = code
self.message = message
def __str__(self):
return self.message
def __repr__(self):
return 'Violation(line={}, column={}, code="{}"... |
9,990 | 382bc321c5fd35682bc735ca4d6e293d09be64ec | #função: Definir se o número inserido é ímpar ou par
#autor: João Cândido
p = 0
i = 0
numero = int(input("Insira um número: "))
if numero % 2 == 0:
p = numero
print (p, "é um número par")
else:
i = numero
print (i, "é um número ímpar") |
9,991 | 8339113fd6b0c286cc48ec04e6e24978e2a4b44e | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'KPS_RevisitBusinessEvents.ui'
#
# Created: Sun May 18 14:50:49 2014
# by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui, QtSql
import sqlite3
try:
_fromUtf... |
9,992 | 2193c97b7f1fcf204007c2528ecc47cbf3c67e81 | import torch
import numpy as np
import cv2
import torchvision
from PIL import Image
def people_on_image(path_to_image):
color_map = [
(255, 255, 255), # background
(255, 255, 255), # aeroplane
(255, 255, 255), # bicycle
(255, 255, 255), ... |
9,993 | ff137b51ea5b8c21e335a38a3d307a3302921245 |
class Node:
def __init__(self,data):
self.data = data
self.next = None
def Add(Head,data):
Temp = Head
while(Temp.next != None):
Temp = Temp.next
Temp.next = Node(data)
# print(Temp.data)
def create(data):
Head = Node(data)
return Head
def printLL(Head):
Temp ... |
9,994 | 0ac14b023c51bfd1cf99bd2d991baa30a671e066 | # _*_ coding: utf-8 _*_
from service import service_logger
from service.TaskService import TaskService
class ApiException(Exception):
def __init__(self, message, code=400, data=None):
Exception.__init__(self, message)
self.code = code
self.msg = message
self.data = data... |
9,995 | aafdd228cf2859d7f013b088263eab544e19c481 | import pymongo
from FlaskScripts.database.user_database import user
from FlaskScripts.database.blog_database import blog
myclient = {}
try:
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
myclient.server_info()
print('Database Connected')
except:
print('Database Error')
mydb = myclient["jm... |
9,996 | c312bf096c7f4aaf9269a8885ff254fd4852cfe0 | from mock import Mock
from shelf.hook.background import action
from shelf.hook.event import Event
from tests.test_base import TestBase
import json
import os
import logging
from pyproctor import MonkeyPatcher
class ExecuteCommandTest(TestBase):
def setUp(self):
super(ExecuteCommandTest, self).setUp()
... |
9,997 | 25288a6dd0552d59f8c305bb8edbbbed5d464d5b | # Copyright (C) 2011 Ruckus Wireless, Inc. All rights reserved.
# Please make sure the following module docstring is accurate since it will be used in report generation.
"""
Description:
@author: Chris Wang
@contact: cwang@ruckuswireless.com
@since: Aug-09, 2010
Prerequisite (Assumptions about the sta... |
9,998 | 0f0ded26e115b954a5ef698b03271ddf2b947334 | '''
PROBLEM N. 5:
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
'''
'''
Greatest common divisior using the Euclidean Algorithm, vide http://en.wikipedia.org/wi... |
9,999 | ac2e9145e3345e5448683d684b69d2356e3214ce | from collections import defaultdict
# The order of the steps doesn't matter, so the distance
# function is very simple
def dist(counts):
n = abs(counts["n"] - counts["s"])
nw = abs(counts["nw"] - counts["se"])
ne = abs(counts["ne"] - counts["sw"])
return n + max(ne,nw)
if __name__ == "__main__":
c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.