text
stringlengths
38
1.54M
from PIL import Image import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm from skimage.color import rgb2hsv from skimage.io import imread with np.load("C:\Master\settings\wallackhaus-nord/settings.npz") as settings: clearmask = settings["clearmask"] skymask = settings["skymask"] img ...
""" DESAFIOS HACKERRANK 08. Date and Time """ import calendar # Exemplos '''print(calendar.TextCalendar(firstweekday=6).formatyear(2021)) # ''' # 1/2 Calendar Module (easy) '''data = list(map(int, input().split())) d = calendar.weekday(data[2], data[0], data[1]) wd = ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', '...
import abc from typing import List from model.gamemanageusecase.characters.bobdescription import BobDescription class IBobDescriptionDAO(metaclass=abc.ABCMeta): @abc.abstractmethod def getByID(self, id: str) -> BobDescription: pass @abc.abstractmethod def save(self, description: BobDescripti...
#!/usr/bin/env python # # test_render_ortho.py - # # Author: Paul McCarthy <pauldmccarthy@gmail.com> # import pytest from . import run_cli_tests pytestmark = pytest.mark.clitest cli_tests = """ 3d.nii.gz -lo grid 3d.nii.gz -lo grid -xh 3d.nii.gz -lo...
import requests PROMS_BASE_URI = "http://localhost:5000" PROMS_HOME_DIR = ".." import os from __init__ import w_l def load_rs(): # load the example ReportingSystem, System 01 r = requests.post( PROMS_BASE_URI + '/function/lodge-reportingsystem', #data=open(os.path.join(PROMS_HOME_DIR, 'tests', ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from mpl_toolkits.mplot3d import Axes3D # Save figures to single pdf #from matplotlib.backends.backend_pdf import PdfPages import math # Read data blocks empty_lines = 0 b...
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2019-03-05 22:43 from __future__ import unicode_literals import django.contrib.gis.db.models.fields from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migra...
#!/bin/python #xmen_file = open('xmen.txt') #xmen_file = open('xmen.txt', 'r') -> default as above read operation ## print by default adds a new line character at the end of string #for line in xmen_file: # print(line) ## print without new line characters #print (xmen_file.read()) ## close the file #xmen_file.clos...
# -*- coding: utf8 -*- import re from copy import deepcopy from functools import reduce import attr import numpy as np import six import tensorflow.compat.v1 as tf from attr.validators import instance_of from tensorflow.compat.v1 import AttrValue as _AttrValue from tensorflow.compat.v1 import NameAttrList as _NameAttr...
from __future__ import print_function import os import numpy as np import torch as t import torch.nn as nn from torch.optim.lr_scheduler import ReduceLROnPlateau from torch.autograd import Variable from torchnet import meter from .log import logger from .visualize import Visualizer def get_learning_rates(optimizer...
import numpy as np import pandas as pd from typing import Union, Optional, Sequence class Data: """Abstract dataset. This class implements the basic attributes and methods for a dataset. Attributes ---------- tasks: list of str The names of the tasks. n_tasks: int The number of tasks. n_obs: int or dict ...
"""Basic registry for data loaders.""" _LOADERS = dict() def register(name): """Registers a new data loader function under the given name.""" def add_to_dict(func): _LOADERS[name] = func return func return add_to_dict def get_loader(data_src): """Fetches the data loader function a...
# -*- coding: utf-8 -*- from flask import Flask, render_template, request, send_file, send_from_directory, redirect, url_for, make_response, \ g, flash, jsonify from sqlalchemy import and_,or_, alias, not_ import json import os import datetime from dateutil.parser import parse from prod_app import ...
import numpy as np import pandas as pd import math import mldata from data import * from statistics import * class LogisticRegression(): def __init__(self,features_num, features_info, learning_rate = 0.1, weight_penalty = 0.1): self.features_info = features_info self.weights = np.random.random((features_num,1)) ...
import unittest from tp4 import edit_distance class TestEditDistance(unittest.TestCase): def test_general(self): self.assertEqual( edit_distance("aloroswmenet", "calorosamente", ins_cost=2, del_cost=2, sub_cost=4, swap_cost=3), 9 ) self.assertEqual( ...
""" Initialize the environment and start model serving on Sagemaker or local Docker container. To be executed only during the model deployment. """ from __future__ import print_function import multiprocessing import os import shutil import signal from subprocess import check_call, Popen import sys from pkg_resource...
def factorial(n): if(n==0 or n==1): return 1 else: return n*factorial(n-1) if __name__ == "__main__": print(factorial(3))
#!/usr/bin/python3 """Unittest for HBNBCommand class.""" from console import HBNBCommand from unittest.mock import patch from io import StringIO import console as c import unittest import pep8 class TestBase(unittest.TestCase): """Base class tests.""" def setUp(self): """Base classes to the tests."""...
# Import # here that import Python module from django.db import models from django.utils import timezone # Import # here that import your module from ..user.models import KouZa from ..kuukann.models import Pic, Img # Globel STATION_CHOIES = ( (True, '项目在回收站中'), (None, '项目已被抛弃'), (False, '项目已被还原'), ) # C...
# -*- coding utf-8 -*- # @Time : 2021/8/18 16:27 # @Author : donghao # @File : utils.py # @Desc : 一些简单的函数工具 import os def all_uwbs_connected(uwb_map): """ 判断是否所有的UWB都已经连接上 """ for uwb in uwb_map.values(): if not uwb.connected: return False return True def all_cars_conne...
from __future__ import (absolute_import, print_function) import os from sys import stderr as STDERR from .json import load_component class Error(Exception): pass class LoadError(Error): def __init__(self, msg): self._msg = msg def __str__(self): return self._msg def _component_names...
from autograd import elementwise_grad import numpy as np elementwise_hess = lambda func: elementwise_grad(elementwise_grad(func)) class BaseLoss(object): def __init__(self): pass def grad(self, preds, labels): raise NotImplementedError() def hess(self, preds, labels): raise NotIm...
# -*- coding: utf-8 -*- """ @date: Created on Fri Jul 27 20:01:45 2018 @author: Zhen Chen @Python version: 3.6 @descprition: a recusion about integer partioning """ # output only the number of partioning def f1(n, m): if n==0 or m ==0: return 0 if n==1 or m ==1 : return 1 if m == n:...
from ..models import City, Hotel, HotelComment, Rating, Order class CityModel: def __init__(self, city_name): self.city_name = city_name def create_city(self): city = City.objects.filter(name=self.city_name).first() if not city: city = City(name=self.city_name) ...
import sys import os import smtplib # insert the sender email address sender = "hwlee2014@mmlab.snu.ac.kr" # insert the receivers email address receivers = ["hwlee2014@mmlab.snu.ac.kr"] def usage(): # input the usage of this script print ("Experiment for Modification Record") # input the command to execut...
from sklearn import datasets iris = datasets.load_iris() print(iris.feature_names) # columns print(iris.data[:5]) # first 5 rows of the ndarray print('...') print(iris.DESCR) # description
#!/usr/bin/python3 """ This file contains our base class for our models project. """ import json class Base: """ This is our base class that will be inherited by every other class in this project. Private class attribute: __nb_objects(int) - keeps track of the number of objects cu...
import sys import numpy as np from scipy.stats.mstats import mquantiles import matplotlib.pyplot as plt ######################################################################################## ## Handle batch job arguments: nargs = len(sys.argv) print 'Command line arguments: ' + str(sys.argv) #### # sim...
import json def convert(f, user, test=False): d = {} order = ['email','search','delivery', 'send', 'keywords_important', 'keywords_positive', 'keywords_good', 'keywords_meh', 'keywords_negative'] i = 0 for line in f: line = line.split(':') name = line[0].split(' ')[0].stri...
from pymcutil.resource.resource_reference.standard_resource_reference import StandardResourceReference class FunctionResourceReference(StandardResourceReference): pass
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
# this fucntion reads and organises import pickle as pr from Create_time_series import create_time import datetime as dt # %% Complete the full time series def account_missing_data_s (Data): Time_ref = create_time(2014) comp = len(Time_ref) Variable = [None]*comp for ...
# Dan McGinn, Tufts CEEO # Run with python3 from http.server import BaseHTTPRequestHandler, HTTPServer # package for Webserver from urllib.parse import unquote # package for decoding UTF-8 import getpass, sys, socket, os, webbrowser from time import sleep import requests,json # packages for Thingworx POST & GET import...
#!/usr/bin/python import argparse import yaml from modulos.dockerapi import DockerAPI class DeployTool: def __init__(self): self.parse = argparse.ArgumentParser() self.parse.add_argument('-i', help='Indica o arquivo de deploy') self.args = self.parse.parse_args() def _yaml_to_dict(s...
import numpy as np import scipy from spikeinterface.core import ( WaveformExtractor, get_noise_levels, get_channel_distances, compute_sparsity, get_template_extremum_channel, ) from spikeinterface.sortingcomponents.peak_detection import DetectPeakLocallyExclusive spike_dtype = [ ("sample_index...
from GSM import setup_serial, send_command, parse_response, close_serial from time import sleep from GSM import handle_commands if __name__ == "__main__": ser = setup_serial() commands = [] # commands.append(b'AT+CGPSPWR=0') # commands.append('AT+CGPSINF=0') # commands.append('AT+CGNSPWR=0') #...
import ctypes from ctypes import * import os import numpy as np import platform # TODO: make it run in Linux if platform.system() == 'Linux': os.environ["LD_LIBRARY_PATH"] = os.getcwd() + ":" + os.environ["LD_LIBRARY_PATH"] else: os.environ["PATH"] = "c:\\ProgramData\\qwtw;" + os.environ["PATH"] qq = None plo...
import kray import numpy as np from datetime import datetime, timedelta import pandas as pd import xray from scipy import interpolate as interp from scipy.stats.stats import pearsonr from scipy import stats # Function for creating anomalies by group def group_anom(ds_in, grouping_var, groups, var, period): ''' ...
#Import required libraries import numpy as np import pandas as pd #Reads the training and testing datasets train_adult = pd.read_csv('/home/tezaa/Documents/GitHub/Adult Dataset/adult.csv') test_adult = pd.read_csv('/home/tezaa/Documents/GitHub/Adult Dataset/adult_test.csv') #Creating Dataframes for train and test ...
import pigpio import DHT22 import RPi.GPIO as gpio from time import sleep import paho.mqtt.client as paho gpio.setwarnings(False) gpio.setmode(gpio.BOARD) gpio.setup(36, gpio.OUT) gpio.setup(38, gpio.OUT) broker="soldier.cloudmqtt.com" port=17075 def on_publish(client,userdata,result): print("data published \n"...
#!/usr/bin/env python PACKAGE = "dyn_reconfig_intro" from dynamic_reconfigure.parameter_generator_catkin import * gen = ParameterGenerator() gen.add("freq", double_t, 0, "A double parameter for frequency", 0.5, 0.2, 2.0) # default, min, max gen.add("message", str_t, 0, "A string parameter for the message"...
class Solution: def canFinish(self, numCourses, prerequisites): """ :type numCourses: int :type prerequisites: List[List[int]] :rtype: bool """ need = [[] for i in range(numCourses)] pre_course = [0]*numCourses queue = [] count = 0 ...
from flask import render_template, redirect, request, url_for, flash, current_app from flask_login import login_user, login_required, logout_user, current_user from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from . import auth from ..models import User from ..email import send_email from .forms...
chars = 'SAHFI' for i, c in enumerate(chars): print i, c print '\n' #------------------------------- cs = 'AO' ws = ['Apple','Orange'] for c, w in zip(cs, ws): print c, w print '\n' #----------------------------- student_scores = [(90,100), (60,80)] print (sum(zip(*student_scores)[1])+.0) / len(student_scores)...
class Solution: def convertToTitle(self, columnNumber: int) -> str: # 2021.03.23 # Use ASCII code: 65-90 # chr(65) -> 'A' # e.g. XYZ -> 24*26*26 + 25*26 + 26 = 16900 # -> 16900 = 650*26 = 649*26 + 26 = (24*26 + 25)*26 + 26 -> XYZ # 1st solution: iterative ...
import json import re import sys from pprint import pprint # read in configuration file class ConfigParser: def parse_config(self): with open(sys.argv[1]) as config_file: comment_pattern = r"(?m)^\s*#.*\n?" config_text = re.sub(comment_pattern, "", config_file.read()) ...
from app.extensions import db class Tbl_Sales_Os_Count(db.Model): __tablename__ = 'tbl_sales_os_count_pro' fld_index = db.Column(db.Integer,primary_key=True) fld_os_name = db.Column(db.String(256),unique=True) fld_sale_count = db.Column(db.Integer, unique=True)
def recurcive_function(n): if n == 1: return 10 else: return recurcive_function(n-1) + 15 if __name__ == "__main__": print(recurcive_function(1000))
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html ''' 讲解: 判断当前的Scrapyproject1Pipeline类下面是否有from_crawler方法,如果有的haul,就执行: obj=Scrapyproject1Pipeline.from_cra...
import pygame import enemy class Shakazulu(enemy.Enemy): def __init__(self): super().__init__() self.WIDTH = 60 self.HEIGHT = 15 #self.image = pygame.Surface((self.WIDTH, self.HEIGHT)) self.image = pygame.image.load("shakazulu.png") self.rect = self.image.get_rect()...
import sys, os, tempfile, json, logging, arcpy, fnmatch, shutil, subprocess, arcgis, getpass from arcgis.gis import GIS import datetime as dt from urllib import request from urllib.error import URLError import pandas as pd def calculate_datetime(text_field): date_string = str(text_field) if '.' in date_string:...
# This program collects user input on rainfall # for 12 months and then averages the total. years = int(input('How many years do you want to track? ')) months = 12 total = 0.0 # Get user info on rainfall for years_rain in range(years): print('Year Number', years_rain + 1) print('----...
import numpy as np import cv2 from ano_parser import PascalVocWriter,PascalVocReader from plot import draw_rect from PIL import Image import matplotlib.pyplot as plt import math from tqdm import tqdm from rotation import Rotation from random_translation import Translate from random_scale import Scale from horizontal_f...
""" Given a number represented by a list of digits, find the next greater permutation of a number, in terms of lexicographic ordering. If there is not greater permutation possible, return the permutation with the lowest value/ordering. For example, the list [1,2,3] should return [1,3,2]. The list [1,3,2] should ...
#!/usr/bin/env python ### FUNCTIONS - START ### def printHelp(scriptname): print('\nUsage: ' + scriptname + ' [options]\n') print('\twhere options are:\n'); print('\t\t-f --vector-file: read the specified file.\n') print('\t\t-h --help: print this help message.\n') print('\nAuthor: Daniele Linaro ...
#!/usr/bin/env python3 from setuptools import setup setup( name="binance-futures", version="1.0.1", packages=['binance_f', 'binance_f.impl', 'binance_f.impl.utils', 'binance_f.exception', 'binance_f.model', 'binance_f.base', 'binance_f.constant'], install_requires=['requests', 'apscheduler', 'we...
import Queue import findDistance as fD from Tkinter import * def DistCal(CAMap,destinationNum,xLength,yLength): exitNear = [[] for i in range(destinationNum)] for i in range(26): exitNear[0].append( [4+i,5]) for i in range(25): exitNear[1].append( [5,4+i]) for i in range(20): exitNear[2].append( [5,397+i...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Homimp', fields=[ ('id', models.AutoField(verbo...
# # Copyright (c) 2020-2021 Hopenly srl. # # This file is part of Ilyde. # # 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...
#!/usr/bin/python3 # Copyright (c) 2020 Ben Ashbaugh # # 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, me...
import numpy as np class Detector: def __init__(self, detectors): self.detectors = detectors def get_detectors(self): return self.detectors def get_1local(self,hit): #assume only one hit. return arra([u,v,w]) theModule = self.detectors[(self.detectors.volume_id == hit.volu...
f = open('c:\AllenYan\learn\\record.txt') boy_content = [] girl_content =[] count = 1 for i in f: if i[:6] != '======': role,content = i.split(':',1) if role == '小甲鱼': boy_content.append(content) if role == '小客服': girl_content.append(content) else: boy_f...
from PyPDF2 import PdfFileReader, PdfFileWriter from reportlab.pdfgen import canvas from StringIO import StringIO from cardmodel import Cardmodel def placeCard(cardCount, imgPath, samples): """ This function places a card based on the current count of cards on the appropriate page and position. Args: ...
import vtk from vtk.util.numpy_support import vtk_to_numpy import numpy as np import os import glob from PIL import Image from MeshAlignment import calculate_rotation, calculate_plane_normal from MeshSlices import create_plax_slices # 01. LV myocardium (endo + epi) # 02. RV myocardium (endo + epi) # 03. LA myocardium ...
# -*- coding: utf-8 -*- DESC = "gaap-2018-05-29" INFO = { "DescribeProxyGroupList": { "params": [ { "name": "Offset", "desc": "偏移量,默认值为0。" }, { "name": "Limit", "desc": "返回数量,默认值为20,最大值为100。" }, { "name": "ProjectId", "desc": "项目ID。取值范围...
import pandas as pd path = "/Users/scotthull/Desktop/2000.csv" df = pd.read_csv(path) EARTH_MASS = 5.972 * 10 ** 24 LUNAR_MASS = 7.34767309 * 10 ** 22 data = { "DISK": { "mass": 0, "particles": 0 }, "PLANET": { "mass": 0, "particles": 0 }, "ESCAPE": { "mas...
#!/usr/bin/env python3 import requests import json class LiveDNS: def __init__(self, apikey): self.base_url = 'https://api.gandi.net/v5/livedns' self.apikey = apikey self.s = requests.Session() self.headers = { 'Authorization': 'Apikey %s' % apikey, 'Conten...
""" Check that test suite file doesn't use the pandas namespace inconsistently. We check for cases of ``Series`` and ``pd.Series`` appearing in the same file (likewise for some other common classes). This is meant to be run as a pre-commit hook - to run it manually, you can do: pre-commit run inconsistent-namesp...
from principal import gui from random import randint from principal.gui import * from Estructura.Grafo import * from Estructura.Queue import * from Estructura.Tanque import * import json import threading class Main: if __name__ == '__main__': grafo = Grafo() with open('p.json') as f: ...
import os import json import requests import sys import base64 import zlib import urllib # Specific for Cesar from cesar.settings import CRPP_HOME # ------------------------------------------------------------------------ # See also: 2015_CrpStudioAPI_v1-3b.docx # -----------------------------------------------------...
# Import flask and libs from flask import Flask, render_template # Import SQLAlchemy from flask_sqlalchemy import SQLAlchemy # Define the WSGI application object app = Flask(__name__) # Configurations app.config.from_object('config') # Define the database object which is imported # by modules and controllers db = SQLA...
import pdb from models.artist import Artist from models.album import Album import repositories.artist_repository as artist_repository import repositories.album_repository as album_repository artist_1 = Artist('Car Seat Headrest') artist_repository.save(artist_1) artist_2 = Artist('DOPE LEMON') artist_repository.save(...
n = int(input()) wt = list(map(float,input().split())) wt.sort(reverse=True) #trips = [] trip = 0 i = 0 while i < len(wt): diff = 3.00 - wt[i] #no1 = wt[i] wt.remove(wt[i]) n1 = [x for x in wt if x<=diff] if len(n1) == 0: trip += 1 #trips.append(no1) else: n1 = max...
#type2 - only use add_formula function with parameter def run_formula(dv, param = None): defult_param = {'t1':5,'t2':10} if not param: param = defult_param alpha101_018 = dv.add_formula('alpha101_018', '''-1*Rank(((StdDev(Abs((close-open)),%s)+(close-open))+Correl...
#!/home/cheshire/install/bin/python -i # -*- coding: iso-8859-1 -*- """Change wording of Microfiche data when moving from C2 to C3 (June 2009). Usage: %prog [options] INPUTFILE Positional arguments: INPUTFILE Path to file containing data to strip/insert/replace Optional arguments: -h, --help ...
import numpy as np def check(t_diff, x_diff, y_diff): l1 = abs(x_diff) + abs(y_diff) if l1 > t_diff: return False elif (t_diff - l1) % 2 == 1: return False else: return True N = int(input()) t = np.zeros(N+1,) x = np.zeros(N+1,) y = np.zeros(N+1,) for i in range(N+1): if i...
#!/usr/bin/env python from __future__ import print_function import sys, os sys.path.insert(0, os.path.abspath('./')) import bluepy if __name__ == '__main__': #print bluepy.__dict__ print( "Version: ", bluepy.version()) print( "Builddate: ", bluepy.builddate()) print( "Const: ", bluepy...
# 5.5 Python標準ライブラリ # 5.5.1 setdefault()とdefaultdict()による存在しないキーの処理 print('--- 5.5.1 ---') periodic_table = {'Hydrogen':1, 'Helium':2} print(periodic_table) # setdefault(): keyがなければ、新しい値とともに辞書に追加される。 # ※set...との関数名だけど、dictから値を取得する機能 carbon = periodic_table.setdefault('Carbon', 12) print(carbon) print(periodic_table) ...
import tensorflow as tf from tensorflow.python.ops import array_ops import numpy as np def _get_shape_tuple(tensor): return tuple(dim.value for dim in tensor.get_shape()) class StochasticCGOptimizer: # logit has to be softmax! # Every train var must be a scalar! def __init__(self, loss, train_variab...
#!/usr/bin/env python # coding: utf-8 import logging import os import sys import time import xml.etree.ElementTree as ET from tornado.web import RequestHandler from socrates import hanzi from socrates.set import log from scripts.mongo_operate import del_user, get_user_value from scripts.check_sig import check_sig f...
# coding: utf-8 __author__ = 'Catarina Silva' __version__ = '0.1' __email__ = 'c.alexandracorreia@ua.pt' __status__ = 'Development' import xml.etree.ElementTree as ET def info_cursos_xml(xml_file: str): lista = [] tree = ET.parse(xml_file) root = tree.getroot() for curso in root.findall('curso'): ...
"""Setup module of application.""" from setuptools import find_packages, setup install_requires = [ 'aiohttp==3.6.2', 'aiohttp-cors==0.7.0', 'tartiflette-aiohttp==1.1.0', 'motor==2.1.0', ] setup( name='algernon_backend', version=0.1, platforms=['POSIX'], packages=find_packages(), ...
from collections import defaultdict class RegionPartitioner(object): def __init__(self, M, N, start_longitude, end_longitude, start_latitude, end_latitude): self.M = M self.N = N self.start_longitude = start_longitude self.end_longitude = end_longitude self.start_latitude = ...
""" write a program that will ask the user to enter their name and respond with a greeting using there name """ from math import sqrt print (" Hello! Welcome! ") name = raw_input ("what is your name? ") print ("Hello " + name + "!") #lengths for pythagorean T a = float(input("Please input side a: ")) b =...
import math import time import numpy as np from keras.models import load_model from keras.optimizers import Adam from keras.preprocessing.text import Tokenizer as tk from sklearn.model_selection import train_test_split import nltk from extractors import Extractor from utils.loader import load_glove from utils.utils ...
# Databricks notebook source #dbutils.widgets.dropdown("reset_all_data", "false", ["true", "false"]) # COMMAND ---------- from pyspark.sql.functions import rand, input_file_name, from_json, col from pyspark.sql.types import * from pyspark.ml.feature import StringIndexer, StandardScaler, VectorAssembler from pyspark...
# -*- coding: utf-8 -*- """ pip_services_runtime.config.MicroserviceConfig ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Microservice configuration implementation :copyright: Digital Living Software Corp. 2015-2016, see AUTHORS for more details. :license: MIT, see LICENSE for more details...
#!/usr/bin/env python # coding=utf-8 import os from distutils.core import setup delattr(os, 'link') setup( name='python-tab', version='1.0', author='Jerome Belleman', author_email='Jerome.Belleman@gmail.com', url='http://cern.ch/jbl', description="Print tables", long_description="Lay out ...
""" This document defines the Region app managers classes""" from base.managers import BaseGovernmentQuerySet from institutions.managers import InstitutionQuerySet from aldryn_apphooks_config.managers.base import ManagerMixin from parler.managers import TranslatableManager class CommuneQuerySet(InstitutionQuerySet): ...
import machine import time # Current sensor adc = machine.ADC() currentpin = adc.channel(pin='P17') VCC = 3.3 sens = 40 # 40 mV/A QOV = VCC/2 * 1000 offset = 0 i = 0 while True: print("--------------", i, "--------------") read_value = currentpin.voltage() print("Read value:", read_value) # (5/1023...
import numpy as np import cv2 bodyfind = cv2.CascadeClassifier('haarcascade_upperbody.xml') cap = cv2.VideoCapture(1) retf, framef = cap.read() gray = cv2.cvtColor(framef, cv2.COLOR_BGR2GRAY) body = bodyfind.detectMultiScale(gray, 1.3, 5) cv2.imshow('body',body) for (x,y,w,h) in body: cutbody = framef[y:y+...
from urllib.request import urlopen from bs4 import BeautifulSoup baseURL="https://www.babynames.com/blogs/names-blog/100-trending-names-of-2020/" res=urlopen(baseURL) raw_data=res.read() # raw_data.decode('utf-8') soup = BeautifulSoup(raw_data,'html.parser') #print(soup) rows= soup.select('.namos tr') for row in row...
#!/usr/bin/python # -*- coding: utf-8 -*- #Autor: Saul Vargas Leon from os import abort from selenium import webdriver from selenium.webdriver.common.keys import Keys def navegador(proxy=None, port=None, out_dir='/tmp'): """ Configura el perfil del browser a invocar """ profile = webdriver.FirefoxP...
"""__author__ = 'Шокуров Андрей Александрович'""" # Задача-1: # Ввести ваше имя и возраст в отдельные переменные, # вычесть из возраста 18 и вывести на экран в следующем виде: # "Василий на 2 года/лет больше 18" # по желанию сделать адаптивный вывод, то есть "на 5 лет больше", "на 3 года меньше" и.т.д. name = str(inpu...
# pond problem a = [ [0,0,1,1,1], [0,0,1,1,0], [1,1,1,0,0], [1,1,1,1,1], [0,0,0,1,0] ] count = 0 def fill(i,j): if i<0 or i>=len(a) or j<0 or j>=len(a): return if a[i][j] == 0: a[i][j] = 1 fill(i+1,j); fill(i-1,j); fill(i,j+1); fill(i,j-1) fill(i+1,j+1); fill(i+1,j-1); fill(i-1,j-1); fill(i-1,...
from django.db.models import F from django.http import HttpResponse from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from main.models import Transaction, Mempool, Block_header, Block_transaction, Node from main.api.serializers import Transacti...
# SPDX-FileCopyrightText: 2017 Radomir Dopieralski for Adafruit # Industries # # SPDX-License-Identifier: MIT """ MAX6675 this is a modification of the circuit python driver for the adafruit_max31855 meant to run the max6675 Author: Bobbi Balsano ``adafruit_max31855`` =========================== This is a CircuitPython...
from abc import ABC, abstractmethod, abstractproperty from selectorlib import Extractor import requests import json import os import logging as log log.basicConfig(level=log.DEBUG) PATH = os.path.abspath(os.getcwd()) class Scrapper(ABC): @abstractmethod def __init__(self): self.headers = headers = { '...
import os NEW_WIFI_MGN = ['BVI751', 'BVI752', 'BVI753', 'BVI754', 'BVI755', 'Vlan751', 'Vlan752', 'Vlan753', 'Vlan754', 'Vlan755'] OLD_WIFI_MGN = ['BVI203', 'BVI201', 'Vlan203', 'Vlan201'] MGN_INTERFACES = ['BVI200', 'BVI201', 'Vlan200', 'Vlan201', 'Vlan203', 'Vlan203'] Q_ROUTER = '10.63.255.163' NPM_SERVER = 't...
#!/usr/bin/python # -*- coding:utf8 -*- def searchInsert(nums, target): """ :type nums: List[int] :type target: int :rtype: int """ m = 0 i = 0 while i < (len(nums)): if nums[i] >= target: m = i break else: i += 1 if target > nums[...