index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
700 | 360e661d8538a8f40b7546a54e9a9582fa64bd67 | import numpy as np
from sklearn.metrics import mutual_info_score
def mimic_binary(max_iter=100, fitness_func=None, space=None):
assert fitness_func is not None
assert space is not None
idx = np.random.permutation(np.arange(len(space)))
pool = space[idx[:int(len(space)/2)]] # randomly sample 50% of th... |
701 | f489058c922d405754ad32a737f67bc03c08772b | # Copyright 2018 dhtech
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file
import lib
import urlparse
import yaml
MANIFEST_PATH = '/etc/manifest'
HTTP_BASIC_AUTH = None
def blackbox(name, backend, targets, params,
target='target', path='/probe', label... |
702 | 5299f2c66fd287be667ecbe11b8470263eafab5c | import logging
class ConsoleLogger:
handlers = [
(logging.StreamHandler,
dict(),
"[%(name)s]\t %(asctime)s [%(levelname)s] %(message)s ",
logging.DEBUG)
]
def set_level(self, level):
self.logger.setLevel(level)
def debug(self, message):
self.logger... |
703 | e73e40a63b67ee1a6cca53a328af05e3eb3d8519 | import pytest
from debbiedowner import make_it_negative, complain_about
def test_negativity():
assert make_it_negative(8) == -8
assert complain_about('enthusiasm') == "I hate enthusiasm. Totally boring."
def test_easy():
assert 1 == 1
def test_cleverness():
assert make_it_negative(-3) == 3 |
704 | 01b615f8282d4d42c5e83181fffc2d7cb612c096 | import sys
def saludar(saludo):
print saludo
def iniciales(nombre,ape1,ape2):
iniciales=nombre[0]+'.'+ape1[0]+'.'+ape2[0]+'.'
return "Tus iniciales son:"+iniciales.upper()
def iniciales1(nombre,ape1,*apellidos):
iniciales=nombre[0]+'.'+ape1[0]
for ape in apellidos:
iniciales=iniciales+'.'+ape[0]
return in... |
705 | eeb87891d1a02484a61537745ec6f13387017929 | import os
import shutil
import json
from django.shortcuts import render, HttpResponse
from django.utils.encoding import escape_uri_path
from django.db import transaction
from web_pan.settings import files_folder
from disk import models
# Create your views here.
def logined(func):
def wrapper(request, *args, **k... |
706 | 1b529d8bafc81ef4dd9ff355de6abbd6f4ebddf1 | import logging
from xdcs.app import xdcs
logger = logging.getLogger(__name__)
def asynchronous(func):
def task(*args, **kwargs):
try:
func(*args, **kwargs)
except Exception as e:
logger.exception('Exception during asynchronous execution: ' + str(e))
raise e
... |
707 | cb48a1601798f72f9cf3759d3c13969bc824a0f6 | from pyplasm import *
import random as r
def gen_windows(plan_grid, n, m, window_model):
return STRUCT([
T([1,2])([j,i])(
gen_cube_windows(plan_grid, window_model)(i, j, n, m))
for i in range(n)
for j in range(m)
if plan_grid[i][j]])
def gen_cube_windows(plan_grid, wi... |
708 | 7d3355ee775f759412308ab68a7aa409b9c74b20 | '''
使用random模块,如何产生 50~150之间的数?
'''
import random
num1 = random.randint(50,151)
print(num1) |
709 | 7554b00f8c4d40f1d3ee2341f118048ca7ad10ea | import datetime
class Event(object):
def __init__(self):
self.id = None
self.raw = None
self.create_dt = datetime.datetime.now()
self.device_id = None
self.collector_id = None
self.device_hostname = None
self.device_domain_name = None
self.device_ip_... |
710 | f9db3c96bc3fd4911640d0428672c87072564b0d | """Access IP Camera in Python OpenCV"""
import cv2
#stream = cv2.VideoCapture('protocol://IP:port/1')
# Use the next line if your camera has a username and password
stream = cv2.VideoCapture('rtsp://SeniorDesign:1Hwe2Dxy@10.9.27.28:554/video')
while True:
r, f = stream.read()
cv2.imshow('IP C... |
711 | 7da2be1b530faa8ce9a8570247887e8e0d74c310 | import pandas as pd
#1. 读入数据
#从本地读入“wheat.csv”文件,指定index_col参数为00,即将第一列作为每行的索引。用head()函数查看前几行数据。
data = pd.read_csv("wheat.csv",index_col=0)
print(data.head(6))
#2. 缺失值处理
#该数据集中包含部分缺失值,在模型训练时会遇到特征值为空的问题,故对缺失值进行处理,
## 用DataFrame的fillna方法进行缺失值填充,填充值为用mean方法得到的该列平均值。
data = data.fillna(data.mean())
print(data)
#3. 划分数据... |
712 | 7036ae5f74e6cb04518c20bb52122a1dfae76f23 | import json
from bokeh.plotting import figure, output_file
from bokeh.io import show
from bokeh.palettes import inferno
from bokeh.models import ColumnDataSource, FactorRange
from bokeh.transform import factor_cmap
from bokeh.models import HoverTool
# from bokeh.io import export_svgs
def read_summary(summary_file):
... |
713 | 5eb5388ffe7a7c880d8fcfaa137c2c9a133a0636 | import wikipedia
input_ = input("Type in your question ")
print(wikipedia.summary(input_))
|
714 | 51540a80c7b29dc0bbb6342ee45008108d54b6f2 | # -*- coding: utf-8 -*-
import numpy as np
def gauss_seidel(relax, est, stop):
"""
Método iterativo de Gauss-Seidel para o sistema linear do trabalho.
Onde relax é o fator de relaxação, est é o valor inicial, stop é o
critério de parada, n é a quantidade de linhas do sistema e k é o
nú... |
715 | eb981a2d7f0ff5e6cc4a4a76f269c93c547965ba | from typing import Any, Dict, List
import numpy as np
from kedro.io import AbstractDataSet
from msrest.exceptions import HttpOperationError
from azureml.core import Workspace, Datastore
from azureml.data.data_reference import DataReference
class AZblob_datastore_data(AbstractDataSet):
"""``ImageDataSet`` loads /... |
716 | 0beb5c5c5db9247d66a5a49cfff7282ead52a9b7 | #!/usr/bin/env python
import h5py
class HDF5_Parser(object): # noqa: N801
"""
Examples
--------
>>> import h5py
>>> indata = h5py.File('test.hdf5')
>>> dataset = indata.create_dataset("mydataset", (10,), dtype='i')
>>> indata.close()
>>> with open('test.hdf5') as f:
... da... |
717 | 93d4c6b6aef827d6746afc684c32a9cf1d0229e4 | # 가위, 바위, 보 게임
# 컴퓨터 가위, 바위, 보 리스트에서 랜덤하게 뽑기 위해 random 함수 호출
import random
# 컴퓨터 가위, 바위, 보 리스트
list_b = ["가위", "바위", "보"]
# 이긴횟수, 진 횟수 카운팅 하기 위한 변수
person_win_count = 0
person_lose_count = 0
while person_win_count < 4 or person_lose_count < 4:
# 가위, 바위, 보 입력 받기
player = input("가위, 바위, 보 중 어떤 것을 낼래요? ")
... |
718 | d7d94cfed0b819297069c3434c70359a327403cd | from django.contrib import admin
from . import models
admin.site.register(models.Comentario)
# Register your models here.
|
719 | 32f9b5c32acbb6411fe6ab99616d8459acfd7c74 | import os
import pubmed_parser as pp
nlpPath = "/Users/kapmayn/Desktop/nlp"
articlesFolderPath = nlpPath + "/articles"
abstractsFilePath = nlpPath + "/abstracts.txt"
articlesFileNameList = os.listdir(articlesFolderPath)
articlesFileNameList(reverse = True)
resultFile = open(abstractsFilePath, 'w')
for fileName in ar... |
720 | 373c102018fdcc5211263304c368c2e8beef3257 | # -- coding: utf-8 --
from django.conf.urls import url
from myapp.view import views
from myapp.view import story
from myapp.view import img # 添加
from myapp.view import login
from myapp.view import tuling
from myapp.view import utilView
from myapp.view.wechat import wechat_modules
from myapp.view import router
urlpatt... |
721 | 622b388beb56eba85bbb08510c2bcea55f23da9a | data = " Ramya , Deepa,LIRIL ,amma, dad, Kiran, 12321 , Suresh, Jayesh, Ramesh,Balu"
lst = data.split(",")
for name in lst:
name = name.strip().upper()
rname = name[::-1]
if name == rname:
print(name)
girlsdata = "Tanvi,Dhatri,Haadya,Deepthi,Deepa,Ramya"
# Name which start with DEE get those name... |
722 | e1787fd4be66d19ab83ece44eacfd96cb488b504 | with expression [as var]
#...BODY...
#object is the result of the expression and must have __enter__ and __exit__ methods
#result of the expression must be context manager - implements context management protocol
#https://www.python.org/dev/peps/pep-0343/
# This PEP adds a new statement "with" to the Python language... |
723 | f3167d8f1a806c38fb10672605d8e94265d2fc9c | from database import db
from database import ma
from datetime import datetime
from sqlalchemy import ForeignKeyConstraint
from models.admin import Admin, admin_limited_schema
from models.event_status import EventStatus, event_status_schema
from models.org_unit import org_unit_schema
class Event(db.Model):
# class ... |
724 | a26cab29f0777764f014eeff13745be60e55b62d | import requests
#try make the request
try:
r = requests.get('http://skitter.com')
print(r) # see the results
# catch a failue
except (requests.ConnectionError, requests.Timeout) as x:
pass |
725 | de77edaccdaada785f41828135ad2da4ae2b403e | from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.mail import EmailMultiAlternatives
from django.template import loader
from django.conf import settings
from django.contrib.sites.shortcuts import ... |
726 | c3efaeab600ec9a7a9fffdfad5c9dc1faad8fee7 | try:
from LoggerPlugin import LoggerPlugin
except ImportError:
from RTOC.LoggerPlugin import LoggerPlugin
from .holdPeak_VC820.vc820py.vc820 import MultimeterMessage
import serial
import sys
import traceback
from PyQt5 import uic
from PyQt5 import QtWidgets
import logging as log
log.basicConfig(level=log.INFO... |
727 | 776470546585257bf06073e2d894e8a04cf2376d | """
Duck typing
Ref: http://www.voidspace.org.uk/python/articles/duck_typing.shtml
"""
##########
# mathmatic operator (syntactic sugar)
print 3 + 3
# same as >>>
print int.__add__(3, 3)
# <<<
# overload '+' operator
class Klass1(object):
def __init__(self, a, b):
self.a = a
self.b = b
def __a... |
728 | 60b5e515c7275bfa0f79e22f54302a578c2f7b79 | def find_happy_number(num):
slow, fast = num, num
while True:
slow = find_square_sum(slow) # move one step
fast = find_square_sum(find_square_sum(fast)) # move two steps
if slow == fast: # found the cycle
break
return slow == 1 # see if the cycle is stuck on the number '1'
def find_square_... |
729 | af1a6c6009b21962228fbe737f27c22bf9460762 | from gevent.event import Event
from gevent.queue import Queue
from ping_pong_chat.aio_queue import AGQueue
received_event = Event()
leave_rooms_event = Event()
exit_event = Event()
output_message_queue = AGQueue()
input_message_queue = AGQueue()
matrix_to_aio_queue = AGQueue()
aio_to_matrix_queue = AGQueue()
sync_to_... |
730 | ed80f5f898548ca012779543051ccff5b34e4fcc | from django.shortcuts import render
import requests
from bs4 import BeautifulSoup
import json
from rest_framework.response import Response
from rest_framework.decorators import api_view,authentication_classes,permission_classes
from rest_framework import status
from django.contrib.staticfiles.storage import staticfiles... |
731 | 53fae0103168f4074ba0645c33e4640fcefdfc96 | from urllib.error import URLError
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
import pymysql
import ssl
from pymysql import Error
def decode_page(page_bytes, charsets=('utf-8',)):
"""通过指定的字符集对页面进行解码(不是每个网站都将字符集设置为utf-8)"""
page_html = None
for charset in charsets:
try... |
732 | 45fcafdd30f890ddf5eaa090152fde2e2da4dbef | # 튜플(tuple) - 리스트와 구조가 비슷함
#변경, 삭제 할 수 없다.
t = ('코스모스', '민들레', '국화')
print(t)
print(t[:2])
print(t[1:])
#del t[0] - 삭제 안됨
#t[2] ="매화" - 수정 안됨
t2 = (1, 2, 3)
t3 = (4,) # 1개 추가하기 (쉼표를 붙임)
print(t2)
print(t3)
print(t2 + t3) # 요소 더하기
|
733 | 73e7e43e9cfb3c0884480809bc03ade687d641d6 | from os import wait
import cv2
import numpy as np
import math
import sys
import types
import operator
## orb 및 bf matcher 선언
orb = cv2.cv2.ORB_create(
nfeatures=5000,
scaleFactor=1.2,
nlevels=8,
edgeThreshold=31,
... |
734 | d9538c030c0225c4255100da70d6bf23f550a64f | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2011 NovaPoint Group LLC (<http://www.novapointgroup.com>)
# Copyright (C) 2004-2010 OpenERP SA (<http://www.openerp.com>)
#
# This program is f... |
735 | eb558644283d992af2c324d457dbe674b714235f | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from django.http import JsonResponse
from knowdb.models import Knowledge
import random
# Create your views here.
def answer(request):
ret = {}
data = Knowledge.objects.all()
num = random.choice(range(1,int... |
736 | 40b6d62f1e360c0df19b7e98fcb67dbd578e709f | #!/usr/bin/python
# -*- coding: utf-8 -*-
import csv
from collections import defaultdict
from docopt import docopt
__doc__ = """{f}
Usage:
{f} <used_file>
{f} -h | --help
Options:
-h --help Show this screen and exit.
""".format(f=__file__)
args = docopt(__doc__)
used_file = args['<used_file>']
... |
737 | 4e8a5b0ba13921fb88d5d6371d50e7120ab01265 | from metricsManager import MetricsManager
def TestDrawGraphs():
manager = MetricsManager()
manager.displayMetricsGraph()
return
def main():
TestDrawGraphs()
if __name__ == "__main__":
main()
|
738 | f1f708f00e05941c9a18a24b9a7556558583c3c7 | TRAIN_INPUT_PATH = "~/Projects/competitions/titanic/data/train.csv"
TEST_INPUT_PATH = "~/Projects/competitions/titanic/data/test.csv"
OUTPUT_PATH = "output/"
TRAIN_VAL_SPLIT = 0.75
RANDOM_SEED = 42
MODEL = "LOGISTIC_REGRESSION"
LOG_PATH = "logs/"
|
739 | 911631e96d21bdf22a219007f1bdc04a5e6965dc | __author__ = 'Administrator'
# 抓取IP的主要逻辑
from urllib import request
import urllib.parse
import logging
from multiprocessing import pool
from time import sleep
import random
from lxml import etree
def getRandomUserAgnet():
user_agents=[
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Ge... |
740 | bc890f0f40a7e9c916628d491e473b5ecfa9bb9b | from random import random
import numpy as np
class TemperatureSensor:
sensor_type = "temperature"
unit="celsius"
instance_id="283h62gsj"
#initialisation
def __init__(self, average_temperature, temperature_variation, min_temperature, max_temperature):
self.a... |
741 | fe597ad4462b1af3f3f99346c759c5fa8a7c14f4 | def check_ip_or_mask(temp_str):
IPv4_regex = (r'(?:[0-9]{1,3}\.){3}[0-9]{1,3}')
temp_list_ip_mask = re.findall(IPv4_regex, temp_str)
binary_temp_list_ip_mask = []
temp_binary_ip_mask = ''
for x in range(len(temp_list_ip_mask)):
split_ip_address = re.split(r'\.', temp_list_ip_mask[x])
... |
742 | 0528d7761cbbf3dbe881ff05b81060f3d97e7f6c | import collections
import copy
import threading
import typing as tp
from ..decorators.decorators import wraps
from ..typing import K, V, T
class Monitor:
"""
Base utility class for creating monitors (the synchronization thingies!)
These are NOT re-entrant!
Use it like that:
>>> class MyProtec... |
743 | 8c336edddadbf4689721b474c254ded061ecf4b5 | from . import scramsha1, scrammer
|
744 | 0fb288e3ab074e021ec726d71cbd5c8546a8455b | import shutil
import tempfile
import salt.runners.net as net
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.mock import MagicMock
from tests.support.runtests import RUNTIME_VARS
from tests.support.unit import TestCase, skipIf
@skipIf(not net.HAS_NAPALM, "napalm module required for this tes... |
745 | b12c8d0cb1cd1e48df6246fe3f16467b2db296e0 | import sys
def dir_slash():
slash = '/'
if 'win' in sys.platform: slash = '\\'
return slash
|
746 | a09bc84a14718422894127a519d67dc0c6b13bc9 | #n = int(input())
#s = input()
n, m = map(int, input().split())
#s, t = input().split()
#n, m, l = map(int, input().split())
#s, t, r = input().split()
#a = map(int, input().split())
#a = input().split()
a = [int(input()) for _ in range(n)]
#a = [input() for _ in range(n)]
#t = input()
#m = int(input())
#p, q = map(in... |
747 | 330b843501e0fdaff21cc4eff1ef930d54ab6e8d | '''
Temperature Container
'''
class TempHolder:
range_start = 0
range_end = 0
star_count_lst = [0,0,0,0,0,0]
counter = 0
def __init__(self, in_range_start, in_range_end):
self.range_start = in_range_start
self.range_end = in_range_end
self.counter = 0
self.s... |
748 | 28d8f9d9b39c40c43a362e57a7907c0a38a6bd05 | """
Platformer Game
"""
import arcade
import os
from Toad_arcade import Toad
# Constants
SCREEN_WIDTH = 1920
SCREEN_HEIGHT = 1080
SCREEN_TITLE = "PyToads - Battletoads reimplementation"
# Constants used to scale our sprites from their original size
CHARACTER_SCALING = 1
TILE_SCALING = 0.5
COIN_SCALING = 0.5
MOVEMENT_S... |
749 | b51591de921f6e153c1dd478cec7fad42ff4251a | from flask import request, Flask
import ldap3
app = Flask(__name__)
@app.route("/normal")
def normal():
"""
A RemoteFlowSource is used directly as DN and search filter
"""
unsafe_dc = request.args['dc']
unsafe_filter = request.args['username']
dn = "dc={}".format(unsafe_dc)
search_filte... |
750 | 555f4e41661ff4cbf4b9d72feab41ca8b7da2d5f | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 28 12:54:27 2018
@author: Alex
"""
import numpy as np
def saveListToCSV(filepath, _list):
with open(filepath,'ab') as f:
np.savetxt(f, [_list], delimiter=',', fmt='%f') |
751 | 81f5753e8d0004244b4ee8e26895cb2b38fbb8b6 | #coding=utf-8
import shutil
import zipfile
# shutil.copyfile("file03.txt","file05.txt") #拷贝
# shutil.copytree("movie/大陆","电影") #拷贝文件夹
#忽略不需要拷贝的文件
# shutil.copytree("movie/大陆","电影",ignore=shutil.ignore_patterns("*.txt","*.html"))
#压缩和解压缩
# shutil.make_archive("电影/压缩","zip","movie/大陆")
z1 = zipfile.ZipFile("a.z... |
752 | ea2e9399a8384600d8457a9de3f263db44dc883d | import pandas as pd
# 데이터 로드
train_data = pd.read_csv('./dataset/train_park_daycare.csv')
cctv = pd.read_csv("./dataset/cctv_origin.csv", encoding="EUC-KR")
## 데이터 전처리
# 데이터 추출
cctv = cctv.iloc[1:, :2]
# 구 매핑
gu_dict_num = {'용산구': 0, '양천구': 1, '강동구': 2, '관악구': 3, '노원구': 4, '영등포': 5, '영등포구': 5, '마포구': 6, '서초구': 7, '성... |
753 | 86d42716e05155f9e659b22c42635a8f5b8c4a60 | import tensorflow as tf
from typing import Optional, Tuple, Union, Callable
_data_augmentation = tf.keras.Sequential(
[
tf.keras.layers.experimental.preprocessing.RandomFlip("horizontal"),
tf.keras.layers.experimental.preprocessing.RandomRotation(0.2),
]
)
def _freeze_model(
model: tf.ker... |
754 | cac9d84f20a79b115c84ff4fe8cf4640182a42d7 | """Those things that are core to tests.
This module provides the most fundamental test entities, which include such
things as:
- Tests
- Suites
- Test states
"""
from __future__ import print_function
__docformat__ = "restructuredtext"
import os
import textwrap
import time
import weakref
import inspect
from clevers... |
755 | 7b1c7228c1fc9501ab857cba62a7e073691e75c9 | """
@Description:
@Author : HCQ
@Contact_1: 1756260160@qq.com
@Project : pytorch
@File : call_test
@Time : 2022/5/24 下午10:19
@Last Modify Time @Version @Desciption
-------------------- -------- -----------
2022/5/24 下午10:19 1.0 None
"""
class Person():
def __cal... |
756 | 6a7e5a78f516cecf083ca3900bdaaf427bedd497 | # -*- coding: utf-8 -*-
"""
Created on Tue May 22 15:01:21 2018
@author: Weiyu_Lee
"""
import numpy as np
import pandas as pd
import pickle
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
import config as conf
def get_stock_time_series(data_df, stock_id):
curr_ID_dat... |
757 | 5a33aeffa740a41bd0bd1d80f45796ae37377a4c | from django.contrib.postgres.fields import JSONField
from django.db import models
from core.utils.time import get_now
class BaseManager(models.Manager):
"""
Our basic manager is used to order all child models of AbstractLayer
by created time (descending), therefore it creates a LIFO order,
causing th... |
758 | 5cfd7744f98c80483cb4dd318c17a7cd83ed3ae3 | """
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[2,3]
"""
# O(n) TC and SC
class Solution:
... |
759 | cfa862988edf9d70aa5e975cca58b4e61a4de847 | """
USAGE:
o install in develop mode: navigate to the folder containing this file,
and type 'python setup.py develop --user'.
(ommit '--user' if you want to install for
all users)
"""
from setupt... |
760 | 7b9660bba6fcb8c725251971f3733a1cc915c0e7 | """
Rectangles: Compute overlapping region of two rectangles.
Point(x: number, y: number): Cartesian coordinate pair
Rect(ll: Point, ur: Point): A rectangle defined by lower left
and upper right coordinates
Rect.overlaps(other: Rect) -> boolean: True if non-empty overlap
Rect.intersect(other: Rect... |
761 | f25351a3cb7bf583152baa8e7ec47b0f2161cb9c | # Copyright 2014 The crabapple Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
import abc
class Notifier(object):
__metaclass__ = abc.ABCMeta
def __init__(self):
pass
@abc.abstractmethod
def config(self, kwa... |
762 | d0eb6ea2e816ac59ae93684edb38ff3a49909633 | def usage_list(self):
print('Available modules')
print('=================')
for module in sorted(self.list()):
if ('module' not in self.mods[module]):
self.import_module(module)
if (not self.mods[module]['module'].__doc__):
continue
text = self.mods[module]['m... |
763 | f3329962004a4454c04327da56d8dd1d0f1d45e7 | import csv
import datetime
import json
import re
import requests
import os
r = requests.get("https://www.hithit.com/cs/project/4067/volebni-kalkulacka-on-steroids")
path = os.path.dirname(os.path.realpath(__file__)) + "/"
if r.status_code == 200:
text = r.text
pattern = 'Přispěvatel'
m = re.search(patter... |
764 | 2c505f3f1dfdefae8edbea0916873229bcda901f | from flask import Blueprint
class NestableBlueprint(Blueprint):
def register_blueprint(self, blueprint, **options):
def deferred(state):
# state.url_prefix => 自己url前缀 + blueprint.url_prefix => /v3/api/cmdb/
url_prefix = (state.url_prefix or u"") + (options.get('url_prefix', bluepri... |
765 | 5721786b61cf8706b1d401a46d06f2d32153df8b | n=int(input("enter the number\n"))
sum=0
for i in range(1,n-1):
rem=n%i
if(rem==0):
sum=sum+i
if(sum==n):
print("the number is perfect")
else:
print("not prime")
|
766 | 24f87bd6aab0ff65cf2153e27df31122818ad0ac | import unittest
from Spreadsheet.HTML import Table
class TestColGroup(unittest.TestCase):
def test_colgroup(self):
return
data = [
['a','b','c'],
[1,2,3],
[4,5,6],
]
gen = Table( { 'data': data, 'colgroup': { 'span': 3, 'width': 100 }, 'attr_so... |
767 | 2a0172641c48c47f048bf5e9f1889b29abbb0b7c | #!/usr/bin/env python3
#coding=utf8
from __future__ import (division,absolute_import,print_function,unicode_literals)
import argparse, csv, sys,subprocess,time
NR_THREAD=20
def shell(cmd):
subprocess.call(cmd,shell=True)
print("Done! {0}.".format(cmd))
start=time.time()
cmd = 'mkdir FTRL/tmp -p'
shell(cmd)
... |
768 | eab5bf4776582349615ad56ee1ed93bc8f868565 | from common import *
import serial
CMD_BAUD = chr(129)
BAUD_RATES = [300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, 115200]
class Communication(Module):
def __init__(self, parent, port_name, baud_rate):
self.parent = parent
if not isinstance(port_name, str):
ra... |
769 | abbad57e945d2195021948a0e0838c6bfd9c6a1e | #connect4_JayNa.py
#Jay Na
#CS111 Spring 2018
#This file creates a version of the game Connect4, where the user plays against an AI
from graphics import *
import random
class ConnectWindow:
def __init__(self):
self.window = GraphWin("Connect Four", 690, 590)
self.window.setMouseHandler(self.handleClick)
self.... |
770 | 96d5cf948a9b0f622889977e8b26993299bceead | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 18 13:37:10 2018
@author: ninja1mmm
"""
import os
import numpy as np
import pandas as pd
from sklearn import preprocessing
def file_name(file_dir):
root_tmp=[]
dirs_tmp=[]
files_tmp=[]
for root, dirs, files in os.walk(file_dir): ... |
771 | d09984c6e6a0ce82389dbbbade63507e9687355d | # Generated by Django 2.2.6 on 2019-12-23 16:38
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('Pages', '0014_auto_20191223_2032'),
]
operations = [
migrations.AlterField(
model_name='dept',
... |
772 | 5d4ef314bb7169f5de4795e5c1aca62a1a060bae | from django.db import models
# Login Admin Model
class AdminLoginModel(models.Model):
user_name = models.CharField(max_length=30,unique=True)
password = models.CharField(max_length=16)
# Swiggy Admin State Table
class AdminStateModel(models.Model):
state_id = models.AutoField(primary_key=True)
sta... |
773 | 5c5f00084f37837b749e1fbb52a18d515e09ba06 | import graph as Graph
def BFS(graph: Graph.Graph, start, end):
visited = set()
parent = dict()
parent[start] = None
queue = []
queue.append(start)
visited.add(start)
while queue:
current = queue.pop(0)
if current == end:
break
for v in graph.neighbor... |
774 | 6b785502e8a8983c164ebdffdd304da47c926acb | from django.apps import AppConfig
class LaughsappConfig(AppConfig):
name = 'laughsApp'
|
775 | 4a7f8221208e8252c7f5c0adff2949f0e552def1 | from azureml.core import Workspace
from azureml.pipeline.core import Pipeline
from azureml.core import Experiment
from azureml.pipeline.steps import PythonScriptStep
import requests
ws = Workspace.from_config()
# Step to run a Python script
step1 = PythonScriptStep(
name = "prepare data",
source_di... |
776 | 03fb1cf0aac0c37858dd8163562a7139ed4e1179 | import dtw
import stats
import glob
import argparse
import matplotlib.pyplot as plt
GRAPH = False
PERCENTAGE = False
VERBOSE = False
def buildExpectations(queryPath, searchPatternPath):
"""
Based on SpeechCommand_v0.02 directory structure.
"""
expectations = []
currentDirectory = ""
queryFile... |
777 | 303a8609cb21c60a416160264c3d3da805674920 | import tensorflow as tf
import tensorflow_probability as tfp
import pytest
import numpy as np
from estimators import NormalizingFlowNetwork
tfd = tfp.distributions
tf.random.set_seed(22)
np.random.seed(22)
@pytest.mark.slow
def test_x_noise_reg():
x_train = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300,... |
778 | 830e7e84eebd6a4adb411cc95c9e9c8ff7bdac30 | def isSubsetSum(set, n, sum):
subset =([[False for i in range(sum + 1)] for i in range(n + 1)])
for i in range(n + 1):
subset[i][0] = True
for i in range(1, sum + 1):
subset[0][i]= False
for i in range(1, n + 1):
for j in range(1, sum + 1):
if j<set[i-1]:
... |
779 | e60c3a6aececd97ec08ae32b552bcda795375b3b | import os
import sys
from shutil import copyfile
def buildDocumentation():
"""
Build eMonitor Documentation with sphinx
:param sys.argv:
* html: build html documentation in directory */docs/output/html*
* pdf: build pdf documentation in directory */docs/output/pdf*
"""
helptext = 'u... |
780 | 00a0668d5fcb8358b4bd7736c48e4867afc0f5b6 | """
Copyright 2019 Enzo Busseti, Walaa Moursi, and Stephen Boyd
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 ... |
781 | f5c277da2b22debe26327464ae736892360059b4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
month=['Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb','Mar','Apr','May']
df = pd.DataFrame([[53, 0, 5, 3, 3],[51, 0, 1, 3, 2],[70, 4, 7, 5, 1],[66, 4, 1, 4, 2],[64, 4, 4, 3, 2],[69, 4, 7, 8, 2],[45, 2, 8, 4, 2],[29, 1, 6, 6, 1],[56, 4, 4,... |
782 | 5c2a6802e89314c25f0264bbe2bc7ed2689a255a | a=input("Please enter the elements with spaces between them:").split()
n=len(a)
for i in range(n):
a[i]=int(a[i])
for i in range(n-1):
for j in range(n-i-1):
if a[j]>a[j+1]:
a[j],a[j+1]=a[j+1],a[j]
print("Sortes array :",a) |
783 | 20f0480ee7e0782b23ec8ade150cdd8d8ad718bb | from math import pow
from math import tan
import plotly.figure_factory as ff
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
def euler():
h = 0.1
x = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5]
y_eval = [0.0]
delta_y = [0.0]
y_real = [0.0]
eps = [0.0]
for i in range(1, le... |
784 | f145274c8caa1e725d12003874eb54a580a6e35e | dic = {"city": "Moscow", "temperature": 20}
# print(dic["city"])
# dic["temperature"] -= 5
# print(dic)
print(dic.get("country", "Russia"))
dic["date"] = "27.05.2019"
print(dic) |
785 | 038b8206f77b325bf43fc753f6cee8b4278f4bc9 | import logging
import numpy as np
from deprecated import deprecated
from pycqed.measurement.randomized_benchmarking.clifford_group import clifford_lookuptable
from pycqed.measurement.randomized_benchmarking.clifford_decompositions import gate_decomposition
from pycqed.measurement.randomized_benchmarking.two_qubit_clif... |
786 | 3421c3b839721694945bdbb4f17183bceaed5296 | import unittest
import ConvertListToDict as cldf
class MyDictTestCase(unittest.TestCase):
def test_Dict(self):
# Testcase1 (len(keys) == len(values))
actualDict1 = cldf.ConvertListsToDict([1, 2, 3],['a','b','c'])
expectedDict1 = {1: 'a', 2: 'b', 3: 'c'}
self.assertEqual(actualDict1,... |
787 | 1ea61ab4003de80ffe9fb3e284b6686d4bf20b15 | # Generated by Django 3.2.3 on 2021-08-26 09:18
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Restaura... |
788 | 6db7189d26c63ca9f9667045b780ec11994bac28 | import sys
from pypregel import Pypregel
from pypregel.vertex import Vertex, Edge
from pypregel.reader import Reader
from pypregel.writer import Writer
from pypregel.combiner import Combiner
class PageRankVertex(Vertex):
def compute(self):
if self.superstep() >= 1:
s = 0
while sel... |
789 | 78dc2193c05ddb4cd4c80b1c0322890eca7fcf19 | import signal
import time
import sdnotify
n = sdnotify.SystemdNotifier()
if __name__ == '__main__':
n.notify("READY=1")
time.sleep(2)
|
790 | 2fadc5c90d1bae14c57fc3bf02582e12aa8abdf6 |
import array
from PIL import Image
from generic.editable import XEditable as Editable
class PLTT(Editable):
"""Palette information"""
FORMAT_16BIT = 3
FORMAT_256BIT = 4
def define(self, clr):
self.clr = clr
self.string('magic', length=4, default='PLTT') # not reversed
self... |
791 | bd06b04666ade1e7591b02f8211bc9b62fd08936 | #!/usr/bin/env python
import sys
import errno
# read first line from stdin and discard it
first_line = sys.stdin.readline()
# print all other lines
for line in sys.stdin:
try:
print line,
except IOError, e:
if e.errno == errno.EPIPE:
exit(0)
|
792 | 360063940bb82defefc4195a5e17c9778b47e9e5 | from requests import post
import json
import argparse
import base64
from ReadFromWindow import new_image_string
from ParsOnText import ParsOnText
# Функция возвращает IAM-токен для аккаунта на Яндексе.
def get_iam_token(iam_url, oauth_token):
response = post(iam_url, json={"yandexPassportOauthToken": oauth_token})... |
793 | 75716aaaca63f8ca6d32c885021c1dc0f9a12dac | # -*- coding: utf-8 -*-
# Third party imports
import numpy as np
# Local application imports
from mosqito.sound_level_meter import noct_spectrum
from mosqito.sq_metrics.loudness.loudness_zwst._main_loudness import _main_loudness
from mosqito.sq_metrics.loudness.loudness_zwst._calc_slopes import _calc_slopes
from mosq... |
794 | 0e9d0927e8d69b0c0fad98479d47f2409c95a751 | n = int(input())
a = sorted([int(input()) for _ in range(n)])
x = a[:n//2]
y = a[(n + 1)//2:]
ans = 0
for i in range(len(x)):
ans += abs(x[i] - y[i])
for i in range(1, len(y)):
ans += abs(x[i - 1] - y[i])
if n % 2 == 1:
ans += max(
abs(a[n // 2] - x[-1]),
abs(a[n // 2] - y[0]),
)
print... |
795 | e3dece36ba3e5b3df763e7119c485f6ed2155098 | # Core Packages
import difflib
import tkinter as tk
from tkinter import *
from tkinter import ttk
from tkinter.scrolledtext import *
import tkinter.filedialog
import PyPDF2
from tkinter import filedialog
import torch
import json
from transformers import T5Tokenizer, T5ForConditionalGeneration, T5Config
# ... |
796 | 64366e8532ffe05db7e7b7313e1d573c78a4e030 | import packaging.requirements
import pydantic
import pytest
from prefect.software.pip import PipRequirement, current_environment_requirements
class TestPipRequirement:
def is_packaging_subclass(self):
r = PipRequirement("prefect")
assert isinstance(r, packaging.requirements.Requirement)
def ... |
797 | 8c318d7152bfdf2bc472258eb87dfa499b743193 | # coding:utf-8
def application(env,handle_headers):
status="200"
response_headers=[
('Server','')
]
return "" |
798 | 6a601d1c7c3c162c0902d03e6c39f8d75d4bcaf0 | import numpy as np, argparse, sys, itertools, os, errno, warnings
from mpi4py import MPI
from enlib import enmap as en, powspec, utils
from enlib.degrees_of_freedom import DOF, Arg
from enlib.cg import CG
warnings.filterwarnings("ignore")
#from matplotlib.pylab import *
parser = argparse.ArgumentParser()
parser.add_ar... |
799 | af35075eaca9bba3d6bdb73353eaf944869cdede | # Software Name: MOON
# Version: 5.4
# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors
# SPDX-License-Identifier: Apache-2.0
# This software is distributed under the 'Apache License 2.0',
# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt'
# or see the "LI... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.