text
stringlengths
8
6.05M
/Users/matthewpeterson/anaconda3/lib/python3.7/posixpath.py
''' A sequence of number is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. https://leetcode.com/problems/arithmetic-slices/#/description 错了2次,用的是动态规划的思路,但是最后超时,是因为没有加缓存吗? Time Limit Exceeded ''' class SolutionA(object): def n...
from methods import ask_user print(ask_user())
# Assignment 5 - Kevin Nolan # - CS 4720 - # # This program sends a request to a url provided by the user # and receives either a 200 (OK) response from the server or # an error message 404. It then prints and saves the response to an output file. # import requests userRequest = input("Enter Website: ") # ...
from employee import Employee ''' emp_1 = Employee(1,"Sunny","M.Tech",56000,"CS") emp_2 = Employee(2,"Bunny","M.Tech",56000,"IS") emp_1.show_info() emp_2.show_info() emp_1.increment_salary(2000) emp_1.show_info() emp_2.show_info() ''' lst_emp=[] def load_emp(): with open("empdata.txt") as f: fdata = f.r...
""" Скрипт для rsynca двух каталогов с рекурсивным обходом. Не добавляет то что уже есть в каталоге назначения. Для работы с путями используется MagicPath """ import os from dirsync import sync import MagicPath source_dir = "/home/user/dir/git" dest_dir = "/home/user/git" class Prog: @classmethod def run(...
from django.db import models from django.contrib.auth.models import AbstractUser from django.core.validators import RegexValidator class CustomUser(AbstractUser): first_name = models.CharField(max_length=20, null=False, blank=False) last_name = models.CharField(max_length=20, null=False, blank=False) GEND...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import torch.nn as nn from core.circuit import Circuit from core.controllers.lstm_controller import LSTMController as Controller from core.accessors.static_accessor import StaticAccessor as Accessor class NTM...
n=int(input()) l=[] for i in range(n): l.append(int(input())) small=min(l) ans=[num-small for num in l] for t in ans: print(t)
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if len(strs) == 0: return "" prefix = strs[0] for s in strs: if s.startswith(prefix): continue elif s == '': ...
from peewee import MySQLDatabase, PrimaryKeyField, Model, DateTimeField from datetime import datetime from config import * database = MySQLDatabase(host = DATABASE["host"], port = DATABASE["port"], user = DATABASE["user"], pas...
from django.urls import path from django.contrib.auth import views as auth_views from .views import index, city_view, add_new_place, place_view, all_places urlpatterns = [ path('login/', auth_views.LoginView.as_view(), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path(''...
# -*- coding: utf-8 -*- # Generated by Django 1.9.3 on 2016-09-05 08:35 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('elections', '0013_vote_last_modification'), ] operations = [ migrations.RemoveField(...
#refer to #http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_gui/py_video_display/py_video_display.html #2016-4-26 import numpy as np import cv2 cap = cv2.VideoCapture(0) while (True): ret, frame = cap.read() cv2.imshow('frame',frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindo...
import numpy as np def mean_absolute_percentage_error(y_true, y_pred): y_true, y_pred = np.array(y_true), np.array(y_pred) x = np.mean(np.abs((y_true - y_pred) / y_true)) * 100 return x def symetrique_mean_absolute_percentage_error(y_true, y_pred): y_true, y_pred = np.array(y_true), np.array(y_pred)...
from collections import defaultdict class node: def __init__(self,begin,target,weight): self.b=begin self.t=target self.w=weight class Graph(): def __init__(self, vertices): self.V = vertices self.graph = [] self.graph_matrix = [[0 for column ...
#!/usr/bin/env python # Funtion: # Filename: import socketserver import json, hashlib, os from conf import settings class MyTCPHandlers(socketserver.BaseRequestHandler): def handle(self): self.authentication() # 用户认证 while True: try: self.data = self.request.rec...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('users', '0021_auto_20150803_2332'), ] operations = [ migrations.AlterField( model_name='member', nam...
from base import BaseTestCase from app.models.place import Place from app.models.state import State from app.models.city import City from app.models.user import User from fixtures import * import unittest # for unittest.skip() class PlaceTestCase(BaseTestCase): table = [User, State, City, Place] path = '/place...
from django.urls import path from . import views app_name = 'micro' urlpatterns = [ path('', views.index, name='index'), path('send/', views.send, name='send'), ]
import numpy as np def anisodiff1(img, niter=10, kappa=20, option=1): """ Anisotropic diffusion. Usage: imgout = anisodiff(im, niter, kappa, gamma, option) Arguments: img - input image niter - number of iterations kappa - conduction coefficient 20-100 ? option - 1 sigmoi...
import numpy as np import cv2 import matplotlib.pyplot as plt import scipy.io as sio def phase_correlation(src_1, src_2): rows, cols = src_1.shape src_ph = cv2.copyMakeBorder(src_1, rows, rows, cols, cols, cv2.BORDER_CONSTANT, value=0) dst_ph = cv2.copyMakeBorder(src_2, rows, rows, cols, cols, cv2.BORDER_...
import logging import absl.logging import os import click import importlib @click.command() @click.option('--runner', default="run-ppo", help='Choose runner to start') @click.option('--working_dir', default="./__WORKING_DIRS__/__STANDARD__/", help='Path to working directory') @click.option('--config', default="", hel...
# -*- coding: utf-8 -*- """ Created on Mon Jul 27 13:03:23 2020 @author: rahul Here we will use a large spacy model to calculate document vectors and use it along with XGBoost for classification of twitter texts """ import pandas as pd import re from gensim.parsing import remove_stopwords import spacy from sklearn.mo...
# -*- coding: utf-8 -*- __version__ = "1.2.4" import os import platform from selenium import webdriver import time from unidecode import unidecode import urllib2 import httplib import json import sys import speech_recognition as sr import audioop import urllib from update import update from pydub import AudioSegment ...
with open("/home/cyagen1/Downloads/rosalind_kmer.txt")as f: f.readline() w=f.readline().strip() l="" while w: l+=w w = f.readline().strip() for j,k in enumerate(range(4,13,2)): L=[] for i in range(len(l)): if len(l[i:i+k])==k: L.append(l[i:i+k]) i...
############################################################################## # # Copyright (c) 2001, 2002 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # TH...
# coding=gbk import cv2 import tensorflow as tf from mtcnn.mtcnn import MTCNN from skimage import transform as trans import numpy as np import pdb import facenet import sys #将拼音转成汉字 pinyin2hanzi = {'lingengxin':'林更新','zhoudongyu':'周冬雨','liangjiahui':'梁家辉','shenteng':'沈腾','liyifeng':'李易峰','dengchao':'邓超','sh...
import pytest import json import numpy as np import pickle import tensorflow as tf from google.protobuf import json_format from tensorflow.core.framework.tensor_pb2 import TensorProto from seldon_core.proto import prediction_pb2 from seldon_core.microservice import get_data_from_json, array_to_grpc_datadef, grpc_datad...
# funny.py import re def is_funny(s): return re.match('(ha)+!+', s) != None
from setuptools import setup # Install python package setup( name="mastl", version=0.1, author="Mathias Lohne", author_email="mathialo@ifi.uio.no", license="MIT, LPGLv3", description="Code from my master thesis", install_requires=["tensorflow>=1.5", "numpy", "sigpy"], packages=["mastl"]...
from morepath.request import Response from onegov.wtfs import _ from onegov.wtfs import WtfsApp from onegov.wtfs.forms import CreateInvoicesForm from onegov.wtfs.layouts import InvoiceLayout from onegov.wtfs.models import Invoice from onegov.wtfs.security import ViewModel from typing import TYPE_CHECKING if TYPE_CHEC...
import numpy as np import chainer class Dataset(chainer.dataset.DatasetMixin): def __init__(self, dataset, digit): super().__init__() self.dataset = dataset self.digit = digit def __len__(self): return len(self.dataset) def get_example(self, i): image, label = sel...
# Copyright Alexander Wood 2016. # Solutions for Coursera's Bioinformatics 1 Course. # The following is a variation on the HammingDistance function which quits running its calculations once a bound # on the hamming distance has been reached. So for instance if the bound is d and p and q have a hamming distance of # ...
import math INFINITY = 1e200 * 1e200 try: from rpython.rlib.rfloat import formatd, DTSF_ADD_DOT_0, DTSF_STR_PRECISION from rpython.rlib.rfloat import round_double # pylint: disable=unused-import def float_to_str(value): return formatd(value, "g", DTSF_STR_PRECISION, DTSF_ADD_DOT_0) except Impor...
#!/usr/bin/env python import sys import rospy from std_msgs.msg import Float32MultiArray from std_msgs.msg import Float32 from geometry_msgs.msg import TransformStamped from sensor_msgs.msg import JointState from hardware_tools import Dynamixel import tf global armTorqueActive global gripperTorqueActive gripperTorque...
''' Settings: Controls resolution, colors, difficulties (?). ''' class Settings(): def __init__(self): self.display.set_mode((1200, 800))
# -*- coding: utf-8 -*- # Copyright (c) 2010 Infrae. All rights reserved. # See also LICENSE.txt # $Id$ import unittest from silva.core.services.interfaces import IMemberService from silva.security.renameusers.testing import FunctionalLayer from zope.component import getUtility from Products.Silva.tests.helpers impo...
import os import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torchvision.transforms as transforms from model.model import Spoofing, Classifier from dataset import faceDataset from loss import TripletLoss from torch.autograd import Variable from torch.utils.data import...
import sys, pygame FRAME_UPDATE_EVENT = pygame.USEREVENT+1 screen = None RES_X = 800 RES_Y = 600 key_up = False key_down = False key_left = False key_right = False def initialiseGame(): pass def update(): pass def draw(): pass def keyDown(key): global key_up, key_down, key_left, key_right ...
#-*- coding:utf8 -*- import os,re,json import datetime from django.http import HttpResponseRedirect from django.views.decorators.csrf import csrf_exempt from django.conf import settings from django.core.urlresolvers import reverse from django.contrib import messages from django.db.models import Sum,Count,Max from djang...
from . import osinfo from . import visitor_info import datetime
from future.utils import iteritems import pytest import unittest import numpy as np import pyqg import pickle import os from pyqg import diagnostic_tools as diag def test_describe_diagnostics(): """ Test whether describe_diagnostics runs without error """ m = pyqg.QGModel(1) m.describe_diagnostics() def ...
# Django project settings file # This file should be part of the svn repository of the project and should not # contains any site-specific information. # site-specific information (database name/login/password for example) should be # in the settings_local.py file and should not be added to the svn repository import o...
#!/usr/bin/python # -*- coding:UTF-8 -*- import requests import json import sys if len(sys.argv) < 2: sys.exit() paradero = ' '.join(sys.argv[1:]) rs = requests.session() url = 'http://www.transantiago.cl/predictor/prediccion?codsimt=' ser = '&codser=' url_final = '%s%s%s' % (url,paradero.upper(),ser) micro = web...
## @file MoleculeT.py # @author Christopher Andrade # @brief A Python file containing a single class called "MoleculeT" # that inherits two classes called "ChemEntity" and "Equality" # @date Monday, February 3, 2020 from ChemEntity import ChemEntity from Equality import Equality from ElmSet import ElmSet ...
from datetime import datetime, timedelta import folder_of_meanings.sup_functions as sup def generate_answer(date, need_date, today, c ): answer = "" row = list(c.execute('''SELECT * FROM timetable WHERE date=? ''', (need_date,))) if len(row) != 0: row = row[0][1:] if sup.check_weekend(r...
import RPi.GPIO as GPIO import time import requests from num2words import num2words from subprocess import call cmd_beg= 'espeak ' cmd_end= ' 2>/dev/null' GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(11, GPIO.IN) #Read output from PIR motion sensor x=time.strftime("%H") #to obtain system ti...
# coding: utf8 # Ferran March Azañero # 09/02/2018 numero1=input ("Introduce el primer numero:") numero2=input ("Introduce el segundo numero:") if(numero1>numero2): print "El numero1 es mas grande que el numero2" else: if(numero2>numero1): print "El numero2 es mas grande que el numero1" else: ...
from pandas import read_csv from pandas import DataFrame from pandas import concat from matplotlib import pyplot from pandas.plotting import lag_plot from pandas.plotting import autocorrelation_plot from sklearn.metrics import mean_squared_error from math import sqrt from statsmodels.graphics.tsaplots import plot_acf f...
''' Problem Statement Given an array with positive numbers and a target number, find all of its contiguous subarrays whose product is less than the target number. Example 1: Input: [2, 5, 3, 10], target=30 Output: [2], [5], [2, 5], [3], [5, 3], [10] Explanation: There are six contiguous subarrays whose product is l...
from ctypes import * from numpy import * import time import scipy import sys import traceback import scipy.optimize import os #************************************************************************* #* BELOW is the post-processing of acquired traces by the mathematical dll #* Acqiris_QuantroDLLMath1, which is based...
# Generated by Django 3.0.3 on 2020-02-13 16:12 from django.conf import settings import django.core.validators from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys, threading, pyodbc, logging, ConfigParser from pdu import pdu reload(sys) sys.setdefaultencoding('utf-8') # 生成数据库连接 def connect_to_mssql(): config = ConfigParser.ConfigParser() config.read('conf/sd.conf') # server name server = config.get('mssql', 'server'...
import math radians = float(input()) degrees = round(radians * 180 / math.pi) print(degrees)
import numpy as np from time import time from collections import Counter import networkx as nx # import gmatch4py as gm from grakel import graph_from_networkx, RandomWalk import pandas as pd import os from copy import deepcopy from mvmm.multi_view.block_diag.graph.linalg import get_adjmat_bp from mvmm.multi_view.base ...
# -*- coding: utf-8 -*- { 'name': 'Purchase Invoice Create Hooks', 'version': '1.0', 'category': 'Purchase Management', 'description': ''' Add hook point in purchase.action_invoice_create() ''', 'author': "Ecosoft", 'website': 'http://ecosoft.co.th', 'depends': ['purchase'], 'data': [...
#!/usr/bin/python # -*- coding:utf-8 -*- import xml.etree.ElementTree as ET import uuid, hashlib from datetime import datetime import random import time import pdb def object2dict(obj): t = type(obj) if 'class' in str(t): d = {} for (key, value) in obj.__dict__.items(): d[key] = object2dict(value) return ...
sum=0 aa=input().split() bb=input().split() n=int(aa[0]) k=int(aa[1]) for j in range(0,k): sum=sum+int(bb[j]) print(sum)
''' Find a number in an array of numbers by adding K th elemment with K th element and return the K th largest number. Note: 1. The K th largest number must an absolute number. 2. If the sum is already present in the array then add the number to K th value 3. Negative values will also be passed as ...
import pyotp import time from twilio.rest import Client from django.shortcuts import render from rest_framework.views import APIView from rest_framework import viewsets from rest_framework.response import Response from rest_framework import status from .serializers import (SiteGroupSerializer, CatalogItemDeptSerializer...
# 给定一个二维数组,计算可以围成矩形的个数。这道题当时废了 # 一点功夫,最后想到如果可以围成一个矩形,那么那两行做与 # 运算两个角一定为1,剩下的一定为0,如果有不止两个1,那么 # 用C(n,2)即可 class Solution: def countCornerRectangles(self, grid): """ :type grid: List[List[int]] :rtype: int """ vertical = len(grid) horizontal = len(grid[0]) def...
from requirementmanager.mongodb import ( requirement_collection, requirement_tree_collection, archive_requirement_collection, archive_requirement_tree_collection ) if __name__ == '__main__': requirement_collection.drop() requirement_tree_collection.drop() archive_requirement_collection.drop() a...
import numpy as np def genGaussian(x, mu, sigma): value = 1 / (np.sqrt(2 * np.pi) * sigma) * np.exp(-0.5 * (((x - mu) / sigma) ** 2)) return value def genMix(x, k, w, mu, sigma): value = np.zeros((len(x)), dtype=float) for i in range(k): value += w[i] * genGaussian(x, mu[i], sigma[i]) #...
import imapclient import imaplib import re import datetime from selenium import webdriver imaplib._MAXLINE=10000000 #zwiększenie rozmiaru pobieranych wiadomości imapObj = imapclient.IMAPClient('poczta.interia.pl',ssl=True) #imap dla danej poczty imapObj.login('nazwauzytkownika','haslo') #for i in imapObj.list_folders()...
winlist = [] fname = "Anibal" sname = "Lecter" checklist = [item[1] for item in winlist] if not fname in checklist:#Se agrega a winlist xq no esta winlist.append([fname, sname, 5]) else:#Ya existe fname solo actualizo el uptime winlist[checklist.index(fname)][2] = winlist[checklist.index(fname)][2]+1*5
from openerp.osv import osv, fields from openerp.tools.translate import _ from openerp import netsvc import openerp.addons.decimal_precision as dp class account_move_line(osv.Model): _inherit = "account.move.line" def validate_amount(self, cr, uid, ids, field_name, arg, context): result={} ...
from random import shuffle from word_rank import word_rank """ Scrabble Game Classes: Tile - keeps track of the tile letter and value Rack - keeps track of the tiles in a player's letter rack Bag - keeps track of the remaining tiles in the bag Word - checks the validity of a word and its placement Board - keeps track ...
from flask import Flask, render_template, url_for, request import sys import os import git app = Flask(__name__) @app.route('/', methods=['POST']) def webhook(): if request.method == 'POST': repo = git.Repo('https://github.com/fabrizioperuzzo/magicpy.git') origin = repo.remotes.origin ori...
# Generated by Django 2.2.11 on 2020-03-22 10:24 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('pro...
#!/usr/bin/env ############################################ # exercise_8_ifelse.py # Author: Paul Yang # Date: June, 2016 # Brief: handling the exception of ValueError and FileNotFoundError ############################################ ############################################ # print_file() # open file by the f...
#!/usr/bin/python3 ''' This module runs a query on a database to find states ''' if __name__ == "__main__": import MySQLdb from sys import argv db = MySQLdb.connect(host="localhost", port=3306, user=argv[1], passwd=argv[2], db=argv[3]) cur = db.cursor() cur.execute("SELEC...
def abbreviate(words): string_upper = words.upper() my_string = string_upper.replace('-',' ').replace('_',' ').split() abbreviation = [] for letters in my_string : abbreviation.append(letters[0]) answer = ''.join(abbreviation) return answer
import h5py import mne import numpy as np from mne import create_info from mne.io import RawArray from scipy.io import loadmat from moabb.datasets import download as dl from moabb.datasets.base import BaseDataset Thielen2021_URL = "https://public.data.donders.ru.nl/dcc/DSC_2018.00122_448_v3" # The default electrode...
"""empty message Revision ID: 725ee58a391d Revises: Create Date: 2019-01-21 21:36:09.043513 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = '725ee58a391d' down_revision = None branch_labels = None depends_on = None d...
import os, sys, re; from datetime import datetime, date, time def mkMinutesFriq(minutes, startTime, stopTime): # (curTime-mwSleep[curMW]).seconds/60; #print(minutes, startTime, stopTime); minutesStart = startTime.minute; for i in range(int((stopTime-startTime).seconds/60)+1): #print(i+minutesStart)...
from multiprocessing import Pool, Semaphore, cpu_count import sys sem = Semaphore(value=3) def recur_fibo(n): """Recursive function to print Fibonacci sequence""" if n <= 1: return n else: return(recur_fibo(n-1) + recur_fibo(n-2)) def mycallback(param): print(param) if __name__ == "_...
############################################################################### # # blobtrackHSV.py # # Python OpenCV and Python Lego NXT implementing an object tracking # webcam mounted on a Lego pan-tilt device. # Using HSV color space for object color detection # # January 9, 2018 # ########################...
import re from PIL import Image f = Image.open("oxygen.png") data = [f.getpixel((x,45)) for x in range(0,f.size[0],7)] # 7 is the implication on the picture,try to get the information at the gray line in the pic value = [r for r,g,b,a in data if r==g==b] print "".join(map(chr,map(int,re.findall("\d+","".join(map(chr,v...
#!/usr/bin/env python # coding=utf-8 import numpy as np def base_average_deviation(arry): """ Compute the average deviation The formal parameter is a one dimensional list. """ arry.sort() if len(arry)%2==1: res = abs(np.array(arry)-arry[len(arry)/2]) else: res = abs(n...
class Solution(object): def convert(self, s, numRows): """ :type s: str :type numRows: int :rtype: str """ if numRows == 1: return s newRow = "" gap1 = (numRows-1)*2 gap2 = 0 for i in range(0,numRows): position ...
from django.apps import AppConfig class SamlIdpConfig(AppConfig): name = 'samlidp' label = 'saml2 idp' verbose_name = 'saml2 idp'
#!/usr/bin/python import mplayer import toolbelt #import smartlog import mplayer import code class HashtagPlayer(mplayer.Player, toolbelt.interpreter.Interpreter): log = smartlog.Smartlog(); cursor = toolbelt.coordinates.Cursor(); playlist = []; def __init__(self): args = "-quie...
# -*- coding: utf-8 -*- import time import venusian from os import path from irc3 import base from irc3 import utils from irc3 import config from irc3.compat import asyncio from irc3.compat import Queue from collections import defaultdict from .plugins.command import command from .dec import plugin from .dec import ext...
from django import db from django.shortcuts import render from django.shortcuts import redirect from django.http import HttpResponse from .models import * from django.contrib import messages from django.utils import timezone import datetime import json from json import dumps import pyrebase # Create your views here. c...
# -*- coding: utf-8 -*- """ Created on Mon Feb 13 20:56:56 2017 @author: hina """ import networkx asin = '0805047905' # read the copurchase graph fhr=open("amazon-books-copurchase.edgelist", 'rb') copurchaseGraph=networkx.read_weighted_edgelist(fhr) fhr.close() # get degree centrality of given asin...
from datetime import datetime from app.models.connect import db class User(db.Model): __tablename__ = "users" id = db.Column(db.String(36), primary_key=True) name = db.Column(db.String(100)) create_time = db.Column(db.DateTime, default=datetime.now()) last_update_time = db.Column(db.DateTime, onu...
#!/usr/bin/env python import sys import os from libs.models.math import MainMatrix from libs.io.file_rw import FileManager def main(): # Basic input checks if len(sys.argv) != 2: sys.exit(f"Wrong program invocation " f"`{' '.join(map(os.path.basename, (sys.argv)))}`\n" ...
n=3 for i in range(n): print("*"*(i+1)) for i in range(n): print("*"*(n-i)) # def removerandsplit(string, word): # new = string.replace(word, "") # return new.strip() # string = "raghav isgood football player" # r = removerandsplit(string, "player") # print(r) def rmvsplt(str, word): new = str.r...
#Author - Ajay Amarnath #Email - amarnathajay@gmail.com import matplotlib.pylab as plotter from mpl_toolkits.axes_grid1 import host_subplot import matplotlib.animation as animation fig = plotter.figure() fig.suptitle("Data example for a panning graph", fontsize = 12) animatedGraph = fig.add_subplot(1, 1, 1) ...
#!/usr/bin/env ipython import os import sys import struct import PIL.Image as Image def check_dir(dir_path): if os.path.isdir(dir_path) == False: os.system('mkdir -p %s' % dir_path) def check_file(file_name, url): if os.path.isfile('mnist_data/%s' % file_name) == False: os.chdir('mnist_data...
import datetime __author__ = 'carlos' class Piece: def __init__(self, data, index = None): """ :param data: Must be a Content object or a string """ self.index = index if isinstance(data, Content): self.content = data self.text = None e...
class CryptoquoteAlreadyEncryptedError(Exception): """Exception for Cryptoquote that has already been encrypted.""" pass class ImproperKeyError(Exception): """Key must be 26 unique uppercase alphabetical letters.""" pass class EmptyText(Exception): """Text length must be greater than zero.""" ...
data = open("randomDataRAW.txt, "r");
from PIL import Image import piexif def metadata(img_path): zeroth_ifd = {piexif.ImageIFD.Make: u"DJI", piexif.ImageIFD.XResolution: (72, 1), piexif.ImageIFD.YResolution: (72, 1), piexif.ImageIFD.Software: u"piexif", piexif.ImageIFD.Model: u"FC6...
import hashlib import random import json as simplejson import webapp2 from taskstopipeline.helpers import * from taskstopipeline.models.sharelink import ShareLink from taskstopipeline.view_models import * from jinja2 import Environment, PackageLoader from Crypto.Cipher import AES from base_handler import BaseHandler ...
from django.contrib import admin from .models import CompanyId, MetricEvent, PermissionBuffer # Register your models here. admin.site.register(CompanyId) admin.site.register(MetricEvent) admin.site.register(PermissionBuffer)
#!/usr/bin/env python import rospy import numpy as np from ackermann_msgs.msg import AckermannDriveStamped from sensor_msgs.msg import LaserScan class Safety_Node: def __init__(self): # subscribe to Ackermann rospy.Subscriber("ackermann_cmd_mux/output", AckermannDriveStamped,self.ackermann_cmd_i...
import json import cv2 import numpy as np from utils import canvas def selectCroppingRefPoints(event, x, y, flags, param): # grab references to the global variables global refPt, cropPt # Record the mouse position when the left mouse button is clicked if event == cv2.EVENT_LBUTTONDOWN: # Add...
import pyautogui from PIL import ImageGrab y = 900 while True: if ImageGrab.grab().getpixel((555, y))[0] == 1 : pyautogui.click(555, y) if ImageGrab.grab().getpixel((620, y))[0] == 1 : pyautogui.click(620, y) if ImageGrab.grab().getpixel((690, y))[0] == 1 : pyautogui.click(690, y) if ImageGrab.grab().g...