问:
Oracle NUMBER(10) columns is reported as Int64 instead of Int32
I had to come back to an exiting project (hardly two months old) for a small change. I'm getting exceptions left and right on it now but it was in working condition and deployed to production and is running. The errors are pretty strange as well: It is all Oracle datatypes being read differently now. A Number(10) di column for a row was easily read as a DataRow and saved to a POCO's respective int property. But the same code is failing now.

Original code that was working before:

```<code>public static async Task<(OracleConnection connection, OracleDataAdapter adapter)> GetOraclePackage()
{
    try
    {
        // To satisfy async. serves no purpose.
        await Task.FromResult(0);

        if (WebConfigurationManager.ConnectionStrings[Constants.ConnectionStringBilling] == null)
        {
            throw new ApplicationException("Oracle connection string is not found in web.config");
        }

        var oraConnection = new OracleConnection { ConnectionString = WebConfigurationManager.ConnectionStrings[Constants.ConnectionStringBilling].ConnectionString };
        var oraDataAdapter = new OracleDataAdapter { SelectCommand = new OracleCommand { CommandType = CommandType.Text, Connection = oraConnection } };

        return (oraConnection, oraDataAdapter);
    }
    catch (OracleException oraExp)
    {
        throw new RepositoryLayerException("Oracle error in repository's helper method GetOraclePackage() " + oraExp.Message, oraExp);
    }
    catch (Exception e)
    {
        throw new RepositoryLayerException("Error in repository's helper method GetOraclePackage() " + e.Message, e);
    }
}

public async Task<IList<BDO.AirportServiceWithTerminal>> GetAllServices()
{
    var objResult = new List<BDO.AirportServiceWithTerminal>();
    var oraclePackage = await Helper.GetOraclePackage();
    var ds = new DataSet();

    try
    {
        var sql = @"
                SELECT
                    s.service_code,
                    s.account_code,
                    s.service_fees,
                    s.customer_type,
                    s.period,
                    s.ser_name_e,
                    s.isvat,
                    s.vatvalue
                FROM
                    serviceinfo s
                WHERE
                        sevice_status = '1'
                    AND
                        service_fees > 1
                    AND
                        account_code IN (
                            'AB','BC','CD','DE'
                        )
                ";

        oraclePackage.connection.Open();
        oraclePackage.adapter.SelectCommand.CommandText = sql;
        oraclePackage.adapter.Fill(ds, "ServiceList");

        if (ds.Tables[0] != null)
        {
            foreach (DataRow oneService in ds.Tables[0].Rows)
            {
                var newTerminalService = new BDO.AirportServiceWithTerminal
                {
                    Code = oneService.Field<int>("service_code"),
                    NameEnglish = oneService.Field<string>("ser_name_e").Replace(@"""", "").Trim(),
                    Fee = oneService.Field<decimal>("service_fees"),
                    IsVat = oneService.Field<string>("isvat") == "1",
                    VatValue = int.Parse(oneService.Field<string>("vatvalue"))
                };

                objResult.Add(newTerminalService);
            }
        }
    }
    catch (Exception exp)
    {
        throw new RepositoryLayerException("An error occurred while retrieving all services from billing system", exp);
    }
    finally
    {
        oraclePackage.adapter.Dispose();
        if (oraclePackage.connection.State == ConnectionState.Open) oraclePackage.connection.Close();
        oraclePackage.connection.Dispose();
    }

    return objResult;
}
</code>```

And now, when it tries to cast the service_code to int, it fails. I tried to get the type of service_code as follows:

oneService["service_code"].GetType()

and I either get UnderlyingSystemType: {Name = "Int64" FullName = "System.Int64"} or UnderlyingSystemType: {Name = "Decimal" FullName = "System.Decimal"}

(Whe writing this SO question, I started to get Decimal)

Is there a way around this by doing some cast as I know the database has not been changed and I cannot just accept the new types as there are many. Same case is for decimals now reported as doubles.

答:
In general case Oracle's Number(10) doesn't fit int (Int32) since Number(10) has a wider range:

```<code>  Type        Min Value     Max Value
  ------------------------------------
  Number(10) -9999999999 .. 9999999999
      Int32  -2147483648 .. 2147483647
</code>```

That's why, say, 9876543210 can be represented as Number(10) but not as int (and this is the very reason for .Net to map Number(10) to Int64). If values in the database are guaranteed to be small enough (and thus in fact fit int), try using Convert:

```<code>  Code = Convert.ToInt32(oneService.Field<object>("service_code"));
  ...
  VatValue = Convert.ToInt32(oneService.Field<object>("vatvalue"));
</code>```

Body:
I had to come back to an exiting project (hardly two months old) for a small change. I'm getting exceptions left and right on it now but it was in working condition and deployed to production and is running. The errors are pretty strange as well: It is all Oracle datatypes being read differently now. A Number(10) di column for a row was easily read as a DataRow and saved to a POCO's respective int property. But the same code is failing now.

Original code that was working before:

public static async Task<(OracleConnection connection, OracleDataAdapter adapter)> GetOraclePackage()
{
    try
    {
        // To satisfy async. serves no purpose.
        await Task.FromResult(0);

        if (WebConfigurationManager.ConnectionStrings[Constants.ConnectionStringBilling] == null)
        {
            throw new ApplicationException("Oracle connection string is not found in web.config");
        }

        var oraConnection = new OracleConnection { ConnectionString = WebConfigurationManager.ConnectionStrings[Constants.ConnectionStringBilling].ConnectionString };
        var oraDataAdapter = new OracleDataAdapter { SelectCommand = new OracleCommand { CommandType = CommandType.Text, Connection = oraConnection } };

        return (oraConnection, oraDataAdapter);
    }
    catch (OracleException oraExp)
    {
        throw new RepositoryLayerException("Oracle error in repository's helper method GetOraclePackage() " + oraExp.Message, oraExp);
    }
    catch (Exception e)
    {
        throw new RepositoryLayerException("Error in repository's helper method GetOraclePackage() " + e.Message, e);
    }
}

public async Task<IList<BDO.AirportServiceWithTerminal>> GetAllServices()
{
    var objResult = new List<BDO.AirportServiceWithTerminal>();
    var oraclePackage = await Helper.GetOraclePackage();
    var ds = new DataSet();

    try
    {
        var sql = @"
                SELECT
                    s.service_code,
                    s.account_code,
                    s.service_fees,
                    s.customer_type,
                    s.period,
                    s.ser_name_e,
                    s.isvat,
                    s.vatvalue
                FROM
                    serviceinfo s
                WHERE
                        sevice_status = '1'
                    AND
                        service_fees > 1
                    AND
                        account_code IN (
                            'AB','BC','CD','DE'
                        )
                ";

        oraclePackage.connection.Open();
        oraclePackage.adapter.SelectCommand.CommandText = sql;
        oraclePackage.adapter.Fill(ds, "ServiceList");

        if (ds.Tables[0] != null)
        {
            foreach (DataRow oneService in ds.Tables[0].Rows)
            {
                var newTerminalService = new BDO.AirportServiceWithTerminal
                {
                    Code = oneService.Field<int>("service_code"),
                    NameEnglish = oneService.Field<string>("ser_name_e").Replace(@"""", "").Trim(),
                    Fee = oneService.Field<decimal>("service_fees"),
                    IsVat = oneService.Field<string>("isvat") == "1",
                    VatValue = int.Parse(oneService.Field<string>("vatvalue"))
                };

                objResult.Add(newTerminalService);
            }
        }
    }
    catch (Exception exp)
    {
        throw new RepositoryLayerException("An error occurred while retrieving all services from billing system", exp);
    }
    finally
    {
        oraclePackage.adapter.Dispose();
        if (oraclePackage.connection.State == ConnectionState.Open) oraclePackage.connection.Close();
        oraclePackage.connection.Dispose();
    }

    return objResult;
}

And now, when it tries to cast the service_code to int, it fails. I tried to get the type of service_code as follows:

oneService["service_code"].GetType()

and I either get UnderlyingSystemType: {Name = "Int64" FullName = "System.Int64"} or UnderlyingSystemType: {Name = "Decimal" FullName = "System.Decimal"}

(Whe writing this SO question, I started to get Decimal)

Is there a way around this by doing some cast as I know the database has not been changed and I cannot just accept the new types as there are many. Same case is for decimals now reported as doubles.

Body:
In general case Oracle's Number(10) doesn't fit int (Int32) since Number(10) has a wider range:

  Type        Min Value     Max Value
  ------------------------------------
  Number(10) -9999999999 .. 9999999999
      Int32  -2147483648 .. 2147483647

That's why, say, 9876543210 can be represented as Number(10) but not as int (and this is the very reason for .Net to map Number(10) to Int64). If values in the database are guaranteed to be small enough (and thus in fact fit int), try using Convert:

  Code = Convert.ToInt32(oneService.Field<object>("service_code"));
  ...
  VatValue = Convert.ToInt32(oneService.Field<object>("vatvalue"));


来源: stackexchange

问:
How to access a method from another class without using extends keyword?
I have a main class followed by two sub classes.

As below

```<code>public class Guitar  {

   public static void main(String argd[]) {
       Artist output = new Artist();
       output.perfomance();
   }
}

  class Artist  {
    String Name;
    void perfomance () {

    }

  }

  class Album {

  }
</code>```

Is it possible to call method performance from Artist class and use it in Album class without extends keyword?

答:
Method 1: Use composition

Pass Artist object from constractor

```<code>class Album {
  Artist artist;

  Album(Artist artist) {
    this.artist = artist;
  }

  void doSothing() {
    artist.performance();
  }
}
</code>```

Set Artist object with set Method

```<code>class Album {
      Artist artist;
      void setArtist(Artist artist){
         this.artist = artist;
       }
      void doSothing(Artist artist) {
        artist.performance();
      }
    }
</code>```

Pass Artist object from method

```<code>class Album {
      Artist artist;

      void doSothing(Artist artist) {
        artist.performance();
      }
    }
</code>```

Method 2: Make function perfomance  static

```<code> public class Artist  {
    String Name;
    static void perfomance () {
    }
  }
  class Album {
   void doSothing() {
     Artist.performance();
   }
  }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a main class followed by two sub classes.

As below

public class Guitar  {

   public static void main(String argd[]) {
       Artist output = new Artist();
       output.perfomance();
   }
}

  class Artist  {
    String Name;
    void perfomance () {

    }

  }

  class Album {

  }

Is it possible to call method performance from Artist class and use it in Album class without extends keyword?

Body:
Method 1: Use composition

Pass Artist object from constractor

class Album {
  Artist artist;

  Album(Artist artist) {
    this.artist = artist;
  }

  void doSothing() {
    artist.performance();
  }
}

Set Artist object with set Method

class Album {
      Artist artist;
      void setArtist(Artist artist){
         this.artist = artist;
       }
      void doSothing(Artist artist) {
        artist.performance();
      }
    }

Pass Artist object from method

class Album {
      Artist artist;

      void doSothing(Artist artist) {
        artist.performance();
      }
    }

Method 2: Make function perfomance  static

 public class Artist  {
    String Name;
    static void perfomance () {
    }
  }
  class Album {
   void doSothing() {
     Artist.performance();
   }
  }


问:
.htaccess; redirect all https:// to http:// expect of two domains
I have this code to redirect all https:// to http://:

```<code>RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</code>```

But how can I exclude two domains www.example.com and www.test.com from this rule?

答:
You can use a negative RewriteCond:

```<code>RewriteEngine On

RewriteCond %{HTTP_HOST} !^(?:www\.)?(?:test|example)\.com$ [NC]
RewriteCond %{HTTPS} on
RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]
</code>```

Make sure to clear your browser cache before testing this change.

Body:
I have this code to redirect all https:// to http://:

RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

But how can I exclude two domains www.example.com and www.test.com from this rule?

Body:
You can use a negative RewriteCond:

RewriteEngine On

RewriteCond %{HTTP_HOST} !^(?:www\.)?(?:test|example)\.com$ [NC]
RewriteCond %{HTTPS} on
RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]

Make sure to clear your browser cache before testing this change.


问:
query total reduced by percent
Hey guys I have some query problem. I want to reduced my total with percentage but this code give me some error:

```<code>SELECT `id_sewa`,`nama_villa`,DATE_FORMAT(`tgl_transaksi`, '%d-%m-%Y'),`nama_tamu`,`cek_in`,`cek_out`, datediff(`cek_out`,`cek_in`) as rn,format(`harga`, 0),format(datediff(`cek_out`,`cek_in`) *`harga`, 0)as total,`ref`,
(
CASE
WHEN ref = "direct" THEN format(datediff(`cek_out`,`cek_in`) * `harga`, 0) - 10%
END) AS total_bersih

from sewa_villa
where tgl_transaksi BETWEEN '2017-11-12' and '2017-11-14';
</code>```

My expectation:

total
ref
total bersih

2,000,000
direct
1,800,000

```
</div>
</div>
</p>

<p>This the error:</p>

```1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ') AS total_bersih
from sewa_villa where tgl_transaksi BETWEEN '2017-11-12' and ' at line 6
```

答:
You can't use percentage calculation on MySQL directly (using something like - 10%)! You have to replace - 10% with * 0.9 as I already mentioned in the comments:

```<code>SELECT
    `id_sewa`,
    `nama_villa`,
   DATE_FORMAT(`tgl_transaksi`, '%d-%m-%Y'),
   `nama_tamu`,
   `cek_in`,
   `cek_out`,
   DATEDIFF(`cek_out`,`cek_in`) AS rn,
   FORMAT(`harga`, 0),
   FORMAT(DATEDIFF(`cek_out`,`cek_in`) * `harga`, 0) AS total,
   `ref`, (
       CASE
           WHEN ref = "direct" THEN FORMAT(DATEDIFF(`cek_out`, `cek_in`) * `harga`, 0) * 0.9
       END) AS total_bersih
FROM sewa_villa
WHERE tgl_transaksi BETWEEN '2017-11-12' AND '2017-11-14';
</code>```

The % can be used as following:

wildcard operator (col_name LIKE '%test%')

on a modulo operation (col_name % 5).

In your case: MySQL try to calculate a modulo operation but the number after the % is missing. This is the reason why MySQL throws an error.

Title: query total reduced by percent

Body:
Hey guys I have some query problem. I want to reduced my total with percentage but this code give me some error:

SELECT `id_sewa`,`nama_villa`,DATE_FORMAT(`tgl_transaksi`, '%d-%m-%Y'),`nama_tamu`,`cek_in`,`cek_out`, datediff(`cek_out`,`cek_in`) as rn,format(`harga`, 0),format(datediff(`cek_out`,`cek_in`) *`harga`, 0)as total,`ref`,
(
CASE
WHEN ref = "direct" THEN format(datediff(`cek_out`,`cek_in`) * `harga`, 0) - 10%
END) AS total_bersih

from sewa_villa
where tgl_transaksi BETWEEN '2017-11-12' and '2017-11-14';

My expectation:

total
ref
total bersih

2,000,000
direct
1,800,000

This the error:

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ') AS total_bersih
from sewa_villa where tgl_transaksi BETWEEN '2017-11-12' and ' at line 6

Body:
You can't use percentage calculation on MySQL directly (using something like - 10%)! You have to replace - 10% with * 0.9 as I already mentioned in the comments:

SELECT
    `id_sewa`,
    `nama_villa`,
   DATE_FORMAT(`tgl_transaksi`, '%d-%m-%Y'),
   `nama_tamu`,
   `cek_in`,
   `cek_out`,
   DATEDIFF(`cek_out`,`cek_in`) AS rn,
   FORMAT(`harga`, 0),
   FORMAT(DATEDIFF(`cek_out`,`cek_in`) * `harga`, 0) AS total,
   `ref`, (
       CASE
           WHEN ref = "direct" THEN FORMAT(DATEDIFF(`cek_out`, `cek_in`) * `harga`, 0) * 0.9
       END) AS total_bersih
FROM sewa_villa
WHERE tgl_transaksi BETWEEN '2017-11-12' AND '2017-11-14';

The % can be used as following:

wildcard operator (col_name LIKE '%test%')

on a modulo operation (col_name % 5).

In your case: MySQL try to calculate a modulo operation but the number after the % is missing. This is the reason why MySQL throws an error.


问:
Difference between returning a value and returning Promise.resolve() from a function
I have problem in understanding that what happens when we simply return a value or when we return Promise.resolve() from a function. Specifically: I am trying to understand how promises chaining works. I am chaining methods and verifying whether the value reaches in the method which is last call to then. I just want to understand the difference between returning promises to then, returning Promise.resolve() to then, and returning just a value to then.

答:
I have problem in understanding that what happens when we simply return a value or when we return Promise.resolve() from a function.

So there are (at least) two different scenarios:

In just any old function

If it's just any old function (not a then or catch callback), then the difference is that return value; directly returns the value, whereas return Promise.resolve(value); returns a promise fulfilled with that value. It changes how the calling code uses the result. In the return value; case, the calling code just directly uses it. In the return Promise.resolve(value); case, the calling code needs to consume the promise, just like any other promise (and can't assume that the promise is already settled, even though it is).

If the function is meant to be the start of a promise chain, you'd use return Promise.resolve(value);. (There are use cases for this; for instance, if the function may or may not need to start an asynchronous process: In the branch that doesn't have to, you'd still return a promise because the branch that has to do something asynchronous has to return a promise.) If it isn't, you'd just use return value;.

In then or catch callback

I am trying to understand how promises chaining works.

In that case, you're talking about return value; vs. return Promise.resolve(value); in a then or catch callback. That's easy: There's no point at all to return Promise.resolve(value); in a then or catch callback, it's redundant and unnecessary overhead; just use return value;.

then and catch always return promises. If your callback returns a simple value (return value;), the promise is fulfilled with that value. If your callback returns a thenable (loosely, a promise; e.g., return Promise.resolve(value);), then the promise returned by then/catch is resolved to that thenable: When the thenable is settled, the promise is settled the same way. (And if your then or catch callback throws an error, the promise is rejected with that error.)

There are valid reasons to return a promise from a then or catch callback, if you're starting a new asynchronous process in that callback; but if you have an immediate value ready, there's no point in wrapping it in a promise — then and catch already do that.

ContentLicense: CC BY-SA 4.0


问:
Change button color all edittext fields filled?
I have button and text fields like below in my layout file

```<code><EditText
        android:id="@+id/et_password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView4"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/btn_app_signup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/et_password"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="63dp"
        android:background="@drawable/button"
        android:text="SIGN UP"
        android:textColor="@color/white" />
</code>```

How can I change this background into @drawable/button_success to if all edit text fields filled my Activity class like below

```<code>@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signup);
        btn_app_signup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String name = et_name.getText().toString();
                String email = et_email.getText().toString();
                String password = et_password.getText().toString();

                registerAccount(name, email, password);
            }
        });
    }

    private void registerAccount(String name, String email, String password) {

        if(TextUtils.isEmpty(name) || TextUtils.isEmpty(email) || TextUtils.isEmpty(password)) {
            Toast.makeText(SignupActivity.this, "All fields required", Toast.LENGTH_LONG).show();
        }
        else {

            //save data in datbase
        }
    }
</code>```

How can I do that if I fill all my edit text fields fill change the button button background

答:
You can simply change background with drawable like this:

```<code>btn_app_signup.setBackground(getResources().getDrawable(R.drawable.button_success));
</code>```

When you check your texts:

```<code>if(et_name.getText().toString().equals("") || et_email.getText().toString().equals("") || et_password.getText().toString().equals("")) {
    Toast.makeText(SignupActivity.this, "All fields required", Toast.LENGTH_LONG).show();
}
</code>```

Hope it helps.

Body:
I have button and text fields like below in my layout file

<EditText
        android:id="@+id/et_password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView4"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/btn_app_signup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/et_password"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="63dp"
        android:background="@drawable/button"
        android:text="SIGN UP"
        android:textColor="@color/white" />

How can I change this background into @drawable/button_success to if all edit text fields filled my Activity class like below

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signup);
        btn_app_signup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String name = et_name.getText().toString();
                String email = et_email.getText().toString();
                String password = et_password.getText().toString();

                registerAccount(name, email, password);
            }
        });
    }

    private void registerAccount(String name, String email, String password) {

        if(TextUtils.isEmpty(name) || TextUtils.isEmpty(email) || TextUtils.isEmpty(password)) {
            Toast.makeText(SignupActivity.this, "All fields required", Toast.LENGTH_LONG).show();
        }
        else {

            //save data in datbase
        }
    }

How can I do that if I fill all my edit text fields fill change the button button background

Body:
You can simply change background with drawable like this:

btn_app_signup.setBackground(getResources().getDrawable(R.drawable.button_success));

When you check your texts:

if(et_name.getText().toString().equals("") || et_email.getText().toString().equals("") || et_password.getText().toString().equals("")) {
    Toast.makeText(SignupActivity.this, "All fields required", Toast.LENGTH_LONG).show();
}

Hope it helps.


问:
Debugging Windows Phone 7 device traffic with Fiddler
I followed all the steps from the article but when I try to hit the server from my windows phone it says there is a dns error.

Article for reference.
http://blogs.msdn.com/b/fiddler/archive/2011/01/09/debugging-windows-phone-7-device-traffic-with-fiddler.aspx

How do I know my windows phone is using my local LAN WIFI as opposed to ATT cellular?

答:
Personally, I use Netmon 2.3 for network traffic information from WP7. Fiddler didn't support WP7 up until recently and Netmon/Wireshark did, so I just stick with those.

Using Netmon 2.3, while your device is connected to Zune/WPConnect, you'd be able to see all WP7 device transport on the ZuneComm process. Netmon isn't as user-friendly as Fiddler, but it's fairly darn specific and easy.

ContentLicense: CC BY-SA 2.5


问:
Javascript show/hide, show first div on page load
Can you help me to make the first div show on page load?

function showStuff(element)  {
    var tabContents = document.getElementsByClassName('tabContent');
    for (var i = 0; i < tabContents.length; i++) {
        tabContents[i].style.display = 'none';
    }

    var tabContentIdToShow = element.id.replace(/(\d)/g, '-$1');
    document.getElementById(tabContentIdToShow).style.display = 'block';
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.tabContent {
    display:none;
}</code>```

CARATTERISTICHE

DESTINATARI

 CALENDARIO

tab 1

tab 2 tab 2

tab 3 tab 3 tab 3

```

This is my actual code. jsFiddle
Thanks!

答:
You could try running a function when the document is ready.

```<code>$(document).ready(function () {
    showTab("tabs-1");

function showTab(divId) {
    //Get the element
    var divElement= document.getElementbyId(divId);
    //Set the css property  "display" from "none" to be "block";
    divElement..style.display = "block";
}
}):
</code>```

The function should run once the page has fully loaded.
Let me know how it goes.

Body:
Can you help me to make the first div show on page load?

function showStuff(element)  {
    var tabContents = document.getElementsByClassName('tabContent');
    for (var i = 0; i < tabContents.length; i++) {
        tabContents[i].style.display = 'none';
    }

    var tabContentIdToShow = element.id.replace(/(\d)/g, '-$1');
    document.getElementById(tabContentIdToShow).style.display = 'block';
}

.tabContent {
    display:none;
}

CARATTERISTICHE

DESTINATARI

 CALENDARIO

tab 1

tab 2 tab 2

tab 3 tab 3 tab 3

This is my actual code. jsFiddle
Thanks!

Body:
You could try running a function when the document is ready.

$(document).ready(function () {
    showTab("tabs-1");

function showTab(divId) {
    //Get the element
    var divElement= document.getElementbyId(divId);
    //Set the css property  "display" from "none" to be "block";
    divElement..style.display = "block";
}
}):

The function should run once the page has fully loaded.
Let me know how it goes.


问:
How Spark shuffle operation works?
I'm learning Spark for my project and I'm in stuck with shuffle process in Spark. I want to know how this operation works internal. I found some keywords involved in this operation: ShuffleMapStage, ShuffleMapTask, ShuffledRDD, Shuffle Write, Shuffle Read....

My questions are:

```<code>1) Why we need ShuffleMapStage? When this stage is created and how it works?
2) When ShuffledRDD's compute method is called?
3) What are Shuffle Read and Shuffle Write?
</code>```

答:
The suffle operation consist to distribute coherent data on workers (repartition) using hash function on data key (data localilty problem).

This operation involves data transfert to organise data before perform an action, reduce the number of suffle operation increase the performance.

Shuffle operation are automatically called by Spark between 2 transformation to execute a final action.

Some Spark transformation need shuffle (like Group by, Join, sort)

Some Spark transformation doesn't need shuffle (like Union, Map, Reduce, Filter, count)

Title: How Spark shuffle operation works?

Body:
I'm learning Spark for my project and I'm in stuck with shuffle process in Spark. I want to know how this operation works internal. I found some keywords involved in this operation: ShuffleMapStage, ShuffleMapTask, ShuffledRDD, Shuffle Write, Shuffle Read....

My questions are:

1) Why we need ShuffleMapStage? When this stage is created and how it works?
2) When ShuffledRDD's compute method is called?
3) What are Shuffle Read and Shuffle Write?


问:
Angular 4 hide button
When i click the 1st button how i can show 2nd button and hide 1st button, and want to click 2nd button and then show 1st button and hide 2nd button</p>

```<code><button class="btn" type="button" name="button" (click)="follow()">follow</button>
<button class="btn" type="button" name="button" (click)="followed()">followed</button>
</code>```

答:
Try this

```<code><button class="btn" type="button" [disabled]="!disableBtn" name="button" (click)="follow()">follow</button>
<button class="btn" type="button" [disabled]="disableBtn" name="button" (click)="follow()">followed</button>
</code>```

In component

```<code>export class AppComponent {
  disableBtn : boolean;
  follow(){
      this.disableBtn = !this.disableBtn;
  }
}
</code>```

Here is the working plnker

Title: Angular 4 hide button

Body:
When i click the 1st button how i can show 2nd button and hide 1st button, and want to click 2nd button and then show 1st button and hide 2nd button

<button class="btn" type="button" name="button" (click)="follow()">follow</button>
<button class="btn" type="button" name="button" (click)="followed()">followed</button>

Body:
Try this

<button class="btn" type="button" [disabled]="!disableBtn" name="button" (click)="follow()">follow</button>
<button class="btn" type="button" [disabled]="disableBtn" name="button" (click)="follow()">followed</button>

In component

export class AppComponent {
  disableBtn : boolean;
  follow(){
      this.disableBtn = !this.disableBtn;
  }
}

Here is the working plnker


答:
You need to include two Rewrite Conditions:

```<code>RewriteCond %{HTTP_HOST} !^www\.example\.com%{REQUEST_URI} [NC,OR]
RewriteCond %{HTTP_HOST} !^www\.test\.com%{REQUEST_URI} [NC]
</code>```

This will excluded both of those domains as well as any directories within the domain and keep them as HTTPs. So your code should now look like:

```<code>RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} !^www\.example\.com%{REQUEST_URI} [NC,OR]
RewriteCond %{HTTP_HOST} !^www\.test\.com%{REQUEST_URI} [NC]
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</code>```

Make sure you clear your cache before testing this.

Title: .htaccess; redirect all https:// to http:// expect of two domains

Body:
You need to include two Rewrite Conditions:

RewriteCond %{HTTP_HOST} !^www\.example\.com%{REQUEST_URI} [NC,OR]
RewriteCond %{HTTP_HOST} !^www\.test\.com%{REQUEST_URI} [NC]

This will excluded both of those domains as well as any directories within the domain and keep them as HTTPs. So your code should now look like:

RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} !^www\.example\.com%{REQUEST_URI} [NC,OR]
RewriteCond %{HTTP_HOST} !^www\.test\.com%{REQUEST_URI} [NC]
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Make sure you clear your cache before testing this.


问:
Django: sqlite3.OperationalError: no such table in python shell
I'm following a django blog tutorial. When I used python manage.py shell and tried following commands in shell

```<code>from mainsite.models import Category, Tag
c = Category(name='category test')
c.save()
</code>```

this error occured:

```<code>sqlite3.OperationalError: no such table: mainsite_category
</code>```

This is my model.py in mainsite folder, which I think is correct:

```<code>from django.db import models
from django.contrib.auth.models import User
class Category(models.Model):
    name = models.CharField(max_length=100)

def __str__(self):
    return self.name
</code>```

I have tried manage.py makemigrations, manage.py migrate and can successfully use manage.py runserver to see the website. So what is wrong here?

Edit: this is my INSTALLED APP in settings.py

```<code>INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mainsite',
]
</code>```

And my project structure

```<code>|____djangoBlog
| |______init__.py
| |____settings.py
| |____urls.py
| |____wsgi.py
|____mainsite
| |______init__.py
| |____admin.py
| |____apps.py
| |____models.py
| |____tests.py
| |____urls.py
| |____views.py
|____manage.py
|____README.md
|____requirements.txt
|____templates
| |____blog
| | |____index.html
</code>```

Edit: When I run python manage.py makemigrations and python manage.py migrate, the output is as follows:

```<code>No changes detected

Operations to perform:
    Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
    No migrations to apply.
</code>```

答:
UPD:

Since your project structure is lack of migrations folder in mainsite app, it means that you haven't created migrations for that app. Run python manage.py makemigrations mainsite and then python manage.py migrate.

From docs:

To add migrations to an app that doesn’t have a migrations directory, run makemigrations with the app’s app_label.

And yes, you can create model with simple instance creation. From docs Creating objects.

Original answer:

You need to be sure that you've included your 'mainsite' app in INSTALLED_APPS in settings.py and then run migrations. After that you should be able to do the following:

```<code>c = Category.objects.create(name='category test')
c.save()
</code>```

Body:
I'm following a django blog tutorial. When I used python manage.py shell and tried following commands in shell

from mainsite.models import Category, Tag
c = Category(name='category test')
c.save()

this error occured:

sqlite3.OperationalError: no such table: mainsite_category

This is my model.py in mainsite folder, which I think is correct:

from django.db import models
from django.contrib.auth.models import User
class Category(models.Model):
    name = models.CharField(max_length=100)

def __str__(self):
    return self.name

I have tried manage.py makemigrations, manage.py migrate and can successfully use manage.py runserver to see the website. So what is wrong here?

Edit: this is my INSTALLED APP in settings.py

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mainsite',
]

And my project structure

|____djangoBlog
| |______init__.py
| |____settings.py
| |____urls.py
| |____wsgi.py
|____mainsite
| |______init__.py
| |____admin.py
| |____apps.py
| |____models.py
| |____tests.py
| |____urls.py
| |____views.py
|____manage.py
|____README.md
|____requirements.txt
|____templates
| |____blog
| | |____index.html

Edit: When I run python manage.py makemigrations and python manage.py migrate, the output is as follows:

No changes detected

Operations to perform:
    Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
    No migrations to apply.

Body:
UPD:

Since your project structure is lack of migrations folder in mainsite app, it means that you haven't created migrations for that app. Run python manage.py makemigrations mainsite and then python manage.py migrate.

From docs:

To add migrations to an app that doesn’t have a migrations directory, run makemigrations with the app’s app_label.

And yes, you can create model with simple instance creation. From docs Creating objects.

Original answer:

You need to be sure that you've included your 'mainsite' app in INSTALLED_APPS in settings.py and then run migrations. After that you should be able to do the following:

c = Category.objects.create(name='category test')
c.save()


问:
Making 2D Property Lines Follow Topography in Revit and Instantiating Hosted Family on It
Hi I’ve watched MARCELLO SGAMBELLURI video on making properties lines that follow topography [Link]. The tutorial is great, author explained it very well. However, I’m struggling on instantiating hosted families on top of topography. In my case, the hosted families got instantiated below the topography.

Here’s my dynamo code.

Here's is the output of code in Revit 2017.

See the non-hosted family got instantiated below the topography. I'm wondering is there any way to instantiate the hosted family on top of topography. I am newbiew to dynamo, would appreciate if someone explain how do I instantiate the hosted families on top of topography. Thank you.

答: This can be achieved using the dynamic model updater functionality. Here is a discussion of using an updater in conjunction with the Idling event including two short videos showing examples making use of it.


问:
Python phpserialize unexpected behaviour
Whilst trying to do a natas challange online, I wanted to convert the php code into python, but I do not get the expected result. Might be that I'm missing something from phpserialize

Why is it giving a different output?

Python code

```<code>import base64
from phpserialize import serialize

payload = {'initMsg': "", 'exitMsg': "<?php include('/etc/natas_webpass/natas27');?>", 'logFile': "img/code.php"}
new_ser = base64.encodestring(serialize(payload))
print(new_ser)
</code>```

PHP code

```<code><?php
class Logger{
        private $logFile;
        private $initMsg;
        private $exitMsg;

        function __construct(){
            $this->initMsg = "";
            $this->exitMsg = "<?php include('/etc/natas_webpass/natas27');?>";
            $this->logFile = "img/code.php";
        }
    }

$obj = new Logger();
echo base64_encode(serialize($obj));
?>
</code>```

The PHP code yields: Tzo2OiJMb2dnZXIiOjM6e3M6MTU6IgBMb2dnZXIAbG9nRmlsZSI7czoxMjoiaW1nL2NvZGUucGhwIjtzOjE1OiIATG9nZ2VyAGluaXRNc2ciO3M6MDoiIjtzOjE1OiIATG9nZ2VyAGV4aXRNc2ciO3M6NDY6Ijw/cGhwIGluY2x1ZGUoJy9ldGMvbmF0YXNfd2VicGFzcy9uYXRhczI3Jyk7Pz4iO30=

The python code yields:

```<code>b'YTozOntzOjc6ImluaXRNc2ciO3M6MDoiIjtzOjc6ImV4aXRNc2ciO3M6NDY6Ijw/cGhwIGluY2x1\nZGUoJy9ldGMvbmF0YXNfd2VicGFzcy9uYXRhczI3Jyk7Pz4iO3M6NzoibG9nRmlsZSI7czoxMjoi\naW1nL2NvZGUucGhwIjt9\n'
</code>```

答:
You are serializing a hash in the python version, and an object in the PHP one.Just turn the object into a hash (associative array), and it should yield the same result:</p>

```<code><?php
$obj = array();
$obj['initMsg'] = '';
$obj['exitMsg'] = "<?php include('/etc/natas_webpass/natas27');?>";
$obj['logFile'] = "img/code.php";
echo base64_encode(serialize($obj));
?>
</code>```

Body:
Whilst trying to do a natas challange online, I wanted to convert the php code into python, but I do not get the expected result. Might be that I'm missing something from phpserialize

Why is it giving a different output?

Python code

import base64
from phpserialize import serialize

payload = {'initMsg': "", 'exitMsg': "<?php include('/etc/natas_webpass/natas27');?>", 'logFile': "img/code.php"}
new_ser = base64.encodestring(serialize(payload))
print(new_ser)

PHP code

<?php
class Logger{
        private $logFile;
        private $initMsg;
        private $exitMsg;

        function __construct(){
            $this->initMsg = "";
            $this->exitMsg = "<?php include('/etc/natas_webpass/natas27');?>";
            $this->logFile = "img/code.php";
        }
    }

$obj = new Logger();
echo base64_encode(serialize($obj));
?>

The PHP code yields: Tzo2OiJMb2dnZXIiOjM6e3M6MTU6IgBMb2dnZXIAbG9nRmlsZSI7czoxMjoiaW1nL2NvZGUucGhwIjtzOjE1OiIATG9nZ2VyAGluaXRNc2ciO3M6MDoiIjtzOjE1OiIATG9nZ2VyAGV4aXRNc2ciO3M6NDY6Ijw/cGhwIGluY2x1ZGUoJy9ldGMvbmF0YXNfd2VicGFzcy9uYXRhczI3Jyk7Pz4iO30=

The python code yields:

b'YTozOntzOjc6ImluaXRNc2ciO3M6MDoiIjtzOjc6ImV4aXRNc2ciO3M6NDY6Ijw/cGhwIGluY2x1\nZGUoJy9ldGMvbmF0YXNfd2VicGFzcy9uYXRhczI3Jyk7Pz4iO3M6NzoibG9nRmlsZSI7czoxMjoi\naW1nL2NvZGUucGhwIjt9\n'

Body:
You are serializing a hash in the python version, and an object in the PHP one.Just turn the object into a hash (associative array), and it should yield the same result:

<?php
$obj = array();
$obj['initMsg'] = '';
$obj['exitMsg'] = "<?php include('/etc/natas_webpass/natas27');?>";
$obj['logFile'] = "img/code.php";
echo base64_encode(serialize($obj));
?>


问:
How to read
 tags from database to angularJS view
I would like to convert br that is saved from the database to newline on my front-end.
Here's what I got so far:

```<code><div ng-repeat="desc in items.description.split(',')"><span class="pre-break">{{desc}}</span></div>
</code>```

CSS:

```<code>.pre-break{
     white-space: pre-wrap !important;
}
</code>```

Sample data from Database:

```<code>6 pcs <br/> 2 pc thigh, 2 pc wing, 2 pc chops
</code>```

But the result is still like this:

```<code>6 pcs <br/> 2 pc thigh | 2 pc wing | 2 pc chops
</code>```

What will I do to convert the br tag?

答:
You can use ng-bind-html like

```<code><div ng-repeat="desc in items.description.split(',')">
    <span class="pre-break">
        <p ng-bind-html="desc"></p>
    </span>
</div>
</code>```

Title: How to read <br> tags from database to angularJS view

Body:
I would like to convert br that is saved from the database to newline on my front-end.
Here's what I got so far:

{{desc}}

CSS:

.pre-break{
     white-space: pre-wrap !important;
}

Sample data from Database:

6 pcs
 2 pc thigh, 2 pc wing, 2 pc chops

But the result is still like this:

6 pcs
 2 pc thigh | 2 pc wing | 2 pc chops

What will I do to convert the br tag?

Body:
You can use ng-bind-html like

<div ng-repeat="desc in items.description.split(',')">
    <span class="pre-break">
        <p ng-bind-html="desc"></p>
    </span>
</div>


问:
Using interface realization thru generic class
I try to use a interface realization through a generic class. Wondering on some abstraction magic, but get compiler errors with this approach.

```<code>cannot convert from 'GClass<PosClass>' to 'GClass<IPos>'
</code>```

Here a simplified example:

//Very simple generic with only data access, no internal manipulation
class GClass<T> {
    T value;
    public GClass(T value) {
        this.value = value;
    }
    public T Get() {
        return value;
    }
}

//Simple interface
interface IPos {
    int GetPos();
}

//Simple realization
class PosClass : IPos {
    //Interface realization
    public int GetPos() {
        return 1;
    }
    public int GetAnotherImportantData() {
        return -1;
    }
}

class MainTrouble {
    public int DoUsingInterface(GClass<IPos> interfaceableItem) {
        //Do work using only interface methods
        return interfaceableItem.Get().GetPos();
    }

    public int DoUsingInheritance() {
        GClass<PosClass> item = new GClass<PosClass>(new PosClass());
        //Next line error me
        //cannot convert from 'GClass<PosClass>' to 'GClass<IPos>'
        var r = DoUsingInterface(item);
        //So, next I should execute a several methods using PosClass
        return item.Get().GetAnotherImportantData();
    }
}
```

Some suggestions? Maybe some tricky cast which I miss with it?

答:
This works and I'll add an explanation why at the bottom:

```<code>interface IGClass<out T>
{
    T Get();
}
class GClass<T> : IGClass<T>
{
    T value;
    public GClass(T value)
    {
        this.value = value;
    }
    public T Get()
    {
        return value;
    }
}

//Simple interface
interface IPos
{
    int GetPos();
}

//Simple realization
class PosClass : IPos
{
    //Interface realization
    public int GetPos()
    {
        return 1;
    }
    public int GetAnotherImportantData()
    {
        return -1;
    }
}

class MainTrouble
{
    public int DoUsingInterface(IGClass<IPos> interfaceableItem)
    {
        //Do work using only interface methods
        return interfaceableItem.Get().GetPos();
    }

    public int DoUsingInheritance()
    {
        GClass<PosClass> item = new GClass<PosClass>(new PosClass());

        var r = DoUsingInterface(item);

        return item.Get().GetAnotherImportantData();
    }
}
</code>```

You want a GClass<PosClass> to be a GClass<IPos>. You know that works, because you know that GClass is "readonly". All PosClass are IPos, but obviously not all IPos are PosClass. So for the first to work, both would need to be true.

So you need to make sure your compiler knows what you know: that your class GClass is effectively read-only. Because then you only need the first part and that's always true. This is where the out keyword comes in. It's called covariance and only works on interfaces, that's why I added an extra interface.

Let's play this through with easier and more graphic examples. A Wolf is an Animal. A sheep is an Animal. But a List of sheep is not a list of animals... if it were, I could add a wolf to it, because a wolf is an animal. So what you need is an interface saying "Yes, they are all animals, on reading. Like IEnumerable<T>. An IEnumerable<Sheep> is an IEnumerable<Animal> because it's declared covariant, which is only possible because it only works in one direction: reading.

Body:
I try to use a interface realization through a generic class. Wondering on some abstraction magic, but get compiler errors with this approach.

cannot convert from 'GClass<PosClass>' to 'GClass<IPos>'

Here a simplified example:

//Very simple generic with only data access, no internal manipulation
class GClass<T> {
    T value;
    public GClass(T value) {
        this.value = value;
    }
    public T Get() {
        return value;
    }
}

//Simple interface
interface IPos {
    int GetPos();
}

//Simple realization
class PosClass : IPos {
    //Interface realization
    public int GetPos() {
        return 1;
    }
    public int GetAnotherImportantData() {
        return -1;
    }
}

class MainTrouble {
    public int DoUsingInterface(GClass<IPos> interfaceableItem) {
        //Do work using only interface methods
        return interfaceableItem.Get().GetPos();
    }

    public int DoUsingInheritance() {
        GClass<PosClass> item = new GClass<PosClass>(new PosClass());
        //Next line error me
        //cannot convert from 'GClass<PosClass>' to 'GClass<IPos>'
        var r = DoUsingInterface(item);
        //So, next I should execute a several methods using PosClass
        return item.Get().GetAnotherImportantData();
    }
}

Some suggestions? Maybe some tricky cast which I miss with it?

Body:
This works and I'll add an explanation why at the bottom:

interface IGClass<out T>
{
    T Get();
}
class GClass<T> : IGClass<T>
{
    T value;
    public GClass(T value)
    {
        this.value = value;
    }
    public T Get()
    {
        return value;
    }
}

//Simple interface
interface IPos
{
    int GetPos();
}

//Simple realization
class PosClass : IPos
{
    //Interface realization
    public int GetPos()
    {
        return 1;
    }
    public int GetAnotherImportantData()
    {
        return -1;
    }
}

class MainTrouble
{
    public int DoUsingInterface(IGClass<IPos> interfaceableItem)
    {
        //Do work using only interface methods
        return interfaceableItem.Get().GetPos();
    }

    public int DoUsingInheritance()
    {
        GClass<PosClass> item = new GClass<PosClass>(new PosClass());

        var r = DoUsingInterface(item);

        return item.Get().GetAnotherImportantData();
    }
}

You want a GClass<PosClass> to be a GClass<IPos>. You know that works, because you know that GClass is "readonly". All PosClass are IPos, but obviously not all IPos are PosClass. So for the first to work, both would need to be true.

So you need to make sure your compiler knows what you know: that your class GClass is effectively read-only. Because then you only need the first part and that's always true. This is where the out keyword comes in. It's called covariance and only works on interfaces, that's why I added an extra interface.

Let's play this through with easier and more graphic examples. A Wolf is an Animal. A sheep is an Animal. But a List of sheep is not a list of animals... if it were, I could add a wolf to it, because a wolf is an animal. So what you need is an interface saying "Yes, they are all animals, on reading. Like IEnumerable<T>. An IEnumerable<Sheep> is an IEnumerable<Animal> because it's declared covariant, which is only possible because it only works in one direction: reading.


问:
C++ code without having to declare temporary at the outer scope
Is there any way to write following code without using the temporary "result"?</p>

```<code>result = func();
if(result == -1)
        return func2();
else
    return result;
</code>```

答:
Yes you can.

```<code> return (func() == -1) ? func2() : func();
</code>```

EDIT: Yes you can but be careful

As @Jarod42 said:

You can try to be fancy and not use a temporary value but you can risk having different results (if using rand).

func() can be called twice and may result in performance issues.

tldr: you can only if func() is an idempotent function.

http://www.restapitutorial.com/lessons/idempotency.html

Body:
Is there any way to write following code without using the temporary "result"?

result = func();
if(result == -1)
        return func2();
else
    return result;

Body:
Yes you can.

 return (func() == -1) ? func2() : func();

EDIT: Yes you can but be careful

As @Jarod42 said:

You can try to be fancy and not use a temporary value but you can risk having different results (if using rand).

func() can be called twice and may result in performance issues.

tldr: you can only if func() is an idempotent function.

http://www.restapitutorial.com/lessons/idempotency.html


问:
Compare three different array and arrange them in same order
I tried to arrange three different arrays in the same order, all three arrays as same size but values are not in the same order. How can I arrange them into the same order?

First array:

```<code>Array(
    [0] => Array( [id] => 1 )
    [1] => Array( [id] => 12 )
    [2] => Array( [id] => 25 )
    [3] => Array( [id] => 54 )
)
</code>```

Second array:

```<code>Array(
    [0] => Array( [id] => 24 )
    [1] => Array( [id] => 12 )
    [2] => Array( [id] => 54 )
    [3] => Array( [id] => 1 )
)
</code>```

Third array:

```<code>Array(
    [0] => Array( [id] => 54 )
    [1] => Array( [id] => 25 )
    [2] => Array( [id] => 1 )
    [3] => Array( [id] => 12 )
)
</code>```

Expected final array result:

```<code>Array(
    [0] => Array( [id] => 1 )
    [1] => Array( [id] => 12 )
    [2] => Array( [id] => 25 )
    [3] => Array( [id] => 54 )
)
</code>```

All three arrays are arranged like the first array. I tried a lot but it's not working.

答:
To get all arrays arranged in the same way as a given reference array you can use a custom search function for usort.

```<code>function orderarrayByReferencearrayIds(array $referencearray, array $arrayToSort) {
    // get an array with the id order of the reference array
    $idOrder = array_column($referencearray, 'id');

    usort($arrayToSort, function (array $a, array $b) use ($idOrder) {
        // get the index in reference sort order of each element
        $aIndex = array_search($a['id'], $idOrder);
        $bIndex = array_search($b['id'], $idOrder);

        return $aIndex - $bIndex;
    });

    return $arrayToSort;
}
</code>```

This doesn't work for your second array as the id '24' is not present in the reference array.

Body:
I tried to arrange three different arrays in the same order, all three arrays as same size but values are not in the same order. How can I arrange them into the same order?

First array:

Array(
    [0] => Array( [id] => 1 )
    [1] => Array( [id] => 12 )
    [2] => Array( [id] => 25 )
    [3] => Array( [id] => 54 )
)

Second array:

Array(
    [0] => Array( [id] => 24 )
    [1] => Array( [id] => 12 )
    [2] => Array( [id] => 54 )
    [3] => Array( [id] => 1 )
)

Third array:

Array(
    [0] => Array( [id] => 54 )
    [1] => Array( [id] => 25 )
    [2] => Array( [id] => 1 )
    [3] => Array( [id] => 12 )
)

Expected final array result:

Array(
    [0] => Array( [id] => 1 )
    [1] => Array( [id] => 12 )
    [2] => Array( [id] => 25 )
    [3] => Array( [id] => 54 )
)

All three arrays are arranged like the first array. I tried a lot but it's not working.

Body:
To get all arrays arranged in the same way as a given reference array you can use a custom search function for usort.

function orderarrayByReferencearrayIds(array $referencearray, array $arrayToSort) {
    // get an array with the id order of the reference array
    $idOrder = array_column($referencearray, 'id');

    usort($arrayToSort, function (array $a, array $b) use ($idOrder) {
        // get the index in reference sort order of each element
        $aIndex = array_search($a['id'], $idOrder);
        $bIndex = array_search($b['id'], $idOrder);

        return $aIndex - $bIndex;
    });

    return $arrayToSort;
}

This doesn't work for your second array as the id '24' is not present in the reference array.


问:
Why does the 'xmlns' attribute affect XPath Node lookup?
The following code works perfect. See XML file below.

```<code>XPathDocument xPathDoc = new XPathDocument(@"C:\Authors.xml");
XPathNavigator navigator = xPathDoc.CreateNavigator();
XPathNodeIterator iterator = navigator.Select("/Contacts/Author/FirstName");
iterator.MoveNext();
string firstName = iterator.Current.InnerXml;
Console.WriteLine(firstName);
</code>```

The value of 'firstName' returns 'Joe' which is perfect. However, when I add this attibute xmlns="http://www.w3.org/1999/xhtml" to the '' tag, so that it looks as follows:

```<code><Author xmlns="http://www.w3.org/1999/xhtml">
</code>```

then the code does not return the correct value ('Joe')
Why then the attribute xmlns="http://www.w3.org/1999/xhtml" affects the code above and what am I missing to return the correct value?

Any help will be greatly appreciated.

Here is the xml file:

```<code><?xml version="1.0" encoding="UTF-8" ?>
<Contacts>
<Author>
<FirstName>Joe</FirstName>
</Author>
<Teacher>
<FirstName>Larry</FirstName>
</Teacher>

<Painter>
<FirstName>Mary</FirstName>
</Painter>
</Contacts>
</code>```

答: xmlns is namespace which is used to avoid conflict between tags of the xml. Scenario, when one app is using xml from multiple sources and same tagname exist in two or more xml files. Since probablity of such ambiguity is high, namespace is used to reduce it.</p>

Body:
The following code works perfect. See XML file below.

XPathDocument xPathDoc = new XPathDocument(@"C:\Authors.xml");
XPathNavigator navigator = xPathDoc.CreateNavigator();
XPathNodeIterator iterator = navigator.Select("/Contacts/Author/FirstName");
iterator.MoveNext();
string firstName = iterator.Current.InnerXml;
Console.WriteLine(firstName);

The value of 'firstName' returns 'Joe' which is perfect. However, when I add this attibute xmlns="http://www.w3.org/1999/xhtml" to the '' tag, so that it looks as follows:

<Author xmlns="http://www.w3.org/1999/xhtml">

then the code does not return the correct value ('Joe')
Why then the attribute xmlns="http://www.w3.org/1999/xhtml" affects the code above and what am I missing to return the correct value?

Any help will be greatly appreciated.

Here is the xml file:

<?xml version="1.0" encoding="UTF-8" ?>
<Contacts>
<Author>
<FirstName>Joe</FirstName>
</Author>
<Teacher>
<FirstName>Larry</FirstName>
</Teacher>

<Painter>
<FirstName>Mary</FirstName>
</Painter>
</Contacts>


问:
Simple Select Query taking long time to execute
```<code>select id, subject, date, source
from TABLE_NAME
where source = 'ABC'
order by date desc
</code>```

The above query fetches only 917 rows (out of 300,000 rows), but needs almost 3 minutes

What could be the problem?

答:
This may occur if your table is not properly indexed. Since you are filtering
 917 out of 300000 records, if the column "Source" that you are searching is not indexed, then the Database Engine had to search from the Start to End to find the matching values. Try adding a Non-Clustered Index on the column - If you already have one Clustered index on any other column on the same table.

Refer the below links for more details on Indexing

Understanding SQL Server Indexing - mssqltips.com

SQL Server Indexes Tutorial - SQL Server Planet

Indexes in MS SQL Server - Code Project

Body:
select id, subject, date, source
from TABLE_NAME
where source = 'ABC'
order by date desc

The above query fetches only 917 rows (out of 300,000 rows), but needs almost 3 minutes

What could be the problem?


问:
Input checked state does not affect css selector
So I've been trying to trigger my CSS selector via the checkbox state as you can see below but I've had no luck getting it to trigger. What should happen on click is the tick should simply disappear.

```<code>.i-cb input[type="checkbox"]:checked + label::before {
   display: none;
   width:0px;
   height: 0px;
}
</code>```

JSFiddle : https://jsfiddle.net/7tnepc8r/4/

答:
You just need change the markup order, because you using + sign which indicating label after input:

```<code><div class="i-cb">
  <input id="check" type="checkbox" />
  <label for="check"></label>
</div>
</code>```

Body:
So I've been trying to trigger my CSS selector via the checkbox state as you can see below but I've had no luck getting it to trigger. What should happen on click is the tick should simply disappear.

.i-cb input[type="checkbox"]:checked + label::before {
   display: none;
   width:0px;
   height: 0px;
}

JSFiddle : https://jsfiddle.net/7tnepc8r/4/

Body:
You just need change the markup order, because you using + sign which indicating label after input:

<div class="i-cb">
  <input id="check" type="checkbox" />
  <label for="check"></label>
</div>


答:
I sure can. When you do this kind of stuff best use css. That way when the dom loads the css will kick in and your desired effect will show.

Further more its easier to understand and easier to code up.

```<code>.tabContent  {
    display:none;
}
.tabContent.active  {
    display:block;
}
</code>```

Then in the HTML

```<code><div id="tabs-1" class="tabContent active">
</code>```

So when the page loads tab one is active

Then in your JS

```<code>function showStuff(element)  {
    var tabContents = document.getElementsByClassName('tabContent');
    for (var i = 0; i < tabContents.length; i++) {

      tabContents[i].className="tabContent";
    }

    var tabContentIdToShow = element.id.replace(/(\d)/g, '-$1');
    document.getElementById(tabContentIdToShow).className="tabContent active";
}
</code>```

Updated fiddle!

https://jsfiddle.net/rb5c5095/3/

We could improve things since we know all the tabs will be made invisible at boot up and tab 1 will show. So when a tab is clicked we could just search the tab who has .active class and remove it, then apply the .active class to the new tab. This would have the benefit that any extra css you add in your html markup would not be removed by the JS code, but i reckon you can work that out and if you can't get back to me i can show you :-)

Title: Javascript show/hide, show first div on page load

Body:
Can you help me to make the first div show on page load?

function showStuff(element)  {
    var tabContents = document.getElementsByClassName('tabContent');
    for (var i = 0; i < tabContents.length; i++) {
        tabContents[i].style.display = 'none';
    }

    var tabContentIdToShow = element.id.replace(/(\d)/g, '-$1');
    document.getElementById(tabContentIdToShow).style.display = 'block';
}

.tabContent {
    display:none;
}

CARATTERISTICHE

DESTINATARI

 CALENDARIO

tab 1

tab 2 tab 2

tab 3 tab 3 tab 3

This is my actual code. jsFiddle
Thanks!

Body:
I sure can. When you do this kind of stuff best use css. That way when the dom loads the css will kick in and your desired effect will show.

Further more its easier to understand and easier to code up.

.tabContent  {
    display:none;
}
.tabContent.active  {
    display:block;
}

Then in the HTML

<div id="tabs-1" class="tabContent active">

So when the page loads tab one is active

Then in your JS

function showStuff(element)  {
    var tabContents = document.getElementsByClassName('tabContent');
    for (var i = 0; i < tabContents.length; i++) {

      tabContents[i].className="tabContent";
    }

    var tabContentIdToShow = element.id.replace(/(\d)/g, '-$1');
    document.getElementById(tabContentIdToShow).className="tabContent active";
}

Updated fiddle!

https://jsfiddle.net/rb5c5095/3/

We could improve things since we know all the tabs will be made invisible at boot up and tab 1 will show. So when a tab is clicked we could just search the tab who has .active class and remove it, then apply the .active class to the new tab. This would have the benefit that any extra css you add in your html markup would not be removed by the JS code, but i reckon you can work that out and if you can't get back to me i can show you :-)


问:
Apache Flink: How to store intermedia data in streaming application
I am implementing the MisraGries algorithm with Flink's DataStream API. It keeps k counters to record the data summary by increment or decrement.

What is the best approach to store such counters when using DataStream API to implement the algorithm? Now I just declared a HashMap variable in the operator. Is this the right approach or do I need to use some other features like state?

答:
You should store the counters in Flink's managed state, i.e., either keyed state or operator state and enable checkpointing. Otherwise, the information will be lost in case of a failure.

If state is correctly used and checkpointing is enabled, Flink periodically checkpoints the state of an application. In case of a failure, the job is restarted and its state is reset to the latest checkpoint.


问:
How can I get a vertical scrollbar in my ListBox?
In the example below I have a ListBox with dozens of font names in it.

I would have thought it would automatically have a vertical scrollbar on it so that you can select ANY font, not just the first ones in the list, but it doesn't.

So I added a "ScrollViewer" and that puts a "scrollbar area" on the right but there is no scrollbar in the scrollbar area so that you can scroll (!).

Why isn't a scrollbar automatic and how do I force it to have a scrollbar?

```<code><StackPanel Name="stack1">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="2*"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>
        <ScrollViewer>
            <ListBox Grid.Row="0" Name="lstFonts" Margin="3"  ItemsSource="{x:Static Fonts.SystemFontFamilies}"/>
        </ScrollViewer>
    </Grid>
</StackPanel>
</code>```

答:
The problem with your solution is you're putting a scrollbar around a ListBox where you probably want to put it inside the ListBox.

If you want to force a scrollbar in your ListBox, use the ScrollBar.VerticalScrollBarVisibility attached property.

```<code><ListBox
    ItemsSource="{Binding}"
    ScrollViewer.VerticalScrollBarVisibility="Visible">
</ListBox>
</code>```

Setting this value to Auto will popup the scrollbar on an as needed basis.

OwnerDisplayName: Edward Tanguay

Body:
In the example below I have a ListBox with dozens of font names in it.

I would have thought it would automatically have a vertical scrollbar on it so that you can select ANY font, not just the first ones in the list, but it doesn't.

So I added a "ScrollViewer" and that puts a "scrollbar area" on the right but there is no scrollbar in the scrollbar area so that you can scroll (!).

Why isn't a scrollbar automatic and how do I force it to have a scrollbar?

<StackPanel Name="stack1">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="2*"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>
        <ScrollViewer>
            <ListBox Grid.Row="0" Name="lstFonts" Margin="3"  ItemsSource="{x:Static Fonts.SystemFontFamilies}"/>
        </ScrollViewer>
    </Grid>
</StackPanel>

Body:
The problem with your solution is you're putting a scrollbar around a ListBox where you probably want to put it inside the ListBox.

If you want to force a scrollbar in your ListBox, use the ScrollBar.VerticalScrollBarVisibility attached property.

<ListBox
    ItemsSource="{Binding}"
    ScrollViewer.VerticalScrollBarVisibility="Visible">
</ListBox>

Setting this value to Auto will popup the scrollbar on an as needed basis.

OwnerDisplayName: JaredPar


问:
How to implement Google Adwords conversion code in Contact Form 7 Wordpress
I want to integrate Google conversion Adwords code in Contact form 7 Plugin without redirecting to a ‘Thank You’ page.How to implement  Google Adwords conversion code in Contact form 7 Plugin.Could someone help me.I would not prefer redirecting to another page.

答:
I found solution for implementing Google conversion Adwords code in Contact form 7.

Step 1
Edit the CF7 form you want to track conversions for and paste the Google Adwords Conversion code from google at the end of your form.

Step 2

Replacing on_sent_ok with DOM Events.

To replace it with an alternative code using DOM events, first, find the file named “functions.php” in the directory of your active theme. Second, add the following code at the bottom of the functions.php file:

```<code>add_action( 'wp_footer', 'mycustom_wp_footer' );

function mycustom_wp_footer() {
?>
<script type="text/javascript">
document.addEventListener( 'wpcf7mailsent', function( event ) {
    typeof goog_report_conversion === 'function' && goog_report_conversion();
}, false );
</script>
<?php
}
</code>```

Step 3

Remove the “on_sent_ok” line from the Additional Settings tab and save the contact form.

Body:
I found solution for implementing Google conversion Adwords code in Contact form 7.

Step 1
Edit the CF7 form you want to track conversions for and paste the Google Adwords Conversion code from google at the end of your form.

Step 2

Replacing on_sent_ok with DOM Events.

To replace it with an alternative code using DOM events, first, find the file named “functions.php” in the directory of your active theme. Second, add the following code at the bottom of the functions.php file:

add_action( 'wp_footer', 'mycustom_wp_footer' );

function mycustom_wp_footer() {
?>
<script type="text/javascript">
document.addEventListener( 'wpcf7mailsent', function( event ) {
    typeof goog_report_conversion === 'function' && goog_report_conversion();
}, false );
</script>
<?php
}

Step 3

Remove the “on_sent_ok” line from the Additional Settings tab and save the contact form.


问:
C# Java HashMap equivalent
Coming from a Java world into a C# one is there a HashMap equivalent? If not what would you recommend?</p>

答:
I just wanted to give my two cents.

This is according to @Powerlord 's answer.

Puts "null" instead of null strings.

```<code>private static Dictionary<string, string> map = new Dictionary<string, string>();

public static void put(string key, string value)
{
    if (value == null) value = "null";
    map[key] = value;
}

public static string get(string key, string defaultValue)
{
    try
    {
        return map[key];
    }
    catch (KeyNotFoundException e)
    {
        return defaultValue;
    }
}

public static string get(string key)
{
    return get(key, "null");
}
</code>```

Title: C# Java HashMap equivalent

Body:
I just wanted to give my two cents.

This is according to @Powerlord 's answer.

Puts "null" instead of null strings.

private static Dictionary<string, string> map = new Dictionary<string, string>();

public static void put(string key, string value)
{
    if (value == null) value = "null";
    map[key] = value;
}

public static string get(string key, string defaultValue)
{
    try
    {
        return map[key];
    }
    catch (KeyNotFoundException e)
    {
        return defaultValue;
    }
}

public static string get(string key)
{
    return get(key, "null");
}


问:
Send Firebase notifications to topic based on language
I need to send Firebase notifications to a topic based on the device/user language. So, for example, a notification should be sent to all devices with English language subscribed to the topic "news".

Am I right, that this is not possible using the Firebase Console? Is there another way except creating language specific topics (e.g. "news-en", "news-fr", ...)?

Many thanks!

答:
I recently run into this issue also, and maybe found some workaround, maybe workable for you.

Currently the firebase console can pick a language to push, but the doc says that the language base on the device, but according to my survey, I still can not find the relation yet.

So, I suggest you can add the valuable in the customize key/value, and extend FirebaseMessagingService

Override the function of handleIntent, to get the key/value which you want.

The before push your customize notification, clear all notification of your application, after that, you will receive your customize notification. In this case, you can also customize the notification based on the device display language.


问:
How do I display place labels instead of A or B in Google Maps directions API?
I want to display names of the places on the map instead of labels A and B. How do I do it in Google Maps Directions API? For example, just Start and End or Miami Port to Miami Tower.

CODE

```<code>    let directionsDisplay;
    let directionsService = new google.maps.DirectionsService();
    let map;

    directionsDisplay = new google.maps.DirectionsRenderer();

    let myOptions = {
        mapTypeId: google.maps.MapTypeId.ROADMAP,
    };
    let mapArea = document.getElementById("map_canvas_track_order");

    map = new google.maps.Map(mapArea, myOptions);
    directionsDisplay.setMap(map);

    let start = `25.757928, -80.192897`;
    let end = `25.771969, -80.191235`;
    let request = {
        origin:start,
        destination:end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    directionsService.route(request, function(response, status) {
        if (status === google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
    });
</code>```

CURRENT MAP PREVIEW

答:
You can hide default Marker A and B using suppressMarkers property as true.

```<code>directionsDisplay = new google.maps.DirectionsRenderer({map: map, suppressMarkers: true});
</code>```

And then Make your own Marker at the end points using Marker.

```<code>var marker = new google.maps.Marker({
                position: ,
                label: "~what you want~",
                map: map
            });
</code>```

Body:
I want to display names of the places on the map instead of labels A and B. How do I do it in Google Maps Directions API? For example, just Start and End or Miami Port to Miami Tower.

CODE

    let directionsDisplay;
    let directionsService = new google.maps.DirectionsService();
    let map;

    directionsDisplay = new google.maps.DirectionsRenderer();

    let myOptions = {
        mapTypeId: google.maps.MapTypeId.ROADMAP,
    };
    let mapArea = document.getElementById("map_canvas_track_order");

    map = new google.maps.Map(mapArea, myOptions);
    directionsDisplay.setMap(map);

    let start = `25.757928, -80.192897`;
    let end = `25.771969, -80.191235`;
    let request = {
        origin:start,
        destination:end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    directionsService.route(request, function(response, status) {
        if (status === google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
    });

CURRENT MAP PREVIEW

Body:
You can hide default Marker A and B using suppressMarkers property as true.

directionsDisplay = new google.maps.DirectionsRenderer({map: map, suppressMarkers: true});

And then Make your own Marker at the end points using Marker.

var marker = new google.maps.Marker({
                position: ,
                label: "~what you want~",
                map: map
            });


问:
How do I set the program to find the max grade?
The problem reads "Write a method called findMaxGrade. The method will take an array of int as a parameter and it will return the largest value from the array(i.e., representing the largest grade)."

I can't work my head around it. Previously I had to make the user input a number of grades, find the average of it, and give a corresponding letter to the grade.
How am I supposed to set the program in a way where it will read the inputs and know which is the highest? That is the way it's supposed to work right?

```<code>import java.util.Scanner;
public class ArrayExample3{
    public static void main(String [] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Please enter the total number of grades");
        int n = input.nextInt();
        double [] array = new double [n];
        double total = 0.0;

        for(int i = 0; i < array.length; i++){
            System.out.println("Please enter the grade #"+(i+1));
            double g = input.nextDouble();
            array[i] = g;
            total += array[i];
        }
        double avg = total / array.length;

        System.out.println("AVG: "+avg);

        System.out.println(getGradeByAVG(avg));

    }
    public static String getGradeByAVG(double avg){

        String letterGrade = "";
        if( avg >= 90 && avg <= 100 ) {
            letterGrade = "A";
        }
        else if( avg >= 80 && avg <= 89 ) {
            letterGrade = "B";
        }
        else if( avg >= 70 && avg <= 79 ) {
            letterGrade = "C";
        }
        else if( avg >= 60 && avg <= 69 ) {
            letterGrade = "D";
        }
        else if( avg < 60 ) {
            letterGrade = "F";
        }
        return letterGrade;
    }
}
</code>```

答:
This method should do the trick:

```<code>public int findMaxGrade(int [] array, n)
        {
            int max = -1;
            for(int i = 0; i < n, i++)
                if(max<array[i])
                    max = array[i];

            return max;

        }
</code>```

And you can call it by: findMaxGrade(array, n);

Body:
The problem reads "Write a method called findMaxGrade. The method will take an array of int as a parameter and it will return the largest value from the array(i.e., representing the largest grade)."

I can't work my head around it. Previously I had to make the user input a number of grades, find the average of it, and give a corresponding letter to the grade.
How am I supposed to set the program in a way where it will read the inputs and know which is the highest? That is the way it's supposed to work right?

import java.util.Scanner;
public class ArrayExample3{
    public static void main(String [] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Please enter the total number of grades");
        int n = input.nextInt();
        double [] array = new double [n];
        double total = 0.0;

        for(int i = 0; i < array.length; i++){
            System.out.println("Please enter the grade #"+(i+1));
            double g = input.nextDouble();
            array[i] = g;
            total += array[i];
        }
        double avg = total / array.length;

        System.out.println("AVG: "+avg);

        System.out.println(getGradeByAVG(avg));

    }
    public static String getGradeByAVG(double avg){

        String letterGrade = "";
        if( avg >= 90 && avg <= 100 ) {
            letterGrade = "A";
        }
        else if( avg >= 80 && avg <= 89 ) {
            letterGrade = "B";
        }
        else if( avg >= 70 && avg <= 79 ) {
            letterGrade = "C";
        }
        else if( avg >= 60 && avg <= 69 ) {
            letterGrade = "D";
        }
        else if( avg < 60 ) {
            letterGrade = "F";
        }
        return letterGrade;
    }
}

Body:
This method should do the trick:

public int findMaxGrade(int [] array, n)
        {
            int max = -1;
            for(int i = 0; i < n, i++)
                if(max<array[i])
                    max = array[i];

            return max;

        }

And you can call it by: findMaxGrade(array, n);


问:
Has anyone been successful in using 64-bit Eclipse for Android 2.3 dev on 64-bit Windows 7?
Has anyone been successful in using 64-bit Eclipse for Android 2.3 dev on 64-bit Windows 7?

Please answer positively only if, when you invoke the emulator via Eclipse's Run (Ctrl+F11), your app-to-be-debugged's APK is installed automatically onto the Android emulator and you are running this same exact configuration:

Windows 7 Ultimate 64-bit.

JDK 64-bit (jdk-6u23-windows-x64.exe installed.)

JDK 32-bit (jdk-6u23-windows-i586.exe installed.)

Eclipse Classic 3.6 64-bit (eclipse-SDK-3.6.1-win32-x86_64.zip)

Android 2.3 SDK Starter Package

If you are able to fully use 64-bit Eclipse for Android 2.3 dev on 64-bit Windows 7, please describe the steps you performed to make this happen.

As of now, the following steps did NOT work for me:

install the 64-bit JDK

install the 32-bit JDK

unzip android-sdk_r08-windows.zip to
C:\android-sdk-windows

append C:\android-sdk-windows\tools
to %PATH% in System env vars.

Run C:\android-sdk-windows\tools>android.bat

Install ADT Plugin via Eclipse

Create "Android 2.3 - API Level 9" virtual device via Eclipse

Window > Preferences > Java > Installed JREs: [Search...]

答:
Hope this helps, if anyone else is having this issue.

Following configuration works perfectly fine for me.

Windows 7 Professional 64 bit

Eclipse Helios 3.6.1 64 bit (JavaEE)

JDK 6u23 64 bit

Android SDK 2.3

ADT 8.01

My sequence of steps:

Install 64 bit JDK. Update PATH and JAVA_HOME env variables.

Uncompress Android SDK and get all the required versions 7, 8 and 9. Add ANDROID_HOME env variable.

Uncompress Eclipse 64 bit and install the ADT plugin and then configure the Android SDK in Preferences page of Eclipse.


问:
Java was started but returned with exit code=1
I am receiving error called - Java was started but returned with exit code=1

I have received this error after upgrading my java.
I can see my ini file has below content.

```<code> -startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20140415-2008.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v20150204-1316
-vm C:\Program Files (x86)\Java\jdk1.8.0_73\jre\bin\server\jvm.dll
-vmargs
-Dfile.encoding=UTF-8
-Xms512m
-Xmx1536m
-XX:MaxPermSize=512m
-Dosgi.instance.area.default=@user.home/AnypointStudio/workspace
</code>```

JAVA_HOME has value as C:\Program Files (x86)\Java\jdk1.8.0_73
Path env has value as C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Java\jre1.8.0_73\bin;C:\Program Files (x86)\Java\jdk1.8.0_73\bin;

My new updated jre is in below location.
C:\Program Files (x86)\Java\jre1.8.0_73\bin

Note that i found many solutions for this issue in this site which are not working for me. Kindly guide me where i am doing wrong.

答:
In my case the error was pretty silly: in the config.ini there was an error in the last line where the memory parameter -Xmx was set to "2024".
I'm pretty sure I did not edit that line by hand.
I reverted it to -Xmx1024m to make it work

```<code>-Xmx2024m
</code>```

changed to

```<code>-Xmx1024m
</code>```

the issue seems to be related to the Java vm 1.8.131 (32bit) that responds with an error any time I try to ask more than 1477m, even when I have more than 4GB of free ram:

```<code>java -Xmx1477m
Error occurred during initialization of VM
Could not reserve enough space for 1513472KB object heap
</code>```

on the same PC a JDK 1.7 does not have any issues in using 2GB

Body:
I am receiving error called - Java was started but returned with exit code=1

I have received this error after upgrading my java.
I can see my ini file has below content.

 -startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20140415-2008.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v20150204-1316
-vm C:\Program Files (x86)\Java\jdk1.8.0_73\jre\bin\server\jvm.dll
-vmargs
-Dfile.encoding=UTF-8
-Xms512m
-Xmx1536m
-XX:MaxPermSize=512m
-Dosgi.instance.area.default=@user.home/AnypointStudio/workspace

JAVA_HOME has value as C:\Program Files (x86)\Java\jdk1.8.0_73
Path env has value as C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Java\jre1.8.0_73\bin;C:\Program Files (x86)\Java\jdk1.8.0_73\bin;

My new updated jre is in below location.
C:\Program Files (x86)\Java\jre1.8.0_73\bin

Note that i found many solutions for this issue in this site which are not working for me. Kindly guide me where i am doing wrong.

Body:
In my case the error was pretty silly: in the config.ini there was an error in the last line where the memory parameter -Xmx was set to "2024".
I'm pretty sure I did not edit that line by hand.
I reverted it to -Xmx1024m to make it work

-Xmx2024m

changed to

-Xmx1024m

the issue seems to be related to the Java vm 1.8.131 (32bit) that responds with an error any time I try to ask more than 1477m, even when I have more than 4GB of free ram:

java -Xmx1477m
Error occurred during initialization of VM
Could not reserve enough space for 1513472KB object heap

on the same PC a JDK 1.7 does not have any issues in using 2GB


问:
Javascript show/hide, show first div on page load
Can you help me to make the first div show on page load?

function showStuff(element)  {
    var tabContents = document.getElementsByClassName('tabContent');
    for (var i = 0; i < tabContents.length; i++) {
        tabContents[i].style.display = 'none';
    }

    var tabContentIdToShow = element.id.replace(/(\d)/g, '-$1');
    document.getElementById(tabContentIdToShow).style.display = 'block';
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.tabContent {
    display:none;
}</code>```

CARATTERISTICHE

DESTINATARI

 CALENDARIO

tab 1

tab 2 tab 2

tab 3 tab 3 tab 3

```

This is my actual code. jsFiddle
Thanks!

答:
Here I am invoking the function (upon page load) that tweaks the css of the desired block;
Same can be achieved by $(document).ready;
I took this approach to avoid jquery;</p>

```<code>window.onload =  showDivOne();

function showDivOne() {
    document.getElementById("tabs-1").style.display = "block";
}
</code>```

Body:
Here I am invoking the function (upon page load) that tweaks the css of the desired block;
Same can be achieved by $(document).ready;
I took this approach to avoid jquery;

window.onload =  showDivOne();

function showDivOne() {
    document.getElementById("tabs-1").style.display = "block";
}


问:
Tear down and rebuild Core Data Stack with NSPersistentContainer
I felt sure that this question would have been asked and answered many times, but I was surprised to find that after hours of searching, I cannot find an answer. With the dawn of iOS 10, NSPersistentContainer changed the way we deal with the Core Data Stack. I understand how to set up a Core Data stack. But it is a different process to tear down and rebuild a Core Data stack when the underlying store is replaced (in my case, sqlite). I am hoping this is a stupid question and someone can point me to the 75 questions that I have somehow missed on this topic. Otherwise, I would appreciate any help offered.</p>

答:
Anything you have been doing before should still work the same way.  A NSPersistentContainer is not magic, and does not do that much. It is a convenience for setting up a store with a model and a main thread context.  It is has methods for creating background context. It does not replace everything you know about core-data.  It is all the same stuff inside.  Inside the persistentContainer is a pointer to the persistentStoreCoordinator which has a pointer to the model and to the stores.

I don't know what you code is for replacing a store, so I can't help you translate it to a persistentContainer. If you find you can't do, there is no reason to stick to NSPersistentContainer, as I said before - it is not magic and it doesn't do that much for you.


问:
Change button color all edittext fields filled?
I have button and text fields like below in my layout file

```<code><EditText
        android:id="@+id/et_password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView4"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/btn_app_signup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/et_password"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="63dp"
        android:background="@drawable/button"
        android:text="SIGN UP"
        android:textColor="@color/white" />
</code>```

How can I change this background into @drawable/button_success to if all edit text fields filled my Activity class like below

```<code>@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signup);
        btn_app_signup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String name = et_name.getText().toString();
                String email = et_email.getText().toString();
                String password = et_password.getText().toString();

                registerAccount(name, email, password);
            }
        });
    }

    private void registerAccount(String name, String email, String password) {

        if(TextUtils.isEmpty(name) || TextUtils.isEmpty(email) || TextUtils.isEmpty(password)) {
            Toast.makeText(SignupActivity.this, "All fields required", Toast.LENGTH_LONG).show();
        }
        else {

            //save data in datbase
        }
    }
</code>```

How can I do that if I fill all my edit text fields fill change the button button background

答:
Try this

```<code>private void registerAccount(String name, String email, String password) {

        if(!TextUtils.isEmpty(name)&& !TextUtils.isEmpty(email) && !TextUtils.isEmpty(password)){

           btn_app_signup.setBackground(ContextCompat.getDrawable(this,R.drawable.ic_android_black_24dp));// set here your backgournd to button
          // save data in database

        }else {
            Toast.makeText(this, "All fields required", Toast.LENGTH_LONG).show();
        }

    }
</code>```

Edit

```<code> et_password.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (!TextUtils.isEmpty(et_name.getText().toString()) && !TextUtils.isEmpty(et_email.getText().toString()) && !TextUtils.isEmpty(et_password.getText().toString())) {
                btn_app_signup.setBackground(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_android_black_24dp));// set here your backgournd to button
            }else {
                btn_app_signup.setBackgroundResource(android.R.drawable.btn_default);
            }
        }
    });
    et_email.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (!TextUtils.isEmpty(et_name.getText().toString()) && !TextUtils.isEmpty(et_email.getText().toString()) && !TextUtils.isEmpty(et_password.getText().toString())) {
                btn_app_signup.setBackground(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_android_black_24dp));// set here your backgournd to button
            }else {
                btn_app_signup.setBackgroundResource(android.R.drawable.btn_default);
            }
        }
    });
    et_name.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (!TextUtils.isEmpty(et_name.getText().toString()) && !TextUtils.isEmpty(et_email.getText().toString()) && !TextUtils.isEmpty(et_password.getText().toString())) {
                btn_app_signup.setBackground(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_android_black_24dp));// set here your backgournd to button
            }else {
                btn_app_signup.setBackgroundResource(android.R.drawable.btn_default);
            }
        }
    });
</code>```

Body:
I have button and text fields like below in my layout file

<EditText
        android:id="@+id/et_password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView4"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/btn_app_signup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/et_password"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="63dp"
        android:background="@drawable/button"
        android:text="SIGN UP"
        android:textColor="@color/white" />

How can I change this background into @drawable/button_success to if all edit text fields filled my Activity class like below

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signup);
        btn_app_signup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String name = et_name.getText().toString();
                String email = et_email.getText().toString();
                String password = et_password.getText().toString();

                registerAccount(name, email, password);
            }
        });
    }

    private void registerAccount(String name, String email, String password) {

        if(TextUtils.isEmpty(name) || TextUtils.isEmpty(email) || TextUtils.isEmpty(password)) {
            Toast.makeText(SignupActivity.this, "All fields required", Toast.LENGTH_LONG).show();
        }
        else {

            //save data in datbase
        }
    }

How can I do that if I fill all my edit text fields fill change the button button background

Body:
Try this

private void registerAccount(String name, String email, String password) {

        if(!TextUtils.isEmpty(name)&& !TextUtils.isEmpty(email) && !TextUtils.isEmpty(password)){

           btn_app_signup.setBackground(ContextCompat.getDrawable(this,R.drawable.ic_android_black_24dp));// set here your backgournd to button
          // save data in database

        }else {
            Toast.makeText(this, "All fields required", Toast.LENGTH_LONG).show();
        }

    }

Edit

 et_password.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (!TextUtils.isEmpty(et_name.getText().toString()) && !TextUtils.isEmpty(et_email.getText().toString()) && !TextUtils.isEmpty(et_password.getText().toString())) {
                btn_app_signup.setBackground(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_android_black_24dp));// set here your backgournd to button
            }else {
                btn_app_signup.setBackgroundResource(android.R.drawable.btn_default);
            }
        }
    });
    et_email.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (!TextUtils.isEmpty(et_name.getText().toString()) && !TextUtils.isEmpty(et_email.getText().toString()) && !TextUtils.isEmpty(et_password.getText().toString())) {
                btn_app_signup.setBackground(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_android_black_24dp));// set here your backgournd to button
            }else {
                btn_app_signup.setBackgroundResource(android.R.drawable.btn_default);
            }
        }
    });
    et_name.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (!TextUtils.isEmpty(et_name.getText().toString()) && !TextUtils.isEmpty(et_email.getText().toString()) && !TextUtils.isEmpty(et_password.getText().toString())) {
                btn_app_signup.setBackground(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_android_black_24dp));// set here your backgournd to button
            }else {
                btn_app_signup.setBackgroundResource(android.R.drawable.btn_default);
            }
        }
    });


问:
How can I use AppleScript to check if PowerPoint is playing a presentation?
I'm trying to write some AppleScript that checks if PowerPoint 2011 is currently playing a presentation.

Previously, I wrote the following code for Keynote.

```<code>on isKeynotePlaying()
    tell application "Keynote"
        get properties
        return (not frozen) and playing
    end tell
end isKeynotePlaying
</code>```

After searching through PowerPoint's AppleScript library, properties and attributes of classes, and Google search results, I still haven't been able to generate an equivalent solution.  Any ideas?

答:
After delving even deeper into PowerPoint's AppleScript library, I stumbled upon the slide show view class. Here's my solution.

```<code>on isPowerPointPlaying()
    tell application "Microsoft PowerPoint"
        return slide state of slide show view of slide show window of active presentation is slide show state running
    end tell
end isPowerPointPlaying
</code>```

Body:
I'm trying to write some AppleScript that checks if PowerPoint 2011 is currently playing a presentation.

Previously, I wrote the following code for Keynote.

on isKeynotePlaying()
    tell application "Keynote"
        get properties
        return (not frozen) and playing
    end tell
end isKeynotePlaying

After searching through PowerPoint's AppleScript library, properties and attributes of classes, and Google search results, I still haven't been able to generate an equivalent solution.  Any ideas?

Body:
After delving even deeper into PowerPoint's AppleScript library, I stumbled upon the slide show view class. Here's my solution.

on isPowerPointPlaying()
    tell application "Microsoft PowerPoint"
        return slide state of slide show view of slide show window of active presentation is slide show state running
    end tell
end isPowerPointPlaying


问:
PopupWindow - Dismiss when clicked outside
I have a PopupWindow on my activity, the thing is my PopupWindow still shows even when I'm interacting with my activity (say scrolling on my list).  I can scroll through my list and the PopupWindow is still there.

What I want to achieve is when I'm touching/scrolling/clicking/etc on the screen which is not the PopupWindow, I want to dismiss the PopupWindow.  Just like how a menu works.  If you clicked outside of the menu, the menu will be dismissed.

I've tried setOutsideTouchable(true) but it won't dismiss the window.  Thanks.

答:
Thanks for @LunaKong's answer and @HourGlass's confirmation. I don't want to make a duplicated comment, but only want to make it clear and concise.

```<code>// Closes the popup window when touch outside. This method was written informatively in Google's docs.
mPopupWindow.setOutsideTouchable(true);

// Set focus true to prevent a touch event to go to a below view (main layout), which works like a dialog with 'cancel' property => Try it! And you will know what I mean.
mPopupWindow.setFocusable(true);

// Removes default background.
mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
</code>```

Mttdat.

Body:
Thanks for @LunaKong's answer and @HourGlass's confirmation. I don't want to make a duplicated comment, but only want to make it clear and concise.

// Closes the popup window when touch outside. This method was written informatively in Google's docs.
mPopupWindow.setOutsideTouchable(true);

// Set focus true to prevent a touch event to go to a below view (main layout), which works like a dialog with 'cancel' property => Try it! And you will know what I mean.
mPopupWindow.setFocusable(true);

// Removes default background.
mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

Mttdat.