mardi 28 juin 2016

fullcalendar time limit rendering in AgendaView

With Fullcalendar's agendaView, is it possible to show a limit on time (displayed on the left of the grid)? Example, by default the time displayed is from 12:00 am to 11:59 pm; now say I want to display from 10:30 am - 9:00 pm. Would this use case be possible?

thanks.

How I know if the script works from within a subdirectory or not?

In some cases some of us prefer to insert the script into sub-directory, ex: http://example.com/Script/index.php, and some others prefer to insert the script into root directory ex: http://example.com/index.php.

How to know if the script inside a subdirectory or not ?

How to replace string that contain bracket? (Regex)

i want to ask you something simple. I have string like:

happy (adj)

sad (v)

and i want to replace those brackets with empty string (" ") so it would be like this:

happy

sad

i know that i have to use regex but because im new in regex, can u help me with the pattern guys? thank you :')

Heavily manipulated html in a javascript var

After getting the HTML code out of a file onto PHP and then Javascript, when I try to display it using:

    <a href='filename.php'>Random link</a>
    <p id='par'>
    </p>
    <script>
      str = "<html>...</html>";
      document.getElementById('par').innerHTML = str;
    </script>

So my question is, how come is Ramdom link displayed with plain html. Shouldn't the html be interpreted ?

Building a local wikipedia from scratch

I'm looking to create a personal wikipedia-esque website, both for pleasure and for personal use. I'm aware there are companies that offer such a service, but I'm interesting in doing it from scratch.

That being said, I have two questions: 1) is it possible (I have an introductory knowledge to html, css, php and python 2) where should I start

My main concern lies behind the creation of an editable template for the wikis to be created with.

Thanks,

Troy

Changes made to $scope in directive's controller unavailable to the view

I have the following code:

<div my-dir bar="test">
  {{foo}}
</div>

And the following directive:

    restrict: 'A',
    scope:
    {
        bar: '@'      
    },
    link: link,
    controller: controller

In the controller I'm doing this:

function controller($scope)
{
    console.log("in ctrl", $scope);
    $scope.foo = 'test'
}

However $scope.foo isn't accessible to the view code. It doesn't reflect the update.

What am I doing wrong?

datetimepicker access violation error

datatimepicker is working fine but can't insert the date.time into the database, always get Syntax error or access violation: 1064 error. " note that datetimepicker format is similar to this 06-27-2016 12:00 AM."

<div class='input-group date' id='datetimepicker1'>
             <input type='text' class="form-control" id="datepicker" name="datepicker"/>
             <span class="input-group-addon">
             <span class="glyphicon glyphicon-calendar"></span>
             </span>
         </div>

query

$sql = "INSERT INTO news(`newsdate`,`title`)VALUES (".$_POST["datepicker"]."',".$_POST["title"]."')";

Why does this PHP line of code cause a syntax error on my webhosting, but not on c9?

It is a line of code where the text area should be blank if there is no SESSION. If there is a SESSION, put the contents into the textarea. Is there really an error here, or is it just the webhosting's problem?

<form id="translateform" action="processTranslation.php" method="post"><?php 
echo "<textarea maxlength='3000' id='inputField' placeholder='Enter your Lorem Ipsum text here:' name='translate'>";
if(isset($_SESSION['text'])){
    echo $_SESSION['text'];
    }
    echo "</textarea>";
        ?>

Error message: "Uncaught SyntaxError: Unexpected Identifier".

Extending Data Object in TypeScript

I'm trying to extending a data object in TypeScript, by adding some new fields. While I guess it's a quite common pattern in JavaScript, I can't make it be able to compile, without making bar as optional in the snippet as below.

I'm wondering is there any way to avoid making bar optional. Any suggestion would be welcome, thank you.

interface BaseDataObject {
    foo: string;
}

interface ExtendedDataObject extends BaseDataObject {
    bar?: string;
}

function extendData(input : BaseDataObject) : ExtendedDataObject {
    var output : ExtendedDataObject = input;
    output.bar = input.foo + ' some suffix';
    return output;
}

Is there a way to fill multiple fields using onclick method

I have a matrix of images. Each image currently fills a specific field with information. Code for one image below.

 <a href="#riskrating1" data-toggle="tab"><img src="components/com_safety101/images/a2.jpg" width="72" height="32" border="0" onclick="document.getElementById('jform_pre_control_risk').value = '10: Undesirable'; " /></a>

Is there a way that each image could fill three fields with different information? Not sure if you can stack the document.get ElementById calls?

How do I automate php file creation using an array of x names to create x php files each with a different name?

I have an array with x names and need to create x php files each with a different name from my array. My template file is

$cityNames = array("example1", "example2", "example3");

$_SESSION['CITY'] = '#';

and I need to replace # with a name from my array x number of times to create x number of files. So in this example I need my output to be 3 files named

example1.php (where $_SESSION['CITY'] = 'example1';)

example2.php (where $_SESSION['CITY'] = 'example2';)

example3.php (where $_SESSION['CITY'] = 'example3';)

lundi 27 juin 2016

In Magento orders ship to name sectioin, last name appears twice

I got a problem from the Magento(1.9) website after the customer paid the bill via paypal express.

it seems like that Magento is assigning the full name to the first name field in the first place, and assigning the last name again.

So I got the issue shown in the following picture. The billing address customer name is correct, but the shipping address customer name is duplicated.

ISSUE

Thanks for your help in advance

Multiple Promise.all() because multiple arrays

I have an array of objects, each object has some properties, each property contains an url of an image.

I have more arrays, and I want download all these images, so I use fetch() promise. Promise.all() accepts an array of promises, so I run Promise.all() for each property, since I don't want to have an array with all the promise for all the properties.

But.. do I have to write all of them manually? I know I can't use for loops. Or do I have to use recursion (if it is possible in this case), each time calling a function from the inside with a new array?

Sometimes the div doesn't get scrolledTop

So I'm trying to create my own chat with support to offline messages. I can use it already, but sometimes when I send a message, the scroll doesn't move as it should, and if I want to see the message I just sent I have to scroll down a little bit. It keeps having different behavior everytime and that's what bothers me. this is the script responsible for the scrolling whenever I send a message

success: function () {
                //do something with response
                var url = '/Chat/ReturnTeacherNewMessages?Student_id=' + '@ViewBag.Student_id';
                $('#user_content').load(url);
                $('#MSG').val("");
                $.ajax({
                    success: function () {
                        var wtf = $('#user_content');
                        height = wtf[0].scrollHeight;
                        wtf.scrollTop(height);
                    }
                })
            }

How to access private objects in a component's script?

In this question the OP asked about how to avoid exposing private objets to the outside in a component. I’ve been googling around and can’t find a way to do the opposite. Say I have the component below and I want to access privateObj from either my web page or a parent component. How can it be done using JavaScript and the Polymer API?

<polymer-element name="animating-element">
   <script>    
     var privateObj = {};

     privateObj.internalState = 0; 

     //private static method
     privateObject.setupState = function(polymerObject) {
        if(polymerObject.stateExposedToOutside == /* some conditions */) { 
           privateObject.internalState = 1;
        }
     }

     Polymer('animating-element', {
        stateExposedToOutside: 0,
        ready: function() {

          privateObj.setupState(this);
          this.animate();

        },
        animate: function() {

        }
      });    
   </script>
</polymer-element>

How do I get the files I uploaded in laravel?

Seems really basic right, until you see that I use Super Agent to upload my files:

  onDrop(files) {
    var req = request.post('//' + location.hostname + '/api/v1/blogs/image/upload').set('X-CSRF-TOKEN', $('meta[name="csrf-token"]').attr('content'));

    files.forEach((file)=> {
        req.attach(file.name, file);
    });

    req.end((data) => {
      console.log(data);
    });
  }

When I inspect the request object coming back:

[Image[1]

As you can see the file name could be anything so I can't just do: $request->hasFile('photo')

Any ideas on how to handle this situation?

Display dialogs in a loop and act on the accept event.

In my Nativescript app I have a loop and want to display a dialog for each item being iterated over. When the dialog displays it contains "Accept" and "Reject" options, both of which when clicked I would like to call a method which I pass the iterated item into. The issue is since the option selection returns a promise I lose the reference to the iterated item. What can I do to get around this? Here's an example of my code.

function _showPendingConnections() {    
    for (var i = 0; i < ViewModel.pendingConnections.length; i++) {
        var pendingConnection = ViewModel.pendingConnections[i];
        dialog.confirm({
            message: pendingConnection.PatientFirstName + " would like to share their glucose readings with you.",
            okButtonText:"Accept",
            cancelButtonText:"Reject"                                    
        }).then(function(result) {
            if(result === true) {
                ViewModel.acceptConnection(pendingConnection);
            } else {
                ViewModel.removeConnection(pendingConnection);
            }            
        });
    }
}

Recieve data sent from php with java

I have my server running and there is this index.php file on it. i use this in php to send a file from my server

<?php
$filename = "Small.gif";

if(file_exists($filename)){

//Get file type and set it as Content Type
$finfo = finfo_open(FILEINFO_MIME_TYPE);
header('Content-Type: ' . finfo_file($finfo, $filename));
finfo_close($finfo);

//Use Content-Disposition: attachment to specify the filename
header('Content-Disposition: attachment; filename='.basename($filename));

//No cache
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');

//Define file size
header('Content-Length: ' . filesize($filename));

ob_clean();
flush();
readfile($filename);
exit;
}

?>

so when i open it with a browser it starts downloading the file.

now i'm using a browser to download it.my question is that how could i recieve this file by a java code and save it on my disk.THANKS

How to pass an array from php to chart.js data?

I have this array $data_dispensed, when I echo json_encode($dataary) it, I get

{ "aaa": 11, "bbb": 8, "ccc": 7, "ddd": 7, "eee": 7, "fff": 6, "ggg": 6, "hhh": 6, "iii": 6, "jjj": 35 }

and my chart data as below,

var echartDonut = echarts.init(document.getElementById('echart_donut'), theme);

  echartDonut.setOption({

        emphasis: {
          label: {
            show: true,
            position: 'center',
            textStyle: {
              fontSize: '14',
              fontWeight: 'normal'
            }
          }
        }
      },  legend: {
      x: 'center',
      y: 'bottom',
      data: ['Direct Access', 'E-mail Marketing', 'Union Ad', 'Video Ads', 'Search Engine','AAA','BBB','CCC']  //and replace the data too ???????????
    },
     data: ////how to replace it to php array ?
      {
        value: 10,
        name: 'Direct Access'
      }, {
        value: 20,
        name: 'E-mail Marketing'
      }, {
        value: 30,
        name: 'Union Ad'
      }, {
        value: 40,
        name: 'Video Ads'
      }, {
        value: 50,
        name: 'Search Engine'
      },{
    value:60,
    name: 'AAA'

   },{
    value:70,
    name: 'BBB'  
      },{
    value:80,
     name: 'CCC'
              }
      ]
    }]
  });

I want to pass array from php to data ? Hot to do it ? How to replace the data to php array ?? Any help will be appreciated! thanks!

Switch Map on same mapdiv using leaflet?

Please don't mark as duplicate this question as it's not the same question at all.

So my issue here is I have device on/off switch on a page. So when someone do off it only show all the marker on leaflet map with off data only. Same will happen with on...so if user clicks on then it filter all the off data and only show on data on leaflet map....

So leaflet map define like following:

<div id="mapid2" style="height:400px; width:90%;">

When page refresh and user come on to the page for the first time mapid2 will show all on/off data. But when user clicks on OFF data or ON data then mapid2 will only show ON or OFF marker data on the same mapid2.

Something very simple but I am missing.....Thanks guys in advanced.:)

Creating json_array objects with Elasticsearch-PHP

I am trying to index where the field i have mapped requires an object.

According to: https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/_dealing_with_json_arrays_and_objects_in_php.html

    $params['body'] = [

            'location' => new stdClass()

    ];

should have been sufficient to indicate an empty PHP Object, but it fails on the miss match stating that location is an object mapping and It is wrong.

I have tried the following also:

    $params['body'] = [

            'location' => new stdClass(['lat'=>0,'lon'=>0])

    ];

But that failed with the same reason.

However if I do a raw curl api to elasticsearch:

curl -XPOST 'http://localhost:9200/my_index/my_type/1' -d '{"location":{"lat":0.0,"lon":0.0}}'

this works.

I'm just learning how to code in school and I'm struggling like crazy

In this assignment, you will need to work through each of the steps and figure out what the value of the variable equals each step of the way. Once you have worked out what the value is at each step, send an email to your instructor letting us know what you think the answers are.

variable created: var x = 3;

step 1, what does x after the changes in the code below? x = x + x

step 2, what does x after the changes in the code below? for(var i = 0; i < 4; i++){ x = x + 1 }

step 3, what does x after the changes in the code below? if(x > 10){ x = 2; } else { x = 3; }

step 4, what does x after the changes in the code below? function doubleIt(value){ return value*2; }

doubleIt(x);
x = doubleIt(x);

step 5, what does x after the changes in the code below? var numberArray = [1,2,3];

for(i = 0; i < numberArray.length; i++){
    x = x + numberArray[i];
}

too late to filter categories if get categories is onload?

I'm not sure why the filter I'm using doesn't work, if it is too late to filter the categories once they have loaded or if I am just approaching this totally wrong.

Since updateAvailableMusic() runs onload, and filterAvailableCateories() gets run onclick from the html file as such :

"ng-click='filterAvailableCategories(party)'"

I am wondering if I need to be passing more information to the filter function. And as this is Angular and I don't really understand how to debug Angular (read: "follow it through with a breakpoint the way I would normal javascript", I am hoping to get another perspective on this and much thanks ahead of time.

Here is the code:

$scope.updateAvailableMusic = function () {
    return music.getMusicCategories(null, $scope.featureType).then(function (options) {
        $scope.availableCategoriesUnmapped = options;
        $scope.addDefaultCategories();
        $scope.availableCategories = _.groupBy(options, 'category');
    });
};
$scope.filterAvailableCategories = function (musictype) {

        $scope.availableCategories = $scope.availableCategories.filter(function (rr) {
            switch (musictype) {
            case 'party':
                if (rr.category !== 'Rap' && rr.category !== 'HipHop') {
                    return rr;
                }
                break;
            case 'study':
                if (rr.category !== 'Classical' && rr.category !== 'Jazz') {
                    return rr;
                }
                break;
            }
        });
};

Google MyMaps requesting json issue

I have a question about google maps requesting. I'm using this query string for getting location informations perfectly :

http://maps.google.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude + "&sensor=true

But i want to use myMaps future for getting special area information. Here is my special map and i'm drawing some area and give name it :

https://www.google.com/maps/d/viewer?hl=tr&authuser=0&mid=11In97WOd6VWB5Kc-jGTOcu8TNzs

is there any way to get name this place with my query if some one in this area? For example i want to use maps.google.com/maps/api query and if i'm in this place json give the drawing name for me?

example

Basicly if i'm in red point, i want to get Canberk name(in the left pannel) with this query : http://maps.google.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude + "&sensor=true

If it is not possible, you know is there any api google or not ? Thanks so much.

Cannot get width of Div

<tr>
  <td style = "padding-left: 2%; padding-right: 2%;">
    <span style="padding: 3px; float: left; margin-right:13px;">RISK TAKER</span>
    <div id = "risktakertotal" style= "margin: auto;" class="progress">
      <div id = "risktaker" class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="color:black; width:0%; background-color: #0097a7;"></div>
      <div class="vertical-line" id = "risktakerAvg" style=""></div>
    </div>
  </td>
  <td id = "risktakerKB" ><h4></h4></td> 
  <td id = "risktakerS"><h4></h4></td>
</tr>

I have a very simple table with a Bootstrap progress bar in it. I have a vertical line that indicates the average for the bar (not the actual progress). To calculate where to put that line, I want to get the total width of "risktakertotal" and set the lines margin-left to a percentage of that total width.

However, using Javascript, I cannot get the width of that div. I've used .width(), .style.width, .offsetWidth and anything else I could find online to no luck. Does anyone know of I way I can do this? Or another way that I can move this vertical line without the total width?

changing the url without loading a new page

For my single page website, I have an index of projects. If a project is clicked it opens up a slideshow on the same page. So basically, I only have one URL, and if anyone wants to link to a specific project, they can't.

I'm trying to make it so that if I click on a project, it changes the URL. And so that URL can be used to get to my website with that project opened.

Here is a link to what I have so far.

For reference, I'm trying to achieve something that is found on this site.

I found some good suggestions here, but what happens when I use something like this (below), a new URL is created but it doesn't open up the project if I renter that URL into the browser.

<a href="#" id='click'>Click to change url to bar.html</a>

<script type="text/javascript">
var stateObj = { foo: "bar" };
function change_my_url()
{
   history.pushState(stateObj, "page 2", "bar.html");
}
var link = document.getElementById('click');
link.addEventListener('click', change_my_url, false);
</script>

How to post a value to a controller function on button click using Ajax and also redirect to new page at the same time?

I have a button Next that changes the page -

<a class="disabled" href="step">
   <button class="btn btn-primary launch-btn disabled next">NEXT</button>
</a>

Also, when this button is clicked, I have an Ajax function that sends data to a controller function -

<script type="text/javascript">
$(function(){
    $('.next').click(function() {
    var a = $('#box').data('val');

    $.ajax({
       type: "POST",
       url: "<?php echo base_url(); ?>study/CreateData",
       data: a,
       success: function(data)
       {
          console.log(data); 
       },
       error: function()
       {
          console.log("fail");
       } 
     });
  });
});
</script>

And I'm using this to receive the value from Ajax -

public function CreateData() {
        $data = $this->input->post('data');
        return $data;
    }

When the Next button hits its controller where it changes to a new page, I'm trying to retrieve the value posted by Ajax to the CreateData() function -

public function step()
    {
        $data = $this->CreateData();
        if(!empty($data)){
            print_r($data); exit;
        }
        else {
            echo "blank"; exit;
        }
        $this->load->view('step2');
    }

However, this keeps echoing blank. This obviously means that the $data being returned is empty but I'm not sure why. The success function in my Ajax script is logging data, so it's posting the value to CreateData(). What am I doing wrong here?

i want change int ip address to string ip address


i have a Question about ip address.
i want to input 'int' array ipv4 ip address to 'char' array ip address. i worked on linux. (ubuntu)

so..first on my source, i want distinguish ipv4 / ipv6 address. and then move int array to string array. this is important !!.

but output is wrong ..

for example..

#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>

int main(void)
{
    int i;
    unsinged int val32;
    int ma_ip[4];
    char m_ip[4];
    char ipaddr[INET_ADDRSTRLEN], ipv6[INET6_ADDRSTRLEN];
    int no = 0;
    char *token;
    char s3[] = "10.1.35.1";
    /* just example. test only one ip address.. */
    for(i = 0; i < 1; i++)
    {
        char *mm = strstr(s3, ":");
        if( *mm != NULL)
        {
             token = strtok(s3, ":");
             while(token != NULL)
             {
                 token = strtok(NULL, ":");
                 no++;
             }
             if(no >= 2 && no <= 7)
                 printf("nthis is ipv6n");
             else
                 printf("nwrong ipv6n");
         }
         else
         {
             token = strtok(s3, ".");
             while(token != NULL)
             {
                 token = strtok(NULL, ".");
                 no++;
             }
             if(no == 4)
             {
                 printf("nthis is ipv4.n");
                 val32 = inet_addr(s3)
                 ma_ip[i] = val32;
             }
             else
                 printf("nwrong ipv4.n")
         }
         inet_ntop(AF_INET,&ma_ip[0],ipaddr,INET_ADDRSTRLEN);
         printf("nipaddr = %sn", ipaddr);
         strcpy(&m_ip[0], ipaddr);
         printf("nafter strcpy = %sn", m_ip[0]);
    }

}

but last printf output ipaddr = 0.0.0.10 and

after strcpy is format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ error !

i don't know what source code is wrong. .......

Plz help me ~~~~~

Leaflet - I cannot seem to get the basic examples working

I have been trying to get Leaflet (a webmapping API) working for hours. At first I made the mistake of trying to do too much, now I am just trying to get the basic examples working.

Here's the code that I have (HTML and Javascript):

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <script src="./leaflet.js"></script>
        <link rel="stylesheet" type="text/css" href="./leaflet.css" />  
        <script type="text/javascript">
            function initmap(){
                var map1 = L.map('map');
                //map1.setView([38.642433, -90.255372]),9); //Thanks!
                map1.setView([38.642433, -90.255372],9);

                // add an OpenStreetMap tile layer
                L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
                        attribution: '&amp;copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
                }).addTo(map1);
            }
        </script>
       <style>
            #map {
              position: absolute;
              top: 0;
              right: 0;
              left: 0;
              bottom: 0;
              top: 0;
              z-index: 0;
            }
    </style>
        <!-- Without this styling to set the map dimension, the tiles will get downloaded, but nothing will display on the map div!  Thank you choz for answering this question!  -->
    </head>

    <body onload="initmap()">
        <div id='map'></div>
    </body>
</html>

Summary: I was at first getting "missing ; before statement" and "Reference Error: initmap not defined". That was fixed by removing the extra parenthesis in the map definition, per choz's first comment. Then I had a problem with the maps not showing up, even though the tiles were being downloaded. Choz commented again about the needed style for the map. I included the working code above.

MYSQL Query Select which has same column and group by

I have database table named "messages". I want to get result total message per user and the last message from them. Below is my structure table and result. Here is my SQL:

SELECT COUNT(email), messages.*
FROM messages
WHERE
email = message_id
group by email
order by created_at desc

Here is my Table Structure

+---------------------+----------------+---------------------+---------------------+
| email               | message        | message_id          | created_at          |
+---------------------+----------------+---------------------+---------------------+
| memberONE@gmail.com | first message  | memberONE@gmail.com | 2016-06-26 10:00:00 |
+---------------------+----------------+---------------------+---------------------+
| Admin               | reply admin    | memberONE@gmail.com | 2016-06-26 12:00:00 |
+---------------------+----------------+---------------------+---------------------+
| memberONE@gmail.com | last message   | memberONE@gmail.com | 2016-06-26 22:00:00 |
+---------------------+----------------+---------------------+---------------------+
| memberTWO@gmail.com | first message  | memberTWO@gmail.com | 2016-06-26 10:00:00 |
+---------------------+----------------+---------------------+---------------------+
| memberTWO@gmail.com | second message | memberTWO@gmail.com | 2016-06-26 12:00:00 |
+---------------------+----------------+---------------------+---------------------+
| Admin               | reply admin    | memberTWO@gmail.com | 2016-06-26 18:00:00 |
+---------------------+----------------+---------------------+---------------------+
| memberTWO@gmail.com | last message   | memberTWO@gmail.com | 2016-06-26 22:00:00 |
+---------------------+----------------+---------------------+---------------------+

Result from Above code is this :

+--------------+---------------------+---------------+---------------------+---------------------+
| COUNT(email) | email               | message       | message_id          | created_at          |
+--------------+---------------------+---------------+---------------------+---------------------+
| 2            | memberONE@gmail.com | first message | memberONE@gmail.com | 2016-06-26 10:00:00 |
+--------------+---------------------+---------------+---------------------+---------------------+
| 3            | memberTWO@gmail.com | first message | memberTWO@gmail.com | 2016-06-26 10:00:00 |
+--------------+---------------------+---------------+---------------------+---------------------+

Expected Result : Just want to get the last message from user where column created_at is the last

+--------------+---------------------+--------------+---------------------+---------------------+
| COUNT(email) | email               | message      | message_id          | created_at          |
+--------------+---------------------+--------------+---------------------+---------------------+
| 2            | memberONE@gmail.com | last message | memberONE@gmail.com | 2016-06-26 22:00:00 |
+--------------+---------------------+--------------+---------------------+---------------------+
| 3            | memberTWO@gmail.com | last message | memberTWO@gmail.com | 2016-06-26 22:00:00 |
+--------------+---------------------+--------------+---------------------+---------------------+

Please help me. thank you so much

Best way to check if several inputs have the same value

I have some inputs (random number > 0) and each is inside a div with same class so I have this structure:

<div class="myclass"> <!-- div #1 -->
    <input name="name" class="input">
    <!-- other inputs that don't take care -->
</div>
...
<div class="myclass"> <!-- div #n -->
    <input name="name" class="input">
    <!-- other inputs that don't take care -->
</div>

I need to check that the value of every input doesn't match with other, so if I have in the first input myname as value in the input n I can't have myname.

I have the next JQuery code to iterate over all divs to extract the info about every div.

$('.myclass').each(function() {
    input = $(this).find('input[name="name"]').val();
});

And then, it sends all info (JSON parsed before) through jQuery ajax to PHP scripts which MUST revalidate that input values don't be equal.

So, the question is: what's the best way to go over all divs and know if value is repeated? I thought about making a $.each inside the each I have to iterate over all elements but I don't know about its performance.

And what about with PHP script, what's the best way to afford it? Thank you.

NOTE: JSON parsed array, now have this structure:

{"user_info":{"app_id":0,"user_id":0},"contact":{"has_contact":0},"menu_items":[{"position":0,"name":"Nosotros","icon_id":"ic_delete_black_48dp.png","content":"nosotros"},{"position":1,"name":"Precios","icon_id":"ic_help_black_48dp.png","content":"nosotros"}]}

Don't worry about "user_info" and "has_contact" they are irrelevant, the name for which I was talking is the menu_items[index]['name'] value.

Google Drive API get edit url (aka alternateLink) for file with PHP SDK

  • I've setup my project to use the PHP SDK for the Google Drive API
  • I'm using a refresh token to authenticate a user via OAuth2 (not using a service account, if it matters)
  • I am getting a list of files from a specific folder with this
    function:

.

function getDriveFilesForFolder($app){
    // Get the API client and construct the service object.
    $client = getClient($app); // function that gets an authorized client instance
    $service = new Google_Service_Drive($client);
    // we only want files from a specific folder
    $q="'".$app->constants->get('GOOGLE_DOCS_MAIN_FOLDER_ID')."' in parents";
    $optParams = array(
         'q' => $q
    );
    $results = $service->files->listFiles($optParams);
    if (count($results->getFiles()) == 0) {
        echo "No files found.<br>";
    } else {
        echo "Files:<br>";
        foreach ($results->getFiles() as $file) {
            //var_dump($file);
            echo '<br><br>';
            echo $file->getName()." (".$file->getId().") ";
        }
    }
}

This works and prints out the list of file names and their ids.


  • Now I need to get an editable link for each file and have that print out as well.
  • From my searching, what I want is the alternateLink which is documented here for the Rest endpoint
  • I see no function in Google_Service_Drive_DriveFile or Google_Collection which it extends that will return the alternateLink.

How do I get the alternateLink value from the $file object in my code using the PHP SDK?


Worth mentioning

  • These files are pre-existing and not created with the PHP SDK

How do i solve echo a tag URL

How do i solve the URL ?

i was using echo to call out the a tag. and it run well but the URL include something that are i no understand how do i solve it? and can anyone explain to me? why no URL will have thoes %20%20%

Here is the URL that i echo out

http://localhost/pme/main/directMessageRoom.php?directMessageRoomID=1></a>%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%3Cform%20method=

here is my code

<div class ="direct-message-btn-container ">
        <?php 

   include '../config.php';
    if(isset($_SESSION['id'])){
    $target = $_GET['user'];
    $id = $_SESSION['id'];

    $targetusername = mysqli_query($connection,"SELECT username FROM user WHERE id='$target' ")or die(mysqli_error($connection));
    $username=  mysqli_query($connection,"SELECT username FROM user WHERE id='$id'") or die(mysqli_error($connection));

    $dm_sql="SELECT * FROM direct_message_room WHERE user_1_id ='$id' AND user_2_id='$target' OR user_1_id='$target' AND user_2_id='$id'";
    $check_direct_message_room = mysqli_query($connection, $dm_sql) or die(mysqli_error($connection));

    $check=  mysqli_num_rows($check_direct_message_room);

    if($check == 0){

       $rowUserName=mysqli_fetch_array($username);
       $rowTargetUserName=mysqli_fetch_array($targetusername);
       $room_name=$rowUserName['username']. ' and ' . $rowTargetUserName['username'];

    $direct_message_room_name ="INSERT INTO direct_message_room(`direct_message_room_name`,`user_1_id`,`user_2_id`) VALUES ('$room_name','$id','$target')";

    $newDirectMessageRoom = mysqli_query($connection,$direct_message_room_name)or die(mysqli_error($connection));
    $direct_message_room_id = mysqli_insert_id($connection); 

    echo '<a  href="directMessageRoom.php?directMessageRoomID='.$direct_message_room_id.'></a>';       
    }
    else{
        while($row3 = mysqli_fetch_array($check_direct_message_room)){
             echo '<a  href="directMessageRoom.php?directMessageRoomID='.$row3['id'].'></a>';
        }                        
    } 
?>

    <form method="post" action="" role="form">
        <div class="form-group ">
            <input type = "submit" class="btn content-btn btn-direct-message" value="message" name="chat">
        </div>
    </form>
</div>

unset() not working as expected

Following is my code to delete an object inside a JSON array.

if($_GET['method']=='deleteStudentReflections'){

        $jsonString = file_get_contents('../admin/data/student_reflection.json');

        $data = json_decode($jsonString, true);
        print_r($data["student_reflections"]); 
        unset($data["student_reflections"][$_GET['obj_val']]);

        $newJsonString = json_encode($data);

        file_put_contents('../admin/data/student_reflection.json', $newJsonString);

        print_r($_GET);

}

it should do this: Before calling function JSON array value:

{"english_courses":[{"name":"Abdullah","detail":"Bad Boy","image_link":"images/dp.jpg"},{"name":"Course Chin 2","detail":"Course det 2","image_link":"images/explicit feedly 3.PNG"},{"name":"courses 3 chinese","detail":"courses detail chinese 3","image_link":"images/site turorial.png"}]}

it should delete any object inside 'english_courses' courses array, but instead of deleting it does this:

{"english_courses":{"0":{"name":"Abdullah","detail":"Bad Boy","image_link":"images/dp.jpg"},"2":{"name":"courses 3 chinese","detail":"courses detail chinese 3","image_link":"images/site turorial.png"}}}

this is obj_val code:

function deleteEnglishCourse() { 
           var obj_val=$('#op').val(); 
           console.log(obj_val); 
           var deleteConfirm = confirm("Press 'Ok' to continue, Press 'Cancel' to Cancel "); 
          if (deleteConfirm == true) { 
             $.ajax ({ type: "GET", url: 'delete.php', data: "obj_val="+obj_val+"&method=deleteEnglishCourse", success: function(data) {alert(data); location.reload(); } }); } else { } } 

this is how '#op' is set:

function displayData(data){ 
            var html="<select id='op' class='form-control' onchange='valueSelect(this.value);'>"; for(var i=0;i<data["english_courses"].length;i++){ html+='<option value="'+i+'">' + data["english_courses"][i]["name"] + '</option>'; } 
   html+='</select>'; 
   $('#name_dropdown').append(html); } 

basically dropdown is populated by dynamic data. and when a value is selected it gets to a php file where a particular obj of a json array is deleted based on the value of obj_val

this error only occurs when obj_val is '0' and php function has to delete the first index of the array. Otherwise it works fine

please help !!

0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'call'

I got an error.( 0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'call' ) I've searched about this error. but I couldn't find the solution I want.

the Error Location: http://localhost:57583/Scripts/jquery-ui.min-1.11.1.js How can I solve this problem?

_Layout.vbhtml

<!DOCTYPE html>
<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=yes, target-densitydpi=medium-dpi" />
<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1" />
<meta name="Author" content="" />
<meta name="Keywords" content="" />
<meta name="Description" content="" />
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />

<link href="favicon.ico" rel="shortcut icon" />

<script type="text/javascript" src="@Url.Content("~/Scripts/jquery-1.11.1.min.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery-ui.min-1.11.1.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/modernizr-2.8.3.js")"></script>

@Scripts.Render("~/bundles/kendo")
@Scripts.Render("~/bundles/klis")

@Styles.Render("~/content/kendo")
@Styles.Render("~/content/klis")
@Styles.Render("~/content/okprint")    

</head>

BundleConfig.vb

Public Shared Sub RegisterBundles(ByVal bundles As BundleCollection)

    bundles.Add(New ScriptBundle("~/bundles/jquery").Include(
               "~/Scripts/jquery-{version}.js"))

    bundles.Add(New ScriptBundle("~/bundles/jqueryui").Include(
                "~/Scripts/jquery-ui-{version}.js"))

    bundles.Add(New ScriptBundle("~/bundles/jqueryval").Include(
                "~/Scripts/jquery.unobtrusive*",
                "~/Scripts/jquery.validate*"))

    bundles.Add(New ScriptBundle("~/bundles/klis").Include("~/klis/js/ks.*"))

    bundles.Add(New ScriptBundle("~/bundles/kendo").Include(
                "~/Scripts/kendo.all.min.js",
                "~/Scripts/cultures/kendo.culture.ko-KR.min.js"))

    bundles.Add(New ScriptBundle("~/bundles/modernizr").Include(
                "~/Scripts/modernizr-*"))


    bundles.Add(New StyleBundle("~/content/kendo").Include(
               "~/Content/kendo.common.min.css", "~/Content/kendo.dataviz.min.css", "~/Content/kendo.default.min.css"))

    bundles.Add(New StyleBundle("~/content/klis").Include("~/klis/css/kendo/ks.*", "~/klis/css/ks.*",
                                              "~/klis/css/control/ks.*", "~/klis/css/site/ks.*", "~/klis/css/page/ks.*",
                                              "~/klis/css/view/ks.*", "~/klis/css/item/ks.*"))

    bundles.Add(New StyleBundle("~/content/okprint").Include(
                "~/klis/css/item/ks.item.print.css"))

    BundleTable.EnableOptimizations = True

End Sub

dimanche 26 juin 2016

How to modify existing script to delay popup on blogger?

I have a script below that creates a popup for users to provide their email addresses. It works fine. I tried to use setTimeout() to delay the popup but couldn't get it right. Please advise how my script below should be modified. Many thanks! (I apologize for the messy format.)

Blogger myimmigrationlawyer.blogspot.com

src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjjpBEVvMKAjMp17STaN3dK97UOM5Oo_2UKKvvZBaykXggl3Q1x2E5Vo78y0Ij8apjSkBEVnxPCn_bqC97ao_t9pwtO-2vGC-sE9OPp7gGUt63HMmAi7UV4k2wKSz9Xuybews9Jvi4xbrGZ/s1600/Subscribe+Via+Email.PNG" />
<div id="description">

<img alt="email" border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi1ytRcIGT0jJG3eyEfn7ebJhAeFDExaQbIlCgnKm8hbNKaIto7ZKjJXB-arKVD76wb4p9PCswCnfltVe0RWqkh55YH5SZMLuE-o8_vzOs5uDFxglYjvpDep9Zq4J4BcpirHMMU8RfHV3eW/s1600/Mail.PNG" /> <strong><b>Get instant updates on immigration matters...</b></strong></div>
<form action="http://feedburner.google.com/fb/a/mailverify" method="post" onsubmit="window.open('http://feedburner.google.com/fb/a/mailverify?uri=blogspot/BVMU', 'popupwindow', 'scrollbars=yes,width=550,height=520');return true" target="popupwindow">

<input name="email" placeholder="Enter Your Email..." required="required" type="text" /><input name="uri" type="hidden" value="blogspot/BVMU" /><input name="loc" type="hidden" value="en_US" />

<div class="button">

    <input type="submit" value="Subscribe" /></div>

    </form>

</div>

<div class="btntFollowFooter">

    Delivered by <a href="http://feedburner.google.com/"       target="_blank">FeedBurner</a> | powered by <a     href="http://www.blogtipsntricks.com/" rel="dofollow" target="_blank">blogtipsntricks</a></div>

</div>

</div>


<script 

    src="http://yourjavascript.com/24315621361/jquery.cookie.js"     type="text/javascript">

</script>


<script type="text/javascript">

     var popupStatus = 0;

//this code will load popup with jQuery magic!

function loadPopup(){

    //loads popup only if it is disabled

    if(popupStatus==0){

        $("#backgroundPopup").fadeIn("slow");

        $("#popupContact").fadeIn("slow");

        popupStatus = 1;

    }

}



//This code will disable popup when click on x!

function disablePopup(){

    //disables popup only if it is enabled

    if(popupStatus==1){

        $("#backgroundPopup").fadeOut("slow");

        $("#popupContact").fadeOut("slow");

        popupStatus = 0;

    }

}



//this code will center popup

function centerPopup(){

    //request data for centering

    var windowWidth = document.documentElement.clientWidth;

    var windowHeight = document.documentElement.clientHeight;

    var popupHeight = $("#popupContact").height();

    var popupWidth = $("#popupContact").width();

    //centering

    $("#popupContact").css({

        "position": "absolute",

        "top": windowHeight/2-popupHeight/2,

        "left": windowWidth/2-popupWidth/2

    });

    //only need force for IE6  

    $("#backgroundPopup").css({

        "height": windowHeight

    });



}

//CONTROLLING EVENTS IN jQuery

$(document).ready(function(){

    if ($.cookie("anewsletter") != 1) {  

        //centering with css


       centerPopup();

        //load popup






     loadPopup(); 

    }      

    //CLOSING POPUP

    //Click the x event!

    $("#popupContactClose").click(function(){

        disablePopup();

        $.cookie("anewsletter", "1", { expires: 2 });

    });

    //Press Escape event!

    $(document).keypress(function(e){

        if(e.keyCode==27 && popupStatus==1){

            disablePopup();

            $.cookie("anewsletter", "1", { expires: 7 });

        }

    });



});</script>

Website not being able to login into the REST application

I am developing a web application. My main application is a REST application. Unlike traditional web development, my website connects to my rest application to POST, DELETE, PUT or GET data.

Now, when i POST my username and password to my REST application through a desktop application called Postman(https://www.getpostman.com/) and then GET the account data, it works perfectly fine and I am able to retrieve the data.

But when my website connects to my REST app through cURL library. It is not able to GET any data because the website shows not logged in.

I don't know why Postman and my website are behaving differently even though they are getting data from same REST application.

Note that the sessions are in REST application only, so my website doesnt use any native sessions.

Here are my functions in my website:

function process_api_get($base_url,$extension)
{
    $curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => $base_url . $extension,
        CURLOPT_CUSTOMREQUEST => 'GET'
));

$resp = curl_exec($curl);
curl_close($curl);

 // echo '<pre>';
 // print_r($resp);
 // exit;

return json_decode($resp);
}
function process_api_post($input,$base_url,$extension)
{
    $obj = json_encode($input);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");   
    curl_setopt($ch, CURLOPT_POSTFIELDS, $obj);       
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    curl_setopt($ch, CURLOPT_COOKIESESSION, true);   
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0');

    curl_setopt($ch, CURLOPT_URL, $base_url . $extension);
//    
    if (isset($_COOKIE[session_name()]))
        curl_setopt($ch, CURLOPT_COOKIE, session_name().'='.$_COOKIE[session_name()].'; path=/');

    session_write_close();

    $result = curl_exec($ch);


    curl_close($ch);

  return json_decode($result); 
}

function process_api_put($input,$base_url,$extension)
{

  $obj = json_encode($input);
    $ch = curl_init();
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");   
  curl_setopt($ch, CURLOPT_POSTFIELDS, $obj);       
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch, CURLOPT_COOKIESESSION, true);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0');   
    curl_setopt($ch, CURLOPT_URL, $base_url . $extension);
  if (isset($_COOKIE[session_name()]))
       curl_setopt($ch, CURLOPT_COOKIE, session_name().'='.$_COOKIE[session_name()].'; path=/');

  session_write_close(); 
    $result = curl_exec($ch);
    curl_close($ch);
    session_start();
  return json_decode($result); 

}
function process_api_delete($input,$base_url,$extension)
{
    $obj = json_encode($input);
    $ch = curl_init();
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");   
  curl_setopt($ch, CURLOPT_POSTFIELDS, $obj);       
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, $base_url . $extension);
    $result = curl_exec($ch);
    curl_close($ch);
  return json_decode($result); 
}

PHP: How do I sort the date format m/d/yyyy by year using DateTime or strtotime()? [duplicate]

This question already has an answer here:

I have the following array.................

Array
(
    [0] => Array
        (
            [last_name] => Smith
            [first_name] => Steve
            [gender] => Male
            [date_of_birth] => 3/3/1985
            [favorite_color] => Red
        )

    [1] => Array
        (
            [last_name] => Seles
            [first_name] => Monica
            [gender] => Female
            [date_of_birth] => 12/2/1973
            [favorite_color] => Black
        )

    [2] => Array
        (
            [last_name] => Kournikova
            [first_name] => Anna
            [gender] => Female
            [date_of_birth] => 6/3/1975
            [favorite_color] => Red
        )

    [3] => Array
        (
            [last_name] => Kelly
            [first_name] => Sue
            [gender] => Female
            [date_of_birth] => 7/12/1959
            [favorite_color] => Pink
        )

    [4] => Array
        (
            [last_name] => Hingis
            [first_name] => Martina
            [gender] => Female
            [date_of_birth] => 4/2/1979
            [favorite_color] => Green
        )

    [5] => Array
        (
            [last_name] => Bouillon
            [first_name] => Francis
            [gender] => Male
            [date_of_birth] => 6/3/1975
            [favorite_color] => Blue
        )

    [6] => Array
        (
            [last_name] => Bonk
            [first_name] => Radek
            [gender] => Male
            [date_of_birth] => 6/3/1975
            [favorite_color] => Green
        )

    [7] => Array
        (
            [last_name] => Bishop
            [first_name] => Timothy
            [gender] => Male
            [date_of_birth] => 4/23/1967
            [favorite_color] => Yellow
        )

    [8] => Array
        (
            [last_name] => Abercrombie
            [first_name] => Neil
            [gender] => Male
            [date_of_birth] => 2/13/1943
            [favorite_color] => Tan
        )

)

Here is the code that did it..................

<?php 

    $space_txt = './data/input/space.txt';
    $comma_txt = './data/input/comma.txt';
    $pipe_txt = './data/input/pipe.txt';

    $parsed_space_data = file_get_contents($space_txt);
    $parsed_comma_data = file_get_contents($comma_txt);
    $parsed_pipe_data = file_get_contents($pipe_txt);



    $space_array = myExpldeLoopFunc("space"," ", $parsed_space_data);
    $comma_array = myExpldeLoopFunc("comma",",", $parsed_comma_data);
    $pipe_array = myExpldeLoopFunc("pipe"," | ", $parsed_pipe_data);


    $finalArray = array_merge($space_array, $comma_array, $pipe_array);


    function changeGender($gender) {


        return $gender === 'F' ? 'Female' : 'Male';
    }

    function normalizeDate($date) {
        return str_replace('-', '/', $date);
    }




    function myExpldeLoopFunc($name, $sep, $data) {

        $parsedData = explode("n", $data);




        $arr = [];
        foreach ($parsedData as $data) {
            if ($data === "") continue;
            $data_arr = explode($sep, $data);





            if($name == 'space'){

                $arr[] = [
                    "last_name" => trim($data_arr[0]),
                    "first_name" => trim($data_arr[1]),
                    // "middle_initial" => trim($data_arr[2]),
                    "gender" => changeGender(trim($data_arr[3])),
                    "date_of_birth" => normalizeDate(trim($data_arr[4])),
                    "favorite_color" => trim($data_arr[5])



                ];








            }

                elseif($name == 'comma') {
                    $arr[] = [
                    "last_name" => trim($data_arr[0]),
                    "first_name" => trim($data_arr[1]),
                    "gender" => trim($data_arr[2]),
                    "date_of_birth" => normalizeDate(trim($data_arr[4])),
                    "favorite_color" => trim($data_arr[3])

                    ];
                }

            elseif ($name == 'pipe') {
                    $arr[] = [
                    "last_name" => trim($data_arr[0]),
                    "first_name" => trim($data_arr[1]),
                    // "middle_initial" => trim($data_arr[2]),
                    "gender" => changeGender(trim($data_arr[3])),
                    "date_of_birth" => normalizeDate(trim($data_arr[5])),
                    "favorite_color" => trim($data_arr[4])



                ];


            }





    }



    return $arr;







        }












 ?>

This is the code I use to sort the array by birth_date and last_name............

<?php 

 foreach ($finalArray as $key => $row) {
    $date_of_birth[$key] = $row['date_of_birth'];
    $last_name[$key] = $row['last_name'];
}

 array_multisort($date_of_birth, SORT_NUMERIC, $last_name, SORT_ASC, $finalArray);

 foreach ($finalArray as $row) {
    echo join(' ', $row) . "<br>n";
 }  




  ?>

The following output is this .............................

Abercrombie Neil Male 2/13/1943 Tan
Smith Steve Male 3/3/1985 Red
Bishop Timothy Male 4/23/1967 Yellow
Hingis Martina Female 4/2/1979 Green
Bonk Radek Male 6/3/1975 Green
Bouillon Francis Male 6/3/1975 Blue
Kournikova Anna Female 6/3/1975 Red
Kelly Sue Female 7/12/1959 Pink
Seles Monica Female 12/2/1973 Black

The following output should look like this..............................

Abercrombie Neil Male 2/13/1943 Tan
Kelly Sue Female 7/12/1959 Pink
Bishop Timothy Male 4/23/1967 Yellow
Seles Monica Female 12/2/1973 Black
Bonk Radek Male 6/3/1975 Green
Bouillon Francis Male 6/3/1975 Blue
Kournikova Anna Female 6/3/1975 Red
Hingis Martina Female 4/2/1979 Green
Smith Steve Male 3/3/1985 Red

How can I sort the dates by 'year' in m/d/yyyy format along with the lastnames going in alphabetical order?

How to remove jitter/shaking in my special application of OrbitControl and PerspectiveCamera?

In the live snippet below (also at https://jsfiddle.net/gpolyn/bpo7t7f6), I offer optional dynamic updating of PerspectiveCamera's lookAt parameter and fov in the three.js render cycle. (My goal is to fill as much of the viewport as possible with the subject cube, through all orbit positions.)

I suspect that lack of precision in the matrix math code used to calculate my dynamic fov and lookAt paramters (three.js uses Float32 arrays) causes the jitter/shaking I notice in the cube when orbiting with the dynamic options selected from the controls. (The matrix operations can be found in the snippet addExtrema function.)

In my demo, my highest goal is to remove jitter/shaking in case 1, described here:

  1. the "dynamicFovAndLookAt" control option uses dynamic fov and lookAt updating causing quite a bit of jitter in the cube, no matter the orbit position; the fov and lookAt parameters can be seen fluctuating in the demo's lower right status box;
  2. "dynamicFov" uses dynamic fov updating causing some jitter in the cube, depending on orbiting; the fov parameter in the lower right status box will vary due to the dynamic recalculation;
  3. the "boundingSphere" option uses no dynamic fov, lookAt updating and the cube exhibits no jitter/shake through orbiting – the fov and lookAt parameters are constant in the lower right status box.

(Orbit position is reported in the lower left corner of the demo, while one of the box corners has a green dot to aid any discussion of the jitter effect.)

	var renderer, scene, camera, controls;
	var object;
	var vertices3;
	var cloud;
	var boxToBufferAlphaMapping = {
	  0: 0,
	  2: 1,
	  1: 2,
	  3: 4,
	  6: 7,
	  7: 10,
	  5: 8,
	  4: 6
	}
	var lastAlphas = [];
	var canvasWidth, canvasHeight;
	var windowMatrix;
	var boundingSphere;
	var figure;
	var fovWidth, fovDistance, fovHeight;
	var newFov, newLookAt;
	var dist, height, fov, lookAt;
	var aspect;
	var CONSTANT_FOR_FOV_CALC = 180 / Math.PI;
	var mat3;
	var CORNERS = 8;
	var ndc = new Array(CORNERS);
	var USE_GREEN_DOTS = false;
	var stats, orbitPosition, cameraFacts;
	var useDynamicFov;
	var datGuiData = {};


	init();
	render();
	afterInit();
	animate();

	function init() {

	  mat3 = new THREE.Matrix4();

	  canvasWidth = window.innerWidth;
	  canvasHeight = window.innerHeight;
	  aspect = canvasWidth / canvasHeight;
	  // renderer
	  <!-- renderer = new THREE.WebGLRenderer({antialias:true, logarithmicDepthBuffer:true}); -->
	  renderer = new THREE.WebGLRenderer({
	    antialias: true
	  });
	  renderer.setSize(canvasWidth, canvasHeight);
	  document.body.appendChild(renderer.domElement);

	  // scene
	  scene = new THREE.Scene();

	  // object
	  var geometry = new THREE.BoxGeometry(4, 4, 6);

	  // too lazy to add edges without EdgesHelper...
	  var material = new THREE.MeshBasicMaterial({
	    transparent: true,
	    opacity: 0
	  });
	  var cube = new THREE.Mesh(geometry, material);
	  object = cube;

	  // bounding sphere used for orbiting control in render
	  object.geometry.computeBoundingSphere();
	  boundingSphere = object.geometry.boundingSphere;

	  cube.position.set(2, 2, 3)
	    // awkward, but couldn't transfer cube position to sphere...
	  boundingSphere.translate(new THREE.Vector3(2, 2, 3));

	  // save vertices for subsequent use
	  vertices = cube.geometry.vertices;

	  var edges = new THREE.EdgesHelper(cube)
	  scene.add(edges);
	  scene.add(cube);

	  <!-- if (USE_GREEN_DOTS) addGreenDotsToScene(geometry); -->
	  addGreenDotsToScene(geometry);

	  // camera
	  <!-- camera = new THREE.PerspectiveCamera( 17, window.innerWidth / window.innerHeight, 20, 40 ); -->
	  camera = new THREE.PerspectiveCamera(17, window.innerWidth / window.innerHeight);
	  camera.position.set(20, 20, 20);

	  // controls
	  controls = new THREE.OrbitControls(camera);
	  controls.maxPolarAngle = 0.5 * Math.PI;
	  controls.minAzimuthAngle = 0;
	  controls.maxAzimuthAngle = 0.5 * Math.PI;
	  controls.enableZoom = false;

	  // performance monitor
	  stats = new Stats();
	  document.body.appendChild(stats.dom);

	  // orbitposition tracker
	  orbitPosition = new THREEg.OrbitReporter()
	  orbitPosition.domElement.style.position = 'absolute'
	  orbitPosition.domElement.style.left = '0px'
	  orbitPosition.domElement.style.bottom = '0px'
	  document.body.appendChild(orbitPosition.domElement)

	  // camera facts
	  cameraFacts = new THREEg.CameraReporter()
	  cameraFacts.domElement.style.position = 'absolute'
	  cameraFacts.domElement.style.right = '0px'
	  cameraFacts.domElement.style.bottom = '0px'
	  document.body.appendChild(cameraFacts.domElement)

	  // ambient
	  scene.add(new THREE.AmbientLight(0x222222));

	  // axes
	  scene.add(new THREE.AxisHelper(20));

	  // initial settings
	  dist = boundingSphere.distanceToPoint(camera.position);
	  height = boundingSphere.radius * 2;
	  fov = 2 * Math.atan(height / (2 * dist)) * (CONSTANT_FOR_FOV_CALC);
	  newFov = fov;
	  lookAt = new THREE.Vector3(2, 2, 3); // center of box
	  newLookAt = lookAt;

	  // dat.gui
	  window.onload = function() {
	    var view = datGuiData;
	    view.boundingSphere = true;
	    view.dynamicFov = false;
	    view.dynamicFovAndLookAt = false;

	    var gui = new dat.GUI();

	    var CB1Controller = gui.add(view, 'boundingSphere').listen();
	    CB1Controller.onChange(function(value) {
	      view.boundingSphere = true;
	      view.dynamicFov = false;
	      view.dynamicFovAndLookAt = false;
	    });

	    var CB2Controller = gui.add(view, 'dynamicFov').listen();
	    CB2Controller.onChange(function(value) {
	      view.boundingSphere = false;
	      view.dynamicFov = true;
	      view.dynamicFovAndLookAt = false;
	    });

	    var CB3Controller = gui.add(view, 'dynamicFovAndLookAt').listen();
	    CB3Controller.onChange(function(value) {
	      view.boundingSphere = false;
	      view.dynamicFov = true;
	      view.dynamicFovAndLookAt = true;
	    });
	  };

	}

	function addExtrema() {

	  // thread A		
	  mat3.multiplyMatrices(camera.matrixWorld, mat3.getInverse(camera.projectionMatrix));

	  // thread B	
	  var scratchVar;

	  var topIdx, bottomIdx, leftIdx, rightIdx;
	  var top = Number.NEGATIVE_INFINITY;
	  var bottom = Number.POSITIVE_INFINITY;
	  var right = Number.NEGATIVE_INFINITY;
	  var left = Number.POSITIVE_INFINITY;
	  var closestVertex, closestVertexDistance = Number.POSITIVE_INFINITY;
	  var vtx;

	  for (var i = 0; i < CORNERS; i++) {

	    scratchVar = vertices3[i].clone().applyMatrix4(camera.matrixWorldInverse);
	    scratchVar.applyMatrix4(camera.projectionMatrix);

	    scratchVar.divideScalar(scratchVar.w)
	    ndc[i] = scratchVar;

	    vtx = ndc[i];

	    if (vtx.x < left) {
	      left = vtx.x;
	      leftIdx = i;
	    } else if (vtx.x > right) {
	      right = vtx.x;
	      rightIdx = i;
	    }

	    if (vtx.y < bottom) {
	      bottom = vtx.y;
	      bottomIdx = i;
	    } else if (vtx.y > top) {
	      top = vtx.y;
	      topIdx = i;
	    }

	    if (vtx.z < closestVertexDistance) {
	      closestVertex = i;
	      closestVertexDistance = vtx.z;
	    }

	  }

	  var yNDCPercentCoverage = (Math.abs(ndc[topIdx].y) + Math.abs(ndc[bottomIdx].y)) / 2;
	  yNDCPercentCoverage = Math.min(1, yNDCPercentCoverage);

	  var xNDCPercentCoverage = (Math.abs(ndc[leftIdx].x) + Math.abs(ndc[rightIdx].x)) / 2;
	  xNDCPercentCoverage = Math.min(1, xNDCPercentCoverage);

	  var ulCoords = [ndc[leftIdx].x, ndc[topIdx].y, closestVertexDistance, 1]
	  var blCoords = [ndc[leftIdx].x, ndc[bottomIdx].y, closestVertexDistance, 1]
	  var urCoords = [ndc[rightIdx].x, ndc[topIdx].y, closestVertexDistance, 1]

	  var ul = new THREE.Vector4().fromArray(ulCoords);
	  ul.applyMatrix4(mat3).divideScalar(ul.w);

	  var bl = new THREE.Vector4().fromArray(blCoords);
	  bl.applyMatrix4(mat3).divideScalar(bl.w);

	  var ur = new THREE.Vector4().fromArray(urCoords);
	  ur.applyMatrix4(mat3).divideScalar(ur.w);

	  var center = new THREE.Vector3();
	  center.addVectors(ur, bl);
	  center.divideScalar(2);

	  var dist = camera.position.distanceTo(center);


	  var upperLeft = new THREE.Vector3().fromArray(ul.toArray().slice(0, 3));
	  var p;

	  if ((1 - yNDCPercentCoverage) < (1 - xNDCPercentCoverage)) { // height case
	    var bottomLeft = new THREE.Vector3().fromArray(bl.toArray().slice(0, 3));
	    var height = upperLeft.distanceTo(bottomLeft);
	    p = 2 * Math.atan(height / (2 * dist)) * (CONSTANT_FOR_FOV_CALC);
	  } else { // width case
	    var upperRight = new THREE.Vector3().fromArray(ur.toArray().slice(0, 3));
	    var width = upperRight.distanceTo(upperLeft);
	    p = 2 * Math.atan((width / aspect) / (2 * dist)) * (CONSTANT_FOR_FOV_CALC);
	  }

	  if (datGuiData.dynamicFovAndLookAt || datGuiData.dynamicFov) {
	    newFov = p;
	  } else {
	    dist = boundingSphere.distanceToPoint(camera.position);
	    height = boundingSphere.radius * 2;
	    newFov = 2 * Math.atan(height / (2 * dist)) * (CONSTANT_FOR_FOV_CALC);
	  }

	  if (datGuiData.dynamicFovAndLookAt == true) {
	    newLookAt = center;
	  } else {
	    newLookAt = lookAt;
	  }

	  if (USE_GREEN_DOTS) {
	    var alphas = cloud.geometry.attributes.alpha;

	    // make last points invisible
	    lastAlphas.forEach(function(alphaIndex) {
	      alphas.array[alphaIndex] = 0.0;
	    });
	    // now, make new points visible...
	    // (boxToBufferAlphaMapping is a BufferGeometry-Object3D geometry
	    // map between the object and green dots)
	    alphas.array[boxToBufferAlphaMapping[rightIdx]] = 1.0;
	    alphas.array[boxToBufferAlphaMapping[bottomIdx]] = 1.0;
	    alphas.array[boxToBufferAlphaMapping[topIdx]] = 1.0;
	    alphas.array[boxToBufferAlphaMapping[leftIdx]] = 1.0;

	    // store visible points for next cycle
	    lastAlphas = [boxToBufferAlphaMapping[rightIdx]];
	    lastAlphas.push(boxToBufferAlphaMapping[bottomIdx])
	    lastAlphas.push(boxToBufferAlphaMapping[topIdx])
	    lastAlphas.push(boxToBufferAlphaMapping[leftIdx])

	    alphas.needsUpdate = true;
	  }

	}

	function addGreenDotsToScene(geometry) {

	  var bg = new THREE.BufferGeometry();
	  bg.fromGeometry(geometry);
	  bg.translate(2, 2, 3); // yucky, and quick

	  var numVertices = bg.attributes.position.count;
	  var alphas = new Float32Array(numVertices * 1); // 1 values per vertex

	  <!-- for( var i = 0; i < numVertices; i ++ ) { -->
	  <!--     alphas[ i ] = 1; -->
	  <!-- } -->

	  alphas[2] = 1;

	  bg.addAttribute('alpha', new THREE.BufferAttribute(alphas, 1));

	  var uniforms = {
	    color: {
	      type: "c",
	      value: new THREE.Color(0x00ff00)
	    },
	  };

	  var shaderMaterial = new THREE.ShaderMaterial({
	    uniforms: uniforms,
	    vertexShader: document.getElementById('vertexshader').textContent,
	    fragmentShader: document.getElementById('fragmentshader').textContent,
	    transparent: true
	  });

	  cloud = new THREE.Points(bg, shaderMaterial);
	  scene.add(cloud);

	}

	function afterInit() {

	  windowMatrix = new THREE.Matrix4();
	  windowMatrix.set(canvasWidth / 2, 0, 0, canvasWidth / 2, 0, canvasHeight / 2, 0, canvasHeight / 2, 0, 0, 0.5, 0.5, 0, 0, 0, 1);

	  var vertices2 = object.geometry.vertices.map(function(vtx) {
	    return (new THREE.Vector4(vtx.x, vtx.y, vtx.z));
	  });

	  // create 'world-space' geometry points, using
	  // model ('world') matrix
	  vertices3 = vertices2.map(function(vt) {
	    return vt.applyMatrix4(object.matrixWorld);
	  })

	}

	function render() {

	  <!-- console.log({far: camera.far, camera_near: camera.near}) -->
	  camera.lookAt(newLookAt);
	  camera.fov = newFov;
	  camera.updateProjectionMatrix();
	  renderer.render(scene, camera);

	}

	function animate() {

	  requestAnimationFrame(animate);
	  render();
	  addExtrema()
	  stats.update();
	  orbitPosition.update(controls);
	  cameraFacts.update(camera, newLookAt);

	}
			body {
			  background-color: #000;
			  margin: 0px;
			  overflow: hidden;
			}
			.dg .c {
			  width: 40%
			}
			.dg .property-name {
			  width: 60%
			}
			
<script src="https://rawgit.com/mrdoob/three.js/dev/build/three.min.js"></script>
<script src="https://rawgit.com/mrdoob/three.js/master/examples/js/libs/stats.min.js"></script>
<script src="https://rawgit.com/mrdoob/three.js/master/examples/js/controls/OrbitControls.js"></script>
<script src="https://rawgit.com/gpolyn/789d63a662c1768320756f68a6099f15/raw/3a0f323bb284b09e624a11f93ff4055e23adea80/OrbitReporter.js"></script>
<script src="https://rawgit.com/gpolyn/70352cb34c7900ed2489400d4ecc45f7/raw/7b6e7e6bb3e175d4145879ef1afdeb38c31cf785/camera_reporter.js"></script>
<script src="https://rawgit.com/mrdoob/three.js/master/examples/js/libs/dat.gui.min.js"></script>
<script type="x-shader/x-vertex" id="vertexshader">

  attribute float alpha; varying float vAlpha; void main() { vAlpha = alpha; vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 ); gl_PointSize = 8.0; gl_Position = projectionMatrix * mvPosition; }

</script>

<script type="x-shader/x-fragment" id="fragmentshader">

  uniform vec3 color; varying float vAlpha; void main() { gl_FragColor = vec4( color, vAlpha ); }

</script>

multiple slideshows with different sets of slides in one webpage

I have a website with multiple popups and I want to place a slideshow into each popup; however when i add second slideshow, slides from first slideshow also get to the second slideshow. I use .getElementsByClassName to specify images for slideshows in my script; however i dont understand how can I separate specific slides for each slideshow or adjust functions to handle multiple classnames for each slideshow. Sorry if question is stupid, I am new to this and i am really stuck on this. Thank you for understanding. My code is as follows.

                 <div id="popup1" class="overlay">
                    <div class="popup">
                        <h2>YAMAHA XV950 (BOLT)</h2>
                        <a class="close" href="#">&times;</a>
                        <div class="content">
                            <div class="slideshow-container">
                              <div class="mySlides fade">
                                <div class="numbertext">1 / 3</div>
                                <img src="YAMAHA%20XV950.png"  height="330">
                                <div class="text"></div>
                              </div>

                              <div class="mySlides fade">
                                <div class="numbertext">2 / 3</div>
                                <img src="YAMAHA%20XV950-2.png" height="330">
                                <div class="text"></div>
                              </div>

                              <div class="mySlides fade">
                                <div class="numbertext">3 / 3</div>
                                <img src="YAMAHA%20XV950-3.png" height="330">
                                <div class="text"></div>
                              </div>

                              <a class="prev" onclick="plusSlides(-1)">&#10094;</a>
                              <a class="next" onclick="plusSlides(1)">&#10095;</a>
                            </div>
                            <br>
                            <div style="text-align:center">
                              <span class="dot" onclick="currentSlide(1)"></span> 
                              <span class="dot" onclick="currentSlide(2)"></span> 
                              <span class="dot" onclick="currentSlide(3)"></span> 
                            </div>
                            <br>
                        </div>
                    </div>
                </div>
                <div id="popup2" class="overlay">
                    <div class="popup">
                        <h2>SUZUKI INTRUDER (BOLT)</h2>
                        <a class="close" href="#">&times;</a>
                        <div class="content">
                            <div class="slideshow-container">
                              <div class="mySlides1 fade">
                                <div class="numbertext">1 / 3</div>
                                <img src="SintruderC1500BT%20B.O.S.S..png"  height="330">
                                <div class="text"></div>
                              </div>

                              <div class="mySlides1 fade">
                                <div class="numbertext">2 / 3</div>
                                <img src="SintruderC800B%20B.O.S.S..png" height="330">
                                <div class="text"></div>
                              </div>

                              <div class="mySlides1 fade">
                                <div class="numbertext">3 / 3</div>
                                <img src="SintruderM1800R.png" height="330">
                                <div class="text"></div>
                              </div>

                              <a class="prev" onclick="plusSlides(-1)">&#10094;</a>
                              <a class="next" onclick="plusSlides(1)">&#10095;</a>
                            </div>
                            <br>
                            <div style="text-align:center">
                              <span class="dot" onclick="currentSlide(1)"></span> 
                              <span class="dot" onclick="currentSlide(2)"></span> 
                              <span class="dot" onclick="currentSlide(3)"></span> 
                            </div>
                         </div>
                    </div>
                </div>
                <script>
                var slideIndex = 1;
                showSlides(slideIndex);

                function plusSlides(n) {
                showSlides(slideIndex += n);
                }

                function currentSlide(n) {
                showSlides(slideIndex = n);
                }

                function showSlides(n) {
                var i;
                var slides = document.getElementsByClassName("mySlides");
                var dots = document.getElementsByClassName("dot");
                if (n > slides.length) {slideIndex = 1}
                if (n < 1) {slideIndex = slides.length}
                for (i = 0; i < slides.length; i++) {
                slides[i].style.display = "none";
                }
                for (i = 0; i < dots.length; i++) {
                   dots[i].className = dots[i].className.replace(" active", "");
                }
                slides[slideIndex-1].style.display = "block";
                   dots[slideIndex-1].className += " active";
                }

                </script>