index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
10,700 | f704aa792302a0aee73e305c6ea66605d206dbda | from socket import socket, AF_INET, SOCK_STREAM
def echo_client(client_sock, addr):
print('Got connection from', addr)
print('Socket fd:', client_sock.fileno())
print(type(client_sock))
# Make text-mode file wrappers for read/write
client_in = client_sock.makefile('r', encoding='latin-1')
client_out = client_s... |
10,701 | f9c55bc797b945efc9921daf8c422ad531799893 | #!/usr/bin/env python
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "... |
10,702 | 9090e7ff7afc0c76593f160efac1f72b4422cae4 | #!/usr/bin/env python3
import datetime
import speedtest
from peewee import IntegrityError
from models import Result, Server
st = speedtest.Speedtest()
results = []
for i in range(5):
st.get_best_server()
threads = 1
st.download(threads=threads)
st.upload(threads=threads)
result = st.results.di... |
10,703 | db9a3b79b4054bd94eafdc4f36cb793cf1ebaa87 | #!/usr/bin/env python
import time
from optparse import OptionParser
parser = OptionParser()
parser.add_option('--outname', metavar='F', type='string', action='store',
default='mujets',
dest='outname',
help='Output name for png and pdf files')
parser.add_option(... |
10,704 | 9e7b1abb92a7bf2d0f20409a6bcb831116745294 | #!/usr/bin/env python
import os
import argparse
import logging
import sys
def main(args, loglevel):
logging.basicConfig(format="%(levelname)s: %(message)s", level=loglevel)
f = args.file_input
if not os.path.exists(f):
logging.error("File %s does not exist" % f)
sys.exit(1)
logging.info("Processin... |
10,705 | 214cb65d5b4e7be6397954a5fcffd0c632e251bc | import unittest
import pandas
from oop_pyaaas.dataset import Dataset
import tempfile
import pathlib
from oop_pyaaas.service import AaaSService
class DatasetTest(unittest.TestCase):
def setUp(self):
self.test_data_csv = """age, gender, zipcode\n34, male,81667\n35, female,81668\n6, male,81669\n 37, femal... |
10,706 | ff2b18b7e4afa7b3939189700c91896f6061f527 | import numpy as np
import cv2
def minmax_filter(image, ksize, mode):
rows, cols = image.shape[:2]
dst = np.zeros((rows, cols), np.uint8)
center = ksize // 2
for i in range(center, rows-center):
for j in range(center, cols-center):
y1, y2 = i - center, i + center + 1
x1,... |
10,707 | 6de70bc95d452f00fe9e24cb9ecec3ebb62d3ab8 | '''
Faça uma função que informe a quantidade de dígitos de um determinado número inteiro informado.
'''
def qtddigitos(n):
n = str(n)
return len(n)
n = int(input("Informe um número inteiro: "))
quantidade = qtddigitos(n)
print("O numero informado possui %i digito(s) " %quantidade)
|
10,708 | 5e70b86a388719b55d457a4525c342e1f0178648 | from pluggs.blogs import load_custom_jinja2_env
from pluggs.blogs.routes.blogs_home_controller import bloghome_controller
def load_plugin(app):
print('**** Load Plugin Section ****')
print('App Root Path:', app.root_path)
app.register_blueprint(bloghome_controller, url_prefix="/dashboard/blog")
load_c... |
10,709 | ec01a2a471c6ddbc000f93d20a6e8b14e9852a4e | """Parsers used in selected tests API."""
from evergreen import EvergreenApi
from starlette.requests import Request
from selectedtests.datasource.mongo_wrapper import MongoWrapper
def get_db(request: Request) -> MongoWrapper:
"""
Get the configured database for the application.
:param request: The requ... |
10,710 | 0c784c04317546bc923542bbee8ddac3241f6b45 | /*
A KBase module: kb_SPAdes
A wrapper for the SPAdes assembler with hybrid features supported.
http://bioinf.spbau.ru/spades
Always runs in careful mode.
Runs 3 threads / CPU.
Maximum memory use is set to available memory - 1G.
Autodetection is used for the PHRED quality offset and k-mer sizes.
A coverage cutoff is n... |
10,711 | e1a268fde8a6042582ca64260fad36056506d854 |
import pytorch_lightning as pl
import torch
class BaseModel(pl.LightningModule):
def __init__(self, args):
super().__init__()
self.args = args
self.learning_rate = args.learning_rate
def forward(self):
pass
def training_step(self, batch, batch_idx):
# batch
... |
10,712 | e75b6266fbd45c97110af2098d22c34358a6c46d | #Problem1 test for the survival model
#a cohort of 573 patients over 5 years.
import SurvivalModel as SurvivalCls
MORTALITY_PROB = 0.1 # annual probability of mortality
TIME_STEPS = 100 # simulation length
SIM_POP_SIZE = 573 # population size of the simulated cohort
ALPHA = 0.05 # significance ... |
10,713 | aa023bf53cffaa1c39e691b2904273edda092b17 | import tensorflow as tf
c = tf.constant(10.0, name="c", dtype=tf.float32)
a = tf.constant(5.0, name="a", dtype=tf.float32)
b = tf.constant(13.0, name="b", dtype=tf.float32)
d = tf.Variable(tf.add(tf.multiply(a, c), b))
init = tf.global_variables_initializer()
with tf.Session() as session:
merged = tf.summary.me... |
10,714 | 44fbe170559028e05cc1369f19e9fe1e8bd9dbdc | # Tracy Otieno
# homework_1.2.py
# May 4, 2017
# Prints a tic tac toe board
def draw():
# initialize an empty board
board = ""
# a standard tic-tac-toe board has 5 rows so
for i in range(5):
# switch between printing vertical and horizontal bars
if i%2 == 0:
board += "|... |
10,715 | 70dbfcb29fcab1cd7c0291966f7d3bdfc57b2681 | from __future__ import print_function
import numpy as np
import tensorflow as tf
import argparse
import os
import sys
from PIL import Image
from skimage.io import imread, imshow
from skimage.transform import resize
import matplotlib.pyplot as plt
def get_image_size(data):
image_path = os.path.join(FLAGS.datas... |
10,716 | 476a3e466c154f86f8b82f38909f18e86d72daed | from numpy import linspace, array, matrix, sort, diag, linalg as LA
from misc import tridiag_toeplitz, get_diags
from jacobi import jacobi_rotalg
import matplotlib.pyplot as plt
N = 100
r_0, r_max = 0.0, 10.0
r = linspace(r_0, r_max, N + 2)[1:-1]
h = (r_max - r_0)/(N + 1)
indices = linspace(1.0, 1.0*N, N)
H = matrix(... |
10,717 | 32b5236b15a9a4726f27ee4eb83f193b87314647 | # Copyright (c) 2019 Gunakar Pvt Ltd
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted (subject to the limitations in the disclaimer
# below) provided that the following conditions are met:
# * Redistributions of source code must retain the ... |
10,718 | dd4734b214e2fd67cef7ff262c539f8b6f9f6b3c | import serial
import time
import psutil
## Simple CPU usage monitor.
ser = serial.Serial(port='/dev/ttyACM0', baudrate=345600, timeout=.1)
time.sleep(3);
i=0
while 1:
x = psutil.cpu_percent()
if x<30:
ser.write(bytes('<0,255,0>','utf8'))
if x>50 and x<70:
ser.write(bytes('<255,255,0>','utf8'))
if x>70:
se... |
10,719 | 50fd3d86d1e2499901fe9f5e031c1814fdb68890 | import networkx as nx
import Queue
import pandas as pd
import os
from pandas import Series
from sklearn.cross_validation import train_test_split
def init(queue,G,alpha):
df = pd.read_csv('graph_pre.csv')
no_train, no_test, label_train, label_test = train_test_split(df.no, df.label, test_size=1 - alpha)
... |
10,720 | 3578b21330290c6e2774e3a7114ad55dc48f80c2 | """:mod:`soran.datetime` --- datetime
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Use this module instead :mod:`datetime` to confirm all time related values are
in UTC timezone. because :mod:`datetime` return a naive datetime which
dosen't contain a timezone by default.
.. sourcecode:: python
>>> from soran.datetime... |
10,721 | fe3b3b59cd693c0999ed21a4ce14526ae5bf4820 | from random import randint
numeros = list()
def somaPar(numeros):
total = 0
for i, v in enumerate(numeros):
if v % 2 == 0:
total += v
print(total)
def sorteia():
for i in range(0, 5):
numeros.append(randint(1, 10))
print(numeros)
sorteia()
somaPar(numeros) |
10,722 | 186ea35f99f0310079d23fd7e174233f58cf9f26 | import sys
import os
from add_posts import AddPosts
class UpdatePosts():
def __init__(self, filename=None):
self.template = 'blog_temp.html'
self.folders = ["text reviews/"]
def find_posts(self):
for folder in self.folders:
for filename in os.listdir(folder):
... |
10,723 | 1354f91b27216c96d4163cae1fa836728e39483a | import re
def show_me(name):
if ' ' in name:
return False
elif re.search('--', name) is not None:
return False
elif re.search('-[a-z]', name) is not None:
return False
elif re.search('[a-z][A-Z]', name) is not None:
return False
elif re.search('\A-', name) is not N... |
10,724 | 9709ca436eb39afd1a69023a90a116bff6063542 |
#---------------------------PROBLEM STATEMENT 2-----------------------------------
import re
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
def canditate_phrase(line):
phrases = []
words = nltk.word_tokenize(line) #split the text in words
phrase = ''
for word in wor... |
10,725 | 5b03691ea0a85b38aff77be824b9960553de1888 | from server import SimpleServer
from SimpleWebSocketServer import SimpleWebSocketServer, WebSocket
import time
server = SimpleWebSocketServer('0.0.0.0', 8000, SimpleServer)
start_time = time.time()
while True:
server.serveonce()
|
10,726 | a674c893d8e3d16b35e60b54a01a017d3d0100ce | """
Lab 2 for Programming for Beginners
My First Flowchart
Julia Garant
Jan 23 2020
"""
favNumber = input("What's your favourite number?")
print(favNumber + " is a great number!")
|
10,727 | e29a8ed9ea23a5f835ab2a79a9e1254cbbfd07c6 | import torch
import torch.nn as nn
import torch.nn.functional as F
#
class MyMnistNet(nn.Module):
def __init__(self):
super().__init__()
self.linear1 = nn.Linear(1,30)
self.relu = nn.ReLU()
self.linear2 = nn.Linear(30,20)
self.relu = nn.ReLU()
self.linear3 = nn.Lin... |
10,728 | fbed223f876b21eabe85555b344daa59a713f525 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/11/6 19:10
# @File : leetCode_521.py
'''
如果a,b长度不同,则返回长度较长的
如果长度相同,相等则返回-1
python bool和值进行逻辑运算,结果为 后面的变量值
'''
class Solution(object):
def findLUSlength(self, a, b):
"""
:type a: str
:type b: str
:rtype: int
... |
10,729 | 990afe861b44a7b974e04f5e26c6764256fe80c3 | class Solution(object):
def reconstructQueue(self, people):
"""
:type people: List[List[int]]
:rtype: List[List[int]]
"""
if not people: return []
people = sorted(people, key=lambda (h, k): (-h, k))
print people
res = []
for p in people:
... |
10,730 | 80325839d4dafad53376d3cb2674fa7deaae74e8 | import abc
"""
定义抽象类,实际类应在simulation_filters, simulation_algos, charge_algos分别定义
"""
class DataFilter(metaclass = abc.ABCMeta):
"""
数据过滤器抽象类
"""
@abc.abstractclassmethod
def __init__(self):
pass
@abc.abstractclassmethod
def set_filter(self, filter):
pass
@abc.abstractc... |
10,731 | 0e4193812b6996f0104ae879b6dd9f1c1cb8a001 | N,A,B = map(int,input().split())
a = list(map(int,input().split()))
a.sort()
mo = 10**9 + 7
loop = 0
if A == 1:
for i in range(N):
print(a[i] % mo)
exit()
a_max = a[-1]
while B > 0:
if a[0] * A >= a_max:
loop = B//N
B %= N
break
a[0] *= A
B -= 1
... |
10,732 | 610a9051c154dabd92259b129435c78601d54e55 | import pytest
import responses
import json
from python.prohibition_web_svc.config import Config
from datetime import datetime
import python.prohibition_web_svc.middleware.keycloak_middleware as middleware
from python.prohibition_web_svc.models import db, UserRole, User
from python.prohibition_web_svc.app import create_... |
10,733 | 03e36df7f62ba6681ef26d1a5418541d7188346c | from django.contrib import admin
from geotrek.common.mixins.actions import MergeActionMixin
from geotrek.sensitivity.models import Rule, SportPractice, Species
class RuleAdmin(MergeActionMixin, admin.ModelAdmin):
merge_field = "name"
list_display = ('name', 'code', )
search_fields = ('name', 'code', )
... |
10,734 | c0a03a67c5460974f3fa61d15493c26adadcea4f | from excile_framework.templator import render
class Index:
def __call__(self, request):
return '200 OK', render('index.html', date=request.get('date', None),
python_ver=request.get('python_ver', None),
btc_to_usd=request.get('btc_to_usd', Non... |
10,735 | f1c350b87761355ad44be4703c07596361f2bf2b | from kaa.filetype import filetypedef
class FileTypeInfo(filetypedef.FileTypeInfo):
FILE_EXT = {'.md'}
@classmethod
def get_modetype(cls):
from kaa.filetype.markdown.markdownmode import MarkdownMode
return MarkdownMode
|
10,736 | e8cdf9212f8207dc4513acb5958508f61ed29a88 | """
K-means.
@author Aaron Zampaglione <azampagl@my.fit.edu>
@course CSE 5800 Advanced Topics in CS: Learning/Mining and the Internet, Fall 2011
@project Proj 03, CLUSTERING
@copyright Copyright (c) 2011 Aaron Zampaglione
@license MIT
"""
# Dirty hack for Python < 2.5
import sys
sys.path.append('../../')
from cluster... |
10,737 | f0e6800c7f98e191c28523f6d64263aeee647054 | import pygame
import random
import time
pygame.init()
color_list = {"red": (255, 0, 0), "blue": (0, 0, 255), "green": (0, 255, 0), "yellow": (0, 0, 0)}
class Cell:
def __init__(self, color, x, y):
self.color = color
self.x = x
self.y = y
self.cell = 0
self.clicked = Fals... |
10,738 | a42c6bacdd823c7a5c095efe2e7d161380e0ac5c |
from color_generators import ColorGenerators
class CustomEffects():
def __init__(self, pixel_strand):
self.pixels = pixel_strand
def flash_effect(self, spacing=1, cycle=1):
# flash every other pixel
cg = ColorGenerators()
for times in range(cycle):
#color = cg.ra... |
10,739 | 58c4e5e19166ee3f37a01fb41e877c00f0674859 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'C:\Users\alca0\Documents\Python_Scripts\dicom_ui\dicom_ui_design.ui'
#
# Created by: PyQt5 UI code generator 5.10.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object)... |
10,740 | dd5c76f720fb71b715e4ec6ae4faf3a4e88c9c26 | """Easy to use dialogs. Modified to avoid talking to the window server.
Only Message() is supported, and prints to stdout. The other routines will
throw a NotImplementedError exception.
Message(msg) -- display a message and an OK button.
AskString(prompt, default) -- ask for a string, display OK and Cancel buttons.
... |
10,741 | bf0a11384e1e4ed350c6406744e89de43af98183 | import grid as g
import input as i
import sound as s
import pygame, os, math
class Timer:
def __init__(self):
self.timeStart = 0
self.timeFinish = 0
def start(self):
"""
Stores the current time in seconds.
"""
self.timeStart = pygame.time.get_ticks()
def fi... |
10,742 | 42c002086f0d94cc52e683019a496451e3f35623 | #Python learning exercises
# functions
def echo(thing):
return thing
def swap(n1, n2):
return n2, n1
def main_function():
print"testing echo('marco'): ", echo('marco')
print"testing swap('1, 2'):",swap('1, 2')
#Arithmetic functions
def reverse(x):
return -x
def main_arithmetic():
print "test reverse... |
10,743 | 591448b76980f48afb20e4001b1d7f6198bc80ba | # _*_ coding: utf-8 _*_
# 树的先序,中序,后序递归遍历
class Tree(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def convert(self, root):
_array = [[]] * 3
self.xian(self, root, _array[0])
self.zhong(self, root, _array[1])
s... |
10,744 | 85b8bb4036ed125f5aa128c99c4fb7c366679b61 | #!/usr/bin/python3.6
# -*- coding: utf-8 -*-
import collections
import math
import pdb
import random
import time
from itertools import repeat
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Function as F
def _ntuple(n):
def parse(x):
if isinstance(x, collections.Iterab... |
10,745 | 62eac6c0b7535055320d3b5a07db036dee37d90e | # Stub file
from __future__ import absolute_import
from tsr.kin import * |
10,746 | d61bf7d08a2914fa6a530d9511e9c78409ae99b7 | import json
from unittest.mock import patch
import pytest
from workspace.techsupport.jobs import (
out_of_office_off,
out_of_office_on,
out_of_office_status,
)
@pytest.fixture
def config_path(tmp_path):
yield tmp_path / "test_ooo.json"
@pytest.mark.parametrize(
"config,message",
[
... |
10,747 | b2a0a080663b75490332c6dd1b8471ca06aa3001 | Testing creation of file on new branch MyBranch
|
10,748 | e82b1cf4d234e1b6cda9482cb3239ab5db8cf32c | class Solution:
def equationsPossible(self, equations: 'List[str]') -> 'bool':
def find(val):
if dic[val] != val:
dic[val] = find(dic[val])
return dic[val]
equations = sorted(equations, key=lambda x: x[1] =='!')
dic = {}
for code in range(or... |
10,749 | a95e4b82d19627fd808927083ddda5f3fb8ba7e7 | from wtforms import Form, StringField, PasswordField, SubmitField, validators
class RegisterFormContent(Form):
mobile = StringField('mobile', [validators.Length(min=7, max=11)])
password = PasswordField('New Password', [validators.DataRequired(), validators.EqualTo('confirm', message='Passwords must match')])... |
10,750 | b2e246bbe21c96e0b194c265863d81afc39c7663 | # -*- coding: utf-8 -*-
"""GP_project_Colab
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1MGNXlydcYgFRoAd6NC_EZtLdbv5MM7kk
# New Section
"""
from google.colab import drive
drive.mount('/content/drive')
!pip install dominate
# Commented out IPytho... |
10,751 | 18c70bb0c10a640a883a41d0267dee503075e900 | from typing import Dict, List
from profileNode import Profiler, RacketDefineError, RacketDefineSucess, genesis
from evalexpr import evalexpr, lam
from printing import pttyobj
from structops import makestruct
def handle_define(gc, code, pf_node: Profiler = genesis()):
maybename = code[1]
if code[0] == "define... |
10,752 | 2430d824f20c0fe2ad1789b9aeb51fe8a124c3e7 | # routines for multiplying matrices
from __future__ import print_function
import numpy
def mult_Ax(A, x):
""" return the product of matrix A and vector x: Ax = b """
# x is a vector
if not x.ndim == 1:
print("ERROR: x should be a vector")
return None
N = len(x)
# A is square, w... |
10,753 | 79177baef4e5d639efe409e743d4d694f8c03810 | from tkinter import *
from mainconnection import *
def complen():
root = Tk()
root.geometry("650x500")
root.title("Complain")
f1 = Frame(root)
f1.grid(row=0, column=0)
f2 = Frame(root)
f2.grid(row=1, column=0)
Label(f1, text=" COMPLAIN REGISTRATION FORM", anchor="c").pack()
l1... |
10,754 | 00414ab2914473be6366dca65190a2a7619f3ad4 | from django.urls import path, re_path
from apps.main import views
urlpatterns = [
path('', views.ProductList.as_view(), name='index'),
re_path(r'^catalog/(?P<filter>.+)/$',
views.ProductList.as_view(),
name='catalog_filter'),
re_path(r'^detail/(?P<pk>\d+)/$',
views.P... |
10,755 | 14895c0b90b86eecb4dc386aa96bb48f570495b6 | from sys import argv
from itertools import islice
with open('bakery.csv') as f:
if len(argv) == 1:
for line in f:
print(line.strip())
elif len(argv) == 2:
for line in islice(f, int(argv[1]) - 1, None):
print(line.strip())
elif len(argv) == 3:
for line in isli... |
10,756 | 343c608ad0db774f05adf3204f3cd673bf07304a | # PSDLayerExporter
# Copyright (c) 2016 Under the Weather, LLC
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software
# and associated documentation files (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, m... |
10,757 | 9c8d2c2c32c6846e75983038479f58c4043bc101 | lst_1 = [1, 2, 3, 4, 5] * 8
lst_2 = [2, 1, 2, 3, 2, 4, 2, 5] * 5
lst_3 = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5] * 4
def solution(answers):
result_1 = 0
result_2 = 0
result_3 = 0
for i in range(len(answers)):
temp = i % 40
if answers[i] == lst_1[temp]:
result_1 += 1
if answe... |
10,758 | 611248fe498ea77260416fa1d534f23196856a8e | #!/usr/bin/env python
#import json module
import json
# variable 'f' is set as file stream (handle)
f = open('era.json', 'r')
# variable 'json_string' is set to file content
json_string = f.read()
# variable 'original' is assigned the result of applying json.loads to json_string (makes the program read the contents ... |
10,759 | 0af5448823bdf2e5509a9b000716bd773acb685f | '''
Demonstrate how easy it is to use GameWindow, and show contents of
DummyScene.
'''
from demoscenes import DummyScene
from app import GameWindow
if __name__ == '__main__':
game = GameWindow(title='[Demo] Headcrabs!!!', screen_size=(640, 480))
game.register_scene(DummyScene(), 'dummy')
game.start()
|
10,760 | 5409acd57a2c2aa2717511bfbb43f952097810e6 | #!/usr/bin/env python
"""Command line program to access build information.
"""
__author__ = 'Paul Landes'
from typing import List, Dict, Union, Iterable, Tuple
from dataclasses import dataclass, field
import logging
import re
import sys
import json
import plac
from pathlib import Path
logger = logging.getLogger(__n... |
10,761 | 85bfa30cc8620ba6dd289406d46c499c509eb2ea | from sqlalchemy import create_engine
import pandas as pd
import csv
import psycopg2
# setup psycopg2 and engine
try:
conn = psycopg2.connect("dbname='dbbuurt' user='buurtuser' host='localhost' password='123456'")
print("Database connection established")
except:
print("Database connection failed")
cur = co... |
10,762 | 4ac9c79ad4ed797071ef4e3275bc233dfb391d2e | # Generated by Django 3.0.3 on 2020-08-09 05:37
from django.db import migrations, models
def forwards_func(apps, schema_editor):
City = apps.get_model("job", "City")
db_alias = schema_editor.connection.alias
City.objects.using(db_alias).bulk_create([
City(name="Bangladesh,Barishal"),
City(... |
10,763 | b6c56f19132de32555a077482badd27c00e48c43 | from bs4 import BeautifulSoup
import requests
import random
import re
import nltk
from py2casefold import casefold
from nltk.corpus import stopwords, words
"""
Utility Crawler class which is called for all the different
types of crawler (i.e. DFS, BFS or Focused) This class is open to customization
based on the argue... |
10,764 | f09f17e2e7f3d445e0732dd3da188c924ce8ebca | import os
# allFiles=[]
# def begin_new_listfile():
# global allFiles
# allFiles=[]
# return
def list_all_fm_file(filepath,suffix):
# global allFiles
allFiles = []
files = os.listdir(filepath)
for fi in files:
fi_d = os.path.join(filepath,fi)
if os.path.isdir(fi_d):
list_all_fm_file(fi_d,suffix)
else... |
10,765 | ed455c529a02d7f55d847ae4d94e1ecdcdf72fd2 | import io
from unittest import TestCase
from unittest.mock import patch
from game import character_attack_description
class TestCharacterAttackDescription(TestCase):
@patch('random.randint', side_effect=[0])
@patch('sys.stdout', new_callable=io.StringIO)
def test_character_attack_description_sorcerer_lv1(... |
10,766 | a601ae266064fcb3880194241f2043b7e77af1b0 | saarc=["Bangladesh","India","Nepal","Afganistan","Pakistan","Bhutan","Srilanka"]
for country in saarc:
print(country,"is a member of saarc") |
10,767 | bcad482473e44de5d5a5de6e06ab5d2548c1acb0 | #!/usr/bin/python
lk = [1,23]
s = lk
def f():
return 1, 2,3
s, = f()
print(s) |
10,768 | 811d9b75181a1ec8f22cf9ff349d2de1d3345737 | '''
Input: a List of integers where every int except one shows up twice
Returns: an integer
'''
# not really sure why this isn't passing the test.
def single_number(arr):
# Your code here
cursor = 0
while cursor != len(arr):
# check if the current element is the same as the next element if so
... |
10,769 | 21e5ef6b455e08a1bfcf9e0325b9e4d2a3300b33 | """
# DAO 클래스
data access object
데이터베이스의 데이터에 접근하기 위한 역활 담당
MVC 패턴에서는 서비스클래스와 DAO 객체로 나눠 프로그래밍함
DAO : 주로 DB를 사용해서 데이터를 조죄하거나 조작하는 기능 담당
서비스 : DB 작업전 데이터를 처리하는 기능을 담당
성적처리 프로그램에서의 MVC
Model (데이터) : VO 클래스
View (데이터 출력/입력) : 화면출력
Controller (흐름제어) : service + dao
"""
class Student:
def __... |
10,770 | 75f91c09fa7813e687ea55f14214d96f21e5cb39 | #!/home/sourabh/anaconda3/bin/python
"""
The reducer script for the same job.
It runs computation on the data received by the mapper.
"""
import sys
import csv
def reducer():
"""
MapReduce Reducer.
"""
reader = csv.reader(sys.stdin, delimiter='\t')
writer = \
csv.writer(
sys.s... |
10,771 | 1c2846b0921caabe71ea220a1f798117f729419d | # --- Day 16: Ticket Translation ---
# As you're walking to yet another connecting flight, you realize that one of the legs of your re-routed trip coming up is on a high-speed train. However, the train ticket you were given is in a language you don't understand. You should probably figure out what it says before you ge... |
10,772 | ae526637c324284dbcd9c29eacd1655c497f83cc | from bayes import Bayes
def die_likelihood(roll, die):
"""
Args:
roll (int): result of a single die roll
die (int): number of sides of the die that produced the roll
Returns:
likelihood (float): the probability of the roll given the die.
"""
if roll in range (1, die + 1):... |
10,773 | e7ce25be6e64a0a60e3662856c7819f588fc2feb |
from south.db import db
from django.db import models
from lfs.criteria.models import *
class Migration:
def forwards(self, orm):
# Adding model 'WeightCriterion'
db.create_table('criteria_weightcriterion', (
('operator', models.PositiveIntegerField(_(u"Operator"), null=Tr... |
10,774 | ac5b137a8c40155282fd5cf3da90aef09878bc44 | from flask import jsonify, request
from app import db, app
from app.models import Participant, Event, Location, Enrollment
@app.route("/locations/", methods=["GET"])
def api_get_locations():
""" GET /locations/ – выводит список городов или локаций, пока выведите [] """
locations = []
return jsonify(locati... |
10,775 | 99e933a8e445d0d09db294f962f038b7e1f10a1b | class Monstruo():
def __init__(self, nombre:str,debilidades:list,resistencia:list,descripcion:str):
self.nombre = nombre
self.debilidades = debilidades
self.resistencia = resistencia
self.descripcion = descripcion
self.comentario = ""
def getNombre(self):
return ... |
10,776 | 8f2f955b45a4ec7a910cabc11ae3c58f50024c53 | __author__ = 'Peiman'
import nltk
import re
import time
exampleArray = ['the incredibly intimidating NLP scares people away who are sissies']
def processlanguage():
try:
for item in exampleArray:
tokenized = nltk.word_tokenize(item)
tagged = nltk.pos_tag(tokenized)
pr... |
10,777 | 24bd0e17144177ec5635e1583a5dc8f044139f79 | #!/usr/bin/python
import re, sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), "requests-2.5.1"))
import requests
class BadHTTPCodeError(Exception):
def __init__(self, code):
print(code)
class GaanaDownloader():
def __init__(self):
self.urls = {
'search' : 'http://ga... |
10,778 | f94dbb3a4a6964c5b39147ecb11b4dd2ffff2423 | # -*- coding:utf-8 -*-
from base import BaseHandler
class ErrHandler(BaseHandler):
def get(self):
self.render('error.html', status_code=404)
|
10,779 | d7808235d83bc603ac76522b22980075a8863539 | from flask import Flask, render_template,request, session, redirect, url_for
from pymongo import MongoClient
#from flask.ext.pymongo import PyMongo
from reply_rec import botResponse, chat_history
from flask_pymongo import PyMongo
from flask_login import logout_user
import bcrypt
app = Flask(__name__)
#client=MongoCli... |
10,780 | 2dd8181a26c6f415245c5fad15b88fe8e971280a | # -*- coding: utf-8 -*-
"""
Zerodha Kite Connect - candlestick pattern scanner
@author: Mayank Rasu (http://rasuquant.com/wp/)
"""
from kiteconnect import KiteConnect, KiteTicker
import pandas as pd
import datetime as dt
import os
import time
import numpy as np
import sys
cwd = os.chdir("/home/rajkp... |
10,781 | 016ba775ac09f6ac546f298eca92a01307a391e0 | import random
from random import choice
import discord
import requests
from bs4 import BeautifulSoup
from discord.ext import commands
class Fun(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def ping(self, ctx):
"""
Pong!
... |
10,782 | 7e801fc8bdf3a42f097f38ee5303dd690f43a8f4 | import numpy as np
import yaml
import matplotlib.pyplot as plt
import scipy.signal
import glob
def plotJointState(path, test_joint):
JSPosition_PATH = path['robotCalibration'] + 'test/test_with_700g_payload/jsposition.yaml'
TIME_PATH = path['robotCalibration'] + 'test/test_with_700g_payload/js_time.yaml'
... |
10,783 | 63d32511f0147afc902aad0e81fcbe9de3b63ade | """
大乐透和双色球随机选号程序
Version: 0.1
Author: 姚春敏
Date: 2021-08-18
"""
from random import randrange, randint, sample
# import tkinter
def display(balls):
"""
输出列表中的号码
"""
if s == 2:
for index, ball in enumerate(balls):
if index == len(balls) - 2:
print('|', end=' ')
... |
10,784 | d86919d7d0de021a542df878f78f5f47473b4fc6 | from token_auth.authentication import BaseTokenAuthBackend
from .models import Candidate
class CandidateTokenAuthBackend(BaseTokenAuthBackend):
model_class = Candidate
|
10,785 | 747df4f70f9217b29a4dc43f8761b0678904bd7e | from item_category import ItemCategory
class BackstagePass(ItemCategory):
def update_expired(self, item):
item.quality = 0
def update_quality(self, item):
self.increase_quality(item)
if item.sell_in <= 10:
self.increase_quality(item)
if item.sell_in <= 5:
... |
10,786 | 979ca3e3115370af0a0e04baf5a66c108af174c2 | def int_sp():
return map(int, input().split())
def li_int_sp():
return list(map(int, input().split()))
def trans_li_int_sp():
return list(map(list, (zip(*[li_int_sp() for _ in range(N)]))))
import pdb
import math
ABC = li_int_sp()
gcds = math.gcd(math.gcd(ABC[0],ABC[1]), ABC[2])
pdb.set_trace()
out... |
10,787 | 0ddded1a605c7d9a8a22de7f818c699236ac158e |
for y in range(3):
for x in range(1,4):
print(x,end=" ")
print()
print("------------------------")
for x in range(3):
for y in range(3,0,-1):
print(y,end=" ")
print()
print("------------------------")
for x in range(3):
for y in range(3):
print(x+1,end=" ")
print()
pri... |
10,788 | df05b986a350a232e2287c8bd158323dd7e9d03f | class Solution:
def letterCasePermutation(self, S: str) -> List[str]:
S = S.lower()
n = len(S)
ans = []
def perm(i, res):
if i < n:
perm(i+1, res + S[i])
if S[i].islower(): perm(i+1, res + S[i].upper())
else:
ans... |
10,789 | 5a2474543d5d2607392d728b8206b66003c89efb | import os
print("Hello World!")
exec(open("./tictactoe.py").read())
#exec(open("./rainbow.py").read())
#exec(open("./vuemeter.py").read()) |
10,790 | d1ff1bae4418429288c28e20478f7318696757d5 | # Generated by Django 2.2.1 on 2019-05-26 15:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0003_profile_files'),
]
operations = [
migrations.AlterField(
model_name='profile',
name='files',
... |
10,791 | 082bc32f7fa00d1f07b2a97a56e1a6fdebce7cab | from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
class Account(models.Model):
user = models.OneToOneField(User)
karma = models.IntegerField(default=0)
def __unicode__(self):
return self.user.usernam... |
10,792 | db8ff393a3593ae1b056d6e6bca027126dd467af | import re
import sys
from PyQt5.QtWidgets import QApplication, QDialog, QInputDialog
from PyQt5 import QtCore, QtGui, QtWidgets
from collections import *
import copy
"""
LOLCode Interpreter Class
"""
class Interpreter(QtCore.QObject):
class Lexeme: # constructor for lexeme
def __init__(self, regex, type):
... |
10,793 | 55ae62165f757289721c3796b3aaa2206ff3ad2a | #!/usr/bin/python3
import statistics as stats
class Encoder:
def __init__(self, unique_values, is_categorical):
"""
Constructor of an Encoder using one-hot-encoding
"""
self.is_categorical = is_categorical
self.is_binary = len(unique_values) == 2
self.unique_value... |
10,794 | 7ccb6332f248137a4a0738e8581f376e782a6e26 | from alg3 import *
g=Graph()
a1=g.addVertex(1)
a2=g.addVertex(2)
a3=g.addVertex(3)
a4=g.addVertex(4)
a5=g.addVertex(5)
a6=g.addVertex(6)
a7=g.addVertex(7)
g.addEdge(a1,a2,'x1')
g.addEdge(a2,a3,'y1')
g.addEdge(a3,a4,'z1')
g.addEdge(a2,a5,'x1')
g.addEdge(a6,a5,'z1')
g.addEdge(a7,a5,'y1')
(F,Z,H1,H2,flower1,double1,fore... |
10,795 | 9e0d427bcfa735d90cf3719744fc505a849f1210 | import numpy as np
from scipy.optimize import leastsq, curve_fit
import matplotlib.pyplot as plt
def lorentzian(width, central, height, x):
return height * width / (2 * np.pi) / ((x - central)**2 + width**2 / 4)
def error_func(p, x, y):
return lorentzian(*p, x) - y
def find_r_squared(f, p, x, y):
res ... |
10,796 | fcfe33b6b2984e07821d6a2f246d3eb65a7172f2 | from .deposit import Deposit
from .withdrawal import Withdrawal
from .transfer import Transfer
from .get_balances import GetBalances
|
10,797 | a95b3e1e0728e54f15872b4ba064cad6761d460d | import pytest
import brownie
@pytest.fixture(autouse=True, scope="module")
def set_approval(adam, beth, token):
token.approve(beth, 10 ** 18, {"from": adam})
def test_transferfrom_descreases_owner_balance(adam, beth, token, accounts):
owner_initial_balance = token.balanceOf(adam)
token.transferFrom(adam... |
10,798 | 4a3b711331c1cbaa6152f3a1900a4dd3bbe247e3 | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 29 21:28:10 2016
downsample pacbio data by assign each read a probablity based on the read length
@author: Nan
"""
from Bio import SeqIO
import numpy as np
from scipy.stats import lognorm
import matplotlib.pyplot as plt
import random
random.seed(0)
target_coverage = 15
... |
10,799 | 7f46abbaa67f5f458fbb5ecb73c6ddbc37bfd11e | from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileRequired, FileAllowed
from wtforms import PasswordField, BooleanField, SubmitField
from wtforms.fields.html5 import EmailField
from wtforms.validators import DataRequired
class PhotoForm(FlaskForm):
photo = FileField('Add image', validators... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.