text
stringlengths
38
1.54M
import asyncio import pytest from yawf import BaseHandler @pytest.fixture def evloop(): return asyncio.get_event_loop() def test_basehandler_without_handle(evloop): handler = BaseHandler() @asyncio.coroutine def run_handler(): yield from handler(None) with pytest.raises(NotImplemente...
#There is an array with some numbers. All numbers are equal except for one. Try to find it! #It’s guaranteed that array contains at least 3 numbers. #The tests contain some very huge arrays, so think about performance. def find_uniq(arr): a, b = set (arr) if arr.count(a) == 1: return a else: ...
class EurecomDataset(Dataset): def __init__(self,domain,variation,training_dir=None,transform=None): self.transform = transform self.training_dir = training_dir # For each variant keep a list self.thermal_illu = [] self.thermal_exp = [] self.thermal_pose = [] ...
import csv import json from datetime import datetime from elasticsearch import Elasticsearch from elasticsearch import helpers import pandas as pd import uuid es = Elasticsearch() def convert_csv_to_json(file): workbook = pd.read_csv(file, na_filter=False) doc_columns= [] columns=list(workbook.columns.values) selec...
# ============================================================================================= # Classes # ============================================================================================= class Salario(object): """Representa o tipo Salario""" # Membro privado para armazenar o valor do salário ...
from nautipy import nautipy def test_bearing(): ''' make sure bearing is calculated correctly ''' assert False, 'Incorrect bearing!'
# -*- coding: utf-8 -*- """ Created on Sun Sep 22 20:54:30 2019 @author: Valenzuela """ import numpy as np import pandas as pd outlook=np.array(['sunny','overcast','rainy']) temperature = np.array(['hot','mild','cool']) humildy=np.array(['high','normal']) windy=np.array(['TRUE','FALSE']) play=np.array(['yes','no']) d...
import os import sys import importlib # noinspection PyUnresolvedReferences import tests.mock_tables.dbconnector modules_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.join(modules_path, 'src')) from unittest import TestCase from ax_interface import ValueType from ax_i...
import statistics import timeit import gc import problog from problog import get_evaluatable from problog.program import PrologString from problog.engine import DefaultEngine from problog.logic import Term def test_query_method1(engine, model_db, query_term): times_query = [] for i in range(0, 100): ...
import struct, os def parse_keyvalue(line): if line.find("//") != -1: line = line[:line.find("//")] quotes = [idx for idx, c in enumerate(line) if c == '"'] if len(quotes) < 4: return None key = line[quotes[0]+1 : quotes[1]] value = line[quotes[2]+1 : quotes[3]] return (key, value) ...
#!/usr/bin/python import sys input = """ push 0x736c2f2f push 0x6e69622f """ input = input.splitlines() input = filter(None, input) instructions = [] decoded = "" for i in input: instructions.append(i.replace('\t','')) print '\nNumber of instructions: ' +str(len(instructions)) + '\n' for inst in instruction...
import string dict={} data="" for i in range(len(string.ascii_letters)): dict[string.ascii_letters[i]]=string.ascii_letters[i-1] print(dict) with open("file.txt") as f: while True: c=f.read(1) if not c: print("end of file") break if c in dict: data=dict[c] else: data=c file.write(data) print(...
#!/usr/bin/python import datetime, openpyxl as xl, os from argparse import Namespace import code import operator, collections, re, argparse from django.core.management.base import BaseCommand, CommandError import contacts.models as cont class Command(BaseCommand): ''' Manage 1mo and 1yr calls actions: ...
# Generated by Django 3.0.7 on 2020-07-08 15:50 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0007_produto_tema'), ] operations = [ migrations.AddField( model_name='produto', name='autor', f...
class Room: """This is a class that represents the rooms""" def __init__(self, description, north, east, south, west): self.description = description self.north = north self.east = east self.south = south self.west = west def main(): room_list = [] room = Room("...
import datetime from typing import Optional from fastapi_users import models class User(models.BaseUser): first_name = str birthday = Optional[datetime.date] class Config: arbitrary_types_allowed = True orm_mode = True class UserCreate(models.BaseUserCreate): first_name = str b...
from rest_framework import viewsets from .models import Platillo from .serializer import PlatillosSerializer class PlatillosViewSet(viewsets.ModelViewSet): queryset = Platillo.objects.all() serializer_class = PlatillosSerializer
from gps import * import threading import datetime runGPS = None class GPSlocation_start(threading.Thread): def __init__(self): global runGPS threading.Thread.__init__(self) runGPS = gps(mode=WATCH_ENABLE) self.current_value = None self.running = True # def run(self): ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, division import numpy as np import collections import matplotlib.pyplot as py import matplotlib.gridspec as gridspec import sys from scipy.stats.stats import pearsonr from scipy import stats from operator import itemgetter class Book...
import getpass # coding: utf8 felhasznalo="bori99" jelszo="qwerty" # Kérjünk be felhasználónevet, majd jelszót, és ha megfelelo, akkor engedélyezze # a belépést # A jelszó lehetőség szerint ne jelenjen meg! engedely=False while engedely==False: user=input("Add meg a felhasználó nevét:".encode('cp1252')) #...
from picamera import PiCamera from picamera.array import PiRGBArray from time import sleep camera = PiCamera() camera.resolution = (640,480) camera.framerate = 16 rawCapture = PiRGBArray(camera, size=(640,480)) camera.start_preview() sleep(10) camera.stop_preview()
import numpy as np from typing import Tuple # Use for testing ransac from gen_point_cloud import rodrigues def main(): """ Main entry point for rigid estimation code Func. of interest ================= *estimate_rigid_motion: Estimate the pose using RANSAC *_estimate_rigid_motion: Estimate the pose ...
""" This model translates default strings into localized strings. """ from sqlalchemy import select, update, delete from muddery.server.mappings.element_set import ELEMENT from muddery.server.database.worlddata_db import WorldDataDB from muddery.worldeditor.settings import SETTINGS from muddery.worldeditor.dao import ...
from util.Constants import Constants as cs def compare_cards(trump, card_1, card_2): """ :param trump :param card_1: :param card_2: :return: the number that represents the card that won """ value_map = cs.STANDARD_CARDS_VALUE if card_1 == card_2: return 0 if trump == card...
import random # 创建随机数 n = random.randrange(1,100) # 获取输入 guess = int(input("输入任意数值: ")) while n != guess: # 判断是否正确 # 小于 if guess < n: print("太小了") guess = int(input("再次输入数值: ")) # 大于 elif guess > n: print("太大了!") guess = int(input("再次输入数值: ")) else: break pr...
import torch import torch.optim as optim import numpy as np from acvae import AdversarialcVAE from train_acvae import train, test import argparse import pickle from math import floor from keras.utils import to_categorical from tqdm import tqdm PIK1 = 'data.dat' PIK2 = 'movement_labels.dat' PIK3 = 'surface_labels.dat'...
# -*- coding: utf-8 -*- class DummyMultiDict(dict): """dummy MultiDict class for testing """ def getall(self, key): try: return self.__getitem__(key) except KeyError: return [] class DummyFileParam(object): """dummy FileParam object for testing """ d...
from __future__ import division from gaussianMixturesTesting import Gaussian from gaussianMixturesTesting import GM import numpy as np from scipy.stats import multivariate_normal as mvn import copy from random import random import time import matplotlib.pyplot as plt if __name__ == "__main__": #Initialize some ra...
from setuptools import setup, find_packages setup(name='ConvertCSVtoParquet', version='0.2', description='CSV to Parquet converter', author='KL', packages=find_packages(), zip_safe=False)
# -*- coding: utf-8 -*- """ 工程中我们使用一个名字为config.py的Python模块用来保存全局的配置, 由于logging在工程中每个源代码文件都可能用到, 因此我们把logging模块在config.py中生成一个实例, 这样其它模块只需要引用这个实例就可以了。 在其它模块中,我们使用这样的语句引用logger对象: # from config import logger """ import logging import logging.config import os # 在当前工作目录下创建Log文件夹 def logger(): path = os.getcwd()+"\\Log" ...
import sys input = sys.stdin.readline N = int(input()) values = sorted(list(map(int, input().split()))) start = 0 end = N-1 left = 0 right = N - 1 ans = abs(values[0] + values[N-1]) while start < end: temp = values[start] + values[end] if abs(temp) < ans: ans = abs(temp) left = start ...
#!/usr/bin/env python3 import os import codekit.codetools as codetools import pytest def test_tempdir(): """Test temporary directory context manager""" with codetools.TempDir() as temp_dir: assert os.path.exists(temp_dir) assert os.path.exists(temp_dir) is False def test_debug_lvl_from_env(): ...
import os from Coverage import decision, coverage from time import sleep print(" =^..^= Welcome to the Statement - Decision Coverage tool v0.01 =^..^= ") print("""\033[2;37;40m Made by (Khaled Redhwan) AKA ^___^ ╔═╗┬┬─┐ ╔═╗┌─┐┌┬┐ ^___^ ...
from django.contrib import admin from portfolio.forms import Login # Register your models here. admin.site.register(Login)#I want to see this model inside the admin
from pandas_vb_common import * class concat_categorical(object): goal_time = 0.2 def setup(self): self.s = pd.Series((list('aabbcd') * 1000000)).astype('category') def time_concat_categorical(self): concat([self.s, self.s])
# -*- coding: utf-8 -*- ''' 基于LDA,对人脸数据集进行维数约减,并计算分类准确率 Created by Longrui Dong --2018.01.05 ''' from __future__ import print_function import matplotlib.pyplot as plt from time import time import logging import itertools import numpy as np from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from skle...
from django.contrib import admin from . import models from django.utils.safestring import mark_safe from actions import Actions # Register your models here. class AcceuilAdmin(Actions): fieldsets = [ ('Presentation',{'fields': ['image','titre']}), ('Video', {'fields': ['video']}), ('stat...
""" Uses FilterReg algorithm to match two point clouds """ import numpy as np import open3d as o3d from probreg import filterreg from scanner3d.registration.pair.base_pair_reg import BasePairReg class FilterReg(BasePairReg): def register(self, pcd1, pcd2): f_reg = filterreg.registration_filterreg(pcd1, p...
# Generated by Django 2.2.6 on 2019-10-15 13:55 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("shop", "0009_book")] operations = [ migrations.AddField( model_name="book", name="compiler", field=models.CharField(b...
import csv import random from numpy import genfromtxt import sqlalchemy from sqlalchemy import BigInteger from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session from sqlalchemy.orm import sess...
import pygame import time import random from snake_clase import SnakeGame rand = random.Random() class SnakeGameGUI(SnakeGame): def __init__(self, headless_mode = False): super().__init__() self.AZUL = (0, 0, 255) self.MORADO = (255, 0, 255) self.NEGRO = (0, 0, 0) self...
import requests from django.shortcuts import render, redirect from django.http import HttpResponse, Http404 from django.utils import timezone from .models import Diner, Review, Visited, Comment, Rating from .forms import PostForm, ReviewForm, CommentForm from django.core.paginator import EmptyPage, PageNotAnInteger, P...
import psycopg2 import json from db.config import config conn = None # database code try: # read connection parameters params = config() # connect to the PostgreSQL server print('Connecting to the PostgreSQL database...') conn = psycopg2.connect(**params) # create a cursor cur = conn.c...
''' 设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。 push(x) -- 将元素 x 推入栈中。 pop() -- 删除栈顶的元素。 top() -- 获取栈顶元素。 getMin() -- 检索栈中的最小元素。 示例: MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); --> 返回 -3. minStack.pop(); minStack.top(); --> 返回 0. minStack.getMin(...
import os import cv2 face_cascade = cv2.CascadeClassifier('/home/nitish/Desktop/project/s_w/opencv-4.1.2/data/haarcascades/haarcascade_frontalface_default.xml') def face_extractor(img): gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #to convert into gray scale images faces = face_cascade.detectMultiScale(gray, s...
import nltk nltk.download('punkt') f = open('sravan.txt', 'r',encoding='utf-8') input = f.read() stokens = nltk.sent_tokenize(input) wtokens = nltk.word_tokenize(input) for s in stokens: print(s) print('\n') for t in wtokens: print(t)
from django.shortcuts import redirect, render, reverse from django.http import HttpResponse, HttpResponseRedirect from django.views.generic import FormView, CreateView from ..models import User, AgentApplications from ..forms import PasswordResetForm, NewPasswordForm, AgentSignUpForm from django.contrib.auth.decorators...
import requests import base64 import json import os import glob from flask import current_app redaction_request = { "imageData":"", "imageType":"image/png", "imageRedactionConfigs":[ { "infoType":{ "name":"PHONE_NUMBER" }, "redactionColor":{ "blue":0.93, "green":0.93...
from django.urls import path from app.api.user import views urlpatterns = [ # path('create', views.Position_createAPIView.as_view(), name='api-status-create'), path('list', views.Employee_infoListAPIView.as_view(), name='api-user-list') ]
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.model_selection import GridSearchCV from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import StratifiedKFold from xgboost import XGBClassifier from sklearn.ensemble import ExtraTreesCl...
from mailer.utils.helpers import get_connections class EmailDispacher(object): ''' Email dispacher class, taking the imported engines in the settings file. It tryies to send email to the provider with higher priority, if it fails continue to the next one. ''' def __init__(self, **kwargs): ...
def encodeVer1(text): #for Encryption """ This is one of the ways that the text can be encrypted. It is very simple. Syntax: encodeVer1(text) """ encodedText = list(text) length = len(encodedText) for i in range(0,length): encodedText[i] = ord(encodedText[i]) for i in range(0,len...
#This program removes punctuations from the string #define punctuation punctuations='''!--,''' my_str="Hello , He said !!!!! ---- and went." no_punc= "" for char in my_str: if char not in punctuations: no_punc=no_punc+char print(no_punc)
import random from utils.misc import read_json_from_file def randurl(): return random.randint(1e9,1e10) def getrec(path, currobj): parts = path.split("/") key = parts[0] if currobj["disposition"] == "dict": for child in currobj["childsarg"]: if child["key"] == key: ...
import pandas as pd from constants import CONTEST_ID as cid from constants import TEAMS_NF_FD pool_file = "-".join(['FanDuel-NFL', cid, 'players-list.csv']) pool = pd.read_csv('data/pool/' + pool_file) df = pd.read_csv('data/nf_projections.csv') # modify team names to match player pool df['team'] = df['team'].str.upp...
# from requests_html import HTMLSession # import requests import bs4 import re import sys from PyQt5.QtWidgets import QApplication from PyQt5.QtCore import QUrl from PyQt5.QtWebEngineWidgets import QWebEnginePage def get_phone(soup): soup=str(soup) phone = re.findall(r'^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d...
import tkinter as tk import sys import multiprocessing class MyApp(): def __init__(self): self.root = None #线程管理器 self.processinges = [] #最优化算法 self.CoordinateAlternation = None self.DFP = None self.BFGS = None self.GradientDescent = None se...
# Generated by Django 2.1 on 2018-08-18 14:44 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='location', fields=[ ('id', models.AutoField(a...
# -*- coding: utf-8 -*- # @Author: WuLC # @Date: 2016-10-03 20:02:50 # @Last modified by: WuLC # @Last Modified time: 2016-10-03 20:03:09 # @Email: liangchaowu5@gmail.com class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: int """ count = {} ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.views import View from django.shortcuts import render from .models import Tweet from .forms import TweetForm class MainView(View): def get(self, request): return render(request, 'twitter/index.html') class TweetView(View): d...
#!/usr/bin/env python PACKAGE = 'amr_braitenberg' NODE = 'differential_drive_emulator' import rospy from geometry_msgs.msg import Twist from amr_msgs.msg import WheelSpeeds class DifferentialDriveEmulatorNode: def __init__(self): rospy.init_node(NODE) # read differential drive params: s...
import collections import game_field import consts import unit import random Map = collections.namedtuple('Map', 'row, col, name') Point = collections.namedtuple('Point', 'row, col') class Game: def __init__(self): self.field = self.get_field() self.portal = consts.PORTAL self.castle = co...
"""Controller Local/Global Switch - MAYA 2015 #==================================================== # # DEVELOPMENT HISTORY # # # TO DO # - In the long run setup little "L" and "G" shapes to attach to the local and Global Control. But for this, probably just use different colours an...
#!flask/bin/python from flask import Flask, request from flask_prometheus import monitor from opentracing.ext import tags from opentracing.propagation import Format from jaeger_client import Config import random import logging import sys app = Flask(__name__) def init_tracer(service): logging.getLogger('').handler...
#!/usr/bin/python #coding:utf-8 from django.shortcuts import render from django.http import HttpResponse,HttpResponseRedirect,HttpResponseNotFound import datetime from django.shortcuts import render_to_response from django.template.context import RequestContext from nmaptoolbackground.control import usercontrol,jobcont...
import itertools import mechanize from bs4 import BeautifulSoup br = mechanize.Browser() comb = itertools.product(list("abcdefghijklmnopqrstuvwxyz"),repeat=4) f = open("testfile.txt","w") for i in comb: br = mechanize.Browser() response = br.open('http://localhost/sample/log.php') br.select_form(nr=0) br.form...
import pprint message = 'We on an ultra light beam. This is a god dream.' count = {} for character in message.upper(): count.setdefault(character, 0) count[character] = count[character] + 1 pprint.pprint(count)
from __future__ import absolute_import, division, print_function __metaclass__ = type from ansible.errors import AnsibleFilterError from ansible.module_utils.six import iteritems, string_types from ansible.plugins.filter.core import flatten from numbers import Number def config(parameters, exclude=[]): if not i...
tot_name = os.path.join(os.path.dirname(__file__),'src/data', file_name) # open the json datafile and read it in with open(tot_name, 'r') as inputfile: doc = json.load(inputfile) # transform the data to the correct types and convert temp to celsius id_movie = int(doc['id']) movie_name = str(doc['origi...
import json from django.http import JsonResponse from Management.controller import Controller, Service def request_on(request): controller = Controller() data = json.loads(request.body) room_id = data.get('roomId') mode = data.get('mode') target_temp = controller.settings['defaultTargetTemp'] ...
#encoding: utf-8 from .uralicApi import analyze as uralic_api_analyze from .uralicApi import __where_models as where_models import os, sys from subprocess import Popen, PIPE from mikatools import open_write def _Cg3__parse_sentence(words, language, morphology_ignore_after=None, descrpitive=True,remove_symbols=True): ...
#!/usr/bin/env python # encoding: utf-8 # @author: ZhouYang try: import cPickle as pickle except ImportError as e: print(e) import pickle import logging from addict import Dict from core.database import User from pony.orm import db_session logger = logging.getLogger(__name__) class Session(object): ...
text = """Начало КОНТЕНТ Конец""" text = 'Начало\n\nКОНТЕНТ\n\nКонец' print('-' * 60) print(str(text)) print('-' * 60) print('*' * 60) print('-'*60) print(repr(text)) print('-'*60)
# Parking: | # def can_enter_the_cave(data): # for line in data: # if all(cell == 0 for cell in line): # return True # return False def can_enter_the_cave(data, x=0, y=0): print(x, y) is_last_line = x + 1 == len(data) if data[x][y] != 0 and is_last_line: return False...
import collections from typing import List import tlm.data_gen.bert_data_gen as btd def pad0(seq, max_len): assert len(seq) <= max_len while len(seq) < max_len: seq.append(0) return seq def truncate_seq(tokens_a, max_num_tokens, rng): """Truncates a pair of sequences to a maximum sequence l...
species( label = 'CCC1OC[C]1OC([O])CCC=O(20302)', structure = SMILES('CCC1OC[C]1OC([O])CCC=O'), E0 = (-269.977,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([2750,2770,2790,2810,2830,2850,1425,1437.5,1450,1225,1250,1275,1270,1305,1340,700,750,800,300,350,400,2750,2800,2850,1350,1500,750,1...
from flaskbb import create_app #from flaskbb.configs.production import ProductionConfig from flaskbb.configs.development import DevelopmentConfig #flaskbb = create_app(config=ProductionConfig()) flaskbb = create_app(config=DevelopmentConfig())
from django.conf.urls import url from . import views from shop.views import IndexView app_name = 'shop' urlpatterns = [ url(r'^$', IndexView.as_view(), name='index'), url(r'^register/', views.RegisterCreate.as_view(), name='register'), url(r'^coffee/', views.coffee_view, name='coffee_view'), url(r'^baked/', view...
from django.contrib import admin from .models import Blog, Keyword, Reply class BlogAdmin(admin.ModelAdmin): list_display = ( 'title', 'date', 'image', ) list_filter = ('date',) class ReplyAdmin(admin.ModelAdmin): list_display = ( 'blog', 'author', 'd...
import datetime import numpy as np import tensorflow as tf from tensorflow import keras from auto_forecaster.io import TextForecast, NetCDF class ForecastRegion: def __init__(self, name, region_id, spot_range): """ Parameters ---------- name: str the short-form name ...
import numpy as np import matplotlib.pyplot as plt from sklearn import svm def opendata(file): X = [] Y = [] data = open(file,"r") for line in data: x = [float(num) for num in line.split()[1:]] y = float(line.split()[0]) X.append(x) Y.append(y) X = np.array(X) Y = np.array(Y) return (X,Y) (train_X, tra...
n1 = float(input('Insira um numero:')) n2 = float(input('Insira um numero:')) n3 = float(input('Insira um numero:')) if n1 > n2 > n3 and n1 > n3: print('maior:',n1) print('menor:',n3) elif n1 > n2 and n1 > n3 > n2: print('maior:', n1) print('menor:', n2) elif n2 > n1 > n3 and n2 > n3: print('maior:...
import os import re import unittest from brdm.NcbiBlastData import NcbiBlastData class TestNcbiBlastData(unittest.TestCase): @classmethod def setUpClass(self): dir_path = os.path.dirname(os.path.realpath(__file__)) self.fixture = NcbiBlastData('{}/test_config.yaml'.format(dir_path)) ''' ...
# # Bisection search to guess and check from lecture 3. Code # still break under negative input and numbers from 0 to 1 # # Define main function def main(): # Put down some constants and storing variables first epsilon = 0.01 num_guesses = 0 low = 0 # Prompting user for input and do some initial calcu...
# Generated by Django 2.0.3 on 2018-03-14 23:50 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('organization', '0010_teacher_image'), ] operations = [ migrations.RemoveField( model_name='courseorg', ...
print("Solo menores a siete") def porcentaje (a, nt): p = (a * 100) / nt return p def par(numero): if numero % 2 == 0: return True return False def multiplo(n1, n2): resto = n1 % n2 return resto == 0 n = int(input("Cargue una secuencia de números. Termina en cero: ")) cont_pares = 0 ...
import numpy as np import math import time import numbapro from numbapro import vectorize from numba import autojit, jit from blackscholes import black_scholes #import logging; logging.getLogger().setLevel(logging.WARNING) RISKFREE = 0.02 VOLATILITY = 0.30 @jit('f8(f8)') def normcdf(d): A1 = 0.31938153 A2 = ...
from pyspark import SparkContext from pyspark.sql import SQLContext from pyspark.sql.types import * sc = SparkContext("local","Reading_csv") schema1=StructType([StructField("make",StringType(),True),StructField("fueltype",StringType(),True),StructField("numofdoors",StringType(),True),StructField("bodystyle",StringType(...
from motive_data_helpers import * import quaternion as q import pandas as pd import os import matplotlib.pyplot as plt from scipy.io import savemat import pdb def quat_to_matlab(file_q): data_q = readfile(file_q, 'stop2') quats = data_q[['Rotation'+k for k in ['W','X','Y','Z']]].values savemat(file_q[:-3]+...
import cfg import user_info import bl_as_modul import aiosqlite from telethon.tl import types from telethon.tl.types import ( KeyboardButtonRow, KeyboardButtonCallback, ) from datetime import date, datetime, timedelta mdate_db = cfg.user_db # './mdate.db' bot = bl_as_modul.client tempAM_but = types.Repl...
# -*- coding: utf-8 -*- """ Created on Mon Sep 11 09:39:40 2017 @author: MichaelEK """ from shapely.geometry import Point, LineString, Polygon def getPolyCoords(row, coord_type, geom='geometry'): """Returns the coordinates ('x' or 'y') of edges of a Polygon exterior""" # Parse the exterior of the coordinate...
#Funcion que te dira el maximo de dos numeros def max(A,B): if A>B: return A else: return B A = int(input("Ingrese el primer numero: ")) B = int(input("Ingrese el segundo numero: " )) print (max(A,B))
import os import sys sys.path.append("./") import hashlib import requests import numpy as np from utils import pdf_utils from search_engines import common from html.parser import HTMLParser from enum import Enum class Paper(Enum): TITLE = 3 LINK = 6 class MyHTMLParser(HTMLParser): def __init__(self): ...
# Copyright (C) 2009 Internet Systems Consortium. # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYST...
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_bcrypt import Bcrypt from flask_login import LoginManager from flask_mail import Mail import json app = Flask(__name__, template_folder='templates') app.config['SECRET_KEY'] = '7976b37fadec64fb4ceae186f7533ec4' app.config['SQLALCHEMY_DATABASE_...
#!/usr/bin/env python import datetime import qwiic_ccs811 import time import sys def runExample(): mySensor = qwiic_ccs811.QwiicCcs811() if mySensor.connected == False: print("The Qwiic CCS811 device isn't connected to the system. Please check your connection", \ file=sys.stderr) return mySensor.begin()...
""" Module for wizard dialogs. """ import wx from .input import Dialog class WizardPage(wx.Panel): def __init__(self, parent, title): wx.Panel.__init__(self, parent) self.sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(self.sizer) self.ctrl_title = wx.StaticText(self, label=tit...
# -*- coding:utf-8 -*- from django.db import models from django.contrib.auth.models import User from backend.core.models import ModelDateMixin, ModelUserMixin, ProjectManage, VersionManage, ModuleManage, TaskManage class PageManage(ModelUserMixin, ModelDateMixin): """ 公共表,页面管理 """ version = models.ForeignKey(...
from cooperative_transport.utils import saturation import numpy as np def proportional_control(k_p, r, y, u_max, avoid_overturning): """Implement proportional control law. Arguments: k_p (float): Proportional gain r (float): reference signal y (float): system output signal u_ma...
''' Created on 13 May 2016 @author: Sam ''' # Python 3.5 if __name__ == '__main__': runningbest = (0, 0) for contestant in range(5): line = input().split() score = sum([int(line[a]) for a in range(4)]) if score > runningbest[1]: runningbest = (contestant, sco...