コード例 #1
0
ファイル: clipboards.py プロジェクト: fudp/pandas-1
def to_clipboard(obj, excel=True, sep=None, **kwargs):  # pragma: no cover
    """
    Attempt to write text representation of object to the system clipboard
    The clipboard can be then pasted into Excel for example.

    Parameters
    ----------
    obj : the object to write to the clipboard
    excel : boolean, defaults to True
            if True, use the provided separator, writing in a csv
            format for allowing easy pasting into excel.
            if False, write a string representation of the object
            to the clipboard
    sep : optional, defaults to tab
    other keywords are passed to to_csv

    Notes
    -----
    Requirements for your platform
      - Linux: xclip, or xsel (with PyQt4 modules)
      - Windows:
      - OS X:
    """
    encoding = kwargs.pop("encoding", "utf-8")

    # testing if an invalid encoding is passed to clipboard
    if encoding is not None and encoding.lower().replace("-", "") != "utf8":
        raise ValueError("clipboard only supports utf-8 encoding")

    from pandas.io.clipboard import clipboard_set

    if excel is None:
        excel = True

    if excel:
        try:
            if sep is None:
                sep = "\t"
            buf = StringIO()

            # clipboard_set (pyperclip) expects unicode
            obj.to_csv(buf, sep=sep, encoding="utf-8", **kwargs)
            text = buf.getvalue()

            clipboard_set(text)
            return
        except TypeError:
            warnings.warn(
                "to_clipboard in excel mode requires a single character separator."
            )
    elif sep is not None:
        warnings.warn("to_clipboard with excel=False ignores the sep argument")

    if isinstance(obj, ABCDataFrame):
        # str(df) has various unhelpful defaults, like truncation
        with option_context("display.max_colwidth", None):
            objstr = obj.to_string(**kwargs)
    else:
        objstr = str(obj)
    clipboard_set(objstr)
コード例 #2
0
ファイル: clipboards.py プロジェクト: bwignall/pandas
def to_clipboard(obj, excel=True, sep=None, **kwargs):  # pragma: no cover
    """
    Attempt to write text representation of object to the system clipboard
    The clipboard can be then pasted into Excel for example.

    Parameters
    ----------
    obj : the object to write to the clipboard
    excel : boolean, defaults to True
            if True, use the provided separator, writing in a csv
            format for allowing easy pasting into excel.
            if False, write a string representation of the object
            to the clipboard
    sep : optional, defaults to tab
    other keywords are passed to to_csv

    Notes
    -----
    Requirements for your platform
      - Linux: xclip, or xsel (with gtk or PyQt4 modules)
      - Windows:
      - OS X:
    """
    encoding = kwargs.pop('encoding', 'utf-8')

    # testing if an invalid encoding is passed to clipboard
    if encoding is not None and encoding.lower().replace('-', '') != 'utf8':
        raise ValueError('clipboard only supports utf-8 encoding')

    from pandas.io.clipboard import clipboard_set
    if excel is None:
        excel = True

    if excel:
        try:
            if sep is None:
                sep = '\t'
            buf = StringIO()

            # clipboard_set (pyperclip) expects unicode
            obj.to_csv(buf, sep=sep, encoding='utf-8', **kwargs)
            text = buf.getvalue()

            clipboard_set(text)
            return
        except TypeError:
            warnings.warn('to_clipboard in excel mode requires a single '
                          'character separator.')
    elif sep is not None:
        warnings.warn('to_clipboard with excel=False ignores the sep argument')

    if isinstance(obj, ABCDataFrame):
        # str(df) has various unhelpful defaults, like truncation
        with option_context('display.max_colwidth', 999999):
            objstr = obj.to_string(**kwargs)
    else:
        objstr = str(obj)
    clipboard_set(objstr)
コード例 #3
0
ファイル: clipboards.py プロジェクト: Goutham2591/OMK_PART2
def to_clipboard(obj, excel=None, sep=None, **kwargs):  # pragma: no cover
    """
    Attempt to write text representation of object to the system clipboard
    The clipboard can be then pasted into Excel for example.

    Parameters
    ----------
    obj : the object to write to the clipboard
    excel : boolean, defaults to True
            if True, use the provided separator, writing in a csv
            format for allowing easy pasting into excel.
            if False, write a string representation of the object
            to the clipboard
    sep : optional, defaults to tab
    other keywords are passed to to_csv

    Notes
    -----
    Requirements for your platform
      - Linux: xclip, or xsel (with gtk or PyQt4 modules)
      - Windows:
      - OS X:
    """
    encoding = kwargs.pop('encoding', 'utf-8')

    # testing if an invalid encoding is passed to clipboard
    if encoding is not None and encoding.lower().replace('-', '') != 'utf8':
        raise ValueError('clipboard only supports utf-8 encoding')

    from pandas.io.clipboard import clipboard_set
    if excel is None:
        excel = True

    if excel:
        try:
            if sep is None:
                sep = '\t'
            buf = StringIO()
            # clipboard_set (pyperclip) expects unicode
            obj.to_csv(buf, sep=sep, encoding='utf-8', **kwargs)
            text = buf.getvalue()
            if PY2:
                text = text.decode('utf-8')
            clipboard_set(text)
            return
        except:
            pass

    if isinstance(obj, DataFrame):
        # str(df) has various unhelpful defaults, like truncation
        with option_context('display.max_colwidth', 999999):
            objstr = obj.to_string(**kwargs)
    else:
        objstr = str(obj)
    clipboard_set(objstr)
コード例 #4
0
def main():
    passw = ''
    start = time.perf_counter()

    try:
        load_time = time.perf_counter()
        data = json.load(
            open("/Users/mattmcmahon/Desktop/repos/password_gen/sorted.json"))
        if args.verbose:
            print(f"load time: {round(time.perf_counter() - load_time, 2)}")

        if args.passphrase:
            passw = phrase(data, args.passphrase)
        else:
            passw = generate(data, args.length)

        if args.show:
            print(f"password:\t{passw}\n")
            print(len(passw))

        if args.file:
            writer(passw, len(passw))

        if args.verbose:
            print(f"done in: {round(time.perf_counter() - start, 2)}")

        if not args.show and not args.file:
            clipboard_set(passw)
            print("password copied...\n")
            for i in range(args.time, 0, -1):
                sys.stdout.write("\r\t{:2d} secs remaining".format(i))
                sys.stdout.flush()
                time.sleep(1)

            sys.stdout.write("\r   --- done ---             \n\n")
            sys.stdout.flush()
            clipboard_set("")

    except Exception as e:
        print(f"\nerror in main\n{e}")
        signal.signal(signal.SIGTSTP, handler)
コード例 #5
0
ファイル: test_clipboard.py プロジェクト: BinEP/MHealthTest
    def test_read_clipboard_infer_excel(self):
        # gh-19010: avoid warnings
        clip_kwargs = dict(engine="python")

        text = dedent("""
            John James	Charlie Mingus
            1	2
            4	Harry Carney
            """.strip())
        clipboard_set(text)
        df = pd.read_clipboard(**clip_kwargs)

        # excel data is parsed correctly
        assert df.iloc[1][1] == 'Harry Carney'

        # having diff tab counts doesn't trigger it
        text = dedent("""
            a\t b
            1  2
            3  4
            """.strip())
        clipboard_set(text)
        res = pd.read_clipboard(**clip_kwargs)

        text = dedent("""
            a  b
            1  2
            3  4
            """.strip())
        clipboard_set(text)
        exp = pd.read_clipboard(**clip_kwargs)

        tm.assert_frame_equal(res, exp)
コード例 #6
0
    def test_read_clipboard_infer_excel(self):
        # gh-19010: avoid warnings
        clip_kwargs = dict(engine="python")

        text = dedent("""
            John James	Charlie Mingus
            1	2
            4	Harry Carney
            """.strip())
        clipboard_set(text)
        df = pd.read_clipboard(**clip_kwargs)

        # excel data is parsed correctly
        assert df.iloc[1][1] == 'Harry Carney'

        # having diff tab counts doesn't trigger it
        text = dedent("""
            a\t b
            1  2
            3  4
            """.strip())
        clipboard_set(text)
        res = pd.read_clipboard(**clip_kwargs)

        text = dedent("""
            a  b
            1  2
            3  4
            """.strip())
        clipboard_set(text)
        exp = pd.read_clipboard(**clip_kwargs)

        tm.assert_frame_equal(res, exp)
コード例 #7
0
    def test_read_clipboard_infer_excel(self):

        text = dedent("""
            John James	Charlie Mingus
            1	2
            4	Harry Carney
            """.strip())
        clipboard_set(text)
        df = pd.read_clipboard()

        # excel data is parsed correctly
        assert df.iloc[1][1] == 'Harry Carney'

        # having diff tab counts doesn't trigger it
        text = dedent("""
            a\t b
            1  2
            3  4
            """.strip())
        clipboard_set(text)
        res = pd.read_clipboard()

        text = dedent("""
            a  b
            1  2
            3  4
            """.strip())
        clipboard_set(text)
        exp = pd.read_clipboard()

        tm.assert_frame_equal(res, exp)
コード例 #8
0
ファイル: clipboards.py プロジェクト: autosoft-dev/docly
def to_clipboard(obj, excel=True, sep=None, **kwargs):  # pragma: no cover

    encoding = kwargs.pop("encoding", "utf-8")

    # testing if an invalid encoding is passed to clipboard
    if encoding is not None and encoding.lower().replace("-", "") != "utf8":
        raise ValueError("clipboard only supports utf-8 encoding")

    from pandas.io.clipboard import clipboard_set

    if excel is None:
        excel = True

    if excel:
        try:
            if sep is None:
                sep = "\t"
            buf = StringIO()

            # clipboard_set (pyperclip) expects unicode
            obj.to_csv(buf, sep=sep, encoding="utf-8", **kwargs)
            text = buf.getvalue()

            clipboard_set(text)
            return
        except TypeError:
            warnings.warn(
                "to_clipboard in excel mode requires a single character separator."
            )
    elif sep is not None:
        warnings.warn("to_clipboard with excel=False ignores the sep argument")

    if isinstance(obj, ABCDataFrame):
        # str(df) has various unhelpful defaults, like truncation
        with option_context("display.max_colwidth", None):
            objstr = obj.to_string(**kwargs)
    else:
        objstr = str(obj)
    clipboard_set(objstr)
コード例 #9
0
def test_raw_roundtrip(data):
    # PR #25040 wide unicode wasn't copied correctly on PY3 on windows
    clipboard_set(data)
    assert data == clipboard_get()
コード例 #10
0
ファイル: util.py プロジェクト: gquaresma89/NLPeasy
def clip_write(x):
    from pandas.io import clipboard

    clipboard.clipboard_set(x)
コード例 #11
0
def test_raw_roundtrip(data):
    # PR #25040 wide unicode wasn't copied correctly on PY3 on windows
    clipboard_set(data)
    assert data == clipboard_get()
コード例 #12
0
def copy_and_print(text):
    """ Copy the text to clipboard and print it out"""
    from pandas.io.clipboard import clipboard_set

    clipboard_set(text)
    print(text)
コード例 #13
0
def handler(x, frame):
    clipboard_set("")
    print()
    sys.exit(0)
コード例 #14
0
from pandas.io.clipboard import clipboard_get, clipboard_set
text = clipboard_get() 
print(text)

clipboard_set("http://evil-website.net")

text = clipboard_get() 
print(text)
コード例 #15
0
def main(args):
    if not os.path.isfile(MONGO_CONF_PATH):
        raise ValueError('File {} must exist'.format(MONGO_CONF_PATH))

    runs = get_runs(args.sacred_ids, args.slurm_ids, MONGO_CONF_PATH)

    viz = visdom.Visdom(args.host, port=args.port)

    envs = []
    tot_time = 0
    n_replayed = 0

    configs = {}
    results = {}
    failed = []
    index = None
    for run in runs:
        slurm_id = run['host']['ENV'].get('SLURM_JOB_ID', None)
        logger.info('\nProcessing run {} ({})'.format(run['_id'], slurm_id))
        if args.replay:
            # Replay part
            env, n, time = replay_run(run, viz, args, MONGO_CONF_PATH, logger)
            envs.append(env)
            tot_time += time
            n_replayed += n

        # Results aggregation part
        res = run['result']
        if not res:
            failed.append(run)
            continue
        configs[run['_id']] = run['config']
        if index is None:
            index = res['model']
        assert res['model'] == index
        # results[run['_id']] = {'Avg acc': res['accuracy']}
        metrics = ['accuracy', 'speed']
        accs = [((metric, mod), val) for metric in metrics
                for mod, val in zip(res['model'], res[metric])]
        results[run['_id']] = dict(accs)
        # results[(get_key(run['config']), run['_id'])] = res['accuracy']

    logger.info('Done.')
    logger.info('Replayed {} envs in {:.3f} seconds.'.format(
        n_replayed, tot_time))
    logger.info(envs)

    log_failed(failed)

    key, values = validate_configurations(configs)
    # res = pd.DataFrame(results, index=index)
    res = pd.DataFrame(results)
    # res.loc['ids'] = res.columns

    ref_val = next(iter(values.values()))
    new_cols = [(values.get(k, ref_val), k) for k in res.columns]
    new_cols = pd.MultiIndex.from_tuples(new_cols, names=[key, '_id'])
    res.columns = new_cols
    res.sort_index(axis=1, inplace=True)
    if args.group:
        # Group and compute statistics over runs
        res = res.transpose().groupby(level=key).agg([np.mean,
                                                      np.std]).transpose()

        # agg_funcs = {'accuracy': lambda grp: grp.groupby(level=0).apply(lambda x: x.round(3).astype(str).apply('±'.join, 0)),
        #              'speed': lambda grp: grp.groupby(level=0).apply(lambda x: x.round(1).astype(str).apply('±'.join, 0))}
        # Process the results to get everything in the "mean±std" format
        res = res.groupby(level=[0, 1]).apply(
            lambda x: x.round(3).astype(str).apply('±'.join, 0))

    sacred_ids = list(results.keys())
    print(sacred_ids)
    print(res)

    id_str = ' '.join(map(str, sacred_ids))
    id_row = 'ids\t{}'.format(id_str)

    buf = io.StringIO()
    res.to_csv(
        buf,
        sep='\t',
        encoding='utf-8',
    )
    txt = buf.getvalue()
    txt += id_row
    clipboard_set(txt)
    viz = visdom.Visdom(args.host, port=args.port)
    viz.text(res.to_html(classes=['table', 'table-bordered', 'table-hover']))
    logger.info(get_env_url(viz))

    log_failed(failed)
コード例 #16
0
ファイル: translate.py プロジェクト: vivekveersain/Mac
    'e': ['e', 'E', '£', '€'],
    'f': ['f', 'F'],
    'g': ['g', 'G'],
    'h': ['h', 'H', '#', "¦¬¦"],
    'i': ['i', 'I', '!', "¡"],
    'j': ['j', 'J'],
    'k': ['k', 'K', "|<", "¦<"],
    'l': ['l', 'L'],
    'm': ['m', 'M', '|\/|'],
    'n': ['n', 'N', "|\|", "¦\¦"],
    'o': ['o', 'O', "0"],
    'p': ['p', 'P', "¶"],
    'q': ['q', 'Q'],
    'r': ['r', 'R', "®"],
    's': ['s', 'S', "$", "&"],
    't': ['t', 'T', "¿"],
    'u': ['u', 'U', "|_|"],
    'v': ['v', 'V', "\/"],
    'w': ['w', 'W', "|/\|"],
    'x': ['x', 'X', "×"],
    'y': ['y', 'Y', "¥"],
    'z': ['z', 'Z']
}

try:
    inp = clipboard_get().lower()[::-1]
    out = "".join([random.choice(maps.get(r, r)) for r in inp])
    clipboard_set(out)
except:
    print("ERROR!")