Javascript Flatten an n-dimension array iteratively and recursivley

Javascript Flatten an n-dimension array iteratively and recursivley

Just in case you need to know

Recursively, although a tad more elegant this will blow your stack up until ES6

var data = [ 1, [ 2, 3 ], [4, [ 5, [ 6, 7 ], 8 ], 9] ];
 
function flatten( flattenMe ) {    
    var answer = [];
    function doWork( flattenMe ) {
        for( var i =0, l = flattenMe.length; i<l; i++ ) {
            var element = flattenMe[ i ]; 
            if( typeof element  === "object" && element instanceof Array ) {
               doWork( element );
            }
            else {
                answer.push( element );
            }
        }
    }
    doWork( flattenMe );
    return answer;
}
 
//iterative solution, needs a bit of optimization
function iterativeFlatten( flattenMe ) {
 
   var flattened = [],
       que = [],
       element = "";
 
   que = flattenMe;
   while( que.length ) {
       //get the next element off the que
       element = que.shift();
       //check its type if its another array push its elements on the que
       if( element.constructor == Array){
           var temp = que;
           que = []
           for( var i = 0, l = element.length; i<l; i++ ){
               que.push( element[i] );
           }
           que =  que.concat(temp);
       }
       //else its a primitive push it on the flattened array
       else {
           flattened.push(element)
       }
 
   }
 
   return flattened
 
}
Posted in Uncategorized | Leave a comment

Install Laravel Spark on C9.io workspace

Hope this helps, after two days of toil I finally got a spark project up on a c9.io workspace here are the steps I took. This assumes you have already bought a Spark license at https://spark.laravel.com/

  1. Create the c9 workspace.
  2. Because I ultimatley want to deploy to a digital ocean droplet and the latest laravel / spark requires PHP >5.6 you need to update php on your c9 workspace. I found using php brew works the best:  (  https://community.c9.io/t/how-to-upgrade-to-php7/1379 )  You can use phpbrew on Cloud9. I found that the standard installation process works fine, just run the commands below.We first install the libmcrypt-dev package to avoid running into dependency issues during build:

    $ sudo apt-get update
    $ sudo apt-get install libmcrypt-dev
    


    Next, we download phpbrew and move it to /usr/local/bin:

    
    $ curl -L -O https://github.com/phpbrew/phpbrew/raw/master/phpbrew
    $ chmod +x phpbrew
    $ sudo mv phpbrew /usr/local/bin/
    $ phpbrew init
    
    # add this to your ~/.bashrc:
    $ [[ -e ~/.phpbrew/bashrc ]] && source ~/.phpbrew/bashrc
    
    $ phpbrew lookup-prefix ubuntu
    
    

    Once set up, we install and load PHP 7:

    $ phpbrew install 7.0 +default
    $ phpbrew switch php-7.0.1
    $ phpbrew use php-7.0.1
    $ php -v
    PHP 7.0.1 (cli) (built: Dec 29 2015 22:04:43) ( NTS )
    Copyright (c) 1997-2015 The PHP Group
    Zend Engine v3.0.0, Copyright (c) 1998-2015 Zend Technologies
  3. Next make a phpinfo.php file in your workspace root if you fire up your workspace you will notice that apache still think php is 5.5. You need to disable the old php module and enable the new php 7.0 module . From Roland on C9.io:https://community.c9.io/t/how-to-upgrade-to-php7/1379/17   I had the same problem. You have to disable the php5 module in apache2 and then enable the php7 module:
    $ sudo a2dismod php5
    $ sudo a2enmod php7.0

    When I did this I got an error ‘could not parse envvars’ but I solved this by temporarily renaming this file in the /etc/apache2 directory. The restart apache and now it worked for me.

    If you do not see php7.0 module then do the following:

    $ sudo add-apt-repository ppa:ondrej/php -y
    $ sudo apt-get update -y
    
    $ sudo apt-get install php7.0-curl php7.0-dev php7.0-gd php7.0-intl php7.0-mcrypt php7.0-json php7.0-mysql php7.0-opcache php7.0-bcmath php7.0-mbstring php7.0-soap php7.0-xml
    
    $ sudo apt-get install libapache2-mod-php7.0 -y
  4.  If you going to use Spark then you also need PHP Zip so install
    $ sudo apt-get install php7.0-zip
  5. Clone the Laravel Spark Installer into your workspace root https://github.com/laravel/spark-installer/tree/master/src
  6. Add Spark to your workspace path.
    
    $ vim ~/.bashrc
    
    

    Add these lines at the end of your file

    
    # Laravel Installer
    export PATH="$PATH:$HOME/.composer/vendor/bin"
    
    # Spark Installer
    export PATH="$PATH:$HOME/workspace/spark-installer"
  7. Now you are ready to install sparker. Got into your spark-installer directory and run. That should install spark and all its dependancies.
    composer install
  8. Register Spark, got to https://spark.laravel.com/ and login. In your user settings go to the API page and create a new API token.
  9. From Here you can follow the install insturctions in Spark’s documentation https://spark.laravel.com/docs/3.0/installation
  10. Remember you have to create your Database and Database user and set them in your project .env before you can run php artisan migrate.
  11. The only other problem I had was that the npm intall for my spark project was failing. So to fix I upgraded nodejs to v 6.4. You can do this c9.io by running
    
    $ nvm install 6.4
    $ nvm use 6.4
    
    

    Then run your npm install

    
    $ npm install --save
    
    
Posted in Uncategorized | Leave a comment

Check if images exist before rendering with Javascript and jQuery

Recently I ran into a problem where I was making a bunch of Facebook Graph API requests for Facebook Events in order to build an Events widget. Problem was, after receiving data from the API, some Event objects had a image urls that didn’t resolve. My fix was to check each image url, see if it resolves, and if it doesn’t replace it with a default image. Last, after all images have been checked render the Events mark up that is built with the Events data.

Because I wanted to check and replace all the image urls before rendering the Events markup, I had to set up some sort of asynchronous system to check all the images url resolution. In a nut shell the algorithm goes

  1. Gather all Image urls and make requests for them.
  2. When all Image requests return check which result in 404s
  3. Replace 404 images with default images
  4. Generating Events mark up and add it to the page.

jQuery Deferreds to the rescue.

Considering I have a bunch of Facebook Events jSon in eventsData.

Make a load image function

//make an deferred array to store a jQuery deferred for every image request
 
var deferreds = [];
 
//make a load image function that takes the event index and event image url
var loadImage = function( i, src ){
                    imgDeff = new $.Deferred();	 
		    deferreds.push( imgDeff);
 
		    //make an image and set up load callbacks 
		    var img = new Image();
		    img.onload = function() { 
			            console.log("I exist")
				    console.log(i);
				    deferreds[i].resolve( i,src,"exsist" )
				 };
		    img.onerror = function() { 
				    console.log("I don't exist)
				    console.log(i);
                                    //image doesn't exist so replace it with a default image in this case the FB user image
				    eventsData.data[i].picture.data.url = "//graph.facebook.com/"+eventsData.data[i].owner.id+"picture";
				    deferreds[i].resolve( i,src,"noexsist" );
				 };
		    //apply img
                    img.src = src;
 
    }//end loadImage
 
 
//loop through the events Data
var i = 0;
$.each(eventsData.data,function(){
    loadImage( i, this.picture.data.url );
    i++;				
});
 
//when all the deferreds are resolved add the markup to the page
$.when.apply($,deferreds).done( function(data){ 
    //at this point eventsData has urls that will all resolve so build the markup and render
    console.log(data);
 
})
Posted in Uncategorized | Leave a comment

Template Tag Polyfill for Internet Explorer

Have you used the HTML5 template tag? I have too. Seems like a really great idea, until. until QA tests your project and you realize it won’t work in IE. Better yet, not just IE 7 or 8, all versions of IE. Super bummer.

It turns out that IE will allow you to select a template tags but it doesn’t provide an .content property for them. Something like $(‘template’)[0].content fails in IE. This turns out to be a real kick in the junk, so I came up with this polyfill. The idea is that you and a method to the documents Element.prototype that checks for the existence of the .content property, in the event it’s not there override it. All subsequent template tag calls will have .content in IE

Feel free to use, modify, update, or let me know where I’m intellectually lacking:

  Element.prototype.contentTest = function(){ 
 
      return function( element ){ 
 
         if(element.content){
             return element.content;
         }
 
         var elPlate= element,
             qContent,
             docContent;
 
             qContent = elPlate.childNodes;           
             docContent = document.createDocumentFragment();
 
             while(qContent[0]) {
                docContent.appendChild(qContent[0]);
             }
 
             elPlate.content = docContent;
             return  docContent; 
 
       }(this);
 
  }
 
  //get the templates contents
  var template = $('template')[0],
      templateContents = template.contentTest();
 
  //all subsequent calls to .content or .contentTest() will return the templates contents
Posted in Uncategorized | Comments Off on Template Tag Polyfill for Internet Explorer

Print only lightbox or modal window content

This was a real kick in the Jimmy.

On a recent project I had a requirement to print contents of a modal window. Solution:

  1. When the user clicks a print button add an iframe to the end of the body tag.
  2. Hide it by moving it off the view port.
  3. Get the modal contents and load them into the iframe.
  4. Finally tell the browser to print the iframe.

Easier said than done. Here is my final code hope this helps someone else not lose an entire Sunday. I started working from this code http://www.bennadel.com/blog/1591-ask-ben-print-part-of-a-web-page-with-jquery.htm so props to the Ben for writing and posting it. Note if you want to use this you will have change some of the jQuery selectors to suite your project.

/* @brief Prints modal contents
 * @author lorenzogangi@gmail.com
 */
 
"printModal": function(){
 
    //make a iframe and hide it
    var tempFrame = $("<iframe id="printFrame" name="printFrame" width="300" height="150">")
    tempFrame.css( {
        "width": "1px",
	"height": "1px",
	"position": "absolute",
	"left": "-100000px"	
    } );
 
    //attach the iframe to the end of the body so we can hide the body content for IE. I hate IE
    $body = $("body");
    var ieStyle = $("<style class="ie"> body *{ display: none; } body #printFrame{ display: block !important; } </style>");
    $body.append(tempFrame).append(iestyle);
 
    //get the print styles, these are my custom print styles you could use a string here I chose to put them in a template file
    var printStyle = new  EJS({url: 'templates/mealModalPrintStyles.ejs'}).render({});
 
   //get the modal window content
    var $content = this.element.find(".buildAMeal__meal-info").clone();
    $content.find(".buildAMeal__modal-ingredient-edit-button, .btn-group").remove();
    $content.prepend("
 
 
<h1>YOUR MEAL" );
   printDocument.write( "<html>" );
   printDocument.write( "<body>" );
   printDocument.write( "<head>" );
   printDocument.write( "<title>" );
   printDocument.write( document.title );
   printDocument.write( "</title>" );
   printDocument.write( printStyle );
   printDocument.write( "</head>" );
   printDocument.write( $content.html() );
   printDocument.write( "</body>" );
   printDocument.write( "</html>" );
   printDocument.close();
 
   //focus the iframe and print it 
   printFrame.focus();
   printFrame.print();
 
   //cleanup print style and print iframe 
   ieStyle.remove(); 	
   setTimeout( function(){ tempFrame.remove(); },(60 * 1000));
 
}// end printModal
Posted in Javascript, Uncategorized | Leave a comment

Facebook profiles vs. pages and graph api data retrieval

Help! My Facebook plugin doesn’t retrieve any data!

The problem may be you are trying to retrieve data from a Facebook profile rather than a Facebook page. Facebook puts much tighter restrictions on data its Graph API makes available to public profiles than it does for pages.

The reason you are not retrieving any data is because profiles limit data sharing to other profiles who are ‘friends’. Profile posts and photos have permissions that govern who can access them. This means the data on profiles is not necessarily available for public consumption. Meaning, when you post on your profile wall your friends can all see your post if they are logged into Facebook, but the rest of the Internet can not. Consider a website that the whole world can see, it doesn’t have permission to retrieve and display private posts that have been made between you and your friends on each others walls. There are exceptions to this rule. If you and your friends change a posts permissions to remove these restrictions, plugins and apps can use Facebooks Graph API to retrieve them.

But wait that’s not all!  Even with permissions set, outside sources still may not be able to retrieve posts. Consider an example post where multiple friends are mentioned or a photo where multiple friends are tagged. Just because the profile owner says it’s ok for the world to see does not necessarily mean all the other friends agree. If they have not also lifted the restriction by changing the post permissions Facebook will not all the data to be returned via the API.

To increase the data you can retrieve from your Facebook profile, you have a couple of options.

1) Change the permissions on each posts and photos you want to retrieve with your plugin. Follow these instructions for posts: https://www.facebook.com/help/www/120939471321735?rdrhc and follow these instruction for photos https://www.facebook.com/help/www/120939471321735?rdrhc

2) This is what I recommend. Change your Facebook profile to a Facebook page. Facebook pages are meant to be public facing so the whole world can see them. This means all the data is retrievable by the plugins and apps by default. To make this switch follow these instructions https://www.facebook.com/help/175644189234902/

Posted in jQueryFacebookWall, Uncategorized | Leave a comment

Javascript return focus to parent tab

This one took me a bit. I was creating a new tab on form submission. If a user clicks a button on the new tab, focus had to be shifted back to the parent tab. If the form was submitted again the child tab is deleted and replaced by a new child tab. Makes for a handy query and review results then modify query scenario but in separate tabs. The trick was in returning focus to the parent. One would think this would be possible with window.opener.focus(). But modern browsers don’t allow this because you can manipulate the users tabs. The work around is to name the parent window then use

window.open('','parent')

it to reset the tab focus.

Tested in chrome, but this trick doesn’t work in FF or IE. Hope this helps someone else.

Parent

//markup

//js

 
<script>
 
// <![CDATA[
var i = 0;
var windows = [];
window.name = 'parent';
 
//handle child birth		  
function announceWindow(win){
   //if there is already a window open, close it and save ref to new one
   if(i==1){   
       windows[0].close();
       delete windows[0];
       i = 0;	
   }
   //store a reference to the window
   windows[i] = win;
   i++;
}
// ]]>
 
</script>

child tab
//markup for button that takes you pack to parent

<input type="button" />

//js

<script>
// <![CDATA[
      //tell that parent that the child is born! so it can keep track of them and get rid of them as needed.
      if (window.opener) {
      	window.opener.announceWindow( window );
      }
      //set the focus back to the parent window
      function focusParentWindow(){
        window.open('','parent').focus();
      }
// ]]>
</script>
Posted in Uncategorized | Leave a comment

JavaScript Reg-ex for sub-domain name

This one took me a bit so thought it might be worth writing it down.

If you need to validate a field for a valid subdomain name, ie the “subdomain.inthedomain.com” you have a couple of requirments:

1) Field value starts with an letter or number

2) Field value ends with a letter or number

3) All characters between first and last can be a letter, number, or a non-repeating – or .

so lorenzo.gangi-test would be valid.

lorenzo.-gangi..test1 is invalid

This regex should do the trick

<p id="demo">Click the button to display the matches.</p>
<button onclick="myFunction()">Try it</button>
<script type="text/javascript">
function myFunction()
{
var str = "b.o.b-obo123"; 
var temp = new RegExp(/^([a-zA-Z0-9](\w|[.-](?=\w))+[a-zA-Z0-9])$/)
var n=str.match(temp);
document.getElementById("demo").innerHTML=n;
}
</script>
Posted in Javascript | Comments Off on JavaScript Reg-ex for sub-domain name

Sorry to all the fans

Ladies and gentleman all my blog posts have left the building. I used to use this thing as a way to remeber all the development stuff I couldnt remeber. I ditching that idea. Instead of  all the old unix commands, IDE snafus fixes, and complicated quries, I hope to post a bunch of how too’s. We’ll see how this goes.

Posted in jQueryFacebookWall, Uncategorized | Comments Off on Sorry to all the fans