2019-08-28

Python - List of lists to CSV

import csv

# Data
headers = ['Header1', 'Header2', 'Header3']
rows = [[1,2,3], [5,6,7]]

# Open a file to append to
with open('/path/target_file.txt', 'a') as f:

    # CSV writer instantiation
    writer = csv.writer(
    f
    # Settings
    , quoting=csv.QUOTE_NONE
    , delimiter='\t'
    )

    # Headers
    writer.writerow(headers)

    # All rows
    writer.writerows(rows)

2019-08-05

MongoDB - Retrieve only matching sub-documents

db.collection.find(

    // Match
    {
        "subdocument_to_search_within":  {
        "$elemMatch": {
                "field_within_the_subdocument": 100
            }
    }
    , "other_filter": 1
    }

    // Projection
, {
        "subdocument_to_search_within.$": 1
    }
);

2019-07-27

2019-07-05

Meteor - Javascript template keyup debounce

Template.TEMPLATE_NAME_HERE.events({

  'keyup JQUERY_SELECTOR_HERE': _.debounce(function (evt, tmpl) {

        return evt.currentTarget.value;;

    }, 300)

});

2019-07-03

TSQL - Delete a job if it exists


IF EXISTS(
       SELECT 1
       FROM [msdb].[dbo].[sysjobs] a WITH(NOLOCK)
    WHERE a.Name = 'JOB_NAME_HERE'
)
       EXEC sp_delete_job @job_name='JOB_NAME_HERE', @delete_unused_schedule=1;


TSQL - Replace carriage returns


SELECT REPLACE(REPLACE(@VARIABLE_OR_FIELD_NAME, CHAR(13), ''), CHAR(10), '');


TSQL - Try and catch and raise error


-- Declarations
declare @error_message nvarchar(2000);
set @error_message = null;
declare @error_severity nvarchar(2000);
set @error_severity = null;
declare @error_state nvarchar(2000);
set @error_state = null;
declare @error_number int;
set @error_number = null;


-- Try
BEGIN TRY 
       -- Do something here
END TRY 


-- Catch
BEGIN CATCH 

       -- Available error variables
       /*SELECT
              ERROR_NUMBER() 
              , ERROR_SEVERITY() 
              , ERROR_STATE() 
              , ERROR_PROCEDURE() 
              , ERROR_LINE() 
              , ERROR_MESSAGE() 
       ; */

       -- Error number
       set @error_number = ERROR_NUMBER();                   

       -- Capture the error message, severity and state
       set @error_message = ERROR_MESSAGE();
       set @error_severity = ERROR_SEVERITY();
       set @error_state = ERROR_STATE();

       -- Debug
       print 'ERROR CAUGHT -> ' + @error_message;

       -- Raise error, so the job that will call this procedure launches a notification
       RAISERROR (
                     @error_message, -- Message text. 
                     @error_severity, -- Severity. 
                     @error_state -- State. 
              );

END CATCH