text
stringlengths
8
6.05M
# coding=utf-8 from sshtunnel import SSHTunnelForwarder import pymysql import requests import re import time import json def create_conn(): server = SSHTunnelForwarder( 'serverB_ip', # B机器的配置 ssh_password='Data4truth.com', ssh_username='root', remote_bind_address=(...
#coding=utf-8 #算法复杂度参考 http://blog.sina.com.cn/s/blog_771849d301010ta0.html #left,right, loop #1. This is a test,so add time decorator to test #2. But 1000 random will cause sort_quick out of interation, then need to change sys.setrecursionlimit(1500) #3. But 50000 random will cause python error. then use find_recursi...
# -*- coding: utf-8 -*- ############################################################################## # # Authors: Boris Timokhin, Dmitry Zhuravlev-Nevsky. Copyright InfoSreda LLC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
# -*- coding: utf-8 -*- import torch def point_form(boxes): """ Convert prior_boxes to (xmin, ymin, xmax, ymax) representation for comparison to point form ground truth data. Args: boxes: (tensor) center-size default boxes from priorbox layers. Return: boxes: (tensor) Converted xmin, y...
import time from env import Env from agent import Agent # Init env=Env((5,6)) a1=Agent(env) env.reset() step_cnt=0 # Train for ep in range(1000): exp=env.step(a1) step_cnt=step_cnt+1 a1.update(exp) if step_cnt==10 or exp[-1]==True: env.reset() step_cnt=0 print("Episode: {}".format(ep)) # Test run trained...
import json import subprocess as sp def ffprobe(file: str, ffprobe_binary: str = "ffprobe") -> dict: proc = sp.Popen( [ ffprobe_binary, "-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", f...
# This file is part of Buildbot. Buildbot 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, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
# -*- coding: utf-8 -*- from django.db import models from account.models import User from products.models import Product PAYMENT_STATUS_CHOICES = [ ('PENDING','Pending'), ('DONE','Done'), ] PAYMENT_METHOD_CHOICES = [ ('COD','Cash on Delivery'), ('CREDIT','credit'), ('DEBIT','debit'), ] ORDER_S...
import requests import json from tkinter import * window = Tk() window.title('Covid-19') window.geometry('220x70') lbl = Label(window, text = "Total archive case:-.....") lbl1 = Label(window, text = "Total confirmed cases:-...") lbl.grid(column=1, row=0) lbl1.grid(column=1, row=1) lbl2 = Lab...
from rest_framework import serializers from snippets.models import Snippet # Serializer는 언제 필요한지 # Post가 있을 경우 # List PostSerializer # Retrieve PostRetrieveSerializer # Update PostUpdateSerializer # Create PostCreateSerializer class SnippetSerializer(serializers.ModelSerializer): class Meta...
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
import os import numpy as np import random import json # import gym import gfootball.env as football_env from optparse import OptionParser import torch from torch.utils.tensorboard import SummaryWriter from ddpg import OrnsteinUhlenbeckNoise, DDPG from ppo import PPO from td3 import TD3 from create_logger import creat...
import numpy as np import sys import os import glob from sklearn import preprocessing from sklearn import svm from ConfigParser import * from sklearn.linear_model import LogisticRegression #~ expDir = '/home/mzanotto/renvision/experiments/P29_01_04_16/'+str(sys.argv[1])+'/' os.chdir('/run/media/mzanotto/dataFast/t...
"""User model""" from sqlalchemy import Column, Integer, String, ARRAY, Text from models.db import Model from models.base_object import BaseObject class AudioPilot(BaseObject, Model): id = Column(Integer, primary_key=True) userID = Column(Text(length=10000)) date = Column(...
import pygame from settings import Settings from ship import Ship import game_functions as gf from pygame.sprite import Group from alien import Alien from game_stats import GameStats from button import Button from bullet import Bullet def runGame(): pygame.init() alien_settings=Settings() screen=pygame.dis...
''' The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order, but it also has a rather interesting sub-string divisibility property. Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following: d2d3d4=406 is divisible by 2 ...
print ("hello new feature")
#first we need turtle to do the magic '''No! Not the real old ugly (sometimes cute-only the baby) kind of turtles. I am talking about the -magician- turtle-module''' import turtle #this is to import the library. As Simple as that ''' Everything here is pretty straight forward. Take a look at it. It will make sense...
from samson_const import * import numpy as np def calnH(Gmas,Gnh,KernalLengths,density,Gmetal): #Inputs = Mass, NeutralHydrogenAbundance, Kernal Length, density, metallicity #Unit: Mass (1e10 Msun), .., kpc, 1e10Musn/kpc^3, ... #Convert to cgs Gmas = Gmas*1e10*Msun_in_g KernalLengths = KernalLength...
#tools library for use between playing with different scripts #creates a random array with the length(count) and minimum/maximum number for the random int(mini/maxi) def randomArray(count, mini, maxi): import random i = 0 temp = [] while i < count: temp.append(random.randint(mini, maxi)) i += 1 #returns temp ...
import logging import os import tempfile import threading import time from pteromyini.core.runner.feature_worker import FeatureWorker from pteromyini.lib.design_pattern.observer import Event import subprocess class SubprocessRunner: def __init__(self): self.log = logging.getLogger(__name__...
from django.shortcuts import render from rest_framework import viewsets from task_management.models import TaskList from task_management.serializers import TaskSerializer from django.contrib.auth.models import User from rest_framework import permissions from django.views.generic import TemplateView from django.views.ge...
""" Computations on the n-dimensional sphere embedded in the (n+1)-dimensional Euclidean space. """ import logging import math import numpy as np from geomstats.euclidean_space import EuclideanMetric from geomstats.manifold import Manifold from geomstats.riemannian_metric import RiemannianMetric import geomstats.vect...
import collections MESSAGE_NOT_SAME_NUM_TENSOR_DIMS_AS_DECLARED = \ "Tensor '%s' was declared to have %s tensor dim(s) but had %s." MESSAGE_NOT_SAME_DIM_SIZE_AS_DECLARED_BY = \ "Tensor '%s' dim %s was of size %s but was expected to be %s as declared by '%s' dim %s" MESSAGE_NOT_CORRECT_STATIC_DIM_SIZE = \ ...
class Solution: def frequencySort(self, s): """ :type s: str :rtype: str """ temp = {} for i in s: if i not in temp.keys(): temp[i] = 1 else: temp[i] += 1 temp2 = [] for key in temp.keys(...
import time from rm import Robomaster import threading import socket import os import sys import socket def testattitudepush(data): print(data) def main(mode='host'): robot_ip = '192.168.2.1' robot = Robomaster() if mode == 'network': robot_ip = robotlistener() if robot_ip == '': ...
# coding=utf-8 ################################## ### Importaciones ######### ################################## ## Importamos diccionarios from dictionaries.dictionary import LANGUAGE_DICTIONARY as LANGUAGES ## Importamos driver de Hardware from drivers import Hardware, RPIHat ## Importacion de objetos from servic...
from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter import numpy as np from math import * import sys fig = plt.figure() ax = fig.gca(projection='3d') sliceNumber = 1000 epsilon = 2*pi / sliceNumber # Make da...
my_foods = ['pizza', 'falafel', 'carrot cake'] firend_foods = my_foods[:] fireend_foods = my_foods print("My favorite foods are:") print(my_foods) print("\nMy firend's favorite foods are:") print(firend_foods)
from api.admin_resources import app class MyLogger(object): @classmethod def info(cls, *args, **kwargs): app.logger.info(*args, **kwargs) @classmethod def warning(cls, *args, **kwargs): app.logger.warning(*args, **kwargs) @classmethod def error(cls, *args, **kwargs): ...
import csv import numpy as np import matplotlib.pyplot as plt datax = [] datay = [] xHeading = '' yHeading = '' title = '' with open('Data.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 for row in csv_reader: if line_count == 1: #colum...
from __future__ import absolute_import from .hls_model import HLSModel, HLSConfig
# -*- coding: utf-8 -*- """ Tests for generation of all valid configs defined by a genfile schema. Created on Sun Jul 10 19:59:26 2016 @author: Aaron Beckett """ import pytest import json from ctip import GenSchema def test_single_var_single_arg(): """Test gen schema containing one variable with one argu...
from setuptools import setup, find_packages setup( name="nmf_q", version="0.10", author="hanfei sun", license="LGPL", scripts=["./nmfQ.py","./nmfRec.py"], packages= find_packages())
import os # Monitor BASE_URL = r'https://pass.rzd.ru/timetable/public/en?layer_id=5764' SLEEP_AFTER_RID_REQUEST = 1 SLEEP_AFTER_UNSUCCESSFUL_REQUEST = 1 REQUEST_ATTEMPTS = 10 BASIC_DELAY_BASE = 20 HEADERS = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0', 'Conte...
from datetime import date import boundaries boundaries.register('St. Catharines wards', domain='St. Catharines, ON', last_updated=date(2012, 9, 18), name_func=boundaries.clean_attr('WardName'), authority='City of St. Catharines', encoding='iso-8859-1', metadata={'geographic_code': '3526053'}, ...
from pwn import * r = remote("chall.pwnable.tw", 10207) #r = process("./tcache_tear") l = ELF("libc.so") def malloc(size, data): r.sendlineafter("Your choice :", "1") r.sendlineafter("Size:", str(size)) r.sendlineafter("Data:", data) def free(): r.sendlineafter("Your choice :", "2") def info(): ...
def caracter(string,c): valor = 0 for num in string: if(num == c): valor += 1 return valor string = input() c = input() valor = caracter(string,c) if valor == 0: print("Caractere nao encontrado.") else: print("O caractere buscado ocorre", valor, "vezes na sequencia.")
import time RANGE_STOP = eval(input("RANGE STOP > ")) def recursive_iterationSort(arr, n): if n <= 1: return recursive_iterationSort(arr, n-1) last = arr[len(arr)-1] j = len(arr)-2 while j >= 0 and arr[j] > last: arr[j+1] = arr[j] j -= 1 arr[j+1] = last n = list(ra...
from core.base import Base try: from .base import * except: from base import * class Liepin(SpiderBase, Base): name = 'lagou' def __init__(self, logger=None, *args): super(Liepin, self).__init__(logger, *args) def query_list_page(self, key, page_to_go): l = self.l dq, ...
#!/usr/bin/env python # -------------------------------------------------------- # Tensorflow Faster R-CNN # Licensed under The MIT License [see LICENSE for details] # Written by Xinlei Chen, based on code from Ross Girshick # Edited by Matthew Seals # -------------------------------------------------------- """ Demo...
import numpy as np import random import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from ddpg import QNet, Actor, DDPG from replay_buffer import ReplayBuffer class TD3(DDPG): def __init__(self, num_actions, gamma, tau...
# 3.1 Three in One: # Describe how you could use a single array to implement three stacks # I'll only implement Approach 1 here (fixed stack size) # The other option is to allow flexible stack size # This requires shifting stacks (chunks of the array) when an earlier stack "hits" the start of a later one # Additionall...
#BST Sequence class Tree: def __init__(self , val): self.data = val self.leftChild = None self.rightChild = None def bstSequence(self , root): if root is None: return None print(root.data , ' ' , end = '')...
import logging import click import torch from sonosco.common.constants import SONOSCO from sonosco.common.utils import setup_logging from sonosco.common.path_utils import parse_yaml from sonosco.models import Seq2Seq from sonosco.decoders import GreedyDecoder from sonosco.datasets.processor import AudioDataProcessor f...
from pytorch_lightning import LightningModule from transformers import BertModel class BertExplainer(LightningModule): """This encoder is used to export Bert attention after be trained.""" def __init__(self, hparams): super(BertExplainer, self).__init__() self.bert_encoder = BertModel.from_pr...
import mysql.connector class Tracking(): state_of_parcel = ['Parcel is in the source branch', 'Parcel Express driver prepare to deliver', 'Parcel is at its destination', 'Waiting for receiver', 'Parcel receive'] mydb = mysql.connector.connect( host="35.198.233.244", user="...
import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.keras import layers import time from .spectral import SpectralNormalization from .attention import Attention from .config import Config class SAGAN: def __init__(self, config:Config): self.cfg = config self.generator = self.cre...
from fastapi import ( Depends, FastAPI, ) from fastapi.middleware.cors import CORSMiddleware from sqlalchemy.orm import Session from quipper import ( models, schemas, services, ) from quipper.database import ( SessionLocal, engine, ) # Create the tables models.Base.metadata.create_all(bin...
from django.conf.urls import url,include from . import views urlpatterns=[ url(r'^$',views.index,name="index"), url(r'^post/',views.post,name="post"), url(r'^summary/(?P<id>\d+)/',views.summary,name="summary"), url(r'^search/$',views.search,name="search"), url(r'^gpa/$',views.gpa,name="gpa"), url(r'^search/jobs/summa...
from flask_restful import Resource import boto3 import json """ Queues I Care About: TrialEnrichment EnrichTrials TRIALS2ES """ class SQSService(Resource): def get(self, qname): sqs = boto3.resource('sqs') queue = sqs.get_queue_by_name(QueueName=qname) print(queue.attributes) retu...
# handling byte files b = bytes( range(0, 256) ) # start at 0 stop before 256 # print(b) # now lets write them to a file fout = open('bfile', 'wb') # 'wb' to (over)write bytes fout.write(b) fout.close() # read back fin = open('bfile', 'rb') retrieved_b = fin.read() fin.close() print(retrieved_b)
#!/usr/bin/env python # -*- coding: UTF-8 -*- ''' Creado el 05/02/2015 Ult. Modificacion el 08/03/2015 @author: Aldrix Marfil 10-10940 @author: Leonardo Martinez 11-10576 ''' # Importaciones necesarias from tablaSimbolos import * from lexer import find_column from functions import * # Errores de ...
'''8. Write a Python program to remove the n th index character from a nonempty string. ''' def remove(str, n): first_part = str[:n] last_part = str[n+1:] return first_part + last_part print(remove('Pradip', 0)) print(remove('Pradip', 3)) print(remove('Pradip', 5))
# -*- coding: utf-8 -*- """ Редактор Spyder Это временный скриптовый файл. """ import numpy as np import math from PIL import Image def setWeight(h, p1, p2): return math.exp(-1/h*math.sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2 + (p1[2] - p2[2])**2)) img = Image.open('image.jpg') arr = np.asarray(img, dtyp...
# Normalize data (length of 1) from sklearn.preprocessing import Normalizer from pandas import read_csv from numpy import set_printoptions import numpy as np filename = 'pima-indians-diabetes.data.csv' data = read_csv(filename) array = data.values # separate array into input and output components X = array[:, 0:8] Y ...
""" Usage args = { 'param1': [1e-3, 1e-2, 1e-2], 'param2': [1,5,10,20], } run_sweep_parallel(func, args) or run_sweep_serial(func, args) """ import os import itertools import multiprocessing import random import hashlib from datetime import datetime def _recurse_helper(d): return itertools.product( *...
""" #------------------------------------------------------------------------------ # Create ZV-IC Shaper # # This script will take a generalized input from an undamped second order system subject # to nonzero initial conditions and solve the minimum-time ZV shaper using optimization # # Created: 6/20/17 - Daniel Newm...
#! /usr/bin/env python # -*- coding:utf-8 -*- __author__ = ["Rachel P. B. Moraes", "Fabio Miranda"] import rospy import numpy as np from numpy import linalg from tf import transformations from tf import TransformerROS import tf2_ros import cv2 import math from geometry_msgs.msg import Twist, Vector3, Pose, Vector3Sta...
import cheffu.constants as c def operands_equal(operand_a, operand_b): sigil_a = operand_a['sigil'] sigil_b = operand_b['sigil'] assert(sigil_a == sigil_b == c.OPERAND_SIGIL) name_a = operand_a['name'] name_b = operand_b['name'] if name_a != name_b: return False modifiers_a = op...
from django.conf.urls.defaults import patterns, include, url urlpatterns = patterns('shopback.users.views', url(r'^username/$','get_usernames_by_segstr',name='usernames_by_segstr'), )
import numpy as np from scipy import sparse import h5py from rdkit import Chem from rdkit.Chem import rdMolDescriptors from tqdm import tqdm from pathlib import Path class Setup(object): """Handles all the evaluation stuff for a given fingerprint setting.""" def __init__(self, fingerprint, smifile, verbose=...
#!/usr/bin/env python # coding: utf-8 #from itertools import gzip import cPickle as pickle #import pandas as pd import numpy as np import os import gzip import time import sys #get_ipython().magic(u'matplotlib inline') from operator import itemgetter import matplotlib matplotlib.use('Agg') import matplotlib.pylab as p...
from random import shuffle, randrange import random def geraMapa(w=16, h=8): vis = [[0] * w + [1] for _ in range(h)] + [[1] * (w + 1)] ver = [["10"] * w + ['1'] for _ in range(h)] + [[]] hor = [["11"] * w + ['1'] for _ in range(h + 1)] def walk(x, y): vis[y][x] = 1 d = [(x - 1, y), (...
import pickle as pkl import numpy as np import tensorflow as tf import matplotlib.pyplot as plt import argparse import os import utils from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets( 'MNIST_data' ) '''--------Load the config file--------''' def parse_args(): parser ...
from random import shuffle import sys def re_arrange (words): shuffle(words) return words if __name__ == '__main__': random = [] i = 1 while i < len(sys.argv): random.append(sys.argv[i]) i += 1 words = re_arrange(random) for i in words: print(i) print(random)
import numpy as np from mayavi import mlab def test_surf(): """Test surf on regularly spaced co-ordinates like MayaVi.""" def f(x, y): sin, cos = np.sin, np.cos return sin(x + y) + sin(2 * x - y) + cos(3 * x + 4 * y) x, y = np.mgrid[-7.:7.05:0.1, -5.:5.05:0.05] s = mlab.surf(x, y, f) ...
import sys import urllib.request import json ''' python3 调用百度IP归属地查询接口显示中文结果 ''' # url = "https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query=118.190.33.130&resource_id=6006&t=1511175501478&ie=utf8&oe=gbk&cb=op_aladdin_callback&format=json&tn=baidu&cb=jQuery1102017679529467173427_1511175237779&_=1511175237794"...
from gramps.version import major_version register(GRAMPLET, id="Multimergegramplet Gramplet", name=_("Multimerge Gramplet"), description = _("Multimerge Gramplet"), status=STABLE, fname="multimergegramplet.py", authors = ['Kari Kujansuu', 'Nick Hall'], au...
def mergeSort(arr): if len(arr) > 1: for i in range(3): print() mid = len(arr) // 2 # split L = arr[:mid] R = arr[mid:] print("L : {0}".format(L)) print("R : {0}".format(R)) print("arr : {0}".format(arr)) print("MERGE SORT L...
import pickle import json from del_files import delete_files my_favorite_group_from_picle = {} my_favorite_group_from_json = {} with open('group.pickle','rb') as file: my_favorite_group_from_picle = pickle.load(file) print('from pickle\n',my_favorite_group_from_picle) with open('group.json','r',encoding='utf...
import cv2 import numpy as np img = cv2.imread('cr7.jpg') equ = cv2.equalizeHist(img) res = np.hstack((img,equ)) #stacking images side-by-side cv2.imwrite('res.jpg',res)
#!/usr/bin/python #coding:utf-8 import thread import time # Define a function for the thread def print_time(threadName, delay): count = 0 while count < 5: count += 1 print "%s: %s" % (threadName, time.ctime(time.time())) def check_sum(threadName, valueA, valueB): print "to calculate the sum of two num...
def wiecej_niz(napis, wiecej): ilosci = {} wynik = set() for l in napis: ilosci[l] = ilosci.get(l, 0) + 1 for k, v in ilosci.items(): if v > 3: wynik.add(k) return wynik def test_wiecej_niz_string1(): assert wiecej_niz('ala ma kota a kot ma ale', 3) == {'a', ' '} ...
#!/usr/bin/env python """ Oracle implementation of AddFile """ #This has been modified for Oracle from WMComponent.DBS3Buffer.MySQL.DBSBufferFiles.Add import Add as MySQLAdd class Add(MySQLAdd): """ Oracle implementation of AddFile """ #sql = """insert into dbsbuffer_file(lfn, filesize, events, c...
import asyncio async def do_some_work(x): print("Waiting " + str(x)) await asyncio.sleep(x) #定义一个回调函数 def done_callback(futu): print('Done') loop = asyncio.get_event_loop() futu = asyncio.ensure_future(do_some_work(3)) futu.add_done_callback(done_callback) loop.run_until_complete(futu) # print(asyncio.i...
from helper import * import glob IMG_DIR = '/path/to/img' MODEL_PATH = 'classify_image_graph_def.pb' IMG_NUM = 1408 QUERY_IMG = 22 CANDIDATES = 5 with tf.gfile.FastGFile(MODEL_PATH, 'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) _ = tf.import_graph_def(graph_def, name='') with ...
def do(): some_string = input('введите строку из нескольких слов: ') str_list = some_string.split() for word in str_list: print(word[:10]) if __name__ == '__main__': do()
#MAE.py #encoding:utf8 import math def MAE(records): return sum([abs(rui-pui) for u,i,rui,pui in records])/float(len(records))
import os import persistance from persistance import repo def fill_tables(): f = open("config.txt", "r") for line in f: if line[-1] == "\n": line = line[:-1] splited = line.split(',') if splited[0] == "C": coffee_stand = persistance.Coffee_stand(splited[1], spl...
from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^users$', views.index, name='my_index'), url(r'^users/new$', views.new, name='my_new'), url(r'^users/(?P<user_id>\d+)/edit$', views.edit, name='my_edit'), url(r'^users/(?P<user_id>\d+)$', views.show, name='my_show'), ...
import json import re from django.conf import settings from share.util.graph import MutableGraph from share.util.names import get_related_agent_name from share.util import IDObfuscator from .base import MetadataFormatter def format_type(type_name): # convert from PascalCase to lower case with spaces between wo...
import json from typing import List, Optional, Iterable, Dict, Tuple import numpy as np from matplotlib import pyplot as plt import matplotlib.colors as mc import colorsys from ucca4bpm.util.history import Run, History, Epoch from ucca4bpm.util.metrics import span_matcher, get_metrics def plot_f1_metrics(run_histor...
from django.conf.urls import url from accounts.views import * urlpatterns = [ url(r'^$',Register.as_view()), url(r'login/$',Login.as_view()), url(r'cleaner/$',FindCleaner.as_view()), url(r'book/(?P<city_id>\d+)/$',BookCleaner.as_view()), url(r'confirm/$',ConfirmBooking.as_view()), ]
__author__ = "Komal Atul Sorte" """ Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. Example: Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6. Follow up: If you have figured out the O(n) ...
from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import render, get_object_or_404, redirect from django.views import generic from article.forms import IncomeDebitsForm from article.models import * from users.models import User c...
import unittest import numpy as np from .. import generative_model from ..schemes import label_votes, intensity_id, diffusion_id class TestScheme(unittest.TestCase): def test_voting_methodology(self): """Tests the voting scheme and the voting as a whole method """ # 3 trains subjects, 1 test sub...
from flask import Flask from flask import Blueprint from . import auth from . import api from . import ui from .auth.functions.utils import getUser class Views: _listOfRouters = [auth.router, api.router, ui.router] def __init__(self, app:"Flask"): for r in self._listOfRouters: bp = Bl...
""" The onegov.server can be run through the 'onegov-server' command after installation. Said command runs the onegov server with the given configuration file in the foreground. Use this **for debugging/development only**. Example:: onegov-server --config-file test.yml The onegov-server will load 'onegov.yml' ...
import pandas import geopy from geopy.geocoders import ArcGIS nom = ArcGIS() #df=pandas.read_csv("supermarkets.csv") #df["Address_2"]=df["Address"]+","+df["City"]+","+df["State"]+","+df["Country"] df=pandas.read_csv("customers.csv") df["Address_2"]=df["Address"].apply(str)+","+df["Zip"].apply(str)+","+df["City"].apply...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('productos', '0010_auto_20150807_1634'), ('proyectos', '0004_auto_20150807_1621'), ] operations = [ migrations.Create...
import re import paho.mqtt.client as mqtt from influxdb import InfluxDBClient def on_connect(client, userdata, flags, rc): print("Connected with result code " + str(rc)) client.subscribe("guitar/+") def on_message(client, userdata, msg): match = re.match("guitar/([^/]+)", msg.topic) event_type = match...
print('Hello World') message = 'Hello World' print(message) print("Bobby's World") print('Bobby\'s World') my_message = """Bobby's World was a good cartoon in the 1990s""" print(my_message) print(len(message)) print(message[0]) print(message[10]) print(message[0:5]) print(message[:5]) print(message[6:]) print(message.l...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui_mplconfig.ui' # # Created by: PyQt5 UI code generator 5.14.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.set...
""" call.py - Telemarketing script that displays the next name and phone number of a Customer to call. This script is used to drive promotions for specific customers based on their order history. We only want to call customers that have placed an order of over 20 Wat...
#!/disk41/jjung_linux/util/python/anaconda3/bin/python # step0 return (i,j,k,hr) of model results from air plane path # required input files are : # [1] CAMx 3D met file # [2] CAMx landuse file which has 'TOPO_M' # [3] Aircraft measurement icartt data file # # Original script is from zliu. # Change calculation of fin...
from copy import deepcopy,copy import pygame import random import time pygame.init() background_img=pygame.image.load("background.jpg") frame=pygame.image.load("frame.png") frame2=pygame.image.load("frame.png") tile1=pygame.image.load("tile.jpeg") tile2=pygame.image.load("tile.jpeg") STAT_FONT = pygame.font...
class User: ''' Class that generates intances of a user ''' user_list=[] def __init__(self,accountname,accountpassword): self.accountname = accountname self.accountpassword= accountpassword def saveuser(self): ''' method that saves user object to user list ''' User.user_list.append(s...
#! /usr/bin/env python ############################################################################### # BBB_BasicMotorControl.py # # Basic test of motor control using the SparkFun TB6612FNG breakout board # http://sfe.io/p9457 # # Requires - Adafruit BeagleBone IO Python library # # NOTE: Any plotting is set up for...
import pyautogui size=pyautogui.size() print(size)