text stringlengths 8 6.05M |
|---|
import numpy as np
X=np.loadtxt('data')
#X = np.random.normal(size=[20,8])
#np.savetxt('data', X)
Y=np.zeros((np.size(X[:, 0]), 4), 'complex')
for a in range(0, 4): Y[:,a]=X[:, 2*a]+1j*X[:, 2*a+1]
print Y
#P, D, Q = np.linalg.svd(Y)
P, D, Q = np.linalg.svd(Y, False)
Y_a = np.dot(np.dot(P, np.diag(D)), Q)
print(np.s... |
from heart_server_helpers import validate_patient
import pytest
@pytest.mark.parametrize("pat_id, expected", [
(-1, True),
(-2, True),
(-3, False),
])
def test_existing_beats(pat_id, expected):
pat_exist = validate_patient(pat_id)
assert pat_exist == expected
|
# -*- coding: utf-8 -*-
"""Unittests for Janitoo.
"""
__license__ = """
This file is part of Janitoo.
Janitoo is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
... |
from sqlalchemy import Column, String, create_engine, event, DDL, Integer, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from datetime import datetime, timezone
conn_string = "postgres://user:pwd@localhost:5432/code_examples"
db = create_engine(conn_string, ec... |
from apps.items.models.weapons import *
from apps.items.models.ships import *
|
from netCDF4 import Dataset
from sklearn.preprocessing import StandardScaler
import numpy as np
import pandas as pd
file_extensions = ['air.2m.gauss','uwnd.10m.gauss','pr_wtr.eatm','slp','vwnd.10m.gauss']
folders = ['Air Temperature', 'Horizontal Wind','Precipitation Water', 'Sea Level Pressure','Vertical Wind']
Varia... |
def cal_height(plates):
height = 10
for i in range(1, len(plates)):
if plates[i] == plates[i-1]:
height += 5
else:
height += 10
return height
plates = input()
print(cal_height(plates))
|
"""Unit test package for pygpt."""
|
# Total purchase
# Calculate and show the total purchase for items
# Anatoli Penev
# 27.10.1017
mouse = float(input('Enter price')) # enter price for item "mouse"
keyboard = float(input('Enter price')) # enter price for item "keyboard"
desk = float(input('Enter price')) # enter price for item "desk"
chair = float(i... |
import random
class LinkedList:
def __init__(self):
self.head = 0
self.size = 0
class Node:
def __init__(self,element,next=None ):
self.element = element
self.next = next
def push(self,e):
self.head = self.Node(e,self.head)
... |
from pyModbusTCP import utils
def rewrite_modbus_read(list):
new_list = dict()
for i in range(1,len(list)):
if i%2:
new_list[(i+1)/2] = hex(list[i]) + hex(list[i-1])[2:]
# else:
# new_list[i-1] = hex(list[i+1]) + hex(list[i])[2:]
# print(i)
# p... |
#!/usr/bin/env
# encoding: utf-8
"""
Created by John DiBaggio on 2016-11-30
"""
__author__ = 'johndibaggio'
import sys
import os
argv = list(sys.argv)
input_file = open(argv[1])
output_file = open(argv[2], 'w+')
dna = input_file.read()
rna = ""
for nucleobase in dna:
if nucleobase == 'T':
rna += "U"
... |
import numpy as np
import matplotlib.pyplot as plt
import sys
# >>> DESCOMENTAR PARA ENTREGA <<<
sys_argv = sys.argv
file_argv = sys_argv[1]
iterations_argv = int(sys_argv[2])
# >>> COMENTAR PARA ENTREGA <<<
# file_argv = 'house_prices_train.csv'
# iterations_argv = 300
def print_graph(data, is_theta=False, is_cost... |
# -*- coding: utf-8 -*-
class Solution:
def integerReplacement(self, n):
if n == 1:
return 0
elif n == 2:
return 1
elif n == 3:
return 2
elif n % 4 == 1:
return 3 + self.integerReplacement((n - 1) // 4)
elif n % 4 == 3:
... |
# -*- coding: utf-8 -*-
#
# Author: Amanul Haque
import pandas as pd
import numpy as np
from os import listdir
from os.path import isfile, join
from gensim.models import KeyedVectors
import os
import nltk
import re
from nltk.corpus import stopwords
from nltk.stem import SnowballStemmer
from nltk.stem import WordNetLem... |
#!/usr/bin/env python
'''
astarcmd -- resolves finding paths in road maps with A-Star algorithm
astarcmd is a description
It defines classes_and_methods
@author: Pedro Vicente
@copyright: 2013 Biicode test. All rights reserved.
@license: license
@contact: pedrovfer@gmail.com
@deffield ... |
"""
Flask Documentation: http://flask.pocoo.org/docs/
Jinja2 Documentation: http://jinja.pocoo.org/2/documentation/
Werkzeug Documentation: http://werkzeug.pocoo.org/documentation/
This file creates your application.
"""
import os, jwt, base64
from datetime import datetime
from app import app, db, log... |
import json
import matplotlib.patches as patches
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import sys
tf.compat.v1.enable_eager_execution() # Remove when switching to tf2
from boxes import get_boxes, get_final_box
from constants import feature_size, real_image_height, real_image_widt... |
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
import time
import requests
def geturl(url):
res = requests.head(url)
url = res.headers.get('location')
return url
a = 1
with open('id.txt', 'r') as x:
for line in x:
id = line.replace('\n', '')
url = 'http://cli... |
class Caja:
def __init__(self, alto, ancho, largo):
self.alto = alto
self.ancho = ancho
self.largo = largo
def base_caja(self):
return self.alto * self.ancho * self.largo
alto_caja = int(input("Ingrese el alto de su caja: "))
ancho_caja = int(input("Ingrese el ancho de... |
############################################
# Thomas Lehman-Borer & Rachel Chamberlain #
# Dungeons and Dragons Facilitator #
# CS 1 Final Project #
############################################
from random import shuffle
chars = {}
monst = {}
class SentientBeing:
'''Thi... |
#For Robot
from jetbot import Robot
robot = Robot()
robotSpeed = 0.4
robot.stop()
import jetson.inference
import jetson.utils
net = jetson.inference.detectNet("ssd-mobilenet-v2", threshold=0.5)
#camera = jetson.utils.videoSource("csi://0") # '/dev/video0' for V4L2
camera = jetson.utils.videoSource("/dev/video1")... |
from ctypes import POINTER, c_longlong, c_double, c_int, c_void_p, c_char_p, cdll, Structure, CFUNCTYPE, POINTER, sizeof, CDLL
import logging
log = logging.getLogger(__name__)
lib = cdll.LoadLibrary("./awesome.so")
lib.Exmain()
|
# -*- coding: utf-8 -*-
"""
Author : wangyuqiu
Mail : yuqiuwang929@gmail.com
Website : https://www.yuqiulearn.cn
Created : 2018/7/12 14:31
"""
from selenium import webdriver
import time
import random
# 使用selenium爬取链家成都高新区二手房价信息
# 每一页爬取前,随机等待1~3s
chrome_options = webdriver.ChromeOptions()
chrome_options.add_arg... |
#!/usr/bin/env python3
import random
tr = {}
def parse_table():
for l in open('table.txt', 'r').readlines():
(char, options) = l.split(' = ')
char = char.strip()
options = [x.strip() for x in options.split(',')]
assert len(options) <= 2
options.append(char.lower())
... |
# -*- coding:utf-8 -*-
"""
This is an usage Usage example of the "network" module. In this example, we train a network instance to recognize 28x28 pixels images of handwritten digits
The data used for the training is provided by the mnist database, and loaded by the "mnist_loader" module
"""
#get access to the root ... |
class Player:
def __init__(self, the_name: str, the_token: str):
self.name = the_name
self.token = the_token
self.victory = False
|
import unittest
from subprocess import call
import removeoldbackups as rob
from os import path, utime
from freezegun import freeze_time
from datetime import timedelta, datetime
def touch(fname, times=None):
times = (times.timestamp(), times.timestamp())
with open(fname, 'a'):
utime(fname, times)
@fre... |
# -*- coding: utf-8 -*-
import scrapy
class GongzhonghaoauthSpider(scrapy.Spider):
name = 'GongZhongHaoAuth'
apiDict = {
"wechat_auth_list_api": "https://tianshucloud.cn/api/platform/weixin/internalAuthList?",
"wechat_refresh_taken_api": "https://tianshucloud.cn/api/platform/weixin/refreshTok... |
#import the pygame library
import pygame
import time
import random
from snake import Snake
pygame.init()
#define the colours
black = (0,0,0)
white = (255,255,255)
brown = (134,72,22)
green = (0,255,0)
red = (255,0,0)
#open a window
size = (700,500)
d_width = 800
d_height = 600
screen = pygame.displa... |
import speech_recognition as sr
AUDIO_FILE=("audio.wav") #import the audio file
r=sr.Recognizer() #initialize the recognizer
with sr.AudioFile(AUDIO_FILE) as source:
audio=r.record(source)
try:
print("The audio file contains : "+r.recognize_google(audio))
except sr.UnknownValueError:
print("Could't underst... |
"""Caches remote artifacts on S3."""
from os import path
from shutil import rmtree
from tempfile import mkdtemp
from urllib import urlretrieve
import logging
import re
from stacker.lookups.handlers.default import handler as default_handler
from stacker.lookups.handlers.output import handler as output_handler
from sta... |
try:
import readline
import rlcompleter
import atexit
import os
except ImportError:
print("Python shell enhancement modules not available")
else:
histfile = os.path.join(os.environ["HOME"], ".pythonhistory")
import rlcompleter
readline.parse_and_bind("tab: complete")
if os.path.isfile(histfile):
readline.rea... |
__author__ = "Narwhale"
#
# def select_sort(alist):
# """选择排序"""
#
# n = len(alist)
# for j in range(0,n-1):
# min_index = j
# for i in range(j+1,n):
# if alist[min_index] > alist[i]:
# min_index = i
#
# alist[min_index],alist[j] = alist[j],alist[min_index... |
from django.conf.urls.defaults import *
urlpatterns = patterns('django_webfaction.views',
url(r'^email/add/$', 'email_changeform'),
url(r'^email/(?P<id>\d+)/$', 'email_changeform'),
url(r'^email/$', 'email_changelist'),
)
|
"""
Liquid time constant snn
"""
import os
import shutil
import torch
from torch import nn
from torch.nn.parameter import Parameter
import torch.nn.functional as F
from torch.nn import init
from torch.autograd import Variable
import math
def create_exp_dir(path, scripts_to_save=None):
if not os.path.exists(path):
... |
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from django.utils.translation import ugettext_lazy as _
from .models import GadgetSnap
def get_gadget_snaps():
snaps = [a for a in GadgetSnap.objects.exclude(
release__name='rolling-core').order_by('-release')]
snaps +=... |
import matplotlib.pyplot as plt
import pandas as pd
from scipy.io import loadmat
import numpy as np
from scipy import signal
import math as mat
# reading as python dict
data_dict = loadmat('ecgca771_edfm.mat')
# extracting data array - the key is 'val'
data_array = data_dict['val']
# transpose for consistency
data_a... |
test_case = int(input())
for _ in range(test_case):
a = list(map(int, input().split()))
print(sum(a)//2)
|
from flask_login import login_required
from views.base_view import BaseView
class IndexView(BaseView):
@login_required
def get(self):
return self.render_template('index.html', page_name='Index')
|
from urllib.parse import urlencode
params = {
'name':'zjx',
'age':23,
}
base_url = 'http://zhaojiaxing.top?'
url = base_url+urlencode(params)
print(url) |
# Generated by Django 2.0.3 on 2018-03-13 04:17
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('stock', '0002_product_vid'),
]
operations = [
migrations.RemoveField(
model_name='product',
name='vid',
),
m... |
from common.run_method import RunMethod
import allure
@allure.step("小程序/基础/发送短信验证码")
def verificationCode_receiveVerificationCode_get(params=None, header=None, return_json=True, **kwargs):
'''
:param: url地址后面的参数
:body: 请求体
:return_json: 是否返回json格式的响应(默认是)
:header: 请求的header
:host: 请求的环境
:... |
def check_three_and_two(array):
return [2,3] == sorted([array.count(x) for x in set(array)])
'''
Given an array with 5 string values "a", "b" or "c", check if
the array contains three and two of the same values.
Examples
["a", "a", "a", "b", "b"] ==> true // 3x "a" and 2x "b"
["a", "b", "c", "b", "c"] ==> false... |
from Dota2AbilitiesForAlexa.dota2_skill_builder import Dota2SkillBuilder
from Dota2AbilitiesForAlexa.json_parser import JsonParser
|
def terminate_app():
print 'Are you done? (y/n)'
choice = raw_input()
if choice.lower() == 'n':
from display_menu import display_menu
display_menu()
|
comp = 0
cont = 0
def max_heapfy(lista, raiz, tamanho):
esq = 2 * raiz + 1
dir = 2 * raiz + 2
maior = raiz
global comp
if esq < tamanho and lista[esq] > lista[raiz]:
maior = esq
if dir < tamanho and lista[dir] > lista[maior]:
maior = dir
if maior != raiz:
... |
def obter_salario_atual():
return float(input('Informe o salário atual: '))
def obter_porcentagem_de_aumento(salario):
if salario <= 280:
porcentagem = 20
elif salario <= 700:
porcentagem = 15
elif salario <= 1500:
porcentagem = 10
else:
porcentagem = 5
return ... |
from __future__ import print_function
from __future__ import division
from pyLM.units import *
import h5py
import numpy as np
import os
filename_lm='morph_dend.lm'
filename_morph='CA1dend_small.h5'
NA = 6.022e23
##
##
##
print('Set a simulation space.')
latticeSpacing=nm(8)
#sim=RDME.RDMESimulation(dimensions=mi... |
import re
def make_header(title):
header = '<!DOCTYPE HTML PUBLIC>\n'
header += '<html>\n'
header += '<head>\n'
header += '<title>' + str(title) + '</title>\n'
header += '<script src="../sorttable.js"></script>\n'
header += '<link rel="stylesheet" type="text/css" href="../style.css">\n'
hea... |
from flask_app.config.mysqlconnection import connectToMySQL
from flask import flash
class Survey:
@staticmethod
def validate_survey(survey):
results = connectToMySQL('dojo_survey_schema')
is_valid = True
if len(survey['name']) < 1:
flash ("Name must be at least 1 character ... |
class Second1:
color = "red" #Параметры
form = "cube "
kolichestvo = 1
def changecolor(self, newcolor): #Методы
self.color = newcolor
def changeform(self, newform): #Методы
self.form = newform
def changekolichestvo(self, newkolichestvo):
self.kolichestvo =... |
def replace(s):
ans = s.replace(' ', '%20')
return ans
def main():
s = 'i have a dream'
ans = replace(s)
print ans
if __name__ == '__main__':
main() |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright Kitware 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 ... |
from mcts import MCTS
from nodes import *
from motion_domain_1d import dynamics, random_act_generator, terminal_estimator
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.RandomState(15)
mcts = MCTS(dynamics,random_act_generator,terminal_estimator=terminal_estimator,rng=rng)
# state = np.zeros(2)
sta... |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... |
#encoding=utf8
from jieba import analyse
textrank = analyse.textrank
text = '非常线程是程序执行时的最小单位,它是进程的一个执行流,\ 是CPU调度和分派的基本单位,一个进程可以由很多个线程组成,\ 线程间共享进程的所有资源,每个线程有自己的堆栈和局部变量。\ 线程由CPU独立调度执行,在多CPU环境下就允许多个线程同时运行。\ 同样多线程也可以实现并发操作,每个请求分配一个线程来处理。'
keywords = textrank(text,topK=10,withWeight=True,allowPOS=('ns','n','vn','v'))
fo... |
#encoding: utf-8
from openpyxl import load_workbook
from openpyxl.utils import get_column_letter as num2col
from openpyxl.utils import column_index_from_string as col2num
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
wb1 = load_workbook(filename="yun.xlsx")
ws1 = wb1.get_sheet_names()
s1 = wb1.ge... |
from django.shortcuts import render
from .models import Movie
from .serializers import MovieSerializer
from rest_framework import generics
# Create your views here.
class MovieList(generics.ListCreateAPIView):
queryset = Movie.objects.all()
serializer_class = MovieSerializer
class MovieDetail(generics.Re... |
Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> import tkinter as tk
>>>
[DEBUG ON]
>>>
[DEBUG OFF]
>>>
================================ RESTART: Shell ================================
... |
for hora in range(24):
for minuto in range(0,60,30):
print(str(hora)+ " : "+str(minuto)) |
import chainer
import chainer.functions as F
import chainer.links as L
class Generator(chainer.Chain):
"""docstring for Generator"""
def __init__(self):
super(Generator, self).__init__(
l1=L.Linear(100,128*16*16),
dcv1=L.Deconvolution2D(in_channels=128,out_channels=64,ksize=4,stride=2,pad=1),
... |
class Cell:
"""
Cell(row, col)
A class represent each cell in canvas
Parameters
----------
row : int
The row position coordinate of the cell
col : int
The column position coordinate of the cell
Attributes
----------
current_ro... |
from pyspark.sql import SparkSession
from pyspark.ml.feature import *
from pyspark.ml.regression import LinearRegression
from pyspark.ml.classification import LogisticRegression
from pyspark.ml.clustering import KMeans
from pyspark.ml.evaluation import MulticlassClassificationEvaluator
from pyspark.ml.tuning import Cro... |
# My first python program
def newfunction() :
print "this is a new function"
def addMyName(num1, num2):
print(num1 + num2)
# Hello World in Python
print "Hello World!"
#Added a new comment
num1 = "S"
num2 = "W"
addMyName(num1, num2)
counter = 0
while counter < 10:
print "Loop number: %d... |
def testData():
otest = open('test.txt', 'r')
test = otest.readline()
oanswer = open('answer.txt', 'r')
answer = oanswer.readline()
status = False
print("Runs test data")
result = runCode(test)
print(type(result))
print(type(answer))
if int(result) == int(answer): #... |
from PIL import Image
import math
if __name__ == '__main__':
# 打开图片
im = Image.open("1.jpg")
# 将图片转为黑白模式
im = im.convert("L")
# 初始化压缩比
rect_width = 8
# 获得图片尺寸
(width, height) = im.size
# 压缩后图片宽度
nwidth = math.ceil(width/rect_width)
# 压缩后图片高度
nheight = math.ceil(height/rect_width)
# 获得图片数据
lim = list(im.g... |
import smtplib
from email.message import EmailMessage
import os.path
from os import path
import requests
from bs4 import BeautifulSoup
from lxml import html
import requests
from selenium import webdriver
import time
from os import path
import os
import sys
from selenium import webdriver
from selenium.webdriver.common.k... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/6/6 下午10:55
# @Author : Lucas Ma
# @File : __init__.py |
from django.contrib import admin
from django.core.exceptions import ImproperlyConfigured
from django.conf import settings
from django.apps import apps
from polymorphic.admin import PolymorphicParentModelAdmin, PolymorphicChildModelAdmin
from mptt.admin import MPTTModelAdmin
from .models import (
Rate,
Rule,
... |
# Licensed to Elasticsearch B.V under one or more agreements.
# Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
# See the LICENSE file in the project root for more information
from .utils import NamespacedClient, query_params, _make_path
class MigrationClient(NamespacedClient):
@query_p... |
import socket
import threading
import os
import time
import appJar
HOST = socket.gethostname()
PORT = 5001
all_connections = []
all_address = []
def getFile(name, conn):
while True:
data = conn.recv(1024)
client_command = data.decode('utf-8')
if client_command == 'L':
server_r... |
from pandas_datareader import data as pdr
import fix_yahoo_finance as yf
import numpy as np
import pandas
import os
import util
import numpy as np
from sklearn.preprocessing import normalize
from sklearn.preprocessing import MinMaxScaler
def norm(x):
return x / np.linalg.norm(x)
#scaler = MinMaxScaler(feature_ra... |
__author__ = 'sudoz'
if __name__ == '__main__':
print('this program was executed by itself')
else:
print('it is imported from other module')
|
##length=int(input("enter no.of length do you want"))
##print("enter any nymbers")
##lis=[]
##for number in range(length):
## num=input()
## lis.append(num)
##print("lis=",lis)
newlist=[]
number=int(input("enter the length of to creat a newlist"))
print("enter a numbers here:")
i=0
while i<=number:
lis=int(in... |
# -*- coding: utf-8 -*-
import scrapy
import os
import re
class jxufespider(scrapy.Spider):
name = "jxufespider"
allowed_domains = ["movie.douban.com"]
start_urls = (
'https://movie.douban.com/subject/1291546/reviews?start=0',
)
save_path='..\\doubanAssess\\' #create director f... |
import pygame
aktualnie_wyswietlane = [[0 for col in range(14)] for row in range(5)]
aktualna_podpowiedz = [[0 for col_ in range(14)] for row_ in range(5)]
class Kod(object):
def main(self, aktualny_kolor):
Kod.reset(self)
self.pos = pygame.mouse.get_pos()
if self.stop == 0:
... |
class Codec:
def encode(self, strs: List[str]) -> str:
"""Encodes a list of strings to a single string.
"""
payload = [",".join([str(ord(c)) for c in s]) for s in strs]
return ".".join(payload)
def decode(self, s: str) -> List[str]:
"""Decodes a single string ... |
import datetime
import pytz
from django.conf.global_settings import AUTH_USER_MODEL
from django.db import models
from django.urls import reverse
from django.utils import timezone
def normalize(submission: str):
return submission.replace('\r\n', '\n').strip()
class Problem(models.Model):
title = models.Char... |
# Bài 12: Viết hàm
# def find_x(a_list, x)
# trả lại tất cả các vị trí mà x xuất hiện trong a_list, nếu không có thì trả lại -1
a_list = [1,1,1,2,5]
def find_x(a_list,x) :
my_list = []
for i in range(len(a_list)) :
if x == a_list[i] :
my_list.append(i)
if my_list == [] :
... |
import socket
import struct
import hashlib
import os
import json
import time
sk = socket.socket()
sk.bind(('127.0.0.1',43))
sk.listen()
def login():
def register():
'''
注册
'''
count = 0
while count < 4:
conn.send('请输入注册用户名:'.encode('utf-8'))
username = conn.recv(1024).decode('utf-8')
print(userna... |
"""
наилучшее среднеквадратичное приближениеи
"""
from math import sin, pi, factorial, cos, exp, log
from collections import namedtuple
Table = namedtuple('Table', ['x','y', 'w']) # w = вес функции
eps_const = 0.00001
eps_otn = 0.0001
def fi(x, k):
return x ** k
# Загрузка таблицы координат точек и их весов из ... |
# This is just a lot of long shit
from telegram import InlineKeyboardButton
CONFIRM = [[InlineKeyboardButton("Confirm", callback_data='Confirm'),
InlineKeyboardButton("Back", callback_data='Back')]]
CLASSES_BUTTONS = [[InlineKeyboardButton("Barbarian", callback_data='Barbarian'),
InlineKeybo... |
#!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Make sure lots of actions in the same target don't cause exceeding command
line length.
"""
import sys
if sys.platform == 'win32':
p... |
from arago.actors import Router
class RoundRobinRouter(Router):
("""Routes received messages to its childdren """
"""in a round-robin fashion""")
def __init__(self, name=None, *args, **kwargs):
super().__init__(name=name, *args, **kwargs)
self._next = self._round_robin()
def _round_robin(self):
while len(s... |
import dash_bootstrap_components as dbc
from dash import html
accordion = html.Div(
dbc.Accordion(
[
dbc.AccordionItem(
[
html.P("This is the content of the first section"),
dbc.Button("Click here"),
],
titl... |
from django.contrib import admin
from skills.models import Skill
class SkillsAdmin(admin.ModelAdmin):
list_display = ('id', 'title', 'is_active')
list_display_links = ('id', 'title')
search_fields = ['title']
list_per_page = 20
admin.site.register(Skill, SkillsAdmin)
|
#!/usr/bin/env python
#-*-coding:utf-8-*-
# @File:utils.py
# @Author: Michael.liu
# @Date:2020/6/3 17:49
# @Desc: this code is ....
import pandas as pd
# tf_preprocess
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import pickle as pkl
import numpy as np
im... |
# Push new files to Github within existing repository
# Go into the correct terminal in the directory (ex - HelloWorld)
# git status
# see files which have not been commited in required
# git add .
# git status
# se files turn to green meaning that you've updated them locally?
# git commit ... |
def printBoard(board):
for i in range(8):
for j in range(8):
print(board[i][j], end = " ")
print()
def isSafe(board, row, col):
for i in range(col):
if board[row][i] == 1:
return False
for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
if board[i][j] == 1:
return False
... |
from mago import *
from questi.models import *
from django.contrib.auth.models import User
clas = classe.objects.get(name_classe = nom_cl)
pro = prof.objects.get(name = name_proff)
cu = cours.objects.get(name_classe = clas.id, name_prof = pro.id)
questionnair = cu.questionnaire_set.create(nom_du_cours = nom_cou... |
#!/usr/bin/env python
# a bar plot with errorbars
import barPlot_general
if __name__ == "__main__":
relu16 = (82.46, 87.332, 91.416)
nrelu16= (85.352, 88.836, 94.084)
relu16_std = (1.542741067, 1.321616435, 1.475120334)
nrelu16_std = (1.691558453, 1.807478907, 1.037559637)
num16 = len(relu16)
... |
def sum1(a,b):
return int(a)+int(b)
def sum2(a,b,c):
return (int(a)+int(b)+int(c))
def p():
return "1"
def aa():
return "abc"
|
a=str(input("enter the word"))
l=list(a)
b=len(l)
v=['a','e','i','o','u']
c=len(v)
e=[]
for i in range(0,b):
for j in range(0,c):
if(l[i]==v[j]):
break
else:
e.append(l[i])
print(e)
|
import warnings
from unittest import mock
import pytest
from rubicon_ml import domain
from rubicon_ml.client import Project, Rubicon
from rubicon_ml.exceptions import RubiconException
class MockCompletedProcess:
def __init__(self, stdout="", returncode=0):
self.stdout = stdout
self.returncode = ... |
import matplotlib.image as mpimg
import process
from moviepy.editor import VideoFileClip
import os
import tensorflow as tf
from nets.vgg16 import vgg16
from nets.resnet_v1 import resnetv1
dataset = "voc_2007_trainval+voc_2012_trainval"
nnet = "res101_faster_rcnn_iter_110000.ckpt"
tfmodel = os.path.join("/home/veon... |
tc = int(input())
for i in range(tc):
n = int(input())
d=[]
for j in range(n):
s=input()
if s not in d:
d.append(s)
print(len(d))
|
'''
Module to manage Checks
'''
from __future__ import absolute_import
from socket import error as socket_error
# Import salt libs
import salt.utils
import logging
import time
log = logging.getLogger(__name__)
try:
HAS_LIBS = True
except ImportError:
HAS_LIBS = False
# Define the module's virtual name
__... |
from django.db import models
from django_extensions.db.models import TimeStampedModel
from django_extensions.db.fields.json import JSONField
from documentos.models import Frame, GoalStandard
class ClassifierModel(TimeStampedModel):
json_model = JSONField()
name = models.TextField()
datatxt_id = models.Tex... |
# Hierarchical Clustering
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Mall_Customers.csv')
X = dataset.iloc[:, [3, 4]].values
#create dendogram
from scipy.cluster import hierarchy as sch
dendogram = sch... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.