Esempio n. 1
0
def main_debug(displaying):
    video_file = os.path.join(os.path.dirname(__file__), "video/staircase.mp4")

    vid_stream = VideoStream(video_file, interval=0.03)
    vid_stream.start()

    if debug:
        import ptvsd
        ptvsd.enable_attach(('0.0.0.0', 56781))
        ptvsd.wait_for_attach()
        ptvsd.break_into_debugger()

    while True:
        _, frame = vid_stream.get_frame_with_id()
        detections = detector.detect(frame)
        #logging.info(detections)

        if not displaying:
            logging.info(detections)
            continue

        frame = display(frame, detections)
        # # check to see if the output frame should be displayed to our
        # # screen
        cv2.imshow("Frame", frame)

        key = cv2.waitKey(1) & 0xFF

        if key == ord('q') or key == 27:
            break

    cv2.destroyAllWindows()
Esempio n. 2
0
def _bp(wait=True):
    if not ptvsd.is_attached():
        if _attach(wait):
            ptvsd.break_into_debugger()
    else:
        if need_to_debug():
            ptvsd.break_into_debugger()
Esempio n. 3
0
 def code_to_debug():
     import backchannel
     from dbgimporter import import_and_enable_debugger
     import_and_enable_debugger()
     import ptvsd
     ptvsd.break_into_debugger()
     backchannel.write_json('done')
Esempio n. 4
0
 def code_to_debug():
     # NOTE: These tests verify break_into_debugger for launch
     # and attach cases. For attach this is always after wait_for_attach
     from dbgimporter import import_and_enable_debugger
     import_and_enable_debugger()
     import ptvsd
     ptvsd.break_into_debugger()
     print('break here')
Esempio n. 5
0
 def code_to_debug():
     from dbgimporter import import_and_enable_debugger
     import_and_enable_debugger()
     import ptvsd
     # Since Unicode variable name is a SyntaxError at parse time in Python 2,
     # this needs to do a roundabout way of setting it to avoid parse issues.
     globals()[u'\u16A0'] = 123
     ptvsd.break_into_debugger()
     print('break')
def module_twin_callback(update_state, payload, user_context):
    global TEMPERATURE_THRESHOLD
    ptvsd.break_into_debugger()

    properties_obj = json.loads(payload)

    if DESIRED_PROPERTY_KEY in properties_obj:
        properties_obj = properties_obj[DESIRED_PROPERTY_KEY]

    if TEMP_THRESHOLD_PROPERTY_NAME in properties_obj:
        TEMPERATURE_THRESHOLD = properties_obj[TEMP_THRESHOLD_PROPERTY_NAME]
Esempio n. 7
0
def main():
    count = 0
    while count < 50:
        print(count)
        time.sleep(0.1)
        if os.getenv('PTVSD_BREAK_INTO_DEBUGGER', None) is not None:
            ptvsd.break_into_debugger()
        count += 1
    path = os.getenv('PTVSD_TARGET_FILE', None)
    if path is not None:
        with open(path, 'a') as f:
            print('HERE :)', file=f)
Esempio n. 8
0
def start_app():

    # set protocol to 1.1 so we keep the connection open
    WSGIRequestHandler.protocol_version = "HTTP/1.1"

    if debug:
        import ptvsd
        ptvsd.enable_attach(('0.0.0.0', 56781))
        ptvsd.wait_for_attach()
        ptvsd.break_into_debugger()

    app.run(debug=False, host="detector", port=5010)
Esempio n. 9
0
def main():
    if loopy:
        count = 0
        while count < 50:
            print('one')
            ptvsd.break_into_debugger()
            time.sleep(0.1)
            print('two')
            count += 1
    else:
        print('one')
        ptvsd.break_into_debugger()
        print('two')
Esempio n. 10
0
 def code_to_debug():
     import time
     import ptvsd
     import backchannel
     from dbgimporter import import_and_enable_debugger
     import_and_enable_debugger()
     ptvsd.break_into_debugger()
     print('first')
     backchannel.write_json('continued')
     for _ in range(0, 20):
         time.sleep(0.1)
         ptvsd.break_into_debugger()
         print('second')
Esempio n. 11
0
def module_twin_callback(update_state, payload, user_context):
    ptvsd.break_into_debugger()
    global TWIN_CALLBACKS
    global TEMPERATURE_THRESHOLD
    print(
        "\nTwin callback called with:\nupdateStatus = %s\npayload = %s\ncontext = %s"
        % (update_state, payload, user_context))
    data = json.loads(payload)
    if "desired" in data and "TemperatureThreshold" in data["desired"]:
        TEMPERATURE_THRESHOLD = data["desired"]["TemperatureThreshold"]
    if "TemperatureThreshold" in data:
        TEMPERATURE_THRESHOLD = data["TemperatureThreshold"]
    TWIN_CALLBACKS += 1
    print("Total calls confirmed: %d\n" % TWIN_CALLBACKS)
Esempio n. 12
0
def main():
    count = 0
    while count < 50:
        if os.getenv('PTVSD_WAIT_FOR_ATTACH', None) is not None:
            print('waiting for attach')
            ptvsd.wait_for_attach()
        elif os.getenv('PTVSD_IS_ATTACHED', None) is not None:
            print('checking is attached')
            while not ptvsd.is_attached():
                time.sleep(0.1)
        else:
            pass
        print('one')
        ptvsd.break_into_debugger()
        time.sleep(0.5)
        print('two')
        count += 1
    def SelectPair(self, algorithm, date):
        '''Selects the pair (two stocks) with the highest alpha'''
        dictionary = dict()
        ptvsd.break_into_debugger()
        benchmark = self._getReturns(algorithm, self.benchmark)
        ones = np.ones(len(benchmark))

        for symbol in self.symbols:
            prices = self._getReturns(algorithm, symbol)
            if prices is None: continue
            A = np.vstack([prices, ones]).T

            # Calculate the Least-Square fitting to the returns of a given symbol and the benchmark
            ols = np.linalg.lstsq(A, benchmark)[0]
            dictionary[symbol] = ols[1]

        # Returns the top 2 highest alphas
        orderedDictionary = sorted(dictionary.items(), key= lambda x: x[1], reverse=True)
        return [x[0] for x in orderedDictionary[:2]]
Esempio n. 14
0
def receive_message_callback(message, hubManager):
    ptvsd.break_into_debugger()
    global RECEIVE_CALLBACKS
    global TEMPERATURE_THRESHOLD
    message_buffer = message.get_bytearray()
    size = len(message_buffer)
    message_text = message_buffer[:size].decode('utf-8')
    print("    Data: <<<%s>>> & Size=%d" % (message_text, size))
    map_properties = message.properties()
    key_value_pair = map_properties.get_internals()
    print("    Properties: %s" % key_value_pair)
    RECEIVE_CALLBACKS += 1
    print("    Total calls received: %d" % RECEIVE_CALLBACKS)
    data = json.loads(message_text)
    if "machine" in data and "temperature" in data["machine"] and data[
            "machine"]["temperature"] > TEMPERATURE_THRESHOLD:
        map_properties.add("MessageType", "Alert")
        print("Machine temperature %s exceeds threshold %s" %
              (data["machine"]["temperature"], TEMPERATURE_THRESHOLD))
    hubManager.forward_event_to_output("output1", message, 0)
    return IoTHubMessageDispositionResult.ACCEPTED
Esempio n. 15
0
def main():
    """Run administrative tasks."""
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangotest.settings")

    from django.conf import settings

    if settings.DEBUG:
        import ptvsd

        ptvsd.enable_attach(address=("0.0.0.0", 5678))
        ptvsd.wait_for_attach()
        ptvsd.break_into_debugger()
        print("Debugger Attached!")

    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?") from exc
    execute_from_command_line(sys.argv)
Esempio n. 16
0
def main(protocol):
    try:
        ptvsd.break_into_debugger()
        print("\nPython %s\n" % sys.version)
        print("IoT Hub Client for Python")

        hub_manager = HubManager(protocol)

        print("Starting the IoT Hub Python sample using protocol %s..." %
              hub_manager.client_protocol)
        print(
            "The sample is now waiting for messages and will indefinitely.  Press Ctrl-C to exit. "
        )

        while True:
            time.sleep(1)

    except IoTHubError as iothub_error:
        print("Unexpected error %s from IoTHub" % iothub_error)
        return
    except KeyboardInterrupt:
        print("IoTHubModuleClient sample stopped")
Esempio n. 17
0
def main(
        videoPath ="",
        verbose = False,
        videoWidth = 0,
        videoHeight = 0,
        fontScale = 1.0,
        inference = True,
        confidenceLevel = 0.8
        ):

    global hubManager
    global videoCapture

    try:
        print("\nPython %s\n" % sys.version )
        print("Yolo Capture Azure IoT Edge Module. Press Ctrl-C to exit." )

        with VideoCapture(videoPath, 
                         verbose,
                         videoWidth,
                         videoHeight,
                         fontScale,
                         inference,
                         confidenceLevel) as videoCapture:
            if __myDebug__:
                ptvsd.break_into_debugger()
        
            try:
                hubManager = HubManager(10000, IoTHubTransportProvider.MQTT, False)
                AppState.init(hubManager)
            except IoTHubError as iothub_error:
                print("Unexpected error %s from IoTHub" % iothub_error )
                return

            videoCapture.start()

    except KeyboardInterrupt:
        print("Camera capture module stopped" )
Esempio n. 18
0
def init(*argv, **kwargs):
    """Initialize code_aster as `DEBUT`/`POURSUITE` command does + command
    line options.

    If the code_aster study is embedded under another Python program, the
    "--slave" option may be useful to catch exceptions (even *TimeLimitError*)
    and **try** not to exit the Python interpreter.

    Arguments:
        argv (list): List of command line arguments.
        kwargs (dict): Keywords arguments passed to 'DEBUT'/'POURSUITE' +
            'debug' same as -g/--debug,
            'noargv' to ignore previously passed arguments.
    """
    if kwargs.get('noargv'):
        ExecutionParameter().set_argv([])
    kwargs.pop('noargv', None)
    if not ExecutionStarter.init(argv):
        return

    if kwargs.get('debug'):
        ExecutionParameter().enable(Options.Debug)
    kwargs.pop('debug', None)

    if kwargs.get('ptvsd') and HAS_PTVSD:
        print('Waiting for debugger attach...'),
        ptvsd.enable_attach(address=('127.0.0.1', kwargs['ptvsd']))
        ptvsd.wait_for_attach()
        ptvsd.break_into_debugger()
        # add 10 hours for debugging
        tpmax = ExecutionParameter().get_option("tpmax")
        ExecutionParameter().set_option("tpmax", tpmax + 36000)
    kwargs.pop('ptvsd', None)

    if ExecutionStarter.params.option & Options.Continue:
        Restarter.run_with_argv(**kwargs)
    else:
        Starter.run_with_argv(**kwargs)
def init_aggregator():
    '''
    debug_flask - when set to True we don't instantiate iot edge
    '''

    try:
        if args.debug:
            logging.info("Please attach a debugger to port 5678")

            import ptvsd
            ptvsd.enable_attach(('0.0.0.0', 5678))
            ptvsd.wait_for_attach()
            ptvsd.break_into_debugger()

        logging.info("Starting up Counting Aggregator...")
        aggreg = IoTCountAggregator(COUNT_AGG_QUEUE,
                                    check_every=args.interval,
                                    no_iotedge=args.flask_debug)

        return aggreg

    except IoTHubError as iothub_error:
        print("Unexpected error %s from IoTHub" % iothub_error)
        return
Esempio n. 20
0
 def deal_post_data(self):
     try:
         ctype, pdict = cgi.parse_header(self.headers['Content-Type'])
         pdict['boundary'] = bytes(pdict['boundary'], "utf-8")
         pdict['CONTENT-LENGTH'] = int(self.headers['Content-Length'])
         if ctype == 'multipart/form-data':
             form = cgi.FieldStorage( fp=self.rfile, headers=self.headers, environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':self.headers['Content-Type'], })
             #self.logger.debug(type(form))
             try:
                 if isinstance(form.list, list):
                     for v in form.list:
                         bio = io.BytesIO()
                         bio.write( v.file.read() )
                         self.jpegUpload_call(bio)
                 elif isinstance(form.file, list):
                     for record in form.file:
                         bio = io.BytesIO()
                         bio.write( record.file.read() )
                         self.jpegUpload_call(bio)
                 else:
                     bio = io.BytesIO()
                     bio.write( form.file.read() )
                     self.jpegUpload_call(bio)
             except IOError:
                 self.logger.exception("Fehler beim download der daten!")
                 return (False, "IOError")
         self.jpegUpload_call(None)
         return (True, "Files uploaded")
     except:
         self.logger.exception("Fehler beim verarbeiten der Lerndaten")
         try:
             import ptvsd
             ptvsd.break_into_debugger()
         except:
             pass
         return (False, "General Error")
Esempio n. 21
0
class ActionModule(ActionBase):
    """
    This is an Ansible Action, that combines the following modules:

    1. template
    2. script

    After script execution, it checks the returncode for the action status:

    RC=0    -> ok
    RC=-1   -> changed
    other   -> failed

    Example:

    wd_script:
        src: scripttemplate.sh
        dest: ~/targetfile.sh

    """

    import ptvsd
    ptvsd.enable_attach(address=('127.0.0.1', 3000))
    ptvsd.wait_for_attach()
    ptvsd.break_into_debugger()

    # https://www.ansible.com/blog/how-to-extend-ansible-through-plugins
    # https://docs.ansible.com/ansible/latest/modules/shell_module.html#shell-module

    def run(self, tmp=None, task_vars=None):

        result = super(ActionModule, self).run(tmp, task_vars)

        dest = self._task.args['dest']
        src = self._task.args['src']

        args_template = dict()
        args_template["dest"] = dest
        args_template["src"] = src

        res_template = self._execute_module(module_name='template',
                                            module_args=args_template,
                                            task_vars=task_vars,
                                            tmp=tmp)

        return res_template
Esempio n. 22
0
import os
import ptvsd
import json
import regex
import pprint

from pyknp import KNP

ptvsd.enable_attach(address=("0.0.0.0", 3000))
ptvsd.wait_for_attach()
ptvsd.break_into_debugger()

knp = KNP()     # Default is JUMAN++. If you use JUMAN, use KNP(jumanpp=False)

file_name = "feedbacksheet.json"

if os.path.exists(file_name):
    os.remove(file_name)

dependency_dic = {}
for index in range(2, 22):
    index_json = {}
    feature_json = {}
    with open("data/{}.json".format(index), "r") as f:
        json_data = json.load(f)

    history = json_data.pop("history").strip("[]")
    history_list = regex.findall("{(?>[^{}]+|(?R))*}", history)

    comment_2d_list = []
    for history_str in history_list:
Esempio n. 23
0
 def wait_and_break_deco(*args, **kwargs):
     ptvsd.enable_attach(self.secret, address=self.address)
     ptvsd.wait_for_attach()
     ptvsd.break_into_debugger()
     return function(*args, **kwargs)
Esempio n. 24
0
    def runInference(self, frame, frameW, frameH, confidenceLevel):
        try:
            countsByClassId = {}
            boxes = []
            yoloDetections = []

            frame_small = cv2.resize(frame, (416, 416))
            detections = darknet.detect(darknet.netMain, darknet.metaMain,
                                        frame_small, confidenceLevel)

            boundingBoxes = np.array(
                list((item[2][0], item[2][1], item[2][0] + item[2][2],
                      item[2][1] + item[2][3]) for item in detections[:]))
            idxs = self.__non_max_suppression_fast(boundingBoxes, 0.3)

            reducedDetections = [detections[idx] for idx in idxs]
            for detection in reducedDetections:
                classID = str(detection[0], encoding)
                confidence = detection[1]

                if confidence > confidenceLevel:

                    if classID not in countsByClassId:
                        countsByClassId[classID] = 1
                    else:
                        countsByClassId[classID] = countsByClassId[classID] + 1

                    bounds = detection[2] * np.array([
                        frameW / 416, frameH / 416, frameW / 416, frameH / 416
                    ])

                    width = int(bounds[2])
                    height = int(bounds[3])
                    # Coordinates are around the center
                    xCoord = int(bounds[0] - bounds[2] / 2)
                    yCoord = int(bounds[1] - bounds[3] / 2)
                    # std: obsolete, if working with tracker
                    box = [xCoord, yCoord, xCoord + width, yCoord + height]
                    boxes.append(box)
                    yoloDetections.append(
                        YoloDetection(box, classID, confidence))

                    # draw detection into frame tagged with class id an confidence
                    #self.__draw_rect(frame, classID, confidence, xCoord, yCoord, xCoord + width, yCoord + height)

            if False and __myDebug__:
                if detections is not None and len(detections) > 1:
                    ptvsd.break_into_debugger()
                else:
                    return yoloDetections

            #if len(countsByClassId) > 0 and (datetime.now() - self.lastMessageSentTime).total_seconds() >= 1:
            #    strMessage = json.dumps(countsByClassId)
            #    message = IoTHubMessage(strMessage)
            #    print(strMessage)
            #    AppState.HubManager.send_event_to_output("output1", message, 0)
            #    self.lastMessageSentTime = datetime.now()

        except Exception as e:
            print("Exception during AI Inference")
            print(e)

        return yoloDetections
Esempio n. 25
0
def main(args):
    parser = argparse.ArgumentParser()
    if sys_name == "Linux":
        parser.add_argument("--device",
                            help="BDF of tg3 PCI device",
                            default=None)
        parser.add_argument("--devid",
                            help="id of tg3 PCI device",
                            default=None)
    parser.add_argument("-p",
                        "--ptvsd",
                        help="enable ptvsd server",
                        action="store_true")
    parser.add_argument("--ptvsdpass",
                        help="ptvsd server password",
                        default=None)
    parser.add_argument("-t", "--tests", help="run tests", action="store_true")
    parser.add_argument("-s",
                        "--shell",
                        help="ipython cli",
                        action="store_true")
    parser.add_argument("-b",
                        "--backup",
                        help="create eeprom backup",
                        action="store_true",
                        default=False)
    parser.add_argument("-d",
                        "--driver",
                        help="load userspace tap driver",
                        action="store_true")
    parser.add_argument("-i",
                        "--install",
                        help="install thundergate firmware",
                        action="store_true")
    parser.add_argument("--wait",
                        help="wait for debugger attachment at startup",
                        action="store_true")
    parser.add_argument("--cdpserver",
                        help="launch VS Code debug protocol server",
                        action="store_true")
    parser.add_argument("-g",
                        "--gui",
                        help="launch wxpython gui",
                        action="store_true")

    args = parser.parse_args(args=args[1:])

    if args.cdpserver:
        conout = sys.stdout
        conin = sys.stdin
        sys.stdin = open(os.devnull, "r")
        sys.stdout = open("cdp.%d.log" % os.getpid(), "w")

    banner()

    ima = "inspector"
    try:
        if args.driver: ima = "userspace driver"
    except:
        pass

    logger.info("tg3 %s initializing" % ima)
    logger.debug("process id is %d" % os.getpid())

    if args.ptvsd:
        import ptvsd
        ptvsd.enable_attach(secret=args.ptvsdpass)
        if args.wait:
            logger.info("waiting for ptvsd client...")
            ptvsd.wait_for_attach()
            logger.info("ptvsd client attached!")
            ptvsd.break_into_debugger()
        else:
            logger.info("ptvsd server enabled")
    elif args.wait:
        print "[!] press 'enter' to continue..."
        raw_input()

    if sys_name == 'Linux':
        if args.device is None:
            devid = args.devid
            if devid is None:
                devid = "14e4:1682"
            dbdf = subprocess.check_output(["lspci",
                                            "-d %s" % devid,
                                            "-n"]).split(" ")[0].strip()
            if '' == dbdf:
                logger.error("tigon3 device not found")
                return 1
        else:
            dbdf = args.device
        if len(dbdf.split(':')) == 2:
            dbdf = "0000:%s" % dbdf

        if not os.path.exists("/sys/bus/pci/devices/%s/" % dbdf):
            logger.error(
                "device resources at /sys/bus/pci/devices/%s/ not found; " +
                "is sysfs mounted?", dbdf)
            return 1

        try:
            kmod = os.readlink("/sys/bus/pci/devices/%s/driver" %
                               dbdf).split('/')[-1]
        except:
            kmod = ''
        if kmod == 'vfio-pci':
            dev_interface = VfioInterface(dbdf)
        elif kmod == 'uio_pci_generic':
            dev_interface = UioInterface(dbdf)
        else:
            dev_interface = SysfsInterface(dbdf)

        if kmod == 'tg3' and args.driver:
            logger.error("device is currently bound to tg3; this won't work")
            return 1

    elif sys_name == 'Windows' or sys_name == 'cli':
        try:
            dev_interface = WinInterface()
        except:
            dev_interface = None
    if not args.backup:
        if not os.path.exists("eeprom.bak"):
            logger.warn("no backup image found")
            if not args.cdpserver:
                resp = raw_input(
                    "\n\n" + "would you like to create a backup image (y/n): ")
                if resp[0] in "yY":
                    args.backup = True

    with Device(dev_interface) as dev:
        if args.backup:
            dev.nvram.init()
            dev.nvram.dump_eeprom("eeprom.bak")
            logger.info("eeprom backup saved as 'eeprom.bak'")

        if args.install:
            from tginstall import TgInstaller
            with TgInstaller(dev) as i:
                return i.run()
        elif args.shell:
            from shelldrv import ShellDriver
            with ShellDriver(dev) as shell:
                if args.tests:
                    from testdrv import TestDriver
                    with TestDriver(dev) as test:
                        test.run()
                        return shell.run(loc=locals())
                else:
                    return shell.run(loc=locals())
        elif args.cdpserver:
            from cdpserver import CDPServer
            with CDPServer(dev, conin, conout) as server:
                return server.run()
        elif args.gui:
            import gui
            dev.reset(cold=True)
            gui._run(dev)
        else:
            if args.driver:
                import tap
                return tap.run(dev)
            elif args.tests:
                from testdrv import TestDriver
                with TestDriver(dev) as test:
                    return test.run()
Esempio n. 26
0
def main(args):
    parser = argparse.ArgumentParser()
    if sys_name == "Linux":
        parser.add_argument("--device", help="BDF of tg3 PCI device", default=None)
        parser.add_argument("--devid", help="id of tg3 PCI device", default=None)
    parser.add_argument("-p", "--ptvsd", help="enable ptvsd server", action="store_true")
    parser.add_argument("--ptvsdpass", help="ptvsd server password", default=None)
    parser.add_argument("-t", "--tests", help="run tests", action="store_true")
    parser.add_argument("-s", "--shell", help="ipython cli", action="store_true")
    parser.add_argument("-b", "--backup", help="create eeprom backup", action="store_true", default=False)
    parser.add_argument("-d", "--driver", help="load userspace tap driver", action="store_true")
    parser.add_argument("-i", "--install", help="install thundergate firmware", action="store_true")
    parser.add_argument("--wait", help="wait for debugger attachment at startup", action="store_true")
    parser.add_argument("--cdpserver", help="launch VS Code debug protocol server", action="store_true")
    parser.add_argument("-g", "--gui", help="launch wxpython gui", action="store_true")

    args = parser.parse_args(args=args[1:])

    if args.cdpserver:
        conout = sys.stdout
        conin = sys.stdin
        sys.stdin = open(os.devnull, "r")
        sys.stdout = open("cdp.%d.log" % os.getpid(), "w")
        
    banner()

    ima = "inspector"
    try: 
        if args.driver: ima = "userspace driver"
    except: 
        pass

    logger.info("tg3 %s initializing" % ima)
    logger.debug("process id is %d" % os.getpid())

    if args.ptvsd:
        import ptvsd
        ptvsd.enable_attach(secret=args.ptvsdpass)
        if args.wait:
            logger.info("waiting for ptvsd client...")
            ptvsd.wait_for_attach()
            logger.info("ptvsd client attached!")
            ptvsd.break_into_debugger()
        else:
            logger.info("ptvsd server enabled")
    elif args.wait:
        print "[!] press 'enter' to continue..."
        raw_input()

    if sys_name == 'Linux':
        if args.device is None:
            devid = args.devid
            if devid is None:
                devid = "14e4:1682"
            dbdf = subprocess.check_output(["lspci", "-d %s" % devid, "-n"]).split(" ")[0].strip()
            if '' == dbdf:
                logger.error("tigon3 device not found")
                return 1
        else:
            dbdf = args.device
        if len(dbdf.split(':')) == 2:
            dbdf = "0000:%s" % dbdf

        if not os.path.exists("/sys/bus/pci/devices/%s/" % dbdf):
            logger.error(
                "device resources at /sys/bus/pci/devices/%s/ not found; " +
                "is sysfs mounted?", dbdf)
            return 1
        
        try:
            kmod = os.readlink("/sys/bus/pci/devices/%s/driver" % dbdf).split('/')[-1]
        except:
            kmod = '' 
        if kmod == 'vfio-pci':
            dev_interface = VfioInterface(dbdf)
        elif kmod == 'uio_pci_generic':
            dev_interface = UioInterface(dbdf)
        else:
            dev_interface = SysfsInterface(dbdf)

        if kmod == 'tg3' and args.driver:
            logger.error("device is currently bound to tg3; this won't work")
            return 1

    elif sys_name == 'Windows' or sys_name == 'cli':
        try:
            dev_interface = WinInterface()
        except:
            dev_interface = None
    if not args.backup:
        if not os.path.exists("eeprom.bak"):
            logger.warn("no backup image found")
            if not args.cdpserver:
                resp = raw_input("\n\n" + 
                        "would you like to create a backup image (y/n): ")
                if resp[0] in "yY":
                    args.backup = True

    with Device(dev_interface) as dev:
        if args.backup:
            dev.nvram.init()
            dev.nvram.dump_eeprom("eeprom.bak")
            logger.info("eeprom backup saved as 'eeprom.bak'")

        if args.install:
            from tginstall import TgInstaller
            with TgInstaller(dev) as i:
                return i.run()
        elif args.shell:
            from shelldrv import ShellDriver
            with ShellDriver(dev) as shell:
                if args.tests:
                    from testdrv import TestDriver
                    with TestDriver(dev) as test:
                        test.run()
                        return shell.run(loc=locals())
                else:
                    return shell.run(loc=locals())
        elif args.cdpserver:
            from cdpserver import CDPServer
            with CDPServer(dev, conin, conout) as server:
                return server.run()
        elif args.gui:
            import gui
            dev.reset(cold = True)
            gui._run(dev)
        else:
            if args.driver:
                import tap
                return tap.run(dev)
            elif args.tests:
                from testdrv import TestDriver
                with TestDriver(dev) as test:
                    return test.run()
Esempio n. 27
0
def ptvsd_breakpointhook():
    ptvsd.break_into_debugger()
Esempio n. 28
0
import sys
import ptvsd

if len(sys.argv) > 1:
    open(sys.argv[1], 'w').close()

i = 0
while True:
    if ptvsd.is_attached():
        ptvsd.break_into_debugger()
        if i is None: break
    i += 1

Esempio n. 29
0
def ptvsd_breakpointhook():
    ptvsd.break_into_debugger()
Esempio n. 30
0
    def Initialize(self):
        self.SetStartDate(2019, 4, 30)  # Set Start Date
        self.SetEndDate(2019, 5, 1)  # Set End Date
        self.SetCash(100000)  # Set Strategy Cash
        #self.AddEquity("SPY")
        self.symbol = "BTCUSD"
        #self.AddEquity(self.symbol, Resolution.Minute).Symbol
        self.AddCrypto(self.symbol, Resolution.Minute, Market.Bitfinex).Symbol
        span = 500
        longPeriod = 43200
        ema = self.EMA(self.symbol, span)
        ptvsd.break_into_debugger()

        price = Identity(self.symbol)
        ptvsd.break_into_debugger()

        self.diff_pct_close_ema = IndicatorExtensions.Over(
            IndicatorExtensions.Minus(price, ema), ema)
        ptvsd.break_into_debugger()

        self.diff_pct_close_ema_mean = IndicatorExtensions.SMA(
            self.diff_pct_close_ema, longPeriod)
        ptvsd.break_into_debugger()

        std = self.STD(self.symbol, longPeriod)
        diff_pct_close_ema_std = IndicatorExtensions.Of(
            self.diff_pct_close_ema, std)
        self.negative_abnormal = IndicatorExtensions.Minus(
            self.diff_pct_close_ema_mean,
            IndicatorExtensions.Times(diff_pct_close_ema_std, 1.96))
        self.positive_abnormal = IndicatorExtensions.Plus(
            self.diff_pct_close_ema_mean,
            IndicatorExtensions.Times(diff_pct_close_ema_std, 1.96))
        self.RegisterIndicator(self.symbol, self.diff_pct_close_ema,
                               Resolution.Minute)
        self.RegisterIndicator(self.symbol, diff_pct_close_ema_std,
                               Resolution.Minute)
        self.RegisterIndicator(self.symbol, self.diff_pct_close_ema_mean,
                               Resolution.Minute)
        self.RegisterIndicator(self.symbol, self.negative_abnormal,
                               Resolution.Minute)
        self.RegisterIndicator(self.symbol, self.positive_abnormal,
                               Resolution.Minute)

        self.SetWarmUp(longPeriod)
        #stockPlot = Chart("Trade Plot")
        # On the Trade Plotter Chart we want 2 series: trades :
        #stockPlot.AddSeries(Series("Buy", SeriesType.Scatter, 0))
        #stockPlot.AddSeries(Series("Sell", SeriesType.Scatter, 0))
        #stockPlot.AddSeries(Series("Close", SeriesType.Scatter, 0))
        #self.AddChart(stockPlot)

        # On the Deviation Chart we want serie, diff_pct_close_vs_ema
        #deviation = Chart("Deviation Degree")
        #deviation.AddSeries(Series("Deviation Degree", SeriesType.Line, 0))
        #self.AddChart(deviation)
        self.resamplePeriod = (self.EndDate - self.StartDate) / 4000
        self.AddAlpha(
            EmaReversionAlphaModel(self.symbol, self.diff_pct_close_ema,
                                   self.negative_abnormal,
                                   self.positive_abnormal,
                                   self.diff_pct_close_ema_mean,
                                   self.resamplePeriod))
        self.SetPortfolioConstruction(
            EqualWeightingPortfolioConstructionModel())
        self.SetRiskManagement(MaximumDrawdownPercentPortfolio(0.1))
        self.SetExecution(VolumeWeightedAveragePriceExecutionModel())
Esempio n. 31
0
    def Update(self, algorithm, data):
        insights = []
        PositiveAbnormalIsOverDiff_pct_close_ema = False
        Diff_pct_close_emaIsOverNegativeAbnormal = False
        Diff_pct_close_emaIsOverMean = False
        MeanIsOverDiff_pct_close_ema = False
        #longPeriod_index = 0

        if not data.ContainsKey(self.symbol): return
        #if not data.ContainsKey('SPY'): return
        #if  self.ema.Current.Value == 0: return
        #diff_pct_close_ema = (algorithm.Securities[self.symbol].Price - self.ema.Current.Value) / self.ema.Current.Value
        #longPeriod_index += 1
        #diff_pct_close_ema_sum += diff_pct_close_ema
        #diff_pct_close_ema_list.append(diff_pct_close_ema)
        #if longPeriod_index == longPeriod:
        #   diff_pct_close_ema_mean = diff_pct_close_ema_sum / longPeriod_index
        #  diff_pct_close_ema_std = statistics.stdev(diff_pct_close_ema_list)
        # negative_abnormal = diff_pct_close_ema_mean - 1.96 * diff_pct_close_ema_std
        #positive_abnormal = diff_pct_close_ema_mean + 1.96 * diff_pct_close_ema_std
        #longPeriod_index = 0
        #diff_pct_close_ema_sum = 0
        #diff_pct_close_ema_list = []
        if not self.positive_abnormal.IsReady: return
        ptvsd.break_into_debugger()

        if not algorithm.Portfolio.Invested and PositiveAbnormalIsOverDiff_pct_close_ema and self.diff_pct_close_ema > self.positive_abnormal:
            insights.append(
                Insight.Price(self.symbol, Resolution.Minute, 1,
                              InsightDirection.Down))
            algorithm.Plot("Trade Plot", "Short", data[self.symbol].Price)
        elif not algorithm.Portfolio.Invested and Diff_pct_close_emaIsOverNegativeAbnormal and self.diff_pct_close_ema < self.negative_abnormal:
            insights.append(
                Insight.Price(self.symbol, Resolution.Minute, 1,
                              InsightDirection.Up))
            algorithm.Plot("Trade Plot", "Long", data[self.symbol].Price)
        elif algorithm.Portfolio[
                self.
                symbol].IsShort and Diff_pct_close_emaIsOverMean and self.diff_pct_close_ema < self.diff_pct_close_ema_mean:
            insights.append(
                Insight.Price(self.symbol, Resolution.Minute, 1,
                              InsightDirection.Flat))
            algorithm.Plot("Trade Plot", "Close", data[self.symbol].Price)
        elif algorithm.Portfolio[
                self.
                symbol].IsLong and MeanIsOverDiff_pct_close_ema and self.diff_pct_close_ema > self.diff_pct_close_ema_mean:
            insights.append(
                Insight.Price(self.symbol, Resolution.Minute, 1,
                              InsightDirection.Flat))
            algorithm.Plot("Trade Plot", "Close", data[self.symbol].Price)
        PositiveAbnormalIsOverDiff_pct_close_ema = self.positive_abnormal > self.diff_pct_close_ema
        ptvsd.break_into_debugger()

        Diff_pct_close_emaIsOverNegativeAbnormal = self.diff_pct_close_ema > self.negative_abnormal
        Diff_pct_close_emaIsOverMean = self.diff_pct_close_ema > self.diff_pct_close_ema_mean
        ptvsd.break_into_debugger()

        MeanIsOverDiff_pct_close_ema = not Diff_pct_close_emaIsOverMean

        if algorithm.Time > self.resample:
            self.resample = algorithm.Time + self.resamplePeriod
            algorithm.PlotIndicator("Deviation Degree",
                                    self.diff_pct_close_ema)

        #if (diff_pct_close_ema > positive_abnormal) or (diff_pct_close_ema < negative_abnormal):
        #   self.Plot('Deviation', 'BTCUSD', data[self.symbol].Price)
        #  self.Plot('Deviation', 'EMA', ema.Current.Value)
        # self.Plot('Deviation Degree', 'diff_pct_close_vs_ema', diff_pct_close_ema)

        return insights
Esempio n. 32
0
def main():
    print('one')
    ptvsd.break_into_debugger()
    print('two')
Esempio n. 33
0
    def code_to_debug():
        from debug_me import ptvsd

        ptvsd.break_into_debugger()
        print()