问:
Visual Studio: ContextSwitchDeadlock
I have been getting an error message that I can't resolve. It originates from Visual Studio or the debugger. I'm not sure whether the ultimate error condition is in VS, the debugger, my program, or the database.

This is a Windows app. Not a web app.

First message from VS is a popup box saying:
"No symbols are loaded for any call stack frame. The source code can not be displayed."
When that is clicked away, I get:
"ContextSwitchDeadlock was detected", along with a long message reproduced below.

The error arises in a loop that scans down a DataTable. For each line, it uses a key (HIC #) value from the table as a parameter for a SqlCommand. The command is used to create a SqlDataReader which returns one line. Data are compared. If an error is detected a row is added to a second DataTable.

The error seems to be related to how long the procedure takes to run (i.e. after 60 sec), not how many errors are found. I don't think it's a memory issue. No variables are declared within the loop. The only objects that are created are the SqlDataReaders, and they are in Using structures. Add System.GC.Collect() had no effect.

The db is a SqlServer site on the same laptop.

There are no fancy gizmos or gadgets on the Form.

I am not aware of anything in this proc which is greatly different from what I've done dozens of times before. I have seen the error before, but never on a consistent basis.

Any ideas, anyone?

Full error Text:
The CLR has been unable to transition from COM context 0x1a0b88 to COM context 0x1a0cf8 for 60 seconds. The thread that owns the destination context/apartment is most likely either doing a non pumping wait or processing a very long running operation without pumping Windows messages. This situation generally has a negative performance impact and may even lead to the application becoming non responsive or memory usage accumulating continually over time. To avoid this problem, all single threaded apartment (STA) threads should use pumping wait primitives (such as CoWaitForMultipleHandles) and routinely pump messages during long running operations.

答:
In Visual Studio 2017 Spanish version.

"Depurar" -> "Ventanas" -> "Configuración de Excepciones"

and search "ContextSwitchDeadlock".
Then, uncheck it.
Or shortcut

Ctrl+D,E

Best.

OwnerDisplayName: SeaDrive

Title: Visual Studio: ContextSwitchDeadlock


来源: stackexchange

问:
Limit iOS App even after the user re-installs it
I created an app that gives the user 3 coins at the first launch.

Once the user finished the 3 coins he should buy unlimited coins by an In-App purchase.

The problem is that if the user doesn't want to buy unlimited coins he can delete the app, install the app again and he will have again the 3 coins again.
And he can do this forever without ever buying the In-App purchase.

Is there a simple way to prevent this? How can I know if a user finished the coins inside the app even after deleting it?

答:
There are a few ways to implement it:

Use Keychain to store coins count. Any other local storage is less secure and will not "survive" app deletion. I'm using KeychainAccess library to have an easy access to app keychain.

Store user profile with coins count on your server. Also you could validate each In-App Purchase and validate any coin consume operation to protect from IAP Hack tools, Main-in-the-Middle attacks on user profile sync, etc.

ContentLicense: CC BY-SA 3.0


问:
Search many fields with will_paginate / searchlogic
How do you effectively search among many fields in a model?

```<code># user.rb model
def self.search(search, page)
  paginate :per_page => 20, :page => page,
  :conditions =>
    ['name like ? OR notes like ? OR code like ? OR city like ? OR state like ?,
    "%#{search}%","%#{search}%","%#{search}%","%#{search}%","%#{search}%"
    ], :order => 'name'
</code>```

This code is horrible for any more than a few fields, and it doesn't return a result if, for instance word #1 comes from :name and word #2 comes from :code. Is there a more elegant way?

答:
You can use searchlogic

```<code>def self.search(search, page)
  search_cond = resource.search(name_or_notes_or_code_or_city_or_state_like => search.to_s)
  search_cond.all
end
</code>```

Hope you got the idea

ContentLicense: CC BY-SA 2.5

Body:
How do you effectively search among many fields in a model?

# user.rb model
def self.search(search, page)
  paginate :per_page => 20, :page => page,
  :conditions =>
    ['name like ? OR notes like ? OR code like ? OR city like ? OR state like ?,
    "%#{search}%","%#{search}%","%#{search}%","%#{search}%","%#{search}%"
    ], :order => 'name'

This code is horrible for any more than a few fields, and it doesn't return a result if, for instance word #1 comes from :name and word #2 comes from :code. Is there a more elegant way?

Body:
You can use searchlogic

def self.search(search, page)
  search_cond = resource.search(name_or_notes_or_code_or_city_or_state_like => search.to_s)
  search_cond.all
end

Hope you got the idea


问:
Changing text Size of menu item in android
I am using simple menu items in action bar by using following code in main activity:

```<code>    package com.kaasib.ftpclient;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.app.ActionBar;

public class MainActivity extends Activity {

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        boolean ret;
        if(item.getItemId() == R.id.connection_manager){
            ret = true;
        }else{
            ret = super.onOptionsItemSelected(item);
        }

        return ret;
    }
}
</code>```

Here is menu xml in main.xml:

```<code>    <menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/connection_manager"
        android:orderInCategory="100"
        android:showAsAction="collapseActionView"
        android:title="@string/connection_manager"
        android:textSize="2sp"
        />

</menu>
</code>```

It is working except it is not making any change to text size. Right now text size for menu item is bigger while I want font size to be smaller. So what am I doing wrong?  Shouldn't android:textSize attributute work? Or is there some other way to do so? I believe that text size should be set from XML not from java as it is design related thing. Any suggestion?

答:
So it's been a long time since this was asked but I like this solution as steven smiths answer changes every view:

Add this line to NavigationView:

```<code>app:itemTextAppearance="@style/MenuItems"
</code>```

And this to the styles :

```<code><style name="MenuItems" parent="AppTheme">
    <item name="android:textSize">18sp</item>
    <item name="android:fontFamily">sans-serif-light</item>
</style>
</code>```

Body:
I am using simple menu items in action bar by using following code in main activity:

    package com.kaasib.ftpclient;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.app.ActionBar;

public class MainActivity extends Activity {

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        boolean ret;
        if(item.getItemId() == R.id.connection_manager){
            ret = true;
        }else{
            ret = super.onOptionsItemSelected(item);
        }

        return ret;
    }
}

Here is menu xml in main.xml:

    <menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/connection_manager"
        android:orderInCategory="100"
        android:showAsAction="collapseActionView"
        android:title="@string/connection_manager"
        android:textSize="2sp"
        />

</menu>

It is working except it is not making any change to text size. Right now text size for menu item is bigger while I want font size to be smaller. So what am I doing wrong?  Shouldn't android:textSize attributute work? Or is there some other way to do so? I believe that text size should be set from XML not from java as it is design related thing. Any suggestion?

Body:
So it's been a long time since this was asked but I like this solution as steven smiths answer changes every view:

Add this line to NavigationView:

app:itemTextAppearance="@style/MenuItems"

And this to the styles :

<style name="MenuItems" parent="AppTheme">
    <item name="android:textSize">18sp</item>
    <item name="android:fontFamily">sans-serif-light</item>
</style>


问:
Overlapping border div
i want to create a table just with div tag. I use only two class and it works well.

The only problem is the border of cell inside the table have double width of the table border and it looks ugly. I know the reason is all cell have border around but i can not fix it. I've try some solution in other post but it does not work in this case.

Can some one please help me? Thanks a lot. Note that i don't want to add more class.

.row {
  height: 100%;
  display: flex;
  width: 100%;
  flex-wrap: wrap;
}

.col {
  border: solid 2px blue;
  padding: 5px;
  margin: 0;
  min-height: 1px;
  flex-grow: 1;
  max-width: 100%;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div class="col">x</div>
  <div class="col">x</div>
</div>
<div class="row">
  <div class="col">x</div>
</div>
<div class="row">
  <div class="col">x</div>
  <div class="col">x</div>
  <div class="col">x</div>
</div>
<div class="row">
  <div class="row">
    <div class="col">x</div>
    <div class="col">x</div>
  </div>
  <div class="row">
    <div class="col">x</div>
    <div class="col">x</div>
  </div>
</div></code>```

答:
You can add negative margin top and left equal to width of the border.

.row {
  height: 100%;
  display: flex;
  width: 100%;
  flex-wrap: wrap;
}

.col {
  border: solid 2px blue;
  padding: 5px;
  margin: 0;
  min-height: 1px;
  flex-grow: 1;
  max-width: 100%;
  text-align: center;
  margin-left: -2px;
  margin-top: -2px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div class="col">x</div>
  <div class="col">x</div>
</div>
<div class="row">
  <div class="col">x</div>
</div>
<div class="row">
  <div class="col">x</div>
  <div class="col">x</div>
  <div class="col">x</div>
</div>
<div class="row">
  <div class="row">
    <div class="col">x</div>
    <div class="col">x</div>
  </div>
  <div class="row">
    <div class="col">x</div>
    <div class="col">x</div>
  </div>
</div></code>```

Title: Overlapping border div

Body:
i want to create a table just with div tag. I use only two class and it works well.

The only problem is the border of cell inside the table have double width of the table border and it looks ugly. I know the reason is all cell have border around but i can not fix it. I've try some solution in other post but it does not work in this case.

Can some one please help me? Thanks a lot. Note that i don't want to add more class.

.row {
  height: 100%;
  display: flex;
  width: 100%;
  flex-wrap: wrap;
}

.col {
  border: solid 2px blue;
  padding: 5px;
  margin: 0;
  min-height: 1px;
  flex-grow: 1;
  max-width: 100%;
  text-align: center;
}

x

x

x

x

x

x

x

x

x

x

Body:
You can add negative margin top and left equal to width of the border.

.row {
  height: 100%;
  display: flex;
  width: 100%;
  flex-wrap: wrap;
}

.col {
  border: solid 2px blue;
  padding: 5px;
  margin: 0;
  min-height: 1px;
  flex-grow: 1;
  max-width: 100%;
  text-align: center;
  margin-left: -2px;
  margin-top: -2px;
}

<div class="row">
  <div class="col">x</div>
  <div class="col">x</div>
</div>
<div class="row">
  <div class="col">x</div>
</div>
<div class="row">
  <div class="col">x</div>
  <div class="col">x</div>
  <div class="col">x</div>
</div>
<div class="row">
  <div class="row">
    <div class="col">x</div>
    <div class="col">x</div>
  </div>
  <div class="row">
    <div class="col">x</div>
    <div class="col">x</div>
  </div>
</div>


问:
How to nest php inside if statement
Probably a newbie thing but I can't get the meta name="description" row to work. You should close and open PHP-code if its nested, right?

Thanks!
/Robert

```<code><?php
    $blogname = get_bloginfo('name');
    if ($blogname == 'Wobbling Willy') {
        echo '<meta name="description" content="?><?php bloginfo('description'); ?><?php" />'."\n";
        echo '<meta name="keywords" content=”keyword1, keyword2, keyword3” />'."\n";
    }
?>
</code>```

答:
In reply to the OP's question about nested PHP tags, the nesting of PHP opening and closing tags only applies to doing so within HTML code, as follows:

```<code><div id="<?php echo $id; ?>">
</code>```

Note: this style of mixing HTML and PHP together was far more popular years ago; nowadays this is not considered the best style. Instead, the emphasis is on a separation of concerns, as reflected in the model-view-controller design pattern.  And, nesting PHP code within PHP is not the thing to do and will likely produce a parse error.

Of the various ways to fix the code, you may wish to view my live demo which makes use of heredoc syntax.

What is interesting about the OP's snippet is that it actually does not have any PHP tags nested within PHP code. In fact, if you remove the superfluous tags, allowing for only one open tag, the code just needs minor tweaking to work, as follows:

```<code>// these function implementations are just for demo purposes:
function get_bloginfo($n) {
   return ("Wobbling Willy");
}
function bloginfo($d){
   return("some lovely description ...");
}

$blogname = get_bloginfo('name');
if ($blogname == 'Wobbling Willy') {
    echo '<meta name="description" content="';
    echo bloginfo('description'),'"/>',"\n";
    echo '<meta name="keywords" content="keyword1, keyword2, keyword3" />'."\n";
}
</code>```

See demo

The return value of bloginfo() will not appear unless provided as a  parameter to a function or construct, such as echo, which will output it. Splitting up the  display of the "description" meta tag while awkward will work provided that one uses the single quotes as needed. Lastly, curly quotes can be problematic and in this case I replaced those enveloping the second meta tag's content with straight ones to enclose the keywords.

Title: How to nest php inside if statement

Body:
Probably a newbie thing but I can't get the meta name="description" row to work. You should close and open PHP-code if its nested, right?

Thanks!
/Robert

<?php
    $blogname = get_bloginfo('name');
    if ($blogname == 'Wobbling Willy') {
        echo '<meta name="description" content="?><?php bloginfo('description'); ?><?php" />'."\n";
        echo '<meta name="keywords" content=”keyword1, keyword2, keyword3” />'."\n";
    }
?>

Body:
In reply to the OP's question about nested PHP tags, the nesting of PHP opening and closing tags only applies to doing so within HTML code, as follows:

<div id="<?php echo $id; ?>">

Note: this style of mixing HTML and PHP together was far more popular years ago; nowadays this is not considered the best style. Instead, the emphasis is on a separation of concerns, as reflected in the model-view-controller design pattern.  And, nesting PHP code within PHP is not the thing to do and will likely produce a parse error.

Of the various ways to fix the code, you may wish to view my live demo which makes use of heredoc syntax.

What is interesting about the OP's snippet is that it actually does not have any PHP tags nested within PHP code. In fact, if you remove the superfluous tags, allowing for only one open tag, the code just needs minor tweaking to work, as follows:

// these function implementations are just for demo purposes:
function get_bloginfo($n) {
   return ("Wobbling Willy");
}
function bloginfo($d){
   return("some lovely description ...");
}

$blogname = get_bloginfo('name');
if ($blogname == 'Wobbling Willy') {
    echo '<meta name="description" content="';
    echo bloginfo('description'),'"/>',"\n";
    echo '<meta name="keywords" content="keyword1, keyword2, keyword3" />'."\n";
}

See demo

The return value of bloginfo() will not appear unless provided as a  parameter to a function or construct, such as echo, which will output it. Splitting up the  display of the "description" meta tag while awkward will work provided that one uses the single quotes as needed. Lastly, curly quotes can be problematic and in this case I replaced those enveloping the second meta tag's content with straight ones to enclose the keywords.


问:
Circular button cropped, why z-index doesn't work?
I'm trying to have a circular tag pinned in the top right corner.
By the way it's cropped:

Here is my html

```<code><div class='row'>
  <div class='product'>
    <div class='discount'>
      <span class='green'>
        40%
      </span>
    </div>
    <div class='product_header'>
      10 luglio
    </div>
    <div class='product_inner'>
      <img src='https://images-na.ssl-images-amazon.com/images/I/61eHXu2AgXL._SL1000_.jpg' width='300'>
      <p>Nike Air (Women)</p>
      <p>Size 7</p>
      <p class='price'>
        Price £199.99
      </p>
      <button>guarda offerta</button>
      <button>Storico prezzi</button>
    </div>
    <div class='product_overlay'>
      <h2>Added to basket</h2>
      <i class='fa fa-check'></i>
    </div>
  </div>
</div>
</code>```

And here the CSS

```<code>* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Open Sans Condensed', sans-serif;
  font-weight: 700;
}

.row {
  width: 100%;
  -webkit-box-pack: start;
      -ms-flex-pack: start;
          justify-content: flex-start;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-flow: row wrap;
      flex-flow: row wrap;
}

.product {
  box-shadow: 1px 5px 15px #CCC;
  background-color: white;
  width: 15em;
  height: auto;
  padding: 2em;
  margin: 1em;
  overflow: hidden;
  position: relative;
  -webkit-box-flex: 1;
      -ms-flex: auto;
          flex: auto;
}
.product .discount {
  position: absolute;
  right: -10px;
  top: -10px;
}
.product .discount span.green {
  -webkit-box-pack: center;
      -ms-flex-pack: center;
          justify-content: center;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
  border-radius: 100%;
  text-align: center;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  background: #5EA226;
  width: 3em;
  height: 3em;
  color: #ffffff;
  font-weight: bold;
  font-size: 1.2em;
}
.product img {
  max-width: 100%;
  height: auto !important;
  text-align: center;
}
.product_inner {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
  -ms-flex-flow: column wrap;
      flex-flow: column wrap;
}
.product_inner p {
  color: black;
}
.product_inner .price {
  color: red;
  font-size: 2em;
}
.product_inner button {
  border: 1px solid black;
  color: #000;
  font-size: 1em;
  border-radius: 3px;
  padding: 0.5em 3em;
  margin: 1em 0 0 0;
  background: none;
  cursor: pointer;
  -webkit-transition: background ease-in .25s;
  transition: background ease-in .25s;
}
.product_inner button:hover {
  background: rgba(255, 255, 255, 0.5);
  color: green;
}
.product_inner button:before {
  font-family: FontAwesome;
  content: '\f07A';
  color: #000;
  position: absolute;
  font-size: 1.5em;
  margin: 0 -1.5em;
}
.product_inner button:hover:before {
  color: green;
}
.product_overlay {
  background: rgba(255, 255, 255, 0.9);
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  -webkit-transform: translateY(-500px);
          transform: translateY(-500px);
  opacity: 0;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-flow: column wrap;
      flex-flow: column wrap;
  -webkit-box-pack: center;
      -ms-flex-pack: center;
          justify-content: center;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
}
.product_overlay h2 {
  color: rgba(43, 45, 66, 0.7);
  font-size: 1.2em;
  margin: 1em 0;
}
.product_overlay i {
  color: rgba(43, 45, 66, 0.7);
  font-size: 1.5em;
}
</code>```

The cropped tag is in the top tight corner, I try with z-index but I don't understand what is the issue...

I also have a codepen

答:
change this:

```<code>.product{
    box-shadow: 1px 5px 15px #CCC;
    background-color: white;
    width: 15em;
    height: auto;
    padding: 2em;
    margin: 1em;
    overflow: hidden;
    position: relative;
    -webkit-box-flex: 1;
    -ms-flex: auto;
    flex: auto;
    }
</code>```

to this:

```<code>.product{
    box-shadow: 1px 5px 15px #CCC;
    background-color: white;
    width: 15em;
    height: auto;
    padding: 2em;
    margin: 1em;
    position: relative;
    -webkit-box-flex: 1;
    -ms-flex: auto;
    flex: auto;
    }
</code>```

Body:
I'm trying to have a circular tag pinned in the top right corner.
By the way it's cropped:

Here is my html

        40%

      10 luglio

Nike Air (Women)

Size 7

        Price £199.99

      <button>guarda offerta</button>
      <button>Storico prezzi</button>

Added to basket

And here the CSS

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Open Sans Condensed', sans-serif;
  font-weight: 700;
}

.row {
  width: 100%;
  -webkit-box-pack: start;
      -ms-flex-pack: start;
          justify-content: flex-start;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-flow: row wrap;
      flex-flow: row wrap;
}

.product {
  box-shadow: 1px 5px 15px #CCC;
  background-color: white;
  width: 15em;
  height: auto;
  padding: 2em;
  margin: 1em;
  overflow: hidden;
  position: relative;
  -webkit-box-flex: 1;
      -ms-flex: auto;
          flex: auto;
}
.product .discount {
  position: absolute;
  right: -10px;
  top: -10px;
}
.product .discount span.green {
  -webkit-box-pack: center;
      -ms-flex-pack: center;
          justify-content: center;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
  border-radius: 100%;
  text-align: center;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  background: #5EA226;
  width: 3em;
  height: 3em;
  color: #ffffff;
  font-weight: bold;
  font-size: 1.2em;
}
.product img {
  max-width: 100%;
  height: auto !important;
  text-align: center;
}
.product_inner {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
  -ms-flex-flow: column wrap;
      flex-flow: column wrap;
}
.product_inner p {
  color: black;
}
.product_inner .price {
  color: red;
  font-size: 2em;
}
.product_inner button {
  border: 1px solid black;
  color: #000;
  font-size: 1em;
  border-radius: 3px;
  padding: 0.5em 3em;
  margin: 1em 0 0 0;
  background: none;
  cursor: pointer;
  -webkit-transition: background ease-in .25s;
  transition: background ease-in .25s;
}
.product_inner button:hover {
  background: rgba(255, 255, 255, 0.5);
  color: green;
}
.product_inner button:before {
  font-family: FontAwesome;
  content: '\f07A';
  color: #000;
  position: absolute;
  font-size: 1.5em;
  margin: 0 -1.5em;
}
.product_inner button:hover:before {
  color: green;
}
.product_overlay {
  background: rgba(255, 255, 255, 0.9);
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  -webkit-transform: translateY(-500px);
          transform: translateY(-500px);
  opacity: 0;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-flow: column wrap;
      flex-flow: column wrap;
  -webkit-box-pack: center;
      -ms-flex-pack: center;
          justify-content: center;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
}
.product_overlay h2 {
  color: rgba(43, 45, 66, 0.7);
  font-size: 1.2em;
  margin: 1em 0;
}
.product_overlay i {
  color: rgba(43, 45, 66, 0.7);
  font-size: 1.5em;
}

The cropped tag is in the top tight corner, I try with z-index but I don't understand what is the issue...

I also have a codepen

Body:
change this:

.product{
    box-shadow: 1px 5px 15px #CCC;
    background-color: white;
    width: 15em;
    height: auto;
    padding: 2em;
    margin: 1em;
    overflow: hidden;
    position: relative;
    -webkit-box-flex: 1;
    -ms-flex: auto;
    flex: auto;
    }

to this:

.product{
    box-shadow: 1px 5px 15px #CCC;
    background-color: white;
    width: 15em;
    height: auto;
    padding: 2em;
    margin: 1em;
    position: relative;
    -webkit-box-flex: 1;
    -ms-flex: auto;
    flex: auto;
    }


问:
How set the android:gravity to TextView from Java side in Android
I can use android:gravity="bottom|center_horizontal" in xml on a textview to get my desired results, but I need to do this programmatically. My textview is inside a tablerow if that matters in a relativelayout.

I have tried:

```<code>LayoutParams layoutParams = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
labelTV.setLayoutParams(layoutParams);
</code>```

But if I understand correctly, that would apply it to the tablerow, not the textview?

答:
Use this code</p>

```<code>        TextView textView = new TextView(YourActivity.this);
        textView.setGravity(Gravity.CENTER | Gravity.TOP);
        textView.setText("some text");
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I can use android:gravity="bottom|center_horizontal" in xml on a textview to get my desired results, but I need to do this programmatically. My textview is inside a tablerow if that matters in a relativelayout.

I have tried:

LayoutParams layoutParams = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
labelTV.setLayoutParams(layoutParams);

But if I understand correctly, that would apply it to the tablerow, not the textview?

Body:
Use this code

        TextView textView = new TextView(YourActivity.this);
        textView.setGravity(Gravity.CENTER | Gravity.TOP);
        textView.setText("some text");


问:
Have not been able to launch Visual Studio Code Insider
I've tried to update the VS Code Insider recently. I don't recall whether the update was complete or not. Ever since then, every time I try to launch VS Code Insider, I get the error "A JavaScript error occurred in the main process." I've kept the screenshot below.

How can this be resolved?

答:
Likely fixable by a reinstall or fixed by the next insiders build

Please file these sort of issues against VSCode directly in the future: https://github.com/Microsoft/vscode/issues/new


答:
User can store the value in the keychain of the device. you can save that data in keychain untill he reset all settings in the phone. I normally uses this library to store data using keychain.

But its better to keep the status in server using a webservice because even if you stored data in keychain, user can reset all settings of the device and install app again which gives him 3 coins again. Without a back end support its not possible to do a perfect solution for this

Title: Limit iOS App even after the user re-installs it

Body:
I created an app that gives the user 3 coins at the first launch.

Once the user finished the 3 coins he should buy unlimited coins by an In-App purchase.

The problem is that if the user doesn't want to buy unlimited coins he can delete the app, install the app again and he will have again the 3 coins again.
And he can do this forever without ever buying the In-App purchase.

Is there a simple way to prevent this? How can I know if a user finished the coins inside the app even after deleting it?


问:
Lat/lon distance calculation by converting to utm gives different results than using approximate method
I've got two methods for calculating the distance between georeferenced coordinates in python:

```<code>from pyproj import Proj
import math

def calc_distance(lat1, lon1, lat2, lon2):
    """
    Calculate the great circle distance between two points
    on the earth (specified in decimal degrees)
    """
    # convert decimal degrees to radians
    lon1, lat1, lon2, lat2 = map(math.radians, [lon1, lat1, lon2, lat2])

    # haversine formula
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = math.sin(dlat / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2) ** 2
    c = 2 * math.asin(math.sqrt(a))
    km = 6371 * c

    return km

def calc_distance_convert_utm(lat1, lon1, lat2, lon2):
    myProj = Proj("+proj=utm +zone=42, +north +ellps=WGS84 +datum=WGS84 +units=m +no_defs")

    # convert to utm
    utm_x1, utm_y1 = myProj(lat1, lon1)
    utm_x2, utm_y2 = myProj(lat2, lon2)

    diff_x = abs(utm_x1 - utm_x2)
    diff_y = abs(utm_y1 - utm_y2)

    distance = math.sqrt(diff_x**2 + diff_y**2)

    return distance
</code>```

Which I call with the following values:

```<code>lat1 = 34.866527
lon1 = 69.674606
lat2 = 34.864990
lon2 = 69.657655
print "approximation method: ", calc_distance(lat1, lon1, lat2, lon2)
print "converting to utm method: ", calc_distance_convert_utm(lat1, lon1, lat2, lon2)
</code>```

However, If I compare the results, I get two different values:

```<code>approximation method:  1.55593476881
converting to utm method:  1928.21537269
</code>```

Note, that the first method returns the distance in kilometers while the second returns it in meters.
I've compared the result with distance calculators which you can find online, and it seems that the first method (approximation method) is the "more correct" answer as this is the value most online calculators return. I wonder, why the second method (converting to utm first) does not return a more similar result (something like 1555.9347...). I have a difference of almost 0.5 km which seems pretty much to me.

Did I do anything wrong?
Any help is appreciated! Thanks

答:
I've found the error ...
In the utm converting method I've switched the lat/lon values in the conversion process. It should be:</p>

```<code>utm_x1, utm_y1 = myProj(lon1, lat1)
utm_x2, utm_y2 = myProj(lon2, lat2)
</code>```

Body:
I've got two methods for calculating the distance between georeferenced coordinates in python:

from pyproj import Proj
import math

def calc_distance(lat1, lon1, lat2, lon2):
    """
    Calculate the great circle distance between two points
    on the earth (specified in decimal degrees)
    """
    # convert decimal degrees to radians
    lon1, lat1, lon2, lat2 = map(math.radians, [lon1, lat1, lon2, lat2])

    # haversine formula
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = math.sin(dlat / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2) ** 2
    c = 2 * math.asin(math.sqrt(a))
    km = 6371 * c

    return km

def calc_distance_convert_utm(lat1, lon1, lat2, lon2):
    myProj = Proj("+proj=utm +zone=42, +north +ellps=WGS84 +datum=WGS84 +units=m +no_defs")

    # convert to utm
    utm_x1, utm_y1 = myProj(lat1, lon1)
    utm_x2, utm_y2 = myProj(lat2, lon2)

    diff_x = abs(utm_x1 - utm_x2)
    diff_y = abs(utm_y1 - utm_y2)

    distance = math.sqrt(diff_x**2 + diff_y**2)

    return distance

Which I call with the following values:

lat1 = 34.866527
lon1 = 69.674606
lat2 = 34.864990
lon2 = 69.657655
print "approximation method: ", calc_distance(lat1, lon1, lat2, lon2)
print "converting to utm method: ", calc_distance_convert_utm(lat1, lon1, lat2, lon2)

However, If I compare the results, I get two different values:

approximation method:  1.55593476881
converting to utm method:  1928.21537269

Note, that the first method returns the distance in kilometers while the second returns it in meters.
I've compared the result with distance calculators which you can find online, and it seems that the first method (approximation method) is the "more correct" answer as this is the value most online calculators return. I wonder, why the second method (converting to utm first) does not return a more similar result (something like 1555.9347...). I have a difference of almost 0.5 km which seems pretty much to me.

Did I do anything wrong?
Any help is appreciated! Thanks

Body:
I've found the error ...
In the utm converting method I've switched the lat/lon values in the conversion process. It should be:

utm_x1, utm_y1 = myProj(lon1, lat1)
utm_x2, utm_y2 = myProj(lon2, lat2)


问:
java 8 findFirst vs map on optional
Given this code:

```<code>class Foo {
  Integer attr;
  public Integer getAttr() {return attr;}
}

List<Foo> list = new ArrayList<>();
list.add(new Foo());

list.stream().map(Foo::getAttr).findAny().orElse(null);  //A
list.stream().findAny().map(Foo::getAttr).orElse(null);  //B
</code>```

Line A throws

java.lang.NullPointerException: null

while line B returns null.

What is the cause of this behaviour? Both findAny() and map() return Optional<T>.

答:
First, your two code snippet map are different operations:

```<code>//            v--- stream intermediate operation
list.stream().map(Foo::getAttr).findAny().orElse(null);  //A
//                      v---- a Optional utility method
list.stream().findAny().map(Foo::getAttr).orElse(null);  //B
</code>```

and the NullPointerException occurs in Stream#findAny operation, since it can't accept a null value. due to it uses Optional.of rather than Optional.ofNullable. and the documentation of Stream#findAny is already asserts:

Throws:

NullPointerException - if the element selected is null

so if you want your A code snippet works fine you must filter all null values before calling Stream#findAny, for example:

```<code>//when no elements in stream, `findAny` will be return a empty by Optional.empty()
//                                                       v
list.stream().map(Foo::getAttr).filter(Objects::nonNull).findAny().orElse(null);//A
</code>```

Title: java 8 findFirst vs map on optional

Body:
Given this code:

class Foo {
  Integer attr;
  public Integer getAttr() {return attr;}
}

List<Foo> list = new ArrayList<>();
list.add(new Foo());

list.stream().map(Foo::getAttr).findAny().orElse(null);  //A
list.stream().findAny().map(Foo::getAttr).orElse(null);  //B

Line A throws

java.lang.NullPointerException: null

while line B returns null.

What is the cause of this behaviour? Both findAny() and map() return Optional<T>.

Body:
First, your two code snippet map are different operations:

//            v--- stream intermediate operation
list.stream().map(Foo::getAttr).findAny().orElse(null);  //A
//                      v---- a Optional utility method
list.stream().findAny().map(Foo::getAttr).orElse(null);  //B

and the NullPointerException occurs in Stream#findAny operation, since it can't accept a null value. due to it uses Optional.of rather than Optional.ofNullable. and the documentation of Stream#findAny is already asserts:

Throws:

NullPointerException - if the element selected is null

so if you want your A code snippet works fine you must filter all null values before calling Stream#findAny, for example:

//when no elements in stream, `findAny` will be return a empty by Optional.empty()
//                                                       v
list.stream().map(Foo::getAttr).filter(Objects::nonNull).findAny().orElse(null);//A


问:
How to display an image in an element from another element using jQuery
I want to select and display an image using jQuery.

I'm trying click on tile_details div and display tile__media image in col-md-6 with jQuery.

```<code><div class="tile">
  <div class="tile__media">
    <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-18.jpg" alt="" />
  </div>
  <div class="tile__details">
    <div class="tile__title">
      Top Gear
    </div>
  </div>
</div>

<div class="container-fluid" style="display:none">
  <div class="row">
    <div class="col-md-6">
      Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque eveniet reprehenderit, consequatur perferendis repellendus omnis libero laboriosam nostrum tenetur nulla dolores quos id delectus quo obcaecati eaque provident? Maxime, atque. Lorem ipsum
      dolor sit amet, consectetur adipisicing elit. Itaque eveniet reprehenderit, consequatur perferendis repellendus omnis libero laboriosam nostrum tenetur nulla dolores quos id delectus quo obcaecati eaque provident? Maxime, atque. Lorem ipsum dolor
      sit amet, consectetur adipisicing elit. Itaque eveniet reprehenderit, consequatur perferendis repellendus omnis libero laboriosam nostrum tenetur nulla dolores quos id delectus quo obcaecati eaque provident? Maxime, atque. Lorem ipsum dolor sit
      amet, consectetur adipisicing elit. Itaque eveniet reprehenderit, consequatur perferendis repellendus omnis libero laboriosam nostrum tenetur nulla dolores quos id delectus quo obcaecati eaque provident? Maxime, atque. Lorem ipsum dolor sit amet,
      consectetur adipisicing elit. Itaque eveniet reprehenderit, consequatur perferendis repellendus omnis libero laboriosam nostrum tenetur nulla dolores quos id delectus quo obcaecati eaque provident? Maxime, atque.
    </div>
    <div class="col-md-6">
      //Display Image
    </div>
  </div>
</div>
</code>```

答:
If I understand the question correctly, you want to get the image from the '.tile__media' div and set it to the contents of that div. If you give the div an identifier, this could be achieved through the following jQuery:

```<code>$(".tile__details").click(function(e) {
    $('#imageDiv').html($('.tile__media').html());
});
</code>```

jsFiddle

Update: If you want it to be dynamic, based upon the image you clicked upon, you could clone the image clicked into the div. The code is as follows:

```<code>$(".tile__img").click(function(e) {
    $('#imageDiv').html($(this).clone());
});
</code>```

jsFiddle

Body:
I want to select and display an image using jQuery.

I'm trying click on tile_details div and display tile__media image in col-md-6 with jQuery.

      Top Gear

      Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque eveniet reprehenderit, consequatur perferendis repellendus omnis libero laboriosam nostrum tenetur nulla dolores quos id delectus quo obcaecati eaque provident? Maxime, atque. Lorem ipsum
      dolor sit amet, consectetur adipisicing elit. Itaque eveniet reprehenderit, consequatur perferendis repellendus omnis libero laboriosam nostrum tenetur nulla dolores quos id delectus quo obcaecati eaque provident? Maxime, atque. Lorem ipsum dolor
      sit amet, consectetur adipisicing elit. Itaque eveniet reprehenderit, consequatur perferendis repellendus omnis libero laboriosam nostrum tenetur nulla dolores quos id delectus quo obcaecati eaque provident? Maxime, atque. Lorem ipsum dolor sit
      amet, consectetur adipisicing elit. Itaque eveniet reprehenderit, consequatur perferendis repellendus omnis libero laboriosam nostrum tenetur nulla dolores quos id delectus quo obcaecati eaque provident? Maxime, atque. Lorem ipsum dolor sit amet,
      consectetur adipisicing elit. Itaque eveniet reprehenderit, consequatur perferendis repellendus omnis libero laboriosam nostrum tenetur nulla dolores quos id delectus quo obcaecati eaque provident? Maxime, atque.

      //Display Image

Body:
If I understand the question correctly, you want to get the image from the '.tile__media' div and set it to the contents of that div. If you give the div an identifier, this could be achieved through the following jQuery:

$(".tile__details").click(function(e) {
    $('#imageDiv').html($('.tile__media').html());
});

jsFiddle

Update: If you want it to be dynamic, based upon the image you clicked upon, you could clone the image clicked into the div. The code is as follows:

$(".tile__img").click(function(e) {
    $('#imageDiv').html($(this).clone());
});

jsFiddle


问:
better way of handling nested list
```<code>my_list = [ [1,2,3,4,5,6], [1,3,4],[34,56,56,56]]
for item in my_list:
    var1,var2,var3,var4,var5,var6 = None
     if len(item) ==1:
          var1 = item[0]
     if len(item) == 2:
          var1 = item[0]
          var2  = item[1]
     if len(item) == 3:
         var1 = item[0]
         var2 = item[1]
         var3 = item[2]
     if len(item) == 4:
        var1 = item[0]
        var2 = item[1]
        var3 = item[2]
        var4 = item[3]
    fun(var1,var2,var3,var4,var5,var6)
</code>```

I have a function

```<code>def fun(var1, var2 = None, var3 = None, var4 = None, var5=None, var6= None)
</code>```

Depending upon the values in my inner list. I am passing it to function.
I hope I made it clear.

Thanks

答:
EDIT - the real question is - my have function which takes def fun(var1, var2=None, var3= None,var4=None,var5 = None, var6 = None): so if my inner list contain only 1 element then function takes var1 only. but if more then 1 element in my inner list it is pass to the function

What you would like to use is the * operator

```<code>fun(*l)
</code>```

is equivalent to

```<code>fun(l[0],l[1],....)
</code>```

So you want to use: fun(*my_list[0]) for the first, and so on

To use it for all the lists inside my_list do:

```<code>for i in my_list:
    fun(*i)
</code>```

Title: better way of handling nested list

Body:
my_list = [ [1,2,3,4,5,6], [1,3,4],[34,56,56,56]]
for item in my_list:
    var1,var2,var3,var4,var5,var6 = None
     if len(item) ==1:
          var1 = item[0]
     if len(item) == 2:
          var1 = item[0]
          var2  = item[1]
     if len(item) == 3:
         var1 = item[0]
         var2 = item[1]
         var3 = item[2]
     if len(item) == 4:
        var1 = item[0]
        var2 = item[1]
        var3 = item[2]
        var4 = item[3]
    fun(var1,var2,var3,var4,var5,var6)

I have a function

def fun(var1, var2 = None, var3 = None, var4 = None, var5=None, var6= None)

Depending upon the values in my inner list. I am passing it to function.
I hope I made it clear.

Thanks

Body:
EDIT - the real question is - my have function which takes def fun(var1, var2=None, var3= None,var4=None,var5 = None, var6 = None): so if my inner list contain only 1 element then function takes var1 only. but if more then 1 element in my inner list it is pass to the function

What you would like to use is the * operator

fun(*l)

is equivalent to

fun(l[0],l[1],....)

So you want to use: fun(*my_list[0]) for the first, and so on

To use it for all the lists inside my_list do:

for i in my_list:
    fun(*i)


问:
How to make the shape return back to its default value in jquery?
```<code>$(document).ready(function(){
    $("#info2").click(function(){
       $(this).animate({height: "120px", width:"360px"});
   });
});
</code>```

I would like to know how to return the shape back to the original form after expanding it.

答:
You can record the original dimensions into a data attribute, and them retreive it.

Example:

```<code>$(document).ready(function(){
    $("#info2").data("originalheight", $("#info2").height());
    $("#info2").data("originalwidth", $("#info2").width());
    $("#info2").click(function(){
       $(this).animate({height: "120px", width:"360px"});
   });
//click somewhere else to return to the original dimensions:
$("#another_link").click(function(){
       $("#info2").animate({height: $("#info2").data("originalheight") + "px", width: $("#info2").data("originalwidth") + "px"});
   });
});
</code>```

Body:
$(document).ready(function(){
    $("#info2").click(function(){
       $(this).animate({height: "120px", width:"360px"});
   });
});

I would like to know how to return the shape back to the original form after expanding it.

Body:
You can record the original dimensions into a data attribute, and them retreive it.

Example:

$(document).ready(function(){
    $("#info2").data("originalheight", $("#info2").height());
    $("#info2").data("originalwidth", $("#info2").width());
    $("#info2").click(function(){
       $(this).animate({height: "120px", width:"360px"});
   });
//click somewhere else to return to the original dimensions:
$("#another_link").click(function(){
       $("#info2").animate({height: $("#info2").data("originalheight") + "px", width: $("#info2").data("originalwidth") + "px"});
   });
});


问:
template for a smartpointer and auto deletion of the pointer
I have come across this simple code in a website. I didn't understand it fully. It would be very helpful for me if someone can breakdown the code line by line and explain.

This is a code for creating a template of a smart pointer (auto deletion of pointer is the main motto to create such a pointer)

```<code>#include <iostream>
using namespace std;

template <class T>
class SmartPtr {
    T* ptr;

public:
    explicit SmartPtr(T* p = NULL) {
        ptr = p;
    }
    ~SmartPtr() {
        delete(ptr);
    }
    T& operator*() {
        return *ptr;
    }
    T* operator->() {
        return ptr;
    }
};

int main() {
    SmartPtr<int> ptr(new int());
    *ptr = 20;

    cout << *ptr;
    return 0;
}
</code>```

答:
"Break down line by line" is a little bit excessive, for the future, try to mention single parts that you don't understand in particular. But since it's not that much code...</p>

```<code>#include <iostream>
using namespace std;
template <class T> //make it a template in order to be able to store any type
class SmartPtr {
T *ptr; //wrapped pointer
public: explicit SmartPtr(T *p = NULL) { ptr = p; } //basic constructor

//delete pointer when the object dies.
//Note that this means that this is meant to be a unique pointer,
//a shared pointer would have to count occurencies first
 ~SmartPtr() { delete(ptr); }

//dereference operator to manipulate the content.
//I prefer to go with T& instead of T & to make it clear that it is
//"reference of type T"
T & operator * () {  return *ptr; }
//bad operator which exposes the pointer itself.
//Make this const, like const T* operator -> () const { ... }
//else this could be used for the constructor again,
//leading to undefined behaviour when the pointer is deleted twice
T * operator -> () { return ptr; } }; //class ending brace at bad position

int main(){
SmartPtr<int> ptr(new int());
*ptr = 20;
cout << *ptr;
return 0; }
</code>```

Body:
I have come across this simple code in a website. I didn't understand it fully. It would be very helpful for me if someone can breakdown the code line by line and explain.

This is a code for creating a template of a smart pointer (auto deletion of pointer is the main motto to create such a pointer)

#include <iostream>
using namespace std;

template <class T>
class SmartPtr {
    T* ptr;

public:
    explicit SmartPtr(T* p = NULL) {
        ptr = p;
    }
    ~SmartPtr() {
        delete(ptr);
    }
    T& operator*() {
        return *ptr;
    }
    T* operator->() {
        return ptr;
    }
};

int main() {
    SmartPtr<int> ptr(new int());
    *ptr = 20;

    cout << *ptr;
    return 0;
}

Body:
"Break down line by line" is a little bit excessive, for the future, try to mention single parts that you don't understand in particular. But since it's not that much code...

#include <iostream>
using namespace std;
template <class T> //make it a template in order to be able to store any type
class SmartPtr {
T *ptr; //wrapped pointer
public: explicit SmartPtr(T *p = NULL) { ptr = p; } //basic constructor

//delete pointer when the object dies.
//Note that this means that this is meant to be a unique pointer,
//a shared pointer would have to count occurencies first
 ~SmartPtr() { delete(ptr); }

//dereference operator to manipulate the content.
//I prefer to go with T& instead of T & to make it clear that it is
//"reference of type T"
T & operator * () {  return *ptr; }
//bad operator which exposes the pointer itself.
//Make this const, like const T* operator -> () const { ... }
//else this could be used for the constructor again,
//leading to undefined behaviour when the pointer is deleted twice
T * operator -> () { return ptr; } }; //class ending brace at bad position

int main(){
SmartPtr<int> ptr(new int());
*ptr = 20;
cout << *ptr;
return 0; }


问:
Can't move a file in python? Errno 13- Permission Denied
this is my code:

```<code>def unpack(folders):
for folder in folders:
    files = os.listdir(folder)
    print (files)
    while len(os.listdir(folder)) != 0:
        for file in files:
            if os.path.isdir(file)==False:
                print (file)
                shutil.move(os.path.join(cur_dir,folder,file),os.path.join(cur_dir,file))
            else:
                unpack(file)

    if len(os.listdir(folder))==0:
        os.rmdir(folder)
</code>```

When I call this on the directory this program is in, everything works fine, but I can't copy a file called 'desktop.ini'. This is the error:

```<code>Traceback (most recent call last):
  File "C:\Users\satvi_000\AppData\Local\Programs\Python\Python36\lib\shutil.py", line 544, in move
    os.rename(src, real_dst)
FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'C:\\Users\\satvi_000\\Downloads\\others\\desktop.ini' -> 'C:\\Users\\satvi_000\\Downloads\\desktop.ini'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\satvi_000\Downloads\clean_folder.py", line 37, in <module>
    unpack(folders_list)
  File "C:\Users\satvi_000\Downloads\clean_folder.py", line 30, in unpack
    shutil.move(os.path.join(cur_dir,folder,file),os.path.join(cur_dir,file))
  File "C:\Users\satvi_000\AppData\Local\Programs\Python\Python36\lib\shutil.py", line 558, in move
    copy_function(src, real_dst)
  File "C:\Users\satvi_000\AppData\Local\Programs\Python\Python36\lib\shutil.py", line 257, in copy2
    copyfile(src, dst, follow_symlinks=follow_symlinks)
  File "C:\Users\satvi_000\AppData\Local\Programs\Python\Python36\lib\shutil.py", line 121, in copyfile
    with open(dst, 'wb') as fdst:
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\satvi_000\\Downloads\\desktop.ini'
</code>```

I'm guessing this is a system file or something. How do I get past this? It's not completely necessary to move the file, skipping it is fine.

答:
Look at the first error in the stacktrace:

FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'C:\Users\satvi_000\Downloads\others\desktop.ini' -> 'C:\Users\satvi_000\Downloads\desktop.ini'

The doc of os.rename (which is used by shutil.move) say this about windows:

On Windows, if dst already exists, OSError will be raised even if it is a file; there may be no way to implement an atomic rename when dst names an existing file

So, you have to check that the file does not exist before moving:

```<code>if os.path.exists(path):
    continue
</code>```

Body:
this is my code:

def unpack(folders):
for folder in folders:
    files = os.listdir(folder)
    print (files)
    while len(os.listdir(folder)) != 0:
        for file in files:
            if os.path.isdir(file)==False:
                print (file)
                shutil.move(os.path.join(cur_dir,folder,file),os.path.join(cur_dir,file))
            else:
                unpack(file)

    if len(os.listdir(folder))==0:
        os.rmdir(folder)

When I call this on the directory this program is in, everything works fine, but I can't copy a file called 'desktop.ini'. This is the error:

Traceback (most recent call last):
  File "C:\Users\satvi_000\AppData\Local\Programs\Python\Python36\lib\shutil.py", line 544, in move
    os.rename(src, real_dst)
FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'C:\\Users\\satvi_000\\Downloads\\others\\desktop.ini' -> 'C:\\Users\\satvi_000\\Downloads\\desktop.ini'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\satvi_000\Downloads\clean_folder.py", line 37, in <module>
    unpack(folders_list)
  File "C:\Users\satvi_000\Downloads\clean_folder.py", line 30, in unpack
    shutil.move(os.path.join(cur_dir,folder,file),os.path.join(cur_dir,file))
  File "C:\Users\satvi_000\AppData\Local\Programs\Python\Python36\lib\shutil.py", line 558, in move
    copy_function(src, real_dst)
  File "C:\Users\satvi_000\AppData\Local\Programs\Python\Python36\lib\shutil.py", line 257, in copy2
    copyfile(src, dst, follow_symlinks=follow_symlinks)
  File "C:\Users\satvi_000\AppData\Local\Programs\Python\Python36\lib\shutil.py", line 121, in copyfile
    with open(dst, 'wb') as fdst:
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\satvi_000\\Downloads\\desktop.ini'

I'm guessing this is a system file or something. How do I get past this? It's not completely necessary to move the file, skipping it is fine.

Body:
Look at the first error in the stacktrace:

FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'C:\Users\satvi_000\Downloads\others\desktop.ini' -> 'C:\Users\satvi_000\Downloads\desktop.ini'

The doc of os.rename (which is used by shutil.move) say this about windows:

On Windows, if dst already exists, OSError will be raised even if it is a file; there may be no way to implement an atomic rename when dst names an existing file

So, you have to check that the file does not exist before moving:

if os.path.exists(path):
    continue


问:
Need to get current location and destination location pin
How do I get the current location with green pin and destination location with red pin?

When I work on some stuff I get only destination location with red pin, not at the current location.

My source code.

```<code>#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <MapKit/MKAnnotation.h>
#import <CoreLocation/CoreLocation.h>

@interface AddressAnnotation : NSObject<MKAnnotation> {
    CLLocationCoordinate2D coordinate;

    NSString *mTitle;
    NSString *mSubTitle;

//  CLLocationManager *locationManager;
//  CLLocation *currentLocation;
}
@end
@interface MapViewController : UIViewController <CLLocationManagerDelegate,MKMapViewDelegate>  {

    IBOutlet MKMapView *mapView;
    AddressAnnotation *addAnnotation;
    NSString *address;
    CLLocationManager *locationManager;
    CLLocation *currentLocation;
}
+(MapViewController *)sharedInstance;
-(void)start;
-(void)stop;
-(BOOL)locationKnown;
@property(nonatomic,retain)CLLocation *currentLocation;
@property(nonatomic,retain)NSString *address;
-(CLLocationCoordinate2D) addressLocation;
-(void)showAddress;
@end

#import "MapViewController.h"

@implementation AddressAnnotation
@synthesize coordinate;
//@synthesize currentLocation;

- (NSString *)subtitle{
    //return @"Sub Title";
    return @"Event";
}
- (NSString *)title{
    //return @"Title";
    return @"Allure-Exclusive";
}

-(id)initWithCoordinate:(CLLocationCoordinate2D) c{
    coordinate=c;
    //NSLog(@"%f,%f",c.latitude,c.longitude);
    return self;
}

@end

@implementation MapViewController

@synthesize address;
@synthesize currentLocation;

static MapViewController *sharedInstance;

+(MapViewController *)sharedInstance{
    @synchronized (self)
    {
        if (!sharedInstance)
        [[MapViewController alloc]init];
        }
    return sharedInstance;
}
+(id)alloc{
    @synchronized(self){
        NSAssert(sharedInstance==nil,"Attempted to allocate a second instance of a singleton LocationController.");
        sharedInstance = [super alloc];
    }
    return sharedInstance;
}
-(id)init{
    if(self==[super init]){
        self.currentLocation=[[CLLocation alloc]init];
        locationManager=[[CLLocationManager alloc]init];
        locationManager.delegate=self;
        [self start];
    }
    return self;
}
-(void)start{
    NSLog(@"Start");
    mapView.showsUserLocation=YES;
    [locationManager startUpdatingLocation];
}
-(void)stop{
    mapView.showsUserLocation=NO;
    [locationManager stopUpdatingLocation];
}
-(BOOL)locationKnown{
    if (round(currentLocation.speed)==-1)
        return NO;
        else return YES;

}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    if (abs([newLocation.timestamp timeIntervalSinceDate:[NSDate date]])<120){
        self.currentLocation=newLocation;
    }
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    UIAlertView *alert;
    alert=[[UIAlertView alloc]initWithTitle:@"Error" message:[error description] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    [alert release];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"Map-View";
//  [self addressLocation];
    [self showAddress];
    NSLog(@"address is %@",address);

}

-(void)showAddress{

    MKCoordinateRegion region;
    MKCoordinateSpan span;
    span.latitudeDelta=0.5;
    span.longitudeDelta=0.5;

    CLLocationCoordinate2D location = [self addressLocation];
    region.span=span;
    region.center=location;

    if(addAnnotation != nil) {
        [mapView removeAnnotation:addAnnotation];
        [addAnnotation release];
        addAnnotation = nil;
    }

    addAnnotation = [[AddressAnnotation alloc] initWithCoordinate:location];
    [mapView addAnnotation:addAnnotation];

    [mapView setRegion:region animated:TRUE];
    [mapView regionThatFits:region];

}

-(CLLocationCoordinate2D) addressLocation {

    NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&output=csv",

   [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]];
    NSLog(@"locationString %@",locationString);
    NSArray *listItems = [locationString componentsSeparatedByString:@","];

    double latitude = 0.0;
    double longitude = 0.0;

    if([listItems count] >= 4 && [[listItems objectAtIndex:0] isEqualToString:@"200"]) {
        latitude = [[listItems objectAtIndex:2] doubleValue];
        longitude = [[listItems objectAtIndex:3] doubleValue];
        NSLog(@"listItems %@",[listItems objectAtIndex:2]);
    }
    else {
        //Show error
    }
    CLLocationCoordinate2D location;
    location.latitude = latitude;
    location.longitude = longitude;

    return location;
}

- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation{
    if (annotation==mapView.userLocation) {
        MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentloc"];
        annView.pinColor = MKPinAnnotationColorGreen;
        annView.animatesDrop=YES;
        annView.canShowCallout = YES;
        annView.calloutOffset = CGPointMake(-5, 5);
        return annView;
            //
}
    else {

    MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentloc"];
    annView.pinColor = MKPinAnnotationColorRed;
    annView.animatesDrop=YES;
    annView.canShowCallout = YES;
    annView.calloutOffset = CGPointMake(-5, 5);
    return annView;
}

}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return YES;
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
//  [self stop];
    [super viewDidUnload];

    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
    [address release];
    [super dealloc];
}
@end

- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation{

    if (annotation==mapView.userLocation)
    {
    mapView.userLocation.title=@"Current Location";
    [mapView setRegion:MKCoordinateRegionMakeWithDistance(mapView.userLocation.coordinate, 1000, 1000)animated:YES];
    return nil;
}
else {

    MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentloc"];
    annView.pinColor = MKPinAnnotationColorRed;
    annView.animatesDrop=YES;
    annView.canShowCallout = YES;
    annView.calloutOffset = CGPointMake(-5, 5);
    return annView;

}
}
</code>```

When I changed the method. it's pointing blue and blinking,but it was pointing at different location, which is at infinite Loop mariani Ave location.

It was running this in a simulator.

答:
You'll want to set showsUserLocation.

mapView.showsUserLocation = YES;

Body:
How do I get the current location with green pin and destination location with red pin?

When I work on some stuff I get only destination location with red pin, not at the current location.

My source code.

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <MapKit/MKAnnotation.h>
#import <CoreLocation/CoreLocation.h>

@interface AddressAnnotation : NSObject<MKAnnotation> {
    CLLocationCoordinate2D coordinate;

    NSString *mTitle;
    NSString *mSubTitle;

//  CLLocationManager *locationManager;
//  CLLocation *currentLocation;
}
@end
@interface MapViewController : UIViewController <CLLocationManagerDelegate,MKMapViewDelegate>  {

    IBOutlet MKMapView *mapView;
    AddressAnnotation *addAnnotation;
    NSString *address;
    CLLocationManager *locationManager;
    CLLocation *currentLocation;
}
+(MapViewController *)sharedInstance;
-(void)start;
-(void)stop;
-(BOOL)locationKnown;
@property(nonatomic,retain)CLLocation *currentLocation;
@property(nonatomic,retain)NSString *address;
-(CLLocationCoordinate2D) addressLocation;
-(void)showAddress;
@end

#import "MapViewController.h"

@implementation AddressAnnotation
@synthesize coordinate;
//@synthesize currentLocation;

- (NSString *)subtitle{
    //return @"Sub Title";
    return @"Event";
}
- (NSString *)title{
    //return @"Title";
    return @"Allure-Exclusive";
}

-(id)initWithCoordinate:(CLLocationCoordinate2D) c{
    coordinate=c;
    //NSLog(@"%f,%f",c.latitude,c.longitude);
    return self;
}

@end

@implementation MapViewController

@synthesize address;
@synthesize currentLocation;

static MapViewController *sharedInstance;

+(MapViewController *)sharedInstance{
    @synchronized (self)
    {
        if (!sharedInstance)
        [[MapViewController alloc]init];
        }
    return sharedInstance;
}
+(id)alloc{
    @synchronized(self){
        NSAssert(sharedInstance==nil,"Attempted to allocate a second instance of a singleton LocationController.");
        sharedInstance = [super alloc];
    }
    return sharedInstance;
}
-(id)init{
    if(self==[super init]){
        self.currentLocation=[[CLLocation alloc]init];
        locationManager=[[CLLocationManager alloc]init];
        locationManager.delegate=self;
        [self start];
    }
    return self;
}
-(void)start{
    NSLog(@"Start");
    mapView.showsUserLocation=YES;
    [locationManager startUpdatingLocation];
}
-(void)stop{
    mapView.showsUserLocation=NO;
    [locationManager stopUpdatingLocation];
}
-(BOOL)locationKnown{
    if (round(currentLocation.speed)==-1)
        return NO;
        else return YES;

}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    if (abs([newLocation.timestamp timeIntervalSinceDate:[NSDate date]])<120){
        self.currentLocation=newLocation;
    }
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    UIAlertView *alert;
    alert=[[UIAlertView alloc]initWithTitle:@"Error" message:[error description] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    [alert release];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"Map-View";
//  [self addressLocation];
    [self showAddress];
    NSLog(@"address is %@",address);

}

-(void)showAddress{

    MKCoordinateRegion region;
    MKCoordinateSpan span;
    span.latitudeDelta=0.5;
    span.longitudeDelta=0.5;

    CLLocationCoordinate2D location = [self addressLocation];
    region.span=span;
    region.center=location;

    if(addAnnotation != nil) {
        [mapView removeAnnotation:addAnnotation];
        [addAnnotation release];
        addAnnotation = nil;
    }

    addAnnotation = [[AddressAnnotation alloc] initWithCoordinate:location];
    [mapView addAnnotation:addAnnotation];

    [mapView setRegion:region animated:TRUE];
    [mapView regionThatFits:region];

}

-(CLLocationCoordinate2D) addressLocation {

    NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&output=csv",

   [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]];
    NSLog(@"locationString %@",locationString);
    NSArray *listItems = [locationString componentsSeparatedByString:@","];

    double latitude = 0.0;
    double longitude = 0.0;

    if([listItems count] >= 4 && [[listItems objectAtIndex:0] isEqualToString:@"200"]) {
        latitude = [[listItems objectAtIndex:2] doubleValue];
        longitude = [[listItems objectAtIndex:3] doubleValue];
        NSLog(@"listItems %@",[listItems objectAtIndex:2]);
    }
    else {
        //Show error
    }
    CLLocationCoordinate2D location;
    location.latitude = latitude;
    location.longitude = longitude;

    return location;
}

- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation{
    if (annotation==mapView.userLocation) {
        MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentloc"];
        annView.pinColor = MKPinAnnotationColorGreen;
        annView.animatesDrop=YES;
        annView.canShowCallout = YES;
        annView.calloutOffset = CGPointMake(-5, 5);
        return annView;
            //
}
    else {

    MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentloc"];
    annView.pinColor = MKPinAnnotationColorRed;
    annView.animatesDrop=YES;
    annView.canShowCallout = YES;
    annView.calloutOffset = CGPointMake(-5, 5);
    return annView;
}

}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return YES;
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
//  [self stop];
    [super viewDidUnload];

    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
    [address release];
    [super dealloc];
}
@end

- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation{

    if (annotation==mapView.userLocation)
    {
    mapView.userLocation.title=@"Current Location";
    [mapView setRegion:MKCoordinateRegionMakeWithDistance(mapView.userLocation.coordinate, 1000, 1000)animated:YES];
    return nil;
}
else {

    MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentloc"];
    annView.pinColor = MKPinAnnotationColorRed;
    annView.animatesDrop=YES;
    annView.canShowCallout = YES;
    annView.calloutOffset = CGPointMake(-5, 5);
    return annView;

}
}

When I changed the method. it's pointing blue and blinking,but it was pointing at different location, which is at infinite Loop mariani Ave location.

It was running this in a simulator.


问:
Android Studio - Device Offline
I am having a small issue with Android Studio. Whenever I put my phone into either of the front two USB ports, it shows my device as "Offline". If I use any of the back USB ports, it recognises the device perfectly fine.

I can charge and browse my phone fine from the front two USB ports. I have tried resetting ADB, and installing/updating Samsung USB drivers. I have tried enabling and disabling USB debugging - but no luck.

It really can't be an issue with the phone or with Android Studio, as in the back USB ports it works fine - surely it has to be an issue with the front USB port?

Anybody have any ideas on how I could solve this? (Other than just using the back ones!)

答:
You can try this:

Go to tools/enable adb integration and uncheck it.

now check it and run again. Next time, android studio will restart adb and it may find your device.

Title: Android Studio - Device Offline


问:
Android. Font broken with caps letter T
Strange issue I found.
I'm using font HouschkaRoundedAltBoldRegular.otf

I've added it to my TextView like this.

```<code>Typeface myTypeface = Typeface.createFromAsset(getAssets(), "HouschkaRoundedAltBoldRegular.otf");
tutorialTextView.setTypeface(myTypeface);
</code>```

Worked fine on Android until I noticed caps letter T is broken.
It works fine in other Windows programs (Word Office).

Here are some examples how it looks on phone.

Text: "Tutorial"

Text: "TTu Tu Th Tt To Tk ToTp"

As you see, it breaks if the next letter is shorter than top line of T.

It seems that its an Font + Android bug.

What can I do in this situation?

Thanks.

Edit:
In Photoshop, if you change kerning to Optical it works.

How can I change kerning on Android? Or it will be just easier to fix the font ?

答:
For an interesting issue there is an interesting solution I found.

Just use Russian  Т <= Cyrillic  T <= Latin      ( http://translit.ru )

They look the same, but one works other doesn't. ( Spacing is a bit messed up but its the best solution I found )

Still I can't figure out if its fonts fault or Android, or both.

Title: Android. Font broken with caps letter T

Body:
Strange issue I found.
I'm using font HouschkaRoundedAltBoldRegular.otf

I've added it to my TextView like this.

Typeface myTypeface = Typeface.createFromAsset(getAssets(), "HouschkaRoundedAltBoldRegular.otf");
tutorialTextView.setTypeface(myTypeface);

Worked fine on Android until I noticed caps letter T is broken.
It works fine in other Windows programs (Word Office).

Here are some examples how it looks on phone.

Text: "Tutorial"

Text: "TTu Tu Th Tt To Tk ToTp"

As you see, it breaks if the next letter is shorter than top line of T.

It seems that its an Font + Android bug.

What can I do in this situation?

Thanks.

Edit:
In Photoshop, if you change kerning to Optical it works.

How can I change kerning on Android? Or it will be just easier to fix the font ?


问:
Reading positional parameters using PHP
I am using a .php page just like a shell script. The only problem is that I do not know how to pass the positional parameters to PHP page.

```<code>#!/usr/bin/php
<?php

$myfile="balexp.xml";
</code>```

The following does not work in this php page and does work in the shell script.

```<code>myvar=$1
</code>```

How do I pass variables to a php page?

答:
You need to make use of the array $argv.

Run the following CLI PHP passing it command line arguments:

```<code>#!/usr/bin/php
<?php
var_dump($argv);
?>
</code>```

On running:

```<code>$ chmod u+x a.php
$ ./a.php
array(1) {
  [0]=>
  string(7) "./a.php"
}

$ ./a.php foo
array(2) {
  [0]=>
  string(7) "./a.php"
  [1]=>
  string(3) "foo"
}

$
</code>```

Clearly $argv[0] contains the name of the script, $argv[1] contains the first command line argument.

The manual has all the details on how to handle command line arguments.

Title: Reading positional parameters using PHP

Body:
I am using a .php page just like a shell script. The only problem is that I do not know how to pass the positional parameters to PHP page.

#!/usr/bin/php
<?php

$myfile="balexp.xml";

The following does not work in this php page and does work in the shell script.

myvar=$1

How do I pass variables to a php page?

Body:
You need to make use of the array $argv.

Run the following CLI PHP passing it command line arguments:

#!/usr/bin/php
<?php
var_dump($argv);
?>

On running:

$ chmod u+x a.php
$ ./a.php
array(1) {
  [0]=>
  string(7) "./a.php"
}

$ ./a.php foo
array(2) {
  [0]=>
  string(7) "./a.php"
  [1]=>
  string(3) "foo"
}

$

Clearly $argv[0] contains the name of the script, $argv[1] contains the first command line argument.

The manual has all the details on how to handle command line arguments.


问:
List all spreadsheets using a Google Sheets API
I'm trying to use the Google Sheets API with PHP to list all spreadsheets in user X account whose file name matches certain pattern, for instance "company_abc_052017_en". Is this possible with Google Sheets API and PHP?

Thanks,
Z

答:
If the spreadsheets are located in your Google Drive, you can certainly fetch all spreadsheets using File.list using the queries where you search for MiMEType of type

```<code> application/vnd.google-apps.spreadsheet
</code>```

If you're doing this using Sheetsv4 API per se, there is no method to do this, unlike in Sheets v3 where it had:

```<code>GET https://spreadsheets.google.com/feeds/spreadsheets/private/full
</code>```

Body:
If the spreadsheets are located in your Google Drive, you can certainly fetch all spreadsheets using File.list using the queries where you search for MiMEType of type

 application/vnd.google-apps.spreadsheet

If you're doing this using Sheetsv4 API per se, there is no method to do this, unlike in Sheets v3 where it had:

GET https://spreadsheets.google.com/feeds/spreadsheets/private/full


问:
var in class gives error

Possible Duplicate:

  Using var outside of a method

```<code>class A {
string X;
}
// Proper
class A {
var X;
}
// Improper (gives error)
</code>```

Why is it, that i cant have var type variable declare in Class and what can be done in order to achieve it OR what is an alternative ?

In function/method, i can declare a var type variable,then why can't, i do it in class ?

Thanks.

答:
```<code>// method variable
var X;
</code>```

is never valid - even inside a method; you need immediate initialization to infer the type:

```<code>// method variable
var X = "abc"; // now a string
</code>```

As for why this isn't available for fields with a field-initializer: simply, the spec says so. Now why the spec says so is another debate... I could check the annotated spec, but my suspicion would be simply that they are more necessary for method variables, where the logic is more complex (re LINQ etc). Also, they are often used with anonymous types (that being the necessity for their existence); but anonymous types can't be exposed on a public api... so you could have the very confusing:

```<code>private var foo = new { x = 123, y = "abc"}; // valid
public var bar = new { x = 123, y = "abc"}; // invalid
</code>```

So all in all I'm happy with the current logic.

Title: var in class gives error

Body:
Possible Duplicate:

  Using var outside of a method

class A {
string X;
}
// Proper
class A {
var X;
}
// Improper (gives error)

Why is it, that i cant have var type variable declare in Class and what can be done in order to achieve it OR what is an alternative ?

In function/method, i can declare a var type variable,then why can't, i do it in class ?

Thanks.

Body:
// method variable
var X;

is never valid - even inside a method; you need immediate initialization to infer the type:

// method variable
var X = "abc"; // now a string

As for why this isn't available for fields with a field-initializer: simply, the spec says so. Now why the spec says so is another debate... I could check the annotated spec, but my suspicion would be simply that they are more necessary for method variables, where the logic is more complex (re LINQ etc). Also, they are often used with anonymous types (that being the necessity for their existence); but anonymous types can't be exposed on a public api... so you could have the very confusing:

private var foo = new { x = 123, y = "abc"}; // valid
public var bar = new { x = 123, y = "abc"}; // invalid

So all in all I'm happy with the current logic.


问:
How to get facebook friend list in ios?
I am trying this from the last two days but not getting any solution.
Please help me. i want to fetch the friend list of facebook friends, i am using this code

```<code>loginButton.readPermissions =
    @[@"public_profile", @"email", @"user_friends", @"read_custom_friendlists"];

if ([FBSDKAccessToken currentAccessToken]) {
        [[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:nil]
         startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
             if (!error) {
                 NSLog(@"fetched user:%@", result);
             }
         }];

         FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
                              initWithGraphPath:@"/me/taggable_friends"
                              parameters:@{@"fields": @"id, name"}
                              HTTPMethod:@"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
                                      id result,
                                      NSError *error) {
    NSLog(@"%@",result);
}];

    }

   but in the response i am getting :

fetched user:{
    id = 102045934964446131;
    name = "xyz zyz";
}
      id = "AaKwxUJHqY8miA_dKdOIEoDc1NDF4nTw_K4s-JKAYvFqDdyXYe_dsOyDiUuKPh285CNlc5pAvtHhD7K9PbrpfP8pZmsYwujUenNjdfrUOkrm8g";
        name = "Anshul Katiyar";
    },
            {
        id = "AaLx7VNhGwdmA0vyZjy-Ry7II2kEVeQweLp54HiJC2TU5yIN6Qkl-aT811aqm0aea6pjRy-amUTz3gEXanjuQIKvHXiu-cICJ-VXjnchyL1kug";
        name = "Madhu Verma";

    },
            {
        id = "AaLPkAwYvi6aFu8uTgLfTc0QAbS1tlSM600NF07QOezuwEibLjp8Tq2N7TFKuUrXrwsTmAY5bFhtxEg6XmcVJMZ1xLhrQiMR_hNasPsCpiPpYQ";
        name = "Manojsharma Manojsharma";
    },
            {
        id = "AaIyxf6jtQT_c05h3JdJ18pWNYwRYREKf2A5hIiz9qdp-ehXbvYkwMgTbqF4RptgiyxgdUObU8tLcKDTt2JNpPOWFrXty00OsbMqBrK_Up0Xpg";
        name = "Aarti Tripathi";
    },
            {
        id = "AaJPoNnjzzIT6ELXyl56NTpkGx7xtT5J1wf_WOsX4BD4AFvDTcAOt0sn9m51VaJhSTDwC7eUkU7Gw5hPBHyZn8YxsD9HpwgGnZzxnE7yN853jA";
        name = "Vaibhaw Singh";
    },
            {
        id = AaJE5GA9QFr7oD8KY3Gak4h5aJqrHHHh4WYWKWCvpg97V2HSDm8UjSuygfMMg08QIDPWe20qRqY4eP3R9N82AhJ9Lzg1TpjzNdDZsJoy1hWrmg;
        name = "Saurabh Verma";
    },
            {
        id = "AaKGTx-vlLOyuNExGrlcqoFpwQRMtAHqwtCeuslQfriLeN8pDyB0D_qQeIpIULSIcwVB2fGltbOkMW9Mp94AzX2Y2egxgJw0lAHRCE45DJlkIg";
        name = "Udit Katiyar Nitiya";
    }
);
paging =     {
    cursors =         {
        after = QWFMRWdjYUM1aVlpYW00U2t6Ym5oUnpqdW0tdm1xZA2RSQTc3dk16N1d3WnNEaG81Q2V1ekNTRHNCSEtjYjVPam1XbGZAVRGE0UGsxSEdxZADJZAZAkkwX3BHYlZAodGFBQmNPUmlYWTRfNUtkeVVLUmcZD;
        before = QWFJLXktdTVqeEFOR05ueHRWSWE4eWs0WE5nQVJUN0o5eC03YWVpcW10YkRObjMtNmZAXeTRXTDh5WUNrLV9tQnZAiWWdOSFNrVk8wZATl5a3ZAYWVpsRUxDVnpORG5POG1jZAlpIbm5DS0FFcHZAxb3cZD;
    };
    next = "https://graph.facebook.com/v2.9/10204593496146131/taggable_friends?access_token=EAAasBqLeUy0BAIRjZCZBlRXD4Hleg3J8712Drm5BZA6DC3bvLZCcPy6iklwPi77ymOoj888GjZBhyWdZAyI4nK1hSr2D1ZAvpTjYrc4L2cVZAVuYoeRe39mxVPczuH5GZBHHngGIoTAPv5AdnXPjsybJlt2t4fAmRFGaw8ZC1GiJHLtZCsbYEyvsKYCpGCaWJNNVOFcwUZBaKwM5xZB9DoJw7wFzL&fields=id%2C+name&limit=25&after=QWFMRWdjYUM1aVlpYW00U2t6Ym5oUnpqdW0tdm1xZA2RSQTc3dk16N1d3WnNEaG81Q2V1ekNTRHNCSEtjYjVPam1XbGZAVRGE0UGsxSEdxZADJZAZAkkwX3BHYlZAodGFBQmNPUmlYWTRfNUtkeVVLUmcZD";
};
</code>```

i am getting this output but this is not the full list of friends i want full list how to get that list.
i want to get the email, name and id of all the friends.
I have total friends of 267 but not showing any details of the friends.
 please help.

Thanks In advance

答:
Get Permissions:

```<code> NSArray *permissions = @[@"user_birthday", @"friends_hometown",
                        @"friends_birthday", @"friends_location"];
[FBSession openActiveSessionWithReadPermissions:permissions allowLoginUI:YES completionHandler: .....
NSLog(@"permissions::%@",FBSession.activeSession.permissions);
</code>```

Post FBRequest:

```<code>FBRequest *friendRequest = [FBRequest requestForGraphPath:@"me/friends?fields=name,picture,birthday,location"];
 [ friendRequest startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
    NSArray *data = [result objectForKey:@"data"];
    for (FBGraphObject<FBGraphUser> *friend in data) {
        NSLog(@"%@:%@", [friend name],[friend birthday]);
 }}];
</code>```

Also you can try requestForMyFriends on SDK 3.0 onwards. NB: It may provide Birthday information

```<code>FBRequest* friendsRequest = [FBRequest requestForMyFriends];
[friendsRequest startWithCompletionHandler: ^(FBRequestConnection *connection,
                                  NSDictionary* result,
                                  NSError *error) {
    NSArray* friends = [result objectForKey:@"data"];
    NSLog(@"Found: %lu friends", (unsigned long)friends.count);
    for (NSDictionary<FBGraphUser>* friend in friends) {
        NSLog(@"I have a friend named %@ with id %@", friend.name, friend.objectID);
    }
}];
</code>```

Title: How to get facebook friend list in ios?

Body:
I am trying this from the last two days but not getting any solution.
Please help me. i want to fetch the friend list of facebook friends, i am using this code

loginButton.readPermissions =
    @[@"public_profile", @"email", @"user_friends", @"read_custom_friendlists"];

if ([FBSDKAccessToken currentAccessToken]) {
        [[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:nil]
         startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
             if (!error) {
                 NSLog(@"fetched user:%@", result);
             }
         }];

         FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
                              initWithGraphPath:@"/me/taggable_friends"
                              parameters:@{@"fields": @"id, name"}
                              HTTPMethod:@"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
                                      id result,
                                      NSError *error) {
    NSLog(@"%@",result);
}];

    }

   but in the response i am getting :

fetched user:{
    id = 102045934964446131;
    name = "xyz zyz";
}
      id = "AaKwxUJHqY8miA_dKdOIEoDc1NDF4nTw_K4s-JKAYvFqDdyXYe_dsOyDiUuKPh285CNlc5pAvtHhD7K9PbrpfP8pZmsYwujUenNjdfrUOkrm8g";
        name = "Anshul Katiyar";
    },
            {
        id = "AaLx7VNhGwdmA0vyZjy-Ry7II2kEVeQweLp54HiJC2TU5yIN6Qkl-aT811aqm0aea6pjRy-amUTz3gEXanjuQIKvHXiu-cICJ-VXjnchyL1kug";
        name = "Madhu Verma";

    },
            {
        id = "AaLPkAwYvi6aFu8uTgLfTc0QAbS1tlSM600NF07QOezuwEibLjp8Tq2N7TFKuUrXrwsTmAY5bFhtxEg6XmcVJMZ1xLhrQiMR_hNasPsCpiPpYQ";
        name = "Manojsharma Manojsharma";
    },
            {
        id = "AaIyxf6jtQT_c05h3JdJ18pWNYwRYREKf2A5hIiz9qdp-ehXbvYkwMgTbqF4RptgiyxgdUObU8tLcKDTt2JNpPOWFrXty00OsbMqBrK_Up0Xpg";
        name = "Aarti Tripathi";
    },
            {
        id = "AaJPoNnjzzIT6ELXyl56NTpkGx7xtT5J1wf_WOsX4BD4AFvDTcAOt0sn9m51VaJhSTDwC7eUkU7Gw5hPBHyZn8YxsD9HpwgGnZzxnE7yN853jA";
        name = "Vaibhaw Singh";
    },
            {
        id = AaJE5GA9QFr7oD8KY3Gak4h5aJqrHHHh4WYWKWCvpg97V2HSDm8UjSuygfMMg08QIDPWe20qRqY4eP3R9N82AhJ9Lzg1TpjzNdDZsJoy1hWrmg;
        name = "Saurabh Verma";
    },
            {
        id = "AaKGTx-vlLOyuNExGrlcqoFpwQRMtAHqwtCeuslQfriLeN8pDyB0D_qQeIpIULSIcwVB2fGltbOkMW9Mp94AzX2Y2egxgJw0lAHRCE45DJlkIg";
        name = "Udit Katiyar Nitiya";
    }
);
paging =     {
    cursors =         {
        after = QWFMRWdjYUM1aVlpYW00U2t6Ym5oUnpqdW0tdm1xZA2RSQTc3dk16N1d3WnNEaG81Q2V1ekNTRHNCSEtjYjVPam1XbGZAVRGE0UGsxSEdxZADJZAZAkkwX3BHYlZAodGFBQmNPUmlYWTRfNUtkeVVLUmcZD;
        before = QWFJLXktdTVqeEFOR05ueHRWSWE4eWs0WE5nQVJUN0o5eC03YWVpcW10YkRObjMtNmZAXeTRXTDh5WUNrLV9tQnZAiWWdOSFNrVk8wZATl5a3ZAYWVpsRUxDVnpORG5POG1jZAlpIbm5DS0FFcHZAxb3cZD;
    };
    next = "https://graph.facebook.com/v2.9/10204593496146131/taggable_friends?access_token=EAAasBqLeUy0BAIRjZCZBlRXD4Hleg3J8712Drm5BZA6DC3bvLZCcPy6iklwPi77ymOoj888GjZBhyWdZAyI4nK1hSr2D1ZAvpTjYrc4L2cVZAVuYoeRe39mxVPczuH5GZBHHngGIoTAPv5AdnXPjsybJlt2t4fAmRFGaw8ZC1GiJHLtZCsbYEyvsKYCpGCaWJNNVOFcwUZBaKwM5xZB9DoJw7wFzL&fields=id%2C+name&limit=25&after=QWFMRWdjYUM1aVlpYW00U2t6Ym5oUnpqdW0tdm1xZA2RSQTc3dk16N1d3WnNEaG81Q2V1ekNTRHNCSEtjYjVPam1XbGZAVRGE0UGsxSEdxZADJZAZAkkwX3BHYlZAodGFBQmNPUmlYWTRfNUtkeVVLUmcZD";
};

i am getting this output but this is not the full list of friends i want full list how to get that list.
i want to get the email, name and id of all the friends.
I have total friends of 267 but not showing any details of the friends.
 please help.

Thanks In advance

Body:
Get Permissions:

 NSArray *permissions = @[@"user_birthday", @"friends_hometown",
                        @"friends_birthday", @"friends_location"];
[FBSession openActiveSessionWithReadPermissions:permissions allowLoginUI:YES completionHandler: .....
NSLog(@"permissions::%@",FBSession.activeSession.permissions);

Post FBRequest:

FBRequest *friendRequest = [FBRequest requestForGraphPath:@"me/friends?fields=name,picture,birthday,location"];
 [ friendRequest startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
    NSArray *data = [result objectForKey:@"data"];
    for (FBGraphObject<FBGraphUser> *friend in data) {
        NSLog(@"%@:%@", [friend name],[friend birthday]);
 }}];

Also you can try requestForMyFriends on SDK 3.0 onwards. NB: It may provide Birthday information

FBRequest* friendsRequest = [FBRequest requestForMyFriends];
[friendsRequest startWithCompletionHandler: ^(FBRequestConnection *connection,
                                  NSDictionary* result,
                                  NSError *error) {
    NSArray* friends = [result objectForKey:@"data"];
    NSLog(@"Found: %lu friends", (unsigned long)friends.count);
    for (NSDictionary<FBGraphUser>* friend in friends) {
        NSLog(@"I have a friend named %@ with id %@", friend.name, friend.objectID);
    }
}];