问:
Building minigame in JQuery (Javascript)
I am making a set of minigames for my major project, with this minigame I have being following the same method from a previous minigame that I built before.

In my previous minigame I only had one PuzzleContainer but in this one I'm making now has four. Ever since I added three more PuzzleContainers the code doesn't seem to work. Have I done something wrong in my scipting? Can anyone tell me where I'm going wrong?

This is my code for the minigame I am currently working on.

$(document).ready(function() {

 //speech
 var progress = 0;
 var txt;
 $('#complete, #speech').hide();

 function eventHandler() {
  switch (progress) {
   case 0:
    txt = "Complete";
    break;
   case 1:
    txt = "Move on to the next minigame";
    $('#speech').click(function(){
     window.location.href="minigame8.html";
    });
    break;
   }
   progress++;
   $('#speech').html(txt);
  }

  $('#speech').click(eventHandler);

 // Sortable //

 $('#puzzleContainer1', '#puzzleContainer2', '#puzzleContainer3', '#puzzleContainer4').sortable({
  update: function() {
   var userPieces = '';
   $('#puzzleContainer1 li', '#puzzleContainer2 li', '#puzzleContainer3 li', '#puzzleContainer4 li').each(function() {
    userPieces += $(this).attr('data');
   })
   checkResult(userPieces);
  }
 });
 $('#puzzleContainer1', '#puzzleContainer2', '#puzzleContainer3', '#puzzleContainer4').disableSelection();

 //shows the "Enterpassword once pieces are all correctly aligned
 function checkResult(userPieces) {
  if (userPieces == '1234' && '12345' && '123456') {
   $("#complete").show(0,function() {
    eventHandler()
    $('#speech').show();
   });
  }
 }

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#puzzleContainer1 {
 position: absolute;
 z-index: 5;
 top: 10px;
 left: 130px;
 list-style-type: none;
}

#puzzleContainer2 {
 position: absolute;
 z-index: 5;
 top: 75px;
 left: 130px;
 list-style-type: none;
}

#puzzleContainer3 {
 position: absolute;
 z-index: 5;
 top: 140px;
 left: 130px;
 list-style-type: none;
}

#puzzleContainer4 {
 position: absolute;
 z-index: 5;
 top: 205px;
 left: 130px;
 list-style-type: none;
}

ul, menu, dir {
 display: block;
}

.piece{
 z-index: 5;
 float: left;
 margin: 0 10px 0 0;
 padding: 0;
}

li {
 display: list-item;
 text-align: -webkit-match-parent;
}

#complete {
 position: absolute;
 width: 105px;
 height: 25px;
 top: 240px;
 left: 289px;
 background-color: black;
 color: white;
 font-size: 20px;
 padding: 10px;
 border-style: solid;
 border-width: 5px;
 border-color: white;
 z-index:5;
}

#speech {
 position: absolute;
 width: 655px;
 height: 100px;
 top: 330px;
 left: 15px;
 background-color: black;
 color: white;
 font-size: 25px;
 padding: 10px;
 border-style: solid;
 border-width: 5px;
 border-color: white;
 z-index: 99;
}</code>```

<!doctype html>

<meta charset="utf-8">
<title>MAS340</title>
<link href="styles.css" rel="stylesheet" />

4

1

2

5

3

3

2

4

1

3

2

4

6

1

5

1

4

3

2

  <input id="password" type="text" style="display: block;">
  <button id="submit" style="display: block;">Enter Password</button>

ACCEPTED

```

答:
I think there is a problem with your selector. Try to select  puzzle containers like this: </p>

```<code>$('#puzzleContainer1, #puzzleContainer2, #puzzleContainer3, #puzzleContainer4')
</code>```

Body:
I am making a set of minigames for my major project, with this minigame I have being following the same method from a previous minigame that I built before.

In my previous minigame I only had one PuzzleContainer but in this one I'm making now has four. Ever since I added three more PuzzleContainers the code doesn't seem to work. Have I done something wrong in my scipting? Can anyone tell me where I'm going wrong?

This is my code for the minigame I am currently working on.

$(document).ready(function() {

 //speech
 var progress = 0;
 var txt;
 $('#complete, #speech').hide();

 function eventHandler() {
  switch (progress) {
   case 0:
    txt = "Complete";
    break;
   case 1:
    txt = "Move on to the next minigame";
    $('#speech').click(function(){
     window.location.href="minigame8.html";
    });
    break;
   }
   progress++;
   $('#speech').html(txt);
  }

  $('#speech').click(eventHandler);

 // Sortable //

 $('#puzzleContainer1', '#puzzleContainer2', '#puzzleContainer3', '#puzzleContainer4').sortable({
  update: function() {
   var userPieces = '';
   $('#puzzleContainer1 li', '#puzzleContainer2 li', '#puzzleContainer3 li', '#puzzleContainer4 li').each(function() {
    userPieces += $(this).attr('data');
   })
   checkResult(userPieces);
  }
 });
 $('#puzzleContainer1', '#puzzleContainer2', '#puzzleContainer3', '#puzzleContainer4').disableSelection();

 //shows the "Enterpassword once pieces are all correctly aligned
 function checkResult(userPieces) {
  if (userPieces == '1234' && '12345' && '123456') {
   $("#complete").show(0,function() {
    eventHandler()
    $('#speech').show();
   });
  }
 }

});

#puzzleContainer1 {
 position: absolute;
 z-index: 5;
 top: 10px;
 left: 130px;
 list-style-type: none;
}

#puzzleContainer2 {
 position: absolute;
 z-index: 5;
 top: 75px;
 left: 130px;
 list-style-type: none;
}

#puzzleContainer3 {
 position: absolute;
 z-index: 5;
 top: 140px;
 left: 130px;
 list-style-type: none;
}

#puzzleContainer4 {
 position: absolute;
 z-index: 5;
 top: 205px;
 left: 130px;
 list-style-type: none;
}

ul, menu, dir {
 display: block;
}

.piece{
 z-index: 5;
 float: left;
 margin: 0 10px 0 0;
 padding: 0;
}

li {
 display: list-item;
 text-align: -webkit-match-parent;
}

#complete {
 position: absolute;
 width: 105px;
 height: 25px;
 top: 240px;
 left: 289px;
 background-color: black;
 color: white;
 font-size: 20px;
 padding: 10px;
 border-style: solid;
 border-width: 5px;
 border-color: white;
 z-index:5;
}

#speech {
 position: absolute;
 width: 655px;
 height: 100px;
 top: 330px;
 left: 15px;
 background-color: black;
 color: white;
 font-size: 25px;
 padding: 10px;
 border-style: solid;
 border-width: 5px;
 border-color: white;
 z-index: 99;
}

<!doctype html>

<meta charset="utf-8">
<title>MAS340</title>
<link href="styles.css" rel="stylesheet" />

4

1

2

5

3

3

2

4

1

3

2

4

6

1

5

1

4

3

2

  <input id="password" type="text" style="display: block;">
  <button id="submit" style="display: block;">Enter Password</button>

ACCEPTED

Body:
I think there is a problem with your selector. Try to select  puzzle containers like this:

$('#puzzleContainer1, #puzzleContainer2, #puzzleContainer3, #puzzleContainer4')


来源: stackexchange

问:
How do I create a condition that will not display a field if the field is empty?
I am using advanced custom fields (ACF). I would like to not display the ACF  repeater field the_sub_field('feature_image_post'); if the field is empty. I wrapped the field in a div and wrote a display = none using CSS if the field is empty but I'm sure there is a better way of doing this. My logic doesn't seem to work.

```<code> <?php

        // check if the repeater field has rows of data

        if( have_rows('repeat_field') ):

          // loop through the rows of data
            while ( have_rows('repeat_field') ) : the_row();

                // display a sub field value

                echo '<span class="place-name">';
                  the_sub_field('place_name');
                echo '</span>';

      if (!empty (get_sub_field('feature_image_post')))  {

       echo '<div class="post-feature" style="display:block;">';
       echo the_sub_field('feature_image_post');
       echo '</div>';

      }

      else {
       echo '<div class="post-feature" style="display:none;">'
       echo the_sub_field('feature_image_post');
       echo '</div>';

      }
            endwhile;

        else :

            // no rows found

        endif;
</code>```

答:
```<code>if (! empty(get_sub_field('feature_image_post'))) {
    echo '<div class="post-feature" style="display:block;">';
    the_sub_field('feature_image_post');
    echo '</div>';
}
</code>```

and that's it. in this case where get_sub_field('feature_image_post') is empty it will just skip the whole part.

as far as I know - the_ in ACF means that it display the data, so you won't need echo before that.

and please always check if you have closed your echo with ;, because in the example you didn't.

ContentLicense: CC BY-SA 3.0

Body:
I am using advanced custom fields (ACF). I would like to not display the ACF  repeater field the_sub_field('feature_image_post'); if the field is empty. I wrapped the field in a div and wrote a display = none using CSS if the field is empty but I'm sure there is a better way of doing this. My logic doesn't seem to work.

 <?php

        // check if the repeater field has rows of data

        if( have_rows('repeat_field') ):

          // loop through the rows of data
            while ( have_rows('repeat_field') ) : the_row();

                // display a sub field value

                echo '';
                  the_sub_field('place_name');
                echo '';

      if (!empty (get_sub_field('feature_image_post')))  {

       echo '
';
       echo the_sub_field('feature_image_post');
       echo '
';

      }

      else {
       echo '
'
       echo the_sub_field('feature_image_post');
       echo '
';

      }
            endwhile;

        else :

            // no rows found

        endif;

Body:
if (! empty(get_sub_field('feature_image_post'))) {
    echo '<div class="post-feature" style="display:block;">';
    the_sub_field('feature_image_post');
    echo '</div>';
}

and that's it. in this case where get_sub_field('feature_image_post') is empty it will just skip the whole part.

as far as I know - the_ in ACF means that it display the data, so you won't need echo before that.

and please always check if you have closed your echo with ;, because in the example you didn't.


问:
Can a private channel communication happen between two Pusher Apps
I have two iOS apps, lets call it Agent app and Customer App.
I have a chat feature between these two apps, but the chats need to be recorded on the server.

I have created two Pusher Apps, one for each of the iOS apps. They both subscribe to their respective private-{id}-channel.

Now every time a message is generated from say Agent app (via HTTP request to server), I want server to create a pusher event with Agent's message on Customer's private channel.

Is it possible to achieve the above using Pusher Private channels?

答: I wanted to record the chat on server, therefore, instead of making Customer App directly sending message on Agent App channel, I made the Customer App call my server API, which records the message and relies it on channel that Agent App is listening to. </p>


问:
Iterate Over Media Files Properties And Display Filenames into Listbox
I'm writing a simple WinForms application which I will use prior to when I edit my video footage in order to know the total length of all the video files when combined and "edited".

So ideally, I load them up then get the duration of each video and tally them up.

However I get stuck in terms of which collection class to use since I am using an external library IWMPMedia in addition to WindowsMediaPlayer to get the filenames and duration.

When I use a string array to get the filename, I get the whole path, which is something I don't want. Please see the following code snippet:

```<code> using WMPLib;

 public partial class frmBacklinkMediaSerializer : Form
 {
    WindowsMediaPlayer wmp;
    IWMPMedia mediainfo;

    Double Duration(String file)
    {
        wmp = new WindowsMediaPlayer();
        mediainfo = wmp.newMedia(file);
        return mediainfo.duration;
    }

    void callDialogBox()
    {
        OpenFileDialog theDialog = new OpenFileDialog();
        theDialog.Filter = "MP4 Videos (*.mp4)|*.mp4";
        theDialog.FilterIndex = 0;
        theDialog.Multiselect = true;
        DialogResult result = theDialog.ShowDialog();
        string[] selected = theDialog.FileNames;
        string strFilename = theDialog.FileName;

        if (result == DialogResult.OK)
        {
            FileInfo oFileInfo = new FileInfo(strFilename);
            string temp = Duration(strFilename).ToString();
            TimeSpan conversion =
            TimeSpan.FromSeconds(Duration(strFilename));
            if (strFilename != null || strFilename.Length != 0)
            {
                MessageBox.Show("My file names are below: " + "\n\n" + mediainfo.name + "\n\n" + "My file duration is: " + conversion.ToString(), "Video Properties", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
            }
        }
    }

    //I then call callDialogBox() on a button click event
</code>```

The output shows as per the below screenshot:

I want to be able to select multiple files and show the in the listbox but I get a:

Additional information: COM object that has been separated from its underlying RCW cannot be used.

When adding items to the listbox.

So two problems:

1. Being able to select and list filenames below one another

2. List the filenames in the listbox

With regards to point 1. , the below code snippet does somewhat achieve it but gives me the entire filename..

string[] selected = theDialog.FileNames;
  foreach(string items in selected)
  {
     MessageBox.Show("Here are your filenames: " + items);
  }

Gives me the entire path. Read up on some resources online but I can't seem to get what I want.

I had a look at: How do I drag n drop files into a ListBox with it showing the file path? and it didn't do the trick.

答:
Try the following to add the filenames to the ListBox:

```<code>listBox1.Items.AddRange(selected);
</code>```

Once this is done, you can then display your total duration.

Edit:
To list only file names, use following line.

```<code>listBox1.Items.AddRange(selected.Select(o=>System.IO.Path.GetFileName(o)).ToArray());
</code>```

Body:
I'm writing a simple WinForms application which I will use prior to when I edit my video footage in order to know the total length of all the video files when combined and "edited".

So ideally, I load them up then get the duration of each video and tally them up.

However I get stuck in terms of which collection class to use since I am using an external library IWMPMedia in addition to WindowsMediaPlayer to get the filenames and duration.

When I use a string array to get the filename, I get the whole path, which is something I don't want. Please see the following code snippet:

 using WMPLib;

 public partial class frmBacklinkMediaSerializer : Form
 {
    WindowsMediaPlayer wmp;
    IWMPMedia mediainfo;

    Double Duration(String file)
    {
        wmp = new WindowsMediaPlayer();
        mediainfo = wmp.newMedia(file);
        return mediainfo.duration;
    }

    void callDialogBox()
    {
        OpenFileDialog theDialog = new OpenFileDialog();
        theDialog.Filter = "MP4 Videos (*.mp4)|*.mp4";
        theDialog.FilterIndex = 0;
        theDialog.Multiselect = true;
        DialogResult result = theDialog.ShowDialog();
        string[] selected = theDialog.FileNames;
        string strFilename = theDialog.FileName;

        if (result == DialogResult.OK)
        {
            FileInfo oFileInfo = new FileInfo(strFilename);
            string temp = Duration(strFilename).ToString();
            TimeSpan conversion =
            TimeSpan.FromSeconds(Duration(strFilename));
            if (strFilename != null || strFilename.Length != 0)
            {
                MessageBox.Show("My file names are below: " + "\n\n" + mediainfo.name + "\n\n" + "My file duration is: " + conversion.ToString(), "Video Properties", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
            }
        }
    }

    //I then call callDialogBox() on a button click event

The output shows as per the below screenshot:

I want to be able to select multiple files and show the in the listbox but I get a:

Additional information: COM object that has been separated from its underlying RCW cannot be used.

When adding items to the listbox.

So two problems:

1. Being able to select and list filenames below one another

2. List the filenames in the listbox

With regards to point 1. , the below code snippet does somewhat achieve it but gives me the entire filename..

string[] selected = theDialog.FileNames;
  foreach(string items in selected)
  {
     MessageBox.Show("Here are your filenames: " + items);
  }

Gives me the entire path. Read up on some resources online but I can't seem to get what I want.

I had a look at: How do I drag n drop files into a ListBox with it showing the file path? and it didn't do the trick.

Body:
Try the following to add the filenames to the ListBox:

listBox1.Items.AddRange(selected);

Once this is done, you can then display your total duration.

Edit:
To list only file names, use following line.

listBox1.Items.AddRange(selected.Select(o=>System.IO.Path.GetFileName(o)).ToArray());


问:
How to autofill the right textfield
I need to autocomplete textfields from tableview. How can i select the right textfield(where i am writing at this moment)?

code is here

答:
If I understand correctly you have two UITextFields and a UITableView and when you tap on a cell in the table view you want to put it's text into whichever text field has your input focus.

Try this:

```<code>if firstTextField.isFirstResponder {
    firstTextField.text = selectedCell.textLabel.text
}
if secondTextField.isFirstResponder {
    secondTextField.text = selectedCell.textLabel.text
}
</code>```

The isFirstResponder method tells you if the control has the current focus and only one of them can.

Title: How to autofill the right textfield

Body:
If I understand correctly you have two UITextFields and a UITableView and when you tap on a cell in the table view you want to put it's text into whichever text field has your input focus.

Try this:

if firstTextField.isFirstResponder {
    firstTextField.text = selectedCell.textLabel.text
}
if secondTextField.isFirstResponder {
    secondTextField.text = selectedCell.textLabel.text
}

The isFirstResponder method tells you if the control has the current focus and only one of them can.


问:
SQL Query (Simple)
I would like to know how could a return the number of songs registred each year based on this table:

```<code>Musics={MusicID, SingerID, Recorder, YearOfRecord}
MusicID as PK
</code>```

Thanks for the attention

答:
```<code>SELECT
    COUNT(*) AS NumberOfSongs,
    YearOfRecord
FROM
    Musics
GROUP BY
    YearOfRecord
ORDER BY
    YearOfRecord
</code>```

ContentLicense: CC BY-SA 2.5

Title: SQL Query (Simple)

Body:
I would like to know how could a return the number of songs registred each year based on this table:

Musics={MusicID, SingerID, Recorder, YearOfRecord}
MusicID as PK

Thanks for the attention


问:
execute a trigger when I create a table
I would like to know if a trigger on a system table of PostgreSQL can be executed when I create a table

I need to add 2 functions on each table of my database and I would like to do it dynamically

Thanks

答:
This can be done with an event trigger:

```<code>CREATE OR REPLACE FUNCTION on_create_table_func()
RETURNS event_trigger AS $$
BEGIN
    -- your code here
END
$$
LANGUAGE plpgsql;

CREATE EVENT TRIGGER
on_create_table ON ddl_command_end
WHEN TAG IN ('CREATE TABLE')
EXECUTE PROCEDURE on_create_table_func();
</code>```

Note that there is no way to directly execute any query on the newly created table, or even get its name.
I don't know what you mean by "add 2 functions on each table" since functions don't belong to a specific table, but if you need to perform an operation specific for the new tables, this might not be for you.

Title: execute a trigger when I create a table

Body:
This can be done with an event trigger:

CREATE OR REPLACE FUNCTION on_create_table_func()
RETURNS event_trigger AS $$
BEGIN
    -- your code here
END
$$
LANGUAGE plpgsql;

CREATE EVENT TRIGGER
on_create_table ON ddl_command_end
WHEN TAG IN ('CREATE TABLE')
EXECUTE PROCEDURE on_create_table_func();

Note that there is no way to directly execute any query on the newly created table, or even get its name.
I don't know what you mean by "add 2 functions on each table" since functions don't belong to a specific table, but if you need to perform an operation specific for the new tables, this might not be for you.

ContentLicense: CC BY-SA 4.0


问:
Open a custom url when clicking on a web push notification
I am implementing the Webpush ruby gem to send push notifications to users of my website.

Server code:

```<code>  Webpush.payload_send({
      message: notification.message,
      url: notification.url,  # I can't figure out how to access this key
      id: notification.id,    # or this key from the service worker
      endpoint: endpoint,
      p256dh: p256dh_key,
      vapid: vapid_keys,
      ttl: 24 * 60 * 60,
      auth: auth_key,
    })
</code>```

I have a service worker set up on the client side to show the notification and make it clickable.

```<code>self.addEventListener("push", function (event) {
  var title = (event.data && event.data.text()) || "New Message";

  event.waitUntil(
    self.registration.showNotification(title, {
      body: "New push notification",
      icon: "/images/logo@2x.png",
      tag:  "push-notification-tag",
      data: {
        url: event.data.url, // This is returning null
        id: event.data.id // And this is returning null
      }
    })
  )
});

self.addEventListener('notificationclick', function(event) {
  event.notification.close();
  event.waitUntil(
    clients.openWindow(event.data.url + "?notification_id=" + event.data.id)
  );
})
</code>```

It is all working fine, except the custom keys (url, id) that I am passing through are not accessible from within the service worker.

Does anyone know how to pass custom data through the WebPush gem?

答:
Custom data comes in event.notification object not in event directly(in notificationclick). So if you want to fetch the custom data variable in notificationclick function, then you should do it like this :)

```<code>self.addEventListener('notificationclick', function(event) {
  event.notification.close();
  event.waitUntil(
    clients.openWindow(event.notification.data.url + "?notification_id=" + event.notification.data.id)
  );
})
</code>```

Body:
I am implementing the Webpush ruby gem to send push notifications to users of my website.

Server code:

  Webpush.payload_send({
      message: notification.message,
      url: notification.url,  # I can't figure out how to access this key
      id: notification.id,    # or this key from the service worker
      endpoint: endpoint,
      p256dh: p256dh_key,
      vapid: vapid_keys,
      ttl: 24 * 60 * 60,
      auth: auth_key,
    })

I have a service worker set up on the client side to show the notification and make it clickable.

self.addEventListener("push", function (event) {
  var title = (event.data && event.data.text()) || "New Message";

  event.waitUntil(
    self.registration.showNotification(title, {
      body: "New push notification",
      icon: "/images/logo@2x.png",
      tag:  "push-notification-tag",
      data: {
        url: event.data.url, // This is returning null
        id: event.data.id // And this is returning null
      }
    })
  )
});

self.addEventListener('notificationclick', function(event) {
  event.notification.close();
  event.waitUntil(
    clients.openWindow(event.data.url + "?notification_id=" + event.data.id)
  );
})

It is all working fine, except the custom keys (url, id) that I am passing through are not accessible from within the service worker.

Does anyone know how to pass custom data through the WebPush gem?

Body:
Custom data comes in event.notification object not in event directly(in notificationclick). So if you want to fetch the custom data variable in notificationclick function, then you should do it like this :)

self.addEventListener('notificationclick', function(event) {
  event.notification.close();
  event.waitUntil(
    clients.openWindow(event.notification.data.url + "?notification_id=" + event.notification.data.id)
  );
})


问:
Symfony 3 - Doctrine wrong query structure - multi tables
I have a problem with Doctrine woring in my Symfony project.
That's my code:

```<code>use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Doctrine\Common\Persistence\ObjectManager;
use Factory\MainBundle\Entity\Lastauction;
use Factory\MainBundle\Entity\Offers;

class AuctionListController extends Controller
{
    private $em;
    private $qb;
    private $offer;

    public function getAuctionListAction()
    {
        $this->em = $this->getDoctrine()->getEntityManager();
        $this->qb = $this->em->createQueryBuilder();
        getAllAccount();
        for($offset=0; $offset<20000; $offset++)
        {
            $this->insertOffers();
        }
        return new Response('Offers list generated');
    }

    private function getAllAccount()
    {
        $this->qb->select('ac.mail')
            ->from('FactoryMainBundle:Account', 'ac');
        $result = $this->qb->getQuery()->getResult();
        $this->accounts = array_column($result, 'mail');
    }

    private function insertOffers()
    {
        foreach($this->offers as $id => $offer)
        {
            if($this->checkIfExsistOffer($offer))
            {
                echo $offer .'<br>';
                $offerObj = new Offers();
                $offerObj->setOffer($offer);
                $offerObj->setPage(2);
                $this->em = $this->getDoctrine()->getManager();
                $this->em->persist($offerObj);
                if (($id % $this->batchSize) == 0)
                {
                    $this->em->flush();
                    $this->em->clear();
                }
            }
        }
        $this->em->flush();
        $this->em->clear();
        $this->offers = array();
    }

    private function checkIfExsistOffer($offerUrl)
    {
        $this->qb->select('o.id')
            ->from('FactoryMainBundle:Offers', 'o')
            ->where("o.offer=:offer")
            ->setParameter('offer', $offerUrl);
        $result = $this->qb->getQuery()->getResult();
        return (isset($result['0']['id'])) ? 1 : 0;
    }

}
</code>```

And I get this error:

[Semantical Error] line 0, col 134 near 'o WHERE o.of': Error: 'o' is already defined.

[2/2] QueryException: [Semantical Error] line 0, col 134 near 'o WHERE o.of': Error: 'o' is already defined.

  [1/2] QueryException: SELECT o.id FROM FactoryMainBundle:Account ac, FactoryMainBundle:Lastauction la, FactoryMainBundle:Offers o, FactoryMainBundle:Offers o WHERE o.offer='123'

Why Doctrine takes tables from other queries?

答:
Breakdown of your codeflow regarding $this->qb:

1) In getAuctionListAction: $this->qb = $this->em->createQueryBuilder();

2) In getAllAccount:

```<code>$this->qb->select('ac.mail')
         ->from('FactoryMainBundle:Account', 'ac');
</code>```

3) In checkIfExsistOffer (through insertOffers), 20.000x due to your loop in getAuctionListAction:

```<code>$this->qb->select('o.id')
     ->from('FactoryMainBundle:Offers', 'o')
     ->where("o.offer=:offer")
     ->setParameter('offer', $offerUrl);
</code>```

Long Story short: You're adding multiple tables to your $this->qb querybuilder object (through $this->qb->from(...)), that's why they all get queried.

Body:
I have a problem with Doctrine woring in my Symfony project.
That's my code:

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Doctrine\Common\Persistence\ObjectManager;
use Factory\MainBundle\Entity\Lastauction;
use Factory\MainBundle\Entity\Offers;

class AuctionListController extends Controller
{
    private $em;
    private $qb;
    private $offer;

    public function getAuctionListAction()
    {
        $this->em = $this->getDoctrine()->getEntityManager();
        $this->qb = $this->em->createQueryBuilder();
        getAllAccount();
        for($offset=0; $offset<20000; $offset++)
        {
            $this->insertOffers();
        }
        return new Response('Offers list generated');
    }

    private function getAllAccount()
    {
        $this->qb->select('ac.mail')
            ->from('FactoryMainBundle:Account', 'ac');
        $result = $this->qb->getQuery()->getResult();
        $this->accounts = array_column($result, 'mail');
    }

    private function insertOffers()
    {
        foreach($this->offers as $id => $offer)
        {
            if($this->checkIfExsistOffer($offer))
            {
                echo $offer .'
';
                $offerObj = new Offers();
                $offerObj->setOffer($offer);
                $offerObj->setPage(2);
                $this->em = $this->getDoctrine()->getManager();
                $this->em->persist($offerObj);
                if (($id % $this->batchSize) == 0)
                {
                    $this->em->flush();
                    $this->em->clear();
                }
            }
        }
        $this->em->flush();
        $this->em->clear();
        $this->offers = array();
    }

    private function checkIfExsistOffer($offerUrl)
    {
        $this->qb->select('o.id')
            ->from('FactoryMainBundle:Offers', 'o')
            ->where("o.offer=:offer")
            ->setParameter('offer', $offerUrl);
        $result = $this->qb->getQuery()->getResult();
        return (isset($result['0']['id'])) ? 1 : 0;
    }

}

And I get this error:

[Semantical Error] line 0, col 134 near 'o WHERE o.of': Error: 'o' is already defined.

[2/2] QueryException: [Semantical Error] line 0, col 134 near 'o WHERE o.of': Error: 'o' is already defined.

  [1/2] QueryException: SELECT o.id FROM FactoryMainBundle:Account ac, FactoryMainBundle:Lastauction la, FactoryMainBundle:Offers o, FactoryMainBundle:Offers o WHERE o.offer='123'

Why Doctrine takes tables from other queries?

Body:
Breakdown of your codeflow regarding $this->qb:

1) In getAuctionListAction: $this->qb = $this->em->createQueryBuilder();

2) In getAllAccount:

$this->qb->select('ac.mail')
         ->from('FactoryMainBundle:Account', 'ac');

3) In checkIfExsistOffer (through insertOffers), 20.000x due to your loop in getAuctionListAction:

$this->qb->select('o.id')
     ->from('FactoryMainBundle:Offers', 'o')
     ->where("o.offer=:offer")
     ->setParameter('offer', $offerUrl);

Long Story short: You're adding multiple tables to your $this->qb querybuilder object (through $this->qb->from(...)), that's why they all get queried.


问:
translate typescript to javascript
I need this code is in Javascript

I am not specialized in language typescript.

this is code for play music and record audio in mobile with nativescript

do not think GitHub quickly give answer

in github issues

```<code>import { TNSPlayer } from 'nativescript-audio';

export class YourClass {
    private _player: TNSPlayer;

    constructor() {
        this._player = new TNSPlayer();
        this._player.initFromFile({
            audioFile: '~/audio/song.mp3', // ~ = app directory
            loop: false,
            completeCallback: this._trackComplete.bind(this),
            errorCallback: this._trackError.bind(this)
        }).then(() => {

            this._player.getAudioTrackDuration().then((duration) => {
                // iOS: duration is in seconds
                // Android: duration is in milliseconds
                console.log(`song duration:`, duration);
            });
        });
    }

    public togglePlay() {
        if (this._player.isAudioPlaying()) {
            this._player.pause();
        } else {
            this._player.play();
        }
    }

    private _trackComplete(args: any) {
        console.log('reference back to player:', args.player);

        // iOS only: flag indicating if completed succesfully
        console.log('whether song play completed successfully:', args.flag);
    }

    private _trackError(args: any) {
        console.log('reference back to player:', args.player);
        console.log('the error:', args.error);

        // Android only: extra detail on error
        console.log('extra info on the error:', args.extra);
    }
}
</code>```

答:
If you use Webpack or any Angular (2+) seed project, even angular-cli, all your TypeScript code will "compiled" to ECMAScript and you can choose the version (from 5 to 7).

Just open tsconfig.json. target will give a concrete version of ECMAScript you need.

```<code> "compilerOptions": {
"outDir": "./dist/out-tsc",
"baseUrl": "src",
"sourceMap": true,
"declaration": false,
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es5",
"typeRoots": [
  "node_modules/@types"
]
</code>```

Run build and get your JavaScript file from the outDir directory.

Title: translate typescript to javascript

Body:
I need this code is in Javascript

I am not specialized in language typescript.

this is code for play music and record audio in mobile with nativescript

do not think GitHub quickly give answer

in github issues

import { TNSPlayer } from 'nativescript-audio';

export class YourClass {
    private _player: TNSPlayer;

    constructor() {
        this._player = new TNSPlayer();
        this._player.initFromFile({
            audioFile: '~/audio/song.mp3', // ~ = app directory
            loop: false,
            completeCallback: this._trackComplete.bind(this),
            errorCallback: this._trackError.bind(this)
        }).then(() => {

            this._player.getAudioTrackDuration().then((duration) => {
                // iOS: duration is in seconds
                // Android: duration is in milliseconds
                console.log(`song duration:`, duration);
            });
        });
    }

    public togglePlay() {
        if (this._player.isAudioPlaying()) {
            this._player.pause();
        } else {
            this._player.play();
        }
    }

    private _trackComplete(args: any) {
        console.log('reference back to player:', args.player);

        // iOS only: flag indicating if completed succesfully
        console.log('whether song play completed successfully:', args.flag);
    }

    private _trackError(args: any) {
        console.log('reference back to player:', args.player);
        console.log('the error:', args.error);

        // Android only: extra detail on error
        console.log('extra info on the error:', args.extra);
    }
}

Body:
If you use Webpack or any Angular (2+) seed project, even angular-cli, all your TypeScript code will "compiled" to ECMAScript and you can choose the version (from 5 to 7).

Just open tsconfig.json. target will give a concrete version of ECMAScript you need.

 "compilerOptions": {
"outDir": "./dist/out-tsc",
"baseUrl": "src",
"sourceMap": true,
"declaration": false,
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es5",
"typeRoots": [
  "node_modules/@types"
]

Run build and get your JavaScript file from the outDir directory.


问:
Bootstrap Carousel Jumps to top of page when advancing
When I advance the slider manually, the slider jumps to the top of the page. How can I prevent this from happening? Help much appreciated! Here's the code:</p>

```<code><div class="row">
    <div class="span12">
        <script>
            $('.carousel').carousel({
            interval: 4000
            })
        </script>
        <div class="container">
            <div id="myCarousel" class="carousel slide frame">
                <!-- Carousel items -->
                <div class="carousel-inner">
                    <div class="active item"><a href="work.html"><img src="assets/images/slide_psd.jpg" width="1170"  alt="wga"></a></div>
                    <div class="item"><a href="work.html"><img src="assets/images/slide_wga.jpg" width="1170"  alt="wga"></a></div>
                    <div class="item"><a href="work.html"><img src="assets/images/slide_ts.jpg" width="1170"  alt="top secret hair"></a></div>
                    <div class="item"><a href="work.html"><img src="assets/images/slide_baja.jpg" width="1170"  alt="baja"></a></div>
                </div>
                <!-- Carousel nav -->
                <a class="carousel-control left" href="#myCarousel" data-slide="prev">‹</a>
        <a class="carousel-control right" href="#myCarousel" data-slide="next">›</a>
            </div>
        </div>
        <!-- end cara container-->
    </div>
    <!-- end span-->
</div>
<!-- end row-->
</code>```

答:
This one worked well for me. Replace href with "data-target"
class="carousel-control right" data-slide="next" data-target="#carousel">

Body:
When I advance the slider manually, the slider jumps to the top of the page. How can I prevent this from happening? Help much appreciated! Here's the code:

                ‹
        ›

Body:
This one worked well for me. Replace href with "data-target"
<a class="carousel-control right" data-slide="next" data-target="#carousel">


问:
Set Visibility not working on Image View
Why is my imageView not becoming visible with the checkingBalance = $1200 or more?

I have it set to invisible in the XML file. I essentially want the ivArrow ImageView to only appear visible IF my checkingBalance is over $1199.99.

```<code>public class MainActivity extends AppCompatActivity {

    ImageView ivArrow;
    TextView tvCheckingBalance;
    TextView tvInvestmentsBalance;
    TextView tvPayRate;
    TextView tvToday;
    TextView tvWorkBalance;
    Button btnWork;

    boolean runInitialize = true;
    float checkingBalance;
    float investmentsBalance;
    float payRate;
    float workBalance;
    int today;
    int weekDay;
    int workPercent;

    DecimalFormat dollarFormat = new DecimalFormat("#,###.00");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SharedPreferences settings = getSharedPreferences("com.vuvaia.lifeofme", MODE_PRIVATE);
        runInitialize = settings.getBoolean("runInitialize", runInitialize);

        if (runInitialize) {
            initialize();
            loadSettings();
        } else {
            loadSettings();
        }

        // INITIALIZING VIEW SETUP
        ivArrow = (ImageView) findViewById(R.id.ivArrow);
        tvCheckingBalance = (TextView) findViewById(R.id.tvCheckingBalance);
        tvCheckingBalance.setText("$" + dollarFormat.format(checkingBalance));
        tvInvestmentsBalance = (TextView) findViewById(R.id.tvInvestmentBalance);
        tvInvestmentsBalance.setText("$" + dollarFormat.format(investmentsBalance));
        tvPayRate = (TextView) findViewById(R.id.tvPayRate);
        tvPayRate.setText("$" + dollarFormat.format(payRate) + "/hr");
        tvToday = (TextView) findViewById(R.id.tvToday);
        tvToday.setText(String.valueOf(today));
        tvWorkBalance = (TextView) findViewById(R.id.tvWorkBalance);
        tvWorkBalance.setText("$" + dollarFormat.format(workBalance));

        btnWork = (Button) findViewById(R.id.btnWork);

        btnWork.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                workButtonPressed();
            }
        });

        // TODO SET UP THIS ARROW THAT TRANSFERS MONEY TO INVESTMENTS
        if(checkingBalance > 1199.99f) {
            ivArrow.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadSettings();
    }

    @Override
    protected void onPause() {
        super.onPause();
        saveSettings();
    }

    // WORK BUTTON PRESSED ACTIONS **************************************************
    public void workButtonPressed(){
        if(workPercent < 100){
            workBalance += (payRate * .4);
            tvWorkBalance.setText("$" + dollarFormat.format(workBalance));
            workPercent ++;
            advanceDays();
        } else {
            checkingBalance = checkingBalance + workBalance;
            tvCheckingBalance.setText("$" + dollarFormat.format(checkingBalance));
            workPercent = 0;
            workBalance = 0.0f;
            tvWorkBalance.setText("$" + dollarFormat.format(workBalance));
            today += 2;
            weekDay = 0;
            tvToday.setText(String.valueOf(today));
        }
    }
    // WORK BUTTON PRESSED ACTIONS **************************************************

    // ADVANCING THE CALENDAR DAYS **************************************************
    public void advanceDays(){
        if(weekDay <= 17){
            weekDay ++;
        } else {
            weekDay = 0;
            today ++;
            tvToday.setText(String.valueOf(today));
        }
    }
    // ADVANCING THE CALENDAR DAYS **************************************************

    // LOADING AND SAVING **************************************************
    public void initialize(){
        checkingBalance = 0.00f;
        investmentsBalance = 0.00f;
        payRate = 7.57f;
        today = 0;
        weekDay = 0;
        workBalance = 0.00f;
        workPercent = 0;

        saveSettings();
    }
    public void saveSettings(){
        SharedPreferences settings = getSharedPreferences("com.vuvaia.lifeofme", MODE_PRIVATE);
        settings.edit().putFloat("checkingBalance", checkingBalance).commit();
        settings.edit().putFloat("investmentsBalance", investmentsBalance).commit();
        settings.edit().putFloat("payRate", payRate).commit();
        settings.edit().putBoolean("runInitialize", false).commit();
        settings.edit().putInt("today", today).commit();
        settings.edit().putInt("weekDay", weekDay).commit();
        settings.edit().putFloat("workBalance", workBalance).commit();
        settings.edit().putInt("workPercent", workPercent).commit();
    }
    public void loadSettings(){
        SharedPreferences settings = getSharedPreferences("com.vuvaia.lifeofme", MODE_PRIVATE);
        checkingBalance = settings.getFloat("checkingBalance", checkingBalance);
        investmentsBalance = settings.getFloat("investmentsBalance", investmentsBalance);
        payRate = settings.getFloat("payRate", payRate);
        runInitialize = settings.getBoolean("runInitialize", runInitialize);
        today = settings.getInt("today", today);
        weekDay = settings.getInt("weekDay", weekDay);
        workBalance = settings.getFloat("workBalance", workBalance);
        workPercent = settings.getInt("workPercent", workPercent);
    }
    // LOADING AND SAVING **************************************************
}
</code>```

XML File:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#EEEEEE"
    tools:context="com.vuvaia.lifeofme.MainActivity">

    <Button
        android:id="@+id/btnWork"
        android:layout_width="0dp"
        android:layout_height="75dp"
        android:background="#2A2A2A"
        android:text="Work"
        android:textColor="#EEEEEE"
        android:textSize="30sp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="32dp" />

    <TextView
        android:id="@+id/tvWorkBalance"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:background="#2A2A2A"
        android:textColor="#EEEEEE"
        android:textSize="30sp"
        android:textAlignment="center"
        android:layout_marginBottom="8dp"
        android:paddingBottom="15dp"
        android:paddingTop="15dp"
        app:layout_constraintBottom_toTopOf="@+id/btnWork"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent" />

    <TextView
        android:id="@+id/tvPayRate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#2A2A2A"
        android:layout_marginTop="16dp"
        app:layout_constraintTop_toBottomOf="@+id/tvWorkBalance"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent" />

    <TextView
        android:id="@+id/tvCheckingBalance"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#2A2A2A"
        android:textSize="15sp"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="32dp" />

    <TextView
        android:id="@+id/tvToday"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#2A2A2A"
        android:textSize="15sp"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="32dp"
        android:layout_marginLeft="32dp"
        app:layout_constraintLeft_toLeftOf="parent" />

    <TextView
        android:id="@+id/tvInvestmentBalance"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#2A2A2A"
        android:textSize="15sp"
        android:layout_marginRight="32dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="32dp" />

    <ImageView
        android:id="@+id/ivArrow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="invisible"
        app:srcCompat="@drawable/ic_arrow"
        android:layout_marginTop="8dp"
        app:layout_constraintTop_toBottomOf="@+id/tvCheckingBalance"
        app:layout_constraintLeft_toRightOf="@+id/tvCheckingBalance"
        android:layout_marginLeft="8dp" />
</android.support.constraint.ConstraintLayout>
</code>```

答:
I strongly guess your checkingBalance having problem. Didn't return your expected value .

```<code>    float f1 = 1200;
    float f2 = 1199.99f;
    int compare = Float.compare(f1,f2);

    if(compare > 0){
        System.out.println("First is grater");
    }else if(compare < 0){
        System.out.println("Second is grater");
    }else{
        System.out.println("Both are equal");
    }
</code>```

Body:
Why is my imageView not becoming visible with the checkingBalance = $1200 or more?

I have it set to invisible in the XML file. I essentially want the ivArrow ImageView to only appear visible IF my checkingBalance is over $1199.99.

public class MainActivity extends AppCompatActivity {

    ImageView ivArrow;
    TextView tvCheckingBalance;
    TextView tvInvestmentsBalance;
    TextView tvPayRate;
    TextView tvToday;
    TextView tvWorkBalance;
    Button btnWork;

    boolean runInitialize = true;
    float checkingBalance;
    float investmentsBalance;
    float payRate;
    float workBalance;
    int today;
    int weekDay;
    int workPercent;

    DecimalFormat dollarFormat = new DecimalFormat("#,###.00");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SharedPreferences settings = getSharedPreferences("com.vuvaia.lifeofme", MODE_PRIVATE);
        runInitialize = settings.getBoolean("runInitialize", runInitialize);

        if (runInitialize) {
            initialize();
            loadSettings();
        } else {
            loadSettings();
        }

        // INITIALIZING VIEW SETUP
        ivArrow = (ImageView) findViewById(R.id.ivArrow);
        tvCheckingBalance = (TextView) findViewById(R.id.tvCheckingBalance);
        tvCheckingBalance.setText("$" + dollarFormat.format(checkingBalance));
        tvInvestmentsBalance = (TextView) findViewById(R.id.tvInvestmentBalance);
        tvInvestmentsBalance.setText("$" + dollarFormat.format(investmentsBalance));
        tvPayRate = (TextView) findViewById(R.id.tvPayRate);
        tvPayRate.setText("$" + dollarFormat.format(payRate) + "/hr");
        tvToday = (TextView) findViewById(R.id.tvToday);
        tvToday.setText(String.valueOf(today));
        tvWorkBalance = (TextView) findViewById(R.id.tvWorkBalance);
        tvWorkBalance.setText("$" + dollarFormat.format(workBalance));

        btnWork = (Button) findViewById(R.id.btnWork);

        btnWork.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                workButtonPressed();
            }
        });

        // TODO SET UP THIS ARROW THAT TRANSFERS MONEY TO INVESTMENTS
        if(checkingBalance > 1199.99f) {
            ivArrow.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadSettings();
    }

    @Override
    protected void onPause() {
        super.onPause();
        saveSettings();
    }

    // WORK BUTTON PRESSED ACTIONS **************************************************
    public void workButtonPressed(){
        if(workPercent < 100){
            workBalance += (payRate * .4);
            tvWorkBalance.setText("$" + dollarFormat.format(workBalance));
            workPercent ++;
            advanceDays();
        } else {
            checkingBalance = checkingBalance + workBalance;
            tvCheckingBalance.setText("$" + dollarFormat.format(checkingBalance));
            workPercent = 0;
            workBalance = 0.0f;
            tvWorkBalance.setText("$" + dollarFormat.format(workBalance));
            today += 2;
            weekDay = 0;
            tvToday.setText(String.valueOf(today));
        }
    }
    // WORK BUTTON PRESSED ACTIONS **************************************************

    // ADVANCING THE CALENDAR DAYS **************************************************
    public void advanceDays(){
        if(weekDay <= 17){
            weekDay ++;
        } else {
            weekDay = 0;
            today ++;
            tvToday.setText(String.valueOf(today));
        }
    }
    // ADVANCING THE CALENDAR DAYS **************************************************

    // LOADING AND SAVING **************************************************
    public void initialize(){
        checkingBalance = 0.00f;
        investmentsBalance = 0.00f;
        payRate = 7.57f;
        today = 0;
        weekDay = 0;
        workBalance = 0.00f;
        workPercent = 0;

        saveSettings();
    }
    public void saveSettings(){
        SharedPreferences settings = getSharedPreferences("com.vuvaia.lifeofme", MODE_PRIVATE);
        settings.edit().putFloat("checkingBalance", checkingBalance).commit();
        settings.edit().putFloat("investmentsBalance", investmentsBalance).commit();
        settings.edit().putFloat("payRate", payRate).commit();
        settings.edit().putBoolean("runInitialize", false).commit();
        settings.edit().putInt("today", today).commit();
        settings.edit().putInt("weekDay", weekDay).commit();
        settings.edit().putFloat("workBalance", workBalance).commit();
        settings.edit().putInt("workPercent", workPercent).commit();
    }
    public void loadSettings(){
        SharedPreferences settings = getSharedPreferences("com.vuvaia.lifeofme", MODE_PRIVATE);
        checkingBalance = settings.getFloat("checkingBalance", checkingBalance);
        investmentsBalance = settings.getFloat("investmentsBalance", investmentsBalance);
        payRate = settings.getFloat("payRate", payRate);
        runInitialize = settings.getBoolean("runInitialize", runInitialize);
        today = settings.getInt("today", today);
        weekDay = settings.getInt("weekDay", weekDay);
        workBalance = settings.getFloat("workBalance", workBalance);
        workPercent = settings.getInt("workPercent", workPercent);
    }
    // LOADING AND SAVING **************************************************
}

XML File:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#EEEEEE"
    tools:context="com.vuvaia.lifeofme.MainActivity">

    <Button
        android:id="@+id/btnWork"
        android:layout_width="0dp"
        android:layout_height="75dp"
        android:background="#2A2A2A"
        android:text="Work"
        android:textColor="#EEEEEE"
        android:textSize="30sp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="32dp" />

    <TextView
        android:id="@+id/tvWorkBalance"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:background="#2A2A2A"
        android:textColor="#EEEEEE"
        android:textSize="30sp"
        android:textAlignment="center"
        android:layout_marginBottom="8dp"
        android:paddingBottom="15dp"
        android:paddingTop="15dp"
        app:layout_constraintBottom_toTopOf="@+id/btnWork"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent" />

    <TextView
        android:id="@+id/tvPayRate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#2A2A2A"
        android:layout_marginTop="16dp"
        app:layout_constraintTop_toBottomOf="@+id/tvWorkBalance"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent" />

    <TextView
        android:id="@+id/tvCheckingBalance"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#2A2A2A"
        android:textSize="15sp"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="32dp" />

    <TextView
        android:id="@+id/tvToday"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#2A2A2A"
        android:textSize="15sp"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="32dp"
        android:layout_marginLeft="32dp"
        app:layout_constraintLeft_toLeftOf="parent" />

    <TextView
        android:id="@+id/tvInvestmentBalance"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#2A2A2A"
        android:textSize="15sp"
        android:layout_marginRight="32dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="32dp" />

    <ImageView
        android:id="@+id/ivArrow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="invisible"
        app:srcCompat="@drawable/ic_arrow"
        android:layout_marginTop="8dp"
        app:layout_constraintTop_toBottomOf="@+id/tvCheckingBalance"
        app:layout_constraintLeft_toRightOf="@+id/tvCheckingBalance"
        android:layout_marginLeft="8dp" />
</android.support.constraint.ConstraintLayout>

Body:
I strongly guess your checkingBalance having problem. Didn't return your expected value .

    float f1 = 1200;
    float f2 = 1199.99f;
    int compare = Float.compare(f1,f2);

    if(compare > 0){
        System.out.println("First is grater");
    }else if(compare < 0){
        System.out.println("Second is grater");
    }else{
        System.out.println("Both are equal");
    }


问:
MySQL bidirectional trigger
I have to do two triggers, first one, after insert in test1 table, to insert in test2 table another row. All right, the problem is that i have to do same trigger in reverse form, after insert row in test2 table, insert new row on test1. I know that trigger can't insert in a table when a trigger is firing, but i need resolve this. I don't have a lot experience with triggers, i hope that this could be resolved.

```<code>DELIMITER $$ CREATE TRIGGER `ai_test1_test2` AFTER INSERT ON `test1`
FOR EACH ROW
BEGIN INSERT INTO test2 (vtest2) VALUES (new.vtest1)
END$$
DELIMITER ;
</code>```

Bidirectional trigger:

```<code>DELIMITER $$ CREATE TRIGGER `ai_test2_test1` AFTER INSERT ON `test2`
FOR EACH ROW
BEGIN INSERT INTO test1 (vtest1) VALUES (new.vtest2)
END$$
DELIMITER ;
</code>```

Thanks.

Edit:

The infinite loop can't be resolved. Triggers can't be bidirectional... I think that i must be use a PROCEDURE...

答:
There is a posible solution for the problem:</p>

```<code>DELIMITER $$ CREATE TRIGGER `ai_test1_test2` AFTER INSERT ON `test1`
FOR EACH ROW
BEGIN
  IF NOT EXISTS( SELECT vtest2 FROM test2 WHERE vtest2 = new.vtest1 ) THEN
    INSERT INTO test2 (vtest2) VALUES (new.vtest1)
  END IF;
END$$
DELIMITER ;

DELIMITER $$ CREATE TRIGGER `ai_test2_test1` AFTER INSERT ON `test1`
FOR EACH ROW
BEGIN
  IF NOT EXISTS( SELECT vtest1 FROM test1 WHERE vtest1 = new.vtest2 ) THEN
    INSERT INTO test1 (vtest1) VALUES (new.vtest2)
  END IF;
END$$
DELIMITER ;
</code>```

Title: MySQL bidirectional trigger

Body:
I have to do two triggers, first one, after insert in test1 table, to insert in test2 table another row. All right, the problem is that i have to do same trigger in reverse form, after insert row in test2 table, insert new row on test1. I know that trigger can't insert in a table when a trigger is firing, but i need resolve this. I don't have a lot experience with triggers, i hope that this could be resolved.

DELIMITER $$ CREATE TRIGGER `ai_test1_test2` AFTER INSERT ON `test1`
FOR EACH ROW
BEGIN INSERT INTO test2 (vtest2) VALUES (new.vtest1)
END$$
DELIMITER ;

Bidirectional trigger:

DELIMITER $$ CREATE TRIGGER `ai_test2_test1` AFTER INSERT ON `test2`
FOR EACH ROW
BEGIN INSERT INTO test1 (vtest1) VALUES (new.vtest2)
END$$
DELIMITER ;

Thanks.

Edit:

The infinite loop can't be resolved. Triggers can't be bidirectional... I think that i must be use a PROCEDURE...

Body:
There is a posible solution for the problem:

DELIMITER $$ CREATE TRIGGER `ai_test1_test2` AFTER INSERT ON `test1`
FOR EACH ROW
BEGIN
  IF NOT EXISTS( SELECT vtest2 FROM test2 WHERE vtest2 = new.vtest1 ) THEN
    INSERT INTO test2 (vtest2) VALUES (new.vtest1)
  END IF;
END$$
DELIMITER ;

DELIMITER $$ CREATE TRIGGER `ai_test2_test1` AFTER INSERT ON `test1`
FOR EACH ROW
BEGIN
  IF NOT EXISTS( SELECT vtest1 FROM test1 WHERE vtest1 = new.vtest2 ) THEN
    INSERT INTO test1 (vtest1) VALUES (new.vtest2)
  END IF;
END$$
DELIMITER ;


问:
My increment doesn't work (c)
So, I have this code, at end I have an increment for exit when it reaches 4 (4 times wrong value entered), but it doesn't work:

```<code>int main() {
  int nej;
  printf("1-Triangulo \n");
  printf("2-Division \n");
  printf("3-Menu \n");
  printf("4-Bosque \n");
  printf("0-Salir \n");
  scanf("%d", &nej);
  if (nej == 1) {
    // Ejercicio 1-Triangulo:

    triangulo();
  }

  if (nej == 2) {
    // Ejercicio 2-Division:

    division();
  }

  if (nej == 3) {
    menu();
  }

  if (nej == 4) {
    arboles();
  }

  if (nej == 0) {
    // Salida
    exit(1);
  }

  int nerr = 0;

  while (nej < 0 || nej > 4) {
    nerr++;
    // Contador de error
    if (nerr == 4) {
      exit(1);
    }
  }
}
</code>```

How to fix this?

答:
nej being the input, and the input being invalid if less than 0 or larger than 4, the correct statement would be:

```<code>if (nej < 0 || nej > 4) {
</code>```

(and not while as nej is not changed in the code block).

Title: My increment doesn't work (c)

Body:
So, I have this code, at end I have an increment for exit when it reaches 4 (4 times wrong value entered), but it doesn't work:

int main() {
  int nej;
  printf("1-Triangulo \n");
  printf("2-Division \n");
  printf("3-Menu \n");
  printf("4-Bosque \n");
  printf("0-Salir \n");
  scanf("%d", &nej);
  if (nej == 1) {
    // Ejercicio 1-Triangulo:

    triangulo();
  }

  if (nej == 2) {
    // Ejercicio 2-Division:

    division();
  }

  if (nej == 3) {
    menu();
  }

  if (nej == 4) {
    arboles();
  }

  if (nej == 0) {
    // Salida
    exit(1);
  }

  int nerr = 0;

  while (nej < 0 || nej > 4) {
    nerr++;
    // Contador de error
    if (nerr == 4) {
      exit(1);
    }
  }
}

How to fix this?

Body:
nej being the input, and the input being invalid if less than 0 or larger than 4, the correct statement would be:

if (nej < 0 || nej > 4) {

(and not while as nej is not changed in the code block).


答:
```<code>private function checkIfExsistOffer($offerUrl)
{
        $res = $this->getDoctrine()->getRepository('FactoryMainBundle:Offers')
            ->createQueryBuilder('o')
            ->select('o.id')
            ->where("o.id=:offer")
            ->setParameter('offer', 1)
            ->getQuery()
            ->getSingleResult(); //return single result

        var_dump($res);die; //test
}
</code>```

Title: Symfony 3 - Doctrine wrong query structure - multi tables


问:
Fabric.js - Moving image loaded from url receiving error: Cannot read property 'length' of undefined
I'm new to fabric.js, and I try to add it to a React application. I created the canvas on window so it would be global and available from all components:

window.fabricCanvas = new Fabric.fabric.Canvas();

When clicking an 'Add Image' button the following function is called:

```<code>addImage() {
Fabric.fabric.Image.fromURL(this.state.imageUrl, function(img) {
  let oImg = img.set({left: 50, top: 100, angle: -15}).scale(0.5);
  window.fabricCanvas.add(oImg).renderAll();
  window.fabricCanvas.setActiveObject(oImg);
})};
</code>```

The image is indeed loaded, but if I try moving\scaling the image it disappears, and I get this error in console:

```<code>Cannot read property 'length' of undefined at klass._render (fabric.js:18795)
</code>```

which refers to this line in their code:

if (this.isMoving === false && this.resizeFilters.length && this._needsResize()) {

Any ideas what's wrong with my code?

答: I'm having the same problem with 2.0.0-beta2, but it's working fine with the stable 1.7.11 so try switching to that.</p>

Body:
I'm new to fabric.js, and I try to add it to a React application. I created the canvas on window so it would be global and available from all components:

window.fabricCanvas = new Fabric.fabric.Canvas();

When clicking an 'Add Image' button the following function is called:

addImage() {
Fabric.fabric.Image.fromURL(this.state.imageUrl, function(img) {
  let oImg = img.set({left: 50, top: 100, angle: -15}).scale(0.5);
  window.fabricCanvas.add(oImg).renderAll();
  window.fabricCanvas.setActiveObject(oImg);
})};

The image is indeed loaded, but if I try moving\scaling the image it disappears, and I get this error in console:

Cannot read property 'length' of undefined at klass._render (fabric.js:18795)

which refers to this line in their code:

if (this.isMoving === false && this.resizeFilters.length && this._needsResize()) {

Any ideas what's wrong with my code?


答:
You can use the TypeScript Compiler (tsc) to do that. For your snippet the output is this:</p>

```<code>"use strict";
exports.__esModule = true;
var nativescript_audio_1 = require("nativescript-audio");
var YourClass = (function () {
    function YourClass() {
        var _this = this;
        this._player = new nativescript_audio_1.TNSPlayer();
        this._player.initFromFile({
            audioFile: '~/audio/song.mp3',
            loop: false,
            completeCallback: this._trackComplete.bind(this),
            errorCallback: this._trackError.bind(this)
        }).then(function () {
            _this._player.getAudioTrackDuration().then(function (duration) {
                // iOS: duration is in seconds
                // Android: duration is in milliseconds
                console.log("song duration:", duration);
            });
        });
    }
    YourClass.prototype.togglePlay = function () {
        if (this._player.isAudioPlaying()) {
            this._player.pause();
        }
        else {
            this._player.play();
        }
    };
    YourClass.prototype._trackComplete = function (args) {
        console.log('reference back to player:', args.player);
        // iOS only: flag indicating if completed succesfully
        console.log('whether song play completed successfully:', args.flag);
    };
    YourClass.prototype._trackError = function (args) {
        console.log('reference back to player:', args.player);
        console.log('the error:', args.error);
        // Android only: extra detail on error
        console.log('extra info on the error:', args.extra);
    };
    return YourClass;
}());
exports.YourClass = YourClass;
</code>```

Title: translate typescript to javascript

Body:
You can use the TypeScript Compiler (tsc) to do that. For your snippet the output is this:

"use strict";
exports.__esModule = true;
var nativescript_audio_1 = require("nativescript-audio");
var YourClass = (function () {
    function YourClass() {
        var _this = this;
        this._player = new nativescript_audio_1.TNSPlayer();
        this._player.initFromFile({
            audioFile: '~/audio/song.mp3',
            loop: false,
            completeCallback: this._trackComplete.bind(this),
            errorCallback: this._trackError.bind(this)
        }).then(function () {
            _this._player.getAudioTrackDuration().then(function (duration) {
                // iOS: duration is in seconds
                // Android: duration is in milliseconds
                console.log("song duration:", duration);
            });
        });
    }
    YourClass.prototype.togglePlay = function () {
        if (this._player.isAudioPlaying()) {
            this._player.pause();
        }
        else {
            this._player.play();
        }
    };
    YourClass.prototype._trackComplete = function (args) {
        console.log('reference back to player:', args.player);
        // iOS only: flag indicating if completed succesfully
        console.log('whether song play completed successfully:', args.flag);
    };
    YourClass.prototype._trackError = function (args) {
        console.log('reference back to player:', args.player);
        console.log('the error:', args.error);
        // Android only: extra detail on error
        console.log('extra info on the error:', args.extra);
    };
    return YourClass;
}());
exports.YourClass = YourClass;


问:
How to add shadow in dropdown spinner in Android
I am using a Spinner drop down in my Form. But when I drop down my spinner, the color of it is matching to background color. How can I add shadow to my dropdown spinner in Android </p>

答:
Try using this:

```<code><android.support.v7.widget.AppCompatSpinner
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
</android.support.v7.widget.AppCompatSpinner>
</code>```

Hope this helps.

Body:
Try using this:

<android.support.v7.widget.AppCompatSpinner
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
</android.support.v7.widget.AppCompatSpinner>

Hope this helps.


问:
session attribute removal from jsp
Is it possible to call taglib to remove the attribute on certain object events like onClick() etc because right now these are getting called when the page is getting loaded,I don't want this to happen as the user has to be able to see a report which will require a attribute as well the page where page where is navigates to before the report is beeen presented is the one where this attribute needs to be removed.

Thanks in advance

答: You can issue an ajax-request onclick, and then, in a servlet, you can call session.remove().

Title: session attribute removal from jsp


问:
Getting error in production environment, running fine in localhost
I have total 6 multiple select lists when i select any one or multiple option from these lists i will show them after form submission, initially they hidden.
Below is my script this is works fine in localhost but i am getting syntax error in production
PHP Parse error: syntax error, unexpected 'isset'(T_ISSET). Please someone help me, Thanks in advance</p>

```<code>    <script>
    <?php if(isset($_POST['LS_name']) && !empty(isset($_POST['LS_name']))) { ?>
            $('.mystaff_opt1').collapse('show');
    <?php } ?>
    <?php if(isset($_POST['FamilyIncome']) && !empty(isset($_POST['FamilyIncome']))){ ?>
        $('.mystaff_opt2').collapse('show');
    <?php } ?>
    <?php if(isset($_POST['Religion']) && !empty(isset($_POST['Religion']))){ ?>
        $('.mystaff_opt3').collapse('show');
    <?php } ?>
    <?php if(isset($_POST['Category']) && !empty(isset($_POST['Category']))){ ?>
        $('.mystaff_opt4').collapse('show');
    <?php } ?>
    <?php if(isset($_POST['Gender']) && !empty(isset($_POST['Gender']))){ ?>
        $('.mystaff_opt5').collapse('show');
    <?php } ?>
    <?php if(isset($_POST['State']) && !empty(isset($_POST['Gender']))){ ?>
        $('.mystaff_opt6').collapse('show');
    <?php } ?>
    </script>
</code>```

答:
I'm not sure your code is quite right:

```<code><?php if(isset($_POST['LS_name']) && !empty(isset($_POST['LS_name']))) { ?>
</code>```

This is testing if the variable is set (which it is if you get to the second condition) and then tests !empty(true)

Perhaps that should be:

```<code>if (isset($_POST['LS_name']) && !empty($_POST['LS_name'])) {
</code>```

Lastly - which line is the error reporting.  Check carefully the bracketing and quotes being used on that line.

Body:
I'm not sure your code is quite right:

<?php if(isset($_POST['LS_name']) && !empty(isset($_POST['LS_name']))) { ?>

This is testing if the variable is set (which it is if you get to the second condition) and then tests !empty(true)

Perhaps that should be:

if (isset($_POST['LS_name']) && !empty($_POST['LS_name'])) {

Lastly - which line is the error reporting.  Check carefully the bracketing and quotes being used on that line.


问:
Zero initialising class member which is a struct in C++11
I've tried reading the C++ docs, but I find it so hard to follow. I like to zero initialise my structs like this:

```<code>MyStruct myStruct = {};
</code>```

But if I have this struct as a class member, how do I zero initialise in the constructor?

```<code>struct MyStruct
{
 int x;
 int y;
}

class MyClass
{
 MyStruct mMyStruct;
public:
 MyClass();
}

// is this fine?
MyClass::MyClass()
 : mMyStruct()
{}

// or this?
MyClass::MyClass()
 : mMyStruct({})
{}

// or do I need this?
MyClass::MyClass()
 : mMyStruct()
{
 mMyStruct = {};
}
</code>```

答:
You can use the notation

```<code>MyClass::MyClass()
 : mMyStruct{}
{
}
</code>```

See http://en.cppreference.com/w/cpp/language/initializer_list

That documentation ain't so bad you know.

Body:
I've tried reading the C++ docs, but I find it so hard to follow. I like to zero initialise my structs like this:

MyStruct myStruct = {};

But if I have this struct as a class member, how do I zero initialise in the constructor?

struct MyStruct
{
 int x;
 int y;
}

class MyClass
{
 MyStruct mMyStruct;
public:
 MyClass();
}

// is this fine?
MyClass::MyClass()
 : mMyStruct()
{}

// or this?
MyClass::MyClass()
 : mMyStruct({})
{}

// or do I need this?
MyClass::MyClass()
 : mMyStruct()
{
 mMyStruct = {};
}

Body:
You can use the notation

MyClass::MyClass()
 : mMyStruct{}
{
}

See http://en.cppreference.com/w/cpp/language/initializer_list

That documentation ain't so bad you know.


问:
How to get page load time for a single page application(SPA) using backbone,jquery, require js?
I am building a mobile application using backbone, jquery and require js. I am trying to get the time difference between page init and onShow and but it is not giving proper load time as I am doing lazy loading using require js, and the number of lazy loading in each onShow is dynamic. Can anyone help to figure out a way to calculate how much time the page took to load upon all the elements getting loaded in the DOM including the lazy loading and any other event binding if I am doing in setTimeout, for example.
Thanks in advance.</p>

答: You can try using console.time('Timer1') at the start, then when the code you want to time is finished executing call console.timeEnd('Timer1') and that will console-out the timer value as accurate as it can be.


答:
```<code>select count(*), YearOfRecord
from Musics
group by YearOfRecord
</code>```

Title: SQL Query (Simple)

Body:
I would like to know how could a return the number of songs registred each year based on this table:

Musics={MusicID, SingerID, Recorder, YearOfRecord}
MusicID as PK

Thanks for the attention


问:
Why my test is throwing Exception-Unable to locate element in webdriver?
```<code>package testproject;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
  public class mytestclass {
    public static void main(String[] args) {
       WebDriver Driver = new FirefoxDriver();
        Driver.get("https://www.gmail.com/");
         WebElement wb= Driver.findElement(By.name("Email"));
         wb.sendKeys("sweta");
         WebElement wb1= Driver.findElement(By.name("Passwd"));
         wb1.sendKeys("123456");
         WebElement wb2= Driver.findElement(By.id("signIn"));
         wb2.click();
         WebElement wb3= Driver.findElement(By.xpath(".//*[@id='gb']/div[1]/div[1]/div[2]/div[5]/div[1]/a"));
         wb3.click();
         WebElement wb4= Driver.findElement(By.id("gb_71"));
         wb4.click();
   }
}
</code>```

When i am executing this code everything is going fine till the point where i want the sign in button to be clicked. I am getting exception which says that
Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":".//*[@id='gb']/div[1]/div[1]/div[2]/div[5]/div[1]/a"} but when i am trying to locate it using fierbug its working fine.
In the above mentioned code i changed the email id and password to keep the email safe.

I was facing problem with one more program which i already posted on stakwave so if u can then please have a look at this link-webdriver is not able to click on a hyperlink in firefox

答:
```<code>//launch browser
FirefoxDriver driver = new FirefoxDriver(options);
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
//gmail login :
driver.get("http://www.gmail.com");
driver.findElement(By.id("identifierId")).sendKeys("****",Keys.ENTER);
Thread.sleep(5000);
driver.findElement(By.id("password")).sendKeys("***",Keys.ENTER);
//logout:
driver.findElement(By.xpath("//div[@id='gb']/div[1]/div[1]/div[2]/div[4]/div[1]/a/span")).click();
Thread.sleep(5000);
driver.findElement(By.linkText("Sign out")).click();
</code>```

Body:
package testproject;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
  public class mytestclass {
    public static void main(String[] args) {
       WebDriver Driver = new FirefoxDriver();
        Driver.get("https://www.gmail.com/");
         WebElement wb= Driver.findElement(By.name("Email"));
         wb.sendKeys("sweta");
         WebElement wb1= Driver.findElement(By.name("Passwd"));
         wb1.sendKeys("123456");
         WebElement wb2= Driver.findElement(By.id("signIn"));
         wb2.click();
         WebElement wb3= Driver.findElement(By.xpath(".//*[@id='gb']/div[1]/div[1]/div[2]/div[5]/div[1]/a"));
         wb3.click();
         WebElement wb4= Driver.findElement(By.id("gb_71"));
         wb4.click();
   }
}

When i am executing this code everything is going fine till the point where i want the sign in button to be clicked. I am getting exception which says that
Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":".//*[@id='gb']/div[1]/div[1]/div[2]/div[5]/div[1]/a"} but when i am trying to locate it using fierbug its working fine.
In the above mentioned code i changed the email id and password to keep the email safe.

I was facing problem with one more program which i already posted on stakwave so if u can then please have a look at this link-webdriver is not able to click on a hyperlink in firefox


问:
How to keep the aspect ratio of image window in opencv?
From documantation, it says that we can keep the image ratio by CV_WINDOW_KEEPRATIO but the windows still lost aspect ratio after I adjust it. Would anyone kindly help?

Example code:

```<code>import cv2

# load the image, clone it, and setup the mouse callback function
image = cv2.imread('1.jpg')
cv2.namedWindow('image', cv2.WINDOW_KEEPRATIO)
# keep looping until the 'q' key is pressed
while True:
    # display the image and wait for a keypress
    cv2.imshow('image', image)
    key = cv2.waitKey()

    if key == 27:
        break

# close all open windows
cv2.destroyAllWindows()
</code>```

答: It could be an issue of display itself.Say your display window is by default large. In the above snippet I don't see any changes made to aspect ratio.  Check here</p>

Body:
From documantation, it says that we can keep the image ratio by CV_WINDOW_KEEPRATIO but the windows still lost aspect ratio after I adjust it. Would anyone kindly help?

Example code:

import cv2

# load the image, clone it, and setup the mouse callback function
image = cv2.imread('1.jpg')
cv2.namedWindow('image', cv2.WINDOW_KEEPRATIO)
# keep looping until the 'q' key is pressed
while True:
    # display the image and wait for a keypress
    cv2.imshow('image', image)
    key = cv2.waitKey()

    if key == 27:
        break

# close all open windows
cv2.destroyAllWindows()


问:
Press Default Camera App Capture button programatically like in selfie stick Android
i am making an app in which i want to capture image in default camera app without pressing capture button.i also tired this but it just open camera app.</p>

```<code>  Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
</code>```

答:
i am making an app in which i want to capture image in default camera app without pressing capture button

That is impractical, sorry.

First, there is no single "default camera app". There are ~2 billion Android devices in use, spanning thousands of models. Those models ship with hundreds of "default camera apps".

Second, there is no requirement for a camera app to have a capture button. Some might take a picture by other means. Even for those that have a capture button, there is no requirement for it to have anything in common with capture buttons in other camera apps.

Third, outside of accessibility services and rooted devices, an app cannot fake user input into another app.

You are welcome to write your own camera app, using the camera APIs (android.hardware.Camera, android.hardware.camera2.*), and come up with your own trigger for when a picture should be taken.

Body:
i am making an app in which i want to capture image in default camera app without pressing capture button.i also tired this but it just open camera app.

  Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);


问:
Using multiple values for the same param in a multipart's PartMap request with Retrofit 2
I want to send multiple values of the same param in a multipart query. Here is my code:

Interface:

```<code>@Multipart
@POST("user")
Observable<Void> updateUser(@PartMap() Map<String, RequestBody> partMap, @Part MultipartBody.Part photo);
</code>```

This request allow me to update a user with a new picture and some parameters. In the parameters I can specify the user's skills with a parameter named "skills[]". To specify the parameters that can vary in number I use a HashMap; however with a HashMap I cannot specify multiple parameters using the same name.

i.e. I cannot do:

```<code>for(Integer skill : skills) {
    RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), skill.toString());
    map.put("skills[]", body);
}
</code>```

Because the map will only accept one value of the same key.

How can I specify multiple values of a parameter. I have no problem doing it using Postman to test the request.

I tried to use a HashMap<String, List<RequestBody>> instead:

```<code>List<RequestBody> bodies = new ArrayList<>();
for(Integer skill : skills) {
    RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), skill.toString());
    bodies.add(body);
}
map.put("skills[]", bodies);
</code>```

but it seems that it's not supported. The query created contains null values for the request bodies:

```<code>Content-Disposition: form-data; name="skills[]"
Content-Transfer-Encoding: binary
Content-Type: application/json; charset=UTF-8
Content-Length: 16

[null,null,null]
</code>```

答:
Fixed thanks to Andy Developer

I still use the HashMap<String, RequestBody> but I provide different parameters names:

```<code>for(int i = 0; i < skills.size(); i++) {
    Integer skill = skills.get(i);
    RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), skill.toString());
    map.put("skills[" + i + "]", body);
}
</code>```

Body:
I want to send multiple values of the same param in a multipart query. Here is my code:

Interface:

@Multipart
@POST("user")
Observable<Void> updateUser(@PartMap() Map<String, RequestBody> partMap, @Part MultipartBody.Part photo);

This request allow me to update a user with a new picture and some parameters. In the parameters I can specify the user's skills with a parameter named "skills[]". To specify the parameters that can vary in number I use a HashMap; however with a HashMap I cannot specify multiple parameters using the same name.

i.e. I cannot do:

for(Integer skill : skills) {
    RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), skill.toString());
    map.put("skills[]", body);
}

Because the map will only accept one value of the same key.

How can I specify multiple values of a parameter. I have no problem doing it using Postman to test the request.

I tried to use a HashMap<String, List<RequestBody>> instead:

List<RequestBody> bodies = new ArrayList<>();
for(Integer skill : skills) {
    RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), skill.toString());
    bodies.add(body);
}
map.put("skills[]", bodies);

but it seems that it's not supported. The query created contains null values for the request bodies:

Content-Disposition: form-data; name="skills[]"
Content-Transfer-Encoding: binary
Content-Type: application/json; charset=UTF-8
Content-Length: 16

[null,null,null]

Body:
Fixed thanks to Andy Developer

I still use the HashMap<String, RequestBody> but I provide different parameters names:

for(int i = 0; i < skills.size(); i++) {
    Integer skill = skills.get(i);
    RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), skill.toString());
    map.put("skills[" + i + "]", body);
}


问:
React router v4 cannot display components but no error in console
I am a noob just started learning React a few days ago. I have a problem while I was working with react router v4.

I have a home page component, like this:

```<code>import React, {Component} from 'react';

class AboutPage extends Component {
    render() {
        return (
            <div>
                <h1>About</h1>
                <p>this is the about page</p>
            </div>
        );
    }
}

export default AboutPage;
</code>```

and here is the App.js:

```<code>import React, { Component } from 'react';
import './App.css';
import {
  Link, Route, Switch,BrowserRouter
} from 'react-router-dom'
import Header from './components/common/Header';
import HomePage from './components/home/HomePage';
import AboutPage from './components/about/AboutPage';

class App extends Component {
  render() {
    const home = () =><h1> Home </h1>
    const about = () =><h1> about </h1>

    return (
      <BrowserRouter>
        <div className="container-fluid">
          <Header/>
          <Switch>
          <Route exact path="/" components={home}/>
          <Route path="/about" components={about}/>
          </Switch>
        </div>
      </BrowserRouter>

    );
  }
}

export default App;
</code>```

the headers file is just a nav element I want it for all the component.

The problem is if I click either homepage or about page, it doesn't display the content of these components. It just shows the nav element and that's all.

I built this app using creat-react-app. Is there anything wrong in my code? Thx.

答: Reading the docs looks like that the Route component is expecting the property component and not components. I also believe that what you want to render is your HomePage and AboutPage component

Body:
I am a noob just started learning React a few days ago. I have a problem while I was working with react router v4.

I have a home page component, like this:

import React, {Component} from 'react';

class AboutPage extends Component {
    render() {
        return (

About

this is the about page

        );
    }
}

export default AboutPage;

and here is the App.js:

import React, { Component } from 'react';
import './App.css';
import {
  Link, Route, Switch,BrowserRouter
} from 'react-router-dom'
import Header from './components/common/Header';
import HomePage from './components/home/HomePage';
import AboutPage from './components/about/AboutPage';

class App extends Component {
  render() {
    const home = () =>
 Home

    const about = () =>
 about

    return (
      <BrowserRouter>

          <Switch>
          <Route exact path="/" components={home}/>
          <Route path="/about" components={about}/>
          </Switch>

      </BrowserRouter>

    );
  }
}

export default App;

the headers file is just a nav element I want it for all the component.

The problem is if I click either homepage or about page, it doesn't display the content of these components. It just shows the nav element and that's all.

I built this app using creat-react-app. Is there anything wrong in my code? Thx.


问:
body-parser(node.js) not able to understand form POST using fetch browser api
on sending form data using fetch api  as 'application/x-www-form-urlencoded' from browser to nodejs server, body-parser at node.js server not showing data sent but some object that is not understandable.

Here is the html form code:

```<code><body>
<form action="#" id="formToSubmit">
    <input type="text" name="name" value="xyz">
    <input type="text" name="phone" value="7777777777">
    <input type="submit" value="submit" onClick="submitForm()">
</form>

<script>
    function submitForm(){
        var form = new FormData(document.getElementById("formToSubmit"));
        fetch("http://localhost:8080/ppum", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: form // problem is here
        })
        .then(res => res.json())
        .then(data => console.log(data));

    }
</script>
</code>```

Here is the node server code for body parser:

```<code>app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
</code>```

Here is the output of "req.body" at server:

```<code>{"------WebKitFormBoundary5jfSRwRQ4GjgeApo\r\nContent-Disposition: form-data; name":"\"name\"\r\n\r\nxyz\r\n------WebKitFormBoundary5jfSRwRQ4GjgeApo\r\nContent-Disposition: form-data; name=\"phone\"\r\n\r\n7777777777\r\n------WebKitFormBoundary5jfSRwRQ4GjgeApo--\r\n"}
</code>```

problem is how to send data as 'application/x-www-form-urlencoded' from client side.

why is the output like as shown and how to correct  it.

Note:was previously using stackoverflow.com/a/37562814/3690154 and it workes. if you have some suggesting on how to convert FormData to something like in this answer that will be highly appreciated

答:
You have several problems.

Including your form data

```<code>new FormData("formToSubmit");
</code>```

The argument you pass here needs to be a form. You are passing it a string.

```<code>new FormData(document.getElementById("formToSubmit"));
</code>```

Content Type

Setting the Content-Type header manually won't cause fetch to encode the content in that format.

You are passing a FormData object, so the content will be encoded as a multipart request.

You need to use a body parser that can handle that format. See this question for the details of how to do that.

Submit buttons

Submit buttons submit forms.

You need to prevent the browser from leaving the page after starting the ajax request.

Using the 1990s style event binding you are using, you need to change:

```<code>onClick="submitForm()"
</code>```

to

```<code>onclick="submitForm(); return false;"
</code>```

You should switch to a modern method though.

Body:
on sending form data using fetch api  as 'application/x-www-form-urlencoded' from browser to nodejs server, body-parser at node.js server not showing data sent but some object that is not understandable.

Here is the html form code:

<form action="#" id="formToSubmit">
    <input type="text" name="name" value="xyz">
    <input type="text" name="phone" value="7777777777">
    <input type="submit" value="submit" onClick="submitForm()">
</form>

Here is the node server code for body parser:

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

Here is the output of "req.body" at server:

{"------WebKitFormBoundary5jfSRwRQ4GjgeApo\r\nContent-Disposition: form-data; name":"\"name\"\r\n\r\nxyz\r\n------WebKitFormBoundary5jfSRwRQ4GjgeApo\r\nContent-Disposition: form-data; name=\"phone\"\r\n\r\n7777777777\r\n------WebKitFormBoundary5jfSRwRQ4GjgeApo--\r\n"}

problem is how to send data as 'application/x-www-form-urlencoded' from client side.

why is the output like as shown and how to correct  it.

Note:was previously using stackoverflow.com/a/37562814/3690154 and it workes. if you have some suggesting on how to convert FormData to something like in this answer that will be highly appreciated

Body:
You have several problems.

Including your form data

new FormData("formToSubmit");

The argument you pass here needs to be a form. You are passing it a string.

new FormData(document.getElementById("formToSubmit"));

Content Type

Setting the Content-Type header manually won't cause fetch to encode the content in that format.

You are passing a FormData object, so the content will be encoded as a multipart request.

You need to use a body parser that can handle that format. See this question for the details of how to do that.

Submit buttons

Submit buttons submit forms.

You need to prevent the browser from leaving the page after starting the ajax request.

Using the 1990s style event binding you are using, you need to change:

onClick="submitForm()"

to

onclick="submitForm(); return false;"

You should switch to a modern method though.


问:
How to remove/hide GitExtensions toolbar from Visual Studio?
I tried:

right-click on a toolbar and uncheck GitExtensions

right-click on a toolbar > Customize and delete GitExtensions

moved the toolbar from the second row to the first row

searched GitExtensions settings for a way to disable/hide the toolbar, but didn't find anything

The GitExtensions toolbar shows up again on the second toolbar row after a computer restart.

I use:

Windows 8

Visual Studio 2012

Git 1.7.11

GitExtensions 2.41

答:
Please make sure you remove .git  hidden folder from your solution folder.
or any other .git file


问:
Getting error message as Failed to read schema document 'http://www.mulesoft.org/schema/mule/ee/dw/current/dw.xsd'
I am trying to deploy a Mule app on Mule standalone 3.8.1, but I am getting this error message:

```<code>Ignored XML validation warning
org.xml.sax.SAXParseException: schema_reference.4: Failed to read schema document 'http://www.mulesoft.org/schema/mule/ee/dw/current/dw.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.
    at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source) ~[?:?]
</code>```

It works fine when running from Anypoint Studio using Mule server 3.8.2 EE.

答:
If you are using maven , please add maven dependency for dataweave.

```<code>    <dependency>
        <groupId>com.mulesoft.weave</groupId>
        <artifactId>mule-plugin-weave</artifactId>
        <version>${mule.version}</version>
        <scope>provided</scope>
    </dependency>
</code>```

Hope this helps.

Body:
I am trying to deploy a Mule app on Mule standalone 3.8.1, but I am getting this error message:

Ignored XML validation warning
org.xml.sax.SAXParseException: schema_reference.4: Failed to read schema document 'http://www.mulesoft.org/schema/mule/ee/dw/current/dw.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.
    at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source) ~[?:?]

It works fine when running from Anypoint Studio using Mule server 3.8.2 EE.

Body:
If you are using maven , please add maven dependency for dataweave.

    <dependency>
        <groupId>com.mulesoft.weave</groupId>
        <artifactId>mule-plugin-weave</artifactId>
        <version>${mule.version}</version>
        <scope>provided</scope>
    </dependency>

Hope this helps.


问:
Uploading large video files using angular
after googling for a way to upload a big file using angular 4, i found nothing.

i found this ng-file-upload in this question Upload big files in SPA (angular + express), but it's for angularjs, is there any thing for angular 4 ?

答:
Use ng2 file upload plugin for angular 4 ng2-file-upload

and you can upload large files also