def setUpClass(cls): #启动Firefox try: cls.client=webdriver.FireFox() except: pass #如果无法启动浏览器,则跳过这些测试 if cls.client: #创建程序 cls.app=create_app('testing') cls.app_context=cls.app.app_context() cls.app_context.push() #禁止日志,保持输出整洁 import logging logger=logging.getlogger('werkzeug') logger.setLevel("ERROR") #创建数据库,并使用一些虚拟数据填充 db.create_all() Role.insert_roles() User.generate_fake(10) Post.generate_fake(10) #添加管理员 admin_role=Role.query.filter_by(permission=0xff).first() admin=User(email='*****@*****.**',username='******', password='******',role=admin_role) db.session.add(admin) db.session.commit() #在一个线程中启动FLask服务器 threading.Thread(target=cls.app.run).start()
def __init__(self, sid="client"): self.logger = logging.getlogger("irc-{}".format(sid.lower())) self.connected = False self.features = features.FeatureSet() self.handlers = {} self.socket = None self.reconncount = 0 self.nocheck = False self.whoing = None self.sentmsgs = 0 self.lastping = time.time() # Internal handlers self.addhandler("join", self._on_join) self.addhandler("part", self._on_part) self.addhandler("nick", self._on_nick) self.addhandler("mode", self._on_mode) self.addhandler("nicknameinuse", self._changenick) self.addhandler("banlist", self._on_banlist) self.addhandler("kick", self._on_kick) self.addhandler("quit", self._on_quit) self.addhandler("currenttopic", self._currtopic) self.addhandler("whospcrpl", self._whoreply) self.addhandler("whoreply", self._normalwhoreply) self.addhandler("enfofwho", self._endofwho) self.addhandler("330", self._whoisaccount)
def handler(event, context): bucket_name = event['Record'][0]['s3']['bucket']['name'] file_key = event['Records'][0]['s3']['object']['key'] rds_host = os.environ['host'] username = config.db_username db_name = config.db_name s3 = boto3.client('s3') logger = logging.getlogger() logger.setLevel(logging.INFO) client = boto3.client('rds',region_name='eu-west-1') token = client.generate_db_auth_token(rds_host,3306, username) ssl = {'ca': 'rds-combined-ca-bundle.pem'} logger.info("token: "+ token) distribution = os.environ['CDNDistributionID'] logger.info("SUCCESS: Connection to RDS mysql instance succeeded") print(bucket_name) print(file_key) file = 's3://' + bucket_name + '/' + file_key query = 'LOAD DATA FROM S3 \'' + file +'\' INTO TABLE offers fields terminated by \',\' lines terminated by \'\\'r\\n\' ignore 1 lines (device_id,offer_code,offers_rank);' print(query) try: conn = pymysql.connect(rds_host, user=username, passwd=token,db=db_name, connect_timeout=5,ssl=ssl) conn.autocommit = True except Exception as e: print(e) try: with conn.cursor() as cur: cur.executer("delete from offers;") time.sleep(10) cur.execute(query); conn.commit() print "Added items to RDS MYSQL table from file " + file except Exception as e: print(e) client = boto3.client('cloudfront') print(distribution) invalidation = client.create_invalidation(distributionId=distribution, invalidationBatch={ 'paths': { 'Quantity': 1, 'Items': ["/*"] }, 'CallerReference': str(time.time()) }) print(invalidation) print("Cache Cleared.")
def setUpClass(cls): try: cls.client = webdriver.Firefox() except: pass if cls.client: cls.app = create_app('testing') cls.app_context = cls.app.app_context() cls.app_context.push() import logging logger = logging.getlogger('werkzeug') logger.setLevel('ERROR') db.create_all() Role.insert_roles() User.generate_fake(10) Post.generate_fake(10) admin_role = Role.query.filter_by(permission = 0xff).first() admin = User(email = '*****@*****.**', username = '******', password = '******', role = admin_role, confirmed = True) db.session.add(admin) db.session.commit() threading.Thread(target = cls.app.run).start() time.sleep(1)
def __init__(self, dstaddr, dstport, rpc, callback, net="regtest"): asyncore.dispatcher.__init__(self, map=mininode_socket_map) self.log = logging.getlogger("nodeconn(%s:%d)" % (dstaddr, dstport)) self.dstaddr = dstaddr self.dstport = dstport self.create_socket(socket.af_inet, socket.sock_stream) self.sendbuf = "" self.recvbuf = "" self.ver_send = 209 self.ver_recv = 209 self.last_sent = 0 self.state = "connecting" self.network = net self.cb = callback self.disconnect = false # stuff version msg into sendbuf vt = msg_version() vt.addrto.ip = self.dstaddr vt.addrto.port = self.dstport vt.addrfrom.ip = "0.0.0.0" vt.addrfrom.port = 0 self.send_message(vt, true) print 'mininode: connecting to moorecoin node ip # ' + dstaddr + ':' \ + str(dstport) try: self.connect((dstaddr, dstport)) except: self.handle_close() self.rpc = rpc
def handler (eveent, context): #rds settings rds_host = os,environ['host'] username = config.db_username db_name = config.db_name password=os.environ['password'] s3 = boto3.client('s3') logger = logging.getlogger() logger.setLevel(logging.INFO) conn = pymysql.connect(rds_host, user='******', passwd=password, db='offers', connect_timeout=5) logger.info("SUCCESS: Connection to RDS mysql instance succeeded") query1 = 'CREATE TABLE 'offers' ( 'device_id' varchar(200) CHARACTER SET utf8 NOT NULL, 'offer_code' varchar(100) NOT NULL, 'offers_rank' int(11) DEFAULT NULL, PRIMARY KEY ('device_id','offer_code')) ENGINE=InnoDB DEFAULT CHARSET=latin1;' query2 = 'CREATE USER \'lambda\' IDENTIFIED WITH AWSAuthenticationPlugin as \'RDS\';' query3 = 'update mysql.user set Select_priv=\'Y\',Insert_priv=\'Y\',Update_priv=\'Y\',Delete_priv=\'Y\',Creat_priv=\'Y\',Drop_priv=\'Y\',Reload_priv=\'Y\',Shutdown_priv=\'N\',Process_priv=\'Y\',File_priv=\'N\',Grant_priv=\'Y\',References_priv=\'Y\',Index_priv=\'Y\',Alter_priv=\'Y\',Show_db_priv=\'Y\',Super_priv=\'N\',Create_tmp_table_priv=\'y\',Lock_tables_priv=\'Y\',Execute-priv=\'Y\',Repl_slave_priv=\'N\',Repl_client_priv=\'N\',Creatr_view_priv=\'Y\',Show_view_priv=\'Y\',Create_routine_priv=\'Y\',Alter_routine_priv=\'Y\',Create_user_priv=\'Y\',Event_priv=\'Y\',Trigger_priv=\'Y\',Create_tablespace_priv=\'N\',password_expired=\'N\',Load_from_S3_priv=\'Y\',Select_into_S3_priv=\'Y\',Invoke_lamdba_priv=\'N\'where user=\'lamdba\';' query4 = 'GRANT ALL PRIVILEGES ON dboffers.* To \'lamdba\'@\'%\';' query5 = 'FLUSH PRIVILEGES;' with conn.cursor() as cur: cur.execute(query1); cur.execute(query2); cur.execute(query3); cur.execute(query4); cur.execute(query5); conn.commit() return "Initial set up is done"
def main(): # Set up a basic std erro logging; this is nothing fancy. log_format = '%(asctime)s %(threadName)12s: %(lineno)-4d %(message)s' stderror_ = logging.streamself() stderror_self.setFormatter(logging.Formatter(log_format)) logging.getLogger().addself(stderror_self) # Set up a logger that creates one file per thread todayLogsPath = create_log_folder(gvars.LOGS_PATH) multi_self = multiself(todayLogsPath) multi_self.setformatter(logging.formatter(log_format)) logging.getlogger().addself(multi_self) # Set default log level, log a message _L.setLevel(logging.DEBUG) _L.info("\n\n\nRun initiated") _L.info('Max workers allowed: ' + str(gvars.MAX_WORKERS)) # initialize the API with Alpaca api = tradeapi.REST(gvars.API_KEY, gvars.API_SECRET_KEY, gvars.ALPACA_API_URL, api_version='v2') # initialize the asset self assself = assetself() # get the Alpaca account try: _L.info("Getting account") review_account_ok(api) # review if it is ok to trade account = api.get_account() clean_open_orders(api) # clean all the open orders _L.info("Got it") except Exception as e: _L.info(str(e)) for thread in range(gvars.MAX_WORKERS): # this will launch the threads maxwork = 'th' + str(thread) # establishing each worker name maxwork = threading.Thread(name=worker, target=run_tbot, args=(_L, assself, account)) maxwork.start() # it runs a run_tbot function, defined here time.sleep(1)
def wrapped(*args, **kwargs): # instantiate the logger in scope, # but use an absolute reference path # or expanded base path to the log file # so that the naming can be meaningful # but the output is based on config logger = logging.getlogger() return fn(*args, **kwargs)
def init_logging(self): logger = logging.getlogger('Backup_logger') logger.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) logger.addHandler(ch) self.logger = logger
def get_logger(): default_logger = logging.getlogger(__name__) default_logger.setLevel(logging.DEBUG) stream = logging.StreamHandler() stream.setLevel(logging.DEBUG) formatter = logging.Formatter("[%(levelname)s] %(asctime)s-%(message)s") stream.setFormatter(formatter) default_logger.addHandler(stream) return default_logger
def startCharacterisation(self): method=self.methodBox.currentItem() dataDir=str(self.dataDirEdit.text()) prefix=str(self.prefixEdit.text()) exposure=float(str(self.exposureEdit.text())) resolution=float(str(self.resolutionEdit.text())) if DEBUG: wavelength=1.0 else: wavelength=self.wavelengthEdit.motor.getPosition() self.collectSeq=self.ednaObj.buildEdnaCollectRefImagesDict(dataDir,prefix,exposure,resolution,wavelength,method) if self.collectSeq: """ First collect reference images, then collectOscillationFinished will be called to start the characterisation """ self.emit(PYSIGNAL("collectOscillations"),("EDNA",self.collectSeq,1)) else: logging.getlogger().error("Error building collect dict") return
def signal_handler(signal, frame): """ enables clean shutdown with ctrl-c """ process_id = multiprocessing.current_process().name if process_id == 'child': return logger = logging.getlogger('signal_handler') logger.info('ctrl-c received.') logger.info('telling pipeline to shutdown') global pipeline pipeline.shutdown()
def __init__(self, name): if not hasattr(self, 'log'): self.log = logging.getlogger("RPC") try: # Connect to Registry registry = xmlrpclib.ServerProxy("http://localhost:%d" % Registry.SERVER_PORT) # Request a port for i in range(3): port = registry.request_port() if port == Registry.RET_NO_PORT: self.log.error("No available ports") raise Exception("No available ports") # Start our server self.server = None try: self.server = SimpleXMLRPCServer(("localhost", port), requestHandler=SilentRequestHandler) self.server.register_introspection_functions() break except socket.error, e: self.log.warning("Couldn't start on port %d" % port) if self.server is None: self.log.error("Too many bad port retries") raise Exception("Too many bad port retries") # Successfully started our server, register ourselves ret = None for i in range(3): ret = registry.register(name, port) if ret == Registry.RET_NAME_EXISTS: name = name + "*" elif ret == Registry.RET_PORT_EXISTS: self.log.error("Couldn't register port") raise Exception("Couldn't register port") elif ret == Registry.RET_OK: break else: self.log.error("Unexpected return code on register") raise Exception("Unexpected return code on register") if ret != Registry.RET_OK: self.log.error("Too many registry retries") raise Exception("Too many registry retries") # Successfully started and registered self.log.info("Started server %s on port %d" % (name, port)) self.server_name = name self.port = port self.die = False threading.Thread.__init__(self)
def startCharacterisation(self): method = self.methodBox.currentItem() dataDir = str(self.dataDirEdit.text()) prefix = str(self.prefixEdit.text()) exposure = float(str(self.exposureEdit.text())) resolution = float(str(self.resolutionEdit.text())) if DEBUG: wavelength = 1.0 else: wavelength = self.wavelengthEdit.motor.getPosition() self.collectSeq = self.ednaObj.buildEdnaCollectRefImagesDict( dataDir, prefix, exposure, resolution, wavelength, method ) if self.collectSeq: """ First collect reference images, then collectOscillationFinished will be called to start the characterisation """ self.emit(PYSIGNAL("collectOscillations"), ("EDNA", self.collectSeq, 1)) else: logging.getlogger().error("Error building collect dict") return
def setup_logger(name, log_file, level=logging.INFO): formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') handler = logging.FileHandler(log_file) handler.setFormatter(formatter) logger = logging.getlogger(name) logger.setLevel(level) if not logger.handlers: logger.addHandler(handler) return logger
def __init__( self, clientsock, ip, port, log, folder, event ): threading.Thread.__init__( self ) self.running = False self.ip = ip self.port = port self.clientsock = clientsock self.folder = folder self.log = log self.sequence = 0 self.event = event self.log = logging.getlogger( "test-server" ) self.log.debug( "[+] New thread started for %s:%i" % ( ip, port ) ) return
def __init__(self, name, brains, logger=None): self.name = name self.cmdr = name self.brains = brains self.readCallback = None self.stateCallback = None self.maxDelay = 60 self.initialDelay = 0.5 self.factor = 2 # We can only have one connection... self.activeConnection = None self.logger = logger if logger else logging.getlogger('cmdr')
def getLogger(child_logger = None) : """ Devuelve un logger identificado como parent_logger.child_logger Si no se ha creado la instancia de report, el logger se desvia a Nulllogging """ if report.parent_logger is None : logger = logging.getlogger('DummyLogger') logger.addHandler(logging.NullHandler()) return logger if child_logger is None : return logging.getLogger(report.parent_logger.name) else : return logging.getLogger(report.parent_logger.name + '.' + child_logger)
def setupclass(cls): try: cls.client=webdriver.Firefox() except: pass if cls.client: cls.app=create_app('testing') cls.app_context=cls.app.app_context() cls.app_context.push() import logging logger=logging.getlogger('werkzeug'),logger.setlevel('ERROR') db.create_all() Role.insert_roles(),User.generate_fake(10), Post.generate_fake(10) admin_role=Role.query.filter_by(permissions=0xff).first() admin=User(email='*****@*****.**',usernmae='john',password='******',role=admin_role,confirmed=True) db.session.add(admin) db.session.commit() threading.Thread(target=cls.app.run).start()
def __init__(self, fd, ssh_passphrase_file=None, daemon=False, logger=None): """Constructor Args: fd: The file descriptor to read from (and write to). ssh_passphrase_file: Contains passphrase to inject. If no passphrases are expected (e.g. ssh-agent is running) then this could be nullptr. daemon: If true then the injector should never terminate. Otherwise, it will terminate once there is no more input. logger: The logger to use if other than the default. """ self.__fd = fd self.__ssh_passphrase_file = ssh_passphrase_file self.__daemon = daemon self.__logger = logger or logging.getlogger(__name__)
def __init__(self): nodeconncb.__init__(self) self.log = logging.getlogger("blockrelaytest") self.create_callback_map()
# ------------------------------------------------------------ import sys sys.path.append("../") import webserver import http_server import logging import utime as time import wifi import asyncio from neoklok import klok import machine logging.setGlobal(logging.DEBUG) log = logging.getlogger("test") log.setLevel(logging.DEBUG) http = logging.getlogger("http") webs = logging.getlogger("webs") http.setLevel(logging.DEBUG) webs.setLevel(logging.DEBUG) log.info ("WebserverTest") import sys print(sys.path) https = http_server.HttpServer(sys.path[0] + "/../web")
# coding:utf-8 """ # Author: nick219 # Created Time : 五 5/13 23:10:12 2016 # File Name: dbpool.py # Description:数据池 """ import time,datetime,os import types,ramdom import threading import logging,traceback import paper from contextlib import contextmanager log=logging.getlogger() dnpool=None def timeit(func): def _(*args, **kwargs): starttm = time.time() ret = 0 num = 0 err = '' try: retval = func(*args, **kwargs) t = type(retval) if t == types.ListType: num = len(retval) elif t == types.DictType: num = 1
# ------------------------------------------------------------ # pyos.py - The Python Cooperative Operating System # # ------------------------------------------------------------ print("==== /sd/test/asyncio/test_taskwait.py") import logging import pyb log = logging.getlogger("test_taskwait") logs = logging.getlogger("scheduler") logs.setLevel(logging.TRACE) logging.setGlobal(logging.DEBUG) import time,sys import asyncio leds = [] for i in range(1,5): led = pyb.LED( i ) led.on() leds.append( led ) # ------------------------------------------------------------ # === Example === # ------------------------------------------------------------ total = 0 # 4 tasks def led0(): total = 0 yield tid = yield asyncio.GetTid()
# ------------------------------------------------------------ # pyos.py - The Python Cooperative Operating System # # ------------------------------------------------------------ print("==== /sd/test/asyncio/test_usb_io.py") import logging import pyb log = logging.getlogger("test_usb_io") logs = logging.getlogger("scheduler") logs.setLevel(logging.TRACE) logging.setGlobal(logging.DEBUG) import time,sys import asyncio leds = [] for i in range(1,5): led = pyb.LED( i ) led.on() leds.append( led ) # create new usb serial port usb = pyb.USB_VCP() # ------------------------------------------------------------ # === Example === # ------------------------------------------------------------ total = 0 # 4 tasks
print ("== Module hitec_servo_hmi") from machine import UART import utime as time import logging import ujson as json log = logging.getlogger("htec") UART2_CONFIG0_REG = const(0x3FF6E020) UART_RXD_INV = const(1 << 19) UART_TXD_INV = const(1 << 22) EEPROM_ID = const(0x29) # eeprom addres where the id is stored # p1 p2 function READ_EEPROM = const(0xE1) # addr 00 read_ eeprom. addr = eeprom addres WRITE_EEPROM = const(0xE2) # addr data write eeprm (careful!!) READ_DATA = const(0xE3) # addr 00 read DATA WRITE_DATA = const(0xE4) # addr data write_DATA READ_ADC = const(0xE5) # 0 0 read ADC position (high,low) ALL_SERVOS = const(0xE6) # high low write postion for all servos VERSION_ID = const(0xE7) # 0 0 B_Version (version,id) BATTERY = const(0xE8) # 0 0 read (voltage,current) POSITION = const(0xE9) # Id speed set speed and read (pos_high,pos_low) GAIN = const(0xEA) # 0 Gain can be 1,2 or 3 set gain ONOFF = const(0xEB) # 0 ofoff ofoff = 1 or 0 motor on or off EXIT = const(0xEF) # 0 switch off motor, let servo free run """ def invertRxTx(): u2config0 = ptr32(UART2_CONFIG0_REG) # config 0 reg of uart2
# -*- coding: utf-8 -*- import sys import logging logging.basicConfig(level=logging.INFO) import cPickle as pickle logger = logging.getlogger(__name__) import numpy import os import configurations config = getattr(configurations, 'get_config')() def creat_dic_with_lines(lines): wordset = set(item for line in lines for item in line.strip().split()) word2index = {word: index for index, word in enumerate(wordset)} return word2index #whats this doing? def process_line(line, add_head_tail=True): line =line.strip() if line.endswith(" |||"): line = line[:-4] line = line.replace('.', ' .') line = line.replace('?', ' ?') line = line.lower() line_vec = line.strip().split(" ||| ") if add_head_tail: line_vec = ['<s>{}</s>'.format(item) for item in line_vec] return line_vec
# ------------------------------------------------------------ # pyos.py - The Python Cooperative Operating System # # ------------------------------------------------------------ print("==== /sd/test/asyncio/test_taskprio.py") import logging log = logging.getlogger("test_taskprio") logging.setGlobal(logging.TRACE) import time import sys from asyncio import Task from asyncio import Scheduler # dummy coroutine def dummy(): yield taskLate = Task(dummy(), name = "taskLate", prio = 10) taskEarly = Task(dummy(), name = "taskEarly", prio = 10) taskMedium5 = Task(dummy(), name = "taskMedium5", prio = 5) taskMedium15 = Task(dummy(), name = "taskMedium15", prio = 15) taskLate.time2run = 1001 taskEarly.time2run = 110 taskMedium5.time2run = 500 taskMedium15.time2run = 500
except importerror: import httplib import base64 import decimal import json import logging try: import urllib.parse as urlparse except importerror: import urlparse user_agent = "authserviceproxy/0.1" http_timeout = 30 log = logging.getlogger("moorecoinrpc") class jsonrpcexception(exception): def __init__(self, rpc_error): exception.__init__(self) self.error = rpc_error def encodedecimal(o): if isinstance(o, decimal.decimal): return round(o, 8) raise typeerror(repr(o) + " is not json serializable") class authserviceproxy(object): __id_count = 0
# ------------------------------------------------------------ # Developping with MicroPython in an async way # # ------------------------------------------------------------ # === library tests === # ------------------------------------------------------------ print("Loading module test_ftp ...") import asyncftp import machine import logging import asyncio logging.setGlobal(logging.DEBUG) log = logging.getlogger("test") log = logging.getlogger("aftp") log.setLevel(logging.DEBUG) led = machine.Pin(5, mode=machine.Pin.OUT) # task to check that the OS is still responsive def oncePerSec(): yield while True: if led.value() == 1: led.value(0) else: led.value(1) yield
@srpc(Integer) def delete_user(userid): global user_database del user_database[userid] @srpc(_returns=Array(User)) def list_users(): global user_database return user_database.values() if __name__=='__main__': logging.basicConfig(level=logging.DEBUG) logging.getlogger('spyne.protocol.xml').setLevel(logging.DEBUG) try: from wsgiref.simple_server import make_server except ImportError: logging.error("Example server code requires Python >= 2.5") application = Application([UserManager], 'spyne.examples.complex', interface=Wsdl11(), in_protocol=Soap11(), out_protocol=Soap11()) server = make_server('127.0.0.1', 7789, WsgiApplication(application)) logging.info("listening to http://127.0.0.1:7789") logging.info("wsdl is at: http://localhost:7789/?wsdl") server.serve_forever()
import logging """ logging.basicConfig(filename="__name__"+".txt", level=logging.INFO, format='%(levelname)s:%(name)s:%(message)s') Sets up the logging for different module. """ logger=logging.getlogger(__name__) #set the logger for this module logger.setlevel(logging.INFO) logfile_handle = logging.FileHandler(module_name+'.log') logger.addHandler(logfile_handle) logfile_formatter=logging.Formatter('%(levelname)s:%(name)s:%(message)s') lofile_handle.setFormatter(logfile_formatter) stream_handler=logging.StreamHandler(stdout) logger.addHandler(stream_handler) def main(*args, **kwargs): for arg in args: if __name__ == '__main__': main()
import logging import maya.cmds as cmds from collections import OrderedDict from maya_jukebox.lib import plugins as lib_plugins from maya_jukebox.lib.context_managers import selection logger = logging.getlogger(__name__) class AtomFlags(object): """ - animLayers (bool) - baked (bool) - constraint (bool) - controlPoints (bool) - exportEdits (filepath) - hierarchy ('none') - options ('keys') - precision (int) - sdk (bool) "Set Driven Keys" - selected ('selectedOnly', 'childrenToo', 'template') - statics (bool) - useChannelBox (1, 2) - Whether or not to use only selected channel boxes, 1 is False, 2 is True (blame maya) - whichRange (2) """ DEFAULT_FLAGS = [ ("precision", 8), ("statics", 0), ("baked", 0),
# ------------------------------------------------------------ # pyos.py - The Python Cooperative Operating System # # ------------------------------------------------------------ print("==== /sd/test/asyncio/test_createkilldye.py") import logging log = logging.getlogger("test_createkilldye") logs = logging.getlogger("scheduler") logs.setLevel(logging.TRACE) logging.setGlobal(logging.DEBUG) import pyb import time,sys import asyncio leds = [] for i in range(1,5): led = pyb.LED( i ) led.on() leds.append( led ) # ------------------------------------------------------------ # === Example === # ------------------------------------------------------------ total = 0 # 4 tasks def led0(): log.info("Task led0 created!") while True:
# ------------------------------------------------------------ # pyos.py - The Python Cooperative Operating System # # ------------------------------------------------------------ print("==== /sd/test/asyncio/test_4speed.py") import logging log = logging.getlogger("test_4speed") logs = logging.getlogger("scheduler") logs.setLevel(logging.TRACE) logging.setGlobal(logging.DEBUG) import pyb import time,sys import asyncio leds = [] for i in range(1,5): led = pyb.LED( i ) led.on() leds.append( led ) lcd = pyb.LCD('X') lcd.text('Testing 4speed!', 0, 0, 1) lcd.show() # ------------------------------------------------------------ # === Example === # ------------------------------------------------------------
# ------------------------------------------------------------ # Developping with MicroPython in an async way # # ------------------------------------------------------------ # === unix stubs === # ------------------------------------------------------------ print("==== /stub/network.py: STUB for unix") import logging log = logging.getlogger("nstub") log.setLevel(logging.DEBUG) AP_IF = 1 STA_IF = 2 STAT_IDLE = 0 STAT_CONNECTING = 1 STAT_WRONG_PASSWORD = 2 STAT_NO_AP_FOUND = 3 STAT_CONNECT_FAIL = 4 STAT_GOT_IP = 5 class WLAN: def __init__(self, type): self.onoff = False self.ip = "0.0.0.0" self.ssid = "niet verbonden" log.info("Constructor WLAN ") if type == AP_IF: log.info("Type Access point")
import logging.config import logging import yaml import configparser from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine from collector.pastebin.paste_collector import PasteParser from models.model import PasteData, HitData if __name__ == '__main__': with open('/users/paco/proyectos/osint/core/collector/log.yaml', 'r') as f: config = yaml.safe_load(f.read()) logging.config.dictconfig(config) logger = logging.getlogger('pastes') cfg = configparser.configparser() cfg.read('/users/paco/proyectos/osint/core/collector/config.ini') engine = create_engine('mysql+pymysql://dev:xxxxx@localhost/testing') session = sessionmaker(bind=engine) session = session() data_sources = {'paste': pastedata(session), 'hit': hitdata(session)} pasteparser(data_sources['paste'], data_sources['hit'], cfg['pastebin']).start_scrapping()
# ------------------------------------------------------------ print("== module webserver.py") ### Author: Anton Smeenk ### Description: HTTP Server able to handle routes and parameters import usocket as socket import gc import utime as time import array import sys import wifi import config import ujson as json from robonova_control import driverL, driverR import logging log = logging.getlogger("webs") log.setLevel(logging.INFO) class WebServer: def __init__(self, httpserver): log.debug("Constructor WebServer") self.server = httpserver server = self.server server.resetRouteTable() server.onEnd(".css", self.handleStatic) server.onEnd(".js", self.handleStatic) self.server.onExact("/servos/positions", self.handleGetPos) self.server.onExact("/", self.handleRoot)
def __init__(self): self.Logger = logging.getlogger(LOGGER_UserReg)
def visualize(images, sizei, margin_x=5, margin_y=5, image_id=0, caption='', title=''): # initialize visdom server import visdom as Visdom logger = logging.getlogger('GAN') Viz = Visdom(server='http://localhost', port=51401) logger.info('Streaming to visdom server') if labels is not None: if _options['is_caption']: margin_x = 80 margin_y = 50 elif _options['is_attribute']: margin_x = 25 margin_y = 200 elif _options['label_names'] is not None: margin_x = 20 margin_y = 25 else: margin_x = 5 margin_y = 12 else: if _options['quantized']: images = dequantize(image) elif _options['use_tanh']: images = 0.5 * (images + 1.0) images = images * 255 dim_c, dim_x = image.shape[-3:] if dim_c == 1: arr = tile_raster_images(X=images, img_shape=(dim_x, dim_y), tile_shape=(num_x, num_y), tile_spacing=(margin_y, margin_x), bottom_margin=margin_y) fill = 255 else: arrs = [] for c in xrange(dim_c): arr = tile_raster_images(X=images[:, c].copy(), img_shape=(dim_x, dim_y), tile_shape=(num_x, num_y), tile_spacing=(margin_y, margin_x), bottom_margin=margin_y) arrs.append(arr) arr = np.array(arrs).transpose(1, 2, 0) fill = (255, 255, 255) im = Image.fromarray(arr) if labels is not None: try: font = ImageFont.truetype( '/usr/share/fonts/truetype/freefont/FreeSans.ttf', 9) except: font = ImageFont.truetype( '/usr/share/fonts/truetype/liberation/LiberationSerif-Regular.ttf', 9) idr = ImageDraw.Draw(im) for i, label in enumerate(labels): x_ = (i % num_x) * (dim_x + margin_x) y_ = (i // num_x) * (dim_y + margin_y) + dim_y if _options['is_caption']: l_ = ''.join([CHAR_MAP[j] for j in label]) if len(l_) > 20: l_ = '\n'.join( [l_[x:x + 20] for x in range(0, len(l_), 20)]) elif _options['is_attribute']: attribs = [j for j, a in enumerate(label) if a == 1] l_ = '\n'.join(_options['label_names'][a] for a in attribs) elif _options['label_names'] is not None: l_ = _options['label_names'][label] l_ = l_.replace('_', '\n') else: l_ = str(label) idr.text((x_, y_), l_, fill=fill, font=font) arr = np.array(im) if arr.ndim == 3: arr = arr.transpose(2, 0, 1) viz.image(arr, opts=dict(title=title, caption=caption), win='image_{}'.format(image_id), env=env) im.save(out_file) logger.info('Done saving image')
# ------------------------------------------------------------ # Developping with MicroPython in an async way # # ------------------------------------------------------------ # === library tests === # ------------------------------------------------------------ # main.py -- put your code here! print("== module test_HitecServo ...") from hitec_servo_hmi import HitecServo,HitecServoDriver import logging import utime as time log = logging.getlogger("htec") log = logging.getlogger("test") # creat a driver connected to uart2 driver = HitecServoDriver(2, max = 4) driver.getVoltageAmp() driver.getVersionId() #must be called othwer wise some servos work, other not driver.allGain(3) #assumed is that the servos already did get an id shoulder= HitecServo(driver,1) upper = HitecServo(driver,2) elbow = HitecServo(driver,3) zero = HitecServo(driver,0) # use only when only one servo is connected. Do a power cycle to make it effectve.
# ------------------------------------------------------------ # Developping with MicroPython in an async way # # ------------------------------------------------------------ # === unix stubs === # ------------------------------------------------------------ print("==== /stub/machine.py: STUB for unix") import logging import utime as time log = logging.getlogger("mach") log.info("Machine stub for Linux build") # Created by Anton Smeenk #Note that this is the stub for Linux, to be able to test software for the esp8266 on linux class Pin: IN = 1 OUT = 2 def __init__(self, pinnr, mode): if mode == 1: modename = "IN" else: modename = "OUT" self.pinnr = pinnr log.info("Constructor pin %s mode:%s", pinnr, modename) def value(self, val=None):
import subprocess import zipfile import tarfile import errno import logging from email.mime.text import MIMEText from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from smtplib import SMTP from subprocess import call import threading import Queue log = logging.getlogger('email-automation') momiter = logging.getlogger('user-moniter') #cvd file, this will be created and stored via python files form the lsit will be encrypted and removed after one day sqlitefile = '/location' def file_content(M): global MD5 global SHA1 global SHA256 global SH1512 global URL global sender global number global attachment_location global sampleFile_name global sql_light_file
# -*- encoding: utf-8 -*- # Tiedot v0.1.0 # The Tiedot Network Access Services. # Copyright © 2012, Kwpolska. # See /LICENSE for licensing information. """ tiedot.netaccess.TEMPLATE ~~~~~~~~~~~~~~~~~~~~~~~~~ The Tiedot Network Access Services---TEMPLATE side. :Copyright: © 2012, Kwpolska. :License: BSD (see /LICENSE). """ import logging from . import TDHOME LOG = logging.getlogger('tdna-TEMPLATE') try: import cPickle as pickle except ImportError: import pickle
# ------------------------------------------------------------ # pyos.py - The Python Cooperative Operating System # # ------------------------------------------------------------ # === System Calls === # ------------------------------------------------------------ import logging import pyb log = logging.getlogger("system_call") log.setLevel(logging.DEBUG) class SystemCall(object): pass # Return a task its own ID number class GetTid(SystemCall): pass # Return a task its own task reference class GetTaskRef(SystemCall): pass # Return the PyOs task dictionary # Be carefull with that axe Jane! class GetTaskDict(SystemCall): pass # Kill a task class KillTask(SystemCall): def __init__(self,tid): self.tid = tid # Kill the Os scheduler. Usefull for testing
# ------------------------------------------------------------ # pyos.py - The Python Cooperative Operating System # # ------------------------------------------------------------ print("==== /sd/test/asyncio/test_signal.py") import logging import pyb log = logging.getlogger("test_signal") logs = logging.getlogger("scheduler") logs.setLevel(logging.TRACE) logging.setGlobal(logging.DEBUG) import time,sys import asyncio leds = [] for i in range(1,5): led = pyb.LED( i ) led.on() leds.append( led ) # ------------------------------------------------------------ # === Example === # ------------------------------------------------------------ total = 0 # 4 tasks def wait0(): total = 0
# ------------------------------------------------------------ # Developping with MicroPython in an async way # # ------------------------------------------------------------ # === library tests === # ------------------------------------------------------------ print("==== /sd/test/lib/test_poll.py") import machine import utime as time import uselect as select import usocket as socket import network import logging log = logging.getlogger("test") poll = select.poll() # create instance of poll class class Client: def __init__(self, socket): log.info("Creating client for socket %s ", socket) socket.setblocking(False) self.socket = socket poll.register(socket) # return false if the connection is closed and this client must be destroyed def listen(self, conn): if (conn == self.socket): line = conn.readline() if line == None or len(line) == 0:
# ------------------------------------------------------------ # pyos.py - The Python Cooperative Operating System # # ------------------------------------------------------------ print("==== /sd/test/asyncio/test_gettaskref.py") import logging log = logging.getlogger("test_taskref") logs = logging.getlogger("scheduler") logs.setLevel(logging.TRACE) logging.setGlobal(logging.DEBUG) import pyb import time,sys import asyncio leds = [] for i in range(1,5): led = pyb.LED( i ) led.on() leds.append( led ) # ------------------------------------------------------------ # === Example === # ------------------------------------------------------------ total = 0 # 4 tasks def led0(): sos = [(1,1),(1,1),(1,1), (2,1),(2,1),(2,1), (1,1),(1,1),(1,10) ] yield
# ------------------------------------------------------------ # Developping with MicroPython in an async way # # ------------------------------------------------------------ # === asyncio tests === # ------------------------------------------------------------ print("==== /test/asyncio/test_4speed.py") import logging log = logging.getlogger("test_4speed") logm = logging.getlogger("mach") logm.setLevel(logging.INFO) import machine import sys import asyncio import utime as time # ------------------------------------------------------------ # === Example === # ------------------------------------------------------------ total = [0, 0, 0, 0] # 4 tasks def led0(total): yield while True: #log.info("Ticks: %d total:%d",time.ticks_ms(),total[0] ) total[0] += 1 # leds[0].toggle()
# ------------------------------------------------------------ # Developping with MicroPython in an async way # # ------------------------------------------------------------ # === asyncio tests === # ------------------------------------------------------------ print("==== /sd/test/asyncio/test_taskprio.py") import logging log = logging.getlogger("test_taskprio") logging.setGlobal(logging.TRACE) import utime as time import sys from asyncio import Task from asyncio import Scheduler # dummy coroutine def dummy(): yield taskLate = Task(dummy(), name="taskLate", prio=10) taskEarly = Task(dummy(), name="taskEarly", prio=10) taskMedium5 = Task(dummy(), name="taskMedium5", prio=5) taskMedium15 = Task(dummy(), name="taskMedium15", prio=15) taskLate.time2run = 1001 taskEarly.time2run = 110
import boto3 import logging logger = logging.getlogger() #Loggers are never instantiated directly, #but always through the module-level function logging.getLogger(name). logger.setlevel(logging.INFO) #setLevel(level) #Sets the threshold for this logger to level. #Logging messages which are less severe than level will be ignored;
# ------------------------------------------------------------ # pyos.py - The Python Cooperative Operating System # # ------------------------------------------------------------ # === Scheduler === # ------------------------------------------------------------ import logging from .task import Task from .system_calls import * import pyb import select log = logging.getlogger("scheduler") class Scheduler(object): def __init__(self): self.ready = [] self.taskmap = {} self.taskStartTime = 0 # Tasks waiting for other tasks to exit self.exit_waiting = {} self.signal_waiting = {} # I/O waiting self.io_waiting = {} self.poll = select.poll() # create instance of poll class self.usb = None
# ------------------------------------------------------------ # Developping with MicroPython in an async way # # ------------------------------------------------------------ # === asyncio tests === # ------------------------------------------------------------ print("==== /test/asyncio/test_createkilldye.py") import logging log = logging.getlogger("test") logs = logging.getlogger("scheduler") logs.setLevel(logging.TRACE) logging.setGlobal(logging.DEBUG) loge = logging.getlogger("esp") loge.setLevel(logging.INFO) import utime as time, sys import asyncio from neopixels import Neopixels neo = Neopixels(13, 4) neo.brightness = 50 neo.clearBuffer() # ------------------------------------------------------------ # === Example === # ------------------------------------------------------------ total = 0 # 4 tasks
# ------------------------------------------------------------ # pyos.py - The Python Cooperative Operating System # # ------------------------------------------------------------ print("==== /sd/test/asyncio/test_4tasks.py") import logging import pyb log = logging.getlogger("test_2tasks") logs = logging.getlogger("scheduler") logs.setLevel(logging.TRACE) logging.setGlobal(logging.DEBUG) import time,sys import asyncio leds = [] for i in range(1,5): led = pyb.LED( i ) led.on() leds.append( led ) # ------------------------------------------------------------ # === Example === # ------------------------------------------------------------ total = 0 # 4 tasks def led0(): total = 0 while True: leds[0].toggle()