问:
Set class to active on additional li elements upon navbar click
I have the following side bar menu code. Upon click on any of the nav items it highlights / makes the class active.

```<code>$(document).ready(function() {
  $(".nav li").click(function() {
    if ($(".nav li").removeClass("active")) {
      $(this).removeClass("active");
    }
    $(this).addClass("active");
  });

});

<ul class="nav">
  <li class="nav-item">
    <a data-target="#system-settings" data-toggle="pill" class="nav-link" href="#system-settings" id="system-settings">System Settings</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="#hosts" id="hosts" data-parent="#hosts">Hosts</a>
  </li>
  <li class="nav-item ">
    <a class="nav-link" href="#card-range" id="card-range">Cards</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" id="pinpads" href="#pinpads">Printer</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" id="xmls" href="#xmls">Pinpad</a>
  </li>

</ul>
</code>```

Now I have similar items at the top of the page presented as a connected circle:

```<code><div class="connected-line">
  <ul>
    <li class="active">1
      <p> System </p>
    </li>
    <li id="hosts">2
      <p> Hosts </p>
    </li>
    <li>3
      <p> Cards </p>
    </li>
    <li>4
      <p> Devices </p>
    </li>
  </ul>
</div>
</code>```

See jsfiddle:
https://jsfiddle.net/vk3qw09f/345/

Now if the user clicks on the side bar menu, it should also set corresponding  class as active on the "connected-line" list elements.

For eg: Cliking on navbar "System Settings" should also add a class 'active' to the li item inside the circled li "System"

I know it's not recommednded to have the same 2 ids on the same page. So looking for a smarter way to achieve this.

EDIT: my current code will only make that class active: $(this).addClass("active");

I probably want to make all classes that share the same name active

答:
Rewrite the html code as follows

```<code><div class="connected-line">
  <ul>
    <li class="system active">1
      <p> System </p>
    </li>
    <li class="host" id="hosts">2
      <p> Hosts </p>
    </li>
    <li class="card">3
      <p> Cards </p>
    </li>
    <li class="device">4
      <p> Devices </p>
    </li>
    <li class="lane">5
      <p> Lanes </p>
    </li>
  </ul>
</div>

<ul class="nav">
  <li class="nav-item system">
    <a data-target="#system-settings" data-toggle="pill" class="nav-link" href="#system-settings" id="system-settings">System Settings</a>
  </li>
  <li class="nav-item host">
    <a class="nav-link" href="#hosts" id="hosts" data-parent="#hosts">Hosts</a>
  </li>
  <li class="nav-item card">
    <a class="nav-link" href="#card-range" id="card-range">Cards</a>
  </li>
  <li class="nav-item printer">
    <a class="nav-link" id="pinpads" href="#pinpads">Printer</a>
  </li>
  <li class="nav-item pinpad">
    <a class="nav-link" id="xmls" href="#xmls">Pinpad</a>
  </li>
</ul>
</code>```

Make sure to add same class name to matching li. Then modify the js code as follows,

```<code>$(document).ready(function() {
  $(".nav li").click(function() {
 //Make sure to add class name immediately after "nav-item". For eg."nav-item printer"
  var calss=$(this).attr('class').split(' ')[1];
  console.log(calss);
  $(".nav li").removeClass("active");
  $(".connected-line ul li").removeClass("active");
  $("li." + calss).addClass("active");
  });

});
</code>```

Body:
I have the following side bar menu code. Upon click on any of the nav items it highlights / makes the class active.

$(document).ready(function() {
  $(".nav li").click(function() {
    if ($(".nav li").removeClass("active")) {
      $(this).removeClass("active");
    }
    $(this).addClass("active");
  });

});

    System Settings

    Hosts

    Cards

    Printer

    Pinpad

Now I have similar items at the top of the page presented as a connected circle:

1

 System

2

 Hosts

3

 Cards

4

 Devices

See jsfiddle:
https://jsfiddle.net/vk3qw09f/345/

Now if the user clicks on the side bar menu, it should also set corresponding  class as active on the "connected-line" list elements.

For eg: Cliking on navbar "System Settings" should also add a class 'active' to the li item inside the circled li "System"

I know it's not recommednded to have the same 2 ids on the same page. So looking for a smarter way to achieve this.

EDIT: my current code will only make that class active: $(this).addClass("active");

I probably want to make all classes that share the same name active

Body:
Rewrite the html code as follows

<div class="connected-line">
  <ul>
    <li class="system active">1
      <p> System </p>
    </li>
    <li class="host" id="hosts">2
      <p> Hosts </p>
    </li>
    <li class="card">3
      <p> Cards </p>
    </li>
    <li class="device">4
      <p> Devices </p>
    </li>
    <li class="lane">5
      <p> Lanes </p>
    </li>
  </ul>
</div>

<ul class="nav">
  <li class="nav-item system">
    <a data-target="#system-settings" data-toggle="pill" class="nav-link" href="#system-settings" id="system-settings">System Settings</a>
  </li>
  <li class="nav-item host">
    <a class="nav-link" href="#hosts" id="hosts" data-parent="#hosts">Hosts</a>
  </li>
  <li class="nav-item card">
    <a class="nav-link" href="#card-range" id="card-range">Cards</a>
  </li>
  <li class="nav-item printer">
    <a class="nav-link" id="pinpads" href="#pinpads">Printer</a>
  </li>
  <li class="nav-item pinpad">
    <a class="nav-link" id="xmls" href="#xmls">Pinpad</a>
  </li>
</ul>

Make sure to add same class name to matching li. Then modify the js code as follows,

$(document).ready(function() {
  $(".nav li").click(function() {
 //Make sure to add class name immediately after "nav-item". For eg."nav-item printer"
  var calss=$(this).attr('class').split(' ')[1];
  console.log(calss);
  $(".nav li").removeClass("active");
  $(".connected-line ul li").removeClass("active");
  $("li." + calss).addClass("active");
  });

});


来源: stackexchange

问:
How to call an Alert with Activity Indicator on Xamarim?
I have a code where, after a button click, i start running an Activity Indicator, then after some task, i stop it.

I would like to call a Display Alert function after it. Heres my code:

```<code>private void BtnConect_OnClicked(object sender, EventArgs e)
{
    activityIndicatorLogin.IsRunning = true;
    Task.Delay(1000).ContinueWith(t => TEST());
}

protected void TEST()
{
    activityIndicatorLogin.IsRunning = false;
    DisplayAlert("tiitle test", "messsage test", "close");
}
</code>```

The Activity Indicator runs correctly, it starts and stops as I want. But the alert isnt called! It doesnt throw any excpetions or something, but the alert pop-up doesnt appear!

Am i doing something wrong?

答:
Try this:
Has to be called from uithread + await the display alert or it might not appear.
(If this onclicked is fired from a control in your ui, dont worry about the the thread its running on)</p>

```<code>private async void BtnConect_OnClicked(object sender, EventArgs e)
{
    activityIndicatorLogin.IsRunning = true;
    await Task.Delay(1000);
    await TEST();
}

protected async Task TEST()
{
    activityIndicatorLogin.IsRunning = false;
    await DisplayAlert("tiitle test", "messsage test", "close");
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a code where, after a button click, i start running an Activity Indicator, then after some task, i stop it.

I would like to call a Display Alert function after it. Heres my code:

private void BtnConect_OnClicked(object sender, EventArgs e)
{
    activityIndicatorLogin.IsRunning = true;
    Task.Delay(1000).ContinueWith(t => TEST());
}

protected void TEST()
{
    activityIndicatorLogin.IsRunning = false;
    DisplayAlert("tiitle test", "messsage test", "close");
}

The Activity Indicator runs correctly, it starts and stops as I want. But the alert isnt called! It doesnt throw any excpetions or something, but the alert pop-up doesnt appear!

Am i doing something wrong?

Body:
Try this:
Has to be called from uithread + await the display alert or it might not appear.
(If this onclicked is fired from a control in your ui, dont worry about the the thread its running on)

private async void BtnConect_OnClicked(object sender, EventArgs e)
{
    activityIndicatorLogin.IsRunning = true;
    await Task.Delay(1000);
    await TEST();
}

protected async Task TEST()
{
    activityIndicatorLogin.IsRunning = false;
    await DisplayAlert("tiitle test", "messsage test", "close");
}


问:
Is it safe using `$` as an identifier in C/C++?
Is it safe to use $ character as part of identifier in C/C++?
Like this,

```<code>int $a = 10;
struct $b;
class $c;

void $d();
</code>```

答:
This is not standard and only Microsoft Visual Studio (that I know of) even allows the '$' character in identifiers.

So if you ever want your code to be portable (or readable to others), I'd say no.

ContentLicense: CC BY-SA 2.5

Body:
Is it safe to use $ character as part of identifier in C/C++?
Like this,

int $a = 10;
struct $b;
class $c;

void $d();


问:
Cannot resolve GoogleSignIn and GoogleSignInClient
I am not able to use GoogleSignIn(com.google.android.gms.auth.api.signin.GoogleSignIn
) and GoogleSignInClient(com.google.android.gms.auth.api.signin.GoogleSignInClient
) while implementing Google Sign In in Android Studio while I can access other classes in App like

```<code>com.google.android.gms.auth.api.signin.GoogleSignInAccount;
com.google.android.gms.auth.api.signin.GoogleSignInOptions;
com.google.android.gms.common.SignInButton;
</code>```

A strip down version of my build.gradle(app) file is as follow

```<code>android {

}

dependencies {

    compile 'com.google.android.gms:play-services-auth:11.4.2'
    compile('com.google.api-client:google-api-client-android:1.23.0') {
        exclude group: 'org.apache.httpcomponents'
    }
    compile('com.google.apis:google-api-services-gmail:v1-rev72-1.23.0') {
        exclude group: 'org.apache.httpcomponents'
    }
    implementation 'com.google.gms:google-services:3.1.2'
}

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

and my build.gradle(package) is

```<code>buildscript {

    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
        classpath 'com.google.gms:google-services:3.1.2'
    }
}
</code>```

Any help would be appreciated

答:
I was having the same issue

GoogleSignIn and GoogleSignInClient were introduced in version Google Play services SDK version 11.6. In older versions GoogleApiClient was used.

So try changing the compile 'com.google.android.gms:play-services-auth:11.4.2' to  'com.google.android.gms:play-services-auth:12.0.1' in dependencies

dependencies
{
compile 'com.google.android.gms:play-services-auth:12.0.1'
 }

Body:
I am not able to use GoogleSignIn(com.google.android.gms.auth.api.signin.GoogleSignIn
) and GoogleSignInClient(com.google.android.gms.auth.api.signin.GoogleSignInClient
) while implementing Google Sign In in Android Studio while I can access other classes in App like

com.google.android.gms.auth.api.signin.GoogleSignInAccount;
com.google.android.gms.auth.api.signin.GoogleSignInOptions;
com.google.android.gms.common.SignInButton;

A strip down version of my build.gradle(app) file is as follow

android {

}

dependencies {

    compile 'com.google.android.gms:play-services-auth:11.4.2'
    compile('com.google.api-client:google-api-client-android:1.23.0') {
        exclude group: 'org.apache.httpcomponents'
    }
    compile('com.google.apis:google-api-services-gmail:v1-rev72-1.23.0') {
        exclude group: 'org.apache.httpcomponents'
    }
    implementation 'com.google.gms:google-services:3.1.2'
}

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

and my build.gradle(package) is

buildscript {

    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
        classpath 'com.google.gms:google-services:3.1.2'
    }
}

Any help would be appreciated


问:
LINQ var as field/column in where clause
In my entity, I have some fields/columns named like "aaa", "bbb", "ccc", etc. Each can have the values "s" or "n".

For example, if I try this:

```<code>items = items.Where(p => p.aaa == "s");
</code>```

It will restrict the records to those with aaa having "s" (tested, it works).

I now need to pass a querystring with the name of the field to be searched.

```<code>var qsintervencao = Request.QueryString["intervencao"];

if (qsintervencao == "" || qsintervencao == null || qsintervencao == "all") {
    <a>TEST: </a> qsintervencao not set or set to all
} else {
    items = items.Where(p => p.@qsintervencao == "s");
    <a>TEST: </a> @qsintervencao
}
</code>```

The QS works, qsintervencao (and TEST) outputs the selected field (aaa or bbb), however no records are returned.

Is there any way to pass a var into the where clause?

答:
You can determine the related property dynamically by using Reflection like this;

```<code>  items = items.Where( p => p.GetType().GetProperties().FirstOrDefault(property => property.Name == qsintervencao).GetValue(p, null) == "s");
</code>```

Body:
In my entity, I have some fields/columns named like "aaa", "bbb", "ccc", etc. Each can have the values "s" or "n".

For example, if I try this:

items = items.Where(p => p.aaa == "s");

It will restrict the records to those with aaa having "s" (tested, it works).

I now need to pass a querystring with the name of the field to be searched.

var qsintervencao = Request.QueryString["intervencao"];

if (qsintervencao == "" || qsintervencao == null || qsintervencao == "all") {
    TEST:  qsintervencao not set or set to all
} else {
    items = items.Where(p => p.@qsintervencao == "s");
    TEST:  @qsintervencao
}

The QS works, qsintervencao (and TEST) outputs the selected field (aaa or bbb), however no records are returned.

Is there any way to pass a var into the where clause?

Body:
You can determine the related property dynamically by using Reflection like this;

  items = items.Where( p => p.GetType().GetProperties().FirstOrDefault(property => property.Name == qsintervencao).GetValue(p, null) == "s");


问:
Composer uses wrong openssl version
I have installed openssl@1.1 using brew and added the path to my bash-profile. From Terminal I run "which openssl" and it shows the correct location (as in my bash-profile). Also when I run "openssl version" is shows 1.1.0f so that is also correct.

But when I run "composer diagnose" I get the following warning:

The OpenSSL library (0.9.8y) used by PHP does not support TLSv1.2 or TLSv1.1.
  If possible you should upgrade OpenSSL to version 1.0.1 or above.

I also ran "composer show --platform" and it shows:

lib-openssl         0.9.8.25 OpenSSL 0.9.8y 5 Feb 2013

What do I need to do to get Composer to use the correct version of OpenSSL?

I'm running:
OSX 10.12.6,
MAMP PHP 7.0.0,
Composer 1.5.2,
Brew 1.3.5

Any help would be appreciated.

UPDATE:

I tried adding symlinks as mentioned in many of the offered threads:

```<code>ln -s /usr/local/opt/openssl@1.1/lib/libcrypto.1.1.dyli /usr/local/lib/
ln -s /usr/local/opt/openssl@1.1/lib/libssl.1.1.dylib /usr/local/lib/
</code>```

It didn't work. PHP still shows:

```<code>OpenSSL support => enabled
OpenSSL Library Version => OpenSSL 0.9.8zh 14 Jan 2016
OpenSSL Header Version => OpenSSL 0.9.8y 5 Feb 2013
Openssl default config => /System/Library/OpenSSL/openssl.cnf
</code>```

I first tried to symlink from /System/Library/OpenSSL but it wasn't permitted. Maybe I need to sudo it. Before I do that, are there any risks I should be aware of? Am I on the right path? It's very frustrating that some commands in Terminal point to the new openssl, while others don't.

答:
Check PHP version your Mac OS shipping. It should like PHP 5.6.

Try to upgrade your version of PHP to 7.0 or above.
And run command again check version on your current folder.

```<code>php -v

php -i | grep OpenSSL
</code>```

If the output of php -v still doesn’t echoes the version 7, type following command to update your path.

```<code>export PATH=/usr/local/php5/bin:$PATH
</code>```

Title: Composer uses wrong openssl version

Body:
I have installed openssl@1.1 using brew and added the path to my bash-profile. From Terminal I run "which openssl" and it shows the correct location (as in my bash-profile). Also when I run "openssl version" is shows 1.1.0f so that is also correct.

But when I run "composer diagnose" I get the following warning:

The OpenSSL library (0.9.8y) used by PHP does not support TLSv1.2 or TLSv1.1.
  If possible you should upgrade OpenSSL to version 1.0.1 or above.

I also ran "composer show --platform" and it shows:

lib-openssl         0.9.8.25 OpenSSL 0.9.8y 5 Feb 2013

What do I need to do to get Composer to use the correct version of OpenSSL?

I'm running:
OSX 10.12.6,
MAMP PHP 7.0.0,
Composer 1.5.2,
Brew 1.3.5

Any help would be appreciated.

UPDATE:

I tried adding symlinks as mentioned in many of the offered threads:

ln -s /usr/local/opt/openssl@1.1/lib/libcrypto.1.1.dyli /usr/local/lib/
ln -s /usr/local/opt/openssl@1.1/lib/libssl.1.1.dylib /usr/local/lib/

It didn't work. PHP still shows:

OpenSSL support => enabled
OpenSSL Library Version => OpenSSL 0.9.8zh 14 Jan 2016
OpenSSL Header Version => OpenSSL 0.9.8y 5 Feb 2013
Openssl default config => /System/Library/OpenSSL/openssl.cnf

I first tried to symlink from /System/Library/OpenSSL but it wasn't permitted. Maybe I need to sudo it. Before I do that, are there any risks I should be aware of? Am I on the right path? It's very frustrating that some commands in Terminal point to the new openssl, while others don't.

Body:
Check PHP version your Mac OS shipping. It should like PHP 5.6.

Try to upgrade your version of PHP to 7.0 or above.
And run command again check version on your current folder.

php -v

php -i | grep OpenSSL

If the output of php -v still doesn’t echoes the version 7, type following command to update your path.

export PATH=/usr/local/php5/bin:$PATH


问:
Swift - Date from components is incorrect when printed. Date has 2 values?
I'm trying to store a time of day in a Date:

```<code>let calendar = NSCalendar.init(identifier: .gregorian)
let components = NSDateComponents()
components.hour = 7
components.minute = 0

var newDate = calendar?.date(from: components as DateComponents)!

print(newDate!)
</code>```

However, this yields some bizarre results when I try to print or otherwise use the value. Here's a Swift Playground of the results:

How can newDate be both 7:00AM and 11:56AM at the same time?

答:
You didn't specify a time zone (by setting the timeZone property of either components or calendar). So the system used your local time zone to convert components to a date.

The playground system used your local time zone to convert newDate to the string “Jan 1, 1 at 7:00 AM”. (The playground system has special-case code for displaying Date objects. The special-case code uses your local time zone.)

The print function used the UTC time zone to convert newDate to the string “0001-01-01 11:56:02 +0000”.  (The print function uses the CustomStringConvertible protocol. Date's CustomStringConvertible implementation uses the UTC time zone.)

I deduce that your local time zone is US/Eastern time, also known as America/New_York:

```<code>import Foundation

var calendar = Calendar(identifier: .gregorian)
let components = NSDateComponents()
components.hour = 7
components.minute = 0

for timeZoneIdentifier in TimeZone.knownTimeZoneIdentifiers {
    calendar.timeZone = TimeZone(identifier: timeZoneIdentifier)!
    let date = calendar.date(from: components as DateComponents)!
    let dateString = "\(date)"
    if dateString == "0001-01-01 11:56:02 +0000" {
        print("\(timeZoneIdentifier) \(date)")
    }
}
// Only one line of output: America/New_York 0001-01-01 11:56:02 +0000
</code>```

So why the weird minutes and seconds in UTC?  Because at noon on November 18, 1883, the US and Canada railway companies began using a new, standard time system, which is the time system we still use today. Observe:

```<code>import Foundation

let formatter = ISO8601DateFormatter()

var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(identifier: "America/New_York")!
let components = NSDateComponents()

components.year = 1883
components.month = 11
components.day = 18

components.hour = 11
print(formatter.string(from: calendar.date(from: components as DateComponents)!))
// prints 1883-11-18T15:56:02Z

components.hour = 12
print(formatter.string(from: calendar.date(from: components as DateComponents)!))
// prints 1883-11-18T17:00:00Z
</code>```

Prior to noon, the difference from UTC time is 4:56:02.

Before the advent of standard railway time, we typically defined local time based on local apparent noon (the moment when the sun is highest in the sky and shadows point exactly north or south or disappear entirely if the sun is directly overhead).

If we look at the definition of America/New_York in the tz Time Zone Database, we find this:

# From Paul Eggert (2014-09-06):
# Monthly Notices of the Royal Astronomical Society 44, 4 (1884-02-08), 208
# says that New York City Hall time was 3 minutes 58.4 seconds fast of
# Eastern time (i.e., -4:56:01.6) just before the 1883 switch.  Round to the
# nearest second.
```

<p>and a bit further down:</p>

<pre class="lang-none prettyprint-override"><code>Zone America/New_York   -4:56:02 -  LMT 1883 Nov 18 12:03:58
</code>```

This explains the difference we see above prior to noon on November 18, 1883.

Body:
I'm trying to store a time of day in a Date:

let calendar = NSCalendar.init(identifier: .gregorian)
let components = NSDateComponents()
components.hour = 7
components.minute = 0

var newDate = calendar?.date(from: components as DateComponents)!

print(newDate!)

However, this yields some bizarre results when I try to print or otherwise use the value. Here's a Swift Playground of the results:

How can newDate be both 7:00AM and 11:56AM at the same time?

Body:
You didn't specify a time zone (by setting the timeZone property of either components or calendar). So the system used your local time zone to convert components to a date.

The playground system used your local time zone to convert newDate to the string “Jan 1, 1 at 7:00 AM”. (The playground system has special-case code for displaying Date objects. The special-case code uses your local time zone.)

The print function used the UTC time zone to convert newDate to the string “0001-01-01 11:56:02 +0000”.  (The print function uses the CustomStringConvertible protocol. Date's CustomStringConvertible implementation uses the UTC time zone.)

I deduce that your local time zone is US/Eastern time, also known as America/New_York:

import Foundation

var calendar = Calendar(identifier: .gregorian)
let components = NSDateComponents()
components.hour = 7
components.minute = 0

for timeZoneIdentifier in TimeZone.knownTimeZoneIdentifiers {
    calendar.timeZone = TimeZone(identifier: timeZoneIdentifier)!
    let date = calendar.date(from: components as DateComponents)!
    let dateString = "\(date)"
    if dateString == "0001-01-01 11:56:02 +0000" {
        print("\(timeZoneIdentifier) \(date)")
    }
}
// Only one line of output: America/New_York 0001-01-01 11:56:02 +0000

So why the weird minutes and seconds in UTC?  Because at noon on November 18, 1883, the US and Canada railway companies began using a new, standard time system, which is the time system we still use today. Observe:

import Foundation

let formatter = ISO8601DateFormatter()

var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(identifier: "America/New_York")!
let components = NSDateComponents()

components.year = 1883
components.month = 11
components.day = 18

components.hour = 11
print(formatter.string(from: calendar.date(from: components as DateComponents)!))
// prints 1883-11-18T15:56:02Z

components.hour = 12
print(formatter.string(from: calendar.date(from: components as DateComponents)!))
// prints 1883-11-18T17:00:00Z

Prior to noon, the difference from UTC time is 4:56:02.

Before the advent of standard railway time, we typically defined local time based on local apparent noon (the moment when the sun is highest in the sky and shadows point exactly north or south or disappear entirely if the sun is directly overhead).

If we look at the definition of America/New_York in the tz Time Zone Database, we find this:

# From Paul Eggert (2014-09-06):
# Monthly Notices of the Royal Astronomical Society 44, 4 (1884-02-08), 208
# says that New York City Hall time was 3 minutes 58.4 seconds fast of
# Eastern time (i.e., -4:56:01.6) just before the 1883 switch.  Round to the
# nearest second.

and a bit further down:

Zone America/New_York   -4:56:02 -  LMT 1883 Nov 18 12:03:58

This explains the difference we see above prior to noon on November 18, 1883.


问:
C++ filling array of structure from file
Hi I need to read a file and get data from file to array of structure.

Structure

```<code>struct Activity {
    string ID;
    string Name;
    string quantity; };
</code>```

I have this function for reading from file

```<code>int* fillStructure(ifstream &fileActivity){

    int i=0;
    int numberOfElements = numberOfLines(fileActivity);

    Activity* myActivity = new Activity[numberOfElements];

    while (i < numberOfElements)
    {
          getline(fileActivity, myAktivity[i].ID, ',');
          getline(fileActivity, myActivity[i].Name, ',');
          getline(fileActivity, myActivity[i].quantity, '\n');
          i++;
    }

   fileActivity.close();
   return myActivity; }
</code>```

And when i try in main function to print members of structures It doesnt work

```<code>int main(){

    if (!(fileActivity.is_open())){
        cout << "Error when reading file" << endl;
        return 0;
    }

    fillStructure(fileActivity);

    cout << myActivity[1].ID << endl; return 0;  }
</code>```

I am beginner, can you guys help me what I am doing wrong ?

答:
You have to declare your return value in the main function.

```<code>struct Activity {
string ID;
string Name;
string quantitiy;
};

Activity* fillStructure(ifstream &fileActivity) {

int i = 0;
int numberOfElements = numberOfLines(fileActivity);
Activity* myActivity = new Activity[numberOfElements];

while (i < numberOfElements)
{
    getline(fileActivity, myActivity[i].ID, ',');
    getline(fileActivity, myActivity[i].Name, ',');
    getline(fileActivity, myActivity[i].quantitiy, '\n');
    i++;
}

fileActivity.close();

return myActivity;
}

int main(){

ifstream fileActivity ("test.txt", ifstream::in);
Activity* retFile;

retFile = fillStructure(fileActivity);

cout << retFile[1].ID << endl;

return 0;
}
</code>```

Declare the return Type of the fillStructure function in the main function like this:

```<code>Activity* retFile;
</code>```

This codesnippet works for me

Body:
Hi I need to read a file and get data from file to array of structure.

Structure

struct Activity {
    string ID;
    string Name;
    string quantity; };

I have this function for reading from file

int* fillStructure(ifstream &fileActivity){

    int i=0;
    int numberOfElements = numberOfLines(fileActivity);

    Activity* myActivity = new Activity[numberOfElements];

    while (i < numberOfElements)
    {
          getline(fileActivity, myAktivity[i].ID, ',');
          getline(fileActivity, myActivity[i].Name, ',');
          getline(fileActivity, myActivity[i].quantity, '\n');
          i++;
    }

   fileActivity.close();
   return myActivity; }

And when i try in main function to print members of structures It doesnt work

int main(){

    if (!(fileActivity.is_open())){
        cout << "Error when reading file" << endl;
        return 0;
    }

    fillStructure(fileActivity);

    cout << myActivity[1].ID << endl; return 0;  }

I am beginner, can you guys help me what I am doing wrong ?

Body:
You have to declare your return value in the main function.

struct Activity {
string ID;
string Name;
string quantitiy;
};

Activity* fillStructure(ifstream &fileActivity) {

int i = 0;
int numberOfElements = numberOfLines(fileActivity);
Activity* myActivity = new Activity[numberOfElements];

while (i < numberOfElements)
{
    getline(fileActivity, myActivity[i].ID, ',');
    getline(fileActivity, myActivity[i].Name, ',');
    getline(fileActivity, myActivity[i].quantitiy, '\n');
    i++;
}

fileActivity.close();

return myActivity;
}

int main(){

ifstream fileActivity ("test.txt", ifstream::in);
Activity* retFile;

retFile = fillStructure(fileActivity);

cout << retFile[1].ID << endl;

return 0;
}

Declare the return Type of the fillStructure function in the main function like this:

Activity* retFile;

This codesnippet works for me


问:
How do I create an empty op_array?
In my PHP extension, how can I create an op_array with no opcodes in it?</p>

答:
You can use init_op_array(), declared in from zend_compile.h:

```<code>zend_op_array * op_array = emalloc(sizeof(zend_op_array));
init_op_array(op_array, type, INITIAL_OP_ARRAY_SIZE TSRMLS_CC);
</code>```

type can be ZEND_EVAL_CODE or ZEND_USER_FUNCTION.

Title: How do I create an empty op_array?

Body:
You can use init_op_array(), declared in from zend_compile.h:

zend_op_array * op_array = emalloc(sizeof(zend_op_array));
init_op_array(op_array, type, INITIAL_OP_ARRAY_SIZE TSRMLS_CC);

type can be ZEND_EVAL_CODE or ZEND_USER_FUNCTION.


问:
WebGL: Invalid Image when loading 8-bit grayscale image to texture
I am trying to render an 8-bit grayscale JPG downloaded from my server into a texture to render with WebGL.

```<code>// Pretend for the sake of example that I have passed in an argument
// 'img' that is an Image object that I used to download the jpg.
// See the EDIT below for how this happens...

// ...also presume that I have set up my WebGL context and assigned it
// to the variable 'gl':
// const gl = canvas.getContext('experimental-webgl');

const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);

// Set the parameters so we can render any size image.
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);

// Upload the image into the texture.
gl.texImage2D(gl.TEXTURE_2D, 0, gl.LUMINANCE, gl.LUMINANCE, gl.UNSIGNED_BYTE, img);
</code>```

At this point, WebGL slaps me in the face and takes my lunch money:

```<code>WebGL: INVALID_VALUE: texImage2D: invalid image
</code>```

and I am left to ask: WHAT MOAR U WANT WebGL?? WHY NOT U JUST B HAPPY???

I'm probably missing something basic, but the internets are a mess with WebGL stuff that doesn't answer my question. Can any WebGL gurus here advise?

Here is the image:

EDIT:

Here are some more details about how the image is obtained. Note: the reason for doing it this way is that I need a download queue that I can shuffle, cancel, and restart, ad nauseam. Hence the use of fetch, blobs, and object URLs. This whole thing is part of a deep-zoom image viewer that should efficiently load only the image tiles visible in the viewport (which often changes moment to moment). Anyway, here's how I get the image:

```<code>// Take care of vendor prefixes:
window.URL = window.URL || window.webkitURL;

// This is where we'll assign our final product
const imageTag = new Image();

imageTag.onerror = (err) => {
  console.error('IMG ERROR:', err);
};
imageTag.onload = () => {
  // Once the image tag has loaded the blob data, clean up our object url:
  window.URL.revokeObjectURL(imageTag.src);

  // imageTag is now passed into the code above as 'img'
};

// Grab the image data as a blob
fetch(`<url_of_image>`)
  .then(res => res.blob())
  .then(blob => {
    // When we get the image data, wrap it in an object url and assign
    // it to src. The onload event won't fire until the next tick.
    imageTag.src = window.URL.createObjectURL(blob);
  });
</code>```

I should point out that I was originally rendering using the canvas2D API, and that it was able to draw the images just fine using the drawImage() method. So I'm pretty sure the images objects are loading ok.  My reason for implementing a WebGL renderer is to open the door to greater performance enhancements.

Thanks for looking!

答: From the search through Chromium codebase for the error message string and looking at revokeObjectURL reference it seems that it is the culprit. The image content represented by image URL simply gets "freed" to early. The solution would be to call revokeObjectURL after calling texImage2D.

Body:
I am trying to render an 8-bit grayscale JPG downloaded from my server into a texture to render with WebGL.

// Pretend for the sake of example that I have passed in an argument
// 'img' that is an Image object that I used to download the jpg.
// See the EDIT below for how this happens...

// ...also presume that I have set up my WebGL context and assigned it
// to the variable 'gl':
// const gl = canvas.getContext('experimental-webgl');

const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);

// Set the parameters so we can render any size image.
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);

// Upload the image into the texture.
gl.texImage2D(gl.TEXTURE_2D, 0, gl.LUMINANCE, gl.LUMINANCE, gl.UNSIGNED_BYTE, img);

At this point, WebGL slaps me in the face and takes my lunch money:

WebGL: INVALID_VALUE: texImage2D: invalid image

and I am left to ask: WHAT MOAR U WANT WebGL?? WHY NOT U JUST B HAPPY???

I'm probably missing something basic, but the internets are a mess with WebGL stuff that doesn't answer my question. Can any WebGL gurus here advise?

Here is the image:

EDIT:

Here are some more details about how the image is obtained. Note: the reason for doing it this way is that I need a download queue that I can shuffle, cancel, and restart, ad nauseam. Hence the use of fetch, blobs, and object URLs. This whole thing is part of a deep-zoom image viewer that should efficiently load only the image tiles visible in the viewport (which often changes moment to moment). Anyway, here's how I get the image:

// Take care of vendor prefixes:
window.URL = window.URL || window.webkitURL;

// This is where we'll assign our final product
const imageTag = new Image();

imageTag.onerror = (err) => {
  console.error('IMG ERROR:', err);
};
imageTag.onload = () => {
  // Once the image tag has loaded the blob data, clean up our object url:
  window.URL.revokeObjectURL(imageTag.src);

  // imageTag is now passed into the code above as 'img'
};

// Grab the image data as a blob
fetch(`<url_of_image>`)
  .then(res => res.blob())
  .then(blob => {
    // When we get the image data, wrap it in an object url and assign
    // it to src. The onload event won't fire until the next tick.
    imageTag.src = window.URL.createObjectURL(blob);
  });

I should point out that I was originally rendering using the canvas2D API, and that it was able to draw the images just fine using the drawImage() method. So I'm pretty sure the images objects are loading ok.  My reason for implementing a WebGL renderer is to open the door to greater performance enhancements.

Thanks for looking!


问:
EXCEL: SUMPRODUCTS with operator
I am trying to include an operator in a SUMPRODUCTS formula, however I keep getting a #VALUE error. I am trying to divide by a value instead of multiple by it. For example instead of multiple by 3, I want to multiply by 1/3.

The following formula works perfectly:

```<code>= SUMPRODUCT(('Sheet1'!J:J="Example")+0;('Sheet1'!M:M=F$73)+0;'Sheet1'!G:G;'Sheet1'!N:N;INT('Sheet1'!$Q:$Q>=$A74);INT('Sheet1'!$Q:$Q<=EOMONTH($A74;0));'Sheet1'!K:K)
</code>```

However, once I attempt to divide by column K instead of multiplying, I get the error. I tried to following formulas:

```<code>= SUMPRODUCT(('Sheet1'!J:J="Example")+0;('Sheet1'!M:M=F$73)+0;'Sheet1'!G:G;'Sheet1'!N:N;INT('Sheet1'!$Q:$Q>=$A74);INT('Sheet1'!$Q:$Q<=EOMONTH($A74;0));MINVERSE('Sheet1'!K:K))

= SUMPRODUCT(('Sheet1'!J:J="Example")+0;('Sheet1'!M:M=F$73)+0;'Sheet1'!G:G;'Sheet1'!N:N;INT('Sheet1'!$Q:$Q>=$A74);INT('Sheet1'!$Q:$Q<=EOMONTH($A74;0));('Sheet1'!K:K)^-1)

= SUMPRODUCT(('Sheet1'!J:J="Example")+0;('Sheet1'!M:M=F$73)+0;'Sheet1'!G:G;'Sheet1'!N:N;INT('Sheet1'!$Q:$Q>=$A74);INT('Sheet1'!$Q:$Q<=EOMONTH($A74;0));1/('Sheet1'!K:K))
</code>```

Any suggestions how I could do that?

Thanks in advance!

答:
The error is presumably caused by dividing by zero for blanks in column K. If you restrict the range to only the rows with data your formula may work as it stands if there are no zeroes or blanks in the column K range.

Alternatively try using IFERROR and ideally restricting the range, e.g. restricted to 1,000 rows

=SUMPRODUCT(('Sheet1'!J$2:J$1000="Example")*('Sheet1'!M$2:M$1000=F$73)*('Sheet1'!$Q$2:$Q$1000>=$A74)*('Sheet1'!$Q$2:$Q$1000<=EOMONTH($A74;0));'Sheet1'!G$2:G$1000;'Sheet1'!N$2:N$1000;IFERROR(1/'Sheet1'!K$2:K$1000,0))

confirm with CTRL+SHIFT+ENTER

Title: EXCEL: SUMPRODUCTS with operator

Body:
I am trying to include an operator in a SUMPRODUCTS formula, however I keep getting a #VALUE error. I am trying to divide by a value instead of multiple by it. For example instead of multiple by 3, I want to multiply by 1/3.

The following formula works perfectly:

= SUMPRODUCT(('Sheet1'!J:J="Example")+0;('Sheet1'!M:M=F$73)+0;'Sheet1'!G:G;'Sheet1'!N:N;INT('Sheet1'!$Q:$Q>=$A74);INT('Sheet1'!$Q:$Q<=EOMONTH($A74;0));'Sheet1'!K:K)

However, once I attempt to divide by column K instead of multiplying, I get the error. I tried to following formulas:

= SUMPRODUCT(('Sheet1'!J:J="Example")+0;('Sheet1'!M:M=F$73)+0;'Sheet1'!G:G;'Sheet1'!N:N;INT('Sheet1'!$Q:$Q>=$A74);INT('Sheet1'!$Q:$Q<=EOMONTH($A74;0));MINVERSE('Sheet1'!K:K))

= SUMPRODUCT(('Sheet1'!J:J="Example")+0;('Sheet1'!M:M=F$73)+0;'Sheet1'!G:G;'Sheet1'!N:N;INT('Sheet1'!$Q:$Q>=$A74);INT('Sheet1'!$Q:$Q<=EOMONTH($A74;0));('Sheet1'!K:K)^-1)

= SUMPRODUCT(('Sheet1'!J:J="Example")+0;('Sheet1'!M:M=F$73)+0;'Sheet1'!G:G;'Sheet1'!N:N;INT('Sheet1'!$Q:$Q>=$A74);INT('Sheet1'!$Q:$Q<=EOMONTH($A74;0));1/('Sheet1'!K:K))

Any suggestions how I could do that?

Thanks in advance!


问:
Titanic dataset in R
I am trying to work in a problem for the "Titanic" dataset in R.

In this data, the last column gives the frequency of observations ('freq' column).
For example- the third row says that frequency = 35, which means that this particular row will be repeated 35 times.

I am therefore coding a new data frame in which all the rows which have a frequency > 0 are printed those many times (row number 3 is appended in the new data frame, 35 times).

The total number of rows in the new data frame = 2201, which is the sum of all values in frequency column.

I have used a character vector of length 2201 to store all the values for the first column "Class" in which I am appending the values.

I have written the following code-

```<code>data(Titanic)
# View(Titanic)

# create a data frame out of 'Titanic' data frame-
T <- as.data.frame(Titanic, stringsAsFactors = FALSE)

# cat("Total # of observations - ", sum(T$Freq))    # O/P = 2201
n <- sum(T$Freq)

# full_titanic <- data.frame(Class = character(n), Sex = character(n), Age = character(n), Survived = character(n), stringsAsFactors=FALSE)

full_Class <- character(n)  # create an array of 2201 character objects

for(i in 1:nrow(T))
{
    if(T$Freq[i] > 0)
    {
        cnt = T$Freq[i]
        # repeating_val <- T$Class[i]
        j <- 0

        while(j < cnt)
        {
            # full_Class[i] <- repeating_val
            full_Class[i + j] <- T$Class[i]
            # cat("T$Class[", i, "] = ", T$Class[i], "\n")
            # cat("Repeating for i = ", i, "\n")
            j <- j + 1
        }
    }
    else
    {
        full_Class[i] <- T$Class[i]
    }

    # cat("i = ", i, "\n")
}
</code>```

However, this code is leaving a lot of blanks in the character vector 'full_Class' when I print it.

I am able to see the discrepancy as-

```<code>table(full_Class) # shows the sum of all classes = 1520

sum(T$Freq[T$Class == "1st"]) # equals 325

sum(T$Freq[T$Class == "2nd"]) # equals 285

sum(T$Freq[T$Class == "3rd"]) # equals 706

sum(T$Freq[T$Class == "Crew"]) # equals 885

(325 - 67) + (285 - 11) + (706 - 63) + (885 - 540) # equalss 1520
</code>```

What's going wrong ?

Thanks!

答:
Does this help?

```<code>T1<-T[T$Freq==0,] # data with zero frequency
T2<-T[rep(row.names(T),T$Freq),] #data with nonzero frequency
T3<-rbind(T1,T2) #full data
rownames(T3) <- 1:nrow(T3) #reset row index of full data
</code>```

The output

> head(T3,20)
   Class    Sex   Age Survived Freq
1    1st   Male Child       No    0
2    2nd   Male Child       No    0
3   Crew   Male Child       No    0
4    1st Female Child       No    0
5    2nd Female Child       No    0
6   Crew Female Child       No    0
7   Crew   Male Child      Yes    0
8   Crew Female Child      Yes    0
9    3rd   Male Child       No   35
10   3rd   Male Child       No   35
11   3rd   Male Child       No   35
12   3rd   Male Child       No   35
13   3rd   Male Child       No   35
14   3rd   Male Child       No   35
15   3rd   Male Child       No   35
16   3rd   Male Child       No   35
17   3rd   Male Child       No   35
18   3rd   Male Child       No   35
19   3rd   Male Child       No   35
20   3rd   Male Child       No   35

Title: Titanic dataset in R

Body:
I am trying to work in a problem for the "Titanic" dataset in R.

In this data, the last column gives the frequency of observations ('freq' column).
For example- the third row says that frequency = 35, which means that this particular row will be repeated 35 times.

I am therefore coding a new data frame in which all the rows which have a frequency > 0 are printed those many times (row number 3 is appended in the new data frame, 35 times).

The total number of rows in the new data frame = 2201, which is the sum of all values in frequency column.

I have used a character vector of length 2201 to store all the values for the first column "Class" in which I am appending the values.

I have written the following code-

data(Titanic)
# View(Titanic)

# create a data frame out of 'Titanic' data frame-
T <- as.data.frame(Titanic, stringsAsFactors = FALSE)

# cat("Total # of observations - ", sum(T$Freq))    # O/P = 2201
n <- sum(T$Freq)

# full_titanic <- data.frame(Class = character(n), Sex = character(n), Age = character(n), Survived = character(n), stringsAsFactors=FALSE)

full_Class <- character(n)  # create an array of 2201 character objects

for(i in 1:nrow(T))
{
    if(T$Freq[i] > 0)
    {
        cnt = T$Freq[i]
        # repeating_val <- T$Class[i]
        j <- 0

        while(j < cnt)
        {
            # full_Class[i] <- repeating_val
            full_Class[i + j] <- T$Class[i]
            # cat("T$Class[", i, "] = ", T$Class[i], "\n")
            # cat("Repeating for i = ", i, "\n")
            j <- j + 1
        }
    }
    else
    {
        full_Class[i] <- T$Class[i]
    }

    # cat("i = ", i, "\n")
}

However, this code is leaving a lot of blanks in the character vector 'full_Class' when I print it.

I am able to see the discrepancy as-

table(full_Class) # shows the sum of all classes = 1520

sum(T$Freq[T$Class == "1st"]) # equals 325

sum(T$Freq[T$Class == "2nd"]) # equals 285

sum(T$Freq[T$Class == "3rd"]) # equals 706

sum(T$Freq[T$Class == "Crew"]) # equals 885

(325 - 67) + (285 - 11) + (706 - 63) + (885 - 540) # equalss 1520

What's going wrong ?

Thanks!

Body:
Does this help?

T1<-T[T$Freq==0,] # data with zero frequency
T2<-T[rep(row.names(T),T$Freq),] #data with nonzero frequency
T3<-rbind(T1,T2) #full data
rownames(T3) <- 1:nrow(T3) #reset row index of full data

The output

> head(T3,20)
   Class    Sex   Age Survived Freq
1    1st   Male Child       No    0
2    2nd   Male Child       No    0
3   Crew   Male Child       No    0
4    1st Female Child       No    0
5    2nd Female Child       No    0
6   Crew Female Child       No    0
7   Crew   Male Child      Yes    0
8   Crew Female Child      Yes    0
9    3rd   Male Child       No   35
10   3rd   Male Child       No   35
11   3rd   Male Child       No   35
12   3rd   Male Child       No   35
13   3rd   Male Child       No   35
14   3rd   Male Child       No   35
15   3rd   Male Child       No   35
16   3rd   Male Child       No   35
17   3rd   Male Child       No   35
18   3rd   Male Child       No   35
19   3rd   Male Child       No   35
20   3rd   Male Child       No   35


问:
Using @Column and @Formula in Hibernate at the same time
I've got a POJO and currently I'm getting a value from a single column. However, I'm moving to retrieve it using Hibernate @Formula (I select the latest record from another table). I want to go softly in order not to break anything.

So what I want to do is something like this:

```<code>class SomeDto {
    private someField;

    @Column("PREVIOUS_FIELD_COLUMN", nullable = false, length = 1)
    @Formula("@NEW RETRIEVING LOGIC@")
    public getSomeField() {
    ...
}
</code>```

so that I could be able to store the someField value in the PREVIOUS_FIELD_COLUMN and at the same time retrieve the value based on the new criteria.

However now it seems that Hibernate ignores the @Column annotation as I get the following error:

SQLIntegrityConstraintViolationException: ORA-01400: cannot insert
  NULL into

I see in logs that Hibernate skips PREVIOUS_FIELD_COLUMN in the insert statement being generated (doesn't list it and doesn't set the value from POJO).

Any help appreciated, thank you very much!

答:
You could elect to just remap the previous value to a new field so it continues to be persisted for old records and you remap the old value to your @Formula logic.

```<code>public class SomeEntity {
  @Formula("your new formula logic");
  public Object getSomeField() {}

  @Column(name= "PREVIOUS_VALUE")
  public Object getPreviousValue() {}
}
</code>```

Your post sounds like all you're concerned with technically is allowing your application to still interact with the object in the same way but you wish to source the value from somewhere else; however, being able to preserve access to and storage of the old value.

The above solution allows just that.

Body:
I've got a POJO and currently I'm getting a value from a single column. However, I'm moving to retrieve it using Hibernate @Formula (I select the latest record from another table). I want to go softly in order not to break anything.

So what I want to do is something like this:

class SomeDto {
    private someField;

    @Column("PREVIOUS_FIELD_COLUMN", nullable = false, length = 1)
    @Formula("@NEW RETRIEVING LOGIC@")
    public getSomeField() {
    ...
}

so that I could be able to store the someField value in the PREVIOUS_FIELD_COLUMN and at the same time retrieve the value based on the new criteria.

However now it seems that Hibernate ignores the @Column annotation as I get the following error:

SQLIntegrityConstraintViolationException: ORA-01400: cannot insert
  NULL into

I see in logs that Hibernate skips PREVIOUS_FIELD_COLUMN in the insert statement being generated (doesn't list it and doesn't set the value from POJO).

Any help appreciated, thank you very much!

Body:
You could elect to just remap the previous value to a new field so it continues to be persisted for old records and you remap the old value to your @Formula logic.

public class SomeEntity {
  @Formula("your new formula logic");
  public Object getSomeField() {}

  @Column(name= "PREVIOUS_VALUE")
  public Object getPreviousValue() {}
}

Your post sounds like all you're concerned with technically is allowing your application to still interact with the object in the same way but you wish to source the value from somewhere else; however, being able to preserve access to and storage of the old value.

The above solution allows just that.


问:
alertDialogBuilder crashes only when relaunching the APP
I have a "alertDialogBuilder" to rename an entry when a button is pressed. This works fine when the App is freshly opened. But If I press the back button (meaning the App is minimized and I am back at the Android home-screen), when I relaunch the App and press the button, this time the APP crashes. This happens every time and I have no idea how to debug this. I have checked the lifecycle and "onPause" and "onStop" are called when pressing the back button. But I don't see why that should be a problem.

Any ideas?

Here is the code where I launch the prompt dialogue in a helper class:

```<code>public void loadPromptInput(Context promptcontext, final OnOkGetText onOk, String InitialTxt) {

    //pathText.setText("Prompt input");
    LayoutInflater li = LayoutInflater.from(promptcontext);
    View promptsView = li.inflate(R.layout.prompts_dialog, null);
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( promptcontext);

    // set prompts.xml to alertdialog builder
    alertDialogBuilder.setView(promptsView);

    final EditText userInput = (EditText) promptsView
            .findViewById(R.id.editTextDialogUserInput);
    userInput.setText("");
    userInput.append(InitialTxt);
      alertDialogBuilder
            .setCancelable(false)
            .setPositiveButton("OK",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {

                            onOk.hereIsYouText(userInput.getText().toString());
                        }
                    })
            .setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });

    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();

    // show it
    alertDialog.show();

    // make the keyboard shown by default
    alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
</code>```

E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com...., PID: 31622
                                                                                android.view.WindowManager$BadTokenException: Unable to add window --
  token android.os.BinderProxy@423c9940 is not valid; is your activity
  running?
                                                                                at android.view.ViewRootImpl.setView(ViewRootImpl.java:532)
                                                                                at
  android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:259)
                                                                                at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
                                                                                at android.app.Dialog.show(Dialog.java:286)
                                                                                at
  com....myUtils.loadPromptInput(myUtils.java:71)
                                                                                at
  com....MainActivity$6.onReceive(MainActivity.java:557)
                                                                                at
  android.support.v4.content.LocalBroadcastManager.executePendingBroadcasts(LocalBroadcastManager.java:308)
                                                                                at
  android.support.v4.content.LocalBroadcastManager.access$000(LocalBroadcastManager.java:46)
                                                                                at
  android.support.v4.content.LocalBroadcastManager$1.handleMessage(LocalBroadcastManager.java:118)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:136)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5095)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:515)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
                                                                                at
  com.zte.heartyservice.SCC.FrameworkBridge.main(FrameworkBridge.java:136)
                                                                                at dalvik.system.NativeStart.main(Native Meth

od)

答:
It would be helpful looking at your code to see where you call:

void loadPromptInput(Context promptcontext...

...most probably you are passing as parameter an instance of a context no more valid.

In any case before calling your method check if the activity is finishing:

```<code>//in a fragment
if(getActivity() != null && !getActivity().isFinishing()) {
    loadPromptInput(getActivity()...
}

//in an activity
if(!isFinishing()) {
    loadPromptInput(this...
}
</code>```

Body:
I have a "alertDialogBuilder" to rename an entry when a button is pressed. This works fine when the App is freshly opened. But If I press the back button (meaning the App is minimized and I am back at the Android home-screen), when I relaunch the App and press the button, this time the APP crashes. This happens every time and I have no idea how to debug this. I have checked the lifecycle and "onPause" and "onStop" are called when pressing the back button. But I don't see why that should be a problem.

Any ideas?

Here is the code where I launch the prompt dialogue in a helper class:

public void loadPromptInput(Context promptcontext, final OnOkGetText onOk, String InitialTxt) {

    //pathText.setText("Prompt input");
    LayoutInflater li = LayoutInflater.from(promptcontext);
    View promptsView = li.inflate(R.layout.prompts_dialog, null);
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( promptcontext);

    // set prompts.xml to alertdialog builder
    alertDialogBuilder.setView(promptsView);

    final EditText userInput = (EditText) promptsView
            .findViewById(R.id.editTextDialogUserInput);
    userInput.setText("");
    userInput.append(InitialTxt);
      alertDialogBuilder
            .setCancelable(false)
            .setPositiveButton("OK",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {

                            onOk.hereIsYouText(userInput.getText().toString());
                        }
                    })
            .setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });

    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();

    // show it
    alertDialog.show();

    // make the keyboard shown by default
    alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}

E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com...., PID: 31622
                                                                                android.view.WindowManager$BadTokenException: Unable to add window --
  token android.os.BinderProxy@423c9940 is not valid; is your activity
  running?
                                                                                at android.view.ViewRootImpl.setView(ViewRootImpl.java:532)
                                                                                at
  android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:259)
                                                                                at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
                                                                                at android.app.Dialog.show(Dialog.java:286)
                                                                                at
  com....myUtils.loadPromptInput(myUtils.java:71)
                                                                                at
  com....MainActivity$6.onReceive(MainActivity.java:557)
                                                                                at
  android.support.v4.content.LocalBroadcastManager.executePendingBroadcasts(LocalBroadcastManager.java:308)
                                                                                at
  android.support.v4.content.LocalBroadcastManager.access$000(LocalBroadcastManager.java:46)
                                                                                at
  android.support.v4.content.LocalBroadcastManager$1.handleMessage(LocalBroadcastManager.java:118)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:136)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5095)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:515)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
                                                                                at
  com.zte.heartyservice.SCC.FrameworkBridge.main(FrameworkBridge.java:136)
                                                                                at dalvik.system.NativeStart.main(Native Meth

od)

Body:
It would be helpful looking at your code to see where you call:

void loadPromptInput(Context promptcontext...

...most probably you are passing as parameter an instance of a context no more valid.

In any case before calling your method check if the activity is finishing:

//in a fragment
if(getActivity() != null && !getActivity().isFinishing()) {
    loadPromptInput(getActivity()...
}

//in an activity
if(!isFinishing()) {
    loadPromptInput(this...
}


问:
Create a PHP Class Outline
I am looking for a function or class that can effectively outline a class:

```<code>class MyClass{

  /*
  * Perhaps include the function comments
  * in the function.
  */
  function mainFunction(){
    //Does Something
  }

  function functionWithArgs($arg1,$arg2=false){
    //Does Something
    //The function I want will give e the arguments w/default values
  }

}
</code>```

Is there a function or library in existence that can give me some kind of access to the information about this class, or even the file.

ex.

get_file_outline('fileWithAboveClass.php');

or

get_class_outline('MyClass');

Does anybody know of either, or know a way of easily writing this?

答:
Take a look at the PHP Reflection API

```<code>//use the ReflectionClass to find out about MyClass
$classInfo = new ReflectionClass('MyClass');

//then you can find out pretty much anything you want to know...
$methods = $classInfo->getMethods();
var_dump($methods);

//you can even extract your comments, e.g.
$comment=$classInfo->getMethod('mainFunction')->getDocComment();
</code>```

Note that for the comment extraction to work, they have to be formatted like PHPDoc / Doxygen comments, and begin with an opening /**

Title: Create a PHP Class Outline

Body:
I am looking for a function or class that can effectively outline a class:

class MyClass{

  /*
  * Perhaps include the function comments
  * in the function.
  */
  function mainFunction(){
    //Does Something
  }

  function functionWithArgs($arg1,$arg2=false){
    //Does Something
    //The function I want will give e the arguments w/default values
  }

}

Is there a function or library in existence that can give me some kind of access to the information about this class, or even the file.

ex.

get_file_outline('fileWithAboveClass.php');

or

get_class_outline('MyClass');

Does anybody know of either, or know a way of easily writing this?

Body:
Take a look at the PHP Reflection API

//use the ReflectionClass to find out about MyClass
$classInfo = new ReflectionClass('MyClass');

//then you can find out pretty much anything you want to know...
$methods = $classInfo->getMethods();
var_dump($methods);

//you can even extract your comments, e.g.
$comment=$classInfo->getMethod('mainFunction')->getDocComment();

Note that for the comment extraction to work, they have to be formatted like PHPDoc / Doxygen comments, and begin with an opening /**


问:
django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured
I want to connect MySQL database to my django project, but it is throwing an error :

"django.core.exceptions.ImproperlyConfigured: Requested setting
  USE_I18N, but settings are not configured. You must either define the
  environment variable DJANGO_SETTINGS_MODULE or call
  settings.configure() before accessing settings."

Trace:

```<code> (myenv) LIBINGLADWINs-MacBook-Air:libinrenold$ django-admin dbshell
Traceback (most recent call last):
  File "/Users/libinrenold/Desktop/djangoworks/myenv/bin/django-admin", line 11, in <module>
    sys.exit(execute_from_command_line())
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
    utility.execute()
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/base.py", line 322, in execute
    saved_locale = translation.get_language()
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/utils/translation/__init__.py", line 195, in get_language
    return _trans.get_language()
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/utils/translation/__init__.py", line 59, in __getattr__
    if settings.USE_I18N:
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__
    self._setup(name)
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/conf/__init__.py", line 39, in _setup
    % (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
</code>```

settings.py.

```<code>  DATABASES = {
        'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'test',
        'USER': 'user',
        'PASSWORD': 'root',
        'HOST':'',
        'PORT': '',
        }
     }
</code>```

答:
You must define the relevant variable to show where your settings.py file lives:

```<code>export DJANGO_SETTINGS_MODULE=mysite.settings
</code>```

This is the relevant docs entry:

When you use Django, you have to tell it which settings you’re using.
Do this by using an environment variable, DJANGO_SETTINGS_MODULE.

The value of DJANGO_SETTINGS_MODULE should be in Python path syntax,
e.g. mysite.settings. Note that the settings module should be on the
Python import search path.

If you are using a virtualenv (which is the best practice), you can paste the relevant export command in the file <path-to-virtualenv>/bin/activate

Body:
I want to connect MySQL database to my django project, but it is throwing an error :

"django.core.exceptions.ImproperlyConfigured: Requested setting
  USE_I18N, but settings are not configured. You must either define the
  environment variable DJANGO_SETTINGS_MODULE or call
  settings.configure() before accessing settings."

Trace:

 (myenv) LIBINGLADWINs-MacBook-Air:libinrenold$ django-admin dbshell
Traceback (most recent call last):
  File "/Users/libinrenold/Desktop/djangoworks/myenv/bin/django-admin", line 11, in <module>
    sys.exit(execute_from_command_line())
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
    utility.execute()
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/base.py", line 322, in execute
    saved_locale = translation.get_language()
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/utils/translation/__init__.py", line 195, in get_language
    return _trans.get_language()
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/utils/translation/__init__.py", line 59, in __getattr__
    if settings.USE_I18N:
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__
    self._setup(name)
  File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/conf/__init__.py", line 39, in _setup
    % (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

settings.py.

  DATABASES = {
        'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'test',
        'USER': 'user',
        'PASSWORD': 'root',
        'HOST':'',
        'PORT': '',
        }
     }

Body:
You must define the relevant variable to show where your settings.py file lives:

export DJANGO_SETTINGS_MODULE=mysite.settings

This is the relevant docs entry:

When you use Django, you have to tell it which settings you’re using.
Do this by using an environment variable, DJANGO_SETTINGS_MODULE.

The value of DJANGO_SETTINGS_MODULE should be in Python path syntax,
e.g. mysite.settings. Note that the settings module should be on the
Python import search path.

If you are using a virtualenv (which is the best practice), you can paste the relevant export command in the file <path-to-virtualenv>/bin/activate

ContentLicense: CC BY-SA 4.0


问:
Error bars in different colors with matplotlib
I have the following code, that produces a simple graph with both vertical and horizontal error bars:

```<code>#!/usr/bin/python
# -*- coding: utf-8 -*-

import pylab as pl
import matplotlib.pyplot as plt

x=[2,3]
error_x=[0.5,0.4]
y=[25,28]
error_y=[0.6,0.8]
lines={'linestyle': 'None'}
plt.rc('lines', **lines)
pl.plot(x, y, 'ro', markersize=6)
pl.errorbar(x, y, xerr=error_x, yerr=error_y, fmt='b')
pl.xlim(1.3,3.6)
pl.ylim(24.0,29.0)
pl.show()
</code>```

However, both error bars (vertical and horizontal) are blue, and I don't see how I could specify different colors for both of them. Is this possible? I would like, for example, for all horizontal error bars to be blue and for all vertical error bars to be green.

答:
Another "trick" for people with an older matplotlib version:</p>

```<code>import pylab as pl
import matplotlib.pyplot as plt

x=[2,3]
error_x=[0.5,0.4]
y=[25,28]
error_y=[0.6,0.8]
lines={'linestyle': 'None'}
plt.rc('lines', **lines)
pl.plot(x, y, 'ro', markersize=6)
pl.errorbar(x, y, xerr=error_x, yerr=0, fmt='b', ecolor='b')
pl.errorbar(x, y, xerr=0, yerr=error_y, fmt='g', ecolor='g')
pl.xlim(1.3,3.6)
pl.ylim(24.0,29.0)
pl.show()
</code>```

Body:
I have the following code, that produces a simple graph with both vertical and horizontal error bars:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import pylab as pl
import matplotlib.pyplot as plt

x=[2,3]
error_x=[0.5,0.4]
y=[25,28]
error_y=[0.6,0.8]
lines={'linestyle': 'None'}
plt.rc('lines', **lines)
pl.plot(x, y, 'ro', markersize=6)
pl.errorbar(x, y, xerr=error_x, yerr=error_y, fmt='b')
pl.xlim(1.3,3.6)
pl.ylim(24.0,29.0)
pl.show()

However, both error bars (vertical and horizontal) are blue, and I don't see how I could specify different colors for both of them. Is this possible? I would like, for example, for all horizontal error bars to be blue and for all vertical error bars to be green.

Body:
Another "trick" for people with an older matplotlib version:

import pylab as pl
import matplotlib.pyplot as plt

x=[2,3]
error_x=[0.5,0.4]
y=[25,28]
error_y=[0.6,0.8]
lines={'linestyle': 'None'}
plt.rc('lines', **lines)
pl.plot(x, y, 'ro', markersize=6)
pl.errorbar(x, y, xerr=error_x, yerr=0, fmt='b', ecolor='b')
pl.errorbar(x, y, xerr=0, yerr=error_y, fmt='g', ecolor='g')
pl.xlim(1.3,3.6)
pl.ylim(24.0,29.0)
pl.show()


问:
jQuery HTML Anchor Tag Progressive Enhancement
I have jQuery that I have written that is supposed to find a particular  tag and change its behavior.  Before jQuery loads, the  tag has an href attribute that points to another page.  I am using jQuery to change the behavior of the  tag so that rather than directing the browser to load that other page, it instead runs javascript when clicked that loads content dynamically in a
 that is positioned at the location of the mouse pointer.

So, for example, I have the following:
```
<a class="funk" href="http://example.com/page2.html">Link</a>
<div class="hidden bubble">Load this instead.</div>
```
The jQuery I have running does the following:
```
$(document).ready(function(){
        $('.bubble').hide()
        $('.bubble').removeClass('hidden');
        $('.funk').attr('href', '#');</p>

```    $('.funk').click(function(e){
        $('.bubble').show();
    })
```

<p>})
```

The problem I have is: Whenever the user clicks the link, the browser acts on the href="#" attribute and brings scrolls the browser to the top of the page.  What is the most "correct" way to make my site so that the browser does not scroll at all, but instead merely executes the jQuery code that I have written for the click event?

答:
Call e.preventDefault() in the click handler.
http://api.jquery.com/event.preventDefault/

Body:
I have jQuery that I have written that is supposed to find a particular  tag and change its behavior.  Before jQuery loads, the  tag has an href attribute that points to another page.  I am using jQuery to change the behavior of the  tag so that rather than directing the browser to load that other page, it instead runs javascript when clicked that loads content dynamically in a
 that is positioned at the location of the mouse pointer.

So, for example, I have the following:

Link

Load this instead.

The jQuery I have running does the following:

$(document).ready(function(){
        $('.bubble').hide()
        $('.bubble').removeClass('hidden');
        $('.funk').attr('href', '#');

    $('.funk').click(function(e){
        $('.bubble').show();
    })

})

The problem I have is: Whenever the user clicks the link, the browser acts on the href="#" attribute and brings scrolls the browser to the top of the page.  What is the most "correct" way to make my site so that the browser does not scroll at all, but instead merely executes the jQuery code that I have written for the click event?


问:
PHPUnit: Class not found
I use PHPUnit 5.7.23 in my class Compte, I develop this code in a method

```<code>   /**
     * @covers Compte::method()
     * @dataProvider entityToJsonData
     */
    public function testMethod($data, $expected)
    {
        $this->object = $this->getMockBuilder('Compte')
            ->getMock();

        $actualReponse = $this->object->method($data);
        $this->assertEquals($expected, $actualReponse);

    }
</code>```

PHP display this error message:

Fatal error: Class 'Compte' not found in CompteTest.php

Can you help me ?

答:
You have to use Namespaces:

```<code>$this->object = $this->getMockBuilder('<Vendor>\<Component>\Compte')
        ->getMock();
</code>```

Alternatively, you can also use an already visible class ('use' statement above the class declaration) such as follows:

```<code><?php
use <Vendor>\<Component>\Compte;

class MyClassTest extends TestCase
{
...
    public function testMethod($data, $expected)
    {
        $this->object = $this->getMockBuilder(Compte::class)
            ->getMock();
        ...
    }
...
}
</code>```

Compte::class returns the class name including its namespace.

Title: PHPUnit: Class not found

Body:
I use PHPUnit 5.7.23 in my class Compte, I develop this code in a method

   /**
     * @covers Compte::method()
     * @dataProvider entityToJsonData
     */
    public function testMethod($data, $expected)
    {
        $this->object = $this->getMockBuilder('Compte')
            ->getMock();

        $actualReponse = $this->object->method($data);
        $this->assertEquals($expected, $actualReponse);

    }

PHP display this error message:

Fatal error: Class 'Compte' not found in CompteTest.php

Can you help me ?

Body:
You have to use Namespaces:

$this->object = $this->getMockBuilder('<Vendor>\<Component>\Compte')
        ->getMock();

Alternatively, you can also use an already visible class ('use' statement above the class declaration) such as follows:

<?php
use <Vendor>\<Component>\Compte;

class MyClassTest extends TestCase
{
...
    public function testMethod($data, $expected)
    {
        $this->object = $this->getMockBuilder(Compte::class)
            ->getMock();
        ...
    }
...
}

Compte::class returns the class name including its namespace.


问:
Why does UNION operator cause datatype change in OracleDataAdapter?
I have the following query embedded in the procedure P_GET_TABLE1:

```<code>SELECT
  t1.field1 XXXX
FROM table1 t1
</code>```

field1 is NUMBER(12). The procedure is exectued in a .NET code using OracleDataAdapter and fills a DataTable such that XXXX is converted into a long.

I have another procedure P_GET_TABLE2:

```<code>SELECT
  t1.field1 XXXX
FROM table1 t1
UNION
SELECT
  0 as XXXX
FROM table2
</code>```

The union, however, seems to cause a change of the datatype such that XXXX cannot be converted to a long, only decimal.

My questions are:

Why does a UNION operator causes the OracleDataAdapter to change the datatype?

Can I force the OracleDataAdapter to interpret XXXX as a long

Specifically, this code is used to get data:

```<code>OracleDataAdapter da = new OracleDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
foreach(DataRow row in da.Rows)
{
    long value = (long)row["XXXX"]; // works when P_GET_TABLE1; exception when P_GET_TABLE2 is used;
}
</code>```

The exception: 'Object of type 'System.Decimal' cannot be converted to type 'System.Int64'.'

答:
Hunting this down for you:

The documentation for set operations (including UNION) links to the more general documentation section for "implicit data conversion" - where we can read:

When manipulating numeric values, Oracle usually adjusts precision and scale to allow for maximum capacity. In such cases, the numeric datatype resulting from such operations can differ from the numeric datatype found in the underlying tables.

In your example, the second branch of the UNION produces the value 0, not explicitly cast to any precision and scale. So, by default, that 0 is considered of type NUMBER (which has precision 38 and undetermined scale). When you UNION, the data type will be the "max capacity", which is NUMBER.

The solution is to wrap 0 within CAST:  cast(0 as number(12)) ....

Body:
I have the following query embedded in the procedure P_GET_TABLE1:

SELECT
  t1.field1 XXXX
FROM table1 t1

field1 is NUMBER(12). The procedure is exectued in a .NET code using OracleDataAdapter and fills a DataTable such that XXXX is converted into a long.

I have another procedure P_GET_TABLE2:

SELECT
  t1.field1 XXXX
FROM table1 t1
UNION
SELECT
  0 as XXXX
FROM table2

The union, however, seems to cause a change of the datatype such that XXXX cannot be converted to a long, only decimal.

My questions are:

Why does a UNION operator causes the OracleDataAdapter to change the datatype?

Can I force the OracleDataAdapter to interpret XXXX as a long

Specifically, this code is used to get data:

OracleDataAdapter da = new OracleDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
foreach(DataRow row in da.Rows)
{
    long value = (long)row["XXXX"]; // works when P_GET_TABLE1; exception when P_GET_TABLE2 is used;
}

The exception: 'Object of type 'System.Decimal' cannot be converted to type 'System.Int64'.'


问:
Best method to Merge two Datasets (Maybe if function?)
I have two data sets I am working with. Datasets TestA and Test B (Below is how to make them in R)

```<code>Instructor <- c('Mr.A','Mr.A','Mr.B', 'Mr.C', 'Mr.D')
Class <- c('French','French','English', 'Math', 'Geometry')
Section <- c('1','2','3','5','5')
Time <- c('9:00-10:00','10:00-11:00','9:00-10:00','9:00-10:00','10:00-11:00')
Date <- c('MWF','MWF','TR','TR','MWF')
Enrollment <- c('30','40','24','29','40')

TestA <- data.frame(Instructor,Class,Section,Time,Date,Enrollment)

rm(Instructor,Class,Section,Time,Date,Enrollment)

Student <- c("Frances","Cass","Fern","Pat","Peter","Kory","Cole")
ID <- c('123','121','101','151','456','789','314')
Instructor <- c('','','','','','','')
Time <- c('','','','','','','')
Date <- c('','','','','','','')
Enrollment <- c('','','','','','','')
Class <- c('French','French','French','French','English', 'Math', 'Geometry')
Section <- c('1','1','2','2','3','5','5')

TestB <- data.frame(Student, ID, Instructor, Class, Section, Time, Date, Enrollment)

rm(Instructor,Class,Section,Time,Date,Enrollment,ID,Student)
</code>```

I would like to merge both datasets (If possible, without using merge() ) So that All the columns of Test A are filled with the information provided by TestB and it should be added depending on the Class and Section.

I tried using merge(TestA, TestB, by=c('Class','Section'), all.x=TRUE) but it adds observations to the original TestA. This is just a test but in the datasets I am using there are hundreds of observations. It worked when I did it with these smaller frames but something is happening to the bigger set. That's why I'd like to know if there is a merge alternative.

Any ideas on how to do this?

The output should look like this

```<code>Class   Section Instructor  Time          Date   Enrollment Student ID
English  3      Mr.B    9:00-10:00  TR      24      Peter   456
French   1      Mr.A    9:00-10:00  MWF     30      Frances 123
French   1      Mr.A    9:00-10:00  MWF 30  Cass    121
French   2      Mr.A    10:00-11:00 MWF 40  Fern    101
French   2      Mr.A    10:00-11:00 MWF 40  Pat 151
Geometry 5      Mr.D    10:00-11:00 MWF 40  Cole    314
Math     5      Mr.C    9:00-10:00  TR  29  Kory    789
</code>```

答:
I was once a big fan of merge() until I learned about dplyr's join functions.

Try this instead:

```<code>library(dplyr)

TestA %>%
    left_join(TestB, by = c("Class", "Section")) %>% #Here, you're joining by just the "Class" and "Section" columns of TestA and TestB
    select(Class,
           Section,
           Instructor = Instructor.x,
           Time = Time.x,
           Date = Date.x,
           Enrollment = Enrollment.x,
           Student,
           ID) %>%
    arrange(Class, Section) #Added to match your output.
</code>```

The select statement is keeping only those columns that are specifically named and, in some cases, renaming them.

Output:

```<code>     Class Section Instructor        Time Date Enrollment Student  ID
1  English       3       Mr.B  9:00-10:00   TR         24   Peter 456
2   French       1       Mr.A  9:00-10:00  MWF         30 Frances 123
3   French       1       Mr.A  9:00-10:00  MWF         30    Cass 121
4   French       2       Mr.A 10:00-11:00  MWF         40    Fern 101
5   French       2       Mr.A 10:00-11:00  MWF         40     Pat 151
6 Geometry       5       Mr.D 10:00-11:00  MWF         40    Cole 314
7     Math       5       Mr.C  9:00-10:00   TR         29    Kory 789
</code>```

Body:
I have two data sets I am working with. Datasets TestA and Test B (Below is how to make them in R)

Instructor <- c('Mr.A','Mr.A','Mr.B', 'Mr.C', 'Mr.D')
Class <- c('French','French','English', 'Math', 'Geometry')
Section <- c('1','2','3','5','5')
Time <- c('9:00-10:00','10:00-11:00','9:00-10:00','9:00-10:00','10:00-11:00')
Date <- c('MWF','MWF','TR','TR','MWF')
Enrollment <- c('30','40','24','29','40')

TestA <- data.frame(Instructor,Class,Section,Time,Date,Enrollment)

rm(Instructor,Class,Section,Time,Date,Enrollment)

Student <- c("Frances","Cass","Fern","Pat","Peter","Kory","Cole")
ID <- c('123','121','101','151','456','789','314')
Instructor <- c('','','','','','','')
Time <- c('','','','','','','')
Date <- c('','','','','','','')
Enrollment <- c('','','','','','','')
Class <- c('French','French','French','French','English', 'Math', 'Geometry')
Section <- c('1','1','2','2','3','5','5')

TestB <- data.frame(Student, ID, Instructor, Class, Section, Time, Date, Enrollment)

rm(Instructor,Class,Section,Time,Date,Enrollment,ID,Student)

I would like to merge both datasets (If possible, without using merge() ) So that All the columns of Test A are filled with the information provided by TestB and it should be added depending on the Class and Section.

I tried using merge(TestA, TestB, by=c('Class','Section'), all.x=TRUE) but it adds observations to the original TestA. This is just a test but in the datasets I am using there are hundreds of observations. It worked when I did it with these smaller frames but something is happening to the bigger set. That's why I'd like to know if there is a merge alternative.

Any ideas on how to do this?

The output should look like this

Class   Section Instructor  Time          Date   Enrollment Student ID
English  3      Mr.B    9:00-10:00  TR      24      Peter   456
French   1      Mr.A    9:00-10:00  MWF     30      Frances 123
French   1      Mr.A    9:00-10:00  MWF 30  Cass    121
French   2      Mr.A    10:00-11:00 MWF 40  Fern    101
French   2      Mr.A    10:00-11:00 MWF 40  Pat 151
Geometry 5      Mr.D    10:00-11:00 MWF 40  Cole    314
Math     5      Mr.C    9:00-10:00  TR  29  Kory    789

Body:
I was once a big fan of merge() until I learned about dplyr's join functions.

Try this instead:

library(dplyr)

TestA %>%
    left_join(TestB, by = c("Class", "Section")) %>% #Here, you're joining by just the "Class" and "Section" columns of TestA and TestB
    select(Class,
           Section,
           Instructor = Instructor.x,
           Time = Time.x,
           Date = Date.x,
           Enrollment = Enrollment.x,
           Student,
           ID) %>%
    arrange(Class, Section) #Added to match your output.

The select statement is keeping only those columns that are specifically named and, in some cases, renaming them.

Output:

     Class Section Instructor        Time Date Enrollment Student  ID
1  English       3       Mr.B  9:00-10:00   TR         24   Peter 456
2   French       1       Mr.A  9:00-10:00  MWF         30 Frances 123
3   French       1       Mr.A  9:00-10:00  MWF         30    Cass 121
4   French       2       Mr.A 10:00-11:00  MWF         40    Fern 101
5   French       2       Mr.A 10:00-11:00  MWF         40     Pat 151
6 Geometry       5       Mr.D 10:00-11:00  MWF         40    Cole 314
7     Math       5       Mr.C  9:00-10:00   TR         29    Kory 789


问:
SQL Server : SELECT * FROM [dbo].[Table] WHERE
I'm new to SQL Server, and I'm trying to select a range between two dates.

My column is varchar (format: dd.mm.yyyy hh:mm:ss), but if I use

```<code>SELECT *
FROM [dbo].[Table]
WHERE [Column] BETWEEN 'lower date' AND 'max date'
</code>```

the result is every date that begins with the first two search option. In my case "dd" (dd.mm.yyyy hh:mm:ss).

Is there a solution, without changing the column from varchar to datetime?

答:
If you column is varchar, you can try</p>

```<code>select * from table where CONVERT(Datetime, column, 120) between lower and max
</code>```

Body:
I'm new to SQL Server, and I'm trying to select a range between two dates.

My column is varchar (format: dd.mm.yyyy hh:mm:ss), but if I use

SELECT *
FROM [dbo].[Table]
WHERE [Column] BETWEEN 'lower date' AND 'max date'

the result is every date that begins with the first two search option. In my case "dd" (dd.mm.yyyy hh:mm:ss).

Is there a solution, without changing the column from varchar to datetime?

Body:
If you column is varchar, you can try

select * from table where CONVERT(Datetime, column, 120) between lower and max


问:
Move view up when keyboard is presented
The Question:

I have a ViewController that has a subclass with a UIScrollView in it.

In the scrollView there are 3 UITextFields. 2 of them with a numberPad keyboard and 1 with a UIPickerView keyboard.

The problem is that when the keyboards are presented, it hides the UITextFields. So what I'm trying to do is to move the UIViewController's view up when the keyboards are being shown.

What I've already tried:

I've searched this question on SO and I've found some answers, based on them I've wrote this code:

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    //Keyboard notifications
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

//MARK: - keyboards

@objc fileprivate func keyboardWillShow(notification: Notification) {
    self.changeViewOriginBasedOnKeyboardPosition(notification: notification)
}

@objc fileprivate func keyboardWillHide(notification: Notification) {
    self.changeViewOriginBasedOnKeyboardPosition(notification: notification)
}

fileprivate func changeViewOriginBasedOnKeyboardPosition(notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        let keyboardAnimationDuration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval
        UIView.animate(withDuration: keyboardAnimationDuration != 0 ? keyboardAnimationDuration : 0.2, animations: {
            if self.controllerContentView.frame.origin.y == 0  {
                self.controllerContentView.frame.origin.y = -keyboardSize.height
            } else {
                self.controllerContentView.frame.origin.y = 0
            }
        })
    }
}

fileprivate func dismissKeyboard() {
    self.view.endEditing(true)
}

//Touch handling

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.dismissKeyboard()
}
</code>```

The problem with what I've tried:

Sometimes it works great, but sometimes the view "jumps" back up/"jumps" down and I can't understand why.

Does anybody see any problem with my code that can cause this bug?

Thank you!

答:
I use a CocoaPod for this called IQKeyboardManager.

https://github.com/hackiftekhar/IQKeyboardManager

It is dead simple to set up and works globally.

Title: Move view up when keyboard is presented

Body:
The Question:

I have a ViewController that has a subclass with a UIScrollView in it.

In the scrollView there are 3 UITextFields. 2 of them with a numberPad keyboard and 1 with a UIPickerView keyboard.

The problem is that when the keyboards are presented, it hides the UITextFields. So what I'm trying to do is to move the UIViewController's view up when the keyboards are being shown.

What I've already tried:

I've searched this question on SO and I've found some answers, based on them I've wrote this code:

override func viewDidLoad() {
    super.viewDidLoad()

    //Keyboard notifications
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

//MARK: - keyboards

@objc fileprivate func keyboardWillShow(notification: Notification) {
    self.changeViewOriginBasedOnKeyboardPosition(notification: notification)
}

@objc fileprivate func keyboardWillHide(notification: Notification) {
    self.changeViewOriginBasedOnKeyboardPosition(notification: notification)
}

fileprivate func changeViewOriginBasedOnKeyboardPosition(notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        let keyboardAnimationDuration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval
        UIView.animate(withDuration: keyboardAnimationDuration != 0 ? keyboardAnimationDuration : 0.2, animations: {
            if self.controllerContentView.frame.origin.y == 0  {
                self.controllerContentView.frame.origin.y = -keyboardSize.height
            } else {
                self.controllerContentView.frame.origin.y = 0
            }
        })
    }
}

fileprivate func dismissKeyboard() {
    self.view.endEditing(true)
}

//Touch handling

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.dismissKeyboard()
}

The problem with what I've tried:

Sometimes it works great, but sometimes the view "jumps" back up/"jumps" down and I can't understand why.

Does anybody see any problem with my code that can cause this bug?

Thank you!


问:
Vectorise a code to transform a vector into a matrix
I have a vector A of dimension Nx1 in MATLAB, e.g.

```<code>N = 5;
A = [1
     2
     3
     4
     5];
</code>```

I want to construct a matrix B of dimension (N-1) x N such that:

for i=1,...,N, B(:,i) contains the rows 1,2,...,i-1,i+1,...,N of A.

In the example above,

```<code>B = [2 1 1 1 1
     3 3 2 2 2
     4 4 4 3 3
     5 5 5 5 4]
</code>```

This code does what I want:

```<code> B=zeros(N-1,N);
 for i=1:N
     if i>1 && i<N
         B(:,i)=[A(1:i-1); A(i+1:end)];
     elseif i==1
         B(:,i)=A(i+1:end);
     elseif i==N
         B(:,i)=A(1:i-1);
     end
 end
</code>```

But I want to vectorise it. Any help?

答:
per your example you can just delete every N+1 entry:</p>

```<code>N=5;
a=repmat(1:N,1,N); % make an NxN long vector
a(1:N+1:end)=[]; % delete every N+1 entry
B=reshape(a,N-1,[]) % reshape to N-1 x N matrix
</code>```

Body:
I have a vector A of dimension Nx1 in MATLAB, e.g.

N = 5;
A = [1
     2
     3
     4
     5];

I want to construct a matrix B of dimension (N-1) x N such that:

for i=1,...,N, B(:,i) contains the rows 1,2,...,i-1,i+1,...,N of A.

In the example above,

B = [2 1 1 1 1
     3 3 2 2 2
     4 4 4 3 3
     5 5 5 5 4]

This code does what I want:

 B=zeros(N-1,N);
 for i=1:N
     if i>1 && i<N
         B(:,i)=[A(1:i-1); A(i+1:end)];
     elseif i==1
         B(:,i)=A(i+1:end);
     elseif i==N
         B(:,i)=A(1:i-1);
     end
 end

But I want to vectorise it. Any help?

Body:
per your example you can just delete every N+1 entry:

N=5;
a=repmat(1:N,1,N); % make an NxN long vector
a(1:N+1:end)=[]; % delete every N+1 entry
B=reshape(a,N-1,[]) % reshape to N-1 x N matrix


问:
Windows Form renders unevenly in designer
I have a Windows Form that, for some reason, has changed in looks. Even though no UI changes have been made, certain controls look smaller and some controls, such as the Text in a GroupBox wraps when the app is run. However, when I run the app on other workstations, it looks fine. I don't understand what would cause this unless there were Microsoft updates. Any ideas?

I have attached 2 screenshots, one in the designer mode and the other in execution mode.

Execution Mode

Thanks,

答:
Looks like you didn't design your app with a DPI aware state. Try redesigning it in UWP instead of WFP as UWP is automatically DPI aware.

Also the button that disappears on the right side that says finish, try making sure the Button.visible property is not set to false.


问:
Why can't programs be proven?
Why can't a computer program be proven just as a mathematical statement can?  A mathematical proof is built up on other proofs, which are built up from yet more proofs and on down to axioms - those truths truths we hold as self evident.

Computer programs don't seem to have such a structure.  If you write a computer program, how is it that you can take previous proven works and use them to show the truth of your program?  You can't since none exist.  Further, what are the axioms of programming?  The very atomic truths of the field?

I don't have good answers to the above.  But it seems software can't be proven because it is art and not science.  How do you prove a Picasso?

答:
Just a small comment to those who brought up incompleteness -- it is not the case for all axiomatic systems, only sufficiently powerful ones.

In other words, Godel proved that an axiomatic system powerful enough to describe itself would necessarily be incomplete.  This doesn't mean it would be useless however, and as others have linked to, various attempts at program proofs have been made.

The dual problem (writing programs to check proofs) is also very interesting.

Title: Why can't programs be proven?

OwnerDisplayName: Sumudu Fernando


问:
PyInstaller won't install, Python 3.6.0a4 and x64 Windows
I have said Python version (from https://www.python.org/downloads/windows/), and x64 Windows 10.
Every time I try to execute "pip install pyinstaller" it crashes with an error:

```<code>C:\WINDOWS\system32>pip install pyinstaller
Collecting pyinstaller
  Using cached PyInstaller-3.2.tar.gz
Requirement already satisfied (use --upgrade to upgrade): setuptools in c:\users\jskurski\appdata\local\programs\python\python36\lib\site-packages (from pyinstaller)
Collecting pefile (from pyinstaller)
  Using cached pefile-2016.3.28.tar.gz
Collecting pypiwin32 (from pyinstaller)
  Using cached pypiwin32-219.zip
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\jskurski\AppData\Local\Temp\pip-build-y9lsbd5f\pypiwin32\setup.py", line 121
        print "Building pywin32", pywin32_version
                               ^
    SyntaxError: Missing parentheses in call to 'print'

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\jskurski\AppData\Local\Temp\pip-build-y9lsbd5f\pypiwin32\
</code>```

So, for me it seems there is a version msmatch or something. Unofortunately, I can not figure it out myself.

Any suggestions?
Has anybody sucessfully used PyInstaller with latest 3.6 Python on Windows? Or maybe I should downgrade Python to older version?

edit: tested on another PC (same enviroment) and it was the same.

edit2: seems to work on 3.5.2 version, so it's probably a way to go, for now.

答:
You have to install manually pywin32 according to your version of python. The following link you can download.

https://sourceforge.net/projects/pywin32/files/pywin32/Build%20221/

Once installed pywin32 with your right version of python. Pyinstaller must be installed

Body:
I have said Python version (from https://www.python.org/downloads/windows/), and x64 Windows 10.
Every time I try to execute "pip install pyinstaller" it crashes with an error:

C:\WINDOWS\system32>pip install pyinstaller
Collecting pyinstaller
  Using cached PyInstaller-3.2.tar.gz
Requirement already satisfied (use --upgrade to upgrade): setuptools in c:\users\jskurski\appdata\local\programs\python\python36\lib\site-packages (from pyinstaller)
Collecting pefile (from pyinstaller)
  Using cached pefile-2016.3.28.tar.gz
Collecting pypiwin32 (from pyinstaller)
  Using cached pypiwin32-219.zip
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\jskurski\AppData\Local\Temp\pip-build-y9lsbd5f\pypiwin32\setup.py", line 121
        print "Building pywin32", pywin32_version
                               ^
    SyntaxError: Missing parentheses in call to 'print'

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\jskurski\AppData\Local\Temp\pip-build-y9lsbd5f\pypiwin32\

So, for me it seems there is a version msmatch or something. Unofortunately, I can not figure it out myself.

Any suggestions?
Has anybody sucessfully used PyInstaller with latest 3.6 Python on Windows? Or maybe I should downgrade Python to older version?

edit: tested on another PC (same enviroment) and it was the same.

edit2: seems to work on 3.5.2 version, so it's probably a way to go, for now.