问:
Jenkins pipeline shell step
Trying to get this pipeline working..
I need to prepare some variables (list or string) in groovy, and iterate over it in bash. As I understand, groovy scripts run on jenkins master, but I need to download some files into build workspace, that's why I try to download them in SH step.

```<code>import groovy.json.JsonSlurper
import hudson.FilePath
pipeline {
    agent { label 'xxx' }
    parameters {
 ...
    }
    stages {
        stage ('Get rendered images') {
            steps {
                script {
                    //select grafana API url based on environment
                    if ( params.grafana_env == "111" ) {
                        grafana_url = "http://xxx:3001"
                    } else if ( params.grafana_env == "222" ) {
                        grafana_url = "http://yyy:3001"
                    }

                    //get available grafana dashboards
                    def grafana_url = "${grafana_url}/api/search"
                    URL apiUrl = grafana_url.toURL()
                    List json = new JsonSlurper().parse(apiUrl.newReader())
                    def workspace = pwd()
                    List dash_names = []
                    // save png for each available dashboard
                    for ( dash in json ) {
                        def dash_name = dash['uri'].split('/')
                        dash_names.add(dash_name[1])
                    }
                    dash_names_string = dash_names.join(" ")
                }
                sh "echo $dash_names_string"
                sh """
                    for dash in $dash_names_string;
                    do
                        echo $dash
                    done
                    """
            }
        }
    }
}
</code>```

I get this error when run..

```<code>[Pipeline] End of Pipeline
groovy.lang.MissingPropertyException: No such property: dash for class: WorkflowScript
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:53)
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.getProperty(ScriptBytecodeAdapter.java:458)
    at com.cloudbees.groovy.cps.sandbox.DefaultInvoker.getProperty(DefaultInvoker.java:33)
    at com.cloudbees.groovy.cps.impl.PropertyAccessBlock.rawGet(PropertyAccessBlock.java:20)
    at WorkflowScript.run(WorkflowScript:42)
</code>```

Looks like I'm missing something obvious...

答:
the problem is on line three here:

```<code>for dash in $dash_names_string;
do
  echo $dash
done
</code>```

it's trying to find a $dash property in groovy-land and finding none. i can't actually think how to make this work vi an inline sh step (possibly not enough sleep), but if you save the relevant contents of your json response to a file and then replace those four lines with a shell script that reads the file and call it from the Jenkinsfile like sh './hotScript.sh', it will not try to evaluate that dollar value as groovy, and ought to at least fail in a different way. :)

Title: Jenkins pipeline shell step

Body:
Trying to get this pipeline working..
I need to prepare some variables (list or string) in groovy, and iterate over it in bash. As I understand, groovy scripts run on jenkins master, but I need to download some files into build workspace, that's why I try to download them in SH step.

import groovy.json.JsonSlurper
import hudson.FilePath
pipeline {
    agent { label 'xxx' }
    parameters {
 ...
    }
    stages {
        stage ('Get rendered images') {
            steps {
                script {
                    //select grafana API url based on environment
                    if ( params.grafana_env == "111" ) {
                        grafana_url = "http://xxx:3001"
                    } else if ( params.grafana_env == "222" ) {
                        grafana_url = "http://yyy:3001"
                    }

                    //get available grafana dashboards
                    def grafana_url = "${grafana_url}/api/search"
                    URL apiUrl = grafana_url.toURL()
                    List json = new JsonSlurper().parse(apiUrl.newReader())
                    def workspace = pwd()
                    List dash_names = []
                    // save png for each available dashboard
                    for ( dash in json ) {
                        def dash_name = dash['uri'].split('/')
                        dash_names.add(dash_name[1])
                    }
                    dash_names_string = dash_names.join(" ")
                }
                sh "echo $dash_names_string"
                sh """
                    for dash in $dash_names_string;
                    do
                        echo $dash
                    done
                    """
            }
        }
    }
}

I get this error when run..

[Pipeline] End of Pipeline
groovy.lang.MissingPropertyException: No such property: dash for class: WorkflowScript
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:53)
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.getProperty(ScriptBytecodeAdapter.java:458)
    at com.cloudbees.groovy.cps.sandbox.DefaultInvoker.getProperty(DefaultInvoker.java:33)
    at com.cloudbees.groovy.cps.impl.PropertyAccessBlock.rawGet(PropertyAccessBlock.java:20)
    at WorkflowScript.run(WorkflowScript:42)

Looks like I'm missing something obvious...

Body:
the problem is on line three here:

for dash in $dash_names_string;
do
  echo $dash
done

it's trying to find a $dash property in groovy-land and finding none. i can't actually think how to make this work vi an inline sh step (possibly not enough sleep), but if you save the relevant contents of your json response to a file and then replace those four lines with a shell script that reads the file and call it from the Jenkinsfile like sh './hotScript.sh', it will not try to evaluate that dollar value as groovy, and ought to at least fail in a different way. :)


来源: stackexchange

问:
Column count doesn't match value count only in PHP
I use this solution (the accepted one) to insert no duplicates, because I can't set an unique index (table belong to another software), this way:

```<code>$InsertAddress = $DatabaseConnection -> prepare("INSERT INTO `tt_address` (`pid`, `tstamp`, `first_name`, `last_name`, `email`, `phone`, `address`, `city`, `zip`) SELECT * FROM (SELECT 272 AS `tmp_pid`, ? AS `tmp_tstamp`, ? AS `tmp_first_name`, ? AS `tmp_last_name`, ? AS `tmp_email`, ? AS `tmp_phone`, ? AS `tmp_address`, ? AS `tmp_city`, ? AS `tmp_zip`) AS `tmp` WHERE NOT EXISTS (SELECT `email` FROM `tt_address` WHERE `email` = ?) LIMIT 1")

$InsertAddress -> bind_param('issssssss', $Timestamp, $_POST['firstname'], $_POST['lastname'], $_POST['mail'], $_POST['phone'], $_POST['address'], $_POST['ort'], $_POST['plz'], $_POST['mail']);

$InsertAddress -> execute();

echo($DatabaseConnection -> error);
</code>```

But I get the following error:

Column count doesn't match value count at row 1

If I copy the query in phpMyAdmin and replace the ? with sample data the query works.

What is wrong?

答: Parameter markers (the question marks) can't be used for column names.</p>

ContentLicense: CC BY-SA 3.0

Body:
I use this solution (the accepted one) to insert no duplicates, because I can't set an unique index (table belong to another software), this way:

$InsertAddress = $DatabaseConnection -> prepare("INSERT INTO `tt_address` (`pid`, `tstamp`, `first_name`, `last_name`, `email`, `phone`, `address`, `city`, `zip`) SELECT * FROM (SELECT 272 AS `tmp_pid`, ? AS `tmp_tstamp`, ? AS `tmp_first_name`, ? AS `tmp_last_name`, ? AS `tmp_email`, ? AS `tmp_phone`, ? AS `tmp_address`, ? AS `tmp_city`, ? AS `tmp_zip`) AS `tmp` WHERE NOT EXISTS (SELECT `email` FROM `tt_address` WHERE `email` = ?) LIMIT 1")

$InsertAddress -> bind_param('issssssss', $Timestamp, $_POST['firstname'], $_POST['lastname'], $_POST['mail'], $_POST['phone'], $_POST['address'], $_POST['ort'], $_POST['plz'], $_POST['mail']);

$InsertAddress -> execute();

echo($DatabaseConnection -> error);

But I get the following error:

Column count doesn't match value count at row 1

If I copy the query in phpMyAdmin and replace the ? with sample data the query works.

What is wrong?


问:
Dynamically redirect all requests with the same url path to the same upstream server
I'm trying to create a basic nginx LB that redirects requests to the same upstream server if the url path repeats itself without relying on the senders cookies/ip.

for example lets say I have an LB called A.com and a target called A.com/target.
The first time a request is sent to A.com/target the LB would redirect to a random server in the upstream, so far so good, the problem is that on the second request with the same url path (Doesn't matter who makes that request, therefor cookies are out of the question) I need the LB to redirect to the same server it redirected to last time.

I just cant get it to work properly so I wanted to ask if anybody has a proper way to do it with nginx or with any other simple LB.

答:
You can balance by URL with the help of nginx upstream hash feature introduced in version 1.7.2
Official docs are here here.</p>

```<code>upstream backend {
    hash $scheme://$host$request_uri; # put any variables here

    server backend1.example.com;
    server backend2.example.com;
    server backend3.example.com;
}
</code>```

Body:
You can balance by URL with the help of nginx upstream hash feature introduced in version 1.7.2
Official docs are here here.

upstream backend {
    hash $scheme://$host$request_uri; # put any variables here

    server backend1.example.com;
    server backend2.example.com;
    server backend3.example.com;
}


问:
fetching html element id using jquery for ajax fetched content
scenario :
I have list of cities populated in html select tag and on change of it
list of sub localities are fetched as html checkboxes .

on change of status of sublocality checkboxes , I want to get list of checked element's label  and value in separate arrays . so , that I can process those things for another functionality in document

problem :
if the checkboxes were not dynamically fetched using ajax  I was able to get id of the checkboxes but not when it is fetched using ajax

the code used for the purpose is mentioned below,
any help is appreciated

```<code>var val = [],
    ids = [];
$("input[name='sublocality[]']:checked").each(function(i) {
    if ($(this).attr('id') == 'sublocality') {
        val.push($(this).next("span").text());
        ids.push($(this).val());
    }
})
</code>```

答:
when any html element added dynamically to the DOM then you have to attach its parent element to trigger any event on this

```<code>var val = [],
ids = [];
$(document).find("input[name='sublocality[]']:checked").each(function(i)
{
    if ($(this).attr('id') == 'sublocality') {
        val.push($(this).next("span").text());
        ids.push($(this).val());
    }
})
</code>```

Like here i am attaching the document element to find the checkboxes and triggering events on that

Body:
scenario :
I have list of cities populated in html select tag and on change of it
list of sub localities are fetched as html checkboxes .

on change of status of sublocality checkboxes , I want to get list of checked element's label  and value in separate arrays . so , that I can process those things for another functionality in document

problem :
if the checkboxes were not dynamically fetched using ajax  I was able to get id of the checkboxes but not when it is fetched using ajax

the code used for the purpose is mentioned below,
any help is appreciated

var val = [],
    ids = [];
$("input[name='sublocality[]']:checked").each(function(i) {
    if ($(this).attr('id') == 'sublocality') {
        val.push($(this).next("span").text());
        ids.push($(this).val());
    }
})

Body:
when any html element added dynamically to the DOM then you have to attach its parent element to trigger any event on this

var val = [],
ids = [];
$(document).find("input[name='sublocality[]']:checked").each(function(i)
{
    if ($(this).attr('id') == 'sublocality') {
        val.push($(this).next("span").text());
        ids.push($(this).val());
    }
})

Like here i am attaching the document element to find the checkboxes and triggering events on that


问:
set value of input vield without showing it
when i click on span remove address it removes it from ui but not from the list and the printed value of removeItem is an empty string "".
and how can i pass the stringList to input value="" with id clientAdd without showing it on the input .

var stringList = [];
$("#clientAdd").keypress(function(e) {
  if (e.which === 13) {
    $(".target").append("" + "" + '+' + "" + this.value + "");
    stringList.push(this.value);
    this.value = "";
    console.log(stringList);
    $(document).on("click", ".removeAddress", function() {
      var removeItem = $(this).parent().parent().val();
      console.log(removeItem);
      stringList.splice($.inArray(removeItem, stringList), 1);
      $(this).parent().remove();

      console.log(stringList);
    });
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <div class="form-group">
    <div class="col-md-12 col-sm-12">
      <label>Address *</label>
      <div class="target"></div>
      <input type="text" id="clientAdd" name="address" value="" class="form-control required">
    </div>
  </div>
</div></code>```

答:
you can hide whole input or you can use input type="hidden". Usually you have one input displayed for humans as a event trigger and input hidden for the value which is processed on the server side</p>

```<code><div class="row">
          <div class="form-group">
            <div class="col-md-12 col-sm-12">
              <label>Address *</label>
              <div class="target"></div>
              <input type="text" id="clientAdd" name="address" value="" class="form-control required">
              <input type="hidden" id="clientAddCode" name="addressCode">
            </div>
          </div>
</div>

var stringList = [];
$("#clientAdd").keypress(function (e) {
if (e.which === 13) {
     $(".target").append("<a href='#' class='tag'>" +"<span class='removeAddress'>"+'+'+"</span>"+ this.value + "</a>");
        stringList.push(this.value);
        this.value = "";
        console.log(stringList);
        $("#clientAddCode").val(stringList);
        $(document).on("click", ".removeAddress", function() {
            var removeItem = $(this).parent().parent().val();
            console.log(removeItem);
            stringList.splice( $.inArray(removeItem, stringList ) ,1 );
            $(this).parent().remove();

            console.log(stringList);
            $("#clientAddCode").val(stringList);
        });
}
});
</code>```

Body:
when i click on span remove address it removes it from ui but not from the list and the printed value of removeItem is an empty string "".
and how can i pass the stringList to input value="" with id clientAdd without showing it on the input .

var stringList = [];
$("#clientAdd").keypress(function(e) {
  if (e.which === 13) {
    $(".target").append("" + "" + '+' + "" + this.value + "");
    stringList.push(this.value);
    this.value = "";
    console.log(stringList);
    $(document).on("click", ".removeAddress", function() {
      var removeItem = $(this).parent().parent().val();
      console.log(removeItem);
      stringList.splice($.inArray(removeItem, stringList), 1);
      $(this).parent().remove();

      console.log(stringList);
    });
  }
});

      Address *

      <input type="text" id="clientAdd" name="address" value="" class="form-control required">

Body:
you can hide whole input or you can use input type="hidden". Usually you have one input displayed for humans as a event trigger and input hidden for the value which is processed on the server side

<div class="row">
          <div class="form-group">
            <div class="col-md-12 col-sm-12">
              <label>Address *</label>
              <div class="target"></div>
              <input type="text" id="clientAdd" name="address" value="" class="form-control required">
              <input type="hidden" id="clientAddCode" name="addressCode">
            </div>
          </div>
</div>

var stringList = [];
$("#clientAdd").keypress(function (e) {
if (e.which === 13) {
     $(".target").append("<a href='#' class='tag'>" +"<span class='removeAddress'>"+'+'+"</span>"+ this.value + "</a>");
        stringList.push(this.value);
        this.value = "";
        console.log(stringList);
        $("#clientAddCode").val(stringList);
        $(document).on("click", ".removeAddress", function() {
            var removeItem = $(this).parent().parent().val();
            console.log(removeItem);
            stringList.splice( $.inArray(removeItem, stringList ) ,1 );
            $(this).parent().remove();

            console.log(stringList);
            $("#clientAddCode").val(stringList);
        });
}
});


问:
Powershell: A positional parameter cannot be found that accepts argument “test”
I'm trying to execute the following command via command line

```<code>C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe  Send-MailMessage -from "mail.me" -to "mail.me" -Subject "PS test !" -Body "Hi this is a power shell mail test" -SmtpServer "mail.domain.com"
</code>```

But I'm getting the following error :

Send-MailMessage: A positional parameter cannot be found that accepts argument  « test ».

Au niveau de ligne : 1 Caractère : 17

Send-MailMessage <<<<  -from mail.me -to mail.me -Subject PS test ! -Body Hi this is a power shell mail test -SmtpServer mail.domain.com

CategoryInfo          : InvalidArgument: (:) [Send-MailMessage], ParameterBindingException

FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell

.Commands.SendMailMessage

The problem is that the same command works well when directly executed in Power Shell, but without the path.

What could be the problem generating this exception ?

答:
You need to escape double quotes in your command. Otherwise command processor strips it, and your "test" appears as parameter to Send-MailMessage.

```<code>C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe  Send-MailMessage -from "mail.me" -to "mail.me" -Subject \"PS test !\" -Body \"Hi this is a power shell mail test\" -SmtpServer "mail.domain.com"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to execute the following command via command line

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe  Send-MailMessage -from "mail.me" -to "mail.me" -Subject "PS test !" -Body "Hi this is a power shell mail test" -SmtpServer "mail.domain.com"

But I'm getting the following error :

Send-MailMessage: A positional parameter cannot be found that accepts argument  « test ».

Au niveau de ligne : 1 Caractère : 17

Send-MailMessage <<<<  -from mail.me -to mail.me -Subject PS test ! -Body Hi this is a power shell mail test -SmtpServer mail.domain.com

CategoryInfo          : InvalidArgument: (:) [Send-MailMessage], ParameterBindingException

FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell

.Commands.SendMailMessage

The problem is that the same command works well when directly executed in Power Shell, but without the path.

What could be the problem generating this exception ?

Body:
You need to escape double quotes in your command. Otherwise command processor strips it, and your "test" appears as parameter to Send-MailMessage.

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe  Send-MailMessage -from "mail.me" -to "mail.me" -Subject \"PS test !\" -Body \"Hi this is a power shell mail test\" -SmtpServer "mail.domain.com"


问:
Undesirable duplicate content with double foreach in blade
how can I make sure I use more foreach in my blade, without the content repeating more than once?

```<code>    $review = Review::orderBy('created_at', 'desc')->paginate(9);
    $info_games = array();
    $games = array();
    foreach ($review as $value) {
        $info_games[]   =   InfoGames::where('id_game', $value->id_game)->first();
        $games[]    =   Games::where('id', $value->id_game)->first();
    }
    return view('front.pages.review.list', compact('review','info_games','games'));
</code>```

and my blade:

```<code>@foreach ($review as $value)
@foreach ($info_games as $info_game)
    <div>
      <img src="https://gamelite.net/{{$info_game->image}}">
      <p>{!! str_limit($value->body, 150)  !!}</p>
    </div>
@endforeach
@endforeach
{!! $review->render() !!}
</code>```

答:
use array_filter($array) . It will return unique .
in your case </p>

```<code>$info_games = array_filter($info_games);
</code>```

Body:
how can I make sure I use more foreach in my blade, without the content repeating more than once?

    $review = Review::orderBy('created_at', 'desc')->paginate(9);
    $info_games = array();
    $games = array();
    foreach ($review as $value) {
        $info_games[]   =   InfoGames::where('id_game', $value->id_game)->first();
        $games[]    =   Games::where('id', $value->id_game)->first();
    }
    return view('front.pages.review.list', compact('review','info_games','games'));

and my blade:

@foreach ($review as $value)
@foreach ($info_games as $info_game)

      image}}">

{!! str_limit($value->body, 150)  !!}

@endforeach
@endforeach
{!! $review->render() !!}

Body:
use array_filter($array) . It will return unique .
in your case

$info_games = array_filter($info_games);


问:
Javascript move players with keys
I am trying to be able to control two players and make them move with a certain speed, I ain't getting any errors in the console and it writes out what it should be doing... But I see no action happening.</p>

```<code>//control system

    window.addEventListener('keydown', function (event) {
    //left key
        if (event.keyCode === 37) {
            playerOne.x -= 1;
            console.log("player 1 left");
        }
    //right key
        else if (event.keyCode === 39) {
            playerOne.x += 1;
            console.log("player 1 right");
        }
    //up key
        else if (event.keyCode === 38) {
            playerOne.y -= 1;
            console.log("player 1 up");
        }
    //down
        else if (event.keyCode === 40) {
            playerOne.y += 1;
            console.log("player 1 down");
        }
    // bomb
         else if (event.keyCode === 13) {
            console.log("place bomb");
        }
    });
    window.addEventListener('keydown', function (event) {
    //left key
        if (event.keyCode === 65) {
            playerTwo.x -= 1;
            console.log("player 2 left");
        }
    //right key
        else if (event.keyCode === 68) {
            playerTwo.x += 1;
            console.log("player 2 right");
        }
    //up key
        else if (event.keyCode === 87) {
            playerTwo.y -= 1;
            console.log("player 2 up");
        }
    //down
        else if (event.keyCode === 83) {
            playerTwo.y += 1;
            console.log("player 2 down");
    }
    // bomb
    else if (event.keyCode === 32) {
        console.log("place bomb");
    }
});

function movePlayers() {
    "use strict";
    if (keys.moveLeft) {
        playerOne.x -= powerUps.speed;
        if (playerOne.currentDirection != "left") {
            playerOne.gotoAndPlay('left')
            playerOne.currentDirection = "left";
        }
    }
    if (keys.moveRight) {
        playerOne.x += powerUps.speed;
        if (playerOne.currentDirection != "right") {
            playerOne.gotoAndPlay('right')
            playerOne.currentDirection = "right";
        }
    }
    if (keys.moveUp) {
        playerOne.y -= powerUps.speed;
        if (playerOne.currentDirection != "up") {
            playerOne.gotoAndPlay('up')
            playerOne.currentDirection = "up";
        }
    }
    if (keys.moveDown) {
        playerOne.y += powerUps.speed;
        if (playerOne.currentDirection != "down") {
            playerOne.gotoAndPlay('down')
            playerOne.currentDirection = "down";
        }
    }
    if (keys.moveLeft) {
        playerTwo.x -= powerUps.speed;
        if (playerTwo.currentDirection != "left") {
            playerTwo.gotoAndPlay('left')
            playerTwo.currentDirection = "left";
        }
    }
    if (keys.moveRight) {
        playerTwo.x += powerUps.speed;
        if (playerTwo.currentDirection != "right") {
            playerTwo.gotoAndPlay('right')
            playerTwo.currentDirection = "right";
        }
    }
    if (keys.moveUp) {
        playerTwo.y -= powerUps.speed;
        if (playerTwo.currentDirection != "up") {
            playerTwo.gotoAndPlay('up')
            playerTwo.currentDirection = "up";
        }
    }
    if (keys.moveDown) {
        playerTwo.y += powerUps.speed;
        if (playerTwo.currentDirection != "down") {
            playerTwo.gotoAndPlay('down')
            playerTwo.currentDirection = "down";
        }
    }
}
</code>```

答:
That´s only an Tipp not an answer - but the place in comments is not enough.

I thinks that´s not an good way with your "if" construction, a sample for an easier way:

  <!doctype html>

    <meta charset="UTF-8">
    <title>Table key´s</title>

  ```

Title: Javascript move players with keys

Body:
I am trying to be able to control two players and make them move with a certain speed, I ain't getting any errors in the console and it writes out what it should be doing... But I see no action happening.

//control system

    window.addEventListener('keydown', function (event) {
    //left key
        if (event.keyCode === 37) {
            playerOne.x -= 1;
            console.log("player 1 left");
        }
    //right key
        else if (event.keyCode === 39) {
            playerOne.x += 1;
            console.log("player 1 right");
        }
    //up key
        else if (event.keyCode === 38) {
            playerOne.y -= 1;
            console.log("player 1 up");
        }
    //down
        else if (event.keyCode === 40) {
            playerOne.y += 1;
            console.log("player 1 down");
        }
    // bomb
         else if (event.keyCode === 13) {
            console.log("place bomb");
        }
    });
    window.addEventListener('keydown', function (event) {
    //left key
        if (event.keyCode === 65) {
            playerTwo.x -= 1;
            console.log("player 2 left");
        }
    //right key
        else if (event.keyCode === 68) {
            playerTwo.x += 1;
            console.log("player 2 right");
        }
    //up key
        else if (event.keyCode === 87) {
            playerTwo.y -= 1;
            console.log("player 2 up");
        }
    //down
        else if (event.keyCode === 83) {
            playerTwo.y += 1;
            console.log("player 2 down");
    }
    // bomb
    else if (event.keyCode === 32) {
        console.log("place bomb");
    }
});

function movePlayers() {
    "use strict";
    if (keys.moveLeft) {
        playerOne.x -= powerUps.speed;
        if (playerOne.currentDirection != "left") {
            playerOne.gotoAndPlay('left')
            playerOne.currentDirection = "left";
        }
    }
    if (keys.moveRight) {
        playerOne.x += powerUps.speed;
        if (playerOne.currentDirection != "right") {
            playerOne.gotoAndPlay('right')
            playerOne.currentDirection = "right";
        }
    }
    if (keys.moveUp) {
        playerOne.y -= powerUps.speed;
        if (playerOne.currentDirection != "up") {
            playerOne.gotoAndPlay('up')
            playerOne.currentDirection = "up";
        }
    }
    if (keys.moveDown) {
        playerOne.y += powerUps.speed;
        if (playerOne.currentDirection != "down") {
            playerOne.gotoAndPlay('down')
            playerOne.currentDirection = "down";
        }
    }
    if (keys.moveLeft) {
        playerTwo.x -= powerUps.speed;
        if (playerTwo.currentDirection != "left") {
            playerTwo.gotoAndPlay('left')
            playerTwo.currentDirection = "left";
        }
    }
    if (keys.moveRight) {
        playerTwo.x += powerUps.speed;
        if (playerTwo.currentDirection != "right") {
            playerTwo.gotoAndPlay('right')
            playerTwo.currentDirection = "right";
        }
    }
    if (keys.moveUp) {
        playerTwo.y -= powerUps.speed;
        if (playerTwo.currentDirection != "up") {
            playerTwo.gotoAndPlay('up')
            playerTwo.currentDirection = "up";
        }
    }
    if (keys.moveDown) {
        playerTwo.y += powerUps.speed;
        if (playerTwo.currentDirection != "down") {
            playerTwo.gotoAndPlay('down')
            playerTwo.currentDirection = "down";
        }
    }
}

Body:
That´s only an Tipp not an answer - but the place in comments is not enough.

I thinks that´s not an good way with your "if" construction, a sample for an easier way:

  <!doctype html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Table key´s</title>
    <style>
      td{width:10px;height:10px;background:#ddd;}
      tr:nth-child(5) td:nth-child(5){background:#f00;}
    </style>
  </head>
  <body>
    <div id="tableContainer">
    </div>
    <script>
      var row=col=5,max=10;
      tableContainer.innerHTML = '<table>'+('<tr>'+'<td>'.repeat(max)).repeat(max)+'</table>';
      window.addEventListener("keyup", function(e){
        var colDiff, rowDiff;
        var keyMap = new Map([[37,[-1,0]],[38,[0,-1]],[39,[1,0]],[40,[0,1]]]);
        if (keyMap.has(e.keyCode)){
          document.querySelector(`tr:nth-child(${row}) td:nth-child(${col})`).style.background='#ddd';
          [colDiff,rowDiff]=keyMap.get(e.keyCode);
          row+=rowDiff;
          col+=colDiff;
          row = (row>max) ? max : (row < 1) ? 1 : row;
          col = (col>max) ? max : (col < 1) ? 1 : col;
          document.querySelector(`tr:nth-child(${row}) td:nth-child(${col})`).style.background='#f00';
        }
      })
    </script>
  </body>
  </html>


问:
jquery autocomplete
i have problem about remote jquery autocompete

i get a json object from the server in this format

```<code>[{"id":"4cd8d3b37adf3515c800003e","name":"University of Alberta"},
 {"id":"4cd8d3b37adf3515c800003f","name":"Athabasca University"},
 {"id":"4cd8d3b37adf3515c8000040","name":"University of Calgary"},
 {"id":"4cd8d3b37adf3515c8000041","name":"University of Lethbridge"},
 {"id":"4cd8d3b37adf3515c8000042","name":"Mount Royal University"},
 {"id":"4cd8d3b37adf3515c8000043","name":"University of Toronto"},
 {"id":"4cd8d3b37adf3515c8000045","name":"Queens University"},
 {"id":"4cd8d3b37adf3515c8000046","name":"University of Waterloo"},
 {"id":"4cd8d3b37adf3515c8000047","name":"McGill University"},
 {"id":"4cd8d3b37adf3515c8000048","name":"University of British Columbia"},
 {"id":"4cd8d3b37adf3515c8000049","name":"University of Saskatchewan"},
 {"id":"4cec8ead7adf3502a100001f","name":"University of Alberta"}]
</code>```

Now what i need to do is only show the names of the university in the autocomplete list and populate the corresponding id in one hidden field when the user selects the university.

i tried moving aroung formatResult and formatItem with this json object but couldn't figure out how to autocomplete.

It would be helpful if someone explain how to apply formatResult and formatItem methods of jquery autocomplete with json objects

Thanks

答:
You can use a getJson to get the data i and then use some thing like this to make it autocomplite

```<code><body>
    <br /><br />API Reference: <input id="example" /> (try "U")<br /><br />
    ID for selectet university <span id="UniID"></span>
    <script type="text/javascript">
        $(function() {
            $.getJSON('JSonUni.txt' , function(autoData) { // Get the data for autocomplite
                $("#example").autocomplete(autoData, {
                    formatItem: function(item) {
                        return item.name;
                    }
                }).result(function(event, item) {
                    $('#UniID').text(item.id);
                });
            }); // end JSON
        }); // End function
    </script>
</body>
</code>```

Also include this lines

```<code><link rel="stylesheet" href="http://dev.jquery.com/view/trunk/plugins/autocomplete/jquery.autocomplete.css" type="text/css" />
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/autocomplete/jquery.autocomplete.js"></script>
</code>```

ContentLicense: CC BY-SA 2.5

Title: jquery autocomplete

Body:
i have problem about remote jquery autocompete

i get a json object from the server in this format

[{"id":"4cd8d3b37adf3515c800003e","name":"University of Alberta"},
 {"id":"4cd8d3b37adf3515c800003f","name":"Athabasca University"},
 {"id":"4cd8d3b37adf3515c8000040","name":"University of Calgary"},
 {"id":"4cd8d3b37adf3515c8000041","name":"University of Lethbridge"},
 {"id":"4cd8d3b37adf3515c8000042","name":"Mount Royal University"},
 {"id":"4cd8d3b37adf3515c8000043","name":"University of Toronto"},
 {"id":"4cd8d3b37adf3515c8000045","name":"Queens University"},
 {"id":"4cd8d3b37adf3515c8000046","name":"University of Waterloo"},
 {"id":"4cd8d3b37adf3515c8000047","name":"McGill University"},
 {"id":"4cd8d3b37adf3515c8000048","name":"University of British Columbia"},
 {"id":"4cd8d3b37adf3515c8000049","name":"University of Saskatchewan"},
 {"id":"4cec8ead7adf3502a100001f","name":"University of Alberta"}]

Now what i need to do is only show the names of the university in the autocomplete list and populate the corresponding id in one hidden field when the user selects the university.

i tried moving aroung formatResult and formatItem with this json object but couldn't figure out how to autocomplete.

It would be helpful if someone explain how to apply formatResult and formatItem methods of jquery autocomplete with json objects

Thanks

Body:
You can use a getJson to get the data i and then use some thing like this to make it autocomplite

<body>
    <br /><br />API Reference: <input id="example" /> (try "U")<br /><br />
    ID for selectet university <span id="UniID"></span>
    <script type="text/javascript">
        $(function() {
            $.getJSON('JSonUni.txt' , function(autoData) { // Get the data for autocomplite
                $("#example").autocomplete(autoData, {
                    formatItem: function(item) {
                        return item.name;
                    }
                }).result(function(event, item) {
                    $('#UniID').text(item.id);
                });
            }); // end JSON
        }); // End function
    </script>
</body>

Also include this lines

<link rel="stylesheet" href="http://dev.jquery.com/view/trunk/plugins/autocomplete/jquery.autocomplete.css" type="text/css" />
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/autocomplete/jquery.autocomplete.js"></script>


问:
Making a variable constant without using a final keyword
I came across this question in interview, that how to make a variable constant without final keyword in java</p>

答:
I suspect that they were looking for an answer "declare your variable inside an interface". According to Java language specifications, all variables declared in an interface are implicitly static and final:</p>

```<code>interface Foo {
    int BAR = 100;
}
class Test {
    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.println(Foo.BAR);
    }
}
</code>```

Body:
I suspect that they were looking for an answer "declare your variable inside an interface". According to Java language specifications, all variables declared in an interface are implicitly static and final:

interface Foo {
    int BAR = 100;
}
class Test {
    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.println(Foo.BAR);
    }
}


问:
On typing a query, each alphabet is producing new single page. How it should be prevented?
I'm working, a project in which I have to create a search engine. I'm facing problem, whenever a user types a query for each and every alphabet typed a new page is being reproduced. For example if I type - 'fos' , 3 pages are being produced. If I type 'fossa' 5 pages are being produced.

I have used redux architecture and angular 2 in my project. How should I solve this problem ? Thanks in advance :)

```<code>onquery(event: any) {
   if (event.target.value.length > 2) {
     this.store.dispatch(new query.QueryAction(event.target.value));
     this.displayStatus = 'showbox';
     this.submit();
     this.hidebox(event);
    }
  }
submit() {
  this.router.navigate(['/search'], {queryParams: this.searchdata});
}
</code>```

HTML

```<code><input #input type="text" name="query" class="form-control" id="nav-input" (keyup)="onquery($event)"
           [(ngModel)]="searchdata.query" autocomplete="off">
</code>```

Reducer code -

```<code>export const CHANGE = 'CHANGE';

export interface State {
  searchresults: any;
  items: any;
}

const initialState: State = {
  searchresults: {},
  items: []
};

export function reducer(state: State = initialState, action: search.Actions): State {
  switch (action.type) {
    case search.ActionTypes.CHANGE: {
      const search = action.payload;
      return Object.assign({}, state, {
        searchresults: search,
        items: search.channels[0].items
      });
    }
    default: {
      return state;
    }
</code>```

答:
If your problem is about: how to limit calling of a function (which create a new page) for each keystroke when user typing. You should consider using debounce or throttle.

Debounce and throttle are two similar (but different!) techniques to
  control how many times we allow a function to be executed over time.

Here an example in jQuery as a start, be aware you need to adapt it for your angular app:

https://gist.github.com/makenova/7885923

Useful:
https://davidwalsh.name/javascript-debounce-function

Body:
I'm working, a project in which I have to create a search engine. I'm facing problem, whenever a user types a query for each and every alphabet typed a new page is being reproduced. For example if I type - 'fos' , 3 pages are being produced. If I type 'fossa' 5 pages are being produced.

I have used redux architecture and angular 2 in my project. How should I solve this problem ? Thanks in advance :)

onquery(event: any) {
   if (event.target.value.length > 2) {
     this.store.dispatch(new query.QueryAction(event.target.value));
     this.displayStatus = 'showbox';
     this.submit();
     this.hidebox(event);
    }
  }
submit() {
  this.router.navigate(['/search'], {queryParams: this.searchdata});
}

HTML

<input #input type="text" name="query" class="form-control" id="nav-input" (keyup)="onquery($event)"
           [(ngModel)]="searchdata.query" autocomplete="off">

Reducer code -

export const CHANGE = 'CHANGE';

export interface State {
  searchresults: any;
  items: any;
}

const initialState: State = {
  searchresults: {},
  items: []
};

export function reducer(state: State = initialState, action: search.Actions): State {
  switch (action.type) {
    case search.ActionTypes.CHANGE: {
      const search = action.payload;
      return Object.assign({}, state, {
        searchresults: search,
        items: search.channels[0].items
      });
    }
    default: {
      return state;
    }


问:
Android: Edittext that only allows a digit from 1-9
I am looking for a way so that users can only input a number between 1-9 with edittext. No exception should be displayed. It should not be possible to type in more than one digit. </p>

答:
You can set the input type programmatically like this :-

myEditText.setInputType(InputType.TYPE_CLASS_NUMBER |
InputType.TYPE_NUMBER_VARIATION_PASSWORD);
myEditText.setKeyListener(DigitsKeyListener.getInstance("123456789"));
InputFilter[] inputArray = new InputFilter[1];
inputArray[0] = new InputFilter.LengthFilter(1);
myEditText.setFilters(inputArray);
  ```
</div>
</div>
</p>

<p>or you can set the XML attributes like this :-</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> android:inputType="number"
 android:digits="123456789"
 android:maxLength="1"</code>```

Body:
You can set the input type programmatically like this :-

myEditText.setInputType(InputType.TYPE_CLASS_NUMBER |
InputType.TYPE_NUMBER_VARIATION_PASSWORD);
myEditText.setKeyListener(DigitsKeyListener.getInstance("123456789"));
InputFilter[] inputArray = new InputFilter[1];
inputArray[0] = new InputFilter.LengthFilter(1);
myEditText.setFilters(inputArray);

or you can set the XML attributes like this :-

 android:inputType="number"
 android:digits="123456789"
 android:maxLength="1"


问:
How to use FlvPlayBack to play back and live videos?
I want it to automatically detect if there's a live video,then play live;otherwise play back.

How to do it that way?

答:
Currently, there is no way to detect if a stream is live or not. You need some kind of metadata passed into the player (like Aurel300 suggested).

-Andrian


问:
typescript destructuring object literal in construct of the class, default properties does not work
I'm trying to use default values for destructuring object literal, but I don't get the default values, just 'undefined'. What is the right way?</p>

```<code>import { Component } from '@angular/core';
export class Hero {
  id: number;
  name: string;
 // constructor( {id = 3, name = 'defaulthero'} = {}) {
  constructor( {id  , name }: {id?: number, name?: string } = { id:3, name: 'defaulthero'} ) {
    console.log( id, name);
    this.id = id;
    this.name = name;
  }
}

@Component({
  selector: 'my-app',
  template: `<h1>{{title}}</h1><h2>Hero {{hero3.id}} {{hero3.name}}</h2>`,
})
export class AppComponent    {
  title = 'Tour of Heros';
  public hero3: Hero;

  ngOnInit() {

    //this.hero3  = new Hero (  ) ;  // work
    //this.hero3  = new Hero (  {} ) ; // does not work
    this.hero3  = new Hero ( {id: 0} ) ;  // does not work, default value 'defaulthero' not assign, just i get 'undefined'
  }
}
</code>```

答:
I've found two alternatives solutions inspired in:

1) Solution class Hero:
https://github.com/Microsoft/TypeScript/wiki/What%27s-new-in-TypeScript#improved-checking-for-destructuring-object-literal

2) Solution class Hero2: section "Optional Properties"
https://www.typescriptlang.org/docs/handbook/interfaces.html

```<code>import { Component, OnInit  } from '@angular/core';

interface HeroInterface {
  // you need add ? for each variable (Optional Properties)
  id?: number;
  name?: string;

}

// Class using solution 1
class Hero {
  id: number;
  name: string;
  //without interface: constructor({id= 3, name= 'defaulthero'}: {id?: number, name?: string } = {}) {
  constructor({id= 4, name= 'Spiderman'}: HeroInterface = {}) {
    this.id = id;
    this.name = name;
  }

}

// Class solution 2 ,using short way of assign property on constructor()
class Hero2 {
  constructor(public config: HeroInterface = {}) { // short way to assign config like this.config = config;

    if (!config.id) this.config.id =10;
    if (!config.name) this.config.name = 'SuperMan';
  }

}

@Component ( {
  selector: 'my-app',
  template: `hero1: id: {{hero.id}} name: {{hero.name}}
            <br/>hero2: id: {{hero2.config.id}} name: {{hero2.config.name}}
    `
})
export class AppComponent implements OnInit {
  hero: Hero ;
  hero2: Hero2 ;
  ngOnInit () {

    // SOLUTION 1:
    // this.hero = new Hero ();
    this.hero = new Hero ( { id:9 });

    // SOLUTION 2:
    this.hero2 = new Hero2 ( ); // Works with default values
    //this.hero2 = new Hero2 ( { id: 20} ); // Works with default name value
    //this.hero2 =  new Hero2 ( { id: 20, name: 'Asterix'}); // send all values, don't need use default values
    //this.hero2 = new Hero2 ( { id:19 , name: 'Asterix', weight:90}); // Error, 'weight' does not exist in type 'HeroInterface'
  }
}
</code>```

Body:
I'm trying to use default values for destructuring object literal, but I don't get the default values, just 'undefined'. What is the right way?

import { Component } from '@angular/core';
export class Hero {
  id: number;
  name: string;
 // constructor( {id = 3, name = 'defaulthero'} = {}) {
  constructor( {id  , name }: {id?: number, name?: string } = { id:3, name: 'defaulthero'} ) {
    console.log( id, name);
    this.id = id;
    this.name = name;
  }
}

@Component({
  selector: 'my-app',
  template: `<h1>{{title}}</h1><h2>Hero {{hero3.id}} {{hero3.name}}</h2>`,
})
export class AppComponent    {
  title = 'Tour of Heros';
  public hero3: Hero;

  ngOnInit() {

    //this.hero3  = new Hero (  ) ;  // work
    //this.hero3  = new Hero (  {} ) ; // does not work
    this.hero3  = new Hero ( {id: 0} ) ;  // does not work, default value 'defaulthero' not assign, just i get 'undefined'
  }
}

Body:
I've found two alternatives solutions inspired in:

1) Solution class Hero:
https://github.com/Microsoft/TypeScript/wiki/What%27s-new-in-TypeScript#improved-checking-for-destructuring-object-literal

2) Solution class Hero2: section "Optional Properties"
https://www.typescriptlang.org/docs/handbook/interfaces.html

import { Component, OnInit  } from '@angular/core';

interface HeroInterface {
  // you need add ? for each variable (Optional Properties)
  id?: number;
  name?: string;

}

// Class using solution 1
class Hero {
  id: number;
  name: string;
  //without interface: constructor({id= 3, name= 'defaulthero'}: {id?: number, name?: string } = {}) {
  constructor({id= 4, name= 'Spiderman'}: HeroInterface = {}) {
    this.id = id;
    this.name = name;
  }

}

// Class solution 2 ,using short way of assign property on constructor()
class Hero2 {
  constructor(public config: HeroInterface = {}) { // short way to assign config like this.config = config;

    if (!config.id) this.config.id =10;
    if (!config.name) this.config.name = 'SuperMan';
  }

}

@Component ( {
  selector: 'my-app',
  template: `hero1: id: {{hero.id}} name: {{hero.name}}
            <br/>hero2: id: {{hero2.config.id}} name: {{hero2.config.name}}
    `
})
export class AppComponent implements OnInit {
  hero: Hero ;
  hero2: Hero2 ;
  ngOnInit () {

    // SOLUTION 1:
    // this.hero = new Hero ();
    this.hero = new Hero ( { id:9 });

    // SOLUTION 2:
    this.hero2 = new Hero2 ( ); // Works with default values
    //this.hero2 = new Hero2 ( { id: 20} ); // Works with default name value
    //this.hero2 =  new Hero2 ( { id: 20, name: 'Asterix'}); // send all values, don't need use default values
    //this.hero2 = new Hero2 ( { id:19 , name: 'Asterix', weight:90}); // Error, 'weight' does not exist in type 'HeroInterface'
  }
}


答:
try this way

```<code><EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:digits="123456789"
        android:maxLength="1"
        android:inputType="number" />
</code>```

Title: Android: Edittext that only allows a digit from 1-9

Body: I am looking for a way so that users can only input a number between 1-9 with edittext. No exception should be displayed. It should not be possible to type in more than one digit.

Body:
try this way

<EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:digits="123456789"
        android:maxLength="1"
        android:inputType="number" />


问:
Replace string with emoji
Given is an input field with an code representing an emoji.
I now want to replace this code with the corresponding emoji.

The idea was to substitute the value with the unicode but that does not work for me in inputs. Only when I copy the emoji itself into the code, the replacement works.

Example:

Given code: [e-1f60e],

converted: 😎,

should be:

My question: how can I convert the given code to the emoji inside JavaScript?

$("#tauschen").click(function() {
  $('#blub').val(function(index, value) {
    return value.replace('[e-1f60e]', '😎'); // Doesn't work
  });
});

$("#tauschen2").click(function() {
  $('#blub2').val(function(index, value) {
    return value.replace('[e-1f60e]', ''); // Works - but how to convert the given string to an emoji?!
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
  Given are strings in an imout field like these, representing an emoji: <strong>[e-1f60e]</strong> </p>

<p>
 Now I want to display them "live" as emojis, instead of only the code: 😎
</p>

<input id="blub" type="text" name="test" value="[e-1f60e]">
<input type="submit" value="Test 1" id="tauschen">
<br>

<input id="blub2" type="text" name="test" value="[e-1f60e]">
<input type="submit" value="Test 2" id="tauschen2"></code>```

JSFiddle: https://jsfiddle.net/r07qnuoz/1/

答:
You need to...

...find or extract the hexadecimal code point within the string

...convert that hexadecimal string to a number

...convert that code point number to a string via String.fromCodePoint

function convertEmoji(str) {
  return str.replace(/\[e-([0-9a-fA-F]+)\]/g, (match, hex) =>
    String.fromCodePoint(Number.parseInt(hex, 16))
  );
}

console.log(convertEmoji('[e-1f60e]')); // ```
</div>
</div>
</p>

<p>For compatibility with IE, use <code>String.fromCharCode</code> either as detailed here or by direct conversion to 16-bit surrogate pairs according to the specification:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// Convert supplementary plane code point to two surrogate 16-bit code units:
function surrogate(cp) {
  return [
    ((cp - 0x010000 & 0xffc00) >> 10) + 0xd800,
    (cp - 0x010000 & 0x3ff) + 0xdc00
  ];
}

function convertEmoji(str) {
  return str.replace(/\[e-([0-9a-fA-F]+)\]/g, function(match, hex) {
    return String.fromCharCode.apply(null, surrogate(Number.parseInt(hex, 16)))
  });
}

console.log(convertEmoji('[e-1f60e]')); // </code>```

Title: Replace string with emoji

Body:
Given is an input field with an code representing an emoji.
I now want to replace this code with the corresponding emoji.

The idea was to substitute the value with the unicode but that does not work for me in inputs. Only when I copy the emoji itself into the code, the replacement works.

Example:

Given code: [e-1f60e],

converted: 😎,

should be:

My question: how can I convert the given code to the emoji inside JavaScript?

$("#tauschen").click(function() {
  $('#blub').val(function(index, value) {
    return value.replace('[e-1f60e]', '😎'); // Doesn't work
  });
});

$("#tauschen2").click(function() {
  $('#blub2').val(function(index, value) {
    return value.replace('[e-1f60e]', ''); // Works - but how to convert the given string to an emoji?!
  });
});

  Given are strings in an imout field like these, representing an emoji: [e-1f60e]

 Now I want to display them "live" as emojis, instead of only the code: 😎

<input id="blub" type="text" name="test" value="[e-1f60e]">
<input type="submit" value="Test 1" id="tauschen">

<input id="blub2" type="text" name="test" value="[e-1f60e]">
<input type="submit" value="Test 2" id="tauschen2">

JSFiddle: https://jsfiddle.net/r07qnuoz/1/

Body:
You need to...

...find or extract the hexadecimal code point within the string

...convert that hexadecimal string to a number

...convert that code point number to a string via String.fromCodePoint

function convertEmoji(str) {
  return str.replace(/\[e-([0-9a-fA-F]+)\]/g, (match, hex) =>
    String.fromCodePoint(Number.parseInt(hex, 16))
  );
}

console.log(convertEmoji('[e-1f60e]')); //

For compatibility with IE, use String.fromCharCode either as detailed here or by direct conversion to 16-bit surrogate pairs according to the specification:

// Convert supplementary plane code point to two surrogate 16-bit code units:
function surrogate(cp) {
  return [
    ((cp - 0x010000 & 0xffc00) >> 10) + 0xd800,
    (cp - 0x010000 & 0x3ff) + 0xdc00
  ];
}

function convertEmoji(str) {
  return str.replace(/\[e-([0-9a-fA-F]+)\]/g, function(match, hex) {
    return String.fromCharCode.apply(null, surrogate(Number.parseInt(hex, 16)))
  });
}

console.log(convertEmoji('[e-1f60e]')); //


问:
How do I know which groups each product is in?
```<code>class Product(models.Model):
    name = models.CharField(max_length=256)

class Group(models.Model):
    name = models.CharField(max_length=32, unique=False)
    products = models.ManyToManyField(Product, blank=True)
</code>```

Products in group.pk == 1:

```<code>products = Group.objects.get(pk=1).products.all().values('name')
</code>```

Result:

```<code><QuerySet [
    {"name": "product1"},
    {"name": "product2"},
    {"name": "product3"},
]
</code>```

How do I know which groups each product is in? Like this:

```<code><QuerySet [
    {"name": "product1", "groups": [{"pk": 1, "name": "group1"}]},
    {"name": "product2", "groups": []"},
    {"name": "product3", "groups": [{"pk": 1, "name": "group1"}, {"pk": 2, "name": "group2"}},
]
</code>```

Thanks!

UPD1.

If we have data:

```<code>group1 | product 1
group1 | product 2
group2 | product 2
group2 | product 3
</code>```

The idea of creating a table (html) is as follows:

/group/1:

```<code>product 1 | dropdown (group1)
product 2 | dropdown (group1, group2)
</code>```

/group/2:

```<code>product 2 | dropdown (group1, group2)
product 3 | dropdown (group2)
</code>```

答:
As my understanding, you want to have reverse lookup from your manytomany field to the Model.

You can get the Product groups like this:

Here product is a Product object, and you want to list all the groups associated with that product.

```<code>product.group_set.all()
</code>```

Body:
class Product(models.Model):
    name = models.CharField(max_length=256)

class Group(models.Model):
    name = models.CharField(max_length=32, unique=False)
    products = models.ManyToManyField(Product, blank=True)

Products in group.pk == 1:

products = Group.objects.get(pk=1).products.all().values('name')

Result:

<QuerySet [
    {"name": "product1"},
    {"name": "product2"},
    {"name": "product3"},
]

How do I know which groups each product is in? Like this:

<QuerySet [
    {"name": "product1", "groups": [{"pk": 1, "name": "group1"}]},
    {"name": "product2", "groups": []"},
    {"name": "product3", "groups": [{"pk": 1, "name": "group1"}, {"pk": 2, "name": "group2"}},
]

Thanks!

UPD1.

If we have data:

group1 | product 1
group1 | product 2
group2 | product 2
group2 | product 3

The idea of creating a table (html) is as follows:

/group/1:

product 1 | dropdown (group1)
product 2 | dropdown (group1, group2)

/group/2:

product 2 | dropdown (group1, group2)
product 3 | dropdown (group2)

Body:
As my understanding, you want to have reverse lookup from your manytomany field to the Model.

You can get the Product groups like this:

Here product is a Product object, and you want to list all the groups associated with that product.

product.group_set.all()


问:
Mysql join tables with or without a condition
I have a problem i've been having quite a lot recently and it would be great to find a solution for it.
Let's say we have two tables Table1 and Table2. Is there a way to make a join on these tables with or without a condition?

e.g:

```<code>Select * from Table1 t1 left join Table2 t2 on t1.column = t2.column where t2.anothercolumn in (v1,v2,v3) and ...;

Select * from Table1 t1 left join Table2 t2 on t1.column = t2.column where t2.anothercolumn in ('') and ....;
</code>```

So in these two cases i wanna be able to do a join, if I point a condition on the t2 column then it would show me results related to that otherwise show everything.

At the moment if I put the in('') it wouldn't show anything.

Thanks in advance.

答:
When you do a left join, conditions on the second table go in the ON clause:

```<code>Select *
from Table1 t1 left join
     Table2 t2
     on t1.column = t2.column and
        t2.anothercolumn in (v1, v2, v3) and ...;
</code>```

Conditions in the first table go in the where clause.  This might seem like an arcane rule.  But if you understand the underlying mechanisms, it makes a lot of sense.

A left join keeps all rows in the first table, regardless of whether or not the on clause evaluates to true.  Hence, a condition on the first table has no effect on the results (because left join keeps the first records anyway).

On the other hand, your version turns the left join into an inner join, because the values on the second table are NULL when the where clause is processing them.

Body:
I have a problem i've been having quite a lot recently and it would be great to find a solution for it.
Let's say we have two tables Table1 and Table2. Is there a way to make a join on these tables with or without a condition?

e.g:

Select * from Table1 t1 left join Table2 t2 on t1.column = t2.column where t2.anothercolumn in (v1,v2,v3) and ...;

Select * from Table1 t1 left join Table2 t2 on t1.column = t2.column where t2.anothercolumn in ('') and ....;

So in these two cases i wanna be able to do a join, if I point a condition on the t2 column then it would show me results related to that otherwise show everything.

At the moment if I put the in('') it wouldn't show anything.

Thanks in advance.

Body:
When you do a left join, conditions on the second table go in the ON clause:

Select *
from Table1 t1 left join
     Table2 t2
     on t1.column = t2.column and
        t2.anothercolumn in (v1, v2, v3) and ...;

Conditions in the first table go in the where clause.  This might seem like an arcane rule.  But if you understand the underlying mechanisms, it makes a lot of sense.

A left join keeps all rows in the first table, regardless of whether or not the on clause evaluates to true.  Hence, a condition on the first table has no effect on the results (because left join keeps the first records anyway).

On the other hand, your version turns the left join into an inner join, because the values on the second table are NULL when the where clause is processing them.


问:
How do you rotate a two dimensional array?
Inspired by Raymond Chen's post, say you have a 4x4 two dimensional array, write a function that rotates it 90 degrees. Raymond links to a solution in pseudo code, but I'd like to see some real world stuff.

```<code>[1][2][3][4]
[5][6][7][8]
[9][0][1][2]
[3][4][5][6]
</code>```

Becomes:

```<code>[3][9][5][1]
[4][0][6][2]
[5][1][7][3]
[6][2][8][4]
</code>```

Update: Nick's answer is the most straightforward, but is there a way to do it better than n^2? What if the matrix was 10000x10000?

答:
Here is one that does the rotation in place instead of using a completely new array to hold the result.  I've left off initialization of the array and printing it out.  This only works for square arrays but they can be of any size.  Memory overhead is equal to the size of one element of the array so you can do the rotation of as large an array as you want.

int a[4][4];
int n = 4;
int tmp;
for (int i = 0; i < n / 2; i++)
{
    for (int j = i; j < n - i - 1; j++)
    {
        tmp             = a[i][j];
        a[i][j]         = a[j][n-i-1];
        a[j][n-i-1]     = a[n-i-1][n-j-1];
        a[n-i-1][n-j-1] = a[n-j-1][i];
        a[n-j-1][i]     = tmp;
    }
}
```

OwnerDisplayName: swilliams

Body:
Inspired by Raymond Chen's post, say you have a 4x4 two dimensional array, write a function that rotates it 90 degrees. Raymond links to a solution in pseudo code, but I'd like to see some real world stuff.

[1][2][3][4]
[5][6][7][8]
[9][0][1][2]
[3][4][5][6]

Becomes:

[3][9][5][1]
[4][0][6][2]
[5][1][7][3]
[6][2][8][4]

Update: Nick's answer is the most straightforward, but is there a way to do it better than n^2? What if the matrix was 10000x10000?

LastEditorDisplayName: Jakub Šturc

OwnerDisplayName: dagorym


问:
GWT code-splitting download progressbar - like gmail
I have to use code-splitting in my project. but anyway there are some codes for initial downloading for first time.

Now I want to show to end-user the progress for code downloading (.cache.html - or other code-splitting) like gmail startup progress.

Would you please help me.

RGDS

答:
GWT doesn't have any widget like progress bar. I also wanted to add this feature to my application but I couldn't

You can use incubator progress bar.

http://google-web-toolkit-incubator.googlecode.com/svn/trunk/demo/ProgressBar/index.html


答:
values takes another argument called 'group' use that to get the related group. Is not giving the expect result you want. But gives idea.</p>

```<code>>>> Product.objects.all().values('name', 'group')
<QuerySet [
    {'group': 1, 'name': u'Product 3'},
    {'group': 2, 'name': u'Product 3'},
    {'group': 1, 'name': u'Product 2'},
    {'group': 2, 'name': u'Product 1'}]>
</code>```

Title: How do I know which groups each product is in?

Body:
values takes another argument called 'group' use that to get the related group. Is not giving the expect result you want. But gives idea.

>>> Product.objects.all().values('name', 'group')
<QuerySet [
    {'group': 1, 'name': u'Product 3'},
    {'group': 2, 'name': u'Product 3'},
    {'group': 1, 'name': u'Product 2'},
    {'group': 2, 'name': u'Product 1'}]>


问:
How can I get actual value in AndroidManifest.xml using Androguard?
I tried to use androguard to analyze apk files, but some apk's AndroidManifest.xml do not show value directly, for example

```<code><meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@7F0A02D1">
</code>```

How can I retrieve the value of "@7F0A02D1" with androguard?

Please help, thanks.

答:
I find a way to get this value:

```<code>from androguard.core.bytecodes.apk import APK

a = APK(path_to_apk)
r = a.get_android_resources()
location = int('7F0A02D1', 16)
resolved_strings = r.get_resolved_strings()
package_name = a.get_package()
value = resolved_strings.get(package_name, {}).get('DEFAULT', {}).get(location, '')
</code>```

'DEFAULT' could be other values, check it out for yourself.

Body:
I tried to use androguard to analyze apk files, but some apk's AndroidManifest.xml do not show value directly, for example

<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@7F0A02D1">

How can I retrieve the value of "@7F0A02D1" with androguard?

Please help, thanks.

Body:
I find a way to get this value:

from androguard.core.bytecodes.apk import APK

a = APK(path_to_apk)
r = a.get_android_resources()
location = int('7F0A02D1', 16)
resolved_strings = r.get_resolved_strings()
package_name = a.get_package()
value = resolved_strings.get(package_name, {}).get('DEFAULT', {}).get(location, '')

'DEFAULT' could be other values, check it out for yourself.


问:
arithmetic operations in query builder laravel
i want to prerform this query in query builder of laravel 5.4

```<code>select title, price,  price*tauxDiscount/100 as newPrice
from products p, hasdiscount pd, discounts d
WHERE p.idProd = pd.idProd
and d.idDiscount = pd.idDiscount
and now() BETWEEN dateStart and dateEnd
</code>```

so i write this

```<code>$products =  DB::table('products')
        ->join('hasDiscount', 'products.idProd', '=', 'hasDiscount.idProd')
        ->join('discounts', 'discounts.idDiscount', '=', 'hasDiscount.idDiscount')
        ->select('products.*', '(products.price * discounts.tauxDiscount / 100) as newPrice')
        ->get();
</code>```

but he show an this error

```<code>[SQLSTATE[42S22]: Column not found: 1054 Unknown column '(products.price
* discounts.tauxDiscount / 100)' in 'field list' (SQL: select
`products`.*, `(products`.`price * discounts`.`tauxDiscount / 100)` as
`newPrice` from `products` inner join `hasDiscount` on
`products`.`idProd` = `hasDiscount`.`idProd` inner join `discounts` on
`discounts`.`idDiscount` = `hasDiscount`.`idDiscount`)][1]
</code>```

答:
You need to use raw expression like that :

```<code>$products =  DB::table('products')
        ->join('hasDiscount', 'products.idProd', '=', 'hasDiscount.idProd')
        ->join('discounts', 'discounts.idDiscount', '=', 'hasDiscount.idDiscount')
        ->select(DB::raw('products.*,(products.price * discounts.tauxDiscount/100) as newPrice'))
        ->get();
</code>```

https://laravel.com/docs/5.4/queries#raw-expressions

Body:
i want to prerform this query in query builder of laravel 5.4

select title, price,  price*tauxDiscount/100 as newPrice
from products p, hasdiscount pd, discounts d
WHERE p.idProd = pd.idProd
and d.idDiscount = pd.idDiscount
and now() BETWEEN dateStart and dateEnd

so i write this

$products =  DB::table('products')
        ->join('hasDiscount', 'products.idProd', '=', 'hasDiscount.idProd')
        ->join('discounts', 'discounts.idDiscount', '=', 'hasDiscount.idDiscount')
        ->select('products.*', '(products.price * discounts.tauxDiscount / 100) as newPrice')
        ->get();

but he show an this error

[SQLSTATE[42S22]: Column not found: 1054 Unknown column '(products.price
* discounts.tauxDiscount / 100)' in 'field list' (SQL: select
`products`.*, `(products`.`price * discounts`.`tauxDiscount / 100)` as
`newPrice` from `products` inner join `hasDiscount` on
`products`.`idProd` = `hasDiscount`.`idProd` inner join `discounts` on
`discounts`.`idDiscount` = `hasDiscount`.`idDiscount`)][1]

Body:
You need to use raw expression like that :

$products =  DB::table('products')
        ->join('hasDiscount', 'products.idProd', '=', 'hasDiscount.idProd')
        ->join('discounts', 'discounts.idDiscount', '=', 'hasDiscount.idDiscount')
        ->select(DB::raw('products.*,(products.price * discounts.tauxDiscount/100) as newPrice'))
        ->get();

https://laravel.com/docs/5.4/queries#raw-expressions


问:
Integrate android project into React Native
i am new to react native...... I had a developed android project and now i want to integrate it into React Native. how can i import or migrate or integrate it into React native? any help..........!
i.e, if i run react-native run-android in command prompt my old Project have to be run. i have tried to import my entire project as a library even then it was running app folder only by default.....  In Android folder instead of app folder my_Project have to be come......

答:
React Native is great when you are starting a new mobile app from scratch. However, it also works well for adding a single view or user flow to existing native applications. With a few steps, you can add new React Native based features, screens, views, etc.

The keys to integrating React Native components into your Android application are to:

1.Understand what React Native components you want to integrate.

2.Install react-native in your Android application root directory to create node_modules/ directory.

3.Create your actual React Native components in JavaScript.

4.Add com.facebook.react:react-native:+ and a maven pointing to the react-native binaries in node_modules/ to your build.gradle file.

5.Create a custom React Native specific Activity that creates a ReactRootView.

6.Start the React Native server and run your native application.

7.Optionally add more React Native components.

8.Debug.

9.Prepare for deployment.

10.Deploy and Profit!

More Detail refereed this link http://facebook.github.io/react-native/releases/0.42/docs/integration-with-existing-apps.html#integration-with-existing-apps


问:
How to solve unrecognized arguments error?
The problem is that I can not get through the first step of running the simplest command. When I write this code

```<code>import argparse
parser = argparse.ArgumentParser()
parser.parse_args()
</code>```

an then i get this error

usage: main.py [-h]

  main.py: error: unrecognized arguments: -f

  C:\Users\Saeid\AppData\Roaming\jupyter\runtime\kernel-301e1312-128e-4c4d-9ae8-

  035b05a69a59.json

An exception has occurred, use %tb to see the full traceback.

SystemExit: 2

C:\Program Files\Anaconda3\lib\site-

  packages\IPython\core\interactiveshell.py:2889: UserWarning: To exit: use

  'exit', 'quit', or Ctrl-D.

  warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)

答: The argparse module is used to parse command line arguments. Hence, it doesn't make much sense to do so in an IPython or Jupyter notebook. The error propably stems from the fact that the notebook was invoked with an -f option.

Body:
The problem is that I can not get through the first step of running the simplest command. When I write this code

import argparse
parser = argparse.ArgumentParser()
parser.parse_args()

an then i get this error

usage: main.py [-h]

  main.py: error: unrecognized arguments: -f

  C:\Users\Saeid\AppData\Roaming\jupyter\runtime\kernel-301e1312-128e-4c4d-9ae8-

  035b05a69a59.json

An exception has occurred, use %tb to see the full traceback.

SystemExit: 2

C:\Program Files\Anaconda3\lib\site-

  packages\IPython\core\interactiveshell.py:2889: UserWarning: To exit: use

  'exit', 'quit', or Ctrl-D.

  warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)


问:
Typescript union type inference
How would I achieve type inference in the following case:</p>

```<code>type a = {
    foo: number;
    bar: string;
}

type b = {
    foo: string;
}

let baz: a | b;

if (baz.foo === 5) {
    baz.bar = "abc"; // baz type is still a | b, should be a
}
</code>```

答:
baz type is still a | b, should be a

Actually what the TypeScript compiler does is restricts property access of all unified types (a | b) to properties that exist on all of them, thus, baz.bar does not even compile because bar does not exist on type b.

Title: Typescript union type inference

Body:
How would I achieve type inference in the following case:

type a = {
    foo: number;
    bar: string;
}

type b = {
    foo: string;
}

let baz: a | b;

if (baz.foo === 5) {
    baz.bar = "abc"; // baz type is still a | b, should be a
}


问:
css class not working properly
i'm redesigning my website. and doing that i'm finding myself in some problems using the css code i wrote.

i use div's to get an image and some text next to each other.
i'm unable to get the text moved to the correct place (see pictures) the margin-left doesn't seem to work when it is in the css file but it works when directly embedded in the div tags, am i doing something wrong?

also i'dd like to add that i don't need to set the image size in the html code but its in the css code is this possible?

What i get

What i want

body
{
 background:#333 url(bg.jpg) repeat top left;
 font-family:Arial;
 color:white;
 text-align:center;
}

body header.heading
{
 width:1150px;
 /*background:transparent url(../images/menu/MEbanner.jpg) no-repeat top;
 background-size: 1150 100px;
 padding-top:101px;*/
 margin:0 auto;
 z-index:0;

}

body.Content
{
 width:1150px;
}

main
{
width:1150px;
 margin: 0 auto;
}

section
{
 text-align:left;
 margin:0 auto;
}

header nav
{
 width:1150px;
 background:transparent url(../images/menu/MEbanner.jpg) no-repeat top;
 background-size: 1150 100px;
 padding-top:101px;
 margin:0 auto;
 z-index:0;
}

header nav ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

header nav li {
    float: left;
    border-right: 1px solid #bbb;
}

header nav li:last-child {
    border-right: none;
}

/*header nav li a {
    display: block;
    color: white;
    text-align: center;
    padding: 20px 16px;
    text-decoration: none;
}*/

/* Change the link color to #111 (black) on hover */
header nav li a:hover {
    background-color: #111;
}

header nav li.active {
    background-color: #4CAF50;
}

header nav li a, .dropbtn {
    display: inline-block;
    color: white;
    text-align: center;
    padding: 20px 16px;
    text-decoration: none;
}

header nav li a:hover, .dropdown:hover .dropbtn {
    background-color:  #111;
}

header nav li.dropdown {
    display: inline-block;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
    display: block;
}

nav
{
 text-align:left;
 margin:0 auto;
}

.hidden {display:none}

hr
{
 border-left: none;
 border-right: none;
 height:4px;
 margin: 2em 0 2em 0;
}

main a:link {color:#fff;}      /* unvisited link */

main a:visited {color:#fff;}  /* visited link */

main a:hover {color:#159;}  /* mouse over link */

blockquote{
 color:white;
 border-left: 8px solid;
 border-color: #0BD676;/*#0DFF8C;*/
 padding-left:10px;
}

h2
{
 font-size: 30px;
 color:Black;
}

h1,h2,h3,h4
{
 font-family: 'Open Sans Condensed', sans-serif;
 color:#4CAF50;
 text-decoration:underline;
}

h2, h3
{
 font-size: 1.6em;
 letter-spacing: -1px;
 margin: 0 0 0.75em 0;
}

h3
{
 font-size:1.3em;
}

h1
{
 font:bold;
}

h4
{
 font-size:1em;
 margin: 0.5em 0 0.5em;
 padding-left:1em;
}

.green
{
 border-left: 8px solid;
 border-color: #0BD676;/*#0DFF8C;*/
 padding-left:10px;
 color: #4CAF50;
 margin-left:40px;
 font-style:oblique;
}

article.centeralign
{
 text-align:center;
}

div.wrapper{
 width: 800px;
 overflow: hidden;
}

div.toolsWrapper{
 width: 980px;
 overflow: hidden;
}

div.left{
    width: 200px;
    float:left;
    margin-right:40px;
    padding-left:40px;
}

div.right{
    float:left;
    margin-left: 20px;
}

div.cc
 {
  width:200px;
  text-align:right;
  font-size:10px;
 }

div.ccf
 {
  text-align:center;
  font-size:12px;
 }

iframe
{
 text-align:center;
 float:center;
}

/* ===========================
   ====== Contact Form =======
   =========================== */

input, textarea {
 padding: 10px;
 border: 1px solid #E5E5E5;
 width: 200px;
 color: #999999;
 box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
 -moz-box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
 -webkit-box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
}

textarea {
 width: 400px;
 height: 150px;
 max-width: 400px;
 line-height: 18px;
}

input:hover, textarea:hover,
input:focus, textarea:focus {
 border-color: 1px solid #C9C9C9;
 box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
 -moz-box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
 -webkit-box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
}

.form label {
 margin-left: 10px;
 color: #999999;
}

/* ===========================
   ====== Submit Button ======
   =========================== */

.submit input {
 width: 100px;
 height: 40px;
 background-color: #474E69;
 color: #FFF;
 border-radius: 3px;
 -moz-border-radius: 3px;
 -webkit-border-radius: 3px;
}

table, th, td {
    border: 1px solid black;
    border-color:white;
}

th, td {
    padding: 15px;
}

.blue{
  background: url(blue.png) no-repeat left center;
    color: #109CEF;
    padding: 0px 40px 0px 20px;
  font-style:oblique;
 }

.red{
  background: url(red.png) no-repeat left center;
  color:#FF0000;
  padding: 0px 40px 0px 20px;
  font-style:oblique;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><article>
  <h1>Audio Projects</h1>
    <blockquote>
     <h3>

              Class D Amplifier

      </h3>
      <div class="wrapper">
          <div class="left">
              <img src="Damp/Damp_front.JPG"/>
          </div>
          <div class="right">
              Some text that should be next to image
          </div>
      </div>
  </blockquote>
</article></code>```

答:
You just need to change a few styles, and replace the
 with a
 (For IE support)

div.wrapper {
  width: 800px;
  overflow: hidden;
}
div.toolsWrapper {
  width: 980px;
  overflow: hidden;
}
div.left {
  width: 200px;
  float: left;
  margin-right: 40px;
  padding-left: 40px;
}
div.right {
  color: white;
  display: inline-block;
  position: absolute;
  top: 0;
}
.wrapper {
  position: relative;
  width: 50%;
}
.title {
  color: #4B9F49;
}
.inner_title {
  color: white;
}
.blockquote {
  border-left: 3px solid #0CD673;
  padding-left: 5px;
}
#article {
  background: black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="article">
  <h3>
    Audio Projects
  </h3>
  <blockquote class="blockquote">
    <h3>
      Class D Amplifier
    </h3>
    <div class="wrapper">
      <img src="Damp/Damp_front.JPG" style="height:80px; width:200px;"/>
      <div class="right">
        Some text that is now next to the image.
      </div>
    </div>
  </blockquote>
</div></code>```

Title: css class not working properly

Body:
i'm redesigning my website. and doing that i'm finding myself in some problems using the css code i wrote.

i use div's to get an image and some text next to each other.
i'm unable to get the text moved to the correct place (see pictures) the margin-left doesn't seem to work when it is in the css file but it works when directly embedded in the div tags, am i doing something wrong?

also i'dd like to add that i don't need to set the image size in the html code but its in the css code is this possible?

What i get

What i want

body
{
 background:#333 url(bg.jpg) repeat top left;
 font-family:Arial;
 color:white;
 text-align:center;
}

body header.heading
{
 width:1150px;
 /*background:transparent url(../images/menu/MEbanner.jpg) no-repeat top;
 background-size: 1150 100px;
 padding-top:101px;*/
 margin:0 auto;
 z-index:0;

}

body.Content
{
 width:1150px;
}

main
{
width:1150px;
 margin: 0 auto;
}

section
{
 text-align:left;
 margin:0 auto;
}

header nav
{
 width:1150px;
 background:transparent url(../images/menu/MEbanner.jpg) no-repeat top;
 background-size: 1150 100px;
 padding-top:101px;
 margin:0 auto;
 z-index:0;
}

header nav ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

header nav li {
    float: left;
    border-right: 1px solid #bbb;
}

header nav li:last-child {
    border-right: none;
}

/*header nav li a {
    display: block;
    color: white;
    text-align: center;
    padding: 20px 16px;
    text-decoration: none;
}*/

/* Change the link color to #111 (black) on hover */
header nav li a:hover {
    background-color: #111;
}

header nav li.active {
    background-color: #4CAF50;
}

header nav li a, .dropbtn {
    display: inline-block;
    color: white;
    text-align: center;
    padding: 20px 16px;
    text-decoration: none;
}

header nav li a:hover, .dropdown:hover .dropbtn {
    background-color:  #111;
}

header nav li.dropdown {
    display: inline-block;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
    display: block;
}

nav
{
 text-align:left;
 margin:0 auto;
}

.hidden {display:none}

hr
{
 border-left: none;
 border-right: none;
 height:4px;
 margin: 2em 0 2em 0;
}

main a:link {color:#fff;}      /* unvisited link */

main a:visited {color:#fff;}  /* visited link */

main a:hover {color:#159;}  /* mouse over link */

blockquote{
 color:white;
 border-left: 8px solid;
 border-color: #0BD676;/*#0DFF8C;*/
 padding-left:10px;
}

h2
{
 font-size: 30px;
 color:Black;
}

h1,h2,h3,h4
{
 font-family: 'Open Sans Condensed', sans-serif;
 color:#4CAF50;
 text-decoration:underline;
}

h2, h3
{
 font-size: 1.6em;
 letter-spacing: -1px;
 margin: 0 0 0.75em 0;
}

h3
{
 font-size:1.3em;
}

h1
{
 font:bold;
}

h4
{
 font-size:1em;
 margin: 0.5em 0 0.5em;
 padding-left:1em;
}

.green
{
 border-left: 8px solid;
 border-color: #0BD676;/*#0DFF8C;*/
 padding-left:10px;
 color: #4CAF50;
 margin-left:40px;
 font-style:oblique;
}

article.centeralign
{
 text-align:center;
}

div.wrapper{
 width: 800px;
 overflow: hidden;
}

div.toolsWrapper{
 width: 980px;
 overflow: hidden;
}

div.left{
    width: 200px;
    float:left;
    margin-right:40px;
    padding-left:40px;
}

div.right{
    float:left;
    margin-left: 20px;
}

div.cc
 {
  width:200px;
  text-align:right;
  font-size:10px;
 }

div.ccf
 {
  text-align:center;
  font-size:12px;
 }

iframe
{
 text-align:center;
 float:center;
}

/* ===========================
   ====== Contact Form =======
   =========================== */

input, textarea {
 padding: 10px;
 border: 1px solid #E5E5E5;
 width: 200px;
 color: #999999;
 box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
 -moz-box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
 -webkit-box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
}

textarea {
 width: 400px;
 height: 150px;
 max-width: 400px;
 line-height: 18px;
}

input:hover, textarea:hover,
input:focus, textarea:focus {
 border-color: 1px solid #C9C9C9;
 box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
 -moz-box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
 -webkit-box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
}

.form label {
 margin-left: 10px;
 color: #999999;
}

/* ===========================
   ====== Submit Button ======
   =========================== */

.submit input {
 width: 100px;
 height: 40px;
 background-color: #474E69;
 color: #FFF;
 border-radius: 3px;
 -moz-border-radius: 3px;
 -webkit-border-radius: 3px;
}

table, th, td {
    border: 1px solid black;
    border-color:white;
}

th, td {
    padding: 15px;
}

.blue{
  background: url(blue.png) no-repeat left center;
    color: #109CEF;
    padding: 0px 40px 0px 20px;
  font-style:oblique;
 }

.red{
  background: url(red.png) no-repeat left center;
  color:#FF0000;
  padding: 0px 40px 0px 20px;
  font-style:oblique;
}

Audio Projects

              Class D Amplifier

              Some text that should be next to image

Body:
You just need to change a few styles, and replace the <article> with a <div> (For IE support)

div.wrapper {
  width: 800px;
  overflow: hidden;
}
div.toolsWrapper {
  width: 980px;
  overflow: hidden;
}
div.left {
  width: 200px;
  float: left;
  margin-right: 40px;
  padding-left: 40px;
}
div.right {
  color: white;
  display: inline-block;
  position: absolute;
  top: 0;
}
.wrapper {
  position: relative;
  width: 50%;
}
.title {
  color: #4B9F49;
}
.inner_title {
  color: white;
}
.blockquote {
  border-left: 3px solid #0CD673;
  padding-left: 5px;
}
#article {
  background: black;
}

<div id="article">
  <h3>
    <a href="Damp" class="title">Audio Projects</a>
  </h3>
  <blockquote class="blockquote">
    <h3>
      <a href="Damp" class="inner_title">Class D Amplifier</a>
    </h3>
    <div class="wrapper">
      <img src="Damp/Damp_front.JPG" style="height:80px; width:200px;"/>
      <div class="right">
        Some text that is now next to the image.
      </div>
    </div>
  </blockquote>
</div>


问:
How to use page.php?id={id} routes on laravel
I'm rewriting an website in laravel, and for the sake of the SEO, I have to create some routes that will do a 301 redirect in case the visitor get to access the old style links of the website:

Using Laravel 5.4 + PHP 7.0

For example:

Old links: www.website.com/category.php?category={id}

will redirect to:

New Link: www.website.com/category/{category-name}

But when I create a route like this on laravel, it doesn't work:

```<code>Route::get('/category.php?category={id}', function ($id) {
 // Old route style, search new route and do the redirect.
});
</code>```

If I remove the "?" it kinda works, but then it won't target my old links, cause there's no "?" in the url.

Is this supported on laravel ?

If it isn't, what would be a good way to achieve this?

答:
Htaccess is your friend in this case. You can create a 301 redirect from your old category base to the new like so:</p>

```<code>RewriteEngine on
RewriteBase /
RewriteRule ^category.php?category=(.*) http://www.website.com/category/$1 [R=301,L]
</code>```

Body:
I'm rewriting an website in laravel, and for the sake of the SEO, I have to create some routes that will do a 301 redirect in case the visitor get to access the old style links of the website:

Using Laravel 5.4 + PHP 7.0

For example:

Old links: www.website.com/category.php?category={id}

will redirect to:

New Link: www.website.com/category/{category-name}

But when I create a route like this on laravel, it doesn't work:

Route::get('/category.php?category={id}', function ($id) {
 // Old route style, search new route and do the redirect.
});

If I remove the "?" it kinda works, but then it won't target my old links, cause there's no "?" in the url.

Is this supported on laravel ?

If it isn't, what would be a good way to achieve this?

Body:
Htaccess is your friend in this case. You can create a 301 redirect from your old category base to the new like so:

RewriteEngine on
RewriteBase /
RewriteRule ^category.php?category=(.*) http://www.website.com/category/$1 [R=301,L]


问:
Deterministic API call results in the redux store
I have a deterministic API call to calculate IncomeTax which always returns the same values when supplied with a particular input.

Is it better practise to put the result of this API call in the redux store or should I use a caching library like redux-reselect.

答:
This is almost the perfect use-case for a selector library such as reselect.

You should retrieve your calculated value via a selector getter that takes the input values. This will call api and cache the result based on the input values and, if those values change, the api will fetch the new value and cache it too.

If you use react then you should make sure you store your inputs in redux-state. That way should the state values be changed then the getter will be automatically called and the new (or previously cached) calculated value retrieved.


问:
Display custom post type in desired order
I am using following code to get all the registered custom post types. But along with that i want to display them in desired order like in the order I registered them.</p>

```<code>$custom_post_types = get_post_types(
    array(
        '_builtin' => false,
        'public'   => true
        ),
    'objects'
    );

ksort( $custom_post_types, SORT_ASC );
</code>```

答:
```<code><?php
$args = array( 'post_type' => 'custom_type_name', 'posts_per_page' => 50 'orderby' => 'date',
      'order' => 'ASC');
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$thumb = wp_get_attachment_image_src( get_post_thumbnail_id($loop->ID), 'full' );
$url = $thumb['0'];
?>
<a href="<?php echo get_the_permalink(); ?>">
<img src="<?php echo $url ?>" alt="<?php the_title(); ?>" class="img-responsive" width="100%"/></a>
<h3><a href="<?php echo get_the_permalink(); ?>"> <?php the_title(); ?></a></h3>
<p><a href="<?php echo get_the_permalink(); ?>" class="hvr-bounce-to-top redbtn"> Read More</a></p>
<?php endwhile; ?>
</code>```

Body:
I am using following code to get all the registered custom post types. But along with that i want to display them in desired order like in the order I registered them.

$custom_post_types = get_post_types(
    array(
        '_builtin' => false,
        'public'   => true
        ),
    'objects'
    );

ksort( $custom_post_types, SORT_ASC );