index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
6,000 | ff3f6d50498f58f3a340e2d690165efcc1a5fb1d | class User:
account = []
def __init__(self,balance,int_rate):
self.balance = balance
self.int_rate = int_rate
User.account.append(self)
def dep(self,amount):
self.balance += amount
return self
def make_withdrawal(self,amount):
if(self.balance-amount) >= 0... |
6,001 | 72c1226d40b3cdce29ef28493344c3cf68892149 | # Generated by Django 3.0.4 on 2020-03-29 19:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('index', '0003_auto_20200330_0444'),
]
operations = [
migrations.AlterField(
model_name='information',
name='comment'... |
6,002 | 780dc49c3eaef3fb25ca0aac760326b1c3adc633 | #!/usr/bin/env python
# Copyright (C) 2014 Open Data ("Open Data" refers to
# one or more of the following companies: Open Data Partners LLC,
# Open Data Research LLC, or Open Data Capital LLC.)
#
# This file is part of Hadrian.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this... |
6,003 | 699410536c9a195024c5abbcccc88c17e8e095e3 | ############################################################
# Hierarchical Reinforcement Learning for Relation Extraction
# Multiprocessing with CUDA
# Require: PyTorch 0.3.0
# Author: Tianyang Zhang, Ryuichi Takanobu
# E-mail: keavilzhangzty@gmail.com, truthless11@gmail.com
###########################################... |
6,004 | a89724be31b4ccc1a3d83305509d9624da364a0c | import sys
def solution(input):
k = 1
for v in sorted(input):
if v >= k:
k += 1
return k - 1
testcase = sys.stdin.readline()
for i in range(int(testcase)):
sys.stdin.readline()
line1 = sys.stdin.readline().rstrip('\n')
line2 = sys.stdin.readline().rstrip('\n')
ans = sol... |
6,005 | 21c8078a18ee4579fa9b4b1b667d6ea0c1ce99b3 | # Generated by Django 2.1.3 on 2019-04-10 11:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0014_auto_20190409_1917'),
]
operations = [
migrations.AlterField(
model_name='article',
name='estArchive',
... |
6,006 | e08ab06be0957e5e173df798742abc493eac84d0 | import time
import numpy as np
import matplotlib.pyplot as plt
import cv2
import matplotlib.image as mpimg
import random
import skimage
import scipy
from PIL import Image
def readimg(dirs, imgname):
img = cv2.imread(dirs + imgname)
img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
return img
def readimg_color(d... |
6,007 | c77db71844c65eb96946ac0cc384de43ad49ca99 | import math
def math_builtins():
assert abs(-123) == 123
assert abs(-123.456) == 123.456
assert abs(2+3j) == math.sqrt(2**2 + 3**2)
assert divmod(5, 2) == (2, 1)
assert max(1, 2, 3, 4) == 4
assert min(1, 2, 3, 4) == 1
a = 2
b = 3
c = 7
assert pow(a, b) == a ** b
assert po... |
6,008 | f69544a9123f1738cd7d21c1b4fc02dd73fb9d1b | '''Module main'''
import argparse
import api
import quoridor
import quoridorx
def analyser_commande():
'''Analyseur de ligne de commande.'''
parser = argparse.ArgumentParser(description='Jeu Quoridor - phase 3')
parser.add_argument("idul", help="IDUL du joueur.")
parser.add_argument("-l", '--lister'... |
6,009 | ef3fa538828315845de5e2f7d4949f690e44276e | """
Flask app for testing the OpenID Connect extension.
"""
import json
from unittest.mock import MagicMock, Mock
from flask import Flask, g
import flask_oidc
from tests.json_snippets import *
oidc = None
def index():
return "too many secrets", 200, {
'Content-Type': 'text/plain; charset=utf-8'
}
... |
6,010 | 9dfc8414628a8b09de3c24c504dd4163efdd3d35 | # This is main file where we create the instances of Movie class
# and run the file to view the movie website page
# we have to import media where class Movie is defined and
# fresh_tomatoes python files
import fresh_tomatoes
import media
# Each instance has 8 arguments: Title, story line, poster image,
# trailer url... |
6,011 | 83733e707a1be131335c4980cdf4beed365eb530 | from simulating_blobs_of_fluid.simulation import Simulation
from simulating_blobs_of_fluid.fluid_renderer import FluidRenderer
import arcade
def main():
simulation = Simulation(particle_count=50, dt=0.016, box_width=250)
FluidRenderer(simulation.box_width, 800, simulation)
arcade.run()
if __name__ == ... |
6,012 | a4492af775899ec2dcc0cac44b2740edd8422273 | import copy
import random
def parse_arrow(string):
return tuple(string.split(' -> '))
def parse_sig(string, vals=None):
parts = string.split()
if len(parts) == 1:
return resolve(parts[0], vals)
elif parts[1] == 'AND':
return resolve(parts[0], vals) & resolve(parts[2], vals)
elif ... |
6,013 | 918db455fc50b49ca2b40dd78cecdec4ba08dcb8 | import math
# 计算像素点属于哪个中心点
from utils.util import distance
def attenuation(color, last_mean):
return 1 - math.exp(((distance(color, last_mean) / 80) ** 2) * -1)
def get_Count_By_distance(centers, pixel_use,d):
# d_min设置过低会产生多的中心点,许多很相似但是没有归到一类中
# d_min设置过高产生少的中心点,不相似的归到一类中
d_min = 1;
d_b = d;
... |
6,014 | b66f588149d160c119f9cc24af3acb9f64432d6e | import dash
import dash_html_components as html
app = dash.Dash(__name__)
app.layout = html.H1("Hello dashboard")
if __name__ == "__main__":
app.run_server(debug=False, port=8080, host="127.0.0.1")
|
6,015 | 10bf7959f178d3b5c0ce6e97253e665d32363af7 | #!/usr/bin/env python
# KMeans
# 参考 https://qiita.com/g-k/items/0d5d22a12a4507ecbf11
#
# データを適当なクラスタに分けた後、クラスタの平均を用いてうまい具合にデータがわかれるように調整させていくアルゴリズム
# 任意の指定のk個のクラスタを作成するアルゴリズムであることから、k-means法(k点平均法と呼ばれている)
# k-meansの初期値選択の弱点を解消したのが、k-means++
# k-means++では、中心点が互いに遠いところに配置されるような確率が高くなるように操作する。
# 教師なし学習のアルゴ... |
6,016 | 16cc85324b555f0cfec8d577b776b86872578822 | # Given an array of integers, return indices of the two numbers such that they add up to a specific target.
# You may assume that each input would have exactly one solution, and you may not use the same element twice.
# Example:
# Given nums = [2, 7, 11, 15], target = 9,
# Because nums[0] + nums[1] = 2 + 7 = 9,
# retu... |
6,017 | f98d6dd9ac4714c24ce070a1a81dc4610d04b97e | # -*- coding: UTF-8 -*-
# File Name: ll.py
# Author: Sam
# mail: samyunwei@163.com
# Created Time: 2016年03月09日 星期三 19时18分02秒
#########################################################################
#!/usr/bin/env python
def checkmark(marks):
if not isinstance(marks,list):
return 'marks Error'
else:
... |
6,018 | 8b2911586e21162bec074732216c410c591f18a8 | from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.models import User
from .models import Museo, Distrito, Comentario, Favorito, Like, Titulo, Letra, Color
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import authenticate, login
from django.... |
6,019 | f76185095ebb1adbf7ae22ffb500ffc3d6b0a30d | #!/usr/bin/env python3
"""
This file contains all the required methods for the street prediction utilizing
the Hough transform.
"""
import numpy as np
import scipy.ndimage as ndi
from skimage.draw import polygon
from skimage.transform import hough_line
def draw_roads(roads, shape):
"""
Creates an image wit... |
6,020 | c5f41b69ac215bd661ee39bdc8c3119db9606ca8 | import os, json, locale, requests, dash, dash_table, copy, time, flask, base64
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objects as go
import pandas as pd
from os import listdir
import plotly.figure_factory as ff
from concurrent.futures import ThreadPoolExecutor, Process... |
6,021 | 95163a28a35cc88240d9d6edc2e9b416e5493909 | import json
import sys
with open(sys.argv[1], 'r') as f:
x = json.load(f)
with open('my_wire_to_quartus_wire.json', 'r') as f:
wirenamemap = json.load(f)
print("----- There are {} muxes in the database".format(len(x)))
print("----- There are {} routing pairs in the database".format(sum((len(v) for k, v in x.i... |
6,022 | f5a953d91e95d82e84e3e6d18ee89d28ba1b1515 | import asyncio
import multiprocessing
from concurrent.futures import ProcessPoolExecutor
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from datetime import datetime
import time
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.combining import OrTrigger
from apschedu... |
6,023 | ca0aedcfb997299240870649823fb872e0d9f99a | from accessor import *
from order import Order
from copy import deepcopy
import pandas as pd
import numpy as np
import util
class Broker:
def __init__(self, equity):
self.execute = Execute(equity) # Execute
def make_order(self, unit, limit_price, stop_loss, stop_profit):
ord... |
6,024 | 4156b003210a41d6ec8f30e2d20adfb1f4b3deb0 | import torch
from torchvision import datasets, transforms
from torch.utils.data import Dataset, DataLoader
# load the data Set
from torch.utils.data import random_split
from torchvision.datasets import ImageFolder
batch_size = 256
data_dir = 'nut_snacks/dataset/'
data_transforms = transfor... |
6,025 | 9bd63181de024c2f4517defa9ed51bdbc8d610d2 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from urllib import request,parse
# req = request.Request('https://api.douban.com/v2/book/2129650')
# req.add_header('User-Agent', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36')
# with request.urlopen(req) as f:... |
6,026 | 3605e8b8b2f8f49cc7c40fc436c147578b12091c | from . import metrics
from . import matrices
from .pairwise import apply_pairwise_rect, apply_pairwise_sparse, apply_running_rect
from . import numba_tools as nb_tools
from . import running_metrics as running
__all__ = ['metrics',
'apply_pairwise_rect',
'apply_pairwise_sparse',
'apply_... |
6,027 | 1dd223854c10e69a397098511eab50b9ebd347c8 | # My Godzilla Hat Code - @alt_bier
from adafruit_circuitplayground.express import cpx
import random
#cpx.pixels.brightness = 0.5 # 50 pct
cpx.pixels.fill((0, 0, 0)) # Turn off the NeoPixels if they're on!
# Function to give us a nice color swirl on the built in NeoPixel (R,G,B)
def wheeln(pos, sft):
if (pos + sf... |
6,028 | ecbc1da3efb39300b60aeb47897fb01b6bd7af31 |
import code2
print ("Main en code1: %s\n" % __name__)
|
6,029 | 4d9064add28302fe173a8b0a81ee7d187db8aead | from typing import Any
from typing import List
from xsdata.codegen.mixins import RelativeHandlerInterface
from xsdata.codegen.models import Attr
from xsdata.codegen.models import Class
from xsdata.models.enums import Tag
from xsdata.utils.namespaces import build_qname
class ClassEnumerationHandler(RelativeHandlerInt... |
6,030 | bc8bc5c3b6954302d005fe618827c644f93ad14e | ### 15/04/2020
### Author: Omer Goder
### Looping through a list
months = ['january','fabruary','march','april','may','june','july','august','september','october','november','december']
# Using a for loop to print a list
for month in months:
print("The next month is:\t" + month)
print('\n')
print("\nEnd ... |
6,031 | 2464da1c4d2ddab3a053f0a14e3cc9a8beabe031 | from MyFeistel import MyFeistel, LengthPreservingCipher
import pytest
import base64
import os
class TestMyFeistel:
def test_Functionality(self):
key = base64.urlsafe_b64encode(os.urandom(16))
feistel = MyFeistel(key, 10)
# decrypt(encrypt(msg)) == msg
for i in xrange(20):
... |
6,032 | e0075e4afafba9da70bbcb2ee073b5c1f7782d7d | import numpy as np
import scipy.signal as sp
from common import *
class Processor:
def __init__(self, sr, **kwargs):
self.samprate = float(sr)
self.hopSize = kwargs.get("hopSize", roundUpToPowerOf2(self.samprate * 0.005))
self.olaFac = int(kwargs.get("olaFac", 2))
def analyze(self, x)... |
6,033 | 8b4bc312bf4b64f98c4f84f4bf89984291be0428 | # Generated by Django 3.1.7 on 2021-03-19 14:38
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('news', '0002_auto_202103... |
6,034 | 75741d11bebcd74b790efe7e5633d4507e65a25f | class HashTable:
def __init__(self):
self.size = 11
self.slots = [None] * self.size
self.data = [None] * self.size
def put(self, key, data):
# there are three situations,
#1. the hashvalue returned by hashfunction of the slot is empty, just put the key in that slot, and the data in the datalist
hashvalu... |
6,035 | 12f05f42c9ed56d6a2c95fb56a8619fae47a2f1a | /home/runner/.cache/pip/pool/9b/88/a0/f20a7b2f367cd365add3353eba0cf34569d5f62a33587f96cebe6d4360 |
6,036 | e11c479a99ab68755de8ab565e3d360d557129cf | # Copyright 2010 Google Inc.
#
# 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 to in writing,... |
6,037 | 0b7bba826b82c3751c072395431e17bc1dc9bb90 | import numpy as np
from scipy import fft
import math
from sklearn import svm
from activity_recognition import WiiGesture
class WiiGestureClassifier():
"""
This class uses the FFT on the average of all three sensor values
to provide the training data for the SVM
Three good distinguishable gestures are... |
6,038 | 3218a9e82cd19bab1680079aee5f09a97992629e | from flask import Flask
app = Flask(__name__)
import orderapi, views, models, processing
if __name__=="__main__":
orderapi.app.debug = True
orderapi.app.run(host='0.0.0.0', port=34203)
views.app.debug = True
views.app.run(host='0.0.0.0', port=42720)
|
6,039 | ade300f2921ca860bbe92aa351df2c88238b7996 | import sys, string, math
s = input()
print(ord(s))
|
6,040 | 848374ea7d706bbd2ef5a76489cabeff998acb82 | # Generated by Django 3.1.5 on 2021-05-30 14:27
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('fuser', '0009_movement_type'),
]
operations = [
migrations.AlterField(
model_name='movementpass... |
6,041 | 6e6f153857879da625f57f0382f1997fcae4f6c8 | from django.db import models
from django.contrib.auth.models import User, Group
from userena.models import UserenaBaseProfile
from django.db.models.signals import post_save
from tastypie.models import create_api_key
class UserProfile(UserenaBaseProfile):
# user reference
user = models.OneToOneField(User)
... |
6,042 | 7b7705cdaa8483f6abbc3f4fb3fa1ca506742da8 | import math,random,numpy as np
def myt():
x=[0]*10
y=[]
for i in range(100000):
tmp = int(random.random()*10)
x[tmp] = x[tmp]+1
tmpy=[0]*10
tmpy[tmp] = 1
for j in range(10):
tmpy[j] = tmpy[j] + np.random.laplace(0,2,None)
y.append(tmpy)
result... |
6,043 | 31a2fa5b2febc2ef80b57e45c2ebb662b886c4b7 | '''Чи можна в квадратному залі площею S помістити круглу сцену радіусом R так,
щоб від стіни до сцени був прохід не менше K?'''
from math import sqrt
s = int(input('Input your area of square (S): '))
r = int(input('Input your radius of scene (R): '))
k = int(input('Input your width of passage (K): '))
k2 = sqrt... |
6,044 | 286801b69546046853d123c5708f24eaaa2e8cec | from __future__ import annotations
from collections import Counter
from distribution import Distribution, Normal
class GoodKind:
"""
The definition of a kind of good. "Vegtable" is a kind of good, as is
"Iron Ore", "Rocket Fuel", and "Electic Motor"
"""
def __init__(self, name: str):
as... |
6,045 | 9a183b1f81681b3dec1132a27b17e389438ab725 | """
Copyright (c) 2017 - Philip Paquette
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, modify, merge, publish, distribu... |
6,046 | 02a28b61ad9d664c89829df019f4887c2c869f91 | import input_data
import tensorflow as tf
from infogan import InfoGAN
if __name__ == '__main__':
# get input data
mnist_data = input_data.load_mnist_dataset('../../dataset/mnist_data', one_hot=True)
num_sample = mnist_data.train.num_examples
dataset = 'mnist'
if dataset == 'mnist':
input_di... |
6,047 | 3abeac4fb80244d2da14e14a6048c09b0c0c1393 | """
You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2.
The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exi... |
6,048 | 58d144b2c6c307719cef0b5097945c8206135ccf | """CPU functionality."""
import sys
HLT = 0b00000001
LDI = 0b10000010
PRN = 0b01000111
MUL = 0b10100010
PUSH = 0b01000101
POP = 0b01000110
CMP = 0b10100111
CALL = 0b01010000
RET = 0b00010001
ADD = 0b10100000
CMP = 0b10100111
JMP = 0b01010100
JEQ = 0b01010101
JNE = 0b01010110
AND = 0b10101000
NOT = 0b01101001
OR = 0b10... |
6,049 | 0054921928838d9aee63cf58f50a0a01ee12635d | from django.db import models
class crontab(models.Model):
name = models.CharField(max_length=20)
class converter(models.Model):
name = models.CharField(max_length=20)
class MainTable(models.Model):
rank = models.IntegerField(null=True)
coinid = models.CharField(max_length=30,null=True)
symbol = ... |
6,050 | ea12ede51881f6e826a044df5d7aba457c434658 | """
Problem Link: https://practice.geeksforgeeks.org/problems/palindrome/0
Given an integer, check whether it is a palindrome or not.
Input:
The first line of input contains an integer T denoting the number of test cases.
For each test case there will be single line containing single integer N.
Output:
Print "Yes" ... |
6,051 | 25b3defc8410c72c7c6f25288af91bd0c826f2ed | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui/about.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtG... |
6,052 | ac0e301e58ea64465ccd4b2b9aa4ae69283d6d0c | import FWCore.ParameterSet.Config as cms
process = cms.Process("GeometryInfo")
# minimum of logs
process.MessageLogger = cms.Service("MessageLogger",
cerr = cms.untracked.PSet(
enable = cms.untracked.bool(False)
),
cout = cms.untracked.PSet(
enable = cms.untracked.bool(True),
thresh... |
6,053 | 64ac007faeebe0e71ba0060e74fa07154e6291e2 | from django.urls import path
from .views import PollsList, SinglePollsView, PollsCreate, PollsAnswer
app_name = "authors"
# app_name will help us do a reverse look-up latter.
urlpatterns = [
path('polls/', PollsList.as_view()),
path('polls/create', PollsCreate.as_view()),
path('polls/<int:pk>', SinglePollsV... |
6,054 | 2a5f69fbb26bd1f94c10ff0da687391bf5bd3c23 | import fs
gInfo = {
'obj': g2.go(capUrl),
'Headers-C-T': g2.response.headers['Content-Type'],
'url': g2.response.url,
'urlDetails': g2.response.url_details()
}
capHtml = capHtml = gInfo['obj'].unicode_body(ignore_errors=True, fix_special_entities=True)
b64cap = re.findall(r'base64,(.*?)\\" id=', capHtml, re.DO... |
6,055 | 1145050d82e614d5c248fc7e6a71720e6ff72414 | # -*- coding: utf-8 -*-
"""
# @Time : 2018/6/11 下午6:45
# @Author : zhanzecheng
# @File : 542.01矩阵1.py
# @Software: PyCharm
"""
# 一个简单的循环方式来解决这个问题
# 这一题的思路不错,用多次循环来计数
# TODO: check 1
class Solution:
def updateMatrix(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[in... |
6,056 | 96708216c5ffa56a60475b295c21b18225e6eed9 | from django.urls import path
from rest_framework.routers import DefaultRouter
from . import views
app_name = "rooms"
router = DefaultRouter()
router.register("", views.RoomViewSet)
urlpatterns = router.urls
#
# urlpatterns = [
# # path("list/", views.ListRoomsView.as_view()),
# # path("list/", views.rooms_vie... |
6,057 | a74f2050a057f579a8a8b77ac04ef09073cdb6cf | import matplotlib.pyplot as plt
import numpy as np
import random
plt.ion()
def draw_board(grid_size, hole_pos,wall_pos):
board = np.ones((grid_size,grid_size))
board[wall_pos] = 10
board[hole_pos] = 0
return board
class Game():
"""
A class which implements the Gobble game. Initializes with a ... |
6,058 | 1935cab249bf559aeadf785ce7abcecb03344c04 | from .signals import get_restaurant_coordinates, count_average_price, count_total_calories
from .dish import Dish
from .ingredients import Ingredient
from .restaurants import Restaurant
|
6,059 | 81ae5bbc8e3e712ee4f54656bc28f385a0b4a29f | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 18 23:54:17 2015
@author: rein
@license: MIT
@version: 0.1
"""
from __future__ import print_function
import numpy as np
import footballpy.processing.ragged_array as ra
""" Ranking dictionary necessary to determine the column number
of each player.
The type ... |
6,060 | 3e7d2bacb15c39658ef5044685b73068deb1c145 | from math import pi
from root_regula_falsi import *
r = 1.0
ρs = 200.0
ρw = 1000.0
def f(h):
Vw = 4*pi*r**3/3 - pi*h**2/3*(3*r - h) # displaced volume of water
Vs = 4*pi*r**3/3
return ρw*Vw - ρs*Vs
xr = root_regula_falsi(f, 0.0, 2*r) |
6,061 | 7f21fcc1265be8b3263971a4e76470616459f433 | from django.core.exceptions import ObjectDoesNotExist
from django.shortcuts import render, HttpResponseRedirect, Http404
from django.contrib.auth import authenticate, login, logout
from accounts.forms import RegistrationForm, LoginForm, StudentDetailsForm, companyDetailsForm, SocietyDetailsForm
from accounts.models im... |
6,062 | 61484d9a08f2e3fcd15573ce89be4118a442dc2e | # Generated by Django 3.1 on 2020-09-26 03:46
import datetime
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('bcs', '0002_auto_20200915_2245'),
]
operations = [
migrations.AddField(
model_name='s... |
6,063 | 1ccb23435d8501ed82debf91bd6bf856830d01cb | from flask import Blueprint, render_template, request, session, url_for, redirect
from flask_socketio import join_room, leave_room, send, emit
from models.game.game import Game
from models.games.games import Games
from decorators.req_login import requires_login
game_blueprint = Blueprint('game', __name__)
@game_bl... |
6,064 | 0d18272f8056f37eddabb024dd769a2793f88c24 | #!/usr/bin/env python
import argparse
import xml.etree.cElementTree as ET
from datetime import datetime, timedelta
from requests import codes as requests_codes
from requests_futures.sessions import FuturesSession
from xml.etree import ElementTree as ET
parser = argparse.ArgumentParser(description='Fetch dqm images')... |
6,065 | 7cc77de31adff5b4a394f117fc743cd6dd4bc06c | import base
import telebot
import markups
from starter import start_bot, bot
@bot.message_handler(commands=['start'])
def start(message):
chat = message.chat
# welcome(msg)
msg = bot.send_message(chat.id, "Select a language in the list", reply_markup=markups.language())
bot.register_next_step_handler(... |
6,066 | 42371760d691eac9c3dfe5693b03cbecc13fd94d | __source__ = 'https://leetcode.com/problems/merge-two-binary-trees/'
# Time: O(n)
# Space: O(n)
#
# Description: Leetcode # 617. Merge Two Binary Trees
#
# Given two binary trees and imagine that when you put one of them to cover the other,
# some nodes of the two trees are overlapped while the others are not.
#
# You... |
6,067 | dafefc65335a0d7e27057f51b43e52b286f5bc6b | from haven import haven_utils as hu
import itertools, copy
EXP_GROUPS = {}
EXP_GROUPS['starter_issam'] = hu.cartesian_exp_group({
'batch_size': 32,
'opt': {'name': 'adamW', 'lr': 0.0001, 'wd': 1e-6},
'model': {'name': 'resnext50_32x4d_ssl'},
... |
6,068 | 67b1cdfa514aac4fdac3804285ec8d0aebce944d | from Bio.PDB import *
import urllib.request
import numpy as np
import pandas as pd
from math import sqrt
import time
import os
import heapq
from datetime import datetime
dir_path = os.getcwd()
peptidasesList = pd.read_csv("./MCSA_EC3.4_peptidases.csv")
peptidasesList = peptidasesList[peptidasesList.iloc[:, 4] == "res... |
6,069 | 1f01989f10be5404d415d4abd1ef9ab6c8695aba | from valuate.predict import *
def get_profit_rate(intent, popularity):
"""
获取畅销系数
"""
# 按畅销程度分级,各交易方式相比于标价的固定比例
profits = gl.PROFITS
profit = profits[popularity]
# 计算各交易方式的价格相比于标价的固定比例
if intent == 'sell':
# 商家收购价相比加权平均价的比例
profit_rate = 1 - profit[0] - profit[1]
el... |
6,070 | 70c9d75dabfa9eac23e34f94f34d39c08e21b3c0 | import rospy
#: the parameter namespace for the arni_countermeasure node
ARNI_CTM_NS = "arni/countermeasure/"
#: the parameter namespace for configuration files
#: of the arni_countermeasure node
ARNI_CTM_CFG_NS = ARNI_CTM_NS + "config/"
def get_param_num(param):
#dummy val
value = 1
try:
value... |
6,071 | 5e68233fde741c0d2a94bf099afb6a91c08e2a29 | def test_corr_callable_method(self, datetime_series):
my_corr = (lambda a, b: (1.0 if (a == b).all() else 0.0))
s1 = Series([1, 2, 3, 4, 5])
s2 = Series([5, 4, 3, 2, 1])
expected = 0
tm.assert_almost_equal(s1.corr(s2, method=my_corr), expected)
tm.assert_almost_equal(datetime_series.corr(datetim... |
6,072 | 49a9fb43f3651d28d3ffac5e33d10c428afd08fd | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def calcLuckyNumber(x):
resultSet = set()
for i in range(30):
for j in range(30):
for k in range(30):
number = pow(3, i) * pow(5, j) * pow(7, k)
if number > 1 and number <= x:
resultSet.add(nu... |
6,073 | 4bf140ae01f2eaa0c67f667766c3ec921d552066 | import pulumi
import pulumi_aws as aws
bar = aws.elasticache.get_replication_group(replication_group_id="example")
|
6,074 | 7254e74ff3f562613cc610e4816a2d92b6b1cd4c | name = 'Ледяная скорбь'
description = 'Тот кто держит этот клинок, должен обладать бесконечной силой. Подобно тому, как он разрывает плоть, он разрывает души.'
price = 3000
fightable = True
def fight_use(user, reply, room):
return 200 |
6,075 | 79a8ff0000f3be79a62d693ed6bae7480673d970 | import argparse
from ray.tune.config_parser import make_parser
from ray.tune.result import DEFAULT_RESULTS_DIR
EXAMPLE_USAGE = """
Training example:
python ./train.py --run DQN --env CartPole-v0 --no-log-flatland-stats
Training with Config:
python ./train.py -f experiments/flatland_random_sparse_small/global... |
6,076 | ff959a388438a6d9c6d418e28c676ec3fd196ea0 | from django.conf.urls import url, include
from api.resources import PlayerResource, GameResource
from . import views
player_resource = PlayerResource()
game_resource = GameResource()
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^api/', include(player_resource.urls)),
url(r'^api/', include(... |
6,077 | e5b5a0c8c0cbe4862243548b3661057240e9d8fd | # -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import pandas
import numpy
import json
import torch.utils.data as data
import os
import torch
def load_json(file):
with open(file) as json_file:
data = json.load(json_file)
return data
class VideoDataSet(data.Dataset):
def __init_... |
6,078 | f08677430e54822abbce61d0cac5a6fea14d3872 | from a10sdk.common.A10BaseClass import A10BaseClass
class MacAgeTime(A10BaseClass):
"""Class Description::
Set Aging period for all MAC Interfaces.
Class mac-age-time supports CRUD Operations and inherits from `common/A10BaseClass`.
This class is the `"PARENT"` class for this module.`
:para... |
6,079 | e55115a65ebee5d41dcd01a5cbabc328acf152da | from flask import Flask
from flask import request, redirect, render_template
from flask_bootstrap import Bootstrap
import urllib.request
import urllib.parse
import json
import uuid
import yaml
import hashlib
from Crypto import Random
from Crypto.Cipher import AES
import base64
app = Flask(__name__)
Bootstrap(app)
... |
6,080 | a5a764586faabb5af58f4649cdd20b6b18236a99 | import numpy as np
class Layer:
def __init__(self):
pass
@property
def need_update(self):
return False
class FC(Layer):
def __init__(self, W, b, lr, decay, epoch_drop, l2=0):
self.W = W.copy()
self.b = b.copy()
self.alpha_0 = lr
self.decay = decay
... |
6,081 | d867d17b2873de7c63d0ff29eb585cce1a68dda6 | import sys
pdb = open(sys.argv[1])
name = sys.argv[2]
res = []
resid = None
for l in pdb:
if not l.startswith("ATOM"):
continue
if int(l[22:26]) != resid:
res.append([])
resid = int(l[22:26])
res[-1].append(l)
for i in range(len(res)-2):
outp = open("%s%d-%dr.pdb"%(name,i+1,i+... |
6,082 | 7ed6d475bfe36fdd0b6cd2f0902a0bccb22f7f60 | # -*- coding: utf-8 -*-
"""
项目:爬取思否网站首页推荐文章
作者:cho
时间:2019.9.23
"""
import json
import parsel
import scrapy
from scrapy import Request
from SF.items import SfItem
class SfCrawlSpider(scrapy.Spider):
name = 'sf_crawl'
allowed_domains = ['segmentfault.com']
header = {
'user-agent': 'Mozilla/5.0 (W... |
6,083 | 14b6dc403be76abef5fde2cca5d773c88faa4b40 | #!usr/bin/python
#--*--coding:utf-8--*--
import sys
import re
if __name__ == '__main__':
category = re.compile('\[\[Category\:.*\]\]')#.は改行以外の任意の文字列にマッチ
for line in open(sys.argv[1]):
if category.search(line) is not None:#比較にはisを用いなければならない
print line.strip() |
6,084 | f0b98a3d6015d57a49e315ac984cac1cccf0b382 | import sys
def input(_type=str):
return _type(sys.stdin.readline().strip())
def main():
N, K, D = map(int, input().split())
rules = [tuple(map(int, input().split())) for _ in range(K)]
minv, maxv = min([r[0] for r in rules]), max([r[1] for r in rules])
while minv + 1 < maxv:
midv = (minv + maxv)//2
cnt, max_... |
6,085 | 4276fd61ad48b325961cd45be68eea6eab51f916 | import os
os.environ['CITY_CONF']='/opt/ris-web/city/duisburg.py'
from webapp import app
app.run(debug=True, host='0.0.0.0')
|
6,086 | ade4d797a83eaa06e8bde90972a56376d7e0f55a | import pprint
class ErrorResponseCollection(object):
def __init__(self, status, message, param = "message"):
self.status = status
self.message = message
self.param = param
def as_md(self):
return '\n\n> **%s**\n\n```\n{\n\n\t"%s": "%s"\n\n}\n\n```' % \
... |
6,087 | 092c6d637fe85136b4184d05f0ac7db17a8efb3b | # -*- coding:utf-8 -*-
import time
from abc import ABCMeta, abstractmethod
from xlreportform.worksheet import WorkSheet
__author__ = "Andy Yang"
class Bases(metaclass=ABCMeta):
def __init__(self):
pass
@abstractmethod
def set_style(self):
"""set workshet's style, indent,bor... |
6,088 | c9b1956d66f0b8ae8a7ce7e509259747c8b7709e | #program, ktory zisti, ci zadany rok je prestupny
rok=input("Zadaj rok: ")
rok_int= int(rok)
if rok_int% 4==0:
if rok_int % 100 != 0:
if rok_int % 400:
print(f'Rok {rok_int} je priestupny')
else:
print("rok je neprestupny")
else:
print("rok je prestupny")
else:
... |
6,089 | 7ba8f0bd962413f6ff825df27330447b11360f10 | from .base import BaseLevel
from map_objects import DefinedMap
from entity.monster import Daemon
from entity.weapons import Axe
class FinalLevel(BaseLevel):
def __init__(self):
lvl_map = DefinedMap('levels/demon_lair.xp')
super().__init__(lvl_map.width, lvl_map.height)
self.map = lvl_... |
6,090 | dc261b29c1c11bb8449ff20a7f2fd120bef9efca | #颜色选择对话框
import tkinter
import tkinter.colorchooser
root = tkinter.Tk()
root.minsize(300,300)
#添加颜色选择按钮
def select():
#打开颜色选择器
result = tkinter.colorchooser.askcolor(title = '内裤颜色种类',initialcolor = 'purple')
print(result)
#改变按钮颜色
btn1['bg'] = result[1]
btn1 = tkinter.Button(root,text = '请选择你的内裤颜色... |
6,091 | e99d557808c7ae32ebfef7e7fb2fddb04f45b13a | class Config(object):
DEBUG = False
TESTING = False
SQLALCHEMY_TRACK_MODIFICATIONS = False
class Production(Config):
SQLALCHEMY_DATABASE_URI = '<Production DB URL>'
class Development(Config):
# psql postgresql://Nghi:nghi1996@localhost/postgres
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'pos... |
6,092 | 6b0b60ec571cf026d0f0cff3d9517362c16b459b | import re
from collections import OrderedDict
OPENING_TAG = '<{}>'
CLOSING_TAG= '</{}>'
U_LIST = '<ul>{}</ul>'
LIST_ITEM = '<li>{}</li>'
STRONG = '<strong>{}</strong>'
ITALIC = '<em>{}</em>'
PARAGRAPH = '<p>{}</p>'
HEADERS = OrderedDict({'######': 'h6',
'#####': 'h5',
'###... |
6,093 | 43792a647243b9d667d6d98b62a086d742e8e910 | from datetime import timedelta
from django import template
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse
from django.utils import timezone
from api.analysis import *
from api.models import Service
register = template.Library()
# ... |
6,094 | e7b1ccbcbb81ff02561d858a4db54d49a2aa0f8a | from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Upload
class DocumentForm(forms.ModelForm):
class Meta:
model = Upload
fields = ('document',)
|
6,095 | cbbb314a3262713f6cb2bb2dd90709d7bf1ca8eb | # i have created this file-hitu
from django.http import HttpResponse
from django.shortcuts import render
from .forms import Sign_Up, Login
from .models import Student
# render is used to create and impot the templates
# render takes first arg = request, 2nd arg = name of the file you want to import, 3rd arg = parame... |
6,096 | 4a8e8994ec8734664a5965b81da9d146d8504f8d | import weakref
from soma.controller import Controller
from soma.functiontools import SomaPartial
from traits.api import File, Undefined, Instance
class MatlabConfig(Controller):
executable = File(Undefined, output=False,
desc='Full path of the matlab executable')
def load_module(capsul_... |
6,097 | d549303228e860ae278a5a9497a4a3a68989aeca | from packer.utils import hello_world
|
6,098 | 4c63072b6242507c9b869c7fd38228488fda2771 | """Test that Chopsticks remote processes can launch tunnels."""
from unittest import TestCase
from chopsticks.helpers import output_lines
from chopsticks.tunnel import Local, Docker, RemoteException
from chopsticks.facts import python_version
def ping_docker():
"""Start a docker container and read out its Python ... |
6,099 | 4736f4e06f166b3c3fd8379a2021eb84a34fcbd3 | import socket
import threading
import os
import time
import psutil
import shutil
class server:
def __init__(self):
self.commandSock = socket.socket()
self.commandPort = 8080
self.transferSock = socket.socket()
self.transferPort = 8088
self.chatSock=socket.socket()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.