コード例 #1
0
 def datetime_prefix_on():
     old = ic.prefix
     try:
         ic.configureOutput(prefix=yyyymmddhhmiss)
         yield
     finally:
         ic.prefix = old
コード例 #2
0
    def __init__(self, lines: list, options, inFilename: str):
        """Initialize a few class variables in preparation for our walk."""
        self.lines = lines
        self.options = options
        self.inFilename = inFilename
        self.docLines = []

        ic.configureOutput(includeContext=True)
        ic.enable() if self.options.debug else ic.disable()
コード例 #3
0
        def do_icecream(self, arg):
            """ic(ecream) expression
            Icecream print.
            """
            try:
                from icecream import ic

                val = self._getval(arg)
                ic.configureOutput(prefix="🍦 |> ")
                self._print(ic.format(arg, val))
            except BaseException:
                pass
コード例 #4
0
ファイル: test_icecream.py プロジェクト: gruns/icecream
def configureIcecreamOutput(prefix=None, outputFunction=None,
                            argToStringFunction=None, includeContext=None):
    oldPrefix = ic.prefix
    oldOutputFunction = ic.outputFunction
    oldArgToStringFunction = ic.argToStringFunction
    oldIncludeContext = ic.includeContext

    if prefix:
        ic.configureOutput(prefix=prefix)
    if outputFunction:
        ic.configureOutput(outputFunction=outputFunction)
    if argToStringFunction:
        ic.configureOutput(argToStringFunction=argToStringFunction)
    if includeContext:
        ic.configureOutput(includeContext=includeContext)

    yield

    ic.configureOutput(
        oldPrefix, oldOutputFunction, oldArgToStringFunction,
        oldIncludeContext)
コード例 #5
0
def R_login(request):
    """
    登录
    :param request:
    :return:
    """
    ic.configureOutput(prefix=time_format)
    blank = magicalValue.BLANK.value
    NULL = magicalValue.NULL.value
    if request.method == "POST":
        data = json.loads(request.body)
        name = data['name']
        pwd = data['pwd']
        ic(data)
        insert = {'user': name, 'pwd': pwd}
        if name == NULL or pwd == NULL:
            dic = json.dumps(RE.PARAMETER_IS_EMPTY.value)
            return HttpResponse(dic, content_type=RE.CONTENT_TYPE.value)
        elif blank in name or blank in pwd:
            dic = json.dumps(RE.PAY_ATTENTION_TO_SPACES.value)
            return HttpResponse(dic, content_type=RE.CONTENT_TYPE.value)
        else:
            num = service_login(insert)
            if num['code'] == RE.SUCCESS.value['code']:
                dic = json.dumps(num)
                return HttpResponse(dic, content_type=RE.CONTENT_TYPE.value)
            else:
                dic = json.dumps({
                    "code": 30030,
                    "data": "false",
                    "message": f"{num}"
                })
                return HttpResponse(dic, content_type=RE.CONTENT_TYPE.value)
    else:
        dic = json.dumps(RE.WRONG_REQUEST.value)
        return HttpResponse(dic, content_type=RE.CONTENT_TYPE.value)
コード例 #6
0
ファイル: test_icecream.py プロジェクト: mariku/icecream
def configureIcecreamOutput(prefix=None, outputFunction=None):
    oldPrefix = ic.prefix
    oldOutputFunction = ic.outputFunction

    if prefix:
        ic.configureOutput(prefix=prefix)
    if outputFunction:
        ic.configureOutput(outputFunction=outputFunction)

    yield

    ic.configureOutput(oldPrefix, oldOutputFunction)
コード例 #7
0

def ic(*a):  # pylint: disable=invalid-name
    """Just in case package icecream is not available: For logging purpuses."""
    if not a:
        return None
    return a[0] if len(a) == 1 else a


if __debug__:
    try:
        from icecream import ic  # type: ignore[import,no-redef]  # noqa: F811,W0404
    except ImportError:
        pass  # Fallback to default
    else:
        ic.configureOutput(includeContext=True)  # type: ignore[attr-defined]
try:
    from cpu_load_generator import load_single_core  # type: ignore[import]
except ImportError:
    pass
else:

    def loadonecore(
        loadduration: int = 10, loadedcore: int = 0, theload: float = 0.5
    ) -> None:
        """just a helper function to generate load on one given core"""
        load_single_core(
            core_num=loadedcore,
            duration_s=loadduration,
            target_load=theload,
        )
コード例 #8
0
from icecream import ic as println
from decryption import Decrypt
from encryption import Encrypt
from retreive import Retreive
from append import Append
from secure_lock import Generate
from _all import All
println.configureOutput(prefix='Neutron > ', includeContext=False)
def init():
     SK = input("Neutron > SK (h for help): ")
     if SK == "h":
          println("SK 0 is used to access the email client.")
          println("SK 1 is used to access the password manager.")
          println("OK 0 for SK 1 is used to append passwords to your personal password database.")
          println("OK 1 for SK 1 is used to retreive passwords from your personal password database.")
          println("OK 2 for SK 1 is used to generate passwords and append them to you personal password database.")
          println("OK 3 for SK 1 is used to retreive all your passwords from your personal password database.")
          println("SK 2 is used to access the encryption machine.")
          println("OK 0 for SK 2 is used to encrypt messages.")
          println("OK 1 for SK 2 is used to decrypt messages previously encrypted by Neutron.")
          init()
     elif SK == "0":
          println(SK)
     elif SK == "1":
          println(SK)
          OK = input("Neutron > OK (h for help): ")
          if OK == "0":
               Site = input("Neutron > Site: ")
               Password = input("Neutron > Password: "******"1":
コード例 #9
0
def baseDebugInfoOut(s):
    """
    icecream output function into a
    rotating log with time stamps and
    to STDOUT
    """
    global log

    log.info(s)
    print(s)


# Configure icecream with time stamp and output to
# file and screen
ic.configureOutput(prefix=baseUnixTimestamp, outputFunction=baseDebugInfoOut)

# Create log file that icecream will output to
log = baseCreateRotatingLog()


def main():
    try:
        fn = sys.argv[1]
    except IndexError:
        print('Usage: {} file_name'.format(sys.argv[0]))
        sys.exit(1)

    ic(fn)

    import requests
コード例 #10
0
ファイル: common.py プロジェクト: tedinGH/lvyaoyu
import os
import re
import zipfile

from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LAParams, LTTextBoxHorizontal
from pdfminer.pdfinterp import PDFTextExtractionNotAllowed, PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfparser import PDFParser, PDFDocument

from icecream import ic
from datetime import datetime

ic.configureOutput(prefix=str(datetime.now()) + ' - ', includeContext=True)


# 删除文件或文件夹及里面的内容
def rm_dir_file(path):
    if os.path.isfile(path):
        os.remove(path)
        print('文件 %s 删除成功' % path)
    elif os.path.isdir(path):
        for root, dirs, files in os.walk(path, topdown=False):
            for name in files:
                os.remove(os.path.join(root, name))
                print('文件 %s 删除成功' % os.path.join(root, name))
            for name in dirs:
                os.rmdir(os.path.join(root, name))
                print('文件 %s 删除成功' % os.path.join(root, name))
        else:
            os.rmdir(path)
            print('文件夹 %s 删除成功' % path)
コード例 #11
0
ファイル: test_icecream.py プロジェクト: gruns/icecream
def disableColoring():
    originalOutputFunction = ic.outputFunction

    ic.configureOutput(outputFunction=stderrPrint)
    yield
    ic.configureOutput(outputFunction=originalOutputFunction)
コード例 #12
0
import requests
from icecream import ic
from datetime import datetime
import time
from .dirmanager.init_file import *


def time_format():
    return f'{datetime.now()}|> '


ic.configureOutput(prefix=time_format)

# NEURO_URL = 'https://www.google.com/'


class DataSender:
    def __init__(self, ip, port, filtrSubURL, readySubURL):
        self.ip = ip
        self.port = port
        self.filtrSubURL = filtrSubURL
        self.readySubURL = readySubURL

    def waitWhileBusy(self):
        response_code = 0
        while response_code != 200:
            url = 'http://{}:{}{}'.format(self.ip, self.port, self.readySubURL)
            response_code = requests.get(url).status_code
            ic(f'\nAnswer from API {response_code}\n')
            if response_code != 200:
                time.sleep(1)
コード例 #13
0
ファイル: test_times.py プロジェクト: giladbarnea/timefred
from itertools import product, permutations
from random import randint, random
from typing import NoReturn, Union

import pytest
from arrow import Arrow
from arrow.locales import EnglishLocale
from icecream import ic

from test import TEST_START_ARROW
from timefred.config import config
from timefred.log import log
from timefred.time import XArrow
from timefred.time.timeutils import secs2human, arrows2rel_time

ic.configureOutput(prefix='')

FORMATS = config.time.formats
TIME_UNITS = {
    'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second'
}


def assert_equal_attrs(obj1, obj2, attr: Union[str, Iterable[str]],
                       *attrs) -> NoReturn:
    __tracebackhide__ = True
    if not isinstance(attr, str):
        if attrs:
            raise ValueError('If attr is iterable, attrs must be empty')
        attributes = attr
    else:
コード例 #14
0
def baseDebugInfoOut(s):
    """
    icecream output function into a
    rotating log with time stamps and
    to STDOUT
    """
    global log

    log.info(s)
    # print(s)


# Configure icecream with time stamp and output to
# file and screen
ic.configureOutput(prefix=baseUnixTimestamp, outputFunction=baseDebugInfoOut)

# Create log file that icecream will output to
log = baseCreateRotatingLog()

# End template code -----------------------


def randNumBetween(nrange):
    """
    Return number between
    nrange[0] and (nrange[1] - 1)
    """
    num = 0
    ic(nrange)
    while (num < nrange[0]):
コード例 #15
0
ファイル: trx.py プロジェクト: mmagnus/rna-tools
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""

"""
import pandas as pd

from icecream import ic
import sys

ic.configureOutput(outputFunction=lambda *a: print(*a, file=sys.stderr),
                   includeContext=True)
ic.configureOutput(prefix='> ')

import argparse
import glob
import random

TRX_DB = "/Users/magnus/work/src/rna-tools/rna_tools/tools/triplexibility/trx-db/triple-db-ext-2+Clash200x2+Contacts-1_fix36UCG.csv"


def get_parser():
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)

    #parser.add_argument('-', "--", help="", default="")

    parser.add_argument("-v",
                        "--verbose",
                        action="store_true",
コード例 #16
0
ファイル: macro.py プロジェクト: 8luebottle/ticketing-macro
import pause
import pyautogui
import webbrowser

from time import sleep
from icecream import ic

import ticketing.mouse_positions as position
from confs.config import conf
from ticketing.errors import formatted_error
from ticketing.times import timestamp, click_time, Wait

ic.configureOutput(prefix=timestamp)
Site = conf["site"]

ic("🤖 : Start my job")
ic("open the browser")
webbrowser.get("chrome").open_new_tab(Site.url())

ic("Click the browser")
pyautogui.click(position.APPLY_BTN)
sleep(Wait.load_page)

ic("Scroll down")
for i in range(13):
    pyautogui.scroll(-10)

ic("Pause for click time")
pause.until(click_time(hour=2, minute=18, second=10))

total_clicks = 0
コード例 #17
0
import time
from sklearn.utils import shuffle
from sklearn.cluster import KMeans
from PIL import Image as im
from agents.utils import print_messages

#from agents.f1.settings import telemetry, x_row, center_image, width, height, telemetry_mask, max_distance
#from settings import x_row, center_image, width, height, telemetry_mask, max_distance
from rl_studio.envs.f1.image_f1 import ImageF1
from rl_studio.envs.f1.models.f1_env import F1Env
from rl_studio.envs.gazebo_utils import set_new_pose

ic.enable()
#ic.disable()
#ic.configureOutput(prefix='Debug | ')
ic.configureOutput(prefix=f'{datetime.now()} | ')

class F1DDPGCameraEnv(F1Env):

    def __init__(self, **config):

        F1Env.__init__(self, **config)
        self.image = ImageF1()
        #self.cv_image_pub = None
        self.image_raw_from_topic = None
        self.f1_image_camera = None

        self.sensor = config['sensor']

        # Image
        self.image_resizing = config['image_resizing'] / 100
コード例 #18
0
#como depurar normalmente
from icecream import ic


def sumar(x, y):
    ic()
    ic(x)
    ic(y)
    suma = x + y
    return suma


ic.configureOutput(prefix="Prueba ", includeContext=True)
ic(sumar(3, 4))

# para instalar paquetes en python uso icecream
#al terminar tengo que eliminar los debugs y la biblioteca
コード例 #19
0
ファイル: h.py プロジェクト: sudo-gera/c
    a = a[len(s[0]) + 4:]
    if '\n' in a:
        a = a.split('\n', 1)
        a = '- \n'.join(a)
    s = split(r'- ', a)
    func = s[0]
    a = a[len(func) + 2:]
    args = a
    print("\x1b[92mline \x1b[94m" + line + "\x1b[92m file \x1b[94m" + file +
          "\x1b[92m func \x1b[94m" + func + "\x1b[92m \x1b[0m" + args,
          file=stderr)


from icecream import ic
import icecream
ic.configureOutput(includeContext=1)
ic.configureOutput(outputFunction=outputFunction)
ic.configureOutput(prefix='')
from builtins import *
import builtins
home = str(Path.home()) + '/'


def rand(q=2**64, e=None):
    if e != None:
        q, e = e, q
    else:
        e = 0
    assert q
    return randint(e, q - 1)
コード例 #20
0
#print('sayi1: ',sayi1)
#print('sayi2: ', sayi2)

#ic(sayi1)
#ic(sayi2)

def topla(sayi):
    return sayi + 5

#ic(topla(4))
#ic(topla(5))

def giris(kullanici:bool):
    if kullanici:
        ic()
    else:
        ic()

#giris(kullanici=False)

def zamanGetir():
    return f'{datetime.now()} |>'
ic.configureOutput(prefix=zamanGetir())

for _ in range(3):
    time.sleep(1)
    ic('Merhaba')

ic(topla(25))
ic(topla(-2))
コード例 #21
0
from pathlib import Path

from future.utils import iteritems

import pickle

from pprint import PrettyPrinter

from BinaryParser import SlidingParser
from BinaryParser import GPRMC_extractor, temperatures_extractor, channel_stats_extractor

import matplotlib.pyplot as plt

from icecream import ic

ic.configureOutput(prefix="", outputFunction=print)

pp = PrettyPrinter(indent=2).pprint


# just a small helper function for displaying the available data
def dump_keys(d, lvl=0):
    """Pretty print a dict showing only keys and size of the
    list entries."""
    for k, v in iteritems(d):
        if type(v) == list:
            print("{}{}: size {}".format(lvl * ' ', k, len(v)))
        else:
            print("{}{}".format(lvl * ' ', k))
            if type(v) == dict:
                dump_keys(v, lvl + 1)
コード例 #22
0
from threading import Thread

import pandas as pd
from flask import Flask

from flask import jsonify
from flask import request
from flask_cors import CORS
from icecream import ic
from loguru import logger

from items import Items
# import pysnooper
from flask_cors import CORS, cross_origin

ic.configureOutput(outputFunction=lambda s: logger.debug(s))
ic.configureOutput(includeContext=True)
ic.configureOutput(prefix="")

####################

app = Flask(__name__)
#cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
cors = CORS(app)

app.config['CORS_HEADERS'] = 'Content-Type'
items = Items()
##########################
# todo: change as needed
# can also write in train class and import to here
# invocations functions, as this function subject to highly frequent changes, just keep it here
コード例 #23
0
'''

import datetime
from sqlalchemy import (BigInteger, Column, DateTime, Integer, MetaData, String, Table, create_engine, LargeBinary,TEXT)
from sqlalchemy.dialects.mysql import LONGTEXT
from sqlalchemy.dialects.mysql import MEDIUMTEXT
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import mapper,sessionmaker
from sqlalchemy.schema import CreateTable
import os,sys,re
from icecream import ic

# 调试配置
def time_format():
    return f'{datetime.datetime.now()}|> '
ic.configureOutput(prefix=time_format)
ic.configureOutput(includeContext=True)

# 创建sqlalchemy基类,使用BaseSQL.metadata.create_all可以创建继承该基类的所有创建的module类
BaseSQL = declarative_base()
# metadata = MetaData() # 初始化表的元数据定义

# module template模板 默认创建主键为Id,防止传入没有创建
class template(BaseSQL):
    __abstract__ = True  # 关键语句,定义所有数据库表对应的父类
    __table_args__ = {"extend_existing": True}  # 允许表已存在
    Id = Column(Integer, primary_key=True)

    # 需要可以自行对动态类添加返回信息
    # def __repr__(self):
    #     """__repr__ print result
コード例 #24
0
#!/usr/bin/env python3

import os
import sys
from math import inf
from pathlib import Path
from shutil import get_terminal_size
from kcl.assertops import maxone
from kcl.assertops import verify
from kcl.inputops import human_filesize_to_int
from kcl.byteops import read_by_byte
from icecream import ic
import click
ic.configureOutput(includeContext=True)
ic.lineWrapWidth, _ = get_terminal_size((80, 20))

# 'st_atime'
# 'st_atime_ns'
# 'st_blksize'
# 'st_blocks'
# 'st_ctime'
# 'st_ctime_ns'
# 'st_dev'
# 'st_gid'
# 'st_ino'
# 'st_mode'
# 'st_mtime'
# 'st_mtime_ns'
# 'st_nlink'
# 'st_rdev'
# 'st_size'
コード例 #25
0
        switch = {
            SourceType.CSV: pd.read_csv,
            SourceType.JSON: pd.read_json,
            SourceType.EXCEL: pd.read_excel
        }

        if self.source.conn_type == ConnType.DIRECTORY:
            df = pd.concat(
                map(switch[self.source.type], self.source.validate()))
        else:
            df = switch[self.source.type](self.source.validate())

        return df


ic.configureOutput(includeContext=False)
ic('Starting...')

con1 = config['DATA SOURCE']['DataSource1']
con2 = config['DATA SOURCE']['DataSource2']

s1 = CSV_Source(con1)
s2 = Excel_Source(con2)

ic(s1.conn_type)
ic(s2.conn_type)
ic(s1.type)
ic(s2.type)

ic(s1)
コード例 #26
0
        return ts.strftime("%H:%M:%S.%f")[:-7]


def now_pp_to(ndig=3):
    return ts_pp_to(dt.now(), ndig=ndig)


# icecream debbuger
from icecream import ic


def x():
    return f'{now_pp_to(0)} ic| '


ic.configureOutput(includeContext=True, prefix=x)


@dataclass
class Timer():
    """
        Classe Timer

            para testar performance de tempo

            tem 3 metodos: 
                Timer.start() - começa a contar tempo
                Timer.stop() - 
    """

    # TODO: #21 criar every x period, ex.: every 1 min
コード例 #27
0
import regex
from icecream import ic
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QDialog, QListWidgetItem, QMessageBox, qApp

from yapgrep_common_gui import Ui_Common
from yapgrep_gui import Ui_MainWindow

types = {}  # type dict from json file


def unixTimestamp():
    return "%s |> " % datetime.now()


ic.configureOutput(prefix=unixTimestamp)


class YapCancel(Exception):
    pass


class CommonDialog(Ui_Common):
    def __init__(self, Common):
        super().__init__()
        self.setupUi(Common)
        self.checkBox_3.stateChanged.connect(self.lineChange)
        self.checkBox_2.stateChanged.connect(self.ignoreChange)
        self.checkBox_5.stateChanged.connect(self.smartChange)

    def lineChange(self, i):
コード例 #28
0
ファイル: trx_score.py プロジェクト: mmagnus/rna-tools
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd
import argparse
import os

from rna_tools.tools.triplexibility import trx
from icecream import ic
import sys
ic.configureOutput(outputFunction=lambda *a: print(*a, file=sys.stderr))
ic.configureOutput(prefix='> ')


def get_parser():
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("-v",
                        "--verbose",
                        action="store_true",
                        help="be verbose")
    parser.add_argument("--fig", help="", default="fig.py")  # nargs='+')
    parser.add_argument("ref", help="", default="")  # nargs='+')
    parser.add_argument("-e", "--edge", help="",
                        default="Triple_cWW_cHS")  # nargs='+')
    parser.add_argument("-t",
                        "--threshold",
                        help="if t not none then if score > t is 1 else 0",
                        type=int)  # nargs='+')
    return parser
コード例 #29
0
# Debug Python code with custom prefix using icecream instead of print

from datetime import datetime
def get_datetime():
    return str(datetime.now()) + " : "


# Using print
def check_boolean(status):
    if status:
        print(get_datetime() +  " True")
    else:
        print(get_datetime() +  " False")
check_boolean(True)
#Output: 2021-04-11 11:42:54.046729 :  True


#Using Icecream
#pip install icecream
from icecream import ic
ic.configureOutput(prefix=get_datetime)
def check_boolean(status):
    if status:
        ic("True")
    else:
        ic("False")
check_boolean(False)
#Output: 2021-04-11 11:42:54.176384 : 'False'

コード例 #30
0
from fire import Fire
from atcodertools.client.atcoder import AtCoderClient, Contest
from pathlib import Path
from icecream import ic


def write2log(s):
    if Path('icecream.log').exists():
        with open("icecream.log", "a") as myfile:
            myfile.write(s + '\n')
    else:
        with open("icecream.log", "w+") as myfile:
            myfile.write(s + '\n')


ic.configureOutput(includeContext=True, outputFunction=write2log)


def main(lang='ja'):

    alphabet = str(Path('.').absolute().name)
    contest_id = str(Path('.').absolute().parent.name)

    client = AtCoderClient()
    client.login()
    ic(client.check_logging_in())

    contest = Contest(ic(contest_id))
    ic(contest.get_url())
    problem_list = client.download_problem_list(ic(contest))
    problem = problem_list[['A', 'B', 'C', 'D', 'E', 'F'].index(ic(alphabet))]
コード例 #31
0
from decryption import Decrypt
from icecream import ic as println  # Used for custom outputs
import os
import sys
from encryption import *
println.configureOutput(prefix='Neutron > ',
                        includeContext=False)  # Setting up custom outputs


def init():
    SK = input(
        "Neutron > SK (h for help): "
    )  # Neutron Start Key, determining what function Neutron leads to (0, 1, 2, h)
    if SK == "h":
        println("SK 0 is used to access the email client.")
        println("SK 1 is used to access the password manager.")
        println("SK 2 is used to access the encryption machine.")
        println("OK 0 for SK 2 is used to encrypt messages.")
        println(
            "OK 1 for SK 2 is used to decrypt messages previously encrypted by Neutron."
        )
        init()
    elif SK == "0":
        println(SK)
    elif SK == "1":
        println(SK)
    elif SK == "2":
        println(SK)
        OK = input("Neutron > OK (h for help): ")
        if OK == "h":
            println("OK 0 is used to encrypt messages.")