logo
down
shadow

Converting .raw file into Hex


Converting .raw file into Hex

By : Waqar Sahi
Date : November 17 2020, 01:00 AM
seems to work fine The problem is you pass the name of the file to hexdump() which treats it like data. The following corrects that and applies other relatively minor fixes to your code (and seems to work in my limited testing):
code :
try:
    xrange
except NameError:  # Python3
    xrange = range

def hexdump(filename, length=16, sep='.'):
    result = []

    with open(filename, 'rb') as file:
        src = file.read()  # Read whole file into memory

    for i in xrange(0, len(src), length):
        subSrc = src[i:i+length]
        hexa = ''
        isMiddle = False;
        for h in xrange(0,len(subSrc)):
            if h == length/2:
                hexa += ' '
            h = subSrc[h]
            if not isinstance(h, int):
                h = ord(h)
            h = hex(h).replace('0x','')
            if len(h) == 1:
                h = '0'+h;
            hexa += h+' '
        hexa = hexa.strip(' ')
        text = ''
        for c in subSrc:
            if not isinstance(c, int):
                c = ord(c)
            if 0x20 <= c < 0x7F:
                text += chr(c)
            else:
                text += sep;
        result.append(('%08X:  %-'+str(length*(2+1)+1)+'s  |%s|') %
                      (i, hexa, text))

    return '\n'.join(result)

if __name__ == "__main__":
    import sys

    filename = sys.argv[1]
    print(hexdump(filename, length=16, sep='.'))


Share : facebook icon twitter icon
C# - Converting multi page tiff file to base64 string and converting back results with single image

C# - Converting multi page tiff file to base64 string and converting back results with single image


By : user3098010
Date : March 29 2020, 07:55 AM
This might help you For people who have a problem about converting multi page tiff file to base64 and vice versa you can refer to that link:
Is it possible to create a base64 string which has all frames of a multi page tiff file?
Converting PDF color existing file to a PDF gray file or a PDF B/W file

Converting PDF color existing file to a PDF gray file or a PDF B/W file


By : Ayushman Dash
Date : March 29 2020, 07:55 AM
Does that help I found a solution. I give you the most important part of the solution code:
code :
public enum DPIResolution {DPI72, DPI150, DPI300, DPI300PLUS}

// Program paths
public static final String PROGRAM_GSWIN64C_PATH = "C:/gs/gs9.16/bin/gswin64c.exe";
public static final String PROGRAM_GSWIN64C_OLD_PATH = "C:/gs/gs9.07/bin/gswin64c.exe";
public static final String PS_TMP_PATH = "D:/tmp.ps";

// Convert PDF Color to PDF Gray
private static int convertPDFColorToPDFGray(String inputPath, String outputPath, DPIResolution dpiResolution){
    String[] cmd = {
        PROGRAM_GSWIN64C_PATH, "-sDEVICE=pdfwrite", "-dPDFSETTINGS=/" + dpiForGS,
        "-sColorConversionStrategy=Gray", "-sColorConversionStrategyForImages=Gray", "-sProcessColorModel=DeviceGray",
        "-dCompatibilityLevel=1.4", "-dNOPAUSE", "-dBATCH",
        "-sOutputFile=" + outputPath, inputPath, "-c", "quit"
    };

    int exitCode = ghostScriptCommand(cmd);
}

// Convert PDF Color to PDF Black and White
private static int convertPDFColorToPDFBlackAndWhite(String inputPath, String outputPath){
    String[] cmd = {
        PROGRAM_GSWIN64C_OLD_PATH, "-sDEVICE=psmono", "-dNOPAUSE", "-dBATCH",
        "-sOutputFile=" + PS_TMP_PATH, inputPath, "-c", "quit"
    };

    String[] cmd2 = {
        PROGRAM_GSWIN64C_PATH, "-sDEVICE=pdfwrite", "-dNOPAUSE", "-dBATCH",
        "-sOutputFile=" + outputPath, PS_TMP_PATH, "-c", "quit"
    };

    int exitCode = ghostScriptCommand(cmd);
    exitCode = ghostScriptCommand(cmd2);

    // We remove the PS tmp file
    File file = new File(PS_TMP_PATH);
    try{
        if(!file.delete()) System.out.println("Erreur de suppression de " + file.getName());
    } catch(Exception e){
        System.err.println("Erreur: " + e.getMessage());
        e.printStackTrace();
    }
};

// Command to Ghost Script (GS)
private static int ghostScriptCommand(String[] cmd){
    try {
        Process process = Runtime.getRuntime().exec(cmd);
        int exitCode = process.waitFor();

        // read the output from the command
        String s;
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String stringstdInput = "- Standard output of the command :\n";
        while ((s = stdInput.readLine()) != null) {
            stringstdInput += s + "\n";
        }
        // read any errors from the attempted command
        boolean hasStdError = false;
        BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        String stringstdError = "- Standard error of the command :\n";
        while ((s = stdError.readLine()) != null) {
            hasStdError = true;
            stringstdError += s + "\n";
        }
        System.out.print(stringstdInput);
        if(hasStdError) System.err.print(stringstdError);

    } catch (Exception e) {
        System.err.println("Erreur: " + e.getMessage());
        e.printStackTrace();
    }

    return exitCode;
}

private static String dpiResolutionToGS(DPIResolution dpiResolution){
    String dpiForGS;

    switch(dpiResolution){
        case DPI72 :
            dpiForGS = "screen";
            break;
        case DPI150 :
            dpiForGS = "ebook";
            break;
        case DPI300 :
            dpiForGS = "printer";
            break;
        case DPI300PLUS :
            dpiForGS = "prepress";
            break;
        default :
            dpiForGS = "default";
    }

    return dpiForGS;
}
OpenCV's createsamples tool fails to use all samples when converting info file to vec file

OpenCV's createsamples tool fails to use all samples when converting info file to vec file


By : rb_dett
Date : March 29 2020, 07:55 AM
Any of those help The cause of this is that a ROI that was improperly defined while creating the samples. In my specific case, this specific line was found:
code :
positives\2\005.png 2 9 6 6 7 0 0 0 0
[filename] [# of objects] [[x y width height] [... 2nd object] ...]
positives\2\005.png 1 9 6 6 7
positives\2\005.png 2 9 6 6 7 -5 0 3 2
positives\2\005.png 2 9 6 6 7 30 30 200 300
positives\2\005.png 2 9 6 6 7 35 35 3 5
Converting a large wrongly created csv file into a tab delimited file using python and pandas

Converting a large wrongly created csv file into a tab delimited file using python and pandas


By : Shan Lim
Date : March 29 2020, 07:55 AM
I hope this helps you . You shouldn't need pandas here. Just iterate through the lines of the file and write the fixed lines to a new file.
code :
with open('new.csv', 'w') as newcsv:
    with open('file.csv') as csvf:
        for line in csvf:
            head, _, tail = line.strip().rpartition(',')
            newcsv.write('{}\t{}\n'.format(head, tail))
How can I import a JSON file into MySQL database, using a simple query, without actually converting it to any other file

How can I import a JSON file into MySQL database, using a simple query, without actually converting it to any other file


By : Salih Altıntop
Date : March 29 2020, 07:55 AM
Hope that helps I hope that in the near future there is a native functionality from MySQL.
An option (not simple query) is something like the following script (adapt as needed). Depending on the number of items may have performance problems.
code :
[
  {
    "executionDateTime":"2017-07-07 15:21:15",
    "A":1,
    "B":1
  },
  {
    "executionDateTime":"2017-07-07 15:21:15",
    "A":2,
    "B":2
  },
  {
    "executionDateTime":"2017-07-07 15:21:15",
    "A":3,
    "B":3
  },
  {
    "executionDateTime":"2017-07-07 15:21:15",
    "A":4,
    "B":4
  }
]
mysql> SELECT VERSION();
+-----------+
| VERSION() |
+-----------+
| 5.7.18    |
+-----------+
1 row in set (0.00 sec)

mysql> DROP PROCEDURE IF EXISTS `import_from_json`;
Query OK, 0 rows affected (0.00 sec)

mysql> DROP FUNCTION IF EXISTS `uuid_to_bin`;
Query OK, 0 rows affected (0.00 sec)

mysql> DROP TABLE IF EXISTS `temp_my_table`, `my_table`;
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE TABLE IF NOT EXISTS `temp_my_table` (
    ->   `id` BINARY(16) NOT NULL PRIMARY KEY,
    ->   `content` JSON NOT NULL
    -> );
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE TABLE IF NOT EXISTS `my_table` (
    ->   `executionDateTime` TIMESTAMP,
    ->   `A` BIGINT UNSIGNED,
    ->   `B` BIGINT UNSIGNED
    -> );
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE FUNCTION `uuid_to_bin` (`id` VARCHAR(36))
    -> RETURNS BINARY(16)
    -> DETERMINISTIC
    ->   RETURN UNHEX(REPLACE(`id`, '-', ''));
Query OK, 0 rows affected (0.00 sec)

mysql> DELIMITER //

mysql> CREATE PROCEDURE `import_from_json`(`_id` VARCHAR(36))
    -> BEGIN
    ->   DECLARE `_id_current_json` BINARY(16) DEFAULT `uuid_to_bin`(`_id`);
    ->   DECLARE `_items_length`,
    ->           `_current_item` BIGINT UNSIGNED DEFAULT 0;
    ->   DECLARE `_content` JSON DEFAULT (SELECT `content`
    ->                                    FROM `temp_my_table`
    ->                                    WHERE `id` = `_id_current_json`);
    -> 
    ->   IF JSON_VALID(`_content`) THEN
    ->     SET `_items_length` := JSON_LENGTH(`_content`),
    ->         @`insert_import_from_json` := NULL;
    ->     WHILE `_current_item` < `_items_length` DO
    ->       SET @`insert_import_from_json` := CONCAT('
    '>         INSERT INTO `my_table` (
    '>            `executionDateTime`,
    '>            `A`,
    '>            `B`
    '>         )
    '>         SELECT
    '>           `content` ->> \'$[', `_current_item`, '].executionDateTime\',
    '>           `content` ->> \'$[', `_current_item`, '].A\',
    '>           `content` ->> \'$[', `_current_item`, '].B\'
    '>         FROM `temp_my_table`
    '>         WHERE `id` = \'', `_id_current_json`, '\'
    '>       ');
    ->       PREPARE `stmt` FROM @`insert_import_from_json`;
    ->       EXECUTE `stmt`;
    ->       SET `_current_item` := `_current_item` + 1;
    ->     END WHILE;
    ->
    ->     IF `_current_item` > 0 THEN
    ->       SET @`insert_import_from_json` := NULL;
    ->       DEALLOCATE PREPARE `stmt`;
    ->     END IF;
    ->   END IF;
    -> END//
Query OK, 0 rows affected (0.00 sec)

mysql> DELIMITER ;

mysql> SET @`UUID` := UUID();
Query OK, 0 rows affected (0.00 sec)

mysql> LOAD DATA LOCAL INFILE '/path/to/file/loadsetProfile.json' 
    -> INTO TABLE `temp_my_table`
    -> LINES TERMINATED BY '\r'
    -> (`content`)
    -> SET `id` = `uuid_to_bin`(@`UUID`);
Query OK, 1 row affected (0.00 sec)
Records: 1  Deleted: 0  Skipped: 0  Warnings: 0

mysql> CALL `import_from_json`(@`UUID`);
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT
    ->   `executionDateTime`,
    ->   `A`,
    ->   `B`
    -> FROM
    ->   `my_table`;
+---------------------+------+------+
| executionDateTime   | A    | B    |
+---------------------+------+------+
| 2017-07-07 15:21:15 |    1 |    1 |
| 2017-07-07 15:21:15 |    2 |    2 |
| 2017-07-07 15:21:15 |    3 |    3 |
| 2017-07-07 15:21:15 |    4 |    4 |
+---------------------+------+------+
4 rows in set (0.01 sec)
Related Posts Related Posts :
  • Read data with NAs into python and calculate mean row-wise
  • How to print telnet response line by line?
  • Pylint: Avoid checking INSIDE DOCSTRINGS (global directive / rcfile)
  • Sending MIDI messages using Python (on Ubuntu)
  • Generate Dictionary in Python at run time
  • code is cluttered by try-except in Python
  • Python class inheritance - spooky action
  • Why is a Python multiprocessing daemon process not printing to standard output?
  • How to feed numeric data into a classifier?
  • How to unambiguously identify a Model as a lowercase string in Django
  • How to get only one specific line from subprocess output
  • Python network communication with encryption and password protection
  • with urllib urlopen read function but get none
  • django could not find database in ubuntu
  • How to replace a character in a string with a non ascii character in python?
  • Self learning data evaluation in Python
  • Django: UnicodeDecodeError while trying to read template 500.html
  • how can you Import an os variable into PYTHON and have it update?
  • Browse Folders to open a file in python
  • sql select group by a having count(1) > 1 equivalent in python pandas?
  • Why Insert command when button clicked OpenERP
  • Pandas dataframe from nested dictionary to melted data frame
  • Which is more efficient in Python: list.index() or dict.get()
  • Xor bits in python
  • A simple python confusion about format string
  • Finding index of a list containing an item, also in a list
  • How to test Domain is it 'www' domain or subdomain or name server domain or mail domain in python?
  • Keydown event for Pygame
  • Lazy loading csv with pandas
  • Use webdriver,python,beautifulsoup to retrieve dynamic website
  • Scrapy is Visiting same Url despite dont_filter=False
  • How to add support for SNI in python 2.7
  • Pandas: np.where with multiple conditions on dataframes
  • How to get meaningful words by splitting a continuous string?
  • TypeError: 'numpy.ndarray' object is not callable while extracting index and elements are stored in different array in p
  • Python: comparing list to a string
  • Is there any way to write '\r' into a file on linux with python?
  • matplotlib retrieve color from plt.plot command
  • Scrapy JSON export issues
  • beautifulsoup to retrieve the date
  • Django Rest Framework 3.0: Saving Nested, Many-To-One Relationship
  • Lost connection to MySQL server during Python connection
  • uploadede file path django
  • How to reduce a data with the longest string under pandas framework?
  • Single line for-loop to build a dictionary?
  • How to read in lines until a certain line?
  • Beautifulsoup to retrieve the href list
  • Python - Vincenty's inverse formula not converging (Finding distance between points on Earth)
  • Saving django model instance into another model
  • Same URL request fails with python->urllib but not with curl
  • Python dictionary: set value as the key string
  • With setuptools, when does namespace packages __init__.py files disappears?
  • Paraview: NameError: name 'inputs' is not defined
  • Too many values to unpack during template rendering
  • A different type of iterative function
  • Test if value exists in several lists
  • Go and Python HMAC libraries give different results
  • Python Nested Loop Working Weirdly
  • Why is this not assigning the correct value?
  • 'numpy.ndarray' object is not callable
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org