How to...



  • How to display the contents of a circular JSON object in nodejs:

    Method1:

    		const getCircularReplacer = () => {
    		  const seen = new WeakSet();
    		  return (key, value) => {
    		    if (typeof value === "object" && value !== null) {
    		      if (seen.has(value)) {
    		        return;
    		      }
    		      seen.add(value);
    		    }
    		    return value;
    		  };
    		};
    
    		var string=JSON.stringify(circularJSONobject, getCircularReplacer());
    		console.log(string);
    
    

    Method 2:

    var util = require('util'); //a core nodejs function but it has to be imported
    console.log(util.inspect(circularJSONobject));
    


  • How to create post buttons that look like links:

    css:

      .link-button {
        background: none;
        border: none;
        color: #337ab7;
        cursor: pointer;
        font-size: 19px;
        font-weight: 400;
        font-family: 'Lato', sans-serif;
      }
      .link-button:focus {
        outline: none;
      }
      .link-button:active {
        color:red;
      }
      .link-button:hover {
        text-decoration: underline;
        filter: brightness(65%);
      }
    

    html:

    <form method="post" action="https://mics.com/index" class="inline">
    <button type="submit" name="submit_name" value="name" class="link-button">link display text</button>
    </form>
    


  • How to display line numbers for pasted code in NodeBB:

    This is from here.

    NB. (This isn't working for me)

    Put this in your custom header (ACP -> Appearance -> Custom HTML & CSS -> Custom Header):

    <script>
    require(['highlight'], function (hljs) {
      require([
        'https://cdnjs.cloudflare.com/ajax/libs/highlightjs-line-numbers.js/1.1.0/highlightjs-line-numbers.min.js'
      ], function () {
        $(window).on('load action:ajaxify.end', function () {
          setTimeout(function () {
            hljs.initLineNumbersOnLoad();
          }, 100);
        });
      });
    });
    </script>
    

    NB. The contents of 'highlightjs-line-numbers.min.js' are:

    !function(e){"use strict";function t(){"complete"===document.readyState?n():e.addEventListener("DOMContentLoaded",n)}function n(){try{var e=document.querySelectorAll("code.hljs");for(var t in e)e.hasOwnProperty(t)&&r(e[t])}catch(n){console.error("LineNumbers error: ",n)}}function r(e){if("object"==typeof e){var t=e.parentNode,n=o(t.textContent);if(n>1){for(var r="",c=0;n>c;c++)r+=c+1+"\n";var l=document.createElement("code");l.className="hljs hljs-line-numbers",l.style["float"]="left",l.textContent=r,t.insertBefore(l,e)}}}function o(e){if(0===e.length)return 0;var t=/\r\n|\r|\n/g,n=e.match(t);return n=n?n.length:0,e[e.length-1].match(t)||(n+=1),n}"undefined"==typeof e.hljs?console.error("highlight.js not detected!"):(e.hljs.initLineNumbersOnLoad=t,e.hljs.lineNumbersBlock=r)}(window);
    


  • How to cycle/loop through an object in javascript:

    for (var key in req.body) {
        if (key in req.body) {
            console.log(req.body[key]);
        }
    }
    


  • %(#ffffff)[How to publish a package with npm:]

    *Sign in with npm login:

    npm login
    

    You’ll be prompted to enter your username, password, and email address.

    *Create a folder named how-to-publish-to-npm:

    mkdir how-to-publish-to-npm
    

    *Navigate into the folder:

    cd how-to-publish-to-npm
    

    *Begin the project with the npm init command:

    npm init
    

    This command runs you through a few questions and creates a package.json file for you at the end. This package.json file contains the bare necessities you need to publish your project. (Feel free to skip questions that don’t make sense).

    *The final step is to publish your package with the npm publish command:

    npm publish
    


  • How to set permissions in linux with chmod:

    chmod 600 {filespec}	You can read and write; the world can't. Good for files.
    chmod 700 {filespec}	You can read, write, and execute; the world can't. Good for scripts.
    chmod 644 {filespec}	You can read and write; the world can only read. Good for web pages.
    chmod 640 {filespec}	You can read and write; group can read, the world can't do anything.Good for group project..
    chmod 755 {filespec}	You can read, write, and execute; the world can read and execute. Good for programs you want to share, and your public_html directory.
    chmod 750 {filespec}	You can read, write, and execute; the group can read and execute, the world can't do anything. Good for programs you want to share within group.
    


  • How to install WebODM on Windows 10 home:

    • Download Docker Toolbox and install it as an administrator. (You may need to uninstall VirtualBox first.)
    • Launch Docker Quickstart Terminal as an administrator. Note down the IP address shown below the whale.
    
                            ##         .
                      ## ## ##        ==
                   ## ## ## ## ##    ===
               /"""""""""""""""""\___/ ===
          ~~~ {~~ ~~~~ ~~~ ~~~~ ~~~ ~ /  ===- ~~~
               \______ o           __/
                 \    \         __/
                  \____\_______/
    
    docker is configured to use the default machine with IP 192.168.99.100
    For help getting started, check out the docs at https://docs.docker.com
    
    
    • Download WebODM with Git and start it:
    git clone https://github.com/OpenDroneMap/WebODM --config core.autocrlf=input --depth 1
    cd WebODM
    sh ./webodm.sh start
    
    • Navigate to port 8000 of the IP address recorded in the first step:
    http://192.168.99.100:8000
    
    • It is advisable to resize the VM associated with WebODM.
    cd "C:\Program Files\Oracle\VirtualBox"
    ./VBoxManage clonemedium disk --format VDI "C:\Users\username\.docker\machine\machines\default\disk.vmdk" "C:\Users\username\.docker\machine\machines\default\disk.vdi"
    
    ./VBoxManage modifyhd "C:\Users\username\.docker\machine\machines\default\disk.vdi" --resize 100000
    

    After resizing you will need to use a GParted VM to resize the partitions.

    • If you want to stop WebODM then use the command:
    sh ./webodm.sh down
    
    • To completely stop WebODM you will have to also stop the VirtualBox VBoxHeadless process using the Windows task manager


  • How to pipe output from a shell command to Perl to a shell command within a Perl script:

    $com='samtools view -h '.$infile;
    my $zom='samtools view -bS - > q64converted.bam';
    open(SBAM, "$com|");
    open SBOUT, "|$zom";
    while (<SBAM>){
    	print SBOUT "$_";
    }
    close(SBAM);
    close SBOUT;
    


  • How to find out which pages are visited according to user country in Google Analytics:

    how to view visited pages by country.jpg



  • How to horizontally split a file view in sublime text editor:

    Split the view by using View -> Layout -> Rows: 2. Then select Row 1 and go to File -> New View into File. It will open second tab with the same file. Then you can drag that tab to the Row 2.



  • How to push a docker image to Docker Hub:

    • You need to have an account on Docker Hub. In this example the account is named 'ning'.
    • The image must be built so that the account name is within the image name

    Eg. for docker command:

    docker tag nextflow_docker:202004201512  ning/nextflow_docker:202004201512
    
    • For a docker-compose file:
    version: '3'
    services:
      nextflow_docker:
        build: ./nextflow_docker
        image: ning/nextflow_docker:latest
    
    • Then you need to push:
    docker logout
    docker login
    #login with your username and password (if you are on ubuntu you can ignore password keyring (agree but dont enter a password)
    #NB. If you are on ubuntu and get the error message "Error calling StartServiceByName for org.freedesktop.secrets: Timeout was reached" , try the following command "sudo apt remove gnome-keyring golang-docker-credential-helpers"
    docker push ning/nextflow_docker:latest
    


  • How to translate a singularity recipe into a Dockerfile:

    • First install spython:
    git clone https://www.github.com/singularityhub/singularity-cli.git
    cd singularity-cli
    python3 setup.py install
    
    • Then perform the conversion:
    spython recipe /input/path/to/singularity/recipe/Singularity /output/path/to/Dockerfile
    


  • How to resize the left and right padding in large screens with CSS. (NB. Probably better to use bootstrap with 3 columns instead):

    • In the head section:
    <head>
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
      <style>   
        @media screen and (min-width: 768px) {
            body {
                padding-left: 100px;
                padding-right: 100px;
            }
        }
      </style>
    
    </head>
    


  • How to horizontally write the address on an envelope in Japan:

    〒106-0044東京都港区東麻布1-8-1 ISビル4F GPlusMedia



  • How to find the meanings of symbols in R:

    ?"@"
    ?"[["
    


  • How to overcome the following error message in Rstudio:

    WARNING: Rtools is required to build R packages but is not currently installed. Please download and install the appropriate version of Rtools before proceeding:
    

    In the R console:

    #Find where Rtools is installed:
    Sys.which("make")
    
    #Find where .Rprofile or .Rprofile.site is (my .Rprofile.site was in C:\R\R-3.6.2\etc):
    Sys.getenv("HOME")
    

    Add these two lines to .Rprofile.site (or .Rprofile):

    Sys.setenv(PATH = paste("C:/rtools40/usr/bin", Sys.getenv("PATH"), sep=";"))
    Sys.setenv(BINPREF = "C:/rtools40/mingw_$(WIN)/bin/")
    


  • How to use caret library from R to create folds for k-fold validation:

    # Import caret
    library(caret)
    # 10-Fold cross validation
    valid_sets = createFolds(1:nrow(data), k = 10)
    

    How to create a vector with 10 zeroes in R:

    vector = numeric(length(1:10))
    


  • How to find the most common element in a vector in R:

    mostCommon <- function(x){
         un <- unique(x)
         un[which.max(tabulate(match(x,un)))]
    }
    


  • How to normalise data in R:

    
    #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
    ####FUNCTION THAT CAN BE USED TO SCALE TO ANY RANGE 
    #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
    #define the function
        #x is the input vector
        #y is the scale (eg. you can use eg 1:100 or c(1,100))
    normaliza <- function(x,y){
      xin<-as.numeric(x)
      yin<-as.numeric(y)
      xmin<-min(xin)
      xmax<-max(xin)
      ymin<-min(yin)
      ymax<-max(yin)
      nza<-rep(0,length(xin))
      counta<-1
      for(i in xin){
        new<-(((i - xmin)/(xmax - xmin))*(ymax-ymin))+ymin
        nza[counta]<-new
        counta=counta+1
      }
      return(nza)
    }
    
    #define the scale
    y<-c(0,10)
    
    #an example with a vector:
    
    #define a vector
    test_vector<-1:100
    #test the function on a vector
    nzt<-normaliza(test_vector,y)
    sort(nzt)
    
    #an example with a dataframe
    
    #define a dataframe
    test_frame<-as.data.frame(cbind(test_vector,test_vector))
    #test the function on a dataframe
    nzt_frame <- as.data.frame(lapply(test_frame, normaliza,y=y))
    nzt_frame
    
    
    #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
    #### FUNCTION THAT CAN SCALE FROM 0 to 1  
    #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
    
    #define the function:
    normalize <- function(x) {
        return ((x - min(x)) / (max(x) - min(x)))
    }
    
    #test on a data frame:
    nzt_frame <- lapply(test_frame, normalize)
    nzt_frame
    #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
    


  • How to apply a function with multiple parameters in R:

    mylist <- list(a=1,b=2,c=3)
    myfxn <- function(var1,var2){
      var1*var2
    }
    var2 <- 2
    
    sapply(mylist,myfxn,var2=var2)
    

Log in to reply
 

Powered by ShareZomics