2019-12-06
Minimongo - How to output all collection documents to the browser console
collection_name.find({}).forEach(function(doc){console.log(doc);});
2019-11-16
2019-11-10
2019-10-31
Sublime Text - Copy columns of text on MacOS
1. Press the option key and at the same time left click where you want to start copying.
2. Drag until your selection is done.
3. Copy
4. Paste somewhere else
2. Drag until your selection is done.
3. Copy
4. Paste somewhere else
2019-09-10
GIT - How to remove history for already deleted files
# Mirror the repository and get inside its directory
cd ~/Documents/mirrored_repository_name_here.git
# Display the biggest files, which might help figure out what to remove
git ls-tree -r -t -l --full-name HEAD | sort -n -k 4 | tail -n 10
# Get outside of the folder
cd ..
# Run BFG (in the desktop in this example) to delta files of a certain extension
java -jar ~/Desktop/bfg.jar --delete-files *.zip --no-blob-protection mirrored_repository_name_here.git
# Run BFG to delete folders
java -jar ~/Desktop/bfg.jar --delete-folders data --no-blob-protection mirrored_repository_name_here.git
# Remove those files
git reflog expire --expire=now --all && git gc --prune=now --aggressive
# Check on the size of the repository
git count-objects -v
# Push it
git push --force
cd ~/Documents/mirrored_repository_name_here.git
# Display the biggest files, which might help figure out what to remove
git ls-tree -r -t -l --full-name HEAD | sort -n -k 4 | tail -n 10
# Get outside of the folder
cd ..
# Run BFG (in the desktop in this example) to delta files of a certain extension
java -jar ~/Desktop/bfg.jar --delete-files *.zip --no-blob-protection mirrored_repository_name_here.git
# Run BFG to delete folders
java -jar ~/Desktop/bfg.jar --delete-folders data --no-blob-protection mirrored_repository_name_here.git
# Remove those files
git reflog expire --expire=now --all && git gc --prune=now --aggressive
# Check on the size of the repository
git count-objects -v
# Push it
git push --force
2019-09-08
Python - Get string in between two other sub-strings
import re
s = 'STRING_PART_1This is the text you will getSTRING_PART_2'
result = re.search('STRING_PART_1(.*)STRING_PART_2', s)
print result.group(1)
s = 'STRING_PART_1This is the text you will getSTRING_PART_2'
result = re.search('STRING_PART_1(.*)STRING_PART_2', s)
print result.group(1)
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)
# 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
}
);
// Match
{
"subdocument_to_search_within": {
"$elemMatch": {
"field_within_the_subdocument": 100
}
}
, "other_filter": 1
}
// Projection
, {
"subdocument_to_search_within.$": 1
}
);
2019-07-27
MySQL - GROUP_CONCAT Permanent Server Limit Setting Change
SET PERSIST_ONLY group_concat_max_len = 1000000;
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)
});
'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
2019-07-02
TSQL - Pass the result of executed dynamic SQL to a variable
DECLARE @sql nvarchar(max);
declare @result int;
SET @sql = 'SELECT @x = COUNT(*) FROM SCHEMA_NAME.TABLE_NAME;';
EXECUTE sp_executesql @sql, N'@cnt int OUTPUT', @x=@result OUTPUT;
print @result;
declare @result int;
SET @sql = 'SELECT @x = COUNT(*) FROM SCHEMA_NAME.TABLE_NAME;';
EXECUTE sp_executesql @sql, N'@cnt int OUTPUT', @x=@result OUTPUT;
print @result;
2019-06-30
JavaScript - jQuery Filter
// Array of json objects
let json_array = [
{
"item_name": "United States"
, "item_property": "123"
},
{
"item_name": "United Arab Emirates"
, "item_property": "123"
},
{
"item_name": "Mexico"
, "item_property": "234"
}
];
// Filter
$(json_array).filter(function (index, value){
return value.item_property === '123';
});
let json_array = [
{
"item_name": "United States"
, "item_property": "123"
},
{
"item_name": "United Arab Emirates"
, "item_property": "123"
},
{
"item_name": "Mexico"
, "item_property": "234"
}
];
// Filter
$(json_array).filter(function (index, value){
return value.item_property === '123';
});
JavaScript - jQuery Grep
// Arry of json objects
let json = [
{
"item_name": "United States"
, "item_property": "123"
},
{
"item_name": "United Arab Emirates"
, "item_property": "123"
},
{
"item_name": "Mexico"
, "item_property": "234"
}
];
// Grep to filter
$.grep(
json
, function( item, index ) {
return item.item_property === '123';
}
);
let json = [
{
"item_name": "United States"
, "item_property": "123"
},
{
"item_name": "United Arab Emirates"
, "item_property": "123"
},
{
"item_name": "Mexico"
, "item_property": "234"
}
];
// Grep to filter
$.grep(
json
, function( item, index ) {
return item.item_property === '123';
}
);
2019-06-11
SCSS - Iconic Bootstrap implementation sampler
<span
class="
{{! Required class}}
iconic
{{! Icon name}}
iconic-brush
{{!3 versions for each, scaled depending on size}}
iconic-sm {{!iconic-md}}{{!iconic-lg}}
{{! Size }}
iconic-size-sm {{!iconic-size-lg}}
{{! Flip }}
iconic-flip-horizontal-vertical {{!iconic-flip-horizontal}}{{!iconic-flip-vertical}}
{{! Ignore the text in the span, if any }}
iconic-text-replace
"
title="brush"
aria-hidden="true"
>This text will be ignored</span>
PS. SCSS/SSAS.
class="
{{! Required class}}
iconic
{{! Icon name}}
iconic-brush
{{!3 versions for each, scaled depending on size}}
iconic-sm {{!iconic-md}}{{!iconic-lg}}
{{! Size }}
iconic-size-sm {{!iconic-size-lg}}
{{! Flip }}
iconic-flip-horizontal-vertical {{!iconic-flip-horizontal}}{{!iconic-flip-vertical}}
{{! Ignore the text in the span, if any }}
iconic-text-replace
"
title="brush"
aria-hidden="true"
>This text will be ignored</span>
PS. SCSS/SSAS.
2019-06-04
Javascript - How to check if an isotope has already been instantiated or not
if($(".div-class-supposed-to-turn-into-an-isotope").hasClass('isotope')) {}
Credits...
https://stackoverflow.com/questions/16138404/isotope-metafizzy-how-to-check-if-an-element-has-already-been-initialized-as-an
Credits...
https://stackoverflow.com/questions/16138404/isotope-metafizzy-how-to-check-if-an-element-has-already-been-initialized-as-an
2019-05-09
MongoDB - Retrieve documents where a field exists
db.COLLECTION_NAME.find(
{ FIELD_NAME : { $exists: true}}
);
{ FIELD_NAME : { $exists: true}}
);
MongoDB - Retrieve documents where a field does not exist
db.COLLECTION_NAME.find(
{ FIELD_NAME : { $exists: false}}
);
{ FIELD_NAME : { $exists: false}}
);
2019-05-03
MySQL - RegEx replacements
-- This may only work with certain versions of MySQL (v8+ possibly)
-- These functions do not work on select statements using a DISTINCT clause
SELECT REGEXP_REPLACE('a b c', 'b', 'X');
SELECT REGEXP_REPLACE('a b c', '[a-z]', 'X');
SELECT REGEXP_REPLACE('a b c 123 cuando ', '[[:alpha:]]', 'X');
SELECT REGEXP_REPLACE('a b c 1987-2087 cuando ', '[[:alpha:]]', '');
SELECT REGEXP_REPLACE('a b c 1987-2087 cuando ', '[[:alpha:]]', '', 1, 0, 'i');
SELECT REGEXP_REPLACE(
author
-- , '[a-z]+' -- Regex Pattern
, '[[:alpha:]]'
, 'X' -- Replace value
, 1 -- Starting position
, 1 -- Occurrence
, 'i' -- Match type (i=case insensitive, c=case sensitive, m=multiple line mode, u=unix-only line endings)
);
-- These functions do not work on select statements using a DISTINCT clause
SELECT REGEXP_REPLACE('a b c', 'b', 'X');
SELECT REGEXP_REPLACE('a b c', '[a-z]', 'X');
SELECT REGEXP_REPLACE('a b c 123 cuando ', '[[:alpha:]]', 'X');
SELECT REGEXP_REPLACE('a b c 1987-2087 cuando ', '[[:alpha:]]', '');
SELECT REGEXP_REPLACE('a b c 1987-2087 cuando ', '[[:alpha:]]', '', 1, 0, 'i');
SELECT REGEXP_REPLACE(
author
-- , '[a-z]+' -- Regex Pattern
, '[[:alpha:]]'
, 'X' -- Replace value
, 1 -- Starting position
, 1 -- Occurrence
, 'i' -- Match type (i=case insensitive, c=case sensitive, m=multiple line mode, u=unix-only line endings)
);
2019-05-02
MySQL - Split string into pieces delimited by another string, and retrieve only the 'nth' element
select
-- Original field value
original_value
-- Second element, without delimiter
, REPLACE(
-- Second element, including its delimiter
REPLACE(
-- Desired element with all previous ones
SUBSTRING_INDEX( original_value, ',', 2)
-- All previous elements
, SUBSTRING_INDEX( original_value, ',', 1)
, ''
)
, ','
, ''
) as _second_element
-- Fourth element
, REPLACE(
-- Desired element with all previous ones
SUBSTRING_INDEX( original_value, ',', 4)
-- All previous elements
, SUBSTRING_INDEX( original_value, ',', 3)
, ''
) as _fourth_element
from
(select 'apple jelly and toast,bbq chicken,celery logs,daisies-bouquet,ebony,f-key,g-string,ivory' as original_value) as n1
;
-- Original field value
original_value
-- Second element, without delimiter
, REPLACE(
-- Second element, including its delimiter
REPLACE(
-- Desired element with all previous ones
SUBSTRING_INDEX( original_value, ',', 2)
-- All previous elements
, SUBSTRING_INDEX( original_value, ',', 1)
, ''
)
, ','
, ''
) as _second_element
-- Fourth element
, REPLACE(
-- Desired element with all previous ones
SUBSTRING_INDEX( original_value, ',', 4)
-- All previous elements
, SUBSTRING_INDEX( original_value, ',', 3)
, ''
) as _fourth_element
from
(select 'apple jelly and toast,bbq chicken,celery logs,daisies-bouquet,ebony,f-key,g-string,ivory' as original_value) as n1
;
MySQL - Split string into groups and retrieve 'n' number of groups
select
SUBSTRING_INDEX( v, ',', 1) as first_part
, SUBSTRING_INDEX( v, ',', 2) as first_and_second_parts
, SUBSTRING_INDEX( v, ',', 3) as first_through_third_parts
, SUBSTRING_INDEX( v, ',', 4) as first_through_fourth_parts
, SUBSTRING_INDEX( v, ',', 5) as first_through_fifth_parts
, SUBSTRING_INDEX( v, ',', 0) as no_parts
, SUBSTRING_INDEX( v, ',', 100) as all_parts
from
(select 'apple, bbq, celery, daisies, ebony' as v) as n1
;
SUBSTRING_INDEX( v, ',', 1) as first_part
, SUBSTRING_INDEX( v, ',', 2) as first_and_second_parts
, SUBSTRING_INDEX( v, ',', 3) as first_through_third_parts
, SUBSTRING_INDEX( v, ',', 4) as first_through_fourth_parts
, SUBSTRING_INDEX( v, ',', 5) as first_through_fifth_parts
, SUBSTRING_INDEX( v, ',', 0) as no_parts
, SUBSTRING_INDEX( v, ',', 100) as all_parts
from
(select 'apple, bbq, celery, daisies, ebony' as v) as n1
;
2019-04-07
Python - Beautifulsoup filter/get tags that contain a specific attribute
soup.find_all(attrs={'tag_attribute_name':True})
soup.find_all('tag_kind', attrs={'tag_attribute_name':True})
soup.find_all('tag_kind', attrs={'tag_attribute_name':True})
2019-04-04
TSQL - How to create a random ID or GUID
DECLARE @guid uniqueidentifier;
SELECT @guid = CONVERT(nvarchar(255), NEWID());
PRINT @guid
2019-04-01
2019-03-19
Python - Transpose a list using zip, yet transform the result to a list of lists, not a list of tuples
map(list, zip(*list_to_transpose))
2019-03-16
Python - Distinct list, preserving original elements order
from collections import OrderedDict
from itertools import izip, repeat
original_list = ['a', 'b', 'b', 'c']
unique_list = list(OrderedDict(izip(original_list, repeat(None))))
print unique_list
from itertools import izip, repeat
original_list = ['a', 'b', 'b', 'c']
unique_list = list(OrderedDict(izip(original_list, repeat(None))))
print unique_list
Credit to: https://stackoverflow.com/questions/479897/how-to-remove-duplicates-from-python-list-and-keep-order
2019-03-12
Meteor - Determine the version of your meteor instance/project
Navigate to your project root folder using Terminal.
$ cat .meteor/release
METEOR@1.8.0.2
2019-03-10
Python - Get the path of the grandparent directory of the current script
from os import path
print path.dirname(
path.dirname(
path.abspath(__file__)
)
)
Python - Get the path of the directory that holds the current script (not including the current script file name)
from os import path
print path.dirname(
path.abspath(__file__)
)
Python - Retrieve the absolute path of the current script, including its name
from os import path
print path.abspath(__file__)
2019-03-08
Python - Inserting a column to an existing list of lists (fixed value or numerical count/index)
# 1. Original matrixmatrix = [ [1, 'a', 'the letter a'] , [2, 'b', 'the letter b'] ] # 2. Inserting the same fixed valuematrix = [ x + ['new fixed value'] for x in matrix ] # 3. Insert a consecutive numeric valuematrix = [ pair[1] + [pair[0]] for pair in enumerate(matrix) ]
Python - Flatten list of lists using list comprehension
flat = [
y
for x in list_of_lists
for y in x
]
Credits: https://coderwall.com/p/rcmaea/flatten-a-list-of-lists-in-one-line-in-python
y
for x in list_of_lists
for y in x
]
Credits: https://coderwall.com/p/rcmaea/flatten-a-list-of-lists-in-one-line-in-python
2019-03-01
Windows - How to delete all browser caches
@echo off
taskkill /f /im iexplore.exe
erase "%TEMP%\*.*" /f /s /q
for /D %%i in ("%TEMP%\*") do RD /S /Q "%%i"
erase "%TMP%\*.*" /f /s /q
for /D %%i in ("%TMP%\*") do RD /S /Q "%%i"
erase "%ALLUSERSPROFILE%\TEMP\*.*" /f /s /q
for /D %%i in ("%ALLUSERSPROFILE%\TEMP\*") do RD /S /Q "%%i"
erase "%SystemRoot%\TEMP\*.*" /f /s /q
for /D %%i in ("%SystemRoot%\TEMP\*") do RD /S /Q "%%i"
@rem Clear IE cache - (Deletes Temporary Internet Files Only)
start "" "C:\Windows\System32\rundll32.exe" InetCpl.cpl,ClearMyTracksByProcess 255
erase "%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*") do RD /S /Q "%%i"
set DataDir=C:\Windows\Downloaded Program Files
del /q /s /f "%DataDir%"
rd /s /q "%DataDir%"
taskkill /f /im iexplore.exe
erase "%TEMP%\*.*" /f /s /q
for /D %%i in ("%TEMP%\*") do RD /S /Q "%%i"
erase "%TMP%\*.*" /f /s /q
for /D %%i in ("%TMP%\*") do RD /S /Q "%%i"
erase "%ALLUSERSPROFILE%\TEMP\*.*" /f /s /q
for /D %%i in ("%ALLUSERSPROFILE%\TEMP\*") do RD /S /Q "%%i"
erase "%SystemRoot%\TEMP\*.*" /f /s /q
for /D %%i in ("%SystemRoot%\TEMP\*") do RD /S /Q "%%i"
@rem Clear IE cache - (Deletes Temporary Internet Files Only)
start "" "C:\Windows\System32\rundll32.exe" InetCpl.cpl,ClearMyTracksByProcess 255
erase "%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*") do RD /S /Q "%%i"
set DataDir=C:\Windows\Downloaded Program Files
del /q /s /f "%DataDir%"
rd /s /q "%DataDir%"
2019-02-11
Python - Force package installation when getting dependencies errors
sudo pip install PACKAGE_NAME --ignore-installed
2019-02-05
Python - Probability Density Function & Cumulative Density Function, from sample vector of values
import numpy as npimport matplotlib.pyplot as pltfrom scipy.stats import norm # Observationsobs = [ 0.4 , 0.4343 , 0.4571 , 0.48 , 0.5086 , 0.5543 , 0.5714 , 0.5943 , 0.6457 , 0.68 , 0.7086 , 0.7371 , 0.7543 , 0.8 , 0.8286 , 0.8514 , 0.8914 , 0.9086 , 0.9486 , 0.9829 , 1.0057 , 1.0229 , 1.0514 , 1.08 , 1.0914 , 1.12 , 1.1371 , 1.16 , 1.2 , 1.2229 , 1.28 , 1.2971 , 1.32 , 1.3429 , 1.3714 , 1.4171 , 1.44] # Descriptive statisticsminimum = min(obs) maximum = max(obs) m = np.mean(obs, axis=None) s = np.std(obs, axis=None) # Debugprint "mean:", mprint "standard deviation:", sprint "cdf:", "\n", norm.cdf(obs, m, s)print "pdf:", "\n", norm.pdf(obs, m, s) # Plot between min and max with .001 sized stepsx_axis = np.arange(minimum, maximum, 0.001) plt.ylabel('Density') plt.xlabel('Values') plt.plot(x_axis, norm.pdf(x_axis, m, s)) plt.show()
2019-01-29
Python - How to install downloaded packages with Anaconda
conda install --offline --verbose c:\filename.tar.bz2
2019-01-13
MySQL - Command line to display a list of all views in a given database
mysql -NBA -h the_host -u user_name -p -D database_name -e "SHOW FULL TABLES IN database_name WHERE TABLE_TYPE LIKE 'VIEW';"
Cleaner, only 1 column:
mysql -NBA -h the_host -u user_name -p -D database_name -e "SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_TYPE LIKE 'VIEW' AND TABLE_SCHEMA LIKE 'database_name';"
MySQL - Command line to display a list of all tables
mysql -NBA -h the_host -u user_name -p -D database_name -e 'show tables'
Subscribe to:
Posts (Atom)