问:
Autofilling forms using WebView from android
I am using a WebView to try to fill a form using data that I am sending.

```<code>WebView webView;
String url = "http://139.59.34.30/quotation/";
String btn_ci, btn_co, n, a, k, r, m;
Intent in;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_web);
    webView = (WebView) findViewById(R.id.webview);
    in = getIntent();
    btn_ci = in.getStringExtra("checkin");
    btn_co = in.getStringExtra("checkout");
    n = in.getStringExtra("name");
    a = in.getStringExtra("adults");
    k = in.getStringExtra("kids");
    r = in.getStringExtra("rooms");
    m = in.getStringExtra("mail");
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebViewClient(new WebViewClient() {
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            view.loadUrl("javascript:document.getElementsByName('name').value = '"+n+
                    "';document.getElementsByName('checkin').value='"+ btn_ci +
                    "';document.getElementsByName('checkout').value='"+ btn_co +
                    "';document.getElementsByName('no_of_pax').value='"+ a +
                    "';document.getElementsByName('no_of_kid').value='"+ k +
                    "';document.getElementsByName('no_of_rooms').value='"+ r +"';");
        }
    });
    webView.loadUrl(url);
</code>```

But every time the activity executes the page loads for a while with no values filled in and then it just displays the last String I had passed.

答:
Instead of your code inside onPageFinished, you can use the follow code, it will work on all Android API versions,</p>

```<code>        final String js = "javascript: " +
                "var nameDoc = document.getElementsByName('name');" +
                "nameDoc[0].value = '"+n+ "';" +
                "var checkOutDoc = document.getElementsByName('checkout');" +
                "checkOutDoc[0].value = '"+btn_co+ "';" +
                "var noOFPaxDoc = document.getElementsByName('no_of_pax');" +
                "noOFPaxDoc[0].value = '"+a+ "';" + // a should be int based on ur HTML
                "var noOFKidDoc = document.getElementsByName('no_of_kid');" +
                "noOFKidDoc[0].value = '"+k+ "';" + // a should be int based on ur HTML
                "var noOFRoomsDoc = document.getElementsByName('no_of_rooms');" +
                "noOFRoomsDoc[0].value = '"+r+ "';" + // a should be int based on ur HTML
                "var checkInDoc = document.getElementsByName('checkin');" +
                "checkInDoc[0].value = '"+btn_ci+ "';";

        if (Build.VERSION.SDK_INT >= 19) {
            view.evaluateJavascript(js, new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String s) {

                }
            });
        } else {
            view.loadUrl(js);
        }
</code>```

Body:
I am using a WebView to try to fill a form using data that I am sending.

WebView webView;
String url = "http://139.59.34.30/quotation/";
String btn_ci, btn_co, n, a, k, r, m;
Intent in;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_web);
    webView = (WebView) findViewById(R.id.webview);
    in = getIntent();
    btn_ci = in.getStringExtra("checkin");
    btn_co = in.getStringExtra("checkout");
    n = in.getStringExtra("name");
    a = in.getStringExtra("adults");
    k = in.getStringExtra("kids");
    r = in.getStringExtra("rooms");
    m = in.getStringExtra("mail");
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebViewClient(new WebViewClient() {
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            view.loadUrl("javascript:document.getElementsByName('name').value = '"+n+
                    "';document.getElementsByName('checkin').value='"+ btn_ci +
                    "';document.getElementsByName('checkout').value='"+ btn_co +
                    "';document.getElementsByName('no_of_pax').value='"+ a +
                    "';document.getElementsByName('no_of_kid').value='"+ k +
                    "';document.getElementsByName('no_of_rooms').value='"+ r +"';");
        }
    });
    webView.loadUrl(url);

But every time the activity executes the page loads for a while with no values filled in and then it just displays the last String I had passed.

Body:
Instead of your code inside onPageFinished, you can use the follow code, it will work on all Android API versions,

        final String js = "javascript: " +
                "var nameDoc = document.getElementsByName('name');" +
                "nameDoc[0].value = '"+n+ "';" +
                "var checkOutDoc = document.getElementsByName('checkout');" +
                "checkOutDoc[0].value = '"+btn_co+ "';" +
                "var noOFPaxDoc = document.getElementsByName('no_of_pax');" +
                "noOFPaxDoc[0].value = '"+a+ "';" + // a should be int based on ur HTML
                "var noOFKidDoc = document.getElementsByName('no_of_kid');" +
                "noOFKidDoc[0].value = '"+k+ "';" + // a should be int based on ur HTML
                "var noOFRoomsDoc = document.getElementsByName('no_of_rooms');" +
                "noOFRoomsDoc[0].value = '"+r+ "';" + // a should be int based on ur HTML
                "var checkInDoc = document.getElementsByName('checkin');" +
                "checkInDoc[0].value = '"+btn_ci+ "';";

        if (Build.VERSION.SDK_INT >= 19) {
            view.evaluateJavascript(js, new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String s) {

                }
            });
        } else {
            view.loadUrl(js);
        }


来源: stackexchange

问:
Running Laravel queue work daemon with nohup causes PDOException "General error: 1205 Lock wait timeout exceeded"
I made a Laravel app that uses the queue system (via database) to send emails. These emails are Job instances and are pushed to the queue after a cron-job is complete every 3 minutes or so.

If I run the artisan command

```<code>/path_to_php/7.1/bin/php artisan queue:work --queue=emails_1--tries=2 --daemon
</code>```

in the terminal via SSH, it starts processing the jobs and sending emails. Obviously I would like to run this command and exit the terminal with it still running so I used the "nohup" approach.

```<code>nohup /path_to_php/7.1/bin/php artisan queue:work --queue=emails_1--tries=2 --daemon > storage/logs/laravel.log &
</code>```

After running this I get a PDOException:

```<code>PDOException: SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction in ...
</code>```

I'm not really familiar with this error as I've never encountered something like this before but why can't I run the queue work command using nohup but can run it without problems without nohup? Any ideas as to why this is happening ? I'm using Laravel 5.2.

Please enlighten me. Thanks a lot.

答:
Don't use the database queue driver in production. Try to avoid using the database queue driver when you're having a large queue, it's recommended that you use something like Redis which doesn't have the deadlock problems a database-based driver has.

Do you have additional info at Laravel Github: https://github.com/laravel/framework/issues/19242#issuecomment-302505260

ContentLicense: CC BY-SA 3.0

Body:
I made a Laravel app that uses the queue system (via database) to send emails. These emails are Job instances and are pushed to the queue after a cron-job is complete every 3 minutes or so.

If I run the artisan command

/path_to_php/7.1/bin/php artisan queue:work --queue=emails_1--tries=2 --daemon

in the terminal via SSH, it starts processing the jobs and sending emails. Obviously I would like to run this command and exit the terminal with it still running so I used the "nohup" approach.

nohup /path_to_php/7.1/bin/php artisan queue:work --queue=emails_1--tries=2 --daemon > storage/logs/laravel.log &

After running this I get a PDOException:

PDOException: SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction in ...

I'm not really familiar with this error as I've never encountered something like this before but why can't I run the queue work command using nohup but can run it without problems without nohup? Any ideas as to why this is happening ? I'm using Laravel 5.2.

Please enlighten me. Thanks a lot.


问:
How to programmatically check whether a library dependent program can run in a Linux system?
I am having a program(binary) which depends upon libraries such as pthread, sqlite3,libcrypto and libcurl.I want to run this program in multiple user PCs.How to programmatically check whether the dependencies are met, before installing the binary?

./configure cannot be be used as it is for the purpose of building the program as mentioned in , Making os independent configure file which checks for curl dependency.
If I am not wrong .deb and .rpm have there own methods for this.

Can anybody please tell me what is the method they are following for this.Is it just a file name check? For example,if I have build the program using libcurl.so.3, whether it checks that the system in which it will be running is having libcurl.so.3 as a regular file or a simulink.Or any other check is there for the libraries?

What is the reliable method for checking the dependencies, while installing and running a binary?

答:
RPM will automatically detect used libraries and put needed Requires into final RPM package. You can check it using:

```<code>rpm -qpR foo.rpm
</code>```

and it should print something like:

```<code>libc.so.6(GLIBC_2.8)(64bit)
libdl.so.2()(64bit)
</code>```

Body:
RPM will automatically detect used libraries and put needed Requires into final RPM package. You can check it using:

rpm -qpR foo.rpm

and it should print something like:

libc.so.6(GLIBC_2.8)(64bit)
libdl.so.2()(64bit)


答:
PHP has a custom sort option.  Try this:
http://php.net/manual/en/function.usort.php

I haven't used it but I had found it previously and remember it existed.

Title: How to sort this type of complex 3d array in php

Body:
The array is like this (I am using PHP)

array(2){[0]=>
             {[0]=>"DEF"=>
                       {[0]=>"a",[1]=>"c",[2]=>"b"},
              [1]=>"ABC"=>
                      {[0]=>"f",[1]=>"d",[2]=>"e"}},
        [1]=>
            {[0]=>"DEF"=>
                      {[0]=>"h",[1]=>"i",[2]=>"g"},
             [1]=>"ABC"=>
                      {[0]=>"k",[1]=>"l",[2]=>"j"}
            }
        }

I wish to be sort it like the first entry i.e. [0] index has two entries DEF and ABC so it should be sorted ABC and DEF then in ABC also a b c should be sorted.

The final result should be this

array(2){[0]=>
             {[0]=>"ABC"=>
                       {[0]=>"d",[1]=>"e",[2]=>"f"},
              [1]=>"DEF"=>
                      {[0]=>"a",[1]=>"b",[2]=>"c"}},
        [1]=>
            {[0]=>"ABC"=>
                      {[0]=>"j",[1]=>"k",[2]=>"l"},
             [1]=>"DEF"=>
                      {[0]=>"g",[1]=>"h",[2]=>"i"}
            }
        }

Thanks in advance


问:
Divide and conquer algorithm
I had a job interview a few weeks ago and I was asked to design a divide and conquer algorithm. I could not solve the problem, but they just called me for a second interview! Here is the question:

we are giving as input two n-element arrays A[0..n − 1] and B[0..n − 1] (which
are not necessarily sorted) of integers, and an integer value. Give an O(nlogn) divide and conquer algorithm that determines if there exist distinct values i, j (that is, i != j) such that A[i] + B[j] = value. Your algorithm should return True if i, j exists, and return False otherwise. You may assume that the elements in A are distinct, and the elements in B are distinct.

can anybody solve the problem? Thanks

答:
Seems hard to achieve without sorting.

If you leave the arrays unsorted, checking for existence of A[i]+B[j] = Value takes time Ω(n) for fixed i, then checking for all i takes Θ(n²), unless you find a trick to put some order in B.

Balanced Divide & Conquer on the unsorted arrays doesn't seem any better: if you divide A and B in two halves, the solution can lie in one of Al/Bl, Al/Br, Ar/Bl, Ar/Br and this yields a recurrence T(n) = 4 T(n/2), which has a quadratic solution.

If sorting is allowed, the solution by Sanket Makani is a possibility but you do better in terms of time complexity for the search phase.

Indeed, assume A and B now sorted and consider the 2D function A[i]+B[j], which is monotonic in both directions i and j. Then the domain A[i]+B[j] ≤ Value is limited by a monotonic curve j = f(i) or equivalently i = g(j). But strict equality A[i]+B[j] = Value must be checked exhaustively for all points of the curve and one cannot avoid to evaluate f everywhere in the worst case.

Starting from i = 0, you obtain f(i) by dichotomic search. Then you can follow the border curve incrementally. You will perform n step in the i direction, and at most n steps in the j direction, so that the complexity remains bounded by O(n), which is optimal.

Below, an example showing the areas with a sum below and above the target value (there are two matches).

This optimal solution has little to do with Divide & Conquer. It is maybe possible to design a variant based on the evaluation of the sum at a central point, which allows to discard a whole quadrant, but that would be pretty artificial.

Title: Divide and conquer algorithm


问:
CSS3 center triangle on hover HTML
I am trying to center my css triangle to the middle of each navigation item when I hover over it. At the moment the triangle is under the front letter of each item. How do i do this?

If i remove position: absolute, it removes my triangle shape. How can i fix this?

.current {
  color: #FFF;
  text-decoration: underline;
}

nav a:hover:after {
  content: "";
  display: block;
  border: 8px solid #405580;
  border-bottom-color: #fff;
  position: absolute;
  bottom: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>

  <nav>

    <ul>
      <li>Home</li>
      <li>A</li>
      <li>B</li>
      <li>C</li>
      <li>D</li>
      <li>Contact</li>
    </ul>
  </nav>
</header></code>```

答:
You can try making your  relative and then making your nav a :hover :after relative. I've added margin-top to push the arrow down, its up to you now to figure out some way to do that, withoout hardcoding it. :)

```<code>a {
 color: #FFF;
 text-decoration: none;
 font-weight: bold;
 position: relative;
}

nav a:hover:after {
    content: "";
    display: block;
    border: 8px solid #405580;
    border-bottom-color: #fff;
    position: absolute;
    left:33%;
    margin-top: 5px;
}
</code>```

https://codepen.io/daveRanjan/pen/yXyWwR

Title: CSS3 center triangle on hover HTML

Body:
I am trying to center my css triangle to the middle of each navigation item when I hover over it. At the moment the triangle is under the front letter of each item. How do i do this?

If i remove position: absolute, it removes my triangle shape. How can i fix this?

.current {
  color: #FFF;
  text-decoration: underline;
}

nav a:hover:after {
  content: "";
  display: block;
  border: 8px solid #405580;
  border-bottom-color: #fff;
  position: absolute;
  bottom: 0px;
}

Home

A

B

C

D

Contact

Body:
You can try making your <a> relative and then making your nav a :hover :after relative. I've added margin-top to push the arrow down, its up to you now to figure out some way to do that, withoout hardcoding it. :)

a {
 color: #FFF;
 text-decoration: none;
 font-weight: bold;
 position: relative;
}

nav a:hover:after {
    content: "";
    display: block;
    border: 8px solid #405580;
    border-bottom-color: #fff;
    position: absolute;
    left:33%;
    margin-top: 5px;
}

https://codepen.io/daveRanjan/pen/yXyWwR


问:
NullPointerException accessing views in onCreate()
This is a canonical question for a problem frequently posted on StackOverflow.

I'm following a tutorial. I've created a new activity using a wizard. I get NullPointerException when attempting to call a method on Views obtained with findViewById() in my activity onCreate().

Activity onCreate():

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

    View something = findViewById(R.id.something);
    something.setOnClickListener(new View.OnClickListener() { ... }); // NPE HERE

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }
}
</code>```

Layout XML (fragment_main.xml):

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="packagename.MainActivity$PlaceholderFragment" >

    <View
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:id="@+id/something" />

</RelativeLayout>
</code>```

答:
The view "something" is in fragment and not in activity, so instead of accessing it in activity you must access it in the fragment class like

In PlaceholderFragment.class

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_main, container,
  false);

View something = root .findViewById(R.id.something);
something.setOnClickListener(new View.OnClickListener() { ... });

return root;
}
</code>```

Body:
This is a canonical question for a problem frequently posted on StackOverflow.

I'm following a tutorial. I've created a new activity using a wizard. I get NullPointerException when attempting to call a method on Views obtained with findViewById() in my activity onCreate().

Activity onCreate():

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

    View something = findViewById(R.id.something);
    something.setOnClickListener(new View.OnClickListener() { ... }); // NPE HERE

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }
}

Layout XML (fragment_main.xml):

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="packagename.MainActivity$PlaceholderFragment" >

    <View
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:id="@+id/something" />

</RelativeLayout>

Body:
The view "something" is in fragment and not in activity, so instead of accessing it in activity you must access it in the fragment class like

In PlaceholderFragment.class

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_main, container,
  false);

View something = root .findViewById(R.id.something);
something.setOnClickListener(new View.OnClickListener() { ... });

return root;
}


问:
Convert single-quoted string to double-quoted string
I want to check whether the given string is single- or double-quoted. If it is single quote I want to convert it to be double quote, else it has to be same double quote.</p>

答:
Sounds like you are working with JSON. I would just make sure it is always a double quoted like this:

```<code>doubleQString = "{0}".format('my normal string')
with open('sampledict.json','w') as f:
    json.dump(doubleQString ,f)
</code>```

Notice I'm using dump, not dumps.

Sampledict.json will look like this:

```<code>"my normal string"
</code>```

Body:
Sounds like you are working with JSON. I would just make sure it is always a double quoted like this:

doubleQString = "{0}".format('my normal string')
with open('sampledict.json','w') as f:
    json.dump(doubleQString ,f)

Notice I'm using dump, not dumps.

Sampledict.json will look like this:

"my normal string"

ContentLicense: CC BY-SA 4.0


问:
How do I upload a file with the Azure IoT Device sdk
I'm trying to use the Java Azure IoT device client sdk (v1.2.28) to upload files to blob storage. The examples show how to do this with the .net sdk but it seems like the same methods in the DeviceClient class don't exist in the java sdk. Is it not possible yet with the java sdk?

https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-csharp-csharp-file-upload

答:
I reviewed the javadocs of Azure IoT device SDK, as you said, there is not a method to upload file to blob storage.

Accoring to the document File uploads with IoT Hub and the related REST API Create File Upload Sas Uri, the feature is required the blob sas uri, so only using IoT device SDK for Java is not possible, you need to use Azure Storage Java SDK to generate a blob sas uri first to call the REST API to do it.

However, for the other feature to receive file upload notification, there are some classes of Azure IoT service SDK for Java to support, which include FileUploadNotification, FileUploadNotificationReceiver, etc.


问:
Dealing with flexbox while changing an element
I have a problem with styling my bar, which works on flexbox.

bar

As you can see, there is three divs inside: one sticked to the left border and another sticked to right border; there is also a small div in the middle showing the amount of comments (80px) and I want it to go left and stick to the div on left. Is it a chance to manage this with flexbox, without changing for display: inline-block?

The bar has a class .article__metas.
The div in the middle is .social_item.

```<code><div class="article__metas">
    <div class="item date">
        //showing date
    </div>
    <div class="seperator"></div>
    <?php
    /**
    $clist = get_the_category_list(', ');
    if (!empty($clist)) {
        ?>
        <div class="item categories">
            <?php
            echo $clist;
            ?>
        </div>
        <div class="seperator separator-categories"></div>
    <?php } */
    ?>
    <?php
    $share = $app->getPostStats();
    if ($share->comment_count > 0 || $share->share_count > 0):?>
        <div class="item social_item">
            <?php
            if ($share->comment_count > 0) {
                echo '<span>';
                echo '<img src="' . _img_url('comment.svg') . '"/>';
                echo '<span class="amount">' . $share->comment_count . '</span>';
                echo '</span>';
            }
            if ($share->share_count > 0) {
                echo '<span>';
                echo '<img src="' . _img_url('share.svg') . '"/>';
                echo '<span class="amount">' . $share->share_count . '</span>';
                echo '</span>';
            }

            ?>
        </div>
    <?php endif; ?>
    <?php get_template_part('inc/article/share'); ?>
</div>
</code>```

And Sass:

```<code>.article__metas {
  color: #888888;
  font-size: 12px;
  display: flex;
  border-bottom: 1px solid #e5e5e5;
  justify-content: space-between;
  @include link-color('a', '#888');

  a:hover {
    text-decoration: underline;
  }
  .item {
    padding: 20px;
    &:first-child {
      padding-left: $cards_left;
    }
  }
  .seperator {
    display: block;
    align-self: stretch;
    width: 1px;
    background-color: #e5e5e5;
  }
  .social_item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    span + span {
      margin-left: 20px;

    }
    & > span {
      display: block;
      white-space: nowrap;
      img {
        width: 16px;
        display: inline-block;
      }
    }
    img {
      margin-top: 2px;
      margin-right: 9px;
    }
  }

}
</code>```

Thank you in advance!

答:
Please check if this is what you need. SCSS doesn't work here, so you need to copy to your own environment.

.ariticle__metas is now aligned left and .social_item has a margin-left:auto

Fiddle here

.article__metas {
  color: #888888;
  font-size: 12px;
  display: flex;
  border-bottom: 1px solid #e5e5e5;
  justify-content: left;
  @include link-color('a', '#888');
  a:hover {
    text-decoration: underline;
  }
  .item {
    padding: 20px;
    &:first-child {
      padding-left: 10px;
    }
  }
  .seperator {
    display: block;
    align-self: stretch;
    width: 1px;
    background-color: #e5e5e5;
  }
  .social_item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-left: auto;
    span + span {
      margin-left: 20px;
    }
    & > span {
      display: block;
      white-space: nowrap;
      margin-right: 10px;
      img {
        width: 16px;
        display: inline-block;
      }
    }
    img {
      margin-top: 2px;
      margin-right: 9px;
    }
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="article__metas">
  <div class="item">Dodano 18.04.2016</div>
  <div class="seperator"></div>
  <div class="item">1</div>
  <div class="seperator"></div>
  <div class="social_item">
    <span>Spodobal Ci</span>
    <img src="http://placehold.it/15" />
    <img src="http://placehold.it/15" />
    <img src="http://placehold.it/15" />
    <img src="http://placehold.it/15" />
  </div>
</div></code>```

Body:
I have a problem with styling my bar, which works on flexbox.

bar

As you can see, there is three divs inside: one sticked to the left border and another sticked to right border; there is also a small div in the middle showing the amount of comments (80px) and I want it to go left and stick to the div on left. Is it a chance to manage this with flexbox, without changing for display: inline-block?

The bar has a class .article__metas.
The div in the middle is .social_item.

        //showing date

    <?php
    /**
    $clist = get_the_category_list(', ');
    if (!empty($clist)) {
        ?>

            <?php
            echo $clist;
            ?>

    <?php } */
    ?>
    <?php
    $share = $app->getPostStats();
    if ($share->comment_count > 0 || $share->share_count > 0):?>

            <?php
            if ($share->comment_count > 0) {
                echo '';
                echo '';
                echo '' . $share->comment_count . '';
                echo '';
            }
            if ($share->share_count > 0) {
                echo '';
                echo '';
                echo '' . $share->share_count . '';
                echo '';
            }

            ?>

    <?php endif; ?>
    <?php get_template_part('inc/article/share'); ?>

And Sass:

.article__metas {
  color: #888888;
  font-size: 12px;
  display: flex;
  border-bottom: 1px solid #e5e5e5;
  justify-content: space-between;
  @include link-color('a', '#888');

  a:hover {
    text-decoration: underline;
  }
  .item {
    padding: 20px;
    &:first-child {
      padding-left: $cards_left;
    }
  }
  .seperator {
    display: block;
    align-self: stretch;
    width: 1px;
    background-color: #e5e5e5;
  }
  .social_item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    span + span {
      margin-left: 20px;

    }
    & > span {
      display: block;
      white-space: nowrap;
      img {
        width: 16px;
        display: inline-block;
      }
    }
    img {
      margin-top: 2px;
      margin-right: 9px;
    }
  }

}

Thank you in advance!

Body:
Please check if this is what you need. SCSS doesn't work here, so you need to copy to your own environment.

.ariticle__metas is now aligned left and .social_item has a margin-left:auto

Fiddle here

.article__metas {
  color: #888888;
  font-size: 12px;
  display: flex;
  border-bottom: 1px solid #e5e5e5;
  justify-content: left;
  @include link-color('a', '#888');
  a:hover {
    text-decoration: underline;
  }
  .item {
    padding: 20px;
    &:first-child {
      padding-left: 10px;
    }
  }
  .seperator {
    display: block;
    align-self: stretch;
    width: 1px;
    background-color: #e5e5e5;
  }
  .social_item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-left: auto;
    span + span {
      margin-left: 20px;
    }
    & > span {
      display: block;
      white-space: nowrap;
      margin-right: 10px;
      img {
        width: 16px;
        display: inline-block;
      }
    }
    img {
      margin-top: 2px;
      margin-right: 9px;
    }
  }
}

<div class="article__metas">
  <div class="item">Dodano 18.04.2016</div>
  <div class="seperator"></div>
  <div class="item">1</div>
  <div class="seperator"></div>
  <div class="social_item">
    <span>Spodobal Ci</span>
    <img src="http://placehold.it/15" />
    <img src="http://placehold.it/15" />
    <img src="http://placehold.it/15" />
    <img src="http://placehold.it/15" />
  </div>
</div>


问:
How model class "Name" becomes plural "Names" under Admin Page?
In Django's tutorial, a models.py class is created named "Question" (singular).  It is also registered to be included within the Admin Page using  admin.site.register(Question) (singular)

But then under the Admin Page, it's listed as "Questions" (plural)

Is Django automatically renaming things under the Admin Page to be grammatically satisfying?

Django's Tutorial.. add "Question" to Admin Page

link to png of Admin Page

答:
In the model definition of the Question you can control this by declaring the Meta class:

```<code>class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    class Meta(object):
        verbose_name_plural = 'Questions'
</code>```

You can find this here in the docs

As explained in the docs, 'If this isn’t given, Django will use verbose_name + "s".'

Body:
In the model definition of the Question you can control this by declaring the Meta class:

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    class Meta(object):
        verbose_name_plural = 'Questions'

You can find this here in the docs

As explained in the docs, 'If this isn’t given, Django will use verbose_name + "s".'


问:
Qtip hide on destroy, show on hover, Dom cleaning like bootstrap tooltip
I am using jquery qtip2
I want its behaviour just like bootstrap tooltips where

on hover tooltip shows up , also in DOM

on mouseout tooltip hides, removed from DOM as well

Objective:

My objective is I am using lots of qtips, and they are taking unnecessary space in DOM and I want qtip2 to create dom element only when it is active.

JSFIDDLE: https://jsfiddle.net/bababalcksheep/5unavg0q/4/

Can't seem to make it work.Should it not be feature by default. Am I missing something from Docs ?

HTML:

```<code><a href="#test" class="qtiptxt" title="My tooltip text">Hover here!</a>
</code>```

JS:

```<code>$(document).ready(function() {
  $('.qtiptxt').qtip({
    prerender: false,
    overwrite: true,
    hide: {
      event: 'mouseout'
    },
    events: {
      hide: function(event, api) {
        var target = api.elements.target;
        var targetOptions = api.options;
        // Destroy it immediately
        api.destroy(true);
        //re initialize using existing options
        $(target).qtip(targetOptions);
      }
    }
  });
});
</code>```

答:
It seems I did miss the docs. Here is the solution

https://jsfiddle.net/bababalcksheep/5unavg0q/7/

```<code>$(document).ready(function() {
  //
  // from https://github.com/qTip2/qTip2/wiki/Events-Guide#delegation-on--live--delegate
  //
  $('.qtiptxt').on('mouseover', function(event) {
    $(this).qtip({
      prerender: false,
      overwrite: true,
      show: {
        event: event.type,
        ready: true
      },
      hide: {
        event: 'mouseout'
      },
      events: {
        hidden: function(event, api) {
          // Destroy it immediately
          api.destroy(true);
        }
      }
    }, event);
  });
  //
  //
});
</code>```

Body:
I am using jquery qtip2
I want its behaviour just like bootstrap tooltips where

on hover tooltip shows up , also in DOM

on mouseout tooltip hides, removed from DOM as well

Objective:

My objective is I am using lots of qtips, and they are taking unnecessary space in DOM and I want qtip2 to create dom element only when it is active.

JSFIDDLE: https://jsfiddle.net/bababalcksheep/5unavg0q/4/

Can't seem to make it work.Should it not be feature by default. Am I missing something from Docs ?

HTML:

Hover here!

JS:

$(document).ready(function() {
  $('.qtiptxt').qtip({
    prerender: false,
    overwrite: true,
    hide: {
      event: 'mouseout'
    },
    events: {
      hide: function(event, api) {
        var target = api.elements.target;
        var targetOptions = api.options;
        // Destroy it immediately
        api.destroy(true);
        //re initialize using existing options
        $(target).qtip(targetOptions);
      }
    }
  });
});

Body:
It seems I did miss the docs. Here is the solution

https://jsfiddle.net/bababalcksheep/5unavg0q/7/

$(document).ready(function() {
  //
  // from https://github.com/qTip2/qTip2/wiki/Events-Guide#delegation-on--live--delegate
  //
  $('.qtiptxt').on('mouseover', function(event) {
    $(this).qtip({
      prerender: false,
      overwrite: true,
      show: {
        event: event.type,
        ready: true
      },
      hide: {
        event: 'mouseout'
      },
      events: {
        hidden: function(event, api) {
          // Destroy it immediately
          api.destroy(true);
        }
      }
    }, event);
  });
  //
  //
});


问:
python, index errors
I've got some code which draws data from an xml file but it seems to have randomly starting throwing;

```<code>Traceback (most recent call last):
  File "C:\Users\mike\Documents\python\arl xml\turn 24 reader", line 52, in <module>
    unitCount   = getText(evoNode.getElementsByTagName("count")[0].childNodes)
IndexError: list index out of range
</code>```

it was fine for the first couple of times I ran it then, I dunno if I changed it or not by accident, but now it's throwing the error.

This is an example of the section of the xml it's trying to use;

```<code>- <unit>
  <count>1200</count>
  <type>Zweihander Doppelsoldners</type>
  <typeid>102</typeid>
  </unit>
</code>```

and here's the code that it's complains about;

```<code>   for unitNode in node.getElementsByTagName('unit'):
      unitName      = getText(evoNode.getElementsByTagName("type")[0].childNodes)
      unitId     = getText(evoNode.getElementsByTagName("typeid")[0].childNodes)
      unitCount   = getText(evoNode.getElementsByTagName("count")[0].childNodes)

      unitList.append("%s x %s" % (unitName, unitCount))
</code>```

While I accept that it complains about the count line first because count is the highest of the three on the xml file in the units section I'm still not sure why it's complaining, given that it succesfully runs a very similar set of code from which that was cloned and editted.

Anyone know what I can do or can suggest ways to refine the question?

答:
A simple idea: check if evoNode.getElementsByTagName("count") returns a non-empty list:

```<code>counts = evoNode.getElementsByTagName("count")
if counts:
    unitCount = getText(counts[0].childNodes)
</code>```

Of course, the check should be applied to all the lists retrieved by your code.

One Other thing, you iterate using unitNode, but inside the loop, you access evoNode, which is probably the same for every iteration.

ContentLicense: CC BY-SA 2.5

Title: python, index errors

Body:
I've got some code which draws data from an xml file but it seems to have randomly starting throwing;

Traceback (most recent call last):
  File "C:\Users\mike\Documents\python\arl xml\turn 24 reader", line 52, in <module>
    unitCount   = getText(evoNode.getElementsByTagName("count")[0].childNodes)
IndexError: list index out of range

it was fine for the first couple of times I ran it then, I dunno if I changed it or not by accident, but now it's throwing the error.

This is an example of the section of the xml it's trying to use;

- <unit>
  <count>1200</count>
  <type>Zweihander Doppelsoldners</type>
  <typeid>102</typeid>
  </unit>

and here's the code that it's complains about;

   for unitNode in node.getElementsByTagName('unit'):
      unitName      = getText(evoNode.getElementsByTagName("type")[0].childNodes)
      unitId     = getText(evoNode.getElementsByTagName("typeid")[0].childNodes)
      unitCount   = getText(evoNode.getElementsByTagName("count")[0].childNodes)

      unitList.append("%s x %s" % (unitName, unitCount))

While I accept that it complains about the count line first because count is the highest of the three on the xml file in the units section I'm still not sure why it's complaining, given that it succesfully runs a very similar set of code from which that was cloned and editted.

Anyone know what I can do or can suggest ways to refine the question?

Body:
A simple idea: check if evoNode.getElementsByTagName("count") returns a non-empty list:

counts = evoNode.getElementsByTagName("count")
if counts:
    unitCount = getText(counts[0].childNodes)

Of course, the check should be applied to all the lists retrieved by your code.

One Other thing, you iterate using unitNode, but inside the loop, you access evoNode, which is probably the same for every iteration.

OwnerDisplayName: gimel

LastEditorDisplayName: gimel


问:
How to change marker Image in Mapbox?
I am new to mapbox. I am getting trouble in marker image change in mapbox map.
I got the code from https://www.mapbox.com/mapbox-gl-js/example/custom-marker-icons/  I can't change  the marker image.

Here is my code:

```<code>var geojson = {
"type": "FeatureCollection",
"features": [
    {
        "type": "Feature",
        "properties": {
            "message": "IN",
            "iconSize": [30, 30]
        },
        "geometry": {
            "type": "Point",
            "coordinates":<?php echo $in; ?>
        }
    },
    {
        "type": "Feature",
        "properties": {
            "message": "Check IN",
            "iconSize": [30, 30]
        },
        "geometry": {
            "type": "Point",
            "coordinates":<?php echo $c; ?>
        }
    },
    {
        "type": "Feature",
        "properties": {
            "message": "OUT",
            "iconSize": [30, 30]
        },
        "geometry": {
            "type": "Point",
            "coordinates":<?php echo $o; ?>
        }
    }
    ]
};

geojson.features.forEach(function(marker) {

    var el = document.createElement('div');
    el.className = 'marker';
    el.style.backgroundImage = 'url(images/check_in.jpg)';
    el.style.width = marker.properties.iconSize[0] + 'px';
    el.style.height = marker.properties.iconSize[1] + 'px';

    el.addEventListener('click', function() {
        window.alert(marker.properties.message);
    });

    new mapboxgl.Marker(el, {offset: [-marker.properties.iconSize[0] / 2, -marker.properties.iconSize[1] / 2]})
        .setLngLat(marker.geometry.coordinates)
        .addTo(map);
});
</code>```

答:
visit this page for more details https://www.mapbox.com/help/markers/</p>

```<code> var geojson = {
"type": "FeatureCollection",
"features": [
    {
        "type": "Feature",
        "properties": {
            "message": "IN",
            "iconSize": [30, 30]
        },
        "geometry": {
            "type": "Point",
            "coordinates":<?php echo $in; ?>
        }
    },
    {
        "type": "Feature",
        "properties": {
            "message": "Check IN",
            "iconSize": [30, 30]
        },
        "geometry": {
            "type": "Point",
            "coordinates":<?php echo $c; ?>
        }
    },
    {
        "type": "Feature",
        "properties": {
            "message": "OUT",
            "iconSize": [30, 30]
        },
        "geometry": {
            "type": "Point",
            "coordinates":<?php echo $o; ?>
        }
    }
],

"properties": {
      "icon": {
        "iconUrl": "https://www.mapbox.com/mapbox.js/assets/images/astronaut2.png",
        "iconSize": [50, 50], // size of the icon
        "iconAnchor": [25, 25], // point of the icon which will correspond to marker's location
        "popupAnchor": [0, -25], // point from which the popup should open relative to the iconAnchor
        "className": "dot"
      }
    }
};
</code>```

Title: How to change marker Image in Mapbox?

Body:
I am new to mapbox. I am getting trouble in marker image change in mapbox map.
I got the code from https://www.mapbox.com/mapbox-gl-js/example/custom-marker-icons/  I can't change  the marker image.

Here is my code:

var geojson = {
"type": "FeatureCollection",
"features": [
    {
        "type": "Feature",
        "properties": {
            "message": "IN",
            "iconSize": [30, 30]
        },
        "geometry": {
            "type": "Point",
            "coordinates":<?php echo $in; ?>
        }
    },
    {
        "type": "Feature",
        "properties": {
            "message": "Check IN",
            "iconSize": [30, 30]
        },
        "geometry": {
            "type": "Point",
            "coordinates":<?php echo $c; ?>
        }
    },
    {
        "type": "Feature",
        "properties": {
            "message": "OUT",
            "iconSize": [30, 30]
        },
        "geometry": {
            "type": "Point",
            "coordinates":<?php echo $o; ?>
        }
    }
    ]
};

geojson.features.forEach(function(marker) {

    var el = document.createElement('div');
    el.className = 'marker';
    el.style.backgroundImage = 'url(images/check_in.jpg)';
    el.style.width = marker.properties.iconSize[0] + 'px';
    el.style.height = marker.properties.iconSize[1] + 'px';

    el.addEventListener('click', function() {
        window.alert(marker.properties.message);
    });

    new mapboxgl.Marker(el, {offset: [-marker.properties.iconSize[0] / 2, -marker.properties.iconSize[1] / 2]})
        .setLngLat(marker.geometry.coordinates)
        .addTo(map);
});

Body:
visit this page for more details https://www.mapbox.com/help/markers/

 var geojson = {
"type": "FeatureCollection",
"features": [
    {
        "type": "Feature",
        "properties": {
            "message": "IN",
            "iconSize": [30, 30]
        },
        "geometry": {
            "type": "Point",
            "coordinates":<?php echo $in; ?>
        }
    },
    {
        "type": "Feature",
        "properties": {
            "message": "Check IN",
            "iconSize": [30, 30]
        },
        "geometry": {
            "type": "Point",
            "coordinates":<?php echo $c; ?>
        }
    },
    {
        "type": "Feature",
        "properties": {
            "message": "OUT",
            "iconSize": [30, 30]
        },
        "geometry": {
            "type": "Point",
            "coordinates":<?php echo $o; ?>
        }
    }
],

"properties": {
      "icon": {
        "iconUrl": "https://www.mapbox.com/mapbox.js/assets/images/astronaut2.png",
        "iconSize": [50, 50], // size of the icon
        "iconAnchor": [25, 25], // point of the icon which will correspond to marker's location
        "popupAnchor": [0, -25], // point from which the popup should open relative to the iconAnchor
        "className": "dot"
      }
    }
};


问:
How to check if a function exists in a SQL database?
I need to find out if a function exists in a database, so that I can drop it and create it again. It should basically be something like the following code that I use for stored procedures:</p>
```<code>IF EXISTS (
     SELECT  *
     FROM    dbo.sysobjects
     WHERE   id = OBJECT_ID(N'[dbo].[SP_TEST]')
             AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
</code>```

答:
I know this thread is old but I just wanted to add this answer for those who believe it's safer to Alter than Drop and Create. The below will Alter the Function if it exists or Create it if doesn't:

```<code>  IF NOT EXISTS (SELECT *
               FROM   sys.objects
               WHERE  object_id = OBJECT_ID(N'[dbo].[foo]')
                      AND type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' ))
       EXEC('CREATE FUNCTION [dbo].[foo]() RETURNS INT AS BEGIN RETURN 0 END')
  GO
  ALTER FUNCTION [dbo].[foo]
  AS
  ...
</code>```

Body:
I need to find out if a function exists in a database, so that I can drop it and create it again. It should basically be something like the following code that I use for stored procedures:

IF EXISTS (
     SELECT  *
     FROM    dbo.sysobjects
     WHERE   id = OBJECT_ID(N'[dbo].[SP_TEST]')
             AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )

Body:
I know this thread is old but I just wanted to add this answer for those who believe it's safer to Alter than Drop and Create. The below will Alter the Function if it exists or Create it if doesn't:

  IF NOT EXISTS (SELECT *
               FROM   sys.objects
               WHERE  object_id = OBJECT_ID(N'[dbo].[foo]')
                      AND type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' ))
       EXEC('CREATE FUNCTION [dbo].[foo]() RETURNS INT AS BEGIN RETURN 0 END')
  GO
  ALTER FUNCTION [dbo].[foo]
  AS
  ...


问:
Displaying specific row from INNER JOIN - mysqli
I am trying to display information about currently logged in user. The problem is information I need are in two differnet tables so I had to use INNER JOIN and I have problem to display data.

```<code><?php
$email = $_SESSION['email'];

$sql_address =
"SELECT `customer`.`email`, `address`.`first_name`, `address`.`last_name`
FROM `customer` INNER JOIN address ON `customer`.`customer_ID`=`address`.`customer_ID WHERE email =". $email;
$result_address = $db->query($sql_address);

if(isset($_SESSION['email'])){
while($row = mysqli_fetch_array($result_address)){ ?>
                         <div class="col-sm-4 mb-20">
                            <div class="mb-20 mb-md-10">
                               <h3> CUSTOMER DETAILS</h3>
                               <p>Name: <?php echo $row['first_name']. " " .$row['last_name'];?><br/>
                                  Email: <?php echo $row['email'];?>
                               </p>
                            </div>
                         </div>
                         <?php }?>
</code>```

At this moment I am getting this error :

```<code>Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in D:\xamp\htdocs\exercises\website\shipment.php on line 149
</code>```

Can you please tell me where is a problem? Also do you have any suggestion how to make it more secure? I guess putting $email into query is probably not the best idea.

答:
Probably You have an error in sql statement, so $result_address is false. $email should be in single quotes, and also add close quote to the `customer_ID

Try this query

```<code>SELECT `customer`.`email`, `address`.`first_name`, `address`.`last_name`
FROM `customer` INNER JOIN address ON `customer`.`customer_ID`=`address`.`customer_ID` WHERE email = '". $email . "'";
</code>```

Body:
I am trying to display information about currently logged in user. The problem is information I need are in two differnet tables so I had to use INNER JOIN and I have problem to display data.

<?php
$email = $_SESSION['email'];

$sql_address =
"SELECT `customer`.`email`, `address`.`first_name`, `address`.`last_name`
FROM `customer` INNER JOIN address ON `customer`.`customer_ID`=`address`.`customer_ID WHERE email =". $email;
$result_address = $db->query($sql_address);

if(isset($_SESSION['email'])){
while($row = mysqli_fetch_array($result_address)){ ?>

 CUSTOMER DETAILS

Name: <?php echo $row['first_name']. " " .$row['last_name'];?>

                                  Email: <?php echo $row['email'];?>

                         <?php }?>

At this moment I am getting this error :

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in D:\xamp\htdocs\exercises\website\shipment.php on line 149

Can you please tell me where is a problem? Also do you have any suggestion how to make it more secure? I guess putting $email into query is probably not the best idea.

Body:
Probably You have an error in sql statement, so $result_address is false. $email should be in single quotes, and also add close quote to the `customer_ID

Try this query

SELECT `customer`.`email`, `address`.`first_name`, `address`.`last_name`
FROM `customer` INNER JOIN address ON `customer`.`customer_ID`=`address`.`customer_ID` WHERE email = '". $email . "'";


问:
How to change PHP version on MAMP 4.1
I downloaded MAMP 4.1 on my Mac; by default, the only PHP versions I can use are 7.0.15 and 7.1.1

How can I use PHP 5.6?

I tried the solution here  Which says I should rename the versions I don't want to use to something else. But it didn't work for me.

答:
As mentioned by @Scott in the comments under your question:

Your here is the right link. Use the bottom answer to rename the
  bin/php directory. The MAMP preference pane will show the 2 latest
  versions in the php directory. – Scott Eisenberg

And the answer in that links is:

First stop the Server if its running. Go to "/Applications/MAMP/bin/",
  rename the PHP Version you don't need (MAMP is only allowed to use 2
  PHP Versions), e.g. "_php5.2.17". Now MAMP will use the php versions
  that are left. Go to the MAMP Manager and then settings, then switch
  to the php version you need.

In my case (and similarly yours), I renamed the folder named php7.1.1 to _php7.1.1 and now MAMP shows me 5.6.30 and 7.0.15 in the preferences pane.

Title: How to change PHP version on MAMP 4.1


问:
Copying a file to multiple folders in the same directory
I have a file, lets call it EXAMPLE.DBF

The location of this file is C:\EXAMPLE.DBF

Now I would like to copy this file into multiple folders at another location.
These folders are dated Sub-directories so they are named 20140101 -  20141231 and their location would be in d:\bootd\hello\20140101 - 20141231
Not only that but a file named EXAMPLE.DBF already exists in the folders...so it will ask to Copy and Replace.
I will need c:\EXAMPLE to copy and replace the existing EXAMPLE.DBF in 365 folders (20140101-20141231) in a different location.

If anyone could help me out with this I will be truly grateful.

答:
Just a small addition to @Magoo's answer;

in case the destination folders have spaces in their names, use double quotes like this:
for /d %a in (d:\bootd\hello\2014*) do copy /y C:\EXAMPLE.DBF "%a\"

and as pointed out by @ian0411, in case source folder has spaces in its name, use double quotes like this:
for /d %a in (d:\bootd\hello\2014*) do copy /y "C:\EXAMPLE.DBF" %a\


问:
Import Variable from function in Class
I can't figure out how to import a variable that is created in a loop in a function and in a Class. I would then have the error " AttributeError: "Example" object has no attribute "address" .

It looks like this:

a.py

```<code>class Example():
    global address
    address = ""

    def __init__(self):
        pass

    def loop_function(self, cam):

        for i in imageZbar.symbols:
            print(i.data)
            address = i.data
        return address
</code>```

b.py

```<code>from a import Example
from flask import Flask,render_template
app = Flask(__name__)

app.route("/example/")
def blabla():
    imported_address = Example.address
    return render_template("example.html", imported_address = imported_address)
</code>```

答: just remove the line global address

Title: Import Variable from function in Class

Body:
I can't figure out how to import a variable that is created in a loop in a function and in a Class. I would then have the error " AttributeError: "Example" object has no attribute "address" .

It looks like this:

a.py

class Example():
    global address
    address = ""

    def __init__(self):
        pass

    def loop_function(self, cam):

        for i in imageZbar.symbols:
            print(i.data)
            address = i.data
        return address

b.py

from a import Example
from flask import Flask,render_template
app = Flask(__name__)

app.route("/example/")
def blabla():
    imported_address = Example.address
    return render_template("example.html", imported_address = imported_address)

Body: just remove the line global address


问:
why it returns empty value but of boolean type when no match is found
I am using the following code to search an element inside a multi dimensional array.When a match is found it returns the index.But when no match is found it returns a empty value.Not 0 or 1.But if i print out the type , it says boolean.What does that boolean mean if it returns empty.Does it mean that it will be equal to empty string ?</p>

```<code>$arr =Array
(
    0 => Array
        (
            'uid' => '100',
            'name' => 'Sandra Shush'
        ),

    1 => Array
        (
            'uid' => '5465',
            'name' => 'Stefanie Mcmohn'
        ),

    2 => Array
        (
            'uid' => '40489',
            'name' => 'Michael'
        )
);

$match = array_search('546',array_column($arr, 'uid'));

echo gettype($match);
</code>```

答: If you take a look at array_search method description http://php.net/manual/ro/function.array-search.php it says: Returns the key for needle if it is found in the array, FALSE otherwise. There is your answer.</p>

Body:
I am using the following code to search an element inside a multi dimensional array.When a match is found it returns the index.But when no match is found it returns a empty value.Not 0 or 1.But if i print out the type , it says boolean.What does that boolean mean if it returns empty.Does it mean that it will be equal to empty string ?

$arr =Array
(
    0 => Array
        (
            'uid' => '100',
            'name' => 'Sandra Shush'
        ),

    1 => Array
        (
            'uid' => '5465',
            'name' => 'Stefanie Mcmohn'
        ),

    2 => Array
        (
            'uid' => '40489',
            'name' => 'Michael'
        )
);

$match = array_search('546',array_column($arr, 'uid'));

echo gettype($match);


问:
Why can't I move an element into vector of non-copyables?
The compiler tells me I'm trying to access a deleted function (i.e. the copy constructor of a lambda expression).  But I don't see where.

```<code>std::vector<std::function<void()>> tasks;
std::packaged_task<int()> task{ [] { return 1; } };
tasks.emplace_back(
    [ t = std::move(task) ] () mutable { t(); });
</code>```

(code is also here)

(I'm trying to find out why they use shared_ptr<task> in https://www.slideshare.net/GlobalLogicUkraine/c11-multithreading-futures).

On Gcc and MSVC I get the same error - I fear I'm doing something wrong...

```<code>error: use of deleted function
'main()::<lambda()>::<lambda>(const main()::<lambda()>&)'
</code>```

Why can't I emplace this std::function onto the vector?

答:
From cppreference:

F must meet the requirements of Callable and CopyConstructible

Where F is the function type used to construct the std::function. However,  std::packaged_task is not copy constructible. Thus in the capture list, t is not copy constructible, and is a non-static member of the lambda, making the implicit copy constructor for the lambda deleted.

Body:
The compiler tells me I'm trying to access a deleted function (i.e. the copy constructor of a lambda expression).  But I don't see where.

std::vector<std::function<void()>> tasks;
std::packaged_task<int()> task{ [] { return 1; } };
tasks.emplace_back(
    [ t = std::move(task) ] () mutable { t(); });

(code is also here)

(I'm trying to find out why they use shared_ptr<task> in https://www.slideshare.net/GlobalLogicUkraine/c11-multithreading-futures).

On Gcc and MSVC I get the same error - I fear I'm doing something wrong...

error: use of deleted function
'main()::<lambda()>::<lambda>(const main()::<lambda()>&)'

Why can't I emplace this std::function onto the vector?


问:
Filter only parameters that are present in the request
There are lots of articles that are about Java 8 lambda operations however I couldn't find what I need until now. I tried to convert them to my approach unfortunately I couldn't succeed

Imagine that you have request that comes in POJO such as ;

```<code>public class DummyRequest {

    private String name;
    private String surname;
    private String country;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country= country;
    }

}
</code>```

During REST/SOAP request surname variable will be assigned as null.

```<code>List<Person> persons = Arrays.asList(
                new Person("maria", "gambert", "italy"),
                new Person("jack", "johson", "usa"),
                new Person("johnson", "jack", "usa"),
                new Person("kate", "julia", "spain"),
                new Person("jack","bob","uk");

DummyRequest dr = new DummyRequest();
dr.setName("jack");
dr.setCountry("usa");
</code>```

If I knew in advance that the surname field would be null, I could manage to filter the list like this, ignoring that field:

```<code>List<Person> result4 = persons.stream().
filter(x -> dummyRequest.getName().equals(x.getName())).
filter( x-> dummyRequest.getCountry().equals(x.getCountry())).
collect(Collectors.toList());
</code>```

However I don't know which fields will be null and which will not. How could I instead filter my data according to non-null request parameters only?

答:
I would define a static method for that, since you are duplicating the code so many times:

```<code>private static boolean nullableOrEqual(String left, String right) {
    return left == null || left.equals(right);
}
</code>```

And then the usage would be:

```<code>List<Person> result = persons.stream()
            .filter(x -> nullableOrEqual(dr.getSurname(), x.getSurname()))
            .filter(x -> nullableOrEqual(dr.getCountry(), x.getCountry()))
            .filter(x -> nullableOrEqual(dr.getName(), x.getName()))
            .collect(Collectors.toList());
</code>```

Body:
There are lots of articles that are about Java 8 lambda operations however I couldn't find what I need until now. I tried to convert them to my approach unfortunately I couldn't succeed

Imagine that you have request that comes in POJO such as ;

public class DummyRequest {

    private String name;
    private String surname;
    private String country;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country= country;
    }

}

During REST/SOAP request surname variable will be assigned as null.

List<Person> persons = Arrays.asList(
                new Person("maria", "gambert", "italy"),
                new Person("jack", "johson", "usa"),
                new Person("johnson", "jack", "usa"),
                new Person("kate", "julia", "spain"),
                new Person("jack","bob","uk");

DummyRequest dr = new DummyRequest();
dr.setName("jack");
dr.setCountry("usa");

If I knew in advance that the surname field would be null, I could manage to filter the list like this, ignoring that field:

List<Person> result4 = persons.stream().
filter(x -> dummyRequest.getName().equals(x.getName())).
filter( x-> dummyRequest.getCountry().equals(x.getCountry())).
collect(Collectors.toList());

However I don't know which fields will be null and which will not. How could I instead filter my data according to non-null request parameters only?

Body:
I would define a static method for that, since you are duplicating the code so many times:

private static boolean nullableOrEqual(String left, String right) {
    return left == null || left.equals(right);
}

And then the usage would be:

List<Person> result = persons.stream()
            .filter(x -> nullableOrEqual(dr.getSurname(), x.getSurname()))
            .filter(x -> nullableOrEqual(dr.getCountry(), x.getCountry()))
            .filter(x -> nullableOrEqual(dr.getName(), x.getName()))
            .collect(Collectors.toList());


问:
PHP never returns readyState 4 or status 200 in ajax
I have the following generic Ajax function:

```<code>//run post request
function ajaxPost (divid, parameters, file) {

if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  } else {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

xmlhttp.onreadystatechange=function() {
    alert ("ok")
  if (xmlhttp.readyState==4 && xmlhttp.status==200) {
      alert ("ready");
      alert (xmlhttp.responseText);
    divid.innerHTML=xmlhttp.responseText;
    }
  }

  xmlhttp.open("POST", file,true);

  //Send the proper header information along with the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "close");

xmlhttp.send(parameters);
}
</code>```

The problem being that this section does not work as expected:

```<code>xmlhttp.onreadystatechange=function() {
    alert ("ok")
  if (xmlhttp.readyState==4 && xmlhttp.status==200) {
      alert ("ready");
      alert (xmlhttp.responseText);
    divid.innerHTML=xmlhttp.responseText;
    }
  }
</code>```

In browser I get muliple "ok" alerts as I expected but the statements in the if statement never fire. I take this to mean the php is returning state updates but for some reason is never returning ready codes. How that can happen - I have no idea.

Can anyone tell me why I wouldn't recieve the ready codes?

The php itself is not the problem:

```<code><?php

echo "new";

?>
</code>```

I have tested the function input (divid, parameters and file), and these are ok.
This function was previously working in  a seperate project.

答:
xmlhttp.readyState && xmlhttp.status depend on the browser used, not the PHP script. Worst case, the PHP script might not resturn Status 200, and if this happens means that you either have an error in your script(sometimes this leads to Status 500) or the server returnr a 404.
In any case, try accessing the url directly, or look in the firebug log window, it may be easier to debug.

Body:
I have the following generic Ajax function:

//run post request
function ajaxPost (divid, parameters, file) {

if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  } else {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

xmlhttp.onreadystatechange=function() {
    alert ("ok")
  if (xmlhttp.readyState==4 && xmlhttp.status==200) {
      alert ("ready");
      alert (xmlhttp.responseText);
    divid.innerHTML=xmlhttp.responseText;
    }
  }

  xmlhttp.open("POST", file,true);

  //Send the proper header information along with the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "close");

xmlhttp.send(parameters);
}

The problem being that this section does not work as expected:

xmlhttp.onreadystatechange=function() {
    alert ("ok")
  if (xmlhttp.readyState==4 && xmlhttp.status==200) {
      alert ("ready");
      alert (xmlhttp.responseText);
    divid.innerHTML=xmlhttp.responseText;
    }
  }

In browser I get muliple "ok" alerts as I expected but the statements in the if statement never fire. I take this to mean the php is returning state updates but for some reason is never returning ready codes. How that can happen - I have no idea.

Can anyone tell me why I wouldn't recieve the ready codes?

The php itself is not the problem:

<?php

echo "new";

?>

I have tested the function input (divid, parameters and file), and these are ok.
This function was previously working in  a seperate project.


问:
Thread sequencing with Java 8
I have a simple program for two threads to print, incremental numbers, alternately.

So,
first thread prints : 1

Second thread prints : 2

first thread prints : 3... and so on

I am able to use 'Thread' class to do this. But I want to see how to use Executor class to do this.

With the following code .... executor class does NOT seem to work. Any pointers ??

Code :

```<code>import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LocksPackagePractice {

    private int i = 0;

    ReentrantLock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    Runnable r = () -> {
    for(int x = 0; x < 5; x++){
        printValue();
    }
    printValue();
};

    public static void main(String[] args) {

        new LocksPackagePractice().trigger();
    }

    void trigger(){
        ExecutorService service = Executors.newFixedThreadPool(2);
        service.execute(r);
    }

    void printValue(){

        lock.lock();

        try {

            i++;
            System.out.println(Thread.currentThread().getName() + " and value is = " + i);

            condition.signal();
            condition.await();

        } catch(InterruptedException e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }
}
</code>```

答:
I'm not sure, but do you need input to be ordered ? Because you use blocking operations (locks) and it is not good in case of performance.

This code :

```<code>private AtomicInteger number = new AtomicInteger(0);

  public static void main(String[] args) {
    ExecutorService executor = Executors.newFixedThreadPool(2);

    ForTestApplication testApplication = new ForTestApplication();

    for (int i = 0; i < 100; i++) {
      executor.execute(testApplication::print);
    }

  }

  public void print () {
    System.out.println(Thread.currentThread().getName() + " : " + number.incrementAndGet());
  }
</code>```

uses AtomicInteger instead of simple int value and lock operations. But order of output may be like this :

```<code>pool-1-thread-1 : 1
pool-1-thread-2 : 2
pool-1-thread-1 : 3
pool-1-thread-1 : 4
pool-1-thread-2 : 5
pool-1-thread-2 : 7
pool-1-thread-1 : 6
pool-1-thread-2 : 8
pool-1-thread-1 : 9
pool-1-thread-2 : 10
</code>```

It you need order in your output then need to think how to deal with it.

Title: Thread sequencing with Java 8

Body:
I have a simple program for two threads to print, incremental numbers, alternately.

So,
first thread prints : 1

Second thread prints : 2

first thread prints : 3... and so on

I am able to use 'Thread' class to do this. But I want to see how to use Executor class to do this.

With the following code .... executor class does NOT seem to work. Any pointers ??

Code :

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LocksPackagePractice {

    private int i = 0;

    ReentrantLock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    Runnable r = () -> {
    for(int x = 0; x < 5; x++){
        printValue();
    }
    printValue();
};

    public static void main(String[] args) {

        new LocksPackagePractice().trigger();
    }

    void trigger(){
        ExecutorService service = Executors.newFixedThreadPool(2);
        service.execute(r);
    }

    void printValue(){

        lock.lock();

        try {

            i++;
            System.out.println(Thread.currentThread().getName() + " and value is = " + i);

            condition.signal();
            condition.await();

        } catch(InterruptedException e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }
}

Body:
I'm not sure, but do you need input to be ordered ? Because you use blocking operations (locks) and it is not good in case of performance.

This code :

private AtomicInteger number = new AtomicInteger(0);

  public static void main(String[] args) {
    ExecutorService executor = Executors.newFixedThreadPool(2);

    ForTestApplication testApplication = new ForTestApplication();

    for (int i = 0; i < 100; i++) {
      executor.execute(testApplication::print);
    }

  }

  public void print () {
    System.out.println(Thread.currentThread().getName() + " : " + number.incrementAndGet());
  }

uses AtomicInteger instead of simple int value and lock operations. But order of output may be like this :

pool-1-thread-1 : 1
pool-1-thread-2 : 2
pool-1-thread-1 : 3
pool-1-thread-1 : 4
pool-1-thread-2 : 5
pool-1-thread-2 : 7
pool-1-thread-1 : 6
pool-1-thread-2 : 8
pool-1-thread-1 : 9
pool-1-thread-2 : 10

It you need order in your output then need to think how to deal with it.


问:
Why is my Rfacebook loop script not working when there is a post with zero comments?
I've edited my question to be more relevant

It's only been less than a month since I started to learn R and I'm trying to use it to get rid of the tedious work related to Facebook (extracting comments) that we use for our reports.

Using Rfacebook package, i made this script where it extracts (1) the posts of the page for a given period, and (2) Comments on those posts. It worked well for the page I'm doing the report for, but when I tried it on other pages with posts that had zero comments, it reported an error.

Here's the script:
Loading libraries

```<code>library(Rfacebook)
library(lubridate)
library(tibble)
</code>```

Setting time period. Change time as you please.

```<code>current_date <-Sys.Date()
past30days<-current_date-30
</code>```

Assigning a page. Edit this to the page you are monitoring*

```<code>brand<-'bpi'
</code>```

Authenticating Facebook. Use your own

```<code>app_id <- "xxxxxxxxxxxxxxxx"
app_secret <- "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
token <- fbOAuth(app_id,app_secret,extended_permissions = FALSE,legacy_permissions = FALSE)
</code>```

Extract all posts from a page

```<code>listofposts <- getPage(brand, token, n = 5000, since = past30days, until = current_date, feed = FALSE, reactions = FALSE, verbose=TRUE)
write.csv(listofposts,file = paste0('AsOf',current_date,brand,'Posts','.csv'))
</code>```

Convert to a data frame

```<code>df<-as_tibble(listofposts)
</code>```

Convert to a vector

```<code>postidvector<-df[["id"]]
</code>```

Get the number of posts in the period

```<code>n<-length(postidvector)
</code>```

Produce all comments via loop

```<code>reactions<-vector("list",n)
for(i in 1:n){
  reactions[[i]]<-assign(paste(brand,'Comments', i, sep = ""), (getPost((postidvector[i]),token,comments=T,likes=F,n.likes=5000,n.comments=10000)))
}
</code>```

Extract all comments per post to CSV

```<code>for(j in 1:n){
  write.csv(reactions[[j]],file = paste0('AsOf',current_date,brand,'Comments' ,j, '.csv'))
}
</code>```

Here's the error when exporting the comments to CSV when I tried it on the
 pages with posts that had ZERO comments:

```<code>Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE,  :
  arguments imply differing number of rows: 1, 0
</code>```

I tried it on a heavy traffic page, and it worked fine too. One post had 10,000 comments and it extracted just fine. :(

Thanks in advance! :D

答: Pages can be restricted by age or location. You can´t use an App Access Token for those, because it does not include a user session so Facebook does not know if you are allowed to see the Page content. You will have to use a User Token or Page Token for those.</p>

Body:
I've edited my question to be more relevant

It's only been less than a month since I started to learn R and I'm trying to use it to get rid of the tedious work related to Facebook (extracting comments) that we use for our reports.

Using Rfacebook package, i made this script where it extracts (1) the posts of the page for a given period, and (2) Comments on those posts. It worked well for the page I'm doing the report for, but when I tried it on other pages with posts that had zero comments, it reported an error.

Here's the script:
Loading libraries

library(Rfacebook)
library(lubridate)
library(tibble)

Setting time period. Change time as you please.

current_date <-Sys.Date()
past30days<-current_date-30

Assigning a page. Edit this to the page you are monitoring*

brand<-'bpi'

Authenticating Facebook. Use your own

app_id <- "xxxxxxxxxxxxxxxx"
app_secret <- "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
token <- fbOAuth(app_id,app_secret,extended_permissions = FALSE,legacy_permissions = FALSE)

Extract all posts from a page

listofposts <- getPage(brand, token, n = 5000, since = past30days, until = current_date, feed = FALSE, reactions = FALSE, verbose=TRUE)
write.csv(listofposts,file = paste0('AsOf',current_date,brand,'Posts','.csv'))

Convert to a data frame

df<-as_tibble(listofposts)

Convert to a vector

postidvector<-df[["id"]]

Get the number of posts in the period

n<-length(postidvector)

Produce all comments via loop

reactions<-vector("list",n)
for(i in 1:n){
  reactions[[i]]<-assign(paste(brand,'Comments', i, sep = ""), (getPost((postidvector[i]),token,comments=T,likes=F,n.likes=5000,n.comments=10000)))
}

Extract all comments per post to CSV

for(j in 1:n){
  write.csv(reactions[[j]],file = paste0('AsOf',current_date,brand,'Comments' ,j, '.csv'))
}

Here's the error when exporting the comments to CSV when I tried it on the
 pages with posts that had ZERO comments:

Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE,  :
  arguments imply differing number of rows: 1, 0

I tried it on a heavy traffic page, and it worked fine too. One post had 10,000 comments and it extracted just fine. :(

Thanks in advance! :D


问:
Import Maven (or Gradle) project to Eclipse in command line
I would to prepare virtual machine with Eclipse. I would like the Eclipse has pre-imported my Maven project.
Is is possible to execute some script which imports the project to the eclipse, in similar way I can pre-install plugin?

I'm not interested in mvn eclipse:eclipse. I want import with the same process like clicking mouse

PS. Similar question for Gradle.

答: You can add the Eclipse workspace which has your project imported to the vm. </p>


问:
Google fonts loading optimisation and caching
Google's page speed test shows only one problem:

Eliminate render-blocking JavaScript and CSS in above-the-fold content
  Your page has 1 blocking CSS resources. This causes a delay in rendering your page.

  None of the above-the-fold content on your page could be rendered without waiting for the following resources to load. Try to defer or asynchronously load blocking resources, or inline the critical portions of those resources directly in the HTML.

  Optimize CSS Delivery of the following:

  https://fonts.googleapis.com/css?family=Roboto:300,400

The fonts being loaded as fonts.google.com recommends:

```<code><link href="https://fonts.googleapis.com/css?family=Roboto:300,400" rel="stylesheet">
</code>```

Within  tag.

As far as i know, there is no way to control google's fonts caching and also, this url's output depends on user agent, so it doesn't make sense to distribute the fonts locally. So, the question is: what do i suppose to do with that? How do i satisfy google's speed test?

答:
So far i know ist the best solution today if you use Fontloader. It loads first a short .js script and late the font async.

Tipp: Use font-family: 'Roboto', 'sans serif'; async has the problem the font type is switching after the site is rendered. So the user see a short font switch like a flash. If you use sans serif as fallback the switch is not so big.

Or use .wf-active

Body:
Google's page speed test shows only one problem:

Eliminate render-blocking JavaScript and CSS in above-the-fold content
  Your page has 1 blocking CSS resources. This causes a delay in rendering your page.

  None of the above-the-fold content on your page could be rendered without waiting for the following resources to load. Try to defer or asynchronously load blocking resources, or inline the critical portions of those resources directly in the HTML.

  Optimize CSS Delivery of the following:

  https://fonts.googleapis.com/css?family=Roboto:300,400

The fonts being loaded as fonts.google.com recommends:

<link href="https://fonts.googleapis.com/css?family=Roboto:300,400" rel="stylesheet">

Within  tag.

As far as i know, there is no way to control google's fonts caching and also, this url's output depends on user agent, so it doesn't make sense to distribute the fonts locally. So, the question is: what do i suppose to do with that? How do i satisfy google's speed test?


问:
getting 400 Bad Request when trying to upload to aws s3 bucket
I sign the URL on my server and send it back to the client which works fine. This is how that function looks

```<code>const aws = require('aws-sdk'),
    config = require('config'),
    crypto = require('crypto');

module.exports = async function(file_type) {

    aws.config.update({accessKeyId: config.AWS_ACCESS_KEY, secretAccessKey: config.AWS_SECRET_KEY})

    const s3 = new aws.S3();

    try {
        if (!file_type === "image/png") {
            return ({success: false, error: 'Please provide a valid video format'});
        }
        let buffer = await crypto.randomBytes(12);

        let key = buffer.toString('hex');

        let options = {
            Bucket: config.AWS_S3_BUCKET,
            Key: key,
            Expires: 60,
            ContentType: file_type,
            ACL: 'public-read',
        }

        let data = await s3.getSignedUrl('putObject', options);
        console.log('data was', data)
        return ({
            success: true,
            signed_request: data,
            url: ('https://s3.amazonaws.com/' + config.AWS_S3_BUCKET + '/' + key),
            key,
        });
    } catch (error) {
        console.log('the error was', error)
        return ({
            success: false,
            error: error.message,
        })
    }
}
</code>```

So this works fine and winds up getting me a url like

https://mybucket.s3.amazonaws.com/a33b4a43f23fc41de9ddck1k?AWSAccessKeyId=ADIFJDGPMRFRGLXSYWPQ&Content-Type=image%2Fpng&Expires=1496716543&Signature=0zcx%2BFzWUoeFD02RF2CQ2o0bLmo%3D&x-amz-acl=public-read

Then when I get that url back on the client.. i send a PUT request using axios with a function like -

```<code>function uploadToS3(file, signedRequest, callback){

    var options = {
        headers: {
            'Content-Type': file.type
        }
    };

    axios.put(signedRequest, file, options)
        .then(result =>{
            console.log('the result was', result)
            callback(result)
        })
        .catch(err =>{
            callback(err)
        })

}
</code>```

The only I'm getting back is (400) Bad Request

答:
Guess bad header you provided

Works for me

```<code> function upload(file, signedRequest, done) {
  const xhr = new XMLHttpRequest();
  xhr.open('PUT', signedRequest);
  xhr.setRequestHeader('x-amz-acl', 'public-read');
  xhr.onload = () => {
    if (xhr.status === 200) {
      done();
    }
  };

  xhr.send(file);
}
</code>```

Body:
I sign the URL on my server and send it back to the client which works fine. This is how that function looks

const aws = require('aws-sdk'),
    config = require('config'),
    crypto = require('crypto');

module.exports = async function(file_type) {

    aws.config.update({accessKeyId: config.AWS_ACCESS_KEY, secretAccessKey: config.AWS_SECRET_KEY})

    const s3 = new aws.S3();

    try {
        if (!file_type === "image/png") {
            return ({success: false, error: 'Please provide a valid video format'});
        }
        let buffer = await crypto.randomBytes(12);

        let key = buffer.toString('hex');

        let options = {
            Bucket: config.AWS_S3_BUCKET,
            Key: key,
            Expires: 60,
            ContentType: file_type,
            ACL: 'public-read',
        }

        let data = await s3.getSignedUrl('putObject', options);
        console.log('data was', data)
        return ({
            success: true,
            signed_request: data,
            url: ('https://s3.amazonaws.com/' + config.AWS_S3_BUCKET + '/' + key),
            key,
        });
    } catch (error) {
        console.log('the error was', error)
        return ({
            success: false,
            error: error.message,
        })
    }
}

So this works fine and winds up getting me a url like

https://mybucket.s3.amazonaws.com/a33b4a43f23fc41de9ddck1k?AWSAccessKeyId=ADIFJDGPMRFRGLXSYWPQ&Content-Type=image%2Fpng&Expires=1496716543&Signature=0zcx%2BFzWUoeFD02RF2CQ2o0bLmo%3D&x-amz-acl=public-read

Then when I get that url back on the client.. i send a PUT request using axios with a function like -

function uploadToS3(file, signedRequest, callback){

    var options = {
        headers: {
            'Content-Type': file.type
        }
    };

    axios.put(signedRequest, file, options)
        .then(result =>{
            console.log('the result was', result)
            callback(result)
        })
        .catch(err =>{
            callback(err)
        })

}

The only I'm getting back is (400) Bad Request

Body:
Guess bad header you provided

Works for me

 function upload(file, signedRequest, done) {
  const xhr = new XMLHttpRequest();
  xhr.open('PUT', signedRequest);
  xhr.setRequestHeader('x-amz-acl', 'public-read');
  xhr.onload = () => {
    if (xhr.status === 200) {
      done();
    }
  };

  xhr.send(file);
}


问:
Return spring mvc Model on Ajax response
I am having a controller that return model objects like below
model.addAttribute("list", list);

When i click a button ajax call happens and it is goes to controller executing everything and it returns. But i don't know how to access this model object in my jsp on ajax response. When i use alert for success ajax response , I am just seeing a html kind of page.

Please give me some example or reference to achieve this

Thanks in advance

Please find my sample code snippet

Controller.java

```<code>@RequestMapping(value='/ajax' value="POST")
 Public @ResponseBody String displayDropdown(MyForm myform,Model model) {
 //logic to fetch details from DB
 List<String> list = fetchFromDB();
 model.addAttribute("list" list);
 return "ajaxResponse";
}
</code>```

My JSP

In a button click, having the below ajax call

```<code>$.ajax {
   url:'/ajax',
   type:'POST',
   data: $("#myform").serialize();
   success:function(data) {
   alert(response);
   }
}
</code>```

I want to get my model from this ajax response and use it in my jsp.

答:
Yes You can easily get Model data from controller, simply

```<code> @RequestMapping(value='/ajax' value="POST")
 Public String displayDropdown(MyForm myform,Model model) {
 //logic to fetch details from DB
 List<String> list = fetchFromDB();
 model.addAttribute("list" list);
 return "yourjsppage";
 }

 $.ajax {
 url:'/ajax',
 type:'POST',
 data: $("#myform").serialize();
 success:function(data) {
 $("#page-wrapper").html( data );
 }
 }
</code>```

page-wrapper is your content div in jsp page. this returns all jsp page including your model. in this scenario it is also useful when you want (partial rendering) not wanting to refresh whole page but targeting specific page.

Body:
I am having a controller that return model objects like below
model.addAttribute("list", list);

When i click a button ajax call happens and it is goes to controller executing everything and it returns. But i don't know how to access this model object in my jsp on ajax response. When i use alert for success ajax response , I am just seeing a html kind of page.

Please give me some example or reference to achieve this

Thanks in advance

Please find my sample code snippet

Controller.java

@RequestMapping(value='/ajax' value="POST")
 Public @ResponseBody String displayDropdown(MyForm myform,Model model) {
 //logic to fetch details from DB
 List<String> list = fetchFromDB();
 model.addAttribute("list" list);
 return "ajaxResponse";
}

My JSP

In a button click, having the below ajax call

$.ajax {
   url:'/ajax',
   type:'POST',
   data: $("#myform").serialize();
   success:function(data) {
   alert(response);
   }
}

I want to get my model from this ajax response and use it in my jsp.

Body:
Yes You can easily get Model data from controller, simply

 @RequestMapping(value='/ajax' value="POST")
 Public String displayDropdown(MyForm myform,Model model) {
 //logic to fetch details from DB
 List<String> list = fetchFromDB();
 model.addAttribute("list" list);
 return "yourjsppage";
 }

 $.ajax {
 url:'/ajax',
 type:'POST',
 data: $("#myform").serialize();
 success:function(data) {
 $("#page-wrapper").html( data );
 }
 }

page-wrapper is your content div in jsp page. this returns all jsp page including your model. in this scenario it is also useful when you want (partial rendering) not wanting to refresh whole page but targeting specific page.


问:
Android : why does defining the widgets in this part (i.e MainActivity ) Cause an error
If I define the following lines

```<code>myText =(TextView)findViewById(R.id.textView);
button=(Button)findViewById(R.id.button);
</code>```

in onCreate the program runs smoothly but if I do that in Main Activity then it causes an error.

```<code>import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    myText =(TextView)findViewById(R.id.textView); //error
    button=(Button)findViewById(R.id.button);

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

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(myText.getVisibility()==View.VISIBLE){

                    myText.setVisibility(View.INVISIBLE);
                }else
                {
                    myText.setVisibility(View.VISIBLE);
                }

            }
        });
    }
}
</code>```

答:
In onCreate() you call

```<code>setContentView(R.layout.activity_main);
</code>```

Only at that point does the activity have a layout, and findViewById makes sense - it will now recursively look for a view within R.layout.activity_main that has the ID your looking for.

The code you write outside the onCreate method runs on class instantiation, which doesn't help you as it's before the layout as been set.

Try something like this:

```<code>public class MyActivity ... {
  private TextView foo;
  private Button bar;

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

    foo = (TextView)findViewById(R.id.some_id);
    bar = (Button)findViewById(R.id.some_other_id);

    // ... can use foo and bar here and during the rest of the activity lifecycle
  }

  // ...
}
</code>```

Body:
If I define the following lines

myText =(TextView)findViewById(R.id.textView);
button=(Button)findViewById(R.id.button);

in onCreate the program runs smoothly but if I do that in Main Activity then it causes an error.

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    myText =(TextView)findViewById(R.id.textView); //error
    button=(Button)findViewById(R.id.button);

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

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(myText.getVisibility()==View.VISIBLE){

                    myText.setVisibility(View.INVISIBLE);
                }else
                {
                    myText.setVisibility(View.VISIBLE);
                }

            }
        });
    }
}

Body:
In onCreate() you call

setContentView(R.layout.activity_main);

Only at that point does the activity have a layout, and findViewById makes sense - it will now recursively look for a view within R.layout.activity_main that has the ID your looking for.

The code you write outside the onCreate method runs on class instantiation, which doesn't help you as it's before the layout as been set.

Try something like this:

public class MyActivity ... {
  private TextView foo;
  private Button bar;

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

    foo = (TextView)findViewById(R.id.some_id);
    bar = (Button)findViewById(R.id.some_other_id);

    // ... can use foo and bar here and during the rest of the activity lifecycle
  }

  // ...
}


问:
Assign sorted dictionary to the new dictionary
I would like to sort dictionary and save it into the same one, but there is type conflict :

Cannot assign value of type [(Int) : (Double)] to the type [Int : Double].

```<code>dictionary = dictionary.sorted(by: { (elem1: (key: Int, value: Double), elem2: (key: Int, value: Double)) -> Bool in
                        if elem1.value < elem2.value {
                            return true
                        } else {
                            return false
                        }
                    })
</code>```

I know that after sorting it wont be any more a dictionary.

```<code>let sorted = dictionary.sorted(by: { (elem1: (key: Int, value: Double), elem2: (key: Int, value: Double)) -> Bool in
                        if elem1.value < elem2.value {
                            return true
                        } else {
                            return false
                        }
                    })
</code>```

I've made a simple for loop to loop thought sortet "dictionary" to assign values once more to the dictionary but it does not copy them as a sorted ;/

```<code>var test = [Int : Double]()

                    for (key, value) in sorted {
                        test[key] = value
                    }
</code>```

How could I assign the sorted dictionary back to the dictionary in the orded I've sorted it ?

EDID

For each annotation I have to get a deistance from dropped pin. I've made a dictionary which a key is annotation ID and value is a distance between annotation and dropped point. I need a dictionary to recognize in view for cell - table view data source; which annotation match which distance. So I have a dictionary with [Int : Double] and in table view data source :

```<code>let annotation = mapAnnotations[indexPath.row]
var distance = dictionary[annotation.ID]
</code>```

Reasuming, shell I sort mapAnnotations which is an array of Object via values inside dictionary with distances which are makred by annotationId ?

It would be sorting array of object.ID by keys from sorted

Thanks in advance!

答:
A dictionary itself cannot be sorted the concept is meaningless because they are by their very nature unordered.  When using a dictionary you access the values by their hashable key so order is irrelevant.  Although you can access the keys and values as properties they are also not sorted.

What the sorted method does is allows you to get a sorted array of the dictionary and it returns an array of tupples of the keys and values sorted as you determine.  In the example it would return [(key: Int, value: Double)].  So you can't assign that back to the original dictionary because it's not a dictionary it's an array.

The extra code that then assigns back to the dictionary removes all the sorting you have done because as I stated the concept of sorting a dictionary is meaningless.

Body:
I would like to sort dictionary and save it into the same one, but there is type conflict :

Cannot assign value of type [(Int) : (Double)] to the type [Int : Double].

dictionary = dictionary.sorted(by: { (elem1: (key: Int, value: Double), elem2: (key: Int, value: Double)) -> Bool in
                        if elem1.value < elem2.value {
                            return true
                        } else {
                            return false
                        }
                    })

I know that after sorting it wont be any more a dictionary.

let sorted = dictionary.sorted(by: { (elem1: (key: Int, value: Double), elem2: (key: Int, value: Double)) -> Bool in
                        if elem1.value < elem2.value {
                            return true
                        } else {
                            return false
                        }
                    })

I've made a simple for loop to loop thought sortet "dictionary" to assign values once more to the dictionary but it does not copy them as a sorted ;/

var test = [Int : Double]()

                    for (key, value) in sorted {
                        test[key] = value
                    }

How could I assign the sorted dictionary back to the dictionary in the orded I've sorted it ?

EDID

For each annotation I have to get a deistance from dropped pin. I've made a dictionary which a key is annotation ID and value is a distance between annotation and dropped point. I need a dictionary to recognize in view for cell - table view data source; which annotation match which distance. So I have a dictionary with [Int : Double] and in table view data source :

let annotation = mapAnnotations[indexPath.row]
var distance = dictionary[annotation.ID]

Reasuming, shell I sort mapAnnotations which is an array of Object via values inside dictionary with distances which are makred by annotationId ?

It would be sorting array of object.ID by keys from sorted

Thanks in advance!