Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

tickertapes

Users can search for any word or phrase and opt for news of common financial market indexes


Originally implemented as "Twickertapes" and utilizing the original Twitter API (v2.0), this app is merely a demonstration of what can be done with a little text input, and API (the Google News API) and scrolling text and ASCII art.

You can find it on the web here: https://tickertapes.net

 

ChartJS for Data Vizualiizations

I came across ChartJS about 2 years ago while debugging code from another, similar data visualization technology inside an AngularJS app.


ChartJS is a flexible JavaScript data visualization framework which allows for some pretty powerful integrations and customizations


The concept is you have a "<canvas>" DOM element, which you transform into a ChartJS chart via some JavaScript initialization. After that your tasks are simply finding the data you want to render and deciding the options of exactly how you want the chart visual to appear.

You can do some really neat and dynamic stuff with ChartJS.

I have used a lot of charting frameworks, and it does not get more flexible or simple than this:
 <html>  
 <head>  
 <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>  
 </head>  
 <body>  
 <div>  
 <canvas id="myChart" style='background-color:darkgray; width:100%; height:100%;'></canvas>  
 </div>  
 <script>  
 var ctx = document.getElementById('myChart').getContext('2d');;  
 var chart = new Chart(ctx, {  
   type: 'line',  
   data: {  
     labels: ['16_Qtr1', '16_Qtr2', '16_Qtr3', '16_Qtr4', '17_Qtr1', '17_Qtr2', '17_Qtr3', '17_Qtr4', '18_Qtr1', '18_Qtr2', '18_Qtr3', '18_Qtr4', '19_Qtr1', '19_Qtr2', '19_Qtr3', '19_Qtr4', '20_Qtr1', '20_Qtr2', '20_tr3', '20_Qtr4', '21_Qtr1', '21_Qtr2', '21_Qtr3', '21_Qtr4','22_Qtr1', '22_Qtr2', '22_Qtr3', '22_Qtr4', '23_Qtr1', '23_Qtr2', '23_tr3', '23_Qtr4'],  
     datasets: [{  
       label: 'Some random quartley demo data..',  
       backgroundColor: 'black',  
       borderColor: 'lime',  
       data: [40.2, 72.88, 47.1, 22, 54.43, 52.18, 17.1, 52, 67.2, 54.88, 64.1, 78, 67.2, 55.88, 58.1, 57, 50.2, 52.88, 57.1, 62, 74.43, 62.18, 67.1, 72, 77.2, 74.88, 74.1, 78, 77.2, 75.88, 78.1, 77, 70.2, 72.88, 77.1, 62, 64.43, 62.18, 67.1, 72, 67.2, 54.88, 44.1, 28, 27.2, 25.88, 38.1, 37, 40.2, 42.88, 44.1, 52, 54.43, 52.18, 67.1, 82, 87.2, 84.88, 84.1, 88, 87.2, 95.88, 108.1, 127]  
     }]  
   },  
    "options": {  
       "legend": {"position": "bottom"}      
     }  
 });  
 </script>  
 </body>  
 </html>  


Reference: https://www.chartjs.org/

SSRS REST API v2

Here is a response from the SSSR REST API in action.. (you can access a lot more SSRS item properties and customize at will once you know the API)


The SSRS API v2 has far more functionality than v1, but they essentially work the same. You must be authenticated to the SSRS report server you are targeting (localhost in this case) to make web GET/POST requests to the API.

Once auth'd you can push and pull any useful SSRS data pretty easily to make SSRS do some pretty cool things it can't do out of the box..


This is the SSRS API as accessed through a web browser; simply give your .NET app an HttpClient and you can make use of all these responses; it's just JSON...



You can get a collection of SSRS catalog items as in the example above (folders, reports, KPIs) by just specifying the action name, or you can select an individual item by putting the item GUID in parenthesis in the API request URL:


You can access individual items in the API via GUID in parens after the API action name.




Common Useful SSRS API v2 Actions:
  • Reports
  • Datasets
  • Data Sources
  • Folders
  • Schedules
  • Subscriptions
  • Comments
  • KPIs
  • CatalogItems (everything)



Example of a .NET Standard library with an HttpService abstacting the SSRS API calls:
 namespace ExtRS  
 {  
   public class SSRSHttpService  
   {  
     const string ssrsApiURI = "https://localhost/reports/api/v2.0";  
     HttpClient client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });  
         public async Task<GenericItem> GetReportAsync(Guid id)  
     {  
       client.BaseAddress = new Uri(ssrsApiURI + string.Format("/reports({0})", id));  
       var response = await client.GetAsync(client.BaseAddress);  
       var odata = response.Content.ReadAsStringAsync().Result;  
       return JsonConvert.DeserializeObject<GenericItem>(odata);  
     }  
   }  
 }  
This is verbose to better break down the steps of what is happening on the ExtRS service end




A very basic class designed to demonstrate using SSRS API Response to create a .NET object:
 using Newtonsoft.Json;  
 using System.Collections.Generic;  
 namespace ExtRS  
 {  
   public class GenericItem  
   {  
     [JsonProperty("@odata.context")]  
     public string ODataContext { get; set; }  
     [JsonProperty("Id")]  
     public string Id { get; set; }  
     [JsonProperty("Name")]  
     public string Name { get; set; }  
     [JsonProperty("Path")]  
     public string Path { get; set; }  
   }  
 }  
The power of the SSRS API is limited primarily your imagination- lots of customization can be made




And finally, called from a Controller Action in an MVC app:
 using System;  
 using System.Web.Mvc;  
 using System.Threading.Tasks;  
 using ExtRS;  
 namespace Daylite.Controllers  
 {  
   public class ReportsController : Controller  
   {  
     public SSRSHttpService service = new SSRSHttpService();  
     public async Task<ViewResult> GetReportsAsync()  
     {  
       return View("Index", await service.GetReportsAsync());  
     }  
     public async Task<ViewResult> GetFoldersAsync()  
     {  
       APIGenericItemsResponse result = await service.GetFoldersAsync();  
       return View("Index", result);  
     }  
     public async Task<ViewResult> GetReportAsync(Guid id)  
     {  
       GenericItem result = await service.GetReportAsync(id);  
       return View("Index", result);  
     }  
   }  
 }  


Reference: https://github.com/Microsoft/Reporting-Services/tree/master/APISamples


Neat UI Effects with jQueryUI and Animate.CSS

So you want neat animation effects on your UI? Seems like it might be a tricky implementation, right?

Animate.css makes it easy to implement modern UI animation effects that make for better user experience/cues


It could not be simpler with jQuery UI and other open source options. Here is an easy sample to pick up and run with from jQuery.com:

jQuery UI Effects
 <!doctype html>  
 <html lang="en">  
 <head>  
   <meta charset="utf-8">  
   <meta name="viewport" content="width=device-width, initial-scale=1">  
   <title>jQuery UI Effects - Effect demo</title>  
   <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">  
   <link rel="stylesheet" href="/resources/demos/style.css">  
   <style>  
     .toggler {  
       width: 500px;  
       height: 200px;  
       position: relative;  
     }  
     #button {  
       padding: .5em 1em;  
       text-decoration: none;  
     }  
     #effect {  
       width: 240px;  
       height: 170px;  
       padding: 0.4em;  
       position: relative;  
     }  
       #effect h3 {  
         margin: 0;  
         padding: 0.4em;  
         text-align: center;  
       }  
     .ui-effects-transfer {  
       border: 2px dotted gray;  
     }  
   </style>  
   <script src="https://code.jquery.com/jquery-1.12.4.js"></script>  
   <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>  
   <script>  
     $(function () {  
       // run the currently selected effect  
       function runEffect() {  
         // get effect type from  
         var selectedEffect = $("#effectTypes").val();  
         // Most effect types need no options passed by default  
         var options = {};  
         // some effects have required parameters  
         if (selectedEffect === "scale") {  
           options = { percent: 50 };  
         } else if (selectedEffect === "transfer") {  
           options = { to: "#button", className: "ui-effects-transfer" };  
         } else if (selectedEffect === "size") {  
           options = { to: { width: 200, height: 60 } };  
         }  
         // Run the effect  
         $("#effect").effect(selectedEffect, options, 500, callback);  
       };  
       // Callback function to bring a hidden box back  
       function callback() {  
         setTimeout(function () {  
           $("#effect").removeAttr("style").hide().fadeIn();  
         }, 1000);  
       };  
       // Set effect from select menu value  
       $("#button").on("click", function () {  
         runEffect();  
         return false;  
       });  
     });  
   </script>  
 </head>  
 <body>  
   <div class="toggler" style="margin-top:200px;">  
     <div id="effect" class="ui-widget-content ui-corner-all">  
       <h3 class="ui-widget-header ui-corner-all">Effect</h3>  
       <p>  
         Etiam libero neque, luctus a, eleifend nec, semper at, lorem. Sed pede. Nulla lorem metus, adipiscing ut, luctus sed, hendrerit vitae, mi.  
       </p>  
     </div>  
   </div>  
   <select name="effects" id="effectTypes">  
     <option value="blind">Blind</option>  
     <option value="bounce">Bounce</option>  
     <option value="clip">Clip</option>  
     <option value="drop">Drop</option>  
     <option value="explode">Explode</option>  
     <option value="fade">Fade</option>  
     <option value="fold">Fold</option>  
     <option value="highlight">Highlight</option>  
     <option value="puff">Puff</option>  
     <option value="pulsate">Pulsate</option>  
     <option value="scale">Scale</option>  
     <option value="shake">Shake</option>  
     <option value="size">Size</option>  
     <option value="slide">Slide</option>  
     <option value="transfer">Transfer</option>  
   </select>  
   <button id="button" class="ui-state-default ui-corner-all">Run Effect</button>  
 </body>  
 </html>  


And one I whipped up from Animate.css...:
 <html>  
 <head>  
  <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>  
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.2/animate.min.css">  
  <script>                 
      $( document ).ready(function() {  
           myDiv = document.querySelector('#myDiv')       
           $("#buttonBounce").on("click", function () {  
                removeAllClasses();  
                myDiv.classList.add('animated', 'bounce')  
           });  
           $("#buttonSwing").on("click", function () {  
                removeAllClasses();  
                myDiv.classList.add('animated', 'swing')  
           });            
           $("#buttonWobble").on("click", function () {  
                removeAllClasses();  
                myDiv.classList.add('animated', 'wobble')            
           });            
           $("#buttonTada").on("click", function () {  
                removeAllClasses();  
                myDiv.classList.add('animated', 'tada')  
           });       
           $("#buttonBounceOut").on("click", function () {  
                removeAllClasses();  
                myDiv.classList.add('animated', 'bounceOutLeft')  
           });            
           function removeAllClasses(){  
                myDiv.classList.remove('animated', 'bounce', 'wobble', 'bounceOutLeft', 'tada', 'swing');  
           }  
      });       
  </script>  
 </head>  
 <body style="background:#000000;">  
 <div id="myDiv" style="margin-top:100px; margin-left:300px; width:250px; background:aqua; font-weight:bold; font-family:Arial; border: 2px solid lime; padding: 10px; border-radius: 25px;">~Something to animate~</h1>  
 <br/><br/>  
 &nbsp;&nbsp;<input type="button" id="buttonBounce" class="ui-state-default ui-corner-all" value="Bounce" />  
 </br><br/>  
 &nbsp;&nbsp;<input type="button" id="buttonTada" class="ui-state-default ui-corner-all" value="Tada" />  
 </br><br/>  
 &nbsp;&nbsp;<input type="button" id="buttonSwing" class="ui-state-default ui-corner-all" value="Swing" />  
 </br><br/>  
 &nbsp;&nbsp;<input type="button" id="buttonWobble" class="ui-state-default ui-corner-all" value="Wobble" />  
 </br><br/>  
 &nbsp;&nbsp;<input type="button" id="buttonBounceOut" class="ui-state-default ui-corner-all" value="Bounce Out" />  
 </br><br/>  
 </body>  
 </html>  


This is what the Animate.css code above will look like..


Happy coding!


Codepens: 

https://codepen.io/radagast27/pen/pooavXd

https://codepen.io/radagast27/pen/xxxYboM



References:

https://jqueryui.com/effect

https://github.com/daneden/animate.css

Google Maps API

The Google Maps API is a very powerful tool that is relatively easy to use if you have some JavaScript background. The below screen was created with the code that follows (Google API Key obfuscated).


Basic Maps API example with hard-coded lat/long custom markers


Get an API key here: https://developers.google.com/maps/documentation/javascript/get-api-key

Maps API exposed operations reference: https://developers.google.com/maps/documentation/javascript/tutorial

 <!DOCTYPE html>  
 <html>  
  <head>  
   <title>Custom Markers</title>  
   <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">  
   <meta charset="utf-8">  
   <style>  
    /* Always set the map height explicitly to define the size of the div  
     * element that contains the map. */  
    #map {  
     height: 100%;  
    }  
    /* Optional: Makes the sample page fill the window. */  
    html, body {  
     height: 100%;  
     margin: 0;  
     padding: 0;  
    }  
   </style>  
  </head>  
  <body>  
  <div>  
  Debug/Inspect...  
  </div>  
   <div id="map"></div>  
   <script>  
    var map;  
    function initMap() {  
     map = new google.maps.Map(  
       document.getElementById('map'),  
       {center: new google.maps.LatLng(43.0589, -88.0988), zoom: 11, mapTypeId: 'hybrid'});  
     var icons = {  
      bucks: {  
       icon: 'bucks.png'  
      },  
      brewers: {  
       icon: 'brewers.png'  
      },  
      panthers: {  
       icon: 'panthers.jpg'  
      }  
     };  
     var features = [  
      {  
       position: new google.maps.LatLng(43.0280, -87.9712),  
       type: 'brewers'  
      }, {  
       position: new google.maps.LatLng(42.9930, -87.9210),  
       type: 'panthers'  
      }, {  
       position: new google.maps.LatLng(43.0000, -87.8379),  
       type: 'bucks'  
      }  
     ];  
     // Create markers.  
     for (var i = 0; i < features.length; i++) {  
      var marker = new google.maps.Marker({  
       position: features[i].position,  
       icon: icons[features[i].type].icon,  
       map: map  
      });  
     };  
           //Must have API with access to the Places API to get marker click details without much manual code  
    }  
   </script>  
   <script async defer src="https://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXXXXXXXXXXX&callback=initMap">  
   </script>  
  </body>  
 </html>  

Header Text Resizing on Scroll

This is a useful tool for any modern website UI with content that you want to showcase (and get the header content out of the way as much as you can).

CodePen: https://codepen.io/radagast27/pen/JqWENL

Source: This feature works by having JavaScript detect when a certain scroll position from the top of the web document (50 in this case) has been reached at which point a resize animation of the header text and area takes place. Then, the reverse happens when that same scroll position is reached while scrolling back up.

 <!DOCTYPE html>  
 <html>  
 <head>  
 <meta name="viewport" content="width=device-width, initial-scale=1">  
 <style>  
 body {   
  margin: 0;  
  font-family: Arial, Helvetica, sans-serif;  
  color: white;  
  background-color: black;  
 }  
 #header {  
  background-color: green;  
  padding: 30px 30px;  
  color: lightblue;  
  text-align: left;  
  font-size: 74px;   
  font-weight: bold;  
  position: fixed;  
  top: 0;  
  margin-bottom:5%;  
  width: 100%;  
  transition: 0.4s;  
 }  
 </style>  
 </head>  
 <body>  
 <div id="header">Hello.</div>  
 <div style="margin-top:190px; padding:15px 15px 250px 15px;">  
   <p>Lorem ipsum dolor dummy text sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ipsum dolor dummy text sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor dummy text sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ipsum dolor dummy text sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor dummy text sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ipsum dolor dummy text sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor dummy text sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur   
      tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor dummy text sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ipsum dolor dummy text sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor dummy text sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ipsum dolor dummy text sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor dummy text sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ipsum dolor dummy text sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor dummy text sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ipsum dolor dummy text sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor dummy text sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ipsum dolor dummy text sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor dummy text sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ipsum dolor dummy text sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor dummy text sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ipsum dolor dummy text sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ipsum dolor dummy text sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor dummy text sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ipsum dolor dummy text sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor dummy text sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ipsum dolor dummy text sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.  
  </p>  
  <br />  
  The end.  
 </div>  
 <script>  
 window.onscroll = function() {scrollFunction()};  
 function scrollFunction() {  
  var hdr = document.getElementById("header")  
  if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {  
   hdr.style.fontSize = "30px";  
   hdr.style.height = "2%";  
  } else {  
   hdr.style.fontSize = "74px";  
   hdr.style.height = "10%";  
  }  
 }  
 </script>  
 </body>  
 </html>  


Reference: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_shrink_header_scroll

TwickrTape

Real-time scrolling Tweets related to financial news alerts and updates. Just enter the Twitter handle you want to see a marquee of live streaming tweets from.

TL;DR - the working app is here: https://twickrtape.azurewebsites.net
..znd here on Google Play Store: https://play.google.com/store/apps/details?id=io.cordova.twicktape

Use button in lower-left to toggle different Twitter handles

The code is a hodgepodge of various references and vestiges of past personal projects. My initial aim was to get something working end-to-end as I envisioned, and I was able to achieve that pretty easily through the Twitter API and .NET.

The process is standard API stuff- first you authenticate and receive a token which you can then subsequently pass to prove that your requests are valid. Then, using simple (REST API) HTTP GET, we get the content (Twitter Timeline information) that we are interested in.

The gist of the code is .NET C# (an ASP.NET Controller method) and listed below:

  public ActionResult GetTwickr(string handle = "business")  
     {  
       // Set your own keys and screen name  
       var oAuthConsumerKey = "XXXXXXXXXXXXX"; // "API key";  
       var oAuthConsumerSecret = "XXXXXXXXXXXXXXXXXXXXX"; // "API secret key";  
       var oAuthUrl = "https://api.twitter.com/oauth2/token";  
       var screenname = "@" + handle; // default Twitter display current status  
       // Authenticate  
       var authHeaderFormat = "Basic {0}";  
       var authHeader = string.Format(authHeaderFormat,  
         Convert.ToBase64String(Encoding.UTF8.GetBytes(Uri.EscapeDataString(oAuthConsumerKey) + ":" +  
         Uri.EscapeDataString((oAuthConsumerSecret)))  
       ));  
       var postBody = "grant_type=client_credentials";  
       HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(oAuthUrl);  
       authRequest.Headers.Add("Authorization", authHeader);  
       authRequest.Method = "POST";  
       authRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";  
       authRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;  
       using (Stream stream = authRequest.GetRequestStream())  
       {  
         byte[] content = ASCIIEncoding.ASCII.GetBytes(postBody);  
         stream.Write(content, 0, content.Length);  
       }  
       authRequest.Headers.Add("Accept-Encoding", "gzip");  
       WebResponse authResponse = authRequest.GetResponse();  
       // deserialize into an object  
       TwitAuthenticateResponse twitAuthResponse;  
       using (authResponse)  
       {  
         using (var reader = new StreamReader(authResponse.GetResponseStream()))  
         {  
           System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();  
           var objectText = reader.ReadToEnd();  
           twitAuthResponse = JsonConvert.DeserializeObject<TwitAuthenticateResponse>(objectText);  
         }  
       }  
       try  
       {  
         // Get timeline info  
         var timelineFormat = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name={0}&include_rts=1&exclude_replies=1&count=5";  
         var timelineUrl = string.Format(timelineFormat, screenname);  
         HttpWebRequest timeLineRequest = (HttpWebRequest)WebRequest.Create(timelineUrl);  
         var timelineHeaderFormat = "{0} {1}";  
         timeLineRequest.Headers.Add("Authorization", string.Format(timelineHeaderFormat, twitAuthResponse.token_type, twitAuthResponse.access_token));  
         timeLineRequest.Method = "GET";  
         WebResponse timeLineResponse = timeLineRequest.GetResponse();  
         var timeLineJson = string.Empty;  
         string scrolltxt = string.Empty;  
         using (timeLineResponse)  
         {  
           using (var reader = new StreamReader(timeLineResponse.GetResponseStream()))  
           {  
             timeLineJson = reader.ReadToEnd();  
           }  
         }  
         // deserialize into an object  
         dynamic obj = JsonConvert.DeserializeObject(timeLineJson);  
         foreach (var r in obj.Root)  
         {  
           scrolltxt += " ***** " + r.text;  
         }  
         var model = new LoggedInUserTimelineViewModel { TimelineContent = scrolltxt, Handle = handle };  
         return View("TwickrMain", model);  
       }  
       catch (Exception e) { }  
       return View("TwickrMain");  
     }  

Next, using Newtonsoft,Json JsonConvert() function, we deserialize the JSON response and zero in on the 'text' property of each entity (tweet) in the array of JSON results (tweets).

And finally, using some basic Bootstrap HTML, JavaScript and CSS we are able to wire up a very simple, but effective app that interacts with the Twitter API in real-time.

Reference: https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline.html

Refactoring Made Obvious

Refactoring (as a term if not as a practice) gets thrown around quite a bit. Sometimes really necessary refactoring doesn't get the priority it deserves because it is hard to quantify or even visualize/sense the result of a good refactoring (it should be relatively transparent in experience to the original, any differences should be optimization or enhancement- without losing of the original functionality along the way). We can take the case of a simple JavaScript animation, for example.

Simple animating of "+" dropping across the browser screen

Long ago, I used a mobile app that had a neat UI animation feature I really liked, but it took me a while to track down just how to accomplish it. I found some good starting points on SO, and began implementing a draft on JSFiddle.net.

The animation behavior I went about creating is simply a delay of an HTML element falling from the screen (via the "topToBottom" variable you'll see below- which is just the browser screen height property) . In a cascading and sequential set of delays, each falling element is pushed an increasing distance from the left of the screen so that the elements can fall independently (otherwise you would see just one column for all of the falling +'s in the end result).

In the following 4 steps, I am going to present a very basic refactoring scenario- going from the code template references I found, to the final refactored code (css, html and .js).

(1) First I found a fiddle via the SO question reference below: http://jsfiddle.net/reWwx/4/

(2) I then changed the code to create my own draft on JSFiddle.net: http://jsfiddle.net/reWwx/539/

(3) Next, I created an .htm file with the CSS styles and JavaScript inline (not quite what we'd want to check into source control...):
 <html>  
 <head>  
 <style>  
 body {height: 600px; background-color: #999}  
 #line-3 {  
   position:absolute;  
   width:100%;  
   left:20px;  
   top:0px;  
 }  
 #line-4 {  
   position:absolute;  
   width:100%;  
   left:30px;  
   top:0px;  
 }  
 #line-5 {  
   position:absolute;  
   width:100%;  
   left:40px;  
   top:0px;  
 }  
 #line-6 {  
   position:absolute;  
   width:100%;  
   left:55px;  
   top:0px;  
 }  
 #line-7 {  
   position:absolute;  
   width:100%;  
   left:70px;  
   top:0px;  
 }  
 #line-8 {  
   position:absolute;  
   width:100%;  
   left:85px;  
   top:0px;  
 }  
 #line-9 {  
   position:absolute;  
   width:100%;  
   left:100px;  
   top:0px;  
 }  
 #line-10 {  
   position:absolute;  
   width:100%;  
   left:115px;  
   top:0px;  
 }  
 #line-11 {  
   position:absolute;  
   width:100%;  
   left:130px;  
   top:0px;  
 }  
 #line-12 {  
   position:absolute;  
   width:100%;  
   left:145px;  
   top:0px;  
 }  
 #line-13 {  
   position:absolute;  
   width:100%;  
   left:160px;  
   top:0px;  
 }  
 #line-14 {  
   position:absolute;  
   width:100%;  
   left:175px;  
   top:0px;  
 }  
 #line-15 {  
   position:absolute;  
   width:100%;  
   left:195px;  
   top:0px;  
 }  
 #line-16 {  
   position:absolute;  
   width:100%;  
   left:210px;  
   top:0px;  
 }  
 </style>  
 <script>  
 $(document).ready(function(){  
   var bodyHeight = $('body').height();  
   var footerOffsetTop = $('#line-3').offset().top;  
   var topToBottom = bodyHeight -footerOffsetTop;  
  $('#line-3').css({top:'auto',bottom:topToBottom});  
  $("#line-3").delay(100).animate({  
   bottom: '100px',  
   }, 2200);   
  $('#line-4').css({top:'auto',bottom:topToBottom});  
  $("#line-4").delay(108).animate({  
   bottom: '100px',  
   }, 2200);   
  $('#line-5').css({top:'auto',bottom:topToBottom});  
  $("#line-5").delay(145).animate({  
   bottom: '100px',  
   }, 2200);   
  $('#line-6').css({top:'auto',bottom:topToBottom});  
  $("#line-6").delay(119).animate({  
   bottom: '100px',  
   }, 2200);   
  $('#line-7').css({top:'auto',bottom:topToBottom});  
  $("#line-7").delay(115).animate({  
   bottom: '100px',  
   }, 2200);   
    $('#line-8').css({top:'auto',bottom:topToBottom});  
  $("#line-8").delay(176).animate({  
   bottom: '100px',  
   }, 2100);   
    $('#line-9').css({top:'auto',bottom:topToBottom});  
  $("#line-9").delay(13).animate({  
   bottom: '100px',  
   }, 2200);   
    $('#line-10').css({top:'auto',bottom:topToBottom});  
  $("#line-10").delay(12).animate({  
   bottom: '100px',  
   }, 2200);   
    $('#line-11').css({top:'auto',bottom:topToBottom});  
  $("#line-11").delay(11).animate({  
   bottom: '100px',  
   }, 2000);   
    $('#line-12').css({top:'auto',bottom:topToBottom});  
  $("#line-12").delay(10).animate({  
   bottom: '100px',  
   }, 2100);   
    $('#line-13').css({top:'auto',bottom:topToBottom});  
  $("#line-13").delay(11).animate({  
   bottom: '100px',  
   }, 600);   
    $('#line-14').css({top:'auto',bottom:topToBottom});  
  $("#line-14").delay(14).animate({  
   bottom: '100px',  
   }, 700);   
      $('#line-15').css({top:'auto',bottom:topToBottom});  
  $("#line-15").delay(14).animate({  
   bottom: '100px',  
   }, 800);   
      $('#line-16').css({top:'auto',bottom:topToBottom});  
  $("#line-16").delay(24).animate({  
   bottom: '100px',  
   }, 900);   
 })  
 </script>  
 </head>  
 <body>  
 <div id="line-3">+</div>  
 <div id="line-4">+</div>  
 <div id="line-5">+</div>  
 <div id="line-6">+</div>  
 <div id="line-7">+</div>  
 <div id="line-8">+</div>  
 <div id="line-9">+</div>  
 <div id="line-10">+</div>  
 <div id="line-11">+</div>  
 <div id="line-12">+</div>  
 <div id="line-13">+</div>  
 <div id="line-14">+</div>  
 <div id="line-15">+</div>  
 <div id="line-16">+</div>  
 </body>    
 </html>  
(4) And lastly I identified all of the repeating parts and made them dynamic in JavaScript, using the jQuery library to shorten much of the .js behavior:
  <html>   
  <head>   
  <style>   
  body {height: 600px; background-color: #000000; color:lime;}   
  div {   
   position:absolute;   
   top:0px;   
    width:100%;   
  }   
  </style>   
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>   
  <script>   
  $(document).ready(function(){   
   var base = $('#base');  
   var topToBottom = $('body').height();    
   for(i=0; i<83; i++){   
    base.append('<div id=\"line-'+i+'\" style=\"left:'+ Math.abs(i*10) +'\px">+</div>')   
    $("#line-" + i).css({top:'auto', bottom:topToBottom}).delay(100*i).animate({bottom: '100px'}, (1000));    
   }   
  })   
  </script>   
  </head>   
  <body id="base">   
  </body>    
  </html>   

The final result contains the same behavior of the draft but it eliminates repetition by dynamically generating the HTML and dynamically attaching the falling action (which is really just coordinated position and visibility property changes behind the scenes of .animate()). Eliminating duplication, standardizing for better readability, reorganization for better clarity of code purpose and finding patterns (or finding different patterns that are a better match for the task) are the key concepts in refactoring.

Try it yourself by copying the code above, saving to an .htm file and opening the file in a web browser.

Final JSFiddle result: https://jsfiddle.net/radagast/6uzypc80/5

Larger font is always fun: https://twickrtape.azurewebsites.net/Home/About

Reference: https://stackoverflow.com/questions/8518400/jquery-animate-from-css-top-to-bottom

JavaScript for Progress on Scrolling

This topic is a prime example of why I write this web log. I've seen this functionality on countless web pages and mobile apps, but for some reason it is not well explained in most of the areas you will likely first wind up when searching for instructions on how to do this (if you wound up here first great, yay me).

Potential applications of progress on scroll might be a "Terms and Conditions" view, a code walk-through, etc.

The key code is all in $(window).scroll(function(). You have these 3 main components:

  • Document Height: $(document).height() === height of "viewable" window aka viewport
  • Window Height: $(window).height() === height of document being rendered
  • Scroll Top: $(window).scrollTop() === number of pixels content is scrolled

With these values you can set the width of the progress bar (the div with the class "scroll-progress-container"). The width is a simple calculation: scrollTop / (docHeight - windowHeight) * 100.

So you can attach this logic to an anonymous function within the browser's window scroll event a la: $(window).scroll(function() { ...

And then simply assign the result of  "$(window).scrollTop() / (docHeight - windowHeight) * 100;" to the width property of your <div class="scroll-progress">.

That's it.

Code:

 <!doctype html>  
 <head>  
 <title></title>  
 <style>  
 .header-container {  
  width: 100%;  
  height: 60px;  
  background-color: white;  
  position: fixed;  
  z-index: 10;  
  top: 0;  
  left: 0;  
 }  
 .header {  
  padding-left: 10px;  
 }  
 h1 {  
  margin-top: 15px;  
 }  
 .scroll-progress-container {  
  width: 100%;  
  height: 5px;  
  background-color: white;  
  top: 55px;  
  position: absolute;  
 }  
 .scroll-progress {  
  width: 0px;  
  height: 5px;  
  background-color: purple;  
 }  
 .filler-text {  
  width: 60%;  
  margin-top: 80px;  
  margin-left: 50px;  
  position: absolute;  
 }  
 </style>  
 <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>  
 <script>  
  $(document).ready(function() {  
    var docHeight = $(document).height(),  
    windowHeight = $(window).height(),  
    scrollPercent;  
     $(window).scroll(function() {  
       scrollPercent = $(window).scrollTop() / (docHeight - windowHeight) * 100;  
       $('.scroll-progress').width(scrollPercent + '%');  
     });  
 });  
 </script>  
 </head>  
 <body>  
 <div class="header-container">  
 <div class="header">  
 <h1>Progress Scroll Bar Example</h1>  
 </div>  
 <div class="scroll-progress-container">  
 <div class="scroll-progress"></div>  
 </div>  
 </div>  
 Enter lots and lots of text here...  
 </body>  
 </html>  


References

https://www.veracode.com/blog/managing-appsec/building-scroll-progress-bar-javascript-and-jquery

https://stackoverflow.com/questions/14035819/window-height-vs-document-height

Application Walkthroughs with Anno.js

If you need to provide your users a quick intro to your app or new features that you have just released, you might want to give Anno.js a try. Of the several frameworks I sampled, this is was the sharpest looking and easiest to work with (for me, maybe for you too).


To configure:

1). Link to or host the required files in the DemoAnno.html <head> (see code on GitHub).

2). Configure the annoJS object by setting targets (by element selector, '#demo', '.walkDivs', etc.)

3). Create a button and set its onClick() == anno.show(); //anno, or the name of the annoJS object


And in 3 simple steps, you have a walkthrough:






All credit to @iamdanfox who created this great .js plug in. Here is the htm page source code, see references below for more:

 <html>  
 <head>  
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>  
 <script src="anno.js" type="text/javascript"></script>  
 <script src="jquery.scrollintoview.min.js" type="text/javascript"></script>  
 <link href="anno.css" rel="stylesheet" type="text/css" />  
 </head>  
 <body>  
 <div style="background-color='gray'; margin-left:33%;">  
 <b><i>Use this guided tour to see our latest features!</i></b>  
 <br/>  
 <button type="button" class="btn btn-default" onclick="anno.show();">Show Tour</button>  
 <br/>  
 <br/>  
 <div id="demo" style="width:27%;">  
 Your new login button is here: <button name="LOGIN" value="LOGIN">LOGIN</button>  
 <div>  
 </div>  
 <br />  
 </body>  
 <script>  
      var anno = new Anno([{  
       target: '#demo',  
       position:'left',  
       content: "This is our shiny new left div edge!",  
       buttons: [AnnoButton.NextButton]  
      }, {  
       target: '#demo',  
       position:'right',  
       content: "...and on the right...",  
       buttons: [AnnoButton.BackButton]  
      }]);       
 </script>  
 <html>  
Note the NextButton and BackButton- these are very useful for app walkthroughs


GitHub: https://github.com/Radagast27/AnnoJS_WalkthroughDemo

References: http://iamdanfox.github.io/anno.js/

https://github.com/iamdanfox/anno.js#usage

Working with Date and Time in JavaScript

If you have a requirement to get ShortDate (1/11/1900) and AM/PM time down to the second (2:12:27 PM) from a JavaScript Date object; use this Date prototype method "formatMMDDYYYY()" on the Date object:

 Date.prototype.formatMMDDYYYY = function(){  
 return (this.getMonth() + 1) +  
 '/' + this.getDate() +  
 '/' + this.getFullYear();  
 }  
 var time = new Date();  
 console.log(time.formatMMDDYYYY() + ' ' +  
 time.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', second: 'numeric', hour12: true })  
 );  

Say we want to calculate the number of days between two given dates. We can utilize this .js function:

 function getDays(firstDate,secondDate){  
  var startDay = new Date(firstDate);  
  var endDay = new Date(secondDate);  
  var millisecondsPerDay = 1000 * 60 * 60 * 24;  
  var millisBetween = startDay.getTime() - endDay.getTime();  
  var days = millisBetween / millisecondsPerDay;  
  // Round down.  
  return Math.floor(days);  
 }  
 alert(getDays(Date(), '1/1/2017'));  

Also, although not referenced above because I wanted to show pure/plain .js in the example, there are several .js libraries for Date operations. The most popular of which seems to currently be: https://momentjs.com/

Reference: https://stackoverflow.com/questions/2035699/how-to-convert-a-full-date-to-a-short-date-in-javascript/2035706

Animated X-to-Horizontal Lines (Hamburger) Toggle for UI Menu

Here is what you are looking for: https://codepen.io/radagast27/pen/OYmvmd

Implementing this UI feature is just a matter of wiring up some icon animation and fadeIn()/fadeOut() to the menu items.

 <html>  
 <head>  
 <script  
  src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>  
 <script>  
 $(document).ready(function(){  
      $('#nav-icon').click(function(){  
           $(this).toggleClass('open');  
       if($('#menu').css('opacity') == '0'){  
        $('#menu').css('opacity','1');  
        $('#menu').fadeIn(300).css('display','table');  
       }else{  
        $('#menu').css('opacity','0');  
        $('#menu').fadeOut(300).css('display','none');  
       }  
      });  
 });  
 </script>  
 </head>  
 <style>  
 body{  
  background-color: #000000;  
 }  
 #menu{  
   z-index: 5;  
   width: 40%;  
   height: 40%;  
   background-color: rgba(0,0,0, 0.95);  
   position: fixed;  
   font-family: Arial;  
   font-size: 1.5em;  
   text-align: left;  
   left: 100px;  
   top: 0px;  
   opacity: 0;  
   display: table;  
 }  
 .hidden{  
   display: none;  
   visibility: none;  
 }  
 #menu ul{  
   margin: 0;  
   padding: 0;  
   z-index: 10;  
   width: 40%;  
   height: 40%;  
   display: table-cell;  
   vertical-align: left;  
 }  
 #menu ul li{  
   cursor: pointer;  
   text-decoration: none;  
 }  
 #menu ul li:hover{  
   background-color: cyan;  
   -webkit-transition: .15s ease-in-out;  
   -moz-transition: .15s ease-in-out;  
   -o-transition: .15s ease-in-out;  
   transition: .15s ease-in-out;  
 }  
 #menu ul a{  
   letter-spacing: 5px;  
   text-align: left;  
   margin-left: 0px;  
   color: #fff;  
   list-style: none;  
   padding: 0px;  
   line-height: 75px;  
   padding: 10px 70px;  
   text-decoration: none;  
 }  
 #menu ul a:hover{  
   text-decoration: none;  
   color: #fff ;  
 }  
 #nav-icon {  
   z-index: 20;  
  width: 50px;  
  height: 35px;  
  position: relative;  
  margin: 25px;  
  -webkit-transform: rotate(0deg);  
  -moz-transform: rotate(0deg);  
  -o-transform: rotate(0deg);  
  transform: rotate(0deg);  
  -webkit-transition: .5s ease-in-out;  
  -moz-transition: .5s ease-in-out;  
  -o-transition: .5s ease-in-out;  
  transition: .5s ease-in-out;  
  cursor: pointer;  
 }  
 #nav-icon span {  
  display: block;  
  position: absolute;  
  height: 5px;  
  width: 40px;  
  background: #bada33;  
  opacity: 1;  
  -webkit-transform: rotate(0deg);  
  -moz-transform: rotate(0deg);  
  -o-transform: rotate(0deg);  
  transform: rotate(0deg);  
  -webkit-transition: .25s ease-in-out;  
  -moz-transition: .25s ease-in-out;  
  -o-transition: .25s ease-in-out;  
  transition: .25s ease-in-out;  
 }  
 /* Icon 3 */  
 #nav-icon span:nth-child(1) {  
  top: 0px;  
 }  
 #nav-icon span:nth-child(2),#nav-icon span:nth-child(3) {  
  top: 12px;  
 }  
 #nav-icon span:nth-child(4) {  
  top: 24px;  
 }  
 #nav-icon.open span:nth-child(1) {  
  top: 8px;  
  width: 0%;  
  left: 50%;  
 }  
 #nav-icon.open span:nth-child(2) {  
  -webkit-transform: rotate(45deg);  
  -moz-transform: rotate(45deg);  
  -o-transform: rotate(45deg);  
  transform: rotate(45deg);  
 }  
 #nav-icon.open span:nth-child(3) {  
  -webkit-transform: rotate(-45deg);  
  -moz-transform: rotate(-45deg);  
  -o-transform: rotate(-45deg);  
  transform: rotate(-45deg);  
 }  
 #nav-icon.open span:nth-child(4) {  
  top: 8px;  
  width: 0%;  
  left: 50%;  
 }  
 </style>  
 <body>  
 <header>  
   <div id="topbar"> <!-- top bar -->  
       <div id="nav-icon">  
        <span></span>  
        <span></span>  
        <span></span>  
        <span></span>  
       </div>  
     <div id="menu">  
       <ul>  
         <li><a href="#">Home</a></li>  
         <li><a href="#">About Us</a></li>  
         <li><a href="#">Portfolio</a></li>  
         <li><a href="#">Case Studies</a></li>  
         <li><a href="#">Careers</a></li>  
       </ul>  
     </div>  
   </div>  
 </header>  
 </html>  
 </body>  
Some minor tweaking of the flexible code referenced above can give you a modern .js transition toggle


Reference: https://jsfiddle.net/f19kz640/

Developer Scratchpad (.NET C#, VB, JavaScript, Powershell, Python, SQL, etc.)

If you memorize infrequently used code, you are wasting mental storage space- reference notes!



--------NETWORK-----------------------------------------------------------
--------------------------------------WINDOWS BUILTIN CMDs-------------------------------------
//converting Windows back slashes to Unix forward slashes
SET string=C:\Users\Admin\Desktop\DeskDEV\
ECHO %string:\=/%
//converting Unix forward slashes to Windows back slashes
SET string=C:/Users/Admin/Desktop/DeskDEV/
ECHO %string:/=\%
netsh interface ip show config
netsh interface ip set address "Local Area Connection" static 192.168.0.10 255.255.255.0 192.168.0.254
netsh interface ip set address "Local Area Connection" dhcp
netsh http show urlacl
netsh int tcp set heuristics disabled
netsh int tcp set global autotuninglevel=disabled
netsh int tcp set global rss=enabled
netsh int tcp show global
netsh winsock reset
netsh int ip reset
ipconfig /release
ipconfig /renew
ipconfig /flushdns
ipconfig /registerdns
msdt.exe -id NetworkDiagnosticsWeb
msdt.exe -id NetworkDiagnosticsInbound
msdt.exe -id NetworkDiagnosticsNetworkAdapter
ipconfig
sfc /scannow
driverquery
ping and pathping
tasklist and taskkill
nslookup
sigverif
doskey /history
netstat
cipher
getmac
net user
arp
nbstat
logman
route
shutdown
assoc
schtasks
attrib
auditpol
bcdboot
bcdedit
bootcofg
bootsect
cacls
call
cd
certreq
certutil
chcp - (active code page)
checknetisolation
chkdsk
chkntfs
choice - ([Y,N]? prompt in .bat)
cipher - (enc status of files)
clip
cls
cmstp - (connectionMgr interesting*)
comp - (basic file diff)
compact - (compress)
convert - (file system type)
copy
cscript - (execute vbs, etc.)
date
debug - (only on DOS && 32bit Windows)
defrag
del
deltree
dir
diskpart*
diskperf
diskraid
dism - (dply .isos)
dispdiag
djoin - (join domain)
driverquery - (all driver information!)
echo
endlocal - (break out of a script's localalized context)
erase
esentutl - (storage engine mgmt)
eventcreate
expand - (unzip archive)
Extrac32 - (unzip .cab)
extract - (unzip archive)
fc - (compare file sets)
find - (srch for text in file or files)
Findstr - (regex "")
finger - user(s) info
Fltmc - (filter driver installer)
fondue - (new/experimental Windows features)
format - (format drive for some file system)
fsutil - (filesys utiles)
ftp - (chell for ftp comms; "quit")
ftype - default programs
getmac - get MAC of all network controllers on system
gpresult - (grp policy)
gpupdate
icacls
iscsicli - (iSCSI initiator)
klist - Kerberos tickets
Ksetup - (for a kerberos-enabled server)
ktmutil - (kernal transaction mgr utility)
label - (volume label of disks)
licensingdiag - (Windows product activation info)
loadhigh(lh), lock - (old DOS cmds)
lodctr - (registry values for perf counters)
logman - (event trace session)
logoff - (until Win7)
makecab - (cainet maker)
manage-bde - (Bitlocker drive enc)
mklink - (create symbolic link)
mode - (COM/LPT ports - check "CON" device further)
mofcomp - .mof* file display
more
mount - (until SFU was discontinued...)
mountvol - (use this instead)
move
mrinfo - (rounter info)
msg
msiexec - (start an install)
muiunattend - (unattended install)
nbtstat - (see connection info)
net - (cfg network settings)
net1 - ("" "" Y2K issue wkrnd/patch for net)
netcfg - (installs WinPE)
netsh - (network shell, net mgmt)
netstat - (displays listening ports, connects)
nltest - (test secure channels between machines across trusted domains)
nslookup - (hostname from IP)
openfiles - (remote cmd)
path
pathping - (tracert w/net latency, more info)
pause - (Press any key to continue...)
ping
pkgmgr - (windows pkg mgr)
pnpunattend - (unattended driver install)
pnputil
popd
powercfg
print
prompt
pushd
rasautou
rasdial*
rcp - (deprecated)
rd
reagentc - (win recovery)
recover - (recover a file deleted, but not yet overwritten)
reg - (registry cmds)
regini - (hange registry permissions and registry values from the command line)
Regsvr32 - (register .dll as component)
relog - (new perf append to existuing perf data)
rem
ren
repair-bde - (Bitlocker repair)
replace
rmdir
robocopy - (robust copy)
route - (maniupulate network routing tables)
Rpcping
runas
schtasks
sdbinst - (SDB db files, used by OpenOffice)
secedit - (compare current sec levels to a template to ensure no unneeded access, etc.)
setspn - (set service principle name for an AD account)
setx - (user env variable config)
sfc - (System File Checker)
shutdown - (automate poweroff)
sort
sxstrace - tracing
subst - (assoc local path with drive letter; similiar to net use)
takeown - regain access to object
taskkill - (force kill a process)
tasklist - (running proccesses; used by taskmgr.exe, etc.)
tcmsetup - (to set up or disable the Telephony Application Programming Interface (TAPI) client)
telnet
tftp (deprecated?)
time
timeout
title - (cmd prompt window label)
tracerpt - trace rpt
tracert - Internet Control Message Protocol (ICMP) Echo Request messages to a specified remote computer with increasing Time to Live (TTL) field values and displays the IP address and hostname, if available, of the router interfaces between the source and destination.
tree - (awesome)
typeperf - (cmd perf data)
tzutil - (time zones)
unlodctr - (uninstalls a perf counter in registry)
vaultcmd - (manage Windows stored creds)
ver
vol
vssadmin - (volume shadow copy admin)
w32tm - (windows time)
wecutil - (win evt collector)
where - (find by regex)
whoami
winmgmt - (WMI)
winrm - (remote mgmt)
winrs - (remote sh)
winsat - (system assesment tool)
wmic - (WMI CLI)
wsmanhttpconfig
xcopy
xwizard - (register data in Windows, often from a preconfigured XML file)


-------POWERSHELL---------------------------------------------------
Get-Command -Name {..}
get-alias
Get-Help Get-EventLog
Get-ChildItem c:/
$var
(no concept of scope- ALL is glbl)
Remove-Item
//ex. of getting some scv column data...
Get-Command -Verb Export | Select-Object CommandType, Name, Version, Source | Export-Csv -NoTypeInformation -Path C:\NewFolder\ExportCommands.CSV
//Outfile is useful
Get-Command -Verb Export | Select-Object CommandType, Name, Version, Source | Out-File C:\NewFolder\ExportCommands.txt
Get-Process -Id 10500 | Stop-Process
Get-EventLog -LogName System -Newest 5
Clear-EventLog "Windows PowerShell"
Get-WmiObject -List -Class Win32*
Enter-PSSession Computer1
Invoke-Command -ComputerName Computer1, Computer2, Computer3, -ScriptBlock {Get-Process}
//Create a new (persistant) session, and save it
$session = New-PSSession -ComputerName Computer1, Computer2
Set-ExecutionPolicy
Get-ExecutionPolicy
Get-Service | Where-Object {$_.status -eq "stopped"}
//Create html from basic data structs (in this case, ps cmdlet aliases)
get-alias | convertto-html > aliases.htm
invoke-item aliases.htm
Get-EventLog -Log "Application"
Stop-Process -processname note*
Get-Service | Where-Object {$_.Status -eq 'Running'}
Get-AuthenticodeSignature somescript.ps1 @(Get-ChildItem cert:\CurrentUser\My -codesigning)[0] -IncludeChain "All" -TimestampServer "http://timestamp.verisign.com/scripts/timstamp.dll"
Get-Process | ForEach-Object {Write-Host $_.name -foregroundcolor cyan}
Clear-Content C:\Temp\TestFile.txt
Clear-Content -path * -filter *.TXT –force (all text files force clear)
Checkpoint-Computer -Description "My 2nd checkpoint" -RestorePointType "Modify_Settings"
Get-ComputerRestorePoint | format-list
Compare-Object $obj1 $obj2
 [string[]]$arrayFromFile = Get-Content -Path 'C:\someplace\file.txt'
 foreach ($uri in $arrayFromFile) {
   yt-dl -f 140 $uri
  }
$settings = $TextData | ConvertFrom-StringData
ConvertTo-SecureString [-String] SomeString
Get-Service wuauserv -ComputerName chi-dc04,chi-p50,chi-core01 |
Export-Clixml -Path c:\work\wu.xml
Get-AppLockerPolicy
New-ItemProperty
$ourObject = New-Object -TypeName psobject
/////////////////////////////////////////////////////
$url = http://<webapp>.azurewebsites.net/CreateSite.asmx
$proxy = New-WebServiceProxy $url
$spAccount = "<username>"
$spPassword = Read-Host -Prompt "Enter password" –AsSecureString
$projectGuid = ""
$createOneNote = $false
$proxy | gm -memberType Method
New-WSManInstance winrm/config/Listener
-SelectorSet @{Address="*";Transport="HTTPS"}
-ValueSet @{Hostname="Test01";CertificateThumbprint="01F7EB07A4531750D920CE6A588BF5"}
/////////////////////////////////////////////////////
Get-Process | Sort-Object name -Descending | Select-Object -Index 0,1,2,3,4
New-Alias np c:\windows\system32\notepad.exe
Set-StrictMode
Wait-Job
Write-Progress -PercentComplete (($var1/$var2) * 100))
$job = Start-Job -ScriptBlock { Set-PSBreakpoint C:\DebugDemos\MyJobDemo1.ps1 -Line 8; C:\DebugDemos\MyJobDemo1.ps1 }
Debug-Job $job
Get-Counter -Counter "\Processor(_Total)\% Processor Time" -SampleInterval 2 -MaxSamples 3
Test-Path C:\Scripts\Archive
Get-WinEvent -ListLog *
Invoke-TroubleshootingPack (Get-TroubleshootingPack C:\Windows\diagnostics\system\networking)
Measure-Command
Get-Process | Measure-Object VirtualMemorySize -Sum
New-EventLog -LogName Wtf_Log -Source SomewhereOutThere
Receive-Job -Name HighMemProcess
Register-EngineEvent PowerShell.Exiting -Action {"PowerShell exited at " + (Get-Date) | Out-File c:\log.txt -Append}
Register-ObjectEvent
Remove-Event
Set-PSDebug
Start-Sleep
Tee-Object
Test-AppLockerPolicy
Test-ComputerSecureChannel
Trace-Command
Write-Debug "`$return has $($return.count) items"

-------VISUAL STUDIO----------------------
Ctrl+, . for Autosuggest
Sort usings by Right-click on using references

--------.NET------------------------------------------------------
--------------------------C#--------------------------------------
//switch expression*
car foo = line switch {
case 0: foo = 1; break;
case 0: foo = 1; break;
default: for = 0; break;
}
XDocument.Parse is for string XML
XDocument.Load is for XML *Files*
[,] is multidimensional array and [][] is array of arrays.
//collection initializer
List<Coord> ls = new List<Coord>() { new Coord { x = 1, y = 2 }, new Coord { x = 11, y = 12 }};
//lambda expression value
var filteredList = list.Where(o => o.id == targetGUID);
//Make the internals visible to the test assembly for unit testing private dependencies, etc.
[assembly: InternalsVisibleTo("MyTestAssembly")] in the AssemblyInfo.cs file.
//Obsolete attribute to warn that an assembly may go away and that alternatives should be used asap
Obsolete("This method will be deprecated soon. You could use XYZ alternatively.")]
//To prevent a repetition of the execution, change the LINQ result to List after execution
var result = masterCollection.Where(i => i > 100).ToList();
Console.WriteLine(result.Count()); //no extra Linq executions
Console.WriteLine(result.Average()); //no extra Linq executions
//catch Generic Exception and throw for more detail
catch (Exception)
      throw;
//Generic Type using a common Interface
protected class MyGenricClass<T> where T : IMyInterface
public void MyGenericMethod<T>(T t) where T : IMyInterface
//using obj reference for brevity and cleaner code
using (SqlConnection conn = new SqlConnection(strConnection)) { ... }
//aslias namespaces for brevity if you need to explicitly spell out the namespace anywhere
using Excel = Microsoft.Office.Interop.Excel;
var excelapp = new Excel.Application();
//object initializer
Janitor jenkins = new Janitor() { Name = "Jenkins", Address = "1212 DeplPipelnSciptzzz" };
//null checks
if (string.IsNullOrEmpty(s))
//Connection String
"Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;"
//Entity Framework Optimizer/Escape Hatch
using (var db = new MyContext())
{
    db.Query<FooBar>().FromSql("SELECT ProductID, udf_GetNameFromId(ID3) FROM Products");
}
//JSON Serialize and Deserialize with Newtonsoft
string serial = JsonConvert.SerializeObject(genericObject);
var deserial = JsonConvert.DeserializeObject<APIGenericItemsResponse>(await response.Content.ReadAsStringAsync());
//XML Serialize using System.Xml.Serialization
 public void TestSerialize(XMLEntityCollection ents)
     {
       XmlSerializer xmlSerializer = new XmlSerializer(ents.GetType());
       using (StringWriter stringWriter = new StringWriter())
       {
         xmlSerializer.Serialize(stringWriter, ents);
         Assert.IsNotNull(stringWriter);
       }
     }
//XML Deserialize using System.Xml.Serialization
XmlSerializer serializer = new XmlSerializer(typeof(XMLEntityCollection));
       using (StringReader reader = new StringReader(xml))
       {
         XMLEntityCollection ents = (XMLEntityCollection)serializer.Deserialize(reader);
         TestSerialize(ents);
       }
-------------------------VB--------------------------------------
Dim i As Integer = 1
Begin Function(ByVal a As String) As Double
     Return 37
End Function
Namespace MyNamespace
End Namespace
Public Class Manager
     Inherits Employee
End Class
Public Overridable Function CalculateSalary() As Integer
End Function
Public Overrides Function CalculateSalary() As Integer
End Function
MyBase (base in C#)
Public Interface IEmployee
    Property EmployeeID() As Integer
    Property Name() As String
    Property Age() As Integer
    Function CalculateSalary() As Integer
End Interface
Public Class Manager
Implements IEmployee
End Class

--------PYTHON-----------------------------
#cool-youtube-API
youtube-dl -f 140 $uri
#formatting opts for youtube-dl

[info] Available formats for P9pzm5b6FFY:
format code extension resolution  note 
140         m4a       audio only  DASH audio , audio@128k (worst)
160         mp4       144p        DASH video , video only
133         mp4       240p        DASH video , video only
134         mp4       360p        DASH video , video only
135         mp4       480p        DASH video , video only
136         mp4       720p        DASH video , video only
17          3gp       176x144     
36          3gp       320x240     
5           flv       400x240     
43          webm      640x360     
18          mp4       640x360     
22          mp4       1280x720    (best)
#reverse string
a =  "NotPalindrome"
print("Reverse is",a[::-1])
#transpose matrix
mat = [[1, 2, 3], [4, 5, 6]]
zip(*mat)
#store array as indiv vars
a = [1, 2, 3]
x, y, z = a
#print array elments as string
a = ["This", "is", "a", "string"]
print(" ".join(a))
#print coords of 2 combined lists
list1 = ['a', 'b', 'c', 'd']
list2 = ['p', 'q', 'r', 's']
for x, y in zip(list1,list2):
...    print(x, y)
#switch var vals in 1 line
a=2
b=4
b, a =a, b
#execute recursion without loops
print("cool"*2+' '+"beans"*5)
#convert matrix to list without loop
import itertools
a = [[1, 2], [3, 4], [5, 6]]
list(itertools.chain.from_iterable(a))

-------JAVASCRIPT------------------------------------
//Use "var" or "let" when creating any variables Assignment to an undeclared variable automatically //results in a global variable being created. Avoid global variables.
var a = 'not Globl';
=== instead of == (former compares value and type)
//Be careful when using typeof, instanceof and constructor.
var arr = ["a", "b", "c"];
typeof arr;   // return "object"
arr  instanceof Array // true
//get random item from an array
var items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119];
var  randomItem = items[Math.floor(Math.random() * items.length)];
//get random number in a specific range
var x = Math.floor(Math.random() * (max - min + 1)) + min;
//Trim String prototype extension function
String.prototype.trim = function(){return this.replace(/^s+|s+$/g, "");};
//Append array to array
var array1 = [12 , "foo" , {name "Joe"} , -2458];
var array2 = ["Doe" , 555 , 100];
Array.prototype.push.apply(array1, array2);
//Object to Array
var argArray = Array.prototype.slice.call(arguments);
//Verify numeric
function isNumber(n){
    return !isNaN(parseFloat(n)) && isFinite(n);
}
//verify Array type
function isArray(obj){
    return Object.prototype.toString.call(obj) === '[object Array]' ;
}
//Max and Min
var  numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
var maxInNumbers = Math.max.apply(Math, numbers);
var minInNumbers = Math.min.apply(Math, numbers);
//Empty the array
var myArray = [12 , 222 , 1000 ];
myArray.length = 0;
//use splice() not delete() for removing JS array elements
var items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ];
items.length; // return 11
items.splice(3,1) ;
items.length; // return 10
//use map() to loop through array
var squares = [1,2,3,4].map(function (val) {
    return val * val;
});
//rounding a decimal numeric
var num =2.443242342;
num = num.toFixed(4);
//check object props
for (var name in object) {
    if (object.hasOwnProperty(name)) {
        // do something with name                 
    }
}
//Serialize and Deserialize
var person = {name :'Saad', age : 26, department : {ID : 15, name : "R&D"} };
var stringFromPerson = JSON.stringify(person);
/* stringFromPerson is equal to "{"name":"Saad","age":26,"department":{"ID":15,"name":"R&D"}}"   */
var personFromString = JSON.parse(stringFromPerson);
/* personFromString is equal to person object  */
//Best/fastest JS looping structure
var sum = 0;
for (var i = 0, len = arrayNumbers.length; i < len; i++) {
    sum += arrayNumbers[i];
}
//Pass functions (not string ref of function) to SetTimeout() and SetInterval()
setInterval(doSomethingEverySecond, 1000);
setTimeout(doSomethingEveryFiveSeconds, 5000);
//Clone a type
function clone(object) {
    function OneShotConstructor(){};
    OneShotConstructor.prototype= object;
    return new OneShotConstructor();
}
clone(Array).prototype ;  // []
//HTML escape function
function escapeHTML(text) {
    var replacements= {"<": "&lt;", ">": "&gt;","&": "&amp;", """: "&quot;"};                   
    return text.replace(/[<>&"]/g, function(character) {
        return replacements[character];
    });
}
//Set timeouts on async function calls
var xhr = new XMLHttpRequest ();
xhr.onreadystatechange = function () {
    if (this.readyState == 4) {
        clearTimeout(timeout);
        // do something with response data
    }
}
var timeout = setTimeout( function () {
    xhr.abort(); // call error callback
}, 60*1000 /* timeout after a minute */ );
xhr.open('GET', url, true);

xhr.send();

//deal with websocket timeout
var timerID = 0;
function keepAlive() {
    var timeout = 15000;
    if (webSocket.readyState == webSocket.OPEN) {
        webSocket.send('');
    }
    timerId = setTimeout(keepAlive, timeout);
}
function cancelKeepAlive() {
    if (timerId) {
        cancelTimeout(timerId);
    }
}

-------T-SQL-----------------------------------------------------------
SELECT dateadd(mm, datediff(mm, 1, getDate()), 0) as FirstOfTheMonth
SELECT dateadd(ms, -3, dateadd(mm, datediff(m, 0, getDate()) + 1, 0)) as LastOfTheMonth
SELECT dateadd(qq, datediff(qq, 0, getDate()), 0) as FirstDayOfQtr
SELECT dateadd(wk, datediff(wk, 0, dateadd(dd, 6 - datepart(day, getDate()), getDate())), 0)  --(First Monday of Month)
--Find all instances of a 'string' within a string (varchar/nvarchar)
CREATE FUNCTION dbo.FindPatternLocation
(
    @string NVARCHAR(MAX),
    @term   NVARCHAR(255)
)
RETURNS TABLE
AS
    RETURN
    (
      SELECT pos = Number - LEN(@term)
      FROM (SELECT Number, Item = LTRIM(RTRIM(SUBSTRING(@string, Number,
      CHARINDEX(@term, @string + @term, Number) - Number)))
      FROM (SELECT ROW_NUMBER() OVER (ORDER BY [object_id])
      FROM sys.all_objects) AS n(Number)
      WHERE Number > 1 AND Number <= CONVERT(INT, LEN(@string)+1)
      AND SUBSTRING(@term + @string, Number, LEN(@term)) = @term
    ) AS y);
--Windowing for running totals, referencing related rows and row group totals
SELECT xact_amt,
     SUM(xact_amt) OVER (ORDER BY xact_datetime) AS running_total
FROM SOME_DB.dbo.SOME_TABLE
 --Get ids from a csv of ids
 SELECT * FROM string_split('100,101,201,301,411,414', ',')
--Push a series of values into one row
 SELECT playerID,
 STUFF((select '; ' + teamID
      from Managers
      where teamID like('%P%')
            group by teamID
      for xml path('')), 1, 1, '') allTeams
 FROM Managers
--Dynamic SQL
 DECLARE @mult bit = 0
 DECLARE @sqlToExecute varchar(500)
 DECLARE @srvWest varchar(50) = 'WestZoneSqlSrv08'
 DECLARE @srvEast varchar(50) = 'EastZoneSqlSrv08'
 IF @mult = 0
      SET @sqlToExecute = 'SELECT TOP 1 OrderId, PersonId FROM ALGO.dbo.[Order]'
 ELSE
      SET @sqlToExecute = 'SELECT TOP 1 OrderId, PersonId FROM ' + @srvEast + '.ALGO.dbo.[Order] UNION ALL SELECT TOP 1 OrderID, PersonId FROM ' + @srvWest + '.ALGO.dbo.Order' 
 EXEC(@sqlToExecute)
--CTE
WITH Entity (EntityID, Name, ParentID, Tree)
AS
(
   SELECT ID, Val1, Val2 FROM SomeDbServer.dbo.SomeDatabase;
)

SELECT * FROM Entity;

-------GIT------------------------------------------------------
git log
git diff
git init
git branch
git branch -a
git branch <branchname> ((new branch))
git switch <branchname> ((same as checkout))
git merge <branchname> ((merge another branch into current working branch))
git push origin <branchname>
git push -u origin <branchname>
git pull origin <branchname>
git remote add origin <ssh or https URI>

--------WinDbg--------
!sos.threadpool (Strike subset of modules useful (yet safe) for debugging .NET)
!sos.savemodule
!sos.finalizequeue
!mex.us
!mex.aspxpagesext
!mex.mthreads / !sos.threads
!mex.dae
!mex.clrstack2

!sym noisy
g - (Go)
r - (Registers)
d - (virtual memory commands)
!teb - (thread environment block)
!peb - (process execution block)
~{thread id}|| ~*k to execute "each thread" and assoc k cmd on them
k - (look at stacks in debugger => top is end, bottom is init/start 00000000)
? - (evaluation cmd to get HEX equiv)
lm (loaded modules (lm v m malware => show verbose module (m)atching 'malware'))
du - (display Unicode value)
.crash - (forces blue screen crash and .dmp)

-------REGEX--------------------------------------------------
(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?
File Path with Filename and extension
/((\/|\\|\/\/|https?:\\\\|https?:\/\/)[a-z0-9 _@\-^!#$%&+={}.\/\\\[\]]+)+\.[a-z]+$/
 File Path with optional Filename, extension
/^(.+)/([^/]+)$/
File Name with extension having 3 chars
/^[\w,\s-]+\.[A-Za-z]{3}$/
/* Match IPv4 address */
/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/
/* Match IPv6 address */
/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/
/* Match both IPv4, IPv6 addresses */
/((^\s*((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\s*$)|(^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$))/
Elements with Attributes /<\/?[\w\s]*>|<.+[\W]>/
Slug /^[a-z0-9]+(?:-[a-z0-9]+)*$/
Digits
    Whole Numbers – /^\d+$/
    Decimal Numbers – /^\d*\.\d+$/
    Whole + Decimal Numbers – /^\d*(\.\d+)?$/
    Negative, Positive Whole + Decimal Numbers – /^-?\d*(\.\d+)?$/
    Whole + Decimal + Fractions – /[-]?[0-9]+[,.]?[0-9]*([\/][0-9]+[,.]?[0-9]*)*/
Alphanumeric without space – /^[a-zA-Z0-9]*$/
Alphanumeric with space – /^[a-zA-Z0-9 ]*$/
Common email Ids – /^([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6})*$/
Uncommon email ids – /^([a-z0-9_\.\+-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/
Password Strength
Complex: Should have 1 lowercase letter, 1 uppercase letter, 1 number, 1 special character and be at least 8 characters long
/(?=(.*[0-9]))(?=.*[\!@#$%^&*()\\[\]{}\-_+=~`|:;"'<>,./?])(?=.*[a-z])(?=(.*[A-Z]))(?=(.*)).{8,}/
Moderate: Should have 1 lc letter, 1 UC letter, 1 number, and be at least 8 characters long
/(?=(.*[0-9]))((?=.*[A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z]))^.{8,}$/
/* Username */
    Alphanumeric string that may include _ and – having a length of 3 to 16 characters –
    /^[a-z0-9_-]{3,16}$/
/* Date Format YYYY-MM-dd */
/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/
    Time Format HH:MM 12-hour, optional leading 0
    /^(0?[1-9]|1[0-2]):[0-5][0-9]$/
    Time Format HH:MM 12-hour, optional leading 0, Meridiems (AM/PM)
    /((1[0-2]|0?[1-9]):([0-5][0-9]) ?([AaPp][Mm]))/
    Time Format HH:MM 24-hour with leading 0
    /^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/
    Time Format HH:MM 24-hour, optional leading 0
    /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/
    Time Format HH:MM:SS 24-hour
    /(?:[01]\d|2[0123]):(?:[012345]\d):(?:[012345]\d)/


/* PowerShell has interesting return value behavior; vars are kept in global scope unless explicitly removed
$a = "Hello, World"
return $a
$a = "Hello, World"
$a
return */

-------DATA LAKE--------
Intermittent data holding area; a function of time restrictions, best for unstruct'd data/Ops Log/Config Data....... (for monitoring apps before a problem happens or gets worse)



References:

https://modernweb.com/45-useful-javascript-tips-tricks-and-best-practices/

https://pythontips.com/2015/04/19/nifty-python-tricks/#more-580

https://www.freelancer.com/community/articles/top-16-c-programming-tips-tricks

https://docs.microsoft.com/en-us/dotnet/csharp/tutorials/inheritance 

https://www.debuggex.com/

https://digitalfortress.tech/tricks/top-15-commonly-used-regex/