text stringlengths 8 6.05M |
|---|
import math
import time
import logging
from schoolboy.service import find_faces
def calc_distances(moved_distance, first_angle, second_angle):
"""Calculate the distances in X and Y for two given angles and
a distance in X between those two angles.
"""
beta1 = 180 - second_angle
alpha1 = 180 -... |
from flask import Blueprint, jsonify
root = Blueprint('root', __name__)
@root.route("/")
def index():
return "Hello, Flask!"
@root.route("/healthcheck")
def healthcheck():
return jsonify(success=True, message="Ok")
|
from django.contrib import admin
from .models import *
class CustomerAdmin(admin.ModelAdmin):
list_display = ["id", "name", 'surname', 'username', 'date']
class ProductAdmin(admin.ModelAdmin):
list_display = ["id", 'name', 'description', 'price']
class ProductPhotoAdmin(admin.ModelAdmin):
list_display... |
WORDS = []
with open("IELTS Word List.txt", "r", encoding="utf-8") as f:
line = ""
while "EOF" not in line:
line = f.readline()
if "Word List" in line or line == '\n':
continue
WORDS.append(line.split(" "))
# for word in WORDS:
# print(word)
with open("I... |
#!/usr/bin/python
import configparser
def get_sections(path):
"""Return a list of all section names [Section 1] in config file"""
config = configparser.ConfigParser()
config.optionxform = str # Disable converting everything to lowercase
config.read(path)
#print(Config.sections())
return conf... |
import uuid
from datetime import datetime
from flask import url_for
from marshmallow import fields, pre_load, ValidationError, validates, post_load
from mongoengine import DoesNotExist, ValidationError as MValidationError
from werkzeug.security import generate_password_hash
from backend import ma
from backend.models ... |
from typing import List
class Solution:
def my_jump(self, nums: List[int]) -> int:
n = len(nums)
start_addr = 0
step = 0
if n == 1:
return 0
while True:
fastest = 0
next_move = None
for can_move_long in range(1, nums[start_... |
@app.route('/login', methods=["GET", "POST"])
@app.route('/register', methods=["GET", "POST"])
@app.route('forgot-password', methods=["GET", "POST"])
@app.route('transaction/<txid>', methods=["GET"])
@app.route('balance', methods=["GET"])
@app.route('send_tx', methods=["GET", "POST"])
@app.route('receive_tx', methods=[... |
'''
Day 18 - Morning (pt. 1)
It seems like the assembly is meant to operate on a set of registers that are each named with a single letter and that can each hold a single integer.
You suppose each register should start with a value of 0.
There aren't that many instructions, so it shouldn't be hard to figure out what... |
N, M = map(int, input().split())
A = [[0,0] for i in range(M+1)]
|
import tensorflow as tf
from typing import List
from common_layer import FeedForwardNetwork, ResidualNormalizationWrapper, LayerNormalization
from embedding import TokenEmbedding, AddPositionalEncoding
from attention import MultiheadAttention, SelfAttention
from metrics import padded_cross_entropy_loss, padded_accuracy... |
"""
Swap Numbers
Challenge Description:
Write a program that, given a sentence where each word has a single digit
positive integer as a prefix and suffix, swaps the numbers while retaining
the word in between. Words in the sentence are delimited from each other by a
space.
Input sample:
The first ar... |
from copy import deepcopy
import pytest
from pystachio.basic import *
from pystachio.composite import *
from pystachio.container import *
from pystachio.naming import Ref
def ref(address):
return Ref.from_address(address)
def test_ref_parsing():
for input in ['', None, type, 1, 3.0, 'hork bork']:
with pyt... |
class Assignment:
def __init__(self, description, score, total):
self._description = description
self._score = score
self._total = total
def getDescription(self):
return self._description
def getScore(self):
return float(self._score)
def getTotal(self):
... |
# coding=utf8
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
... |
import random
cards = list(range(1,11))
cards.append(V)
cards.append(Q)
cards.append(K)
club = cards
spade = cards
diamond = cards
heart = cards
fullGame1 = club+spade+diamond+heart
fullGame2 = club+spade+diamond+heart
print(fullGame1)
print(fullGame2)
hand1 = random.choices(fullGame1,k=10)
hand2 = random.choices(f... |
### PROBLEM 7 - 10001st PRIME
# The Problem: Find the 10,001st prime number
# The Code:
# Let's just use an import prime library - the thought process:
# People spend a long time writing these libraries, any solution
# they have is almost certainly better than mine
from primesieve import nth_prime as nprime
print("T... |
from ED6ScenarioHelper import *
def main():
# 蔡斯
CreateScenaFile(
FileName = 'T3118 ._SN',
MapName = 'Zeiss',
Location = 'T3118.x',
MapIndex = 1,
MapDefaultBGM = "ed60013",
Flags = 0,
En... |
import os
from transmission import Transmission
from config import torrent_path
from utils.bdd_utils import create_connection
def add_torrent_to_queue(torrent_name):
torrent_file = f"{os.getcwd()}/downloads/torrent_files/{torrent_name}"
connection = create_connection()
cursor = connection.cursor()
... |
def calculate_isbn10_barcode_check_digit(isbn_10):
sum = 0
#Multiply
for multiply_counter, num in enumerate(isbn_10,-10):
num = int(num)
sum += (num*(-multiply_counter))
#Calculate the remainder of the sum when divided by 11.
check_digit = 11 - (sum % 11)
if check_digit == 10:
... |
# Programa que divide um premio de R$780mil para 3 ganhadores
# O primeiro receberá 46%
# O segundo receberá 32%
# O terceiro receberá o restante
premio = float(780.000)
ganhador_1 = (premio * 46) / 100
ganhador_2 = (premio * 32) / 100
ganhador_3 = (premio * 22) / 100
print(f'O primeiro ganhador receberá a quantia de... |
from rest_framework import viewsets
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
"""
Viewset class ia type fo class-based View, that does not provide any method handlers
such as .get() or .post(), and instead provides actions such as .list() or .creaate()
.get() 혹은 .post() 대... |
import hashlib
a="a test string".encode('utf8')
print(hashlib.md5(a).hexdigest())
print(hashlib.sha1(a).hexdigest())
print(hashlib.sha224(a).hexdigest())
print(hashlib.sha256(a).hexdigest())
print(hashlib.sha384(a).hexdigest())
print(hashlib.sha512(a).hexdigest())
from Crypto.Hash import SHA256
h = SHA256.new()
h.up... |
'''
Definition of default values of the add-on.
'''
POSITION_OPTIONS = ['Top', 'Bottom']
STYLE_OPTIONS = [
'Default', 'Cde', 'Cleanlooks', 'Fusion', 'Gtk', 'Macintosh',
'Motif', 'Plastique', 'Windows', 'Windows Vista', 'Windows XP'
]
TEXT_FORMAT = [
{'text': 'None'},
{'text': 'current/total (XX%)', 'f... |
from django.dispatch import Signal
user_logged_in = Signal(providing_args=["user","top_session","top_parameters"])
merge_trade_signal = Signal(providing_args=['trade'])
refund_signal = Signal(providing_args=["refund"])
rule_signal = Signal(providing_args=["trade_id"])
change_addr_signal = Signal(providi... |
from django.contrib import admin
from .models import *
admin.site.register(Words)
admin.site.register(FilesAdmin) |
import cv2
import numpy as np
ship_cascade = cv2.CascadeClassifier('cascade.xml')
img = cv2.imread('0.jpg',cv2.IMREAD_COLOR)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ships = ship_cascade.detectMultiScale(gray,20,20)
print(ships)
for (x,y,w,h) in ships:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
prin... |
filename = 'guest_book.txt'
with open(filename, 'w') as file_object:
while 1:
name = input('Please input your name(Press q to exit): ')
if name == 'q':
break
else:
name = name + '\n'
file_object.write(name) |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 3 08:09:48 2014
@author: atproofer - MBocamazo
"""
#p is the number of rows, q is the number of columns
def printnbyn(p,q):
k = 'x '+'- '*4
j = '| '+' '*4
x = k*q+'x'
y = j*q+'|'
for m in range(0,p):
print x
for i in range(0,4):
... |
import socket
import os
TARGET_IP = "10.151.253.199"
TARGET_PORT = 5006
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
namafile="bart.png"
ukuran = os.stat(namafile).st_size
try :
fp = open('bart.png','rb')
k = fp.read()
terkirim=0
for x in k:
k_bytes = bytes([x])
sock.sendto(k_byte... |
# -*- coding: utf-8 -*-
from django.conf.urls import url
from forms import views
urlpatterns = (
url(
r'^(?P<lang>\w{2})/forms/callback/$',
views.CallbackRequestView.as_view(), name='callback'
),
url(
r'^(?P<lang>\w{2})/forms/feedback/$',
views.FeedbackRequestView.as_view(... |
#celsius to fahrenheit
def main():
celsius = float(input("Digite a temperatura: "))
fahrenheit = (9*celsius + 160) / 5
print("Fahrenheit: ", fahrenheit)
# Fim do Programa
#-----------------------------------------------------
#-----------------------------------------------------
if __name__ ... |
import importlib
import torch
from pytorch_lightning.core.lightning import LightningModule
from hydra.utils import instantiate
from source.metric.MRRMetric import MRRMetric
class CoModel(LightningModule):
"""Encodes the code and desc into an same space of embeddings."""
def __init__(self, hparams):
... |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class StructuredAttention_bi(nn.Module):
def __init__(self, dropout=0.1, scale=100):
super(StructuredAttention_bi, self).__init__()
self.dropout = dropout
self.scale = scale
def forward(self, C, Q, c_mas... |
import os
import appdirs
from . import version
APPNAME = "Screenshotto"
__version__ = version.version
VERSION_STRING = f"{APPNAME} - version {__version__}"
CONFIG_DIR = appdirs.user_config_dir(APPNAME, False)
CONFIG_FN = f"{APPNAME}.ini"
CONFIG_PATH = os.path.join(CONFIG_DIR, CONFIG_FN)
|
# #!/usr/bin/env python
# # Funtion:
# # Filename:
#
# import networkx as nx
# import matplotlib.pyplot as plt
#
# g = nx.Graph() # 建立一个空的无向图G
# # 添加有向图的方式: G = nx.DiGraph()
# # 需要主要的是:再添加边3-2与边2-3,则被认为是两条不同的边
# # 有向图和无向图是可以相互转化的,分别用到Graph.to_undirected() 和 Graph.to_directed()两个方法。
#
#
# g.add_node(2) # 添加一个... |
"""
Fitness inference code for bulk fitness assay, by Atish Agarwala. Latest version of fitness inference algorithm as
described in: http://dx.doi.org/10.1016/j.cell.2016.08.002.
"""
import numpy as np
import os
import matplotlib.pyplot as plt
from scipy.stats import norm
def inferFitness(barcodes,cyc... |
#!/usr/bin/python
# vim: set expandtab ts=4
import unittest as ut
from OperatorTest import *
from ChandraTest import *
from HigherOrderChandraTest import *
from CylinderTest import *
if __name__ == '__main__':
ut.main()
|
from copy import deepcopy
def dispBoard(board):
for r in board:
print(' '.join(['-','X','O'][c] for c in r))
def checkVictory(board,y,x,side):
testBoard = deepcopy(board)
testBoard[y][x] = side
# Common row
if testBoard[y] == [side]*3:
return True
# Common column
if [r[x] f... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import copy
import json
import math
import re
import collections
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.nn.parameter import Parameter
def gelu(x):
... |
# from aux.internals.pluginhook import PluginImporter
import sys
import os
import imp
import device
import service
from aux import systems_pool
#these imports should be kept in a system pool and only be instantiated once.
class SystemNotFoundException(Exception):pass
def scan_files(files, systemtype):
for f in f... |
import Util
import matplotlib.pyplot as plt
def plot(data_dict):
for key in data_dict.keys():
#print key
values=data_dict[key]
for x in values:
plt.scatter(key,x,color="blue")
plt.xlabel("PPL")
plt.ylabel("access")
plt.show()
def read_content():
filename = "..... |
# -*- coding: utf-8 -*-
import os
import time
import irc3
import datetime
from irc3.compat import asyncio
from concurrent.futures import ThreadPoolExecutor
__doc__ = '''
==========================================
:mod:`irc3.plugins.feeds` Feeds plugin
==========================================
Send a notification on ... |
from datetime import datetime
from io import BytesIO
from morepath import redirect
from morepath.request import Response
from onegov.core.security import Private
from onegov.gazette import _
from onegov.gazette import GazetteApp
from onegov.gazette.collections import OrganizationCollection
from onegov.gazette.forms imp... |
from ED6ScenarioHelper import *
def main():
# 玛诺利亚村 村长家
CreateScenaFile(
FileName = 'T2301 ._SN',
MapName = 'Ruan',
Location = 'T2301.x',
MapIndex = 1,
MapDefaultBGM = "ed60084",
Flags = 0,
... |
from matplotlib.dates import date2num
import datetime as dt
import logging
import numpy as np
import os
import networkNames as names
import mospat_inc_directories as IncDir
import mospat_utils_equation
import IncludeFile as IncF
from INetwork import INetwork
from aux_operations import naive_num2date
import pdb
# r... |
from algo_crate.datastructures.heap import MinHeap
def heapsort(a):
min_heap = MinHeap(a)
return [min_heap.extract_min() for _ in range(len(min_heap))]
|
import numpy as np
from sklearn.cluster import DBSCAN
import distance
class DbScan:
def __init__(self, eps=5, min_samples=2):
self.eps = eps
self.min_samples = min_samples
def fit(self, metric, data):
self.data = data
X = np.arange(len(data)).reshape(-1, 1)
dbscan_alg ... |
import time
import numpy
from pyvisa.vpp43 import set_attribute
from application.lib.instrum_classes import *
"""
This module implements the basic controls of a Tabor AWG.
09/2016
"""
class Waveform:
def __init__(self):
"""
this is the doc string for the init method...
"""
self._... |
# coding: utf-8
import time
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy
from individu import *
def couleur_rgb_to_matplotlib(couleur):
return couleur[0] / 255, couleur[1] / 255, couleur[2] / 255
class Stats:
id_axs = 0
tk_jour = None
tk_nb_individus = None
... |
import struct
import urwid
class UDP:
def __init__(self, raw_data):
self.src_port, self.dest_port, self.size = struct.unpack('! H H 2x H', raw_data[:8])
self.data = raw_data[8:]
def get_name(self):
name = ''
name += '{:18}UDP '.format(f'{self.src_port} --> {self.dest_port} ')... |
import os
from pocketsphinx import LiveSpeech, get_model_path
import requests
name = str(input('what is your username: '))
command = str(input('what should I do? [record] or [clear] '))
if command=='clear':
req = requests.get('https://roberttoyonaga.api.stdlib.com/pierre-sheets@dev/?operation=entries')
req_li... |
from reporter_app import create_app
from reporter_app import db as _db
from reporter_app.models import Role
from sqlalchemy.sql import func
from config_testing import TestConfig
import secrets
import pytest
STANDARD_USER = {
'username': 'standard',
'first_name': 'standard',
'surname': 'standard',
'email': 'standar... |
from interface import Interface
class RpcClient(Interface):
def call(self, topic, data):
pass
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
"""
Job engine
"""
import os
import time
import ast
import glob
import logging
import gevent
import datetime
from gevent import Greenlet
from .validator import ScriptValidator
from ava.util import time_uuid
from ava.runt... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import unittest
class NewVisitorTest(unittest.TestCase):
def setUp(self):
# 테스트 시작 전 실행
self.browser = webdriver.Firefox(executable_path=
'C:/Users/Jaehyeong/AppData/Local/Programs/python/geckodriver.exe')
self.browser.imp... |
import argparse
import logging
import os
import time
from datetime import datetime
from typing import Optional
import brownie.network
from brownie.network.contract import Contract
from eth_abi.exceptions import InsufficientDataBytes
from pandas import DataFrame
from src.core.operations.current_block import get_block_... |
#
# Copyright (c) James Quintero 2020
#
# Last Modified: 12/2022
#
#Menu provided to user for playing or simulating Mississippi Stud
from Play import Play
from Simulate import Simulate
class MississippiStud:
def __init__(self):
pass
"""
Provides menu to the user
"""
def run(self):
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.8 on 2016-09-03 11:25
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import phonenumber_field.modelfields
class Migration(migrations.Migration):
dependencies = [
('cities_light', '0006_co... |
"""
Crea una base de datos desde cero con la información del año actual y el año anterior de todos los sistemas, nodos y mercados.
Debería utilizarse sólo inicialmente.
Modificar folder destino al deseado, debe tener la estructura adecuada.
Se utiliza Firefox
"""
import os
import sys
import time
from bs4 import Beauti... |
# Oppgave 1, side 133
tall = float(input('Skriv inn tall, fra 1 tilogmed 7: '))
if tall < 1:
print('Tallet er ikke fra 1 tilogmed 7!')
else:
if tall == 1:
print('Mandag.')
else:
if tall == 2:
print('Tirsdag.')
else:
if tall == 3:
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from BeautifulSoup import BeautifulSoup
import re
import urllib2
import MySQLdb
db = MySQLdb.connect(
host="localhost",
user="root",
passwd="Southampton11",
db="Test")
cursor = db.cursor()
base_url = "http://stackoverflow.com"
program_url = base_url + "/tags?page="
... |
class Solution(object):
def lastRemaining(self, n):
left, remain, head, step = True, n, 1, 1
while remain > 1:
if left or (remain % 2 == 1):
head += step
remain /= 2
step *= 2
left = not left
return head |
'''
Ceiling of a number
Problem Statement #
Given an array of numbers sorted in an ascending order, find the ceiling of a given number ‘key’. The ceiling of the ‘key’ will be the smallest element in the given array greater than or equal to the ‘key’.
Write a function to return the index of the ceiling of the ‘key’. ... |
from tests.level1 import tryit
cc = tryit.aa
cc.bb()
|
from django.db import models
from jadegram.users import models as user_models
from django.utils.encoding import python_2_unicode_compatible
from taggit.managers import TaggableManager
# Create your models here.
@python_2_unicode_compatible
class TimeStampedModel(models.Model):
created_at = models.DateTimeField(au... |
import logging
from typing import Dict
from sonosco.serialization import serializable
from sonosco.training.abstract_callback import AbstractCallback, ModelTrainer
from torch.utils.tensorboard import SummaryWriter
LOGGER = logging.getLogger(__name__)
@serializable
class TensorBoardCallback(AbstractCallback):
""... |
import numpy as np
import matplotlib.pyplot as plt
#### class acceptable attacked
##adv attacks
#f="../results/4000_gen_adv_config/result_per_nb_step/result_exec_norm/results_exec_4000_pts_20_iter.csv"
#f="../results/4000_gen_adv_config/result_per_nb_step/result_exec_norm/results_exec_4000_pts_50_iter.csv"
#f="../resu... |
import sys
import numpy as np
import pandas as pd
from skimage import io
from skimage.color import rgb2gray
import matplotlib.pyplot as plt
import seaborn as sns
def fig(val, output_name):
#df = pd.DataFrame({'Frame': [i+1 for i in range(len(val))], 'Signal': val})
g = sns.tsplot(val, err_style="ci_bars")
... |
from common.dto.scenario import Scenario
from common.dto_dependency_loader import asinstanceof
class DynamicAnalysisResult:
# if no dynamic analysis was run, log_id should not be set
def __init__(self,
scenario,
log_id=None,
crashed_on_run=False,
... |
from flask import Flask, render_template
# from flask import request
app = Flask(__name__)
@app.route('/')
def hello_world():
return render_template("hello.tpl", name="tiger")
|
from flask import Flask, render_template, request, session, redirect
app=Flask(__name__)
@app.route('/')
@app.route('/about')
def about():
#Track whether the user has logged in
if 'logged' not in session:
session['logged']=False
return render_template('about.html',s=session)
@app.route('/login')
... |
# Generated by Django 2.0 on 2017-12-25 10:33
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='userprofile',
name='first_name',
),
... |
import airflow
#from airflow.example_dags.subdags.subdag import subdag
from airflow.models import DAG
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators.subdag_operator import SubDagOperator
DAG_NAME = 'Ashish_example_subdag1'
args = {
'owner': 'airflow',
'start_date': airflow.u... |
import unittest
from conans.test.utils.tools import TestClient
conanfile = """from conans import ConanFile
class Pkg(ConanFile):
def requirements(self):
if self.develop:
self.output.info("Develop requirements!")
def source(self):
if self.develop:
self.output.info("Devel... |
""" open() -> função para abrir um arquivo """
''' var = open(nome, modo) onde:
-> NOME = nome do arquivo/pasta;
-> MODO = forma que abriremos o arquivo, sendo esses modos:
-> r: somente leitura
-> w: escrita (se existir será apagado e será criado um novo)
-> a: leitura e escrita (conteúdo no final)
-> r+: l... |
N = int( input())
A = [ int( input()) for _ in range(N)]
A.sort(key=None, reverse = True)
ans = A[0]
for i in range(1, N):
if ans != A[i]:
ans = A[i]
break
print(ans)
|
from sklearn import model_selection
from sklearn.ensemble import BaggingClassifier
from sklearn.tree import DecisionTreeClassifier
import pandas as pd
url = "wine_data.xlsx"
dataframe = pd.read_excel(url)
arr = dataframe.values
X = arr[:, 1:14]
Y = arr[:, 0]
seed = 8
kfold = model_selection.KFold(n_spli... |
# Default imports
import numpy as np
ipl_matches_array =np.genfromtxt("data/ipl_matches_small.csv", dtype="|S50", skip_header=1, delimiter=",")
# Your Solution
def get_total_deliveries_played(batsman = 'ST Jayasuriya'):
a = ipl_matches_array[0:,13]
# b = batsman.values('ST Jayasuriya')
# b = ipl_matches_a... |
from app import app
app.run(host='0.0.0.0',port=8080,debug = True)
|
#!/usr/bin/env python3
"""
This is textual version of popular game Minesweeper.
Now you can play the game on your job even if sysadmins deleted all the games before you got your computer :)
If you find some typos or bugs please don't hesitate to report them.
"""
import random
import math
# There you can change game ... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '.\MainWinSignalSlot02.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.s... |
from ui import Ui_MainWindow
from PyQt5.QtWidgets import QApplication, QMainWindow
class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.setupUi(self)
self.show_all()
self.add_button.clicke... |
from sense_emu import SenseHat
from time import sleep
import pygal
temp = []
sense = SenseHat()
##sense.clear()
weather= pygal.Line()
i =0;
while True:
sleep(0.1)
myfile = open('weather.txt','a')
temp.append(sense.get_temperature())
if (i>10):
temp.pop(1)
## weather.render_to_file('/home/pi/o... |
import logging
import os
from logging.handlers import RotatingFileHandler
log_path = "/data/proclog/log/detecttoredis/"
log_file_message = "/data/proclog/log/detecttoredis/detecttoredis.log"
try:
if(not os.path.exists(log_path)):
cmd = str("mkdir -p %s" % log_path);
os.system(cmd);
Rtha... |
import pytest
from marshmallow import ValidationError
from opsy.schema import validate_ip
def test_validate_ip():
# Test invalid IP
with pytest.raises(ValidationError):
validate_ip("invalid")
# Test valid IPv4
validate_ip("192.168.0.1")
# Test valid IPv6
validate_ip("::1")
|
from codecs import open
from random import randint, uniform
from collections import defaultdict
from math import log
from utility import change_count
from utility import get_value
class BHMM(object):
""" Bayesian Hidden Markov Model with Gibbs sampling. """
def __init__(self, args):
# Input file
... |
import StringIO
def un(source, row=list):
"""Parse a text stream to TSV
If the source is a string, it is converted to a line-iterable stream. If
it is a file handle or other object, we assume that we can iterate over
the lines in it.
The result is a generator, and what it contains depends on whe... |
# Python program for implementation of Quicksort
# This function is same in both iterative and recursive
def partition(arr, l, h):
#write your code here
i=l-1
pivot=arr[h]
for j in range(l,h):
if arr[j]<pivot:
i+=1
arr[i],arr[j]=arr[j],arr[i]
arr[i+1],arr[h]=arr[h],arr[i+1]
return i+1
def ... |
import requests
from flask import current_app, g, session, jsonify
from werkzeug.local import LocalProxy
import pymongo
from bson import json_util
import json
from pymongo import MongoClient, DESCENDING, ASCENDING
from pymongo.write_concern import WriteConcern
from pymongo.errors import DuplicateKeyError, OperationFail... |
from typing import Tuple
class Color:
def __init__(self, x: float, y: float, z: float, name: str = ...) -> None:
self.name = name
self.x = x
self.y = y
self.z = z
def to_tuple(self) -> Tuple:
return (self.x, self.y, self.z)
class ColorRange:
def __init__(self, min_c... |
#ejemplo
#edades = { 'Paco': 20, 'Luis': 25, 'Lucas': 30}
#nombre = 'Luis'
#edad = edades[nombre]
#print edad
#definicion de procedimiento y funciones
def p_suma(p_num1, p_num2):
#return (p_num1, p_num2)
resultado = p_num1+p_num2
print("El resultado es :", resultado)
def p_restar (p_num1, p_num2)... |
#!/usr/bin/env python
import subprocess
import re
import sys
try:
out = subprocess.check_output(['/usr/lib/ddb/bin/ddb-admin', 'status'])
except Exception, e:
print "Plugin Failed! %s" % e
sys.exit(2)
result = "OK | "
for line in out.split("\n"):
m = re.match(r"^([^ ]+) : ([0-9]+)", line)
if m:
... |
#!/usr/bin/env python
print '\033[34m=\033[0m' * 30
def flat(nested):
try:
try:
nested+''
except TypeError:
pass
else:
raise TypeError
for sublist in nested:
for element in flat(sublist):
yield element
except TypeError:
yield nested
print list(flat(['foo',['bar',['baz']]... |
from pathlib import Path
from selenium import webdriver
from datetime import datetime
from pages.authentication_page import AuthenticationPage
from pages.cart_page import CartPage
from pages.checkout_pages import OrderSummaryPage, ShippingPage, PaymentPage
from pages.customer_account_page import CustomerAccountPage
fr... |
# 목적 : 여러 개의 그래프 그리기
from matplotlib import font_manager, rc
import matplotlib.pyplot as plt
font_location = "C:\windows\Fonrts\malgun.ttf"
font_name = font_manager.FontProperties(fname=font_location).get_name()
rc('font',family=font_name)
plt.plot([1,2,3,4],[1,2,3,4],'y')
plt.xlabel('x축')
plt.ylabel('y축')
plt.title(... |
#! /usr/bin/env python
###############################################################################
# ipcamera.py
#
# classes for handling IP cameras in openCV
#
# NOTE: Any plotting is set up for output, not viewing on screen.
# So, it will likely be ugly on screen. The saved PDFs should look
# better.... |
from flask import request, jsonify
|
import random
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.autograd as autograd
# Creating the architecture of the Neural Network
class Network(nn.Module): #inherinting from nn.Module
#Self - refers to the object that will be created from this class
# - sel... |
#!/usr/bin/env python
# -*-coding:utf-8 -*-
# author:罗徐 time:2019/8/2
# 基于距离变换的分水岭算法
# 1.输入图像 2.灰度处理 3.二值化处理 4.距离变换 5.寻找种子 6.生成marker
# 7.分水岭变换 8.输出图像
import cv2 as cv
import numpy as np
def watershed_demo():
#remove noise if any
print(src.shape)
blurred=cv.pyrMeanShiftFiltering(src,10,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.