index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
2,700 | 06ea697989f8f9ac539559690dcfd7aa73151e0f | # -*- coding: utf-8 -*-
"""
@author: chris
Modified from THOMAS MCTAVISH (2010-11-04).
mpiexec -f ~/machinefile -enable-x -n 96 python Population.py --noplot
"""
from __future__ import with_statement
from __future__ import division
import sys
sys.path.append('../NET/sheff/weasel/')
sys.path.append('../NET/sheffprk/... |
2,701 | 18a17c7326a6ae96f74c843d1a902074b377a6d2 | import os
import sys
import pandas as pd
import pickle as pkl
from src.utils import image as im
if __name__ == '__main__':
pickled = True
create_sets = True
normed = False
if len(sys.argv) > 2:
filename = sys.argv[1]
else:
filename = os.path.join(os.path.pardir, os.path.pardir, 'd... |
2,702 | 784159dfb2e85ca4634adf790e68129834155e4d | # -*- coding: utf-8 -*-
from pathlib import Path
from ruamel.yaml import YAML
from .screen import color2sgr
def _get(d, *paths):
""" Query into configuration dictionary, return None on any error
usag:
_get(d, 'k1.2.k3.k4', 2, 'name')
"""
if d is None:
return None
if paths is None:
return Non... |
2,703 | a3299a2945a638c74c2d16bc28079ed692718fbd | from collections import defaultdict
squares = dict()
for i in range(2000):
squares[i*i] = i
perims = defaultdict(int)
for a in range(1,1001):
for b in range(a+1, 1001):
if a*a+b*b not in squares:
continue
c = squares[a*a+b*b]
perims[a+b+c] += 1
for perim, v in sorted(perims.i... |
2,704 | c75c69b006734e476352de1913fd4a58021bffd6 | import datetime
from datetime import datetime, timedelta
import time
import json
import base64
import requests
from bson.objectid import ObjectId
import urllib
isinpackage = not __name__ in ['google_api', '__main__']
if isinpackage:
from .settings import settings
from . import util
from .util import Just
... |
2,705 | b257e36b3cb4bda28cf18e192aa95598105f5ae9 | import pandas as pd
# read the data
df = pd.read_csv("data/lottery.csv")
# extract needed column
df1 = df[['1','2','3','4','5','6','bonus']]
# translate dataframe to list for convenience
df2 = df1.values.tolist()
# cnt_number is each number's apearance times
cnt_number = []
for i in range(0, 46):
cnt_number.app... |
2,706 | c5d0b23396e084ad6ffade15b3aa3c59b6be3cc0 | from django.test import TestCase
from django.core.files import File
from ResearchManage.forms import ResearchFormMKI
from django.test import Client
from unittest import TestCase, mock
from datetime import date, timedelta
from django.core.files.uploadedfile import SimpleUploadedFile
import os
# Create your tests here.
... |
2,707 | a96575d507a91472176c99d4d55e2a3bbf8111d1 | from django.contrib import admin
from .models import JobListing
from .models import Employer
admin.site.register(JobListing)
admin.site.register(Employer)
|
2,708 | 358fd8efd5c3823255ab64d5f8b88b343415ed0e | #Some people are standing in a queue. A selection process follows a rule where people standing on even positions are selected. Of the selected people a queue is formed and again out of these only people on even position are selected. This continues until we are left with one person. Find out the position of that person... |
2,709 | 3badf65a5301cc9cf26811e3989631aec5d31910 | from django.db import models
# Create your models here.
class Pastebin(models.Model):
name= models.CharField(max_length=30)
textpaste = models.CharField(max_length=80)
pasteurl = models.AutoField(primary_key=True)
def __str__(self):
return self.name
|
2,710 | d07a26a69ccbbccf61402632dd6011315e0d61ed | from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
url = input('Enter - ')
html = urlopen(url).read()
soup = BeautifulSoup(html, "html.parser")
tags = soup.find_all('tr', {'id': re.compile(r'nonplayingnow.*')})
for i in tags:
casa = i.find("td", {'class': re.compile(r'team-home')}).find(... |
2,711 | 774bf2b49f6e546f16294edc17e9ac34fa8a9ba8 | class Figura:
def __init__(self):
print("Tworze obiekt klasy Figura...")
def pobierz_polozenie(self):
print("Metoda pobierz_polozenie klasy Figura.")
def nadaj_polozenie(self):
print("Metoda nadaj_polozenie klasy Figura.")
def wyswietl(self):
print("Metoda wyswietl klasy ... |
2,712 | e95ebb2aa6526e3bf3789da17d144e71cdb49aca | from DHT_Python import dht22
from oled96 import oled
from PiBlynk import Blynk
# read data using pin 4
instance = dht22.DHT22(pin=4)
token = "---token---"
blynk = Blynk(token)
def cnct_cb():
print ("Connected: ")
blynk.on_connect(cnct_cb)
def _funCb(ACT):
result = instance.read()
if result.is_valid():
strTe... |
2,713 | 2105619102de0d4d976c7bdfc839ee08058b7ab5 | #!/usr/bin/python
# Script to time convolution using different number of processors.
# Jason Neal
# December 2016
from __future__ import division, print_function
import datetime
from eniric.nIRanalysis import convolve_spectra
spectrum_name = "lte03900-4.50-0.0.PHOENIX-ACES-AGSS-COND-2011-HiRes_wave.dat"
data_rep = ... |
2,714 | fff70312fa7c3259cf4c3d9e7ebd8ca5b9a56887 | from sqlalchemy import Integer, String, Column
from sqlalchemy.orm import Query
from server import db
class Formation(db):
__tablename__ = "formation"
query: Query
id_form = Column(Integer, primary_key=True)
filiere = Column(String, nullable=False)
lieu = Column(String, nullable=False)
niveau = Column(Str... |
2,715 | 016255d74ccf4ac547e4b212d33bb9a39295c830 | # Generated by Django 3.2.3 on 2021-07-02 08:18
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('khovan', '0003_nhapkho'),
]
operations = [
migrations.AddField(
model_name='phieunhaphang',
... |
2,716 | 8ecd1d6b43027153e05c771eb7183c062319eebc | #d
#b
#c
#b,c |
2,717 | 849c468e4890c19806c678089ec8668576538b12 | from flask import (Flask, g, render_template, flash, redirect, url_for)
from flask_login import (LoginManager, login_user, logout_user,
login_required, current_user)
import forms
import models
import sqlite3
DEBUG = True
app = Flask(__name__)
app.secret_key = 'auoesh.bouoastuh.43,uoausoehuos... |
2,718 | 094f482ec6d36dfaed7e908bc445e6e015ec409d | # coding: utf-8
'''
Created on 2013-7-8
@author: huqiming
'''
import json
import re
import urllib2
'''
图说内容
'''
class ts_content:
'''
图说标题
'''
title = ''
'''
图说日期
'''
date = ''
'''
图说段落
'''
parts = []
def __str__(self):
return 'parts: ... |
2,719 | 844c9af4f0d4ca33e7c69b72f9886f58ceebefdb | from fastapi import APIRouter
from .endpoints import submissions
def get_api_router():
api_router = APIRouter()
api_router.include_router(submissions.router,
prefix="/submissions",
tags=["submissions"])
# api_router.include_router(users.router, ... |
2,720 | 20f56ff484321a7d623cead4315e5a6b3b0653a7 | # Generated by Django 3.1.2 on 2020-10-21 21:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('monitoring', '0002_auto_20201021_0027'),
]
operations = [
migrations.AlterField(
model_name='endpoint',
name='freque... |
2,721 | 67db3a66e5525d41de13df665167a0db2d81056e | from django.views import generic
from .models import GPS
# This is the view for my home page. It is a list view because it needs to display a list of all
# of the GPS units that are currently in the database.
class HomeView(generic.ListView):
model = GPS
template_name = 'inv_templates/home.html'
context_obj... |
2,722 | fdfb71595bf86fbe1763535814ec9c3cfd312d87 | """ Script to run pilon iteratively to correct genome assemblies """
import os
import argparse
import logging
import subprocess
def parse_arguments():
""" Parse command line arguments """
# Create parser
parser = argparse.ArgumentParser(description='Run pilon many times')
# Add arguments
pars... |
2,723 | 0769003c248c099da5bcd75541d35234b01af5de | #!/usr/bin/env python
import os
import sys
from setuptools import setup
from textwrap import dedent
NAME = "docker-zabbix-script-sender"
GITHUB_ORG_URL = "https://github.com/troptop/"
ROOT_DIR = os.path.dirname(__file__)
SOURCE_DIR = os.path.join(ROOT_DIR)
exec(open('docker_zabbix_script_sender/version.py').read())
... |
2,724 | 210d1a184d338d77d4c41327d0a9e2a5a56eb2ae | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Install and activate pre-commit and its hooks into virtual environment."""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import os
import sys
# if sys.version_info[0] > 2 or sys.version_info[1] < 7:
# p... |
2,725 | d48353caa07d3bfa003ea9354b411fe0c79591db | """
k-element subsets of the set [n]
3-element subsets of the set [6]
123
"""
result = []
def get_subset(A, k, n):
a_list = [i for i in A]
if len(a_list) == k:
result.append(a_list)
return
s_num = max(a_list)+1 if a_list else 1
for i in range(s_num, n+1):
a_list.append(i)
... |
2,726 | f3f3bbb715f16dc84221f3349aa5f26e9a6dc7c8 | from typing import Dict, List
pilha = list()
print(pilha) |
2,727 | eec08b3fdd4beb7d88ac0dc6d2e8776cf54fda35 | import tempfile
import unittest
from unittest.mock import mock_open, patch, MagicMock, call
import compare_apple_music_and_spotify as music_compare
class get_apple_music_data(unittest.TestCase):
def test_open_file(self):
with patch("builtins.open", mock_open(read_data="data")) as mock_file:
a... |
2,728 | 60202758a0a42fc26dc1bca9f134a70f28967093 | import json
import pickle
import zlib
from diskcollections.interfaces import IHandler
class PickleHandler(IHandler):
dumps = staticmethod(pickle.dumps)
loads = staticmethod(pickle.loads)
class PickleZLibHandler(IHandler):
@staticmethod
def dumps(
obj,
protocol=pickle.HIGHEST_PROTOC... |
2,729 | 76db5955b29696ca03ab22ef14ac018e0618e9e3 | '''
Seperate a number into several, maximize their product
'''
# recursive
def solution1(n):
if n <= 4:
return n
else:
return max(map(lambda x: solution1(x)*solution1(n-x), range(1, n//2 + 1)))
# dp
def solution2(n):
result_list = [1,2]
for i in range(3, n+1):
max_mult = max(l... |
2,730 | 96d13a883590ca969e997bbb27bcdbee1b24252f | import csv as csv
import hashlib
from sets import Set
def func_hash(parameter):
hash_object = hashlib.sha384(parameter)
table_hash = hash_object.hexdigest()
return table_hash
def myFunk():
with open('users.csv', 'w') as fp:
a = csv.writer(fp, delimiter=',')
roles = ['inspector', 'admin']
d... |
2,731 | 2dddee735e23e8cdb7df83f47f63926727cf8963 | """Stencil based grid operations in 2D."""
from .advection_flux_2d import gen_advection_flux_conservative_eno3_pyst_kernel_2d
from .advection_timestep_2d import (
gen_advection_timestep_euler_forward_conservative_eno3_pyst_kernel_2d,
)
from .brinkmann_penalise_2d import (
gen_brinkmann_penalise_pyst_kernel_2d,
... |
2,732 | fa531e8b07de6ee3c22146904ee8724cefab9033 | # presentation console
# - a python interpreter for "pseudo-interative" demos
#
# usage: $ python prescons.py <filename>
#
# <filename> should be a file that contains python code as would be entered
# directly in a terminal - see example.py
#
# while running, press 'space' to move through the code
#
# github.com/ingles... |
2,733 | c5a7f269f579bd1960afa4f700b5c3436ac6d91a | from rest_framework.views import APIView
from .serializers import UserSerializer
from rest_framework import permissions
from .models import users
from rest_framework.response import Response
from django.http import JsonResponse
from rest_framework import viewsets
from profiles.models import profile
from profiles.serial... |
2,734 | 5220ad793788927e94caf7d6a42df11292851c67 | from django.shortcuts import render
# from emaillist.models import Emaillist
from emaillist.models import Emaillist
from django.http import HttpResponseRedirect
# Create your views here.
# def index(request):
# emaillist_list = Emaillist.objects.all().order_by('-id') # db에서 objects 전체를 불러와서 변수에 저장
# data =... |
2,735 | b7a60322b4a0fcb6de16cd12be33db265a2b8746 | import pytesseract
from PIL import Image
img = Image.open("flag.png")
text = pytesseract.image_to_string(img)
def rot(*symbols):
def _rot(n):
encoded = ''.join(sy[n:] + sy[:n] for sy in symbols)
lookup = str.maketrans(''.join(symbols), encoded)
return lambda s: s.translate(lookup)
re... |
2,736 | f2bf4f5b057af1d2362ec8d1472aa76e774be1c7 | import art
import random
print(art.guess)
print(art.the)
print(art.number)
print("I'm thinking of a number between 1 and 100")
number = random.randint(1,100)
turns = 0
difficulty = input("Chose a difficulty. 'easy' or 'hard'?\n")
if difficulty == 'easy':
turns +=10
else:
turns +=5
gameover = False
while n... |
2,737 | 09712a397ad7915d9865b4aebf16606f85988f67 | # 30 - Faça um programa que receba três números e mostre - os em ordem crescentes.
n1 = int(input("Digite o primeiro número: "))
n2 = int(input("Digite o segundo número: "))
n3 = int(input("Digite o terceiro número: "))
if n1 <= n2 and n2 <= n3:
print(f'A ordem crescente é {n1}, {n2}, {n3}')
elif n1 <= n3 and n3 ... |
2,738 | f1396179152641abf76256dfeab346907cb1e386 | [Interactive Programming with Python - Part 1]
[Arithmetic Expressions]
# numbers - two types, an integer or a decimal number
# two correspending data types int() and float()
print 3, -1, 3.14159, -2.8
# we can convert between data types using int() and float()
# note that int() take the "whole" part of a decimal n... |
2,739 | ce3e2aa2534bb404b45202bcb76e9d07080560cb | import torch
from torch import nn
import pytorch_ssim
class Custom_Loss_for_Autoencoder(nn.Module):
def __init__(self, window_size=6):
super(Custom_Loss_for_Autoencoder, self).__init__()
self.ssim = pytorch_ssim.SSIM(window_size=window_size)
self.mse = nn.MSELoss()
def forward(s... |
2,740 | 9e8b5cebd48b3b98e421c896d9835ada5ec4166e | from django.db.models import Q, Avg
from django.http import JsonResponse
from rest_framework import permissions
from rest_framework.authtoken.models import Token
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.decorators import action
from rest_framework.response import Response
from rest... |
2,741 | 9655cba5b459ae8b6812bcebc31cc46e19e52386 | # Given two binary strings, return their sum (also a binary string).
#
# For example,
# a = "11"
# b = "1"
# Return "100".
#
# Show Company Tags
# Show Tags
# Show Similar Problems
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
... |
2,742 | 8b97c1e14adfcb09806e2d37e2f5c4f0b356c009 | #
# abc088 c
#
import sys
from io import StringIO
import unittest
class TestClass(unittest.TestCase):
def assertIO(self, input, output):
stdout, stdin = sys.stdout, sys.stdin
sys.stdout, sys.stdin = StringIO(), StringIO(input)
resolve()
sys.stdout.seek(0)
out = sys.stdout.r... |
2,743 | f739fb56eae1ada2409ef7d75958bad2018f5134 | from flask import Flask
from raven.contrib.flask import Sentry
from flask.signals import got_request_exception
app = Flask(__name__)
sentry = Sentry(dsn=app.config['SENTRY_DSN'])
@got_request_exception.connect
def log_exception_to_sentry(app, exception=None, **kwargs):
"""
Logs an exception to sentry.
:... |
2,744 | 05851df7ae64d792e0c1faf96e2aca5b40e86d53 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-10-20 11:05
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0052_encounter_note'),
]
operations = [
migrations.CreateModel(
... |
2,745 | ff1db5981a0163df1dfb44869a3d4af2be03c10a | import struct
class H264Packet:
UNKNOWN_TYPE, I_HDR, P_HDR, B_HDR, I_DATA, P_DATA, B_DATA = range(7)
def __init__(self, packet):
self.packet = packet
self.type = None
self.data = None
if len(packet) > 3:
(self.type,) = struct.unpack('H', packet[0:2])
self.data = packet[2:]
def serialize(self):
r... |
2,746 | edd2b7b453d7fa33e6cca3b5dbc895f034a9e22a | import torch
import numpy as np
from torch.autograd import Variable
from util import helpers
from util.metrics import ECELoss, ece_score
import sklearn.metrics as skm
import os
import pandas as pd
import pickle
def eval(path_in, path_out, net, testloader, oodloader, use_cuda=True, save_dir=None):
f1 = open(path_... |
2,747 | def2721cd89501b1004d5d3f4f58df300616c1be |
import sys
with open(sys.argv[1], 'r') as test_cases:
for test in test_cases:
stringe = test.strip()
list1 = stringe.split(" | ")
list2 = list1[0].split(" ")
kha = 0
for item in list2:
for c in list1[1]:
if c in item:
... |
2,748 | 1c31649ac75214a6d26bcb6d6822579be91e5074 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sqlite3 as lite
con = lite.connect('./logs.db')
with con:
cur = con.cursor()
cur.execute("DROP TABLE IF EXISTS log")
cur.execute('''CREATE TABLE log (msg_id text, u_id text, username text, first_name text, last_name text, msg text, ch_id text, d... |
2,749 | 25dc0395da1f1ac2ccd990151c3e5b250802b402 | from schemasheets.schemasheet_datamodel import SchemaSheet
RECORD = "Record"
FIELD = "Field"
METATYPE = "MetaType"
INFO = "Info"
CV = "CV"
PV = "PV"
SDO_MAPPINGS = "schema.org"
WD_MAPPINGS = "wikidata"
DATATYPE = "Datatype"
CASES = [
(1,
[
{
RECORD: "> class",
INFO: " descript... |
2,750 | 8b0e7e8f2031df217894e980758e15d7401c0981 | import sys
def read(inp):
res = []
n, v = map(int, inp.readline().split())
for i in range(n):
x, y = map(int, inp.readline().split())
res.append((x, y))
return v, res
def solve(v, items):
res = 0
rem_v = v
for item in items:
if rem_v > item[1]:
res +... |
2,751 | f11e6a53d8dfc60f73f346772df7a3cab14088ce | """
* @section LICENSE
*
* @copyright
* Copyright (c) 2017 Intel Corporation
*
* @copyright
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* @copyright
* http://www.apache.org... |
2,752 | ee8e117db0348aa37d6aa37e6c06255101f1cff4 | import socket
from time import time, sleep
from threading import Thread
# Define drone
class dm107s():
# Default control value
def __init__(self):
# 4 values for flight
self.roll = 128
self.pitch = 128
self.throttle = 128
self.yaw = 128
# 0 - normal mode, 2 - eme... |
2,753 | ef124e8c15ef347efd709a5e3fb104c7fd1bccde | #!/usr/bin/env python
#coding=utf-8
"""
__init__.py
:license: BSD, see LICENSE for more details.
"""
import os
import logging
import sys
from logging.handlers import SMTPHandler, RotatingFileHandler
from flask import Flask, g, session, request, flash, redirect, jsonify, url_for
from flaskext.babel import Ba... |
2,754 | 19c0c3156488ce99316ce40f32e84e476b7afdac | import pandas as pd
import numpy as np
import matplotlib.pylab as plt
from matplotlib.pylab import rcParams
#from pandas import datetime
#from pandas.tseries.t
from sklearn.preprocessing import MinMaxScaler
#from statsmodels.tsa.seasonal import seasonal_decompose
from pandas import Series
data = pd.read_csv(
r'E:\... |
2,755 | 720ab0c0fcb40a50d73770e4ada6a78465e9ff96 |
# ----------------------
#
# *** WELCOME TO "HANGMAN" GAME ***
# Let's start programming
#
# ----------------------
def displayBoard(missedLetters, correctLetters, secretWord, alfabet_board, theme):
print(hangnam_pics[len(missedLetters)])
print("Тема:", theme)
# Показываем состояние угадываемого сло... |
2,756 | 874fa927a1c0f1beeb31ca7b0de7fd2b16218ea4 | """main.py"""
import tkinter as tk
from tkinter import ttk
from ttkthemes import ThemedStyle
import wikipedia as wk
from newsapi import NewsApiClient as nac
import datetime
import random
class MainWindow:
"""Application controller object."""
def __init__(self):
self.p = None
self... |
2,757 | 67d79a5c9eceef9f1ed69f79d6a9d1f421f3246c | import numpy as np
def calculate_distance_for_tour(tour, node_id_to_location_dict):
length = 0
num = 0
for i in tour:
j = tour[num - 1]
distance = np.linalg.norm(node_id_to_location_dict[i] - node_id_to_location_dict[j])
length += distance
num += 1
return length
def... |
2,758 | a7fae2da8abba6e05b4fc90dec8826194d189853 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#allisnone 20200403
#https://github.com/urllib3/urllib3/issues/1434
#https://github.com/dopstar/requests-ntlm2
#https://github.com/requests/requests-ntlm
#base on python3
#if you request https website, you need to add ASWG CA to following file:
#/root/.pyenv/versio... |
2,759 | fbd5c7fa335d6bde112e41a55d15aee31e3ebaf7 | import os, sys
sys.path.append('./Pytorch-UNet/')
import torch
from torch import optim
import torchvision.transforms as transforms
import torchvision.datasets as dset
import wandb
from datasets import parse_dataset_args, create_dataset
from wt_utils import wt, create_filters, load_checkpoint, load_weights
from argumen... |
2,760 | bddba2fd710829db17c6419878ce535df0aba01c | # -*- coding: utf-8 -*-
from yuancloud import models, fields, api, _
import yuancloud.addons.decimal_precision as dp
from yuancloud.exceptions import UserError
from yuancloud.osv import fields as old_fields
class event_event(models.Model):
_inherit = 'event.event'
event_ticket_ids = fields.One2many(
... |
2,761 | 65a9f732fc8c7b9c63f6ef0d7b2172bb4138a895 | """
Copyright (C) 2019-2020 Zilliz. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed... |
2,762 | 6e434ff213166768a6adadf99dc5d6d8611fa2ba | import os
import shutil
import numpy as np
import unittest
from lsst.ts.wep.Utility import FilterType, runProgram
from lsst.ts.wep.WepController import WepController
from lsst.ts.wep.ctrlIntf.RawExpData import RawExpData
from lsst.ts.aoclcSim.Utility import getModulePath
from lsst.ts.aoclcSim.WepCmpt import WepCmpt
... |
2,763 | c6174fae929366cabb8da3d810df705b19895c1c | """
Function of main.py:
config loader
hprams loader
feature extraction
Call model training and validation
Model Save and Load
Call model validation
载入训练参数
载入指定模型超参数
调用特征提取
调用模型训练和验证
模型保存与载入
调用模型验证
"""
"""A very simple MNIST classifier.
See extensive documentation at
https://www.tensorflow.org/get_started/mnist/beg... |
2,764 | a74653f01b62445c74c8121739bd9185ce21c85a | import urllib.request
import http.cookiejar
import requests
import re
import sys
import time
import json
from bs4 import BeautifulSoup
head = {
"Host": "www.pkuhelper.com",
"Accept": "*/*",
"Accept-Language": "zh-Hans-CN;q=1",
"Connection": "keep-alive",
"Accept-Encoding": "gzip, deflate",
"User-Agent": "PKU Hel... |
2,765 | e83b6b1f4cb12fe3b932903eddddfb0dc0e7d98d | import os, sys, datetime, csv, platform
####FUNCTIONS####
#Get Creation Time
def get_lastupdate_date(path):
return os.path.getmtime(path)
#Get Date From String
def convertIntToTimestamp(timeint):
return str(datetime.datetime.fromtimestamp(timeint))
#Get Filename
def getFilename(name):
return os.path... |
2,766 | 7e11a33d82926ed544640a0192e905d373f575da | # Generated by Django 3.2.3 on 2021-05-23 19:41
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('main_app', '0002_notebook_smathphone'),
]
operations = [
migrations.RenameModel(
old_name='Smathphone',
new_name='Smartphone... |
2,767 | 8f30de819412b03ef12009320978cb1becd85131 | #!/usr/bin/python
#Program for functions pay scale from user input
hrs = raw_input("Enter Hours:")
h = float(hrs)
rate = raw_input("Enter Rate:")
r = float(rate)
def computepay(h,r):
if (h>40) :
pay = (40*r)+(h-40)*1.5*r
else:
pay = (h*r)
return pay
print computepay(h,r)
|
2,768 | 943db90aa7721ddad3d7f5103c4d398fbf4e143b | import sys
import utils
#import random
def findNearestPoint(points,no_used , src):
# If no nearest point found, return max.
dest = src
minDist = sys.float_info.max
for i in range(len(points)):
if no_used[i] and i!=src:
dist = utils.length(points[src], poi... |
2,769 | cd5929496b13dd0d5f5ca97500c5bb3572907cc5 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
try:
from espeak import espeak
except ImportError:
class espeak():
@classmethod
def synth(*args):
print('Cannot generate speech. Please, install python3-espeak module.')
return 1
def run(*args, **kwargs):
text = ' '.jo... |
2,770 | 6914656a2f78fa1fe74a67bf09b017585b3eac88 | """
Main class of the interface.
It setups the experimental parameters such as the :class:`.Experiment`'s and
:class:`.Sample`, geometry (:attr:`geometry <Stratagem.geometry>`), type of
:math:`\\phi(\\rho z)` model (:attr:`prz_mode <Stratagem.prz_mode>`) and
fluorescence mode (:attr:`fluorescence <Stratagem.fluoresce... |
2,771 | 3a7f9bf5420b2d3587f1988c35f2f88bd2fa2b32 | #!/usr/bin/env python3
def main():
pass
def handle_result(args, result, target_window_id, boss):
if args[1] == "next":
boss.active_tab_manager.next_tab(1)
elif args[1] == "previous":
boss.active_tab_manager.next_tab(-1)
boss.active_tab.neighboring_window(args[1])
handle_result.no_ui... |
2,772 | 42ae3804c2d8f6a0d440e2bb6231186a868630b1 | import numpy as np
import cv2
import skimage.color
import skimage.filters
import skimage.io
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
import pickle
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.utils import check_random_state
from keras.preprocessing.i... |
2,773 | 4ffc00e9425992bdd8277341d67a0739119a4798 | def ex(x,y):
max=0
print(x)if x>y else print(y)
return max
|
2,774 | 3b99cc0eb163f4a94bc47429ad3627a6ecad4818 | from sys import stdin
def get_time(d, sp, dists, i, d_old, sp_old):
if i == len(dists):
return 0
times = []
d_new = d[i]
sp_new = sp[i]
if d_new >= dists[i]:
res1 = get_time(d, sp, dists, i + 1, d_new - dists[i], sp_new)
if res1 is not None:
times.append(res1 + (... |
2,775 | be16e13c0e03952e45f98b175975795bba19cf9a | my_list = [9, 9, 9, 8, 8, 7, 7, 6, 6, 5, 4, 4, 4, 2, 2, 1]
new_num = int(input('Enter a new number - '))
i = 0
for n in my_list:
if new_num <= n:
i += 1
my_list.insert(i, float(new_num))
print(my_list) |
2,776 | 561763d4d7b613446f2890ef629b631542f2f472 | from datetime import datetime
start = datetime.now()
# Poker Hand Analyser Library for Project Euler: Problem 54
from collections import namedtuple
# import pe_lib
def character_frequency(s):
freq = {}
for i in s:
if i in freq:
freq[i] += 1
else:
freq[i] = 1
return freq
suits = "HDCS".split()
faces = "2... |
2,777 | 14fb6776ac30802edf43c43acbee64263c6bdd7b | import numpy as np
import itertools
from scipy.linalg import eig, schur
from eigen_rootfinding.polynomial import MultiCheb, MultiPower
from eigen_rootfinding.utils import memoize
from scipy.stats import ortho_group
def indexarray(matrix_terms, which, var):
"""Compute the array mapping monomials under multiplicatio... |
2,778 | c2ff3c5e44fa361671a3fdb38060517bcc4bc82c | from django import forms
class CommentForm(forms.Form):
name = forms.CharField(label='称呼')
email = forms.EmailField(label='邮箱')
content = forms.CharField(label='内容')
|
2,779 | 6f05b1352e776e20d6a9e0eb457d8914cbfc2d22 | password = ["123456", "1111"]
pw = input("รหัสผ่านคือ>>>")
for data in password:
if data != pw:
pass
else:
print("พบข้อมูลรหัสผ่านนี้")
print("แล้วเจอกันใหม่")
|
2,780 | 9b73037e8af7d4f91261cebf895b68650182fcd5 | from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('', views.artifact, name="artifacts"),
path('<int:artifact_id>', views.detail, name="detail"),
path('register/', views.register, name="register")
] |
2,781 | d89e1d653c6db322feb6edba93cbfc622bf47aa2 | #%%
### 날짜 데이터 분리
# 연-월-일 날짜 데이터에서 일부 분리 추출
import pandas as pd
df = pd.read_csv('../../datasets/part5/stock-data.csv')
# 문자열인 날짜 데이터를 판다스 Timestamp로 변환
df['new_Date'] = pd.to_datetime(df['Date']) # df에 새로운 열로 추가
print(df.head())
print()
# dt 속성을 이용하여 new_Data 열의 연-월-일 정보를 년, 월, 일로 구분
df['Year'] = df['new_... |
2,782 | 0e57e25c11ba97aef5467f61d99065609e127f5b | import multiprocessing
import sys
import warnings
from pathlib import Path
import attr
import librosa
import pandas as pd
from rich.progress import BarColumn, Progress, TimeRemainingColumn
from sklearn.preprocessing import LabelEncoder
from tslearn.piecewise import SymbolicAggregateApproximation
from tslearn.preproces... |
2,783 | a567a2dc1dbb59979d849a5a772e4592910a9f27 | num=5
a=5
for row in range(num,0,-1):
for col in range(row,0,-1):
print(a,end="")
a-=1
print() |
2,784 | 4c54cfefbaf90c1dd0648485e62bff1f2787ccfe | from django.db import models
class IssueManager(models.Manager):
def open(self):
return self.filter(status__is_closed=False)
def closed(self):
return self.filter(status__is_closed=True) |
2,785 | b92f24cddae7b392af2417b39bb4f58e3f661cc6 | from activitystreams.core import Object
class Actor(Object):
"""Describes a generic actor."""
pass
class Application(Actor):
"""Describes a software application."""
pass
class Group(Actor):
"""Represents a formal or informal collective of Actors."""
pass
class Organization(Actor):
""... |
2,786 | 2edbf18c90da1ff40fd9abaf25a35dbdaf733bc1 | # -*- coding: utf-8 -*-
"""Success request logging.
This logging is used by "CheckZope" to determine the amount
of work performed by Zope (in order not to bother it with monitor
probes when it is heavily active) and to detect an unreasonable
error rate.
This logging writes two files "<base>_good.<date>" and "<base>_b... |
2,787 | 2f1193e3ab5e0527ab5f89141613eddb18b5f61d | from difflib import SequenceMatcher
import csv
naam = "straat"
def similar(a, b):
return SequenceMatcher(None, a, b).ratio()
f = open("straten.txt", "r")
f.readline()
names = f.readlines()
for name in names:
if similar(name[:-1].lower(),naam.lower()) > 0.7:
sim = similar(name[:-1].lower(),naam.lower(... |
2,788 | 47ad08bb153801f592d90c48d62338d0f7703899 | import csv, requests
from bs4 import BeautifulSoup
items = [] # chooseKey, count, grade, keyType, mainCategory, mainKey,
# name, pricePerOne, subCategory, subKey, totalTradeCount,
# mainLabel, subLabel, description
mpItems = [] # chooseKey, count, grade, keyType, mainCategory, mainKey,
... |
2,789 | f6974c0e5908710031bc3c3bb75c277be426632c | # Greedy Algorithm solves a problem by building a solution incrementally
# The algorithm is greedy because it chooses the next step that gives the most benefit
# Can save a lot of time when used correctly since they don't have to look at the entire problem space
# It's either the most optimal solution or it doesn't wor... |
2,790 | 52ebe80e2d520bf07b21dc668223348002eb6d42 | from django.test import TestCase
# Create your tests here.
import pymongo
client = pymongo.MongoClient(host='127.0.0.1', port=27017)
db = client.NBA_china_spider
collection = db.data
data = [title for title in collection.find()]
print(data[0]['url'])
|
2,791 | 5e8f9a222fb2c35b4720e48f0277481e410aee47 | import random
def createRandomPhoneNumber():
phoneNumberFront = ['130', '131', '132', '133', '134', '135', '136', '137', '138', '139', '150', '151', '152',
'153', '158', '159', '177', '180', '181', '182', '183', '186', '188', '189']
phoneNumberBack = []
for i in range(8):
p... |
2,792 | a2593d5b89b9a35d91b0e1011f5b2a23a5a2062e | # -*- coding: utf-8 -*-
import re
import argparse
import utils
# Les arguments à fournir en ligne de commande
parser = argparse.ArgumentParser(description="""Génère le graph des articles""")
parser.add_argument('corpus', type=str, help="Le nom du corpus (sans l'extension .tsv')")
parser.add_argument('-v', '--verbose... |
2,793 | 286a47cece7002a88f34ace3e08d013e2d14801a | #!/usr/bin/env python
from io import StringIO
import sys
from contextlib import redirect_stdout
import pytest
# test input_name():
from mailroom3 import input_name
def test_1(monkeypatch): # tests "list"
monkeypatch.setattr('builtins.input', lambda x: "list")
f = StringIO()
with redirect_stdout(f):
... |
2,794 | 386fa51b9b285d36c75d6446f9348f6713e0dbaa | import os
WOO_HOST = os.environ.get('WOO_HOST')
#WooCommerce key credentials
WOO_CONSUMER_KEY = os.environ.get('WOO_CONSUMER_KEY')
WOO_CONSUMER_SECRET = os.environ.get('WOO_CONSUMER_SECRET')
#XML feed fields and settings
XML_FEED_FILENAME = os.environ.get('XML_FEED_FILENAME', 'feedXML')
XML_SITE_NAME = os.environ.ge... |
2,795 | fe081a422db6b7f10c89179beab852c6b74ec687 | '''
vetor = ["pares de pregos ligados por uma linha"]
indice do vetor representa os pregos na vertical, e o
inteiro em cada pos, os pregos na horizontal.
i(vertical) e j(horizontal) entao:
vetor[i] = j
pregos a(vertical) e pregos b(horizontal)
se a>i and b<j or a<i and b>j
a e i(são indices) b e j(são os elemnt... |
2,796 | a077221d91f75645172ba5d86afad8e49cb7ed2f | #!/usr/bin/python
import calendar
a=int(raw_input("enter the year to check that year is leap year or not\n"))
cal=calendar.isleap(a)
if cal :
print "leap year"
else :
print "not a leap year"
print "\nthanks "
'''
'''
|
2,797 | 1f385fda1bdc0008ff91b935998c95c8ffcbd297 | tej="votary"
for i in range(5):
print(tej[i])
|
2,798 | c77e320cee90e8210e4c13d854649b15f6e24180 | from .ctoybox import Game, State as FrameState, Input
import numpy as np
from PIL import Image
import json
from typing import Dict, Any, List, Tuple, Union, Optional
def json_str(js: Union[Dict[str, Any], Input, str]) -> str:
"""
Turn an object into a JSON string -- handles dictionaries, the Input class, and... |
2,799 | dce496c9ae6605e95ffbbb2885ec15b19fb756ef | ii = [('CookGHP3.py', 1), ('AubePRP2.py', 1), ('WilkJMC3.py', 1), ('LeakWTI3.py', 1), ('AubePRP.py', 2), ('GellWPT.py', 2), ('AdamWEP.py', 1), ('KiddJAE.py', 1), ('CoolWHM.py', 1), ('WadeJEB.py', 1), ('SoutRD.py', 2), ('WheeJPT.py', 1), ('HowiWRL2.py', 1), ('WilkJMC.py', 1), ('WestJIT.py', 1), ('DequTKM.py', 2), ('Stor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.