index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
1,000 | 153a33b85cf8b3ef9c742f05b460e94e0c684682 | #Author: AKHILESH
#This program illustrates the advanced concepts of inheritance
#Python looks up for method in following order: Instance attributes, class attributes and the
#from the base class
#mro: Method Resolution order
class Data(object):
def __init__(self, data):
self.data = data
def getData(s... |
1,001 | e207063eb3eb1929e0e24b62e6b77a8924a80489 | # -*- coding: utf-8 -*-
"""
Created on Sat Jul 18 20:24:53 2020
@author: filip
"""
import re
texto = "Muito além, nos confins inexplorados da região mais brega da Borda Ocidental desta Galáxia, há um pequeno sol amarelo e esquecido. Girando em torno deste sol, a uma distancia de cerca de 148 milhões de quil... |
1,002 | 5d7080f2778133d1938853512ca038edcf7c0dc4 | from Products.CMFPlone.utils import getFSVersionTuple
from bda.plone.ticketshop.interfaces import ITicketShopExtensionLayer
from plone.app.robotframework.testing import MOCK_MAILHOST_FIXTURE
from plone.app.testing import FunctionalTesting
from plone.app.testing import IntegrationTesting
from plone.app.testing import PL... |
1,003 | 646f6a0afc3dc129250c26270dda4355b8cea080 | #!/usr/local/bin/python3.3
'''
http://projecteuler.net/problem=127()
abc-hits
Problem 127
The radical of n, rad(n), is the product of distinct prime factors of n. For example, 504 = 23 × 32 × 7, so rad(504) = 2 × 3 × 7 = 42.
We shall define the triplet of positive integers (a, b, c) to be an abc-hit if:
GCD(a, b) = ... |
1,004 | 3079fdbe6319454ad166d06bda5670554a5746ee | # len(): tamanho da string
# count(): conta quantas vezes um caractere aparece
# lower(), upper()
# replace(): substitui as letras por outra
# split(): quebra uma string a partir dos espacos em branco
a = len('Karen')
print(a)
b = 'Rainha Elizabeth'.count('a')
print(b)
c = 'karen nayara'.replace('a','@')
print(c)
d = ... |
1,005 | 2cdcd6976a1ec99b927adcedc48c36bbda1b4e18 | """ Generate test pads for padder. """
# usage: python gen.py > pads.txt
import random
pad = ""
count = 0
# The pad chars MUST match the character set used by padder.
# See the 'characters' variable in 'main.hpp' for more
# information.
chars = "abcdefghijklmnopqrstuvwxyz0123456789-"
print "#", "Pad"
while count... |
1,006 | d68bd9c90a106a9eac767607ad77bdd84d0f18d2 | #-*- coding = utf-8-*-
#@Time : 2020/6/26 11:02
#@Author :Ella
#@File :app.py
#@Software : PyCharm
import time
import datetime
from flask import Flask,render_template,request #render_template渲染模板
app = Flask(__name__) #初始化的对象
#路由解析,通过用户访问的路径,匹配想要的函数
@app.route('/')
def hello_world():
return '你好'
#通过访问路径,获取用户的... |
1,007 | 6da828a797efac7c37723db96a2682e960c317b5 | from setuptools import setup
def readme():
with open('README.rst') as f:
return f.read()
setup(name = "keputils",
version = "0.2.1",
description = "Basic module for interaction with KOI and Kepler-stellar tables.",
long_description = readme(),
author = "Timothy D. Morton",
author_email... |
1,008 | 9c6bb885c05ee13a283b09861a5aa7c5e62677cb | #!/usr/bin/python
def check(n):
if n == 0 :
print "neither Positive nor Negative"
if n < 0 :
print "Negative"
if n > 0 :
print "Positive"
print "10 is ", check(10)
print "-5 is ", check(-5)
print "0 is ", check(0) |
1,009 | 93e8e9fc4f0503dfc3243bef5ab8261a4cdfc296 | #!/usr/bin/env python
# encoding: UTF-8
'''
Script to select current version for a given soft (python, ruby or java).
'''
import os
import re
import sys
import glob
import getopt
# fix input in Python 2 and 3
try:
input = raw_input # pylint: disable=redefined-builtin,invalid-name
except NameError:
pass
cl... |
1,010 | 55c2bf914a77c573d1b6835f54c82921d9fa6ad6 | from ED63RDScenarioHelper import *
def main():
SetCodePage("ms932")
CreateScenaFile(
FileName = 'C2219 ._SN',
MapName = 'Ruan',
Location = 'C2219.x',
MapIndex = 84,
MapDefaultBGM = "ed60015",
Flags ... |
1,011 | ecbca04a58c19469e63ee2310e2b2f6b86c41199 | # -*- coding: utf-8 -*-
"""
Created on Wed May 8 15:05:51 2019
@author: Brian Heckman and Kyle Oprisko
"""
import csv
"""this file opens a csv file created in the csv creator class. The main purpose of this class is to
normalize the data in the csv file, so that it can be read by the neural network.
"""
... |
1,012 | 9a7994a1e51c9cf7fe7d8b50ab26fa3d789fc8e5 | #
# tests/middleware/test_static.py
#
import pytest
import growler
from pathlib import Path
from unittest import mock
from sys import version_info
from growler.middleware.static import Static
@pytest.fixture
def static(tmpdir):
return Static(str(tmpdir))
def test_static_fixture(static, tmpdir):
assert isin... |
1,013 | a319ebb05e9034f19aef39bd46830c8a607ed121 | animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
The animal at 1.
The third (3rd) animal.
The first (1st) animal.
The animal at 3.
The fifth (5th) animal.
The animal at 2.
The sixth (6th) animal.
The animal at 4.
|
1,014 | cc6cef70381bb08247720ec32b7e8fe79ed7123d | #!/usr/bin/python
import sys
OPEN_BRACES = ['{', '(', '[']
CLOSE_BRACES = ['}', ')', ']']
def match_paranthesis (s, pos):
stack = []
for i,c in enumerate(s):
if not c in OPEN_BRACES and not c in CLOSE_BRACES:
continue
if c in OPEN_BRACES:
stack.append((i, c))
... |
1,015 | ddaba7a8b53072da36224dd4618696ebf0e9a4e4 | from __future__ import print_function
import os
import shutil
import pymake
import flopy
# set up paths
dstpth = os.path.join('temp')
if not os.path.exists(dstpth):
os.makedirs(dstpth)
mp6pth = os.path.join(dstpth, 'Modpath_7_1_000')
expth = os.path.join(mp6pth, 'examples')
exe_name = 'mp7'
srcpth = os.path.join(... |
1,016 | da3be0d3b815e11d292a7c7e8f5ce32b35580f98 | # Let's look at the lowercase letters.
import string
alphabet = " " + string.ascii_lowercase
|
1,017 | 299432b095f16c3cb4949319705800d06f534cf9 | from __future__ import with_statement # this is to work with python2.5
from pyps import workspace, module
def invoke_function(fu, ws):
return fu._get_code(activate = module.print_code_out_regions)
if __name__=="__main__":
workspace.delete('paws_out_regions')
with workspace('paws_out_regions.c',name='paws_ou... |
1,018 | c1bb7b579e6b251ddce41384aef1243e411c5d0e |
# coding: utf-8
# ## Estimating Travel Time
#
#
# The objective of this document is proposing a prediction model for estimating the travel time of two
# specified locations at a given departure time. The main idea here is predicting the velocity of the trip. Given the distance between starting and ending point of t... |
1,019 | ae84b449c8919f14954633b14993e6291501bc24 | import requests
def login(username, password):
data = {'login':username,'pwd':password,'lang':''}
r = requests.post('http://dms-pit.htb/seeddms51x/seeddms/op/op.Login.php', data=data, allow_redirects=False)
if r.headers['Location'] == '../out/out.Login.php?msg=Error+signing+in.+User+ID+or+password+incorrec... |
1,020 | 9aa54f1259aceb052cfba74cedcfadfe68778ebd | from IPython import embed
from selenium import webdriver
b = webdriver.Firefox()
embed()
|
1,021 | 0bfb089556bfa253bf139f03cd3079ced962d858 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
from sbpy.data import Phys
from sbpy import bib
@pytest.mark.remote_data
def test_from_sbdb():
""" test from_horizons method"""
# query one object
data = Phys.from_sbdb('Ceres')
assert len(data.table) == 1
# query se... |
1,022 | 368151a134f987ed78c8048521137672530b5cce | # KeyLogger.py
# show a character key when pressed without using Enter key
# hide the Tkinter GUI window, only console shows
import Tkinter as tk
def key(event):
if event.keysym == 'Escape':
root.destroy()
print event.char, event.keysym
root = tk.Tk()
print "Press a key (Escape key to exit):"
root.bi... |
1,023 | 70aba6c94b7050113adf7ae48bd4e13aa9a34587 | import typ
@typ.typ(items=[int])
def gnome_sort(items):
"""
>>> gnome_sort([])
[]
>>> gnome_sort([1])
[1]
>>> gnome_sort([2,1])
[1, 2]
>>> gnome_sort([1,2])
[1, 2]
>>> gnome_sort([1,2,2])
[1, 2, 2]
"""
i = 0
n = len(items)
while i < n:
if i and items[i] < items[i-1]:
items[i], i... |
1,024 | 1ead23c6ea4e66b24e60598ae20606e24fa41482 | # SPDX-FileCopyrightText: 2019-2021 Python201 Contributors
# SPDX-License-Identifier: MIT
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path ... |
1,025 | 8fee548466abf6d35ea180f8de4e52a9b8902d3f | import os
import math
from collections import defaultdict
__author__ = 'steven'
question='qb'
fs={'t1','small.in','large'}
def getmincost(n,c,f,x):
t=0.0
for i in range(0,n):
t+=1/(2+f*i)
t=t*c
t+=x/(2+f*n)
ct=getmincostnshift(n,c,f,x)
return min(t,ct);
def getmincostnshift(n,c,f,x):
... |
1,026 | f2e6d23e6d8c5aa6e80a652dc6cb8bda45824d0c | """Code for constructing and executing Tasks"""
from bcipy.tasks.rsvp.calibration.alert_tone_calibration import RSVPAlertToneCalibrationTask
from bcipy.tasks.rsvp.calibration.inter_sequence_feedback_calibration import (
RSVPInterSequenceFeedbackCalibration
)
from bcipy.tasks.rsvp.calibration.calibration import RSVP... |
1,027 | e59e60b0a4b7deca9c510bd6b9c58636c6d34c80 |
l={1,2,3,4}
try:
print(l)
s=len(l)
if s>5:
raise TypeError
print(d[2])
except TypeError:
print("Error!!!length should be less than or equals to 5")
except NameError:
print("index out of range")
else:
for i in l:
print(i)
finally:
print("execution done!!!!!!") |
1,028 | c0503536672aa824eaf0d19b9d4b5431ef910432 | #!/usr/bin/env python
# encoding: utf-8
import os
import argparse
import coaddBatchCutout as cbc
def run(args):
min = -0.0
max = 0.5
Q = 10
if os.path.isfile(args.incat):
cbc.coaddBatchCutFull(args.root, args.incat,
filter=args.filter,
... |
1,029 | 2e140d1174e0b2d8a97df880b1bffdf84dc0d236 | from helper.logger_helper import Log
from helper.mail_helper import MailHelper
import spider.spider as spider
from configuration.configuration_handler import Configuration
from configuration.products_handler import ProductsHandler
if __name__ == "__main__":
logger = Log()
conf = Configuration('configuration/co... |
1,030 | dbb66930edd70729e4df7d3023e83a6eae65cccd | #!/usr/bin/env python
def main():
import sys
from pyramid.paster import get_appsettings
from sqlalchemy import engine_from_config
from pyvideohub.models import ScopedSession, Base
config_file = sys.argv[1]
settings = get_appsettings(config_file)
engine = engine_from_config(settings, 's... |
1,031 | e288403cb310bb7241b25e74d1b5bcc63967128c | """Note: AWS Glue split from spark since it requires different test dependencies."""
from tests.integration.backend_dependencies import BackendDependencies
from tests.integration.integration_test_fixture import IntegrationTestFixture
aws_glue_integration_tests = []
deployment_patterns = [
# TODO: The AWS_GLUE dep... |
1,032 | 8fd74287fbc653ea3ed4aa76a272486aa29185cf | # !/usr/bin/python
# sudo mn --custom _mininet_topo.py --topo mytopo,5
# sudo mn --custom _mininet_topo.py --topo mytopo,3 --test simpletest
# or just run this python file
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.util import dumpNodeConnections
from mininet.log import setLogLevel
fro... |
1,033 | 0e112ecfd4ccf762234dff564dd6f3987418dedd | # Start the HTML and Javascript code
print '''
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["treemap"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
'''
... |
1,034 | ed66e8028d653cf6b7ea4703fef5a658665c48db | # -*- coding: utf-8 -*-
# DATE 2018-08-21
# AUTHER = tongzz
#
import MySQLdb
from Elements.LoginElements import *
import datetime
import sys
class Tradepasswd():
def __init__(self):
self.db_config={
'host': '172.28.38.59',
'usr': 'mysqladmin',
'passwd': '12... |
1,035 | 81a1fbd13b06e4470bfbaa0d1716d5301e1a4b36 | def readint(): return int(raw_input())
T = readint()
for t in xrange(T):
N = int(raw_input())
res = 0
sum = 0
min = 1000000
for i in raw_input().split():
r = int(i)
res ^= r
sum += r
if min > r: min = r
if res == 0:
sum -= min
print "Case #%d: %s" % (t + 1, sum)
else:
print "Case ... |
1,036 | 90fc6e37e3988a2014c66913db61749509db2d53 | import os
class Idea:
def __init__(self, folder):
self.folder = folder
def name(self):
return "jetbrains-idea"
def cmd(self):
return "intellij-idea-ultimate-edition %s" % self.folder
|
1,037 | d2e3ac490ce5fdc20976567fa320a9e6a53cbe34 | # -*- coding: utf-8 -*-
"""
===================================
Demo of DBSCAN clustering algorithm
===================================
Finds core samples of high density and expands clusters from them.
"""
import scipy as sp
import numpy as np
from scipy import spatial
print(__doc__)
from sklearn.cluster import D... |
1,038 | 166a1dfbd3baf766230080361d98648ec0a64455 | #coding=utf8
"""
Created on Thu Feb 20 00:53:28 2020
@author: Neal LONG
"""
import json
import requests
fake_header = { "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36",
"Accept":"text/html,application/xhtml+xml,... |
1,039 | 9ef5d57d536f5c88f705b1032cc0936e2d4cd565 | from Shapes import *
c1 = Circle(5)
r1 = Rectangle(3,2)
c2 = Circle(3)
c3 = Circle(1)
r2 = Rectangle(1,1)
listShapes = [c1,r1,c2,c3,r2]
for item in listShapes:
print(item.toString())
print("Area: " + str(item.area()))
print("Perimeter: " + str(item.perimeter()))
|
1,040 | 813d27e8f9c1a416dab2f891dd71e4791bb92dbb | import sys
import pytest
from presidio_evaluator.evaluation import Evaluator
from tests.conftest import assert_model_results_gt
from presidio_evaluator.models.flair_model import FlairModel
@pytest.mark.slow
@pytest.mark.skipif("flair" not in sys.modules, reason="requires the Flair library")
def test_flair_simple(sm... |
1,041 | cceda9a8a0188499ae0aa588701bb8104b5ed313 |
from pymongo import MongoClient, GEOSPHERE, GEO2D
import os, sys, json, pprint
sys.path.insert(0, '../utils')
import path_functions
client = MongoClient( 'localhost', 27017 )
db = client[ 'nfcdata' ]
json_files_path_list = path_functions.get_json_files('../../ftp-data/geojson-files/quikscat-l2b12')
for json_fil... |
1,042 | 65d5cee6899b0b75474e3898459bf2cfa8b3635b | def solve(bt):
if len(bt) == n:
print(*bt, sep="")
exit()
for i in [1, 2, 3]:
if is_good(bt + [i]):
solve(bt + [i])
def is_good(arr):
for i in range(1, len(arr)//2+1):
if arr[-i:] == arr[-(i*2):-i]:
return False
return True
if __name__ == "__main__":
n = int(input())
sol... |
1,043 | 6be285f9c48a20934c1846785232a73373c7d547 | ##armstrong number##
##n= int(input('enter a number '))
##a=n
##s=0
##
##while n>0:
## rem= n%10
## s= s+rem*rem*rem
## n= n//10
##if a==s:
## print(a,' is an armstrong number')
##else:
## print(a,' is not an armstrong number')
##palindrome or not##
##n= int(input('enter a number ... |
1,044 | 3908d303d0e41677aae332fbdbe9b681bffe5391 | import os
from datetime import timedelta
ROOT_PATH = os.path.split(os.path.abspath(__name__))[0]
DEBUG = True
JWT_SECRET_KEY = 'shop'
# SQLALCHEMY_DATABASE_URI = 'sqlite:///{}'.format(
# os.path.join(ROOT_PATH, 's_shop_flask.db'))
SQLALCHEMY_TRACK_MODIFICATIONS = False
user = 'shop'
passwd = 'shopadmin'
db = 'shop... |
1,045 | 874b87ca20385aa15cc7299707c9c1c0360ace43 | from PyQt4 import QtCore
SceneName = "sphere"
DefaultColor = QtCore.Qt.yellow
|
1,046 | 86fdea2ae8e253aa4639bb3114de70c693536760 | from django.db import models
from django.contrib import admin
from django.utils import timezone
class Libros(models.Model):
ISBN = models.CharField(max_length=13,primary_key=True)
Titulo = models.CharField(max_length=15)
# Portada = models.ImageField(upload_to='imagen/')
Autor = models.CharField(max_le... |
1,047 | ca6b064dbd8200c49665eaa944fdf1fc80c25726 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data=pd.read_csv('regression.csv')
print(data)
x=data.iloc[:,0]
y=data.iloc[:,1]
mx=data['X1'].mean()
my=data['Y'].mean()
print(mx,my)
num, den = 0,0
for i in range(len(x)):
num += (x[i] - mx)*(y[i]-my)
den += (x[i]-mx)**2
be... |
1,048 | 5c415d5bf9d6952863a662d300cb1f706ef02a8f | import openerp
from openerp import pooler
from openerp.report import report_sxw
import xlwt
from openerp.addons.report_xls.report_xls import report_xls
from openerp.tools.translate import _
class openacademy_course_xls_parser(report_sxw.rml_parse):
def __init__(self, cursor, uid, name, context):
super(openacademy_c... |
1,049 | 88590aef975f7e473ef964ee0c4004cff7e24b07 | #!/usr/bin/env python3
import optparse
from bs4 import BeautifulSoup
import re
import jieba
import pickle
import requests
import asyncio
if __name__ == '__main__':
# 读取10000个关键词
fs = open("./src/keywords.txt", "rb")
keywords = fs.read().decode("utf-8").split(",")
fs.close()
# 找出特征
def find_f... |
1,050 | 7fe7ea89908f9d233dbdb9e46bf2d677406ab324 | import networkx as nx
import pytest
from caldera.utils.nx import nx_copy
def add_data(g):
g.add_node(1)
g.add_node(2, x=5)
g.add_edge(1, 2, y=6)
g.add_edge(2, 3, z=[])
def assert_graph_data(g1, g2):
assert g1 is not g2
assert g2.nodes[1] == {}
assert g2.nodes[2] == {"x": 5}
assert g... |
1,051 | 7cb75195df567a5b65fe2385423b0082f3b9de4b | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "Brateaqu, Farolflu"
__copyright__ = "Copyright 2019"
__credits__ = ["Quentin BRATEAU", "Luca FAROLFI"]
__license__ = "GPL"
__version__ = "1.0"
__email__ = ["quentin.brateau@ensta-bretagne.org", "luca.farolfi@ensta-bretagne.org"]
# Importing modules
import... |
1,052 | fecaf41152e8c98784585abfdb3777fc0a4824f3 |
string1 = "Vegetable"
#string2 = "Fruit"
string2 = "vegetable"
print(string1 == string2)
print(string1 != string2)
if string1.lower() == string2.lower():
print("The strings are equal")
else:
print("The strings are not equal")
number1 = 25
number2 = 30
# ==
# !=
# >
# <
# >=
# <=
if number1 <... |
1,053 | 6bc400896c004f0fdddbbd3dd73ef9aaa19eb4db | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Customer',
fields=[
('id', models.AutoField(ver... |
1,054 | 513a2bbcf7a63baf900b73b18cf25618937dc7d0 | """
Prog: helloworld.py
Name: Samuel doyle
Date: 18/04/18
Desc: My first program!
"""
print('Hello, world!')
|
1,055 | a21ac29911931bb71460175cba584e0011fa2ece | import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import base64
import configobj
import datetime
import os
config = configobj.ConfigObj('.env')
port = 2525
smtp_server = "smtp.mailtrap.io"
login = config['SMTP_USERNAME']
password = config['SMTP_PASSWORD']
sender_email... |
1,056 | 562b2c3567e42699cfd0804a5780af7ede142e13 | ## Filename: name.py
# Author: Marcelo Feitoza Parisi
#
# Description: Report the objects
# on the bucket sorted by name.
#
# ###########################
# # DISCLAIMER - IMPORTANT! #
# ###########################
#
# Stuff found here was built as a
# Proof-Of-Concept or Study material
# and should not b... |
1,057 | 358879d83ed3058530031d50fb69e3ce11fbd524 | print(60*60)
seconds_per_hour=60*60
print(24*seconds_per_hour)
seconds_per_day=24*seconds_per_hour
print(seconds_per_day/seconds_per_hour)
print(seconds_per_day//seconds_per_hour)
|
1,058 | 5c1d81c973487f1b091e58a6ccf5947c3f2a7e6d | import unittest
from nldata.corpora import Telegram
import os
class TestTelegram(unittest.TestCase):
def test_export_iter(self):
pass
# telegram = Telegram(data_dir)
# it = telegram.split("train", n=20)
# samples = [s for s in it]
# self.assertEqual(len(samples), 20)
... |
1,059 | 03629e62b11e66eeb0e111fee551c75c8463cbb8 | from compas.geometry import Line
# This import is use to test __repr__.
from compas.geometry import Point # noqa: F401
def test_line():
p1 = [0, 0, 0]
p2 = [1, 0, 0]
line = Line(p1, p2)
assert line.start == p1
assert line.end == p2
def test_equality():
p1 = [0, 0, 0]
p2 = [1, 0, 0]
... |
1,060 | 9bb6fd6fbe212bdc29e2d1ec37fa6ec6ca9a9469 | #!/usr/bin/env python
# encoding: utf-8
import multiprocessing
import time
import sys
def daemon():
p = multiprocessing.current_process()
print('Starting:', p.name, p.pid)
sys.stdout.flush()
time.sleep(2)
print('Exiting :', p.name, p.pid)
sys.stdout.flush()
def non_daemon():
p = multipr... |
1,061 | 267cb37f2ccad5b02a809d9b85327eacd9a49515 | from flask import Flask, jsonify, request
import requests, json, random
from bs4 import BeautifulSoup
import gspread
import pandas as pd
import dataservices as dss
from oauth2client.service_account import ServiceAccountCredentials
# page = requests.get("https://www.worldometers.info/coronavirus/")
# soup = BeautifulSou... |
1,062 | 0555c577a8fb746cf2debb929d02b46cd3be4d7b | from typing import List
def uppercase_first_letter(string: str) -> str:
return string[0:1].upper() + string[1:]
string_list: List[str] = input('Please, input string: ').split(' ')
result: str = ''
for i, value in enumerate(string_list):
result += (lambda index: '' if index == 0 else ' ')(i) + uppercase_fir... |
1,063 | 8355faf7c0d3742be34a56ddc982cb389c80d0a9 | import unittest
from traceback import print_tb
from ml_base.utilities.model_manager import ModelManager
from tests.mocks import MLModelMock
class ModelManagerTests(unittest.TestCase):
def test_model_manager_will_return_same_instance_when_instantiated_many_times(self):
"""Testing that the ModelManager wi... |
1,064 | 8ec18e259af1123fad7563aee3a363e095e30e8e | from django.db import models
from albums.models import Albums
class Song(models.Model):
name = models.CharField(max_length=255)
filename = models.FileField(upload_to='canciones/')
album = models.ForeignKey(Albums)
def __unicode__(self,):
return self.name
|
1,065 | f7d3096d669946e13186a893ffc53067e0fd0a0a | # -*- coding: utf-8 -*-
"""Digital Forensics Virtual File System (dfVFS).
dfVFS, or Digital Forensics Virtual File System, is a Python module
that provides read-only access to file-system objects from various
storage media types and file formats.
"""
|
1,066 | 84980b8923fa25664833f810a906d27531145141 | import cv2, os, fitz, shutil
import numpy as np
from PIL import Image
from pytesseract import pytesseract
from PIL import UnidentifiedImageError
pytesseract.tesseract_cmd = 'C:\\Program Files (x86)\\Tesseract-OCR\\tesseract.exe'
config = r'--oem 3 --psm'
# Возвращает путь к картинке, созданной на основе 1 ... |
1,067 | bb208d40ce098b05594aaf9c579f64b909738d52 | #!/usr/bin/python
import os;
import math;
# os.chdir('data/postgres/linux.env')
os.chdir('data/mysql/linux.env')
# os.chdir('data/mongo/linux.env')
col_time = 0;
col_read_ops = 1
col_read_err = 2
col_write_ops = 3
col_write_err = 4
class ColumnData:
def __init__(self, chart, title, data):
self.chart = ... |
1,068 | 84515ef6879b54b333f9afd48c6c4b7c43ff6957 | class Solution(object):
def minimumTotal(self, triangle):
"""
:type triangle: List[List[int]]
:rtype: int
"""
t = triangle
if len(t) == 1:
return t[0][0]
ret = [0] * len(t)
ret[0] = t[0][0]
for i in range(1, len(t)):
fo... |
1,069 | 1bbadf02c4b9ca22a0099bcc09fa4c62c9901c39 | from django.conf import settings
from django.db import models
def get_image_filename(instance, filename):
a = f'post_images/{instance.post.title}.svg'
return a
def get_main_image_filename(instance, filename):
a = f'post_images/{instance.title}_main.svg'
return a
# Create your models here.
class Po... |
1,070 | 1ea71f7b17809189eeacf19a6b7c4c7d88a5022c | from dataloaders.datasets import caltech, embedding
from torch.utils.data import DataLoader
def make_data_loader(args, **kwargs):
if args.dataset == 'caltech101':
train_set = caltech.caltech101Classification(args, split='train')
val_set = caltech.caltech101Classification(args, split='val')
test_set = caltech.c... |
1,071 | 2ca1b603b18316bc1d970b5e32389e10e4b532e2 | import configure
import connectify
import userlog
import dirlog
import time
def getUser(sock):
try:
userinfo = userlog.getInfo()
except:
userinfo = configure.init(sock)
userinfo = userinfo.split('^')[0]
# print userinfo
return userinfo
if __name__=="__main__":
sock = connectify.createCon()
userinfo = get... |
1,072 | 07544d1eb039da0081716aa489fc1a0a5a200145 | from peewee import *
db = PostgresqlDatabase('contacts', user='postgres', password='',
host='localhost', port=5432)
intro_question = input("What would you like to do with Contacts? Create? Read? Find? Delete? Update? ")
def read_contact():
contacts = Contact.select()
for contact in c... |
1,073 | 289aa48b4433be533c3916dd039136df45e0ac0b | # Generated by Django 2.2.5 on 2019-10-24 05:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('student', '0008_studentbasic_stu_class_num'),
]
operations = [
migrations.AlterModelOptions(
name='onduty',
options=... |
1,074 | 03062ea08bd6ad88376f7c2aa2c89d2194ed8b2e | '''
fibonacci(6) => [1, 1, 2, 3, 5, 8]
fibonacci(7) => [1, 1, 2, 3, 5, 8, 13]
'''
def fibonacci(n):
if n == 0:
return []
elif n == 1:
return [1]
elif n == 2:
return [1, 1]
else:
lista = fibonacci(n-1)
suma = lista[len(lista)-1] + lista[len(lista)-2]
lista... |
1,075 | af668751074df6f182c7121821587270734ea5af | # -*- coding: utf-8 -*-
import scrapy
import os
from topdb.items import BiqugeItem
class NovelsSpider(scrapy.Spider):
name = 'novels'
allowed_domains = ['xbiquge.la']
start_urls = ['http://www.xbiquge.la/xiaoshuodaquan/']
def parse(self, response):
# 小说分类
path = '/Users/qx/Documents... |
1,076 | 06f961c07695d1c312cb943afbfa64508a709c7e | from alive_progress import alive_bar
from time import sleep
with alive_bar(100) as bar: # default setting
for i in range(100):
sleep(0.03)
bar() # call after consuming one item
# using bubble bar and notes spinner
with alive_bar(200, bar='bubbles', spinner=... |
1,077 | 1fafbc1e415b5089afcd2976d4f0dc2aa1c5a144 | def maxProduct(self, A):
size= len(A)
if size==1:
return A[0]
Max=[A[0]]
Min=[A[0]]
for i in range(1,size):
Max.append(max(max(Max[i-1]*A[i],Min[i-1]*A[i]),A[i]))
Min.append(min(min(Max[i-1]*A[i],Min[i-1]*A[i]),A[i]))
tmax=Max[0]
... |
1,078 | 9a6ceeb286bb6c3d5923fe3b53be90a097e16ef5 | '''
Create a dictionary of fasttext embedding, stored locally
fasttext import. This will hopefully make it easier to load
and train data.
This will also be used to store the
Steps to clean scripts (codify):
1) copy direct from website (space-delimited text)
2) remove actions in ... |
1,079 | 618aa64c08ebf8d9a0bc9662195ece2bbd485c17 | dic = {}
try:
print(dic[55])
except Exception as err:
print('Mensagem: ',err)
|
1,080 | 8f5d9918260e2f50fb229a7067f820a186101b99 | import numpy as np
from scipy import stats
from scipy import interpolate
from math import factorial
from scipy import signal
"""
A continuous wavelet transform based peak finder. Tested exclusively on Raman spectra, however,
it should work for most datasets.
Parameters
----------
lowerBound: The lowest value of the... |
1,081 | e51c0d8c6430603d989d55a64fdf77f9e1a2397b | """
Tests of neo.io.exampleio
"""
import pathlib
import unittest
from neo.io.exampleio import ExampleIO # , HAVE_SCIPY
from neo.test.iotest.common_io_test import BaseTestIO
from neo.test.iotest.tools import get_test_file_full_path
from neo.io.proxyobjects import (AnalogSignalProxy,
SpikeTrainProxy, E... |
1,082 | 57b51ea36e9e2a095cf7e9646db2cc400cc72b83 | from mesa.visualization.modules import CanvasGrid
from mesa.visualization.ModularVisualization import ModularServer
from mesa.visualization.modules import ChartModule
from mesa.batchrunner import BatchRunner
from agentPortrayal import agent_portrayal
import metrics
from matplotlib import pyplot as plt
from Architecture... |
1,083 | f5dffa3c22bb35ed07cb5ca28f2ba02ea3c07dda | import math
import random
import pygame
pygame.init()
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
clock = pygame.time.Clock()
pygame.display.set_caption('space invaders')
background = pygame.image.load('background.png')
score = 0
previous_score = 0
score... |
1,084 | e2e4adaa8f7f62662e0c2915faff1bed72986351 | from django.contrib import admin
from .models import Hash
admin.site.register(Hash)
|
1,085 | d8af43d24a2f2b99bc8b5098f251e017852d6d86 | import subprocess
class BaseExecution:
def __init__(self, flag, parser):
self.flag = flag
self.parser = parser
def execute(self):
process = subprocess.Popen(f'df {self.flag}', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, err = process.communicate()
... |
1,086 | 2f2030107f3a23c0d2f404a838eaccc8b35ac410 | fahrenheit = float(input("Enter a fahrenheit degree: "))
celcius = ((fahrenheit - 32) * 5) / 9
print("From fahrenheit to celcius", celcius) |
1,087 | c4fbf206482a04f3e2d2aa98a0dbf525a176c4e7 | __author__ = 'Joe'
import sys
sys.path.insert(0,'../src/')
import grocery_functions
import unittest
class TestGroceryFuncs(unittest.TestCase):
def test_getRecipeNames(self):
recipe_names = grocery_functions.get_recipe_names("test-recipes")
self.assertTrue(recipe_names[0] == "Cajun Chicken & Rice"... |
1,088 | a7db627c49b53cd3a073d866a0373336a46b4053 | from graphviz import Digraph
dot = Digraph()
dot.edge("BaseException", "SystemExit")
dot.edge("BaseException", "KeyboardInterrupt")
dot.edge("BaseException", "GeneratorExit")
dot.edge("BaseException", "Exception")
dot.edge("Exception", "StopIteration")
dot.edge("Exception", "StopAsyncIteration")
dot.edge("Exception",... |
1,089 | 438efbaf35401a29ea5408fee3b49b85f237760e | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-05-12 20:48
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('home', '0010_auto_20170512_2248'),
]
o... |
1,090 | 22523304c9e2ce1339a7527cdbd67a81c780d806 | """
We have created mash sketches of the GPDB database, the MGV database, and the SDSU phage, and
this will figure out the top hits and summarize their familes.
"""
import os
import sys
import argparse
def best_hits(distf, maxscore, verbose=False):
"""
Find the best hits
"""
bh = {}
allph = set()... |
1,091 | 669eb2e898c3a127ae01e0ee3020a3674e5e340d | from yoloPydarknet import pydarknetYOLO
import cv2
import imutils
import time
yolo = pydarknetYOLO(obdata="../darknet/cfg/coco.data", weights="yolov3.weights",
cfg="../darknet/cfg/yolov3.cfg")
video_out = "yolo_output.avi"
start_time = time.time()
if __name__ == "__main__":
VIDEO_IN = cv2.VideoCapture(0)
... |
1,092 | 6b55a9061bb118558e9077c77e18cfc81f3fa034 | #
# @lc app=leetcode id=1121 lang=python3
#
# [1121] Divide Array Into Increasing Sequences
#
# https://leetcode.com/problems/divide-array-into-increasing-sequences/description/
#
# algorithms
# Hard (53.30%)
# Likes: 32
# Dislikes: 11
# Total Accepted: 1.7K
# Total Submissions: 3.2K
# Testcase Example: '[1,2,2,... |
1,093 | d7524a455e62594e321b67f0a32a5c3a7437c1d6 | # 引入基础的工作表
from openpyxl import Workbook
# 引入增强的修改功能
from openpyxl.styles import Font,Alignment,Border,Side,PatternFill,colors
# import openpyxl
def make_example():
# 设定文件目录
addr = './example.xlsx'
# 初始化文件,切换到活动的工作表
work_book = Workbook()
# 读取文件采用
# work_book = openpyxl.load_workbook... |
1,094 | 9fc9d766915bcefde4f0ba5c24cb83e33fc66272 | from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
import dbindexer
dbindexer.autodiscover() #This needs to happen before anything else, hence strange import ordering
urlpatterns = patterns('harvester.views'... |
1,095 | c88e2336432f93d95b4e2285aa532b673a4a410b | # Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack.package import *
class RDt(RPackage):
"""A Wrapper of the JavaScript Library 'DataTables'.
Data obje... |
1,096 | 6b597f1570c022d17e4476e2ab8817e724a166a7 | class Solution:
def evalRPN(self, tokens: List[str]) -> int:
def operation(op1,op2,op):
if op == "+":
return op1 + op2
if op == "-":
return op1 - op2
if op == "*":
return op1 * op2
if op == "/":
... |
1,097 | 09c3a10230e7d0b3b893ccf236c39fc2dc12b2c6 | dic = {'name': 'Eric', 'age': '25'} # 딕셔너리 형태
print(dic['name'])
|
1,098 | ecdc8f5f76b92c3c9dcf2a12b3d9452166fcb706 | """
Config module for storage read only disks
"""
from rhevmtests.storage.config import * # flake8: noqa
TEST_NAME = "read_only"
VM_NAME = "{0}_vm_%s".format(TEST_NAME)
VM_COUNT = 2
DISK_NAMES = dict() # dictionary with storage type as key
DISK_TIMEOUT = 600
# allocation policies
SPARSE = True
DIRECT_LUNS = UNUSE... |
1,099 | a55024f0e5edec22125ce53ef54ee364be185cb8 | """Test the init file of Mailgun."""
import hashlib
import hmac
import pytest
from homeassistant import config_entries, data_entry_flow
from homeassistant.components import mailgun, webhook
from homeassistant.config import async_process_ha_core_config
from homeassistant.const import CONF_API_KEY, CONF_DOMAIN
from hom... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.