问:
Convert an NSURL to an NSString
I have an app where the user can choose an image either from the built-in app images or from the iphone photo library. I use an object Occasion that has an NSString property to save the imagePath.

Now in the case of the built-in app images I do get the file name as an NSString an save in the [occasion imagePath]. But in the 2nd case where the user picks an image form the photo library I get an NSURL which I want to convert to an NSString to be able to save it in [occasion imagePath].

Is it possible to convert the NSURL to an NSString?

答:
You can use any one way

```<code>NSString *string=[NSString stringWithFormat:@"%@",url1];
</code>```

or

```<code>NSString *str=[url1 absoluteString];

NSLog(@"string :: %@",string);
</code>```

string :: file:///var/containers/Bundle/Application/E2D7570B-D5A6-45A0-8EAAA1F7476071FE/RemoDuplicateMedia.app/loading_circle_animation.gif

```<code>NSLog(@"str :: %@", str);
</code>```

str :: file:///var/containers/Bundle/Application/E2D7570B-D5A6-45A0-8EAA-A1F7476071FE/RemoDuplicateMedia.app/loading_circle_animation.gif

Title: Convert an NSURL to an NSString

Body:
You can use any one way

NSString *string=[NSString stringWithFormat:@"%@",url1];

or

NSString *str=[url1 absoluteString];

NSLog(@"string :: %@",string);

string :: file:///var/containers/Bundle/Application/E2D7570B-D5A6-45A0-8EAAA1F7476071FE/RemoDuplicateMedia.app/loading_circle_animation.gif

NSLog(@"str :: %@", str);

str :: file:///var/containers/Bundle/Application/E2D7570B-D5A6-45A0-8EAA-A1F7476071FE/RemoDuplicateMedia.app/loading_circle_animation.gif


来源: stackexchange

问:
Sum of value per X grouped by Y
```<code>declare @table table (Customer  char(1), Transaction char(3), Discount float);
insert into @table values
('A', '001', '10.1'),
('A', '001', '10.1'),
('A', '002', '20.2'),
('B', '003', '30.3'),
('B', '004', '40.4')
</code>```

I am trying to do something like this:

```<code>SELECT Customer, (SELECT SUM(Discount) WHERE Transaction IS DISTINCT)
FROM @table
GROUP BY Customer
</code>```

And the result should look like:

```<code>Customer    Total Discount
--------------------------
A                   30.3
B                   70.7
</code>```

So basically I need club all the discounts for every customer per transaction, because they are sometimes repeated in my data.

答:
Get Distinct Records from table throuth Inline Query and named as "Inline" and then select Customer and Sum Discount from "Inline" Like</p>

```<code>SELECT Inline.Customer,
SUM(Inline.[Discount]) FROM
(SELECT DISTINCT Customer,[Discount] FROM @table)   Inline
  GROUP BY Inline.Customer
</code>```

ContentLicense: CC BY-SA 3.0

Title: Sum of value per X grouped by Y

Body:
declare @table table (Customer  char(1), Transaction char(3), Discount float);
insert into @table values
('A', '001', '10.1'),
('A', '001', '10.1'),
('A', '002', '20.2'),
('B', '003', '30.3'),
('B', '004', '40.4')

I am trying to do something like this:

SELECT Customer, (SELECT SUM(Discount) WHERE Transaction IS DISTINCT)
FROM @table
GROUP BY Customer

And the result should look like:

Customer    Total Discount
--------------------------
A                   30.3
B                   70.7

So basically I need club all the discounts for every customer per transaction, because they are sometimes repeated in my data.

Body:
Get Distinct Records from table throuth Inline Query and named as "Inline" and then select Customer and Sum Discount from "Inline" Like

SELECT Inline.Customer,
SUM(Inline.[Discount]) FROM
(SELECT DISTINCT Customer,[Discount] FROM @table)   Inline
  GROUP BY Inline.Customer


问:
how to download in python
I am writing a script which will run on my server. Its purpose is to download the document. If any person hit the particular url he/she should be able to download the document. I am using urllib.urlretrieve but it download document on the server side not on the client. How to download in python at client side?</p>

答: If the document is on your server and your intention is that the user should be able to download this file, couldn't you just serve the url to that resource as a hyperlink in your HTML code. Sorry if I have been obtuse but this seems the most logical step given your explanation.</p>

ContentLicense: CC BY-SA 2.5

Title: how to download in python


问:
Why doesn't Android Debug mode and Android Monitor work together
Why do android studio close its monitor if I debug the application ?
I need to change database table once I get results while debugging and then again debug , but the process goes like android debug closes the monitor as soon I start to debug .</p>

答:
Drag the Debugtag from the left to the right.

All the labels can be handled like this.


问:
How to target input element whose id, class and xpath changing with every refresh. webdriver Python

User Name

    <input name="xugw1irortn1ogkpy31wxl" type="text" id="xugw1irortn1ogkpy31wxl" style="display:none;" />
    <input name="bzzunemwbpxl44jnmxr0bt" type="text" id="bzzunemwbpxl44jnmxr0bt" style="display:none;" />
    <input name="w4gxjqkwvd4pqp4xrevu2r" type="text" id="w4gxjqkwvd4pqp4xrevu2r" style="display:none;" />
    <input name="bzxdws3vj041exduu1125j" type="text" id="bzxdws3vj041exduu1125j" style="display:none;" />
    <input name="lun5ji01ou4wpyvzaypji1" type="text" id="lun5ji01ou4wpyvzaypji1" style="display:none;" />
    <input name="x1rkfxp4sjwojbvr2uptuz" type="text" id="x1rkfxp4sjwojbvr2uptuz" style="display:none;" />
    <input name="cptv2l0ffvzpwqk0wetlnh" type="text" id="cptv2l0ffvzpwqk0wetlnh" style="display:none;" />
    <input name="couyswy1yfm51bpnyzkyrg" type="text" id="couyswy1yfm51bpnyzkyrg" style="display:none;" />
    <input name="yninikw54iudxqqlzgmxir" type="text" id="yninikw54iudxqqlzgmxir" style="display:none;" />
    <input name="ngb4uczri1l5ftyqvppbgk" type="text" id="ngb4uczri1l5ftyqvppbgk" style="display:none;" />
    <input name="e5dt2tozqrbrqxsivl0ygk" type="text" id="e5dt2tozqrbrqxsivl0ygk" style="display:none;" />
    <input name="rkcjmknvghdly0vk03ynmf" type="text" id="rkcjmknvghdly0vk03ynmf" style="display:none;" />
    <input name="moostndi5vtvpc0fy5sboa" type="text" id="moostndi5vtvpc0fy5sboa" style="display:none;" />
    <input name="1bps10gceliasg41iy455l" type="text" id="1bps10gceliasg41iy455l" style="display:none;" />
    <input name="a1z1amtyvnrtad55ywiqnc" type="text" id="a1z1amtyvnrtad55ywiqnc" style="display:none;" />
    <input name="m3jyv1ibdslgoelr5wdlfd" type="text" id="m3jyv1ibdslgoelr5wdlfd" style="display:none;" />
    <input name="4dgqbpwew3ngbgwdnxaqf4" type="text" id="4dgqbpwew3ngbgwdnxaqf4" style="display:none;" />
    <input name="hocvr1ykprqs5a4agnnfie" type="text" id="hocvr1ykprqs5a4agnnfie" />
    *

Password

 <input name="xugw1irortnb5sraht3azj" type="password" id="xugw1irortnb5sraht3azj" style="display:none;" />
 <input name="bzzunemwbpxb1vpydi1qcv" type="password" id="bzzunemwbpxb1vpydi1qcv" style="display:none;" />
 <input name="w4gxjqkwvd4n50vqqehcab" type="password" id="w4gxjqkwvd4n50vqqehcab" style="display:none;" />
 <input name="bzxdws3vj04w2iargab32a" type="password" id="bzxdws3vj04w2iargab32a" style="display:none;" />
 <input name="lun5ji01ou42tafgvmhc4t" type="password" id="lun5ji01ou42tafgvmhc4t" style="display:none;" />
 <input name="x1rkfxp4sjwtlwvdpsdjkq" type="password" id="x1rkfxp4sjwtlwvdpsdjkq" style="display:none;" />
 <input name="cptv2l0ffvznmop4iqycoe" type="password" id="cptv2l0ffvznmop4iqycoe" style="display:none;" />
 <input name="couyswy1yfm22nbvshuvrv" type="password" id="couyswy1yfm22nbvshuvrv" style="display:none;" />
 <input name="yninikw54iub5zucjoseb2" type="password" id="yninikw54iub5zucjoseb2" style="display:none;" />
 <input name="ngb4uczri1lmusbh0ztgkf" type="password" id="ngb4uczri1lmusbh0ztgkf" style="display:none;" />
 <input name="e5dt2tozqrbiseaipzetp1" type="password" id="e5dt2tozqrbiseaipzetp1" style="display:none;" />
 <input name="rkcjmknvghdfdmhcpfhvrv" type="password" id="rkcjmknvghdfdmhcpfhvrv" style="display:none;" />
 <input name="moostndi5vtep5rwqi5llx" type="password" id="moostndi5vtep5rwqi5llx" style="display:none;" />
 <input name="1bps10gceliy02zzdkpx5p" type="password" id="1bps10gceliy02zzdkpx5p" style="display:none;" />
 <input name="a1z1amtyvnrdygk03jr3vf" type="password" id="a1z1amtyvnrdygk03jr3vf" style="display:none;" />
 <input name="m3jyv1ibdslxju0pbgrmbn" type="password" id="m3jyv1ibdslxju0pbgrmbn" style="display:none;" />
 <input name="4dgqbpwew3n5ru3dbxnzxo" type="password" id="4dgqbpwew3n5ru3dbxnzxo" style="display:none;" />
 <input name="hocvr1ykprqlzaevxie2iv" type="password" id="hocvr1ykprqlzaevxie2iv" />
 *

```

I am trying to login into a  .aspx website using selenium Python webdriver but the problem is the id class and xpath are changing with reload or refresh. Even, there is multiple input  for user and password entry.

source code screenshot:

UI screenshot:

答:
You can try to use below XPath expressions:

```<code>//div[text()="User Name"]/following-sibling::input[not(@style="display:none;")]
</code>```

for Username field and

```<code>//div[text()="Password"]/following-sibling::input[not(@style="display:none;")]
</code>```

for Password

Body:
User Name

    <input name="xugw1irortn1ogkpy31wxl" type="text" id="xugw1irortn1ogkpy31wxl" style="display:none;" />
    <input name="bzzunemwbpxl44jnmxr0bt" type="text" id="bzzunemwbpxl44jnmxr0bt" style="display:none;" />
    <input name="w4gxjqkwvd4pqp4xrevu2r" type="text" id="w4gxjqkwvd4pqp4xrevu2r" style="display:none;" />
    <input name="bzxdws3vj041exduu1125j" type="text" id="bzxdws3vj041exduu1125j" style="display:none;" />
    <input name="lun5ji01ou4wpyvzaypji1" type="text" id="lun5ji01ou4wpyvzaypji1" style="display:none;" />
    <input name="x1rkfxp4sjwojbvr2uptuz" type="text" id="x1rkfxp4sjwojbvr2uptuz" style="display:none;" />
    <input name="cptv2l0ffvzpwqk0wetlnh" type="text" id="cptv2l0ffvzpwqk0wetlnh" style="display:none;" />
    <input name="couyswy1yfm51bpnyzkyrg" type="text" id="couyswy1yfm51bpnyzkyrg" style="display:none;" />
    <input name="yninikw54iudxqqlzgmxir" type="text" id="yninikw54iudxqqlzgmxir" style="display:none;" />
    <input name="ngb4uczri1l5ftyqvppbgk" type="text" id="ngb4uczri1l5ftyqvppbgk" style="display:none;" />
    <input name="e5dt2tozqrbrqxsivl0ygk" type="text" id="e5dt2tozqrbrqxsivl0ygk" style="display:none;" />
    <input name="rkcjmknvghdly0vk03ynmf" type="text" id="rkcjmknvghdly0vk03ynmf" style="display:none;" />
    <input name="moostndi5vtvpc0fy5sboa" type="text" id="moostndi5vtvpc0fy5sboa" style="display:none;" />
    <input name="1bps10gceliasg41iy455l" type="text" id="1bps10gceliasg41iy455l" style="display:none;" />
    <input name="a1z1amtyvnrtad55ywiqnc" type="text" id="a1z1amtyvnrtad55ywiqnc" style="display:none;" />
    <input name="m3jyv1ibdslgoelr5wdlfd" type="text" id="m3jyv1ibdslgoelr5wdlfd" style="display:none;" />
    <input name="4dgqbpwew3ngbgwdnxaqf4" type="text" id="4dgqbpwew3ngbgwdnxaqf4" style="display:none;" />
    <input name="hocvr1ykprqs5a4agnnfie" type="text" id="hocvr1ykprqs5a4agnnfie" />
    *

Password

 <input name="xugw1irortnb5sraht3azj" type="password" id="xugw1irortnb5sraht3azj" style="display:none;" />
 <input name="bzzunemwbpxb1vpydi1qcv" type="password" id="bzzunemwbpxb1vpydi1qcv" style="display:none;" />
 <input name="w4gxjqkwvd4n50vqqehcab" type="password" id="w4gxjqkwvd4n50vqqehcab" style="display:none;" />
 <input name="bzxdws3vj04w2iargab32a" type="password" id="bzxdws3vj04w2iargab32a" style="display:none;" />
 <input name="lun5ji01ou42tafgvmhc4t" type="password" id="lun5ji01ou42tafgvmhc4t" style="display:none;" />
 <input name="x1rkfxp4sjwtlwvdpsdjkq" type="password" id="x1rkfxp4sjwtlwvdpsdjkq" style="display:none;" />
 <input name="cptv2l0ffvznmop4iqycoe" type="password" id="cptv2l0ffvznmop4iqycoe" style="display:none;" />
 <input name="couyswy1yfm22nbvshuvrv" type="password" id="couyswy1yfm22nbvshuvrv" style="display:none;" />
 <input name="yninikw54iub5zucjoseb2" type="password" id="yninikw54iub5zucjoseb2" style="display:none;" />
 <input name="ngb4uczri1lmusbh0ztgkf" type="password" id="ngb4uczri1lmusbh0ztgkf" style="display:none;" />
 <input name="e5dt2tozqrbiseaipzetp1" type="password" id="e5dt2tozqrbiseaipzetp1" style="display:none;" />
 <input name="rkcjmknvghdfdmhcpfhvrv" type="password" id="rkcjmknvghdfdmhcpfhvrv" style="display:none;" />
 <input name="moostndi5vtep5rwqi5llx" type="password" id="moostndi5vtep5rwqi5llx" style="display:none;" />
 <input name="1bps10gceliy02zzdkpx5p" type="password" id="1bps10gceliy02zzdkpx5p" style="display:none;" />
 <input name="a1z1amtyvnrdygk03jr3vf" type="password" id="a1z1amtyvnrdygk03jr3vf" style="display:none;" />
 <input name="m3jyv1ibdslxju0pbgrmbn" type="password" id="m3jyv1ibdslxju0pbgrmbn" style="display:none;" />
 <input name="4dgqbpwew3n5ru3dbxnzxo" type="password" id="4dgqbpwew3n5ru3dbxnzxo" style="display:none;" />
 <input name="hocvr1ykprqlzaevxie2iv" type="password" id="hocvr1ykprqlzaevxie2iv" />
 *

I am trying to login into a  .aspx website using selenium Python webdriver but the problem is the id class and xpath are changing with reload or refresh. Even, there is multiple input  for user and password entry.

source code screenshot:

UI screenshot:

Body:
You can try to use below XPath expressions:

//div[text()="User Name"]/following-sibling::input[not(@style="display:none;")]

for Username field and

//div[text()="Password"]/following-sibling::input[not(@style="display:none;")]

for Password


问:
Laravel : Removing an element from a collection array
i use a variable called $users to "pluck" only the emails from my users table, using:

$users = user::all()->pluck('email');

when i dd($users), i get this

```<code>```
Collection {#214 ▼
  #items: array:8 [▼
    0 => "adminone@example.com"
    1 => "admintwo@example.com"
    2 => "Adobot@example.com"
    3 => "Lawly@example.com"
    4 => "Cerms@example.com"
    5 => "Charlie@example.com"
    6 => "test@example.com"
    7 => "test001@example.com"
  ]
}
```
</code>```

meaning that $users isn't purely an array, i get various types of errors when i treat it like an array.

my question is, in php (in a Laravel Framework) how do i remove a specific user's email from the variable above? or is there a better way to use "pluck" so that it returns an array instead?

thanks in advance.

答:
I had this problem too and i solved it like this:

DB::table('user')->pluck('email')->all();

Body:
i use a variable called $users to "pluck" only the emails from my users table, using:

$users = user::all()->pluck('email');

when i dd($users), i get this

Collection {#214 ▼
  #items: array:8 [▼
    0 => "adminone@example.com"
    1 => "admintwo@example.com"
    2 => "Adobot@example.com"
    3 => "Lawly@example.com"
    4 => "Cerms@example.com"
    5 => "Charlie@example.com"
    6 => "test@example.com"
    7 => "test001@example.com"
  ]
}

meaning that $users isn't purely an array, i get various types of errors when i treat it like an array.

my question is, in php (in a Laravel Framework) how do i remove a specific user's email from the variable above? or is there a better way to use "pluck" so that it returns an array instead?

thanks in advance.


问:
How to create a Nuget Package for Xamarin Forms application
Recently I have started working on Xamarin and I have created a UI component which I can use across multiple projects. I have created Entry component for Xamarin.Forms and added my own customisation for iOS and android.

Now I want to create a Nuget Package which I can directly download from Nuget store for other projects. I'm looking for proper steps for creating a Nuget Package based on my xamarin solution. But unfortunately I'm not getting proper steps which I can follow to create this.

All kind of help is appreciated.

答:
This question is old but for the folks that land here like me, this has been smoothed a bit.

It is explained in : https://developer.xamarin.com/guides/cross-platform/application_fundamentals/nuget-multiplatform-libraries/single-codebase/

Basically you can do it more GUI oriented in Xamarin Studio.

There is an option like this now in Xamarin Studio


问:
Android: advanced text drawing (columns, fixed height, paging). How?
I'm porting application from iPad to Galaxy Tab and, since I hadn't had much experience with programming for Android devices I'd like to know some "general" things.

I've used CoreText for all my ipad text drawing needs, what can I use in Android? How can I break large text apart dividing it in to frames/paths and then layout them on screen (think, columns in news application articles). It looks like that Paint class does some things related to what I need, but I don't know if that's the proper way to go.

Please, enlighten me :)

答: The Layout object is what you are looking for, in particular its subclass StaticLayout. It's what's used by TextView to shape the text and render it on screen. It's basically a smart wrapper around the various methods offered by Paint to measure and draw text.</p>


问:
Using Flexbox, how do I programmatically move a div?
I have a div within a flex container. I need to programmatically position - change top and left - and size - change width and height this div. How do I do this. Flex ignores changes to top and left but does seem to accept changes to width and height.

答:
Top and Left will only affect it if you are setting the div's position. e.g. if you wanted to position it inside the container then you would set position: relative on the container and position: absolute on the div.

However it would be bad practise to use position on a flexbox item since flexbox allows you to easily align and position items itself. Have a look at CSS Tricks flexbox guide to understand how you can manipulate the flexbox properties.


问:
IP Geocode using PHP echo
I'm trying to display the users country (based on their IP) in a form input value.

Here's my code so far ..

```<code><input style="display:block" type="text" name="country" id="country" value="<?php
$pageContent = file_get_contents('http://freegeoip.net/json/echo $_SERVER['REMOTE_ADDR']');
$parsedJson  = json_decode($pageContent);
echo $parsedJson->country_name; ?>" />
</code>```

I'm using PHP JSON-decode to get the data from "http://freegeoip.net/json/(IP ADDRESS)".

That website geocodes the IP address and returns a country name.

What I want to do is to be able to substitute in a users IP address into that web address, which would then return the country name of the user. The best way I could think of was by using

```<code><?php echo $_SERVER['REMOTE_ADDR']; ?>
</code>```

but when I put it in I get a Server Error.

How would I go about doing this?

答:
I've been needing the GeoIPservices myself in some project lately.
I've created a ** PHP wrapper**, in case others are looking for a PHP helper for this.

Can be found at https://github.com/DaanDeSmedt/FreeGeoIp-PHP-Wrapper

Title: IP Geocode using PHP echo

Body:
I'm trying to display the users country (based on their IP) in a form input value.

Here's my code so far ..

<input style="display:block" type="text" name="country" id="country" value="<?php
$pageContent = file_get_contents('http://freegeoip.net/json/echo $_SERVER['REMOTE_ADDR']');
$parsedJson  = json_decode($pageContent);
echo $parsedJson->country_name; ?>" />

I'm using PHP JSON-decode to get the data from "http://freegeoip.net/json/(IP ADDRESS)".

That website geocodes the IP address and returns a country name.

What I want to do is to be able to substitute in a users IP address into that web address, which would then return the country name of the user. The best way I could think of was by using

<?php echo $_SERVER['REMOTE_ADDR']; ?>

but when I put it in I get a Server Error.

How would I go about doing this?


问:
Not getting index value of the clicked a href tag
I have following html

```<code>HTML code for testing purposes (do not submit uncommented):
<body>
  In my life, I used the following web search engines:<br/>
  <a href="#test" id="mmYahooId">Yahoo!</a><br/>
  <a href="#test" id="mmaltaVistaId">AltaVista</a><br/>
  <a href="#test" id="mmgooId">Google</a><br/>
</body>
</code>```

My JS

```<code>$('a[id^=mm]').on('click', function () {
alert("test")
var as = document.body.getElementsByTagName("a");
alert("test")
for(var i=0; i < as.length;i++) {
  as[i].onClick = function(){
          alert(i);
  }
   }
});
</code>```

The alert is not giving me the index of the link clicked. How can i get the index?

答:
Try the following:

$('a[id^=mm]').on('click', function () {
    var nodeList = Array.prototype.slice.call(document.body.getElementsByTagName("a"));
    var index = nodeList.indexOf($(this)[0]);
    alert('You have clicked: '+index)
}); ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
In my life, I used the following web search engines:<br/>
Yahoo!<br/>
AltaVista<br/>
Google<br/></code>```

Body:
I have following html

HTML code for testing purposes (do not submit uncommented):

  In my life, I used the following web search engines:

  Yahoo!

  AltaVista

  Google

My JS

$('a[id^=mm]').on('click', function () {
alert("test")
var as = document.body.getElementsByTagName("a");
alert("test")
for(var i=0; i < as.length;i++) {
  as[i].onClick = function(){
          alert(i);
  }
   }
});

The alert is not giving me the index of the link clicked. How can i get the index?

Body:
Try the following:

$('a[id^=mm]').on('click', function () {
    var nodeList = Array.prototype.slice.call(document.body.getElementsByTagName("a"));
    var index = nodeList.indexOf($(this)[0]);
    alert('You have clicked: '+index)
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
In my life, I used the following web search engines:<br/>
<a href="#test" id="mmYahooId">Yahoo!</a><br/>
<a href="#test" id="mmaltaVistaId">AltaVista</a><br/>
<a href="#test" id="mmgooId">Google</a><br/>


问:
Android Dialog problem with TabView
```<code>   My problem is when a dialog is opened, if I change the tab,  that dialog is displayed in the activity in the next tab.How to remove that .
</code>```

Pls help.
This occurs because according to my requirement I can interact with the dialog and the view behind at the same time.

答: I resolved it by dismissing the dialog in onPause() method</p>

Title: Android Dialog problem with TabView

Body:
   My problem is when a dialog is opened, if I change the tab,  that dialog is displayed in the activity in the next tab.How to remove that .

Pls help.
This occurs because according to my requirement I can interact with the dialog and the view behind at the same time.


问:
How to add Firebase into android
I want added Firebase into my application. I write below codes, but when running application I can't see TOKEN in log!

My dependencies :

```<code>dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
    compile 'com.google.firebase:firebase-messaging:10.0.1'
    testCompile 'junit:junit:4.12'
}

apply plugin: 'com.google.gms.google-services'
</code>```

Manifest :

```<code><application>
...
        <!--Firebase service-->
        <service android:name=".CloudMSG.MyFirebaseInctanceIdService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>

    </application>
</code>```

MyFirebaseInctanceIdService :

```<code>public class MyFirebaseInctanceIdService extends FirebaseInstanceIdService {

    private static final String TAG = "MyFirebaseInctance";

    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d("MyFirebaseInctance", "Refreshed token: " + refreshedToken);

        // If you want to send messages to this application instance or
        // manage this apps subscriptions on the server side, send the
        // Instance ID token to your app server.
        //sendRegistrationToServer(refreshedToken);
    }
}
</code>```

Logs:

```<code>03-30 13:36:42.943 9487-9487/? I/art: Late-enabling -Xcheck:jni
03-30 13:36:43.218 9487-9487/com.example.mohammad.a1_firebase D/FirebaseApp: com.google.firebase.auth.FirebaseAuth is not linked. Skipping initialization.
03-30 13:36:43.269 9487-9487/com.example.mohammad.a1_firebase W/InstanceID/Rpc: Found 10004
03-30 13:36:43.298 9487-9487/com.example.mohammad.a1_firebase D/FirebaseApp: com.google.firebase.crash.FirebaseCrash is not linked. Skipping initialization.
03-30 13:36:43.364 9487-9487/com.example.mohammad.a1_firebase I/FA: App measurement is starting up, version: 10084
03-30 13:36:43.364 9487-9487/com.example.mohammad.a1_firebase I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
03-30 13:36:43.364 9487-9487/com.example.mohammad.a1_firebase D/FA: Debug-level message logging enabled
03-30 13:36:43.364 9487-9487/com.example.mohammad.a1_firebase D/FA: AppMeasurement singleton hash: 720240273
03-30 13:36:43.404 9487-9487/com.example.mohammad.a1_firebase V/FA: Collection enabled
03-30 13:36:43.404 9487-9487/com.example.mohammad.a1_firebase V/FA: App package, google app id: com.example.mohammad.a1_firebase, 1:685652680518:android:0280a3bc1c6da8cb
03-30 13:36:43.405 9487-9487/com.example.mohammad.a1_firebase I/FA: To enable faster debug mode event logging run:
                                                                      adb shell setprop debug.firebase.analytics.app com.example.mohammad.a1_firebase
03-30 13:36:43.463 9487-9487/com.example.mohammad.a1_firebase V/FA: Registered activity lifecycle callback
03-30 13:36:43.465 9487-9487/com.example.mohammad.a1_firebase I/FirebaseInitProvider: FirebaseApp initialization successful
03-30 13:36:43.467 9487-9487/com.example.mohammad.a1_firebase I/InstantRun: Starting Instant Run Server for com.example.mohammad.a1_firebase
03-30 13:36:43.471 9487-9587/com.example.mohammad.a1_firebase V/FA: Using measurement service
03-30 13:36:43.489 9487-9587/com.example.mohammad.a1_firebase V/FA: Connecting to remote service
03-30 13:36:43.528 9487-9587/com.example.mohammad.a1_firebase W/GooglePlayServicesUtil: Google Play services out of date.  Requires 10084000 but found 6599430
03-30 13:36:43.612 9487-9487/com.example.mohammad.a1_firebase D/ContextHelper: convertTheme. context->name=com.example.mohammad.a1_firebase themeResourceId=2131230883
03-30 13:36:43.656 9487-9487/com.example.mohammad.a1_firebase W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
03-30 13:36:43.690 9487-9487/com.example.mohammad.a1_firebase V/FA: onActivityCreated
03-30 13:36:43.696 9487-9487/com.example.mohammad.a1_firebase I/PhoneWindow: [generateLayout] setColorNavigationBar => color=0x ff000001
03-30 13:36:43.718 9487-9487/com.example.mohammad.a1_firebase D/PhoneWindowEx: [PWEx][generateLayout] setNavigationBarColor2 : colors=0xfff5f5f5
03-30 13:36:43.718 9487-9487/com.example.mohammad.a1_firebase I/PhoneWindow: [setNavigationBarColor2] color=0x fff5f5f5
03-30 13:36:43.859 9487-9587/com.example.mohammad.a1_firebase V/FA: Using measurement service
03-30 13:36:43.859 9487-9587/com.example.mohammad.a1_firebase V/FA: Connection attempt already in progress
03-30 13:36:43.864 9487-9587/com.example.mohammad.a1_firebase V/FA: Activity resumed, time: 1436094125
03-30 13:36:43.879 9487-9612/com.example.mohammad.a1_firebase D/OpenGLRenderer: Render dirty regions requested: true
03-30 13:36:43.881 9487-9612/com.example.mohammad.a1_firebase I/Adreno-EGL: <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.00.02.042.013_msm8974_LA.BF.1.1.1_RB1__release_AU ()
                                                                            OpenGL ES Shader Compiler Version: E031.25.03.00
                                                                            Build Date: 01/21/15 Wed
                                                                            Local Branch: mybranch7061829
                                                                            Remote Branch: quic/LA.BF.1.1.1_rb1.7
                                                                            Local Patches: NONE
                                                                            Reconstruct Branch: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.00.02.042.013 +  NOTHING
03-30 13:36:43.882 9487-9612/com.example.mohammad.a1_firebase I/OpenGLRenderer: Initialized EGL, version 1.4
03-30 13:36:43.910 9487-9612/com.example.mohammad.a1_firebase D/OpenGLRenderer: Enabling debug mode 0
03-30 13:36:43.916 9487-9487/com.example.mohammad.a1_firebase D/Atlas: Validating map...
03-30 13:36:43.927 9487-9487/com.example.mohammad.a1_firebase W/FA: Service connection failed: ConnectionResult{statusCode=SERVICE_VERSION_UPDATE_REQUIRED, resolution=null, message=null}
03-30 13:36:43.936 9487-9592/com.example.mohammad.a1_firebase D/FirebaseInstanceId: background sync failed: SERVICE_NOT_AVAILABLE, retry in 30s
03-30 13:36:44.008 9487-9502/com.example.mohammad.a1_firebase W/art: Suspending all threads took: 5.068ms
03-30 13:36:44.047 9487-9487/com.example.mohammad.a1_firebase W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
03-30 13:36:44.183 9487-9487/com.example.mohammad.a1_firebase I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@755dbad time:128236912
03-30 13:37:14.017 9487-10051/com.example.mohammad.a1_firebase D/FirebaseInstanceId: background sync failed: SERVICE_NOT_AVAILABLE, retry in 60s
</code>```

How can I fix this issue and show Firebase token in logs?

答:
Try to uninstall the application and re-install , you will see the
  Refreshed token in the logcat.

Also check in firebase console that Anonymous sign-in status is
  Enabled or not in Authentication menu -> Sign in method

Title: How to add Firebase into android

Body:
I want added Firebase into my application. I write below codes, but when running application I can't see TOKEN in log!

My dependencies :

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
    compile 'com.google.firebase:firebase-messaging:10.0.1'
    testCompile 'junit:junit:4.12'
}

apply plugin: 'com.google.gms.google-services'

Manifest :

<application>
...

        <service android:name=".CloudMSG.MyFirebaseInctanceIdService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>

    </application>

MyFirebaseInctanceIdService :

public class MyFirebaseInctanceIdService extends FirebaseInstanceIdService {

    private static final String TAG = "MyFirebaseInctance";

    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d("MyFirebaseInctance", "Refreshed token: " + refreshedToken);

        // If you want to send messages to this application instance or
        // manage this apps subscriptions on the server side, send the
        // Instance ID token to your app server.
        //sendRegistrationToServer(refreshedToken);
    }
}

Logs:

03-30 13:36:42.943 9487-9487/? I/art: Late-enabling -Xcheck:jni
03-30 13:36:43.218 9487-9487/com.example.mohammad.a1_firebase D/FirebaseApp: com.google.firebase.auth.FirebaseAuth is not linked. Skipping initialization.
03-30 13:36:43.269 9487-9487/com.example.mohammad.a1_firebase W/InstanceID/Rpc: Found 10004
03-30 13:36:43.298 9487-9487/com.example.mohammad.a1_firebase D/FirebaseApp: com.google.firebase.crash.FirebaseCrash is not linked. Skipping initialization.
03-30 13:36:43.364 9487-9487/com.example.mohammad.a1_firebase I/FA: App measurement is starting up, version: 10084
03-30 13:36:43.364 9487-9487/com.example.mohammad.a1_firebase I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
03-30 13:36:43.364 9487-9487/com.example.mohammad.a1_firebase D/FA: Debug-level message logging enabled
03-30 13:36:43.364 9487-9487/com.example.mohammad.a1_firebase D/FA: AppMeasurement singleton hash: 720240273
03-30 13:36:43.404 9487-9487/com.example.mohammad.a1_firebase V/FA: Collection enabled
03-30 13:36:43.404 9487-9487/com.example.mohammad.a1_firebase V/FA: App package, google app id: com.example.mohammad.a1_firebase, 1:685652680518:android:0280a3bc1c6da8cb
03-30 13:36:43.405 9487-9487/com.example.mohammad.a1_firebase I/FA: To enable faster debug mode event logging run:
                                                                      adb shell setprop debug.firebase.analytics.app com.example.mohammad.a1_firebase
03-30 13:36:43.463 9487-9487/com.example.mohammad.a1_firebase V/FA: Registered activity lifecycle callback
03-30 13:36:43.465 9487-9487/com.example.mohammad.a1_firebase I/FirebaseInitProvider: FirebaseApp initialization successful
03-30 13:36:43.467 9487-9487/com.example.mohammad.a1_firebase I/InstantRun: Starting Instant Run Server for com.example.mohammad.a1_firebase
03-30 13:36:43.471 9487-9587/com.example.mohammad.a1_firebase V/FA: Using measurement service
03-30 13:36:43.489 9487-9587/com.example.mohammad.a1_firebase V/FA: Connecting to remote service
03-30 13:36:43.528 9487-9587/com.example.mohammad.a1_firebase W/GooglePlayServicesUtil: Google Play services out of date.  Requires 10084000 but found 6599430
03-30 13:36:43.612 9487-9487/com.example.mohammad.a1_firebase D/ContextHelper: convertTheme. context->name=com.example.mohammad.a1_firebase themeResourceId=2131230883
03-30 13:36:43.656 9487-9487/com.example.mohammad.a1_firebase W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
03-30 13:36:43.690 9487-9487/com.example.mohammad.a1_firebase V/FA: onActivityCreated
03-30 13:36:43.696 9487-9487/com.example.mohammad.a1_firebase I/PhoneWindow: [generateLayout] setColorNavigationBar => color=0x ff000001
03-30 13:36:43.718 9487-9487/com.example.mohammad.a1_firebase D/PhoneWindowEx: [PWEx][generateLayout] setNavigationBarColor2 : colors=0xfff5f5f5
03-30 13:36:43.718 9487-9487/com.example.mohammad.a1_firebase I/PhoneWindow: [setNavigationBarColor2] color=0x fff5f5f5
03-30 13:36:43.859 9487-9587/com.example.mohammad.a1_firebase V/FA: Using measurement service
03-30 13:36:43.859 9487-9587/com.example.mohammad.a1_firebase V/FA: Connection attempt already in progress
03-30 13:36:43.864 9487-9587/com.example.mohammad.a1_firebase V/FA: Activity resumed, time: 1436094125
03-30 13:36:43.879 9487-9612/com.example.mohammad.a1_firebase D/OpenGLRenderer: Render dirty regions requested: true
03-30 13:36:43.881 9487-9612/com.example.mohammad.a1_firebase I/Adreno-EGL: <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.00.02.042.013_msm8974_LA.BF.1.1.1_RB1__release_AU ()
                                                                            OpenGL ES Shader Compiler Version: E031.25.03.00
                                                                            Build Date: 01/21/15 Wed
                                                                            Local Branch: mybranch7061829
                                                                            Remote Branch: quic/LA.BF.1.1.1_rb1.7
                                                                            Local Patches: NONE
                                                                            Reconstruct Branch: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.00.02.042.013 +  NOTHING
03-30 13:36:43.882 9487-9612/com.example.mohammad.a1_firebase I/OpenGLRenderer: Initialized EGL, version 1.4
03-30 13:36:43.910 9487-9612/com.example.mohammad.a1_firebase D/OpenGLRenderer: Enabling debug mode 0
03-30 13:36:43.916 9487-9487/com.example.mohammad.a1_firebase D/Atlas: Validating map...
03-30 13:36:43.927 9487-9487/com.example.mohammad.a1_firebase W/FA: Service connection failed: ConnectionResult{statusCode=SERVICE_VERSION_UPDATE_REQUIRED, resolution=null, message=null}
03-30 13:36:43.936 9487-9592/com.example.mohammad.a1_firebase D/FirebaseInstanceId: background sync failed: SERVICE_NOT_AVAILABLE, retry in 30s
03-30 13:36:44.008 9487-9502/com.example.mohammad.a1_firebase W/art: Suspending all threads took: 5.068ms
03-30 13:36:44.047 9487-9487/com.example.mohammad.a1_firebase W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
03-30 13:36:44.183 9487-9487/com.example.mohammad.a1_firebase I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@755dbad time:128236912
03-30 13:37:14.017 9487-10051/com.example.mohammad.a1_firebase D/FirebaseInstanceId: background sync failed: SERVICE_NOT_AVAILABLE, retry in 60s

How can I fix this issue and show Firebase token in logs?


问:
Generating a migration with custom SQL code in Phoenix
I want to generate a new Ecto Migration with custom SQL code instead of using the provided helpers. The current mix generator tasks handle only models.

How can I write raw SQL code in a migration?

答:
First create a new migration using the provided Mix Task and call it whatever you want:

```<code>$ mix ecto.gen.migration my_custom_migration
</code>```

Now edit the newly generated migration module in your priv/repo/migrations/ and replace the empty change method with up and down methods.

You can then call execute/1 with your raw SQL code in them:

```<code>defmodule MyApp.Repo.Migrations.MyCustomMigration do
  use Ecto.Migration

  def up do
    # Your custom SQL code
    execute "CREATE TABLE some_table ..."
  end

  def down do
    execute "DROP TABLE some_table;"
  end
end
</code>```

Source: Execute Raw SQL In An Ecto Migration

Body:
First create a new migration using the provided Mix Task and call it whatever you want:

$ mix ecto.gen.migration my_custom_migration

Now edit the newly generated migration module in your priv/repo/migrations/ and replace the empty change method with up and down methods.

You can then call execute/1 with your raw SQL code in them:

defmodule MyApp.Repo.Migrations.MyCustomMigration do
  use Ecto.Migration

  def up do
    # Your custom SQL code
    execute "CREATE TABLE some_table ..."
  end

  def down do
    execute "DROP TABLE some_table;"
  end
end

Source: Execute Raw SQL In An Ecto Migration


问:
Why need synchronizedMap() if there is ConcurrentHashMap?
I read an article about thread safe maps and got a question. Collections.synchronizedMap() proxies underlying map with adding synchronized blocks on each method. On the other hand ConcurrentHashMap doesn't lock the whole map on read/write operations. Which means all operations in multi thread system are faster.

So what are the benefits of using synchronizedMap() nowadays? I see the only:

it's available since java 1.2 (vs java 1.5 for ConcurrentHashMap)

can store nullable values (if underlying map can do it)

Are there any other situations when synchronizedMap() is better?

答:
From the ConcurrentHashMap documentation:

"...there is not any support for locking the entire table in a way
  that prevents all access"

When iterating through ConcurrentHashMap elements you may see updates done at the same time by other threads. If you want to prevent such updates you can use Collections.synchronizedMap() instead and put iteration logic in synchronized(map) block.


问:
Transform array by cutting in half but extend elements
I want to transform an existing array to display it. Therefore I cut the array in half but add the content of the cut element to the remained elements.

```<code># source structure
s = [[1, 'blue'],
     [2, 'red'],
     [3, 'yellow'],
     [4, 'green'],
     [5, 'orange'],
     [6, 'black']]

# result structure
format_array(s)
# [[1, 'blue', 4, 'green'],
#  [2, 'red', 5, 'orange'],
#  [3, 'yellow', 6, 'black']]
</code>```

How would you achieve it?

Body:
I want to transform an existing array to display it. Therefore I cut the array in half but add the content of the cut element to the remained elements.

# source structure
s = [[1, 'blue'],
     [2, 'red'],
     [3, 'yellow'],
     [4, 'green'],
     [5, 'orange'],
     [6, 'black']]

# result structure
format_array(s)
# [[1, 'blue', 4, 'green'],
#  [2, 'red', 5, 'orange'],
#  [3, 'yellow', 6, 'black']]

How would you achieve it?

Body:
a = [[1, "blue"], [2, "red"], [3, "yellow"], [4, "green"], [5, "orange"], [6, "black"]]
first, last = a.first(a.size / 2), a.last(a.size / 2)
#=> [[[1, "blue"], [2, "red"], [3, "yellow"]], [[4, "green"], [5, "orange"], [6, "black"]]]
first.zip(last).map(&:flatten)
# [
#   [1, "blue", 4, "green"],
#   [2, "red", 5, "orange"],
#   [3, "yellow", 6, "black"]
# ]


问:
Get(int) asp.net wep api
I really confused with my web api now. Here is my code for Get method:

```<code>public Employee Get(int id)
{
            using (EmployeeDBEntities entities = new EmployeeDBEntities())
            {
                return entities.Employees.FirstOrDefault(e => e.ID==id);
            }
        }
</code>```

And I use jquery ajax to get that:

```<code>$(document).ready(function () {
    $('#btn').click(function () {
        $.ajax({
            url: 'api/employees/1',
            method: 'GET',

            success: function (data) {
                $('#ul').empty();
                $.each(data, function (index, value) {
                    var row = $('<tr><td>' + value.ID + '</td><td>'
                        + value.FirstName + '</td><td>'
                        + value.LastName + '</td><td>'
                        + value.Gender + '</td><td>'
                        + value.Salary + '</td></tr>');
                    $('#ul').append(row);
                });
            }
        });
    });
});
</code>```

when I ran it, it just returned lots of 'undefined'. However when I run "http://localhost:52178/api/employees/1" in browser, I got the right xml I want. Can anyone help me with that?

答:
Use   contentType: "application/json; charset=utf-8" in ajax options

```<code> $.ajax({
        url: 'api/employees/1',
        method: 'GET',
        contentType: "application/json; charset=utf-8",/*use this option*/
        success: function (data) {
            $('#ul').empty();
            $.each(data, function (index, value) {
                var row = $('<tr><td>' + value.ID + '</td><td>'
                    + value.FirstName + '</td><td>'
                    + value.LastName + '</td><td>'
                    + value.Gender + '</td><td>'
                    + value.Salary + '</td></tr>');
                $('#ul').append(row);
            });
        }
    });
</code>```

Title: Get(int) asp.net wep api

Body:
I really confused with my web api now. Here is my code for Get method:

public Employee Get(int id)
{
            using (EmployeeDBEntities entities = new EmployeeDBEntities())
            {
                return entities.Employees.FirstOrDefault(e => e.ID==id);
            }
        }

And I use jquery ajax to get that:

$(document).ready(function () {
    $('#btn').click(function () {
        $.ajax({
            url: 'api/employees/1',
            method: 'GET',

            success: function (data) {
                $('#ul').empty();
                $.each(data, function (index, value) {
                    var row = $('
' + value.ID + '	'
                        + value.FirstName + '	'
                        + value.LastName + '	'
                        + value.Gender + '	'
                        + value.Salary + '
');
                    $('#ul').append(row);
                });
            }
        });
    });
});

when I ran it, it just returned lots of 'undefined'. However when I run "http://localhost:52178/api/employees/1" in browser, I got the right xml I want. Can anyone help me with that?

Body:
Use   contentType: "application/json; charset=utf-8" in ajax options

 $.ajax({
        url: 'api/employees/1',
        method: 'GET',
        contentType: "application/json; charset=utf-8",/*use this option*/
        success: function (data) {
            $('#ul').empty();
            $.each(data, function (index, value) {
                var row = $('<tr><td>' + value.ID + '</td><td>'
                    + value.FirstName + '</td><td>'
                    + value.LastName + '</td><td>'
                    + value.Gender + '</td><td>'
                    + value.Salary + '</td></tr>');
                $('#ul').append(row);
            });
        }
    });


问:
Javascript question: about variable definition
I have no idea why it didn't work if I specify a variable with 'var':
like this:

```<code>var mytool = function(){
      return {
         method: function(){}
     }
}();
</code>```

And later I use it in the same template: mytool.method. This will output mytool was not defined.

But if I define it like this:

```<code>     mytool = function(){
          return {
             method: function(){}
         }
    }();
</code>```

Then it works.

答:
Javascript has function scope. A variable is in scope within the function it was declared in, which also includes any functions you may define within that function.

```<code>function () {
    var x;

    function () {
        // x is in scope here
        x = 42;

        y = 'foo';
    }

    // x is in scope here
}

// x is out of scope here

// y is in scope here
</code>```

When declaring a variable, you use the var keyword.

If you don't use the var keyword, Javascript will traverse up the scope chain, expecting to find the variable declared somewhere in a higher function. That's why the x = 42 assignment above assigns to the x that was declared with var x one level higher.

If you did not declare the variable at all before, Javascript will traverse all the way to the global object and make that variable there for you. The y variable above got attached to the global object as window.y and is therefore in scope outside the function is was declared in.

This is bad and you need to avoid it. Properly declare variables in the right scope, using var.

Body:
I have no idea why it didn't work if I specify a variable with 'var':
like this:

var mytool = function(){
      return {
         method: function(){}
     }
}();

And later I use it in the same template: mytool.method. This will output mytool was not defined.

But if I define it like this:

     mytool = function(){
          return {
             method: function(){}
         }
    }();

Then it works.

Body:
Javascript has function scope. A variable is in scope within the function it was declared in, which also includes any functions you may define within that function.

function () {
    var x;

    function () {
        // x is in scope here
        x = 42;

        y = 'foo';
    }

    // x is in scope here
}

// x is out of scope here

// y is in scope here

When declaring a variable, you use the var keyword.

If you don't use the var keyword, Javascript will traverse up the scope chain, expecting to find the variable declared somewhere in a higher function. That's why the x = 42 assignment above assigns to the x that was declared with var x one level higher.

If you did not declare the variable at all before, Javascript will traverse all the way to the global object and make that variable there for you. The y variable above got attached to the global object as window.y and is therefore in scope outside the function is was declared in.

This is bad and you need to avoid it. Properly declare variables in the right scope, using var.


问:
Getting image path in public folder in laravel
I'm making direction using this method to upload my image

```<code> mkdir(public_path().'/website/'.$path,0777, true);
</code>```

It's supposed to create it on the root folder (Public_html) , but i found it created on new folder with name (public ) , so now i can't get the path of the image using this code

```<code> <img src="{{url('public/website/'.$file->path.$file->file)}}"  />
</code>```

how to get the correct path of the image or even create the folder on the public_html root path ?

答:
Try this to get image

```<code> <img src="<?php echo public_path().'/website/'.$path.$file->file;  ?>"  />
</code>```

Body:
I'm making direction using this method to upload my image

 mkdir(public_path().'/website/'.$path,0777, true);

It's supposed to create it on the root folder (Public_html) , but i found it created on new folder with name (public ) , so now i can't get the path of the image using this code

 path.$file->file)}}"  />

how to get the correct path of the image or even create the folder on the public_html root path ?

Body:
Try this to get image

 <img src="<?php echo public_path().'/website/'.$path.$file->file;  ?>"  />


问:
How to implement fmt::Display on a generically-typed enum in Rust?
I have implemented my linked list using this recursive enum, but now I'd like to implement a custom display format for it

```<code>use std::fmt;

#[derive(Debug)]
enum List<A> {
    Empty,
    Cons(A, Box<List<A>>),
}

impl<T> fmt::Display for List<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            List::Empty => write!(f, "()"),
            List::Cons(x, ref xs) => write!(f, "({} {})", x, xs),
        }
    }
}
</code>```

Error

error[E0277]: the trait bound `T: std::fmt::Display` is not satisfied
  --> src/main.rs:13:59
   |
13 |             List::Cons(x, ref xs) => write!(f, "({} {})", x, xs),
   |                                                           ^ the trait `std::fmt::Display` is not implemented for `T`
   |
   = help: consider adding a `where T: std::fmt::Display` bound
   = note: required by `std::fmt::Display::fmt`
```

<p><strong>Here's the rest of my code if that matters</strong></p>

```fn cons(x: A, xs: List) -> List {
    return List::Cons(x, Box::new(xs));
}

fn len(xs: &List) -> i32 {
    match *xs {
        List::Empty => 0,
        List::Cons(_, ref xs) => 1 + len(xs),
    }
}

fn map(f: &Fn(&A) -> B, xs: &List) -> List {
    match *xs {
        List::Empty => List::Empty,
        List::Cons(ref x, ref xs) => cons(f(x), map(f, xs)),
    }
}

fn main() {
    let xs = cons(1, cons(2, cons(3, List::Empty)));
    println!("{}", xs);
    println!("{:?}", len(&xs));

    let f = |x: &i32| (*x) * (*x);
    let ys = map(&f, &xs);
    println!("{}", ys);
    println!("{}", List::Empty);
}
```

<p><strong>Expected output</strong></p>

<pre class="lang-none prettyprint-override"><code>(1 (2 (3 ())))
3
(1 (4 (9 ())))
()
</code>```

Really what I'd like to see this, but I have absolutely no idea how I'd go about getting this kind of output using fmt::Result

(1 2 3)
3
(1 4 9)
()
```

答:
Solving the compiler error

You are missing a trait bound. That is, you need to tell Rust that T can be displayed:

```<code>impl<T: fmt::Display> fmt::Display for List<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            List::Empty => write!(f, "()"),
            List::Cons(ref x, ref xs) => write!(f, "({} {})", x, xs),
        }
    }
}
</code>```

Note the trait bound T: fmt::Display. This basically means: if T implements fmt::Display, then List<T> implements fmt::Display as well.

The icing on the cake

I am unsure whether you can get nice formatting with a recursive definition. Furthermore, Rust does not guarantee tail-call optimization, so there would always be the possibility of a stack overflow.

An alternative definition could be:

```<code>fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    write!(f, "(")?;
    let mut temp = self;
    while let List::Cons(ref x, ref xs) = *temp {
        write!(f, "{}", x)?;

        // Print trailing whitespace if there are more elements
        if let List::Cons(_, _) = **xs {
            write!(f, " ")?;
        }

        temp = xs;
    }

    write!(f, ")")
}
</code>```

Note the ? after most write! macro invocations. It basically means: if this write! results in an error, return the error now. Otherwise, continue executing the function.

Body:
I have implemented my linked list using this recursive enum, but now I'd like to implement a custom display format for it

use std::fmt;

#[derive(Debug)]
enum List {
    Empty,
    Cons(A, Box<List>),
}

impl<T> fmt::Display for List<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            List::Empty => write!(f, "()"),
            List::Cons(x, ref xs) => write!(f, "({} {})", x, xs),
        }
    }
}

Error

error[E0277]: the trait bound `T: std::fmt::Display` is not satisfied
  --> src/main.rs:13:59
   |
13 |             List::Cons(x, ref xs) => write!(f, "({} {})", x, xs),
   |                                                           ^ the trait `std::fmt::Display` is not implemented for `T`
   |
   = help: consider adding a `where T: std::fmt::Display` bound
   = note: required by `std::fmt::Display::fmt`

Here's the rest of my code if that matters

fn cons(x: A, xs: List) -> List {
    return List::Cons(x, Box::new(xs));
}

fn len(xs: &List) -> i32 {
    match *xs {
        List::Empty => 0,
        List::Cons(_, ref xs) => 1 + len(xs),
    }
}

fn map(f: &Fn(&A) -> B, xs: &List) -> List {
    match *xs {
        List::Empty => List::Empty,
        List::Cons(ref x, ref xs) => cons(f(x), map(f, xs)),
    }
}

fn main() {
    let xs = cons(1, cons(2, cons(3, List::Empty)));
    println!("{}", xs);
    println!("{:?}", len(&xs));

    let f = |x: &i32| (*x) * (*x);
    let ys = map(&f, &xs);
    println!("{}", ys);
    println!("{}", List::Empty);
}

Expected output

(1 (2 (3 ())))
3
(1 (4 (9 ())))
()

Really what I'd like to see this, but I have absolutely no idea how I'd go about getting this kind of output using fmt::Result

(1 2 3)
3
(1 4 9)
()

Body:
Solving the compiler error

You are missing a trait bound. That is, you need to tell Rust that T can be displayed:

impl<T: fmt::Display> fmt::Display for List<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            List::Empty => write!(f, "()"),
            List::Cons(ref x, ref xs) => write!(f, "({} {})", x, xs),
        }
    }
}

Note the trait bound T: fmt::Display. This basically means: if T implements fmt::Display, then List<T> implements fmt::Display as well.

The icing on the cake

I am unsure whether you can get nice formatting with a recursive definition. Furthermore, Rust does not guarantee tail-call optimization, so there would always be the possibility of a stack overflow.

An alternative definition could be:

fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    write!(f, "(")?;
    let mut temp = self;
    while let List::Cons(ref x, ref xs) = *temp {
        write!(f, "{}", x)?;

        // Print trailing whitespace if there are more elements
        if let List::Cons(_, _) = **xs {
            write!(f, " ")?;
        }

        temp = xs;
    }

    write!(f, ")")
}

Note the ? after most write! macro invocations. It basically means: if this write! results in an error, return the error now. Otherwise, continue executing the function.


问:
How these different assignments are changing the output
```<code>class Feline {
public String type = "f ";
public Feline() {
    System.out.print("feline ");
}
}

public class Main extends Feline {
//public String type = "c ";   //Problem 1
public Main() {
    System.out.print("cougar ");
}
void go() {
    //String type = "d"; //Problem 2
    //type = "d ";             //Problem 3
    System.out.print(this.type + super.type + type);
}
public static void main(String[] args) {
    new Main().go();
}
}
</code>```

The Output :

commenting the Problem 1, 2, 3 The output is feline cougar f f f

uncommenting the Problem 1 The output is feline cougar c f c

uncommenting the Problem 2 The output is feline cougar f f d

uncommenting the Problem 3 The output is feline cougar d d d

答:
Main super is Feline, because of the extend.

With Problem 1, you change this.type and type, in this case they are the same, but you don't change the super.type, it still is the one defined in Feline.

With Problem 2 and 3, you are changing a local variable only, not changing super or public type.

With Problem 2 commented and Problem 3 not commented, you are changing the public type variable because you are not declaring a local variable, you are not doing String type.

Body:
class Feline {
public String type = "f ";
public Feline() {
    System.out.print("feline ");
}
}

public class Main extends Feline {
//public String type = "c ";   //Problem 1
public Main() {
    System.out.print("cougar ");
}
void go() {
    //String type = "d"; //Problem 2
    //type = "d ";             //Problem 3
    System.out.print(this.type + super.type + type);
}
public static void main(String[] args) {
    new Main().go();
}
}

The Output :

commenting the Problem 1, 2, 3 The output is feline cougar f f f

uncommenting the Problem 1 The output is feline cougar c f c

uncommenting the Problem 2 The output is feline cougar f f d

uncommenting the Problem 3 The output is feline cougar d d d

ContentLicense: CC BY-SA 4.0


问:
Ansible: use both lists and their contents as variable values
I have key - value pairs association in the form of:

```<code>- mykey1:
    myvalues1: ['a', 'b', 'c']
- mykey2:
    myvalues2: ['d', 'e']
- mykey3:
    myvalues3: ['f']
</code>```

I know that using the with_dict construct I can iterate over both keys and  values (which are lists).
My question is how can I have a loop that iterates over the list's (values) elements?

The output i would like to be able to achieve is:

```<code>a', 'b', 'c', 'd', 'e', 'f'
</code>```

The problem is that I need to maintain the above associations.
Is there a way to avoid duplicating list declarations?

答:
Here is the construct I came up with:

```<code>associations:
    - { key: mykey1, myvalues: ['a', 'b', 'c', ] }
    - { key: mykey2, myvalues: ['d', 'e'] }
    - { key: mykey3, myvalues: ['f'] }
</code>```

When someone wants to iterate over values as single values

```<code>- name: List single items
  debug:
     msg: "{{ item.1 }}"
   with_subelements:
     - associations
     - myvalues
</code>```

When someone wants to iterate over values as lists

```<code>- name: List lists (no pun intended)
  debug:
    msg: "{{ item.myvalues }}"
  with_items: associations
</code>```

Body:
I have key - value pairs association in the form of:

- mykey1:
    myvalues1: ['a', 'b', 'c']
- mykey2:
    myvalues2: ['d', 'e']
- mykey3:
    myvalues3: ['f']

I know that using the with_dict construct I can iterate over both keys and  values (which are lists).
My question is how can I have a loop that iterates over the list's (values) elements?

The output i would like to be able to achieve is:

a', 'b', 'c', 'd', 'e', 'f'

The problem is that I need to maintain the above associations.
Is there a way to avoid duplicating list declarations?

Body:
Here is the construct I came up with:

associations:
    - { key: mykey1, myvalues: ['a', 'b', 'c', ] }
    - { key: mykey2, myvalues: ['d', 'e'] }
    - { key: mykey3, myvalues: ['f'] }

When someone wants to iterate over values as single values

- name: List single items
  debug:
     msg: "{{ item.1 }}"
   with_subelements:
     - associations
     - myvalues

When someone wants to iterate over values as lists

- name: List lists (no pun intended)
  debug:
    msg: "{{ item.myvalues }}"
  with_items: associations


问:
Command for returning index of top 3 values in a matrix.
For example there is a matrix

1 3 5
7 9 2
4 6 8

And how do I find the index of top 3 values?
In this case, it would be, (2,2), (3,3), (2,1)

What command do I have to use?

答:
This returns a nx2 matrix of row-column pairs:</p>

```<code>m =matrix(c(1,3,5,7,9,2,4,6,8), ncol=3, nrow=3)

mm <- arrayInd(which(rank(-m) %in% 1:3,arr.ind=TRUE),dim(m))
</code>```

Body:
This returns a nx2 matrix of row-column pairs:

m =matrix(c(1,3,5,7,9,2,4,6,8), ncol=3, nrow=3)

mm <- arrayInd(which(rank(-m) %in% 1:3,arr.ind=TRUE),dim(m))


问:
Row selection in smart-table is not working
I'm unable to select rows using smart-table. I have added JSON and HTML.
code to open modal window

$scope.getSerialData = function(){

```<code>    var serialNo ='700001117961';// $scope.asupFormData.asup_serial_no;
    $http({
                method: 'GET',
                url: getAsupSerialData+serialNo+'/',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                } // set the headers so angular passing info as form data (not request payload)
            }).success(function(data) {
                $scope.rowCollection1 = JSON.parse(data);
                $scope.rowCollection = $scope.rowCollection1.result;

                console.log($scope.rowCollection)
            }).error(function(data){

            });

    $scope.close = function() {
        uibModalInstance.dismiss('cancel');
    };

    $scope.saveForms = function(){

    uibModalInstance.dismiss('cancel');
    }

    var uibModalInstance = $uibModal.open({
        templateUrl: 'asupsearchform.html/',
        scope: $scope,

        controller:'MainCtrl',
        windowClass: 'device-modal-window'
    });
}
</code>```

rowCollection is

```<code>[["2017032517580346","HA Group Notification (WEEKLY_LOG) NOTICE"],
["2017031818200373","HA Group Notification (WEEKLY_LOG) NOTICE"],
["2017031818200372","HA Group Notification (WEEKLY_LOG) NOTICE"]]
</code>```

$scope.getSerialData is getting called from some link which opens a modal window

HTML

```<code><table st-table="rowCollection" class="table" >
<thead>
<tr>
    <th st-sort="firstName">ID</th>
    <th st-sort="lastName">Title</th>
</tr>
</thead>
<tbody>
<tr  st-select-row="row" st-select-mode="multiple" ng-repeat="row in rowCollection" ng-click="doSomeStuffToSelected(row)">
    <td>{{row[0]}}</td>
    <td>{{row[2]}}</td>

</tr>
</tbody>
</table>
</code>```

Kindly help. With static code selection was working fine.This is happening when i am using it under modalwindow

答:
You need to define style for .st-selected

```<code><style>
  .st-selected{
    background: #216eff !important;
    color: white !important;
  }
</style>
</code>```

Also in your rowCollection values are at positions 0 and 1 in child array, whereas you are using positions 0 and 2

```<code> <td>{{row[0]}}</td>
 <td>{{row[2]}}</td>
</code>```

Here is the WORKING DEMO

EDIT: Demo using modal

Body:
I'm unable to select rows using smart-table. I have added JSON and HTML.
code to open modal window

$scope.getSerialData = function(){

    var serialNo ='700001117961';// $scope.asupFormData.asup_serial_no;
    $http({
                method: 'GET',
                url: getAsupSerialData+serialNo+'/',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                } // set the headers so angular passing info as form data (not request payload)
            }).success(function(data) {
                $scope.rowCollection1 = JSON.parse(data);
                $scope.rowCollection = $scope.rowCollection1.result;

                console.log($scope.rowCollection)
            }).error(function(data){

            });

    $scope.close = function() {
        uibModalInstance.dismiss('cancel');
    };

    $scope.saveForms = function(){

    uibModalInstance.dismiss('cancel');
    }

    var uibModalInstance = $uibModal.open({
        templateUrl: 'asupsearchform.html/',
        scope: $scope,

        controller:'MainCtrl',
        windowClass: 'device-modal-window'
    });
}

rowCollection is

[["2017032517580346","HA Group Notification (WEEKLY_LOG) NOTICE"],
["2017031818200373","HA Group Notification (WEEKLY_LOG) NOTICE"],
["2017031818200372","HA Group Notification (WEEKLY_LOG) NOTICE"]]

$scope.getSerialData is getting called from some link which opens a modal window

HTML

    ID
    Title

    {{row[0]}}
    {{row[2]}}

Kindly help. With static code selection was working fine.This is happening when i am using it under modalwindow

Body:
You need to define style for .st-selected

<style>
  .st-selected{
    background: #216eff !important;
    color: white !important;
  }
</style>

Also in your rowCollection values are at positions 0 and 1 in child array, whereas you are using positions 0 and 2

 <td>{{row[0]}}</td>
 <td>{{row[2]}}</td>

Here is the WORKING DEMO

EDIT: Demo using modal


问:
Is it possible to use Git between two workstations, without a "central" repository?
I made the move from SVN to Git for some home programming, setting up a Git repository on my ReadyNAS drive. I then created a repository, which I cloned onto two different laptops.

These laptops both have changes that are committed but not pushed back to the central repository; this is because the central repository / NAS drive is on a boat somewhere and won't be seen for 6-8 weeks ! So my question is, in the meantime, I have both laptops on the same network and would like to push the local repository commits from one laptop to the other.

Is this possible ? I am running Windows on both laptops, and using the "Git Bash" installable on each one.

答: Yes, sure. A git repository is just a bunch of files and all you need is some way to access them. For example, you could set up a bare "central" repository on one computer's shared folder and then push/pull to/from it from both computer's local clones that you use for development.</p>


问:
Web Forwarding Frame - Change the meta / title
I'm using 123 reg's forwarding frame for a website.

However this forwarding frame is not picking up the inner html's meta data. So the frame is loading in a non responsive format.

Has anyone come across this problem and found a fix?

I ideally need to add the following meta to the parent frame :

```<code><meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
</code>```

Can this be done?

Thanking You!

答:
Has anyone come across this problem and found a fix?

There isn't one.

Frame based web forwarding is, frankly, awful. This is one of the many drawbacks.

The solution is to not use it. Use real DNS that points to your actual server instead.

Body:
I'm using 123 reg's forwarding frame for a website.

However this forwarding frame is not picking up the inner html's meta data. So the frame is loading in a non responsive format.

Has anyone come across this problem and found a fix?

I ideally need to add the following meta to the parent frame :

<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

Can this be done?

Thanking You!


问:
Server Side Calculation using Firebase
Given the starting time/date and duration, how can I make a server side calculation that determines if an object is "finished", "in progress", or "upcoming"

```<code>--Show
  --duration: "144"
  --startDate: "2015-11-10"
  --startTime: "14:00"
  --status: "?"
</code>```

Client-side javascript to determine if the show has started yet:

```<code>// if negative, then show hasn't started yet
var time = (-(startdate.getTime() - currentdate.getTime()) / 1000 / 60);
</code>```

Client-side javascript to determine if the show has finished running yet:

```<code>// if negative, then show has finished
var timeLeft = channelDuration - timerStartTime;
</code>```

答:
For someone passing by, I think now Firebase allow you to do this by Cloud Function. For this case, you can create the function that determine the status of the status by other parameter when the data is added to you database.

Please checkout

https://firebase.google.com/docs/functions/

Title: Server Side Calculation using Firebase

Body:
Given the starting time/date and duration, how can I make a server side calculation that determines if an object is "finished", "in progress", or "upcoming"

--Show
  --duration: "144"
  --startDate: "2015-11-10"
  --startTime: "14:00"
  --status: "?"

Client-side javascript to determine if the show has started yet:

// if negative, then show hasn't started yet
var time = (-(startdate.getTime() - currentdate.getTime()) / 1000 / 60);

Client-side javascript to determine if the show has finished running yet:

// if negative, then show has finished
var timeLeft = channelDuration - timerStartTime;


问:
How to get the last month? date +%Y%m -d '1 month ago' doesn't work on March 30
I wrote a script to delete old files. Part of the script is following:

```<code>lastmonth=`date +%Y%m -d '1 month ago'`
inputdir0=/var/this/directory/${lastmonth}*

if [ `date +%d` -gt 9 ];
then
    rm -Rf $inputdir0
fi
</code>```

There are some directories named after the date +%Y%m%d format.
Now it's March 29/30/31 and the script deleted all files of this month.
Today I learned this happens because there is no February 29/30/31.

How can i fix this?

答:
Subtract the number of days in the current month, and you will get the last day of the previous month. For example:

```<code>date +%Y-%m-%d -d "`date +%d` day ago"
</code>```

results in

```<code>2017-02-28
</code>```

Since you don't care about the day and only want the month, you will always get the correct month:

```<code>lastmonth=$(date +%Y%m -d "$(date +%d) day ago")
</code>```

Body:
I wrote a script to delete old files. Part of the script is following:

lastmonth=`date +%Y%m -d '1 month ago'`
inputdir0=/var/this/directory/${lastmonth}*

if [ `date +%d` -gt 9 ];
then
    rm -Rf $inputdir0
fi

There are some directories named after the date +%Y%m%d format.
Now it's March 29/30/31 and the script deleted all files of this month.
Today I learned this happens because there is no February 29/30/31.

How can i fix this?

Body:
Subtract the number of days in the current month, and you will get the last day of the previous month. For example:

date +%Y-%m-%d -d "`date +%d` day ago"

results in

2017-02-28

Since you don't care about the day and only want the month, you will always get the correct month:

lastmonth=$(date +%Y%m -d "$(date +%d) day ago")


问:
Split text box text value in before "@" in Javascript
Here i have txtemailid and txtlogin(read only) what i type in txtemailid before @ text it will directly go to txtlogin text box when i will happen means when i type something in email text box and next click to mouse without entering the user. how can i do this java and i take code in java script it's not working

Thank you

答:
It is better you use keyboard event to make changes on each time a key is pressed.I am doing using onkeyup.I prefer document.getElementById() rather than document.form because it can accurately retrieve it, every time, without caring about what happens to the document in the meantime.You can use either of the two.

JSFIDDLE

Here is the code:

function myFunction() {
  var text1 = document.getElementById("txtEmailId").value;
  var result = text1.split("@");
  document.getElementById("txtLoginname").value = result[0];
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  Enter Email: <input type="text" id="txtEmailId" onkeyup="myFunction()" /><br/><br/> Login Name: <input type="text" id="txtLoginname" /><br/><br/>
</form></code>```

Body:
It is better you use keyboard event to make changes on each time a key is pressed.I am doing using onkeyup.I prefer document.getElementById() rather than document.form because it can accurately retrieve it, every time, without caring about what happens to the document in the meantime.You can use either of the two.

JSFIDDLE

Here is the code:

function myFunction() {
  var text1 = document.getElementById("txtEmailId").value;
  var result = text1.split("@");
  document.getElementById("txtLoginname").value = result[0];
}

<form>
  Enter Email: <input type="text" id="txtEmailId" onkeyup="myFunction()" /><br/><br/> Login Name: <input type="text" id="txtLoginname" /><br/><br/>
</form>


问:
Extract particular value from column
How to better extract following:

I have following values in column:

```<code>\\v8pip1\90PI-200009-10.PV
</code>```

I need to get just below, \\v8pip1\ is the same for all rows:

```<code> 90PI-200009-10.PV
</code>```

thanks,
S

答:
Try regexp_replace. This will consider string after second single backslash as second group and return it.

```<code>select regexp_replace
(col1,
  '^\\{2}(\w*)\\(.*)',
    '\2')
from  (
select '\\v8pip1\90PI-200009-10.PV' as col1 from dual union all
select '\\first\second string' from dual )
</code>```

Output

```<code>90PI-200009-10.PV
second string
</code>```

Title: Extract particular value from column

Body:
How to better extract following:

I have following values in column:

\\v8pip1\90PI-200009-10.PV

I need to get just below, \\v8pip1\ is the same for all rows:

 90PI-200009-10.PV

thanks,
S

Body:
Try regexp_replace. This will consider string after second single backslash as second group and return it.

select regexp_replace
(col1,
  '^\\{2}(\w*)\\(.*)',
    '\2')
from  (
select '\\v8pip1\90PI-200009-10.PV' as col1 from dual union all
select '\\first\second string' from dual )

Output

90PI-200009-10.PV
second string


问:
Redirect to Settings root page in ios 8, 9 and 10
My question has been asked a lot of time and till now hasn't got a solution.
I'm trying to open Mobile data page from app.

1) I've tried

```<code>[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]]
</code>```

In iOS 8 and iOS 9, instead of root page, it directly went to Settings/AppName page. This is not the behavior that I want. What I want is to enter Settings root page

2) as for iOS 10, the above method doesn't work. I've tried

```<code>[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil]
</code>```

but it doesn't work.

Is there any code that can satisfy both of the above. in iOS 8, 9  and 10, it will go to Settings root page (if possible, mobile data page). If there isn't any way, can provide link why it doesn't work.

UPDATE:

in ios 8 and 9, by using [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=GENERAL"]] i'm able to redirect to Settings Home page.

for ios 10.1.0 and below, using [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=MOBILE_DATA"]] will redirect to app specific page in Settings. but in the latest 10.1.1, it won't do anything.

I'm using Xcode 8.0.

答:
in iOS 10 they changed "prefs:" to "App-Prefs:"</p>

```<code>    guard let profileUrl = URL(string: "App-
     Prefs:root=General") else {
        return
    }

     if UIApplication.shared.canOpenURL(profileUrl) {

     UIApplication.shared.open(profileUrl, completionHandler: { (success) in

        print(" Profile Settings opened: \(success)")

        })
     }
</code>```

Body:
My question has been asked a lot of time and till now hasn't got a solution.
I'm trying to open Mobile data page from app.

1) I've tried

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]]

In iOS 8 and iOS 9, instead of root page, it directly went to Settings/AppName page. This is not the behavior that I want. What I want is to enter Settings root page

2) as for iOS 10, the above method doesn't work. I've tried

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil]

but it doesn't work.

Is there any code that can satisfy both of the above. in iOS 8, 9  and 10, it will go to Settings root page (if possible, mobile data page). If there isn't any way, can provide link why it doesn't work.

UPDATE:

in ios 8 and 9, by using [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=GENERAL"]] i'm able to redirect to Settings Home page.

for ios 10.1.0 and below, using [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=MOBILE_DATA"]] will redirect to app specific page in Settings. but in the latest 10.1.1, it won't do anything.

I'm using Xcode 8.0.

Body:
in iOS 10 they changed "prefs:" to "App-Prefs:"

    guard let profileUrl = URL(string: "App-
     Prefs:root=General") else {
        return
    }

     if UIApplication.shared.canOpenURL(profileUrl) {

     UIApplication.shared.open(profileUrl, completionHandler: { (success) in

        print(" Profile Settings opened: \(success)")

        })
     }


问:
Good piece of software for practicing SQL on Windows?
I brought 31 queries down to 3 for a certain page in my application by using a single join (provided by Django's ORM). Up until that very moment I thought of SQL optimization as something I didn't need to worry about. I instantly realized that there are probably so many areas that run slow which could use some SQL tomFOOlery (SQL FOO is for professionals).

Now I'm looking for a piece of open source software that will allow me to quickly create databases, and tables with a GUI, so I can quickly add data and experiment with queries. Is Access good for this (aside from not being free or open source)? Or, does Access use it's own SQL syntax?

答: SQL Server is an obvious choice for Windows. You can download Express Edition for free but if you want a development tool then the Developer Edition is much better value. Developer Edition typically costs around $50 - much cheaper than Access.</p>


问:
Create new template for CMS pages in prestashop
I have several pages created under the Preferences -> CMS which are ok. Now I need to create some more pages that will have a different look, is there a way to add like a different template and use the same CMS interface to do it?.
I was thinking of something like:

Step 1. Create new cms-2.tpl
Step 2. Modify the database to add a new "template" field
Step 3. Modify the back office to add an extra field to the CMS page to choose the template to be used with the CMS page

So far I have been reading about "Creating pages without CMS" like in this link: Custom page in Prestashop 1.6 without CMS or this other link: Create custom page in Prestashop 1.5.3, but none of them seem to be what i am looking for.

Thanks

答:
Update for prestashop 1.7

You don't need to override the cms controller anymore. This function is already written by default.

You can just create a page-ID.tpl in your themes/your-theme/templates/cms folder. Where ID is the cms page ID.


问:
Rethrow exception in java
I have a very simple question about re-throwing exception in Java.

Here is the code snippet:

```<code>public static void main(String[] args) throws FileNotFoundException {
    try {
        FileReader reader = new FileReader("java.pdf");
    } catch (FileNotFoundException ex) {
        throw ex;
    }
}

public static void main(String[] args) throws FileNotFoundException {
        FileReader reader = new FileReader("java.pdf");
}
</code>```

Why do we need to re-throw ex in the first version while the second version looks more elegant? What might be the benefits and which version is preferred over the other?

答:
Both versions will output the same stacktrace

without try/catch

```<code>import java.io.FileNotFoundException;
import java.io.FileReader;

public class Test {
    public static void main(String[] args) throws FileNotFoundException {
//        try {
            FileReader reader = new FileReader("java.pdf");
//        } catch (FileNotFoundException ex) {
//            throw ex;
//        }
    }
}
</code>```

will output

```<code>Exception in thread "main" java.io.FileNotFoundException: java.pdf (The system cannot find the file specified)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileInputStream.<init>(FileInputStream.java:93)
    at java.io.FileReader.<init>(FileReader.java:58)
    at Test.main(Test.java:7)
</code>```

with try/catch/throw same exception

```<code>import java.io.FileNotFoundException;
import java.io.FileReader;

public class Test {
    public static void main(String[] args) throws FileNotFoundException {
        try {
            FileReader reader = new FileReader("java.pdf");
        } catch (FileNotFoundException ex) {
            throw ex;
        }
    }
}
</code>```

will output exactly the same as before

```<code>Exception in thread "main" java.io.FileNotFoundException: java.pdf (The system cannot find the file specified)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileInputStream.<init>(FileInputStream.java:93)
    at java.io.FileReader.<init>(FileReader.java:58)
    at Test.main(Test.java:7)
</code>```

try/catch/throw wrapping exception

An advisable approach is to throw your own exceptions.
wrap the exception you just caught into it if you want to provide details of the root cause (might be wanted or not wanted)

```<code>import java.io.FileNotFoundException;
import java.io.FileReader;

public class Test {
    public static void main(String[] args) {
        try {
            FileReader reader = new FileReader("java.pdf");
        } catch (FileNotFoundException ex) {
            throw new RuntimeException("Error while doing my process", ex);
        }
    }
}
</code>```

You can clearly see the top-level issue (my process did not complete), and the root cause that led to it (java.pdf file not found)

```<code>Exception in thread "main" java.lang.RuntimeException: Error while doing my process
    at Test.main(Test.java:9)
Caused by: java.io.FileNotFoundException: java.pdf (The system cannot find the file specified)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileInputStream.<init>(FileInputStream.java:93)
    at java.io.FileReader.<init>(FileReader.java:58)
    at Test.main(Test.java:7)
</code>```

Title: Rethrow exception in java

Body:
I have a very simple question about re-throwing exception in Java.

Here is the code snippet:

public static void main(String[] args) throws FileNotFoundException {
    try {
        FileReader reader = new FileReader("java.pdf");
    } catch (FileNotFoundException ex) {
        throw ex;
    }
}

public static void main(String[] args) throws FileNotFoundException {
        FileReader reader = new FileReader("java.pdf");
}

Why do we need to re-throw ex in the first version while the second version looks more elegant? What might be the benefits and which version is preferred over the other?

Body:
Both versions will output the same stacktrace

without try/catch

import java.io.FileNotFoundException;
import java.io.FileReader;

public class Test {
    public static void main(String[] args) throws FileNotFoundException {
//        try {
            FileReader reader = new FileReader("java.pdf");
//        } catch (FileNotFoundException ex) {
//            throw ex;
//        }
    }
}

will output

Exception in thread "main" java.io.FileNotFoundException: java.pdf (The system cannot find the file specified)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileInputStream.<init>(FileInputStream.java:93)
    at java.io.FileReader.<init>(FileReader.java:58)
    at Test.main(Test.java:7)

with try/catch/throw same exception

import java.io.FileNotFoundException;
import java.io.FileReader;

public class Test {
    public static void main(String[] args) throws FileNotFoundException {
        try {
            FileReader reader = new FileReader("java.pdf");
        } catch (FileNotFoundException ex) {
            throw ex;
        }
    }
}

will output exactly the same as before

Exception in thread "main" java.io.FileNotFoundException: java.pdf (The system cannot find the file specified)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileInputStream.<init>(FileInputStream.java:93)
    at java.io.FileReader.<init>(FileReader.java:58)
    at Test.main(Test.java:7)

try/catch/throw wrapping exception

An advisable approach is to throw your own exceptions.
wrap the exception you just caught into it if you want to provide details of the root cause (might be wanted or not wanted)

import java.io.FileNotFoundException;
import java.io.FileReader;

public class Test {
    public static void main(String[] args) {
        try {
            FileReader reader = new FileReader("java.pdf");
        } catch (FileNotFoundException ex) {
            throw new RuntimeException("Error while doing my process", ex);
        }
    }
}

You can clearly see the top-level issue (my process did not complete), and the root cause that led to it (java.pdf file not found)

Exception in thread "main" java.lang.RuntimeException: Error while doing my process
    at Test.main(Test.java:9)
Caused by: java.io.FileNotFoundException: java.pdf (The system cannot find the file specified)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileInputStream.<init>(FileInputStream.java:93)
    at java.io.FileReader.<init>(FileReader.java:58)
    at Test.main(Test.java:7)


问:
Wordpress Upload media isuue Fatal error: Maximum function nesting level of '256' reached
I had a previously working wordpress and recently I updated it to version 4.7.2. But now i can't see my media files.

When I try to upload an image following error popups.

"Fatal error: Maximum function nesting level of '256' reached,
  aborting! in C:\wamp64\www*\wp-includes\cache.php on line 724 "

Please find the code in cache.php(line number 724,725,726)

```<code>protected function _exists( $key, $group ) {
return isset( $this->cache[
$group ] ) && ( isset( $this->cache[ $group ][ $key ] ) ||
array_key_exists( $key, $this->cache[ $group ] ) );
}
</code>```

Please help me out.

Thanks,
Preetham Hegde.

答:
You could try to wiggle down the nesting by implementing parallel workers (like in cluster computing) instead of increasing the number of nesting function calls.

For example: you define a limited number of slots (eg. 100) and monitor the number of "workers" assigned to each/some of them. If any slots become free, you put the waiting workers "in them".

Body:
I had a previously working wordpress and recently I updated it to version 4.7.2. But now i can't see my media files.

When I try to upload an image following error popups.

"Fatal error: Maximum function nesting level of '256' reached,
  aborting! in C:\wamp64\www*\wp-includes\cache.php on line 724 "

Please find the code in cache.php(line number 724,725,726)

protected function _exists( $key, $group ) {
return isset( $this->cache[
$group ] ) && ( isset( $this->cache[ $group ][ $key ] ) ||
array_key_exists( $key, $this->cache[ $group ] ) );
}

Please help me out.

Thanks,
Preetham Hegde.


问:
Rails Active Record query: answered questions, ordered by answer date, not duplicates
A question has many answers.

It is easy to find all questions that have been answered and order them by newest answer:

```<code>def self.answered
  joins(:answers).order('answers.created_at desc')
end
</code>```

In the controller, I'd do @answered = Question.answered

But this returns duplicate records if a question has been answered more than once.

It's easy, on the other hand, to find distinct questions that have been answered, but only if I don't try to order them by their answers' created_at date:

```<code>def self.answered
  joins(:answers).select("DISTINCT questions.title")
end
</code>```

(Let's just assume here that question titles are validated to be unique, so this results in all unique records).

The problem:

This query can't be ordered by an answer's "created_at" date, because I've selected only the question's title in my SQL select statement...

```<code>def self.answered
  joins(:answers).select("DISTINCT questions.title").order('answers.created_at desc')
end
</code>```

results in this error (I'm using Postgres):

```<code>PGError: ERROR:  for SELECT DISTINCT, ORDER BY expressions must appear in select list
</code>```

What it means, I guess, is it wants to see "answers.created_at" in that select DISTINCT statement.

The following looks like it would work if I wanted to order by questions.created_at, but that's not what I want:

```<code>def self.answered
  joins(:answers).select("DISTINCT(questions.title), questions.created_at").order('questions.created_at desc')
end
</code>```

This is where my basic SQL knowledge conks out. How do I select distinct questions (only the ones with answers) and order them in descending order by their latest answer's created_at date?

I'd like to write it using Rails 3 Active Record queries, but straight SQL is fine. I hope someone can help.

答:
This might end up being a little bit more efficient and extensible and should avoid issues where psql gripes about aggregate functions:

```<code>select questions.*, count(answers.id) as answer_count from questions join answers on answers.question_id=questions.id group by answers.question_id having answer_count > 0 order by answers.created_at desc
</code>```

P.S. by extensible I meant, you can split it into Arel structure, and then break out scopes such as with_answers and answered to do your dirty work behind the scenes while keeping the rest clean and allowing you to add on more scopes later. :)

UPDATE: just posting the Arel way:

```<code>scope :answered, select('questions.*, count(answers.id) as answer_count').joins('join answers on answers.question_id=questions.id').group('answers.question_id').having('answer_count > 0').order('answers.created_at desc')
</code>```

Body:
A question has many answers.

It is easy to find all questions that have been answered and order them by newest answer:

def self.answered
  joins(:answers).order('answers.created_at desc')
end

In the controller, I'd do @answered = Question.answered

But this returns duplicate records if a question has been answered more than once.

It's easy, on the other hand, to find distinct questions that have been answered, but only if I don't try to order them by their answers' created_at date:

def self.answered
  joins(:answers).select("DISTINCT questions.title")
end

(Let's just assume here that question titles are validated to be unique, so this results in all unique records).

The problem:

This query can't be ordered by an answer's "created_at" date, because I've selected only the question's title in my SQL select statement...

def self.answered
  joins(:answers).select("DISTINCT questions.title").order('answers.created_at desc')
end

results in this error (I'm using Postgres):

PGError: ERROR:  for SELECT DISTINCT, ORDER BY expressions must appear in select list

What it means, I guess, is it wants to see "answers.created_at" in that select DISTINCT statement.

The following looks like it would work if I wanted to order by questions.created_at, but that's not what I want:

def self.answered
  joins(:answers).select("DISTINCT(questions.title), questions.created_at").order('questions.created_at desc')
end

This is where my basic SQL knowledge conks out. How do I select distinct questions (only the ones with answers) and order them in descending order by their latest answer's created_at date?

I'd like to write it using Rails 3 Active Record queries, but straight SQL is fine. I hope someone can help.

Body:
This might end up being a little bit more efficient and extensible and should avoid issues where psql gripes about aggregate functions:

select questions.*, count(answers.id) as answer_count from questions join answers on answers.question_id=questions.id group by answers.question_id having answer_count > 0 order by answers.created_at desc

P.S. by extensible I meant, you can split it into Arel structure, and then break out scopes such as with_answers and answered to do your dirty work behind the scenes while keeping the rest clean and allowing you to add on more scopes later. :)

UPDATE: just posting the Arel way:

scope :answered, select('questions.*, count(answers.id) as answer_count').joins('join answers on answers.question_id=questions.id').group('answers.question_id').having('answer_count > 0').order('answers.created_at desc')


问:
Bootstrap affix does not work when navigating back
I have used Bootstrap affix to create a fixed position div that behaves similar to the "How to Format" and "Similar Questions" div that appears when you ask a new question in Stackoverflow. It works fine when I load the page the first time, but if I scroll quite far down the page, navigate away, and then return to the page with the back button, the affixed div will sometimes be affixed in the wrong place, and sometimes the fixed positioning will break and it will simply return to its normal place in the document.

Is there something wrong with how I am implementing affix?

Document layout (#engage is the affixed div). It should not scroll over #title or #footer:

Javascript

$('#engage').affix({
    offset: {
        top: $('#donation-content').offset().top,
        bottom: function () {
            return (this.bottom = $('.footer').outerHeight(true))
        }
    }
});
```

<p><strong>CSS</strong></p>

<pre class="lang-css prettyprint-override"><code>#engage.affix {
    position: fixed;
    top: 0;
}

@media(max-width:767px){

   #engage.affix {
    position: static;
    }
}
</code>```

You can find example code at http://www.bootply.com/pxyz1hsefA. Errors tend to happen if you scroll to the bottom of the page, click on "Go somewhere else", then click on the back button. Violent scrolling up and down will also tend to break it.

Edit:
Adding an .affix-bottom class to the css with absolute positioning goes some way to fixing it. At least now when it's 'broken' the div just sticks to the bottom of its scrolling range. When I scroll back to the top, it resumes it's correct fixed position again. But it's still not what I'd call stable.

#engage.affix-bottom {
  position: absolute;
  }
```

答: Adding a tiny timeout fixed my issue. Removing one of the offset settings (top or bottom) helps too but wasn't an option for me.</p>

Body:
I have used Bootstrap affix to create a fixed position div that behaves similar to the "How to Format" and "Similar Questions" div that appears when you ask a new question in Stackoverflow. It works fine when I load the page the first time, but if I scroll quite far down the page, navigate away, and then return to the page with the back button, the affixed div will sometimes be affixed in the wrong place, and sometimes the fixed positioning will break and it will simply return to its normal place in the document.

Is there something wrong with how I am implementing affix?

Document layout (#engage is the affixed div). It should not scroll over #title or #footer:

Javascript

$('#engage').affix({
    offset: {
        top: $('#donation-content').offset().top,
        bottom: function () {
            return (this.bottom = $('.footer').outerHeight(true))
        }
    }
});

CSS

#engage.affix {
    position: fixed;
    top: 0;
}

@media(max-width:767px){

   #engage.affix {
    position: static;
    }
}

You can find example code at http://www.bootply.com/pxyz1hsefA. Errors tend to happen if you scroll to the bottom of the page, click on "Go somewhere else", then click on the back button. Violent scrolling up and down will also tend to break it.

Edit:
Adding an .affix-bottom class to the css with absolute positioning goes some way to fixing it. At least now when it's 'broken' the div just sticks to the bottom of its scrolling range. When I scroll back to the top, it resumes it's correct fixed position again. But it's still not what I'd call stable.

#engage.affix-bottom {
  position: absolute;
  }


问:
Using dlib trained object detector in Python
I'm working on Python. I've been using dlib's function dlib.get_frontal_face_detector() to detect frontal faces, and I'm now using the tutorial on http://dlib.net/fhog_object_detector_ex.cpp.html to train my own object detector. However, this is trained in C++.

How can I use the trained classifier (which I believe is called face_detector.svm) and use it on Python?

(A better question might be how to train dlib's HOG in Python entirely, but it's less crucial.)

Thanks!

答:
Python example where you can train and test object detector can be found here -
github.com/davisking/dlib/blob/master/python_examples/train_object_detector.py</p>