SnippetVamp

Because spending time searching snippets sucks.



ALV 3 XPath 1 abap 9 ahk 1 autohotkey 6 bash 2 cli 2 clipboard 3 excel 1 file 1 file_path 1 greasemonkey 1 javascript 1 python 4 sap 1 screen 1 sql 1 ssh 1 tool 2 tunnel 1

.

last

Welcome to my SnippetVamp space !

OpenSQL (SAP) aggregates

* Récupérer les <id> qui ont plus d'un <code> distinct.

  SELECT id COUNT( DISTINCT code ) FROM zmy_table INTO TABLE wlt_plop
    GROUP BY id
    HAVING COUNT( DISTINCT code ) > 1.

sql abap

<iframe width="100%" height="272" src="http://ginkobox.fr/vamp/index.php?embed=569cf482ea7de" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 18/01/2016

ZDYN_CODE

REPORT zdyn_code.

DATA : wlt_code TYPE TABLE OF char256,
      wlv_line LIKE LINE OF wlt_code,
      wlv_prog TYPE char08,
      wlv_msg  TYPE char120,
      wlv_lin  TYPE char03,
      wlv_wrd  TYPE char10,
      wlv_off  TYPE char03.

wlv_line = 'PROGRAM SUBPOOL.'.
APPEND wlv_line TO wlt_code.

wlv_line = 'FORM f1.'.
APPEND wlv_line TO wlt_code.

wlv_line = ''.
APPEND wlv_line TO wlt_code.
APPEND wlv_line TO wlt_code.
APPEND wlv_line TO wlt_code.

wlv_line = 'BREAK-POINT.'.
APPEND wlv_line TO wlt_code.

wlv_line = ''.
APPEND wlv_line TO wlt_code.

wlv_line = 'ENDFORM.'.
APPEND wlv_line TO wlt_code.

DO.

  EDITOR-CALL FOR wlt_code.
  IF sy-subrc = 4.
    EXIT.
  ENDIF.

  GENERATE SUBROUTINE POOL wlt_code NAME wlv_prog
  MESSAGE wlv_msg
  LINE    wlv_lin
  WORD    wlv_wrd
  OFFSET  wlv_off.
  IF sy-subrc <> 0.
    MESSAGE i000(z_interfaces) WITH wlv_lin wlv_msg wlv_wrd wlv_off.
  ELSE.
    PERFORM f1 IN PROGRAM (wlv_prog).
    EXIT.
  ENDIF.
ENDDO.

abap

<iframe width="100%" height="1064" src="http://ginkobox.fr/vamp/index.php?embed=569cf44de8454" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 18/01/2016

ALV in container (container can be defined from screen painter as a custom control)

  DATA: alv TYPE REF TO cl_salv_table,
        lo_functions TYPE REF TO cl_salv_functions_list.

  DATA: wgr_container TYPE REF TO cl_gui_custom_container.

  IF wgr_container IS NOT BOUND.
    IF cl_salv_table=>is_offline( ) EQ if_salv_c_bool_sap=>false.
      CREATE OBJECT wgr_container
        EXPORTING
          container_name = 'WGC_CONTAINER_PLOP'.
    ENDIF.

    TRY.
        cl_salv_table=>factory(
           EXPORTING r_container    = wgr_container
             container_name = 'WGC_CONTAINER_PLOP'
           IMPORTING r_salv_table = alv
           CHANGING  t_table = wgt_plop ).

        lo_functions = alv->get_functions( ).
        lo_functions->set_all( abap_true ).

        alv->display( ).
      CATCH cx_salv_msg.
        MESSAGE 'ALV display not possible' TYPE 'I'
        DISPLAY LIKE 'E'.
    ENDTRY.
  ENDIF.

ALV abap screen

<iframe width="100%" height="686" src="http://ginkobox.fr/vamp/index.php?embed=567a702c55983" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 23/12/2015

ALV handlers

PROGRAM zkmalve2.

DATA:
  gt_usr   TYPE TABLE OF usr02,
  gs_usr   TYPE usr02.

*----------------------------------------------------------------------*
*       CLASS cl_event_handler DEFINITION
*----------------------------------------------------------------------*
CLASS cl_event_handler DEFINITION.

  PUBLIC SECTION.

    CLASS-METHODS on_before_salv_function         " BEFORE_SALV_FUNCTION
      FOR EVENT if_salv_events_functions~before_salv_function
        OF cl_salv_events_table
          IMPORTING e_salv_function.

    CLASS-METHODS on_after_salv_function          " AFTER_SALV_FUNCTION
      FOR EVENT if_salv_events_functions~before_salv_function
        OF cl_salv_events_table
          IMPORTING e_salv_function.

    CLASS-METHODS on_added_function               " ADDED_FUNCTION
      FOR EVENT if_salv_events_functions~added_function
        OF cl_salv_events_table
          IMPORTING e_salv_function.

    CLASS-METHODS on_top_of_page                  " TOP_OF_PAGE
      FOR EVENT if_salv_events_list~top_of_page
        OF cl_salv_events_table
          IMPORTING r_top_of_page
                    page
                    table_index.

    CLASS-METHODS on_end_of_page                  " END_OF_PAGE
      FOR EVENT if_salv_events_list~end_of_page
        OF cl_salv_events_table
          IMPORTING r_end_of_page
                    page.

    CLASS-METHODS on_double_click                 " DOUBLE_CLICK
      FOR EVENT if_salv_events_actions_table~double_click
        OF cl_salv_events_table
          IMPORTING row
                    column.

    CLASS-METHODS on_link_click                   " LINK_CLICK
      FOR EVENT if_salv_events_actions_table~link_click
        OF cl_salv_events_table
          IMPORTING row
                    column.
ENDCLASS.                    "cl_event_handler DEFINITION

*----------------------------------------------------------------------*
*       CLASS cl_event_handler IMPLEMENTATION
*----------------------------------------------------------------------*
CLASS cl_event_handler IMPLEMENTATION.

  METHOD on_before_salv_function.
    BREAK-POINT.
  ENDMETHOD.                    "on_before_salv_function

  METHOD on_after_salv_function.
    BREAK-POINT.
  ENDMETHOD.                    "on_after_salv_function

  METHOD on_added_function.
    BREAK-POINT.
  ENDMETHOD.                    "on_added_function

  METHOD on_top_of_page.
    BREAK-POINT.
  ENDMETHOD.                    "on_top_of_page

  METHOD on_end_of_page.
    BREAK-POINT.
  ENDMETHOD.                    "on_end_of_page

  METHOD on_double_click.
    BREAK-POINT.
  ENDMETHOD.                    "on_double_click

  METHOD on_link_click.
    BREAK-POINT.
  ENDMETHOD.                    "on_link_click
ENDCLASS.                    "cl_event_handler IMPLEMENTATION

*&---------------------------------------------------------------------*
*&      START-OF-SELECTION
*&---------------------------------------------------------------------*
START-OF-SELECTION.

* read sample data to internal table
  SELECT * FROM usr02 UP TO 30 ROWS
    APPENDING CORRESPONDING FIELDS OF TABLE gt_usr
    ORDER BY bname.

  PERFORM display_alv.

*&---------------------------------------------------------------------*
*&      Form  display_alv
*&---------------------------------------------------------------------*
FORM display_alv.

  DATA:
    lo_table      TYPE REF TO cl_salv_table,
    lo_events     TYPE REF TO cl_salv_events_table,
    lo_columns    TYPE REF TO cl_salv_columns_table,
    lo_column     TYPE REF TO cl_salv_column_list.

  TRY.
      CALL METHOD cl_salv_table=>factory
        IMPORTING
          r_salv_table = lo_table
        CHANGING
          t_table      = gt_usr.

      lo_events = lo_table->get_event( ).
      SET HANDLER cl_event_handler=>on_before_salv_function FOR lo_events.
      SET HANDLER cl_event_handler=>on_after_salv_function FOR lo_events.
      SET HANDLER cl_event_handler=>on_added_function FOR lo_events.
      SET HANDLER cl_event_handler=>on_top_of_page FOR lo_events.
      SET HANDLER cl_event_handler=>on_end_of_page FOR lo_events.
      SET HANDLER cl_event_handler=>on_double_click FOR lo_events.
      SET HANDLER cl_event_handler=>on_link_click FOR lo_events.

*     ALV-Toolbar
      lo_table->set_screen_status(
        pfstatus      = 'STANDARD_FULLSCREEN'
        report        = 'SAPLSLVC_FULLSCREEN'
        set_functions = lo_table->c_functions_all ).

*     Set column as hotspot
      lo_columns = lo_table->get_columns( ).
      lo_column ?= lo_columns->get_column( 'BNAME' ).
      lo_column->set_cell_type( if_salv_c_cell_type=>hotspot ).

      lo_table->display( ).

    CATCH cx_salv_msg.             " cl_salv_table=>factory()
      WRITE: / 'cx_salv_msg exception'.
      STOP.
    CATCH cx_salv_not_found.       " cl_salv_columns_table->get_column()
      WRITE: / 'cx_salv_not_found exception'.
      STOP.
  ENDTRY.
ENDFORM.                    "display_alv

ALV abap

http://www.kerum.pl/infodepot/00007

<iframe width="100%" height="2846" src="http://ginkobox.fr/vamp/index.php?embed=5678114ad7fc9" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 21/12/2015

Création de range à partir de table interne

FUNCTION zcreate_range.
*"----------------------------------------------------------------------
*"*"Interface locale :
*"  IMPORTING
*"     REFERENCE(I_FIELDNAME) TYPE  CHAR30
*"  TABLES
*"      IT_TABLE
*"      ET_RANGE
*"----------------------------------------------------------------------
************************************************************************
* Description : A module function capable of building a range from     *
* any table !!!                                                        *
************************************************************************

  FIELD-SYMBOLS : <ls_value> TYPE any,
                  <fieldname> TYPE any,
                  <ls_range> TYPE any,
                  <lit_range> TYPE STANDARD TABLE,
                  <ls_table> TYPE any.

  ASSIGN i_fieldname TO <fieldname>.
  ASSIGN et_range[] TO <lit_range>[].
  ASSIGN et_range TO <ls_range>.

  LOOP AT it_table ASSIGNING <ls_table>.
    ASSIGN COMPONENT <fieldname> OF STRUCTURE <ls_table> TO <ls_value>.
    <ls_range>(3) = 'IEQ'.
    <ls_range>+3 = <ls_value>.
    APPEND <ls_range> TO  <lit_range>.
  ENDLOOP.

  SORT <lit_range>.
  DELETE ADJACENT DUPLICATES FROM <lit_range>.

ENDFUNCTION.

abap

<iframe width="100%" height="812" src="http://ginkobox.fr/vamp/index.php?embed=55f19a2b6623c" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 10/09/2015

Circle through list

class CircleList(list):
    """A list to circle throught""" # itertools.circle only goes one way
    def __init__(self, l, i=0, stop=None):
        super(CircleList, self).__init__(l)
        self.i = i
        self.stop = stop
    def current(self):
        return self[self.i]
    def previous(self):
        self.i -= 1
        if self.i < 0:
            self.i = 0 if self.stop else len(self)-1
        return self[self.i]
    def next(self):
        self.i += 1
        if self.i > len(self)-1:
            self.i = len(self)-1 if self.stop else 0
        return self[self.i]

python

<iframe width="100%" height="506" src="http://ginkobox.fr/vamp/index.php?embed=55c51d182921a" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 07/08/2015

Get tab-separated tabular data from clipboard and parse it

TYPES:
  BEGIN OF ty_clipdata,
    data TYPE c LENGTH 500,
  END   OF ty_clipdata.
DATA: lt_clipdata TYPE STANDARD TABLE OF ty_clipdata.
DATA: ls_clipdata LIKE LINE OF lt_clipdata.
DATA: lv_clip_len TYPE i.
CONSTANTS: c_tab  TYPE c VALUE cl_bcs_convert=>gc_tab.

DATA: lt_record TYPE STANDARD TABLE OF ty_clipdata.
DATA: ls_record LIKE LINE OF lt_record.
FIELD-SYMBOLS: <lfs_field> TYPE any.

TYPES: BEGIN OF lty_agr,
          myfield1 TYPE myfield,
      myfield2 TYPE urfield,
         END OF lty_agr.
DATA: lt_data TYPE STANDARD TABLE OF lty_agr,
      ls_data TYPE lty_agr,
      lt_agr_db TYPE STANDARD TABLE OF lty_agr.
FIELD-SYMBOLS: <lfs_data>  LIKE LINE OF lt_data.

*&---------------------------------------------------------------------*
*&      Form  GET_CLIP_DATA
*&---------------------------------------------------------------------*
*       Get tab-separated tabular data from clipboard and parse it
*----------------------------------------------------------------------*
FORM get_clip_data .
* --- Get clipboard ---
  cl_gui_frontend_services=>clipboard_import(
    IMPORTING
       data                 = lt_clipdata
       length               = lv_clip_len
     EXCEPTIONS
       cntl_error           = 1
       error_no_gui         = 2
       not_supported_by_gui = 3
       OTHERS               = 4 ).
  IF sy-subrc NE 0.
    MESSAGE 'Error while importing data from clipboard' TYPE 'E'.
  ENDIF.

* --- Parse data ---
  LOOP AT lt_clipdata INTO ls_clipdata.
    SPLIT ls_clipdata AT c_tab INTO TABLE lt_record.
    " SPE >>>
    IF lt_record[ 1 ]-data(2) <> 'ZS'. " Your filter
      CONTINUE.
    ENDIF.
    " <<< SPE
    APPEND INITIAL LINE TO lt_data ASSIGNING <lfs_data>.
    LOOP AT lt_record INTO ls_record.
      ASSIGN COMPONENT sy-tabix OF STRUCTURE <lfs_data> TO <lfs_field>.
      IF sy-subrc EQ 0.
        <lfs_field> = ls_record-data.
      ENDIF.
    ENDLOOP.
  ENDLOOP.
  IF lt_data[] IS INITIAL.
    MESSAGE 'No data parsed from clipboard' TYPE 'E'.
  ENDIF.

ENDFORM.                    " GET_CLIP_DATA

abap clipboard

<iframe width="100%" height="1316" src="http://ginkobox.fr/vamp/index.php?embed=555b6d0abd678" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 19/05/2015

Display any itab in ALV

*&---------------------------------------------------------------------*
*&      Form  write_out
*&---------------------------------------------------------------------*
*       List output
*----------------------------------------------------------------------*
FORM write_out USING p_table. "With inline declaration abap 740
  DATA: alv     TYPE REF TO cl_salv_table.
  TRY.
      cl_salv_table=>factory(
        IMPORTING r_salv_table = alv
        CHANGING  t_table = p_table ).

      DATA(lo_functions) = alv->get_functions( ).
      lo_functions->set_all( abap_true ).

      alv->display( ).
    CATCH cx_salv_msg.
      MESSAGE 'ALV display not possible' TYPE 'I'
              DISPLAY LIKE 'E'.
  ENDTRY.
ENDFORM.                    "write_out
*&---------------------------------------------------------------------*
*&      Form  write_out
*&---------------------------------------------------------------------*
*       List output
*----------------------------------------------------------------------*
FORM write_out USING p_table. "Without inline declaration
  DATA: alv TYPE REF TO cl_salv_table,
        lo_functions TYPE REF TO cl_salv_functions_list.

  TRY.
      cl_salv_table=>factory(
        IMPORTING r_salv_table = alv
        CHANGING  t_table = p_table ).

      lo_functions = alv->get_functions( ).
      lo_functions->set_all( abap_true ).

      alv->display( ).
    CATCH cx_salv_msg.
      MESSAGE 'ALV display not possible' TYPE 'I'
              DISPLAY LIKE 'E'.
  ENDTRY.
ENDFORM.                    "write_out

ALV abap

<iframe width="100%" height="974" src="http://ginkobox.fr/vamp/index.php?embed=555b6c66366cf" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 10/09/2015

ABAP Pattern translation

* Translate pattern from GUI to OpenSQL (* -> % ; + -> _)
TRANSLATE p_obj USING '*%+_'.

abap

<iframe width="100%" height="218" src="http://ginkobox.fr/vamp/index.php?embed=555b6bee444d0" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 19/05/2015

AHK : grep da clipboard

#g:: ; Msc : Grep clipboard
Result =
InputBox, MatchVal, Grep Da Clipboard, Ur match!
Loop, Parse, clipboard, `r, `n
{
    if ( RegExMatch( A_LoopField, MatchVal) > 0)
        Result .= A_LoopField "`r`n"
}
Clipboard := Result
return

ahk clipboard

<iframe width="100%" height="362" src="http://ginkobox.fr/vamp/index.php?embed=5526919497998" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 09/04/2015

AHK : Parse data from excel (ignore empty rows and cells)

Buffer := clipboard
Loop, parse, Buffer,`n, `r
{
    if not A_LoopField
        continue
    Loop, parse, A_LoopField, `t
    {
        if not A_LoopField
            continue
        if (A_Index <> 1)
            Send {tab}
        Clipboard = %A_LoopField%
        Send ^v
    }
    Send `n
}
Clipboard := Buffer

excel autohotkey

<iframe width="100%" height="488" src="http://ginkobox.fr/vamp/index.php?embed=55005dfa5c93a" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 11/03/2015

AHK : Add program to startup

; Create shortcut (if it exists already, will be overwritten)
FileCreateShortcut, %A_WorkingDir%\vpn.exe, %A_Startup%\vpn.exe.lnk

autohotkey

<iframe width="100%" height="218" src="http://ginkobox.fr/vamp/index.php?embed=54ff074cc93a4" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 10/03/2015

AHK : Run Window Spy

#F2:: Run "C:\Program Files\AutoHotkey\AU3_Spy.exe" ; Sfl : Run Window Spy

autohotkey

<iframe width="100%" height="200" src="http://ginkobox.fr/vamp/index.php?embed=54fef8f05ac32" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 10/03/2015

AHK : WaitForImage

WaitForImage(ByRef pic, ByRef windowRef, ByRef timeout)
{
coordmode, pixel, screen
WinGetPos, winX, winY, winWidth, winHeight, %windowRef%
waitVal = 100
count = 0
maxIter := timeout / waitVal
while count < maxIter
{
    IfWinNotActive, %windowRef%
        WinActivate, %windowRef%
    ImageSearch, imageX, imageY, winX, winY, winX+winWidth, winY+winHeight, %pic%
    if not ErrorLevel   ; Found !
    {
        coordmode, pixel, Relative
        return true
    }
    Sleep waitVal
    count += 1
}
coordmode, pixel, Relative
return false
}

autohotkey

<iframe width="100%" height="596" src="http://ginkobox.fr/vamp/index.php?embed=54fdd9eca61f7" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 09/03/2015

AHK : SelfReload

~^s:: ; Slf : Reload script on save
WinGetActiveTitle, Reload
    If InStr(Reload, "myscript.ahk")
        Reload
Return

autohotkey

<iframe width="100%" height="272" src="http://ginkobox.fr/vamp/index.php?embed=54fdd95a9b3ec" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 09/03/2015

AHK : FileRewrite

FileRewrite(ByRef FileName) ; Store clipoard content in file
{
Send ^c
ClipWait
FileDelete, %FileName%
FileAppend , %clipboard%, %FileName%
}

autohotkey

<iframe width="100%" height="308" src="http://ginkobox.fr/vamp/index.php?embed=54fdd91418ec2" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 09/03/2015

ZSPLIT_WIN_FILE_PATH

FUNCTION zsplit_win_file_path.
*"----------------------------------------------------------------------
*"*"Local Interface:
*"  IMPORTING
*"     REFERENCE(I_PATH) TYPE  STRING
*"  EXPORTING
*"     REFERENCE(E_DIRECTORY) TYPE  STRING
*"     REFERENCE(E_FILENAME) TYPE  STRING
*"     REFERENCE(E_EXTENSION) TYPE  STRING
*"----------------------------------------------------------------------

  CONSTANTS c_sep TYPE char1 VALUE '\'.

  SPLIT i_path AT c_sep INTO TABLE DATA(lt_elms).
  DESCRIBE TABLE lt_elms LINES DATA(lv_len).
  READ TABLE lt_elms INDEX lv_len INTO e_filename.
  DELETE lt_elms INDEX lv_len.

  SPLIT e_filename AT '.' INTO TABLE DATA(lt_name_elms).
  DESCRIBE TABLE lt_name_elms LINES DATA(lv_name_len).
  READ TABLE lt_name_elms INDEX lv_name_len INTO e_extension.

  CONCATENATE LINES OF lt_elms INTO e_directory SEPARATED BY c_sep.

ENDFUNCTION.

file_path abap sap

<iframe width="100%" height="632" src="http://ginkobox.fr/vamp/index.php?embed=54c7b5262e606" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 27/01/2015

Gorafi comment order reverser

// ==UserScript==
// @name                Gorafi comment sorter
// @namespace       Plop Corp
// @author               Ginko Aloe
// @licence              CC BY 3.0 - http://creativecommons.org/licenses/by/3.0/
// @description         Sort Gorafi comment chronologically
// @include             http://www.legorafi.fr/*
// @version             1
// @grant               none
// ==/UserScript==

// NB : I think this script should work on many wordpress-powered sites (since legorafi is one of them). Feel free to fork it, this work is under CC By.

function getNode(xpathStmt, node) {
    return document.evaluate( xpathStmt, node, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue;
}

// Get comment nodes
var ol = getNode("//ol[@class='commentlist']", document);
var li = ol.getElementsByClassName('depth-1');

// Build new comment list
var new_ol = document.createElement('ol');
new_ol.className = 'commentlist';
 
var parent = ol.parentNode;

// Copy list elements beginning from the last to the new list
for(var i=li.length - 1; i >= 0 ; i--)    {
    new_ol.appendChild(li[i]);
 }
 
 // Inject the new list and remove the old one
parent.insertBefore(new_ol, ol);
parent.removeChild(ol)

XPath greasemonkey javascript

<iframe width="100%" height="812" src="http://ginkobox.fr/vamp/index.php?embed=54c67287a1928" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 26/01/2015

Translate clipboard content on Windows unsing Google Translate

#!/bin/python
# -*- coding: utf-8 -*-

"""Translate clipboard content on Windows unsing Google Translate"""

# Author : Ginko
# Date : 08/01/2015
# Version : 0.1.a
# License : zlib/libpng

# The zlib/libpng License

# Copyright (c) 2015 Ginko Aloe - ginkobox.fr

# This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.
# Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
#     1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
#     2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
#     3. This notice may not be removed or altered from any source distribution.

# goslate module from http://pythonhosted.org/goslate/
# Clip object inspired from https://stackoverflow.com/a/25678113

# Example usage (from cmd.exe): C:\pathTo\python.exe C:\path\to\translate.py en

import ctypes, sys
import goslate

class Clip(object):
    def __init__(self):
        
        self.wcscpy = ctypes.cdll.msvcrt.wcscpy

        self.OpenClipboard = ctypes.windll.user32.OpenClipboard
        self.EmptyClipboard = ctypes.windll.user32.EmptyClipboard
        self.GetClipboardData = ctypes.windll.user32.GetClipboardData
        self.SetClipboardData = ctypes.windll.user32.SetClipboardData
        self.CloseClipboard = ctypes.windll.user32.CloseClipboard
        self.CF_UNICODETEXT = 13

        self.GlobalAlloc = ctypes.windll.kernel32.GlobalAlloc
        self.GlobalLock = ctypes.windll.kernel32.GlobalLock
        self.GlobalUnlock = ctypes.windll.kernel32.GlobalUnlock
        self.GMEM_DDESHARE = 0x2000 

    def get(self):
        self.OpenClipboard(None)
        handle = self.GetClipboardData(self.CF_UNICODETEXT)
        data = ctypes.c_wchar_p(handle).value
        pcontents = self.GlobalLock(handle)
        data = ctypes.c_wchar_p(pcontents).value if pcontents else u''
        self.GlobalUnlock(handle)
        self.CloseClipboard()
        return data

    def put(self, data):
        # if not isinstance(data, unicode):
            # data = data.decode('mbcs')
        self.OpenClipboard(None)
        self.EmptyClipboard()
        hCd = self.GlobalAlloc(self.GMEM_DDESHARE, 2 * (len(data) + 1))
        pchData = self.GlobalLock(hCd)
        self.wcscpy(ctypes.c_wchar_p(pchData), data)
        self.GlobalUnlock(hCd)
        self.SetClipboardData(self.CF_UNICODETEXT, hCd)
        self.CloseClipboard()
    
def main():
    clip = Clip()
    gs = goslate.Goslate()
    lang = sys.argv[1] if len(sys.argv) > 1 else 'fr'
    c = gs.translate(clip.get(), lang)
    clip.put(c)

if __name__ == "__main__":
    main()

clipboard python

<iframe width="100%" height="1550" src="http://ginkobox.fr/vamp/index.php?embed=54aec9f2a1d9d" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 08/01/2015

fastRename, a tiny tiny tool to replace spaces in file names by other strings

#!/usr/bin/python
# -*- encoding:utf-8 -*-

"""fastRename, a tiny tiny tool to replace strings in file names by other strings"""

# Author : Ginko
# Date : 02/01/2015
# Version : 0.1.a
# License : zlib/libpng

# The zlib/libpng License

# Copyright (c) 2015 Ginko Aloe - ginkobox.fr

# This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.
# Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
#     1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
#     2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
#     3. This notice may not be removed or altered from any source distribution.

import os, sys

if len(sys.argv) < 4:
    print("***{}***\n\nUsage: {} <from> <to> filenames ...".format(__doc__, sys.argv[0]))
else:
    for f in sys.argv[2:]:
        os.rename(f, f.replace(sys.argv[1], sys.argv[2]))

cli file python tool

<iframe width="100%" height="668" src="http://ginkobox.fr/vamp/index.php?embed=54a70f58f3451" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 02/01/2015

pix0meter

#!/usr/bin/python
# -*- encoding:utf-8 -*-

"""pixOmeter, a tiny tool to calculate sizes in mm and px and definition in dpi"""

# Author : Ginko
# Date : 31/12/2014
# Version : 0.1.a
# License : zlib/libpng

# The zlib/libpng License

# Copyright (c) 2014 Ginko Aloe - ginkobox.fr

# This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.
# Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
#     1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
#     2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
#     3. This notice may not be removed or altered from any source distribution.

ISO_formats = {'A0': (841, 1189), # from https://en.wikipedia.org/wiki/ISO_216
'B0': (1000, 1414), 
'A1': (594, 841), 
'B1': (707, 1000), 
'A2': (420, 594), 
'B2': (500, 707), 
'A3': (297, 420), 
'B3': (353, 500), 
'A4': (210, 297), 
'B4': (250, 353), 
'A5': (148, 210), 
'B5': (176, 250), 
'A6': (105, 148), 
'B6': (125, 176), 
'A7': (74, 105), 
'B7': (88, 125), 
'A8': (52, 74), 
'B8': (62, 88), 
'A9': (37, 52), 
'B9': (44, 62), 
'A10': (26, 37), 
'B10': (31, 44), 
'C0': (917, 1297), 
'C1': (648, 917), 
'C2': (458, 648), 
'C3': (324, 458), 
'C4': (229, 324), 
'C5': (162, 229), 
'C6': (114, 162), 
'C7/6': (81, 162), 
'C7': (81, 114), 
'C8': (57, 81), 
'C9': (40, 57), 
'C10': (28, 40), 
'DL': (110, 220) }

class Dimension(object):
    def __init__(self, size=0, definition=0, pixel=0):
        if definition:
            self.definition = definition
        if size and definition:
            self.size = size
            self.pixel = self.definition * self.size / 25.4 # def in inch to def in mm
        elif definition and pixel:
            self.pixel = pixel
            self.size = self.pixel / self.definition * 25.4
        elif size and pixel:
            self.size = size; self.pixel = pixel
            self.definition = self.pixel / self.size * 25.4
    def __str__(self):
        return("{size}mm @ {definition:.0f}dpi = {pixel:.0f}px".format(**self.__dict__))

def iso(_format, definition):
    if _format not in ISO_formats.keys():
        print("Unknow ISO format")
    else:
        l, w = ISO_formats[_format]
        L = Dimension(l, definition)
        W = Dimension(w, definition)
        print("{format}: {L.size} x {W.size} mm @ {definition:.0f}dpi = {L.pixel:.0f} x {W.pixel:.0f} px".format(
            format=_format,
            L=L,
            W=W,
            definition=definition))

def main():
    DEFAULT_DEF = 200
    import argparse
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("-i", "--iso", help="Paper size ISO format, -l for complete list", dest="format")
    parser.add_argument("-l", "--list", help="List of supported ISO formats", action='store_true')
    parser.add_argument("-s", "--size", help="Size in millimeters", dest="size", type=float)
    parser.add_argument("-d", "--definition", help="Definition in dpi", dest="definition", type=int)
    parser.add_argument("-p", "--pixel", help="Size in pixel", dest="pixel", type=int)
    args = parser.parse_args()
    if args.list:
        for k, (w, l) in sorted(ISO_formats.items()): print("{}: {} x {}".format(k, w, l))
    if args.format:
        if not args.definition:
            print("Default definition used: {}dpi".format(DEFAULT_DEF))
            iso(args.format, DEFAULT_DEF)
        else:
            iso(args.format, args.definition)
    else:
        defined = [i for i in (args.size, args.definition, args.pixel) if i]
        if len(defined) < 2:
            print("Missing arguments")
        elif len(defined) > 2:
            print("Too many arguments")
        else:
            print(Dimension(args.size, args.definition, args.pixel))

if __name__ == '__main__':
    main()

cli python tool

<iframe width="100%" height="2234" src="http://ginkobox.fr/vamp/index.php?embed=54a34acf4e8dc" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 31/12/2014

Store and retrieve variables in bash (from file)

# *** Dynamic serialization in bash ***
# The follwing example can keep track of PIDs of running background processes

# The interresting part is the loading and the storage (1. and 3.) !

# *** 1. Load PIDs ***
pidfile=/foo/bar
[[ -e $pidfile ]] && . $pidfile #Source the file !

# *** 2. Do the work ***
func1 () {
    varname="$1pid"
    mybin &
    export ${varname}=$! # Pid of last background process
}

func2 () {
    varname="$1pid"
    [[ ${!varname} ]] && kill ${!varname}} || echo "Fuck"
    unset ${varname}
}

if [[ $whatever ]]; then
    func1 d
else
    func2 d
fi


# *** 3. Store back PIDs ***
[[ -e $pidfile ]] && rm $pidfile # Clean out, only variables that are still set will be serialized
for var in "d" "t" "q"; do
    varname="${var}pid"
    if [[ ${!varname} ]]; then
        declare -p ${varname} | cut -d ' ' -f 3- >> $pidfile # Here is the magic : "declare -p" handles the quotes for you :D
    fi
done

bash

<iframe width="100%" height="848" src="http://ginkobox.fr/vamp/index.php?embed=54986909effb0" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 22/12/2014

SSH Tunnel manager

# Starts and kills SSH tunnels

# *** ssh command explained ***
# -S : The control socket, it's used to monitor the ssh connection
# -M : Mandatory for the use of -S (indicates that this connection is the master). If -M is not specified, ssh looks for the socket of the master connection to attach this ssh session as a slave.
# -N : Don't execute commande
# -f : Go to background (but allow ssh to ask for passwd, that's the difference from a shell &)
# -O : Command line for socket
# -L : Local port forwarding

connect () {
    ssh -M -S ~/.tunnel_${2}.sock -f user@host -L $1 -N && echo "Tunnel $2 started successfully" || echo "Tunnel $2 failed to start"
}

disconnect () {
    case $1 in
        d|t|q) ssh -S ~/.tunnel_${1}.sock -O exit user@host;;
        *) "Unknown target"; exit 1;;
    esac
}

case $1 in
    d) connect "<local_port_d>:target_d.tld:<remote_port_d>" "d";;
    t) connect "<local_port_t>:target_t.tld:<remote_port_t>" "t";;
    q) connect "<local_port_q>:target_q.tld:<remote_port_q>" "q";;
    -k) disconnect $2;;
    -h|--help) echo "tunnel.sh [-K] <target in [dtq]>"; exit 0;;
    *) echo "Unknown target"; exit 1;;
esac

ssh tunnel bash

<iframe width="100%" height="722" src="http://ginkobox.fr/vamp/index.php?embed=54985416ccf48" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 22/12/2014

12

This page's Feed


SnippetVamp 1.84 by Bronco - generated in 0.003 s