问:
How to print 0 to 9 digits without using any digit in our code?
Recently, I found a problem on hackerearth that is how to print 726 without any digits. This is the link to question :https://www.hackerearth.com/challenge/college/r1/golf/726/

I have solved this with this:

```<code>#include <stdio.h>
main()
{
    printf("%d",('\e'*'\e')-('\r'-'\n'));

}
</code>```

but since I found this question interesting, I would love to print every single digit without use of any digit. So, I want to print 0 to 9 all in a new line without using any digit with the help of unicodes. How could I do that?

答:
There's countless of ways to write obscure, nonsense C code. One example:

```<code>#include <stdio.h>

int main (void)
{
  for(size_t i=!"A string."; i<sizeof("A string."); i++)
    printf("%zu ", i);
}
</code>```

Or, more creatively, in pure standard C:

```<code>??= include"stdio.h"

#define wtf(x,...) x%:%: nt ma ##x %:%:n(vo ##x %:%:d) ??<for(x %:%:nt x =(+ __LINE__??!??!\
+__LINE__) +- !!"WTF"; x<=__LINE__; +i++)??<\
pr ##x %:%:nt %:%:f((char[])<%'%','d',' ',!"WTF"??>,-+-x);%>??>

                                   wtf(i)
</code>```

Body:
Recently, I found a problem on hackerearth that is how to print 726 without any digits. This is the link to question :https://www.hackerearth.com/challenge/college/r1/golf/726/

I have solved this with this:

#include <stdio.h>
main()
{
    printf("%d",('\e'*'\e')-('\r'-'\n'));

}

but since I found this question interesting, I would love to print every single digit without use of any digit. So, I want to print 0 to 9 all in a new line without using any digit with the help of unicodes. How could I do that?

Body:
There's countless of ways to write obscure, nonsense C code. One example:

#include <stdio.h>

int main (void)
{
  for(size_t i=!"A string."; i<sizeof("A string."); i++)
    printf("%zu ", i);
}

Or, more creatively, in pure standard C:

??= include"stdio.h"

#define wtf(x,...) x%:%: nt ma ##x %:%:n(vo ##x %:%:d) ??<for(x %:%:nt x =(+ __LINE__??!??!\
+__LINE__) +- !!"WTF"; x<=__LINE__; +i++)??<\
pr ##x %:%:nt %:%:f((char[])<%'%','d',' ',!"WTF"??>,-+-x);%>??>

                                   wtf(i)


来源: stackexchange

问:
BuildConfig.DEBUG always return false
Why does BuildConfig.DEBUG return false, when I run the application?

I use it to control the log like the following:

```<code>public static void d(String LOG_TAG, String msg){
    if(BuildConfig.DEBUG){
        Log.d(LOG_TAG,msg);
    }
}
</code>```

答: Check imports in the class, make sure you are using correct BuildConfig path. You may use BuildConfig not from your app, but from some library.</p>

ContentLicense: CC BY-SA 4.0

Title: BuildConfig.DEBUG always return false

Body:
Why does BuildConfig.DEBUG return false, when I run the application?

I use it to control the log like the following:

public static void d(String LOG_TAG, String msg){
    if(BuildConfig.DEBUG){
        Log.d(LOG_TAG,msg);
    }
}

ContentLicense: CC BY-SA 3.0


问:
EXCEL: Make a formula to discount pricing.
We are making a spreadsheet for our dealers to order our product.  The dealers get different discounts if they order more.

Example: Orders below $2,000 they receive 15%.  Orders 2000-2999 get 20%.  Orders above 3000 get 23% off.

It would be a formula in the total cell we have in place.  When the total reaches above the certain numbers it would discount the total,  so maybe a gross cell with the total then maybe a couple other cells that trigger the discounts if they meet the number would be the easiest?

Any one have any ideas?

Thanks!

答:
Suppose A1 is the total amount of the order. Please put this formula in A2 where it will show the discount as desired. Net amount will be in the Cell A3 = A1-A2
=IF(A1>=3000, ROUND(A1*0.23,0), IF(A1>=2000, ROUND(A1*0.2,0), ROUND(A1*0.15,0)))</p>


问:
DateTime Parameter Throws exception
When passing a parameter, sometimes I get the following error thrown

'String was not recognized as a valid DateTime'

dates like this it does not like:

(Chrome)

date=2017-03-28T13%3a01%3a59+01%3a00

date=2017-04-01T10%3a35%3a57+01%3a00

(Safari 10)

date=2017-06-02

```<code>public ActionResult Add(string date = null)
{
   DateTime startTime = DateTime.Now;
   if (date != null)
   {
      startTime = DateTime.Parse(date);
   }
}
</code>```

Any ideas?

答:
You could try to unescape the string:</p>

```<code>public ActionResult Add(string date = null)
{
    DateTime startTime = DateTime.Now;

    if (date != null)
    {
        startTime = DateTime.Parse(Uri.UnescapeDataString(date));
    }
}
</code>```

Title: DateTime Parameter Throws exception

Body:
When passing a parameter, sometimes I get the following error thrown

'String was not recognized as a valid DateTime'

dates like this it does not like:

(Chrome)

date=2017-03-28T13%3a01%3a59+01%3a00

date=2017-04-01T10%3a35%3a57+01%3a00

(Safari 10)

date=2017-06-02

public ActionResult Add(string date = null)
{
   DateTime startTime = DateTime.Now;
   if (date != null)
   {
      startTime = DateTime.Parse(date);
   }
}

Any ideas?

Body:
You could try to unescape the string:

public ActionResult Add(string date = null)
{
    DateTime startTime = DateTime.Now;

    if (date != null)
    {
        startTime = DateTime.Parse(Uri.UnescapeDataString(date));
    }
}


问:
Unable to get property 'enumerateDevices' of undefined or null reference
I'm using enumerateDevices (See reference here) to get the user's camera and microphones list.

This code works great on Chrome:

```<code>$(document).ready(function(){
    navigator.mediaDevices.enumerateDevices()
    .then(gotDevices)
});
</code>```

But since it's unsupported on IE, it throws an error:

Unable to get property 'enumerateDevices' of undefined or null reference

My question: Is there any alternative I can use that works across all browsers?

答:
According to mediaDevices.enumerateDevices method api. This method doesn't support IE.

Browser Compatibility for This method are:

chrome : 45.0

FireFox(GecKo) : 39

Internet Explorer: not supported

opera: not supported

safari(webKit): not Supported

Hope This Helps!

Body:
I'm using enumerateDevices (See reference here) to get the user's camera and microphones list.

This code works great on Chrome:

$(document).ready(function(){
    navigator.mediaDevices.enumerateDevices()
    .then(gotDevices)
});

But since it's unsupported on IE, it throws an error:

Unable to get property 'enumerateDevices' of undefined or null reference

My question: Is there any alternative I can use that works across all browsers?


问:
How could I pass enum object with nested enum in it to a method as parameter?
Suppose we have an enum object like this:

```<code>public enum Action
{
    FOO,
    BAR;
    public enum Move
    {
         UP,
         DOWN,
         LEFT,
         RIGHT
    }
}
</code>```

and a method like this:

```<code>private void useThisEnum(Action a) {
    //code
}
</code>```

In my Eclipse the method could not accept the enum object with the nested enum. How could I pass it? Should I always use method overloading and declare another method like this:

```<code> private void useThisEnum(Action.Move ma) {
    //code
}
</code>```

Or should I use an Interface instead of the outside enum?

答: This is completely different argument. The Move is not "subclass" of Action so yes, you must declare another method. Move is an Inner class of Action, but that is something else.

Body:
Suppose we have an enum object like this:

public enum Action
{
    FOO,
    BAR;
    public enum Move
    {
         UP,
         DOWN,
         LEFT,
         RIGHT
    }
}

and a method like this:

private void useThisEnum(Action a) {
    //code
}

In my Eclipse the method could not accept the enum object with the nested enum. How could I pass it? Should I always use method overloading and declare another method like this:

 private void useThisEnum(Action.Move ma) {
    //code
}

Or should I use an Interface instead of the outside enum?


问:
Java Input from formatted file
I'm trying to getting input from a file which has various different lines.

e.g. the format is   Book title, Author:Borrower second name  First Name:Borrower state

here's some example lines.

```<code>The Lord of the Rings, JRR Tolkien:McInnes Elizabeth:13 11 10

Crime And Punishment, Fyodor Dostoyevsky

The Clan Of The Cave Bear, Jean M Auel

The God Of Small Things, Arundhati Roy:Robins Joshua:20 11 10
</code>```

So I tried to use useDelimiter after setting up a scanner, but since some line are shorter I don't no quite what to do.

答:
You could use .split()</p>

```<code>try {
    FileInputStream fstream = new FileInputStream("input.txt");
    DataInputStream in = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));

    String line;
    String author;
    String title;
    String borrower;
    String date;

    while ((line = br.readLine()) != null)   {
      (author,title) = line.split(",");

      if (line.contains(":")
        (title,borrower,date) = title.split(":");

      /*** Do what you need to do with the values here ***/
    }

    in.close();

} catch (Exception e) {
    e.printStackTrace();
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Java Input from formatted file

Body:
I'm trying to getting input from a file which has various different lines.

e.g. the format is   Book title, Author:Borrower second name  First Name:Borrower state

here's some example lines.

The Lord of the Rings, JRR Tolkien:McInnes Elizabeth:13 11 10

Crime And Punishment, Fyodor Dostoyevsky

The Clan Of The Cave Bear, Jean M Auel

The God Of Small Things, Arundhati Roy:Robins Joshua:20 11 10

So I tried to use useDelimiter after setting up a scanner, but since some line are shorter I don't no quite what to do.

Body:
You could use .split()

try {
    FileInputStream fstream = new FileInputStream("input.txt");
    DataInputStream in = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));

    String line;
    String author;
    String title;
    String borrower;
    String date;

    while ((line = br.readLine()) != null)   {
      (author,title) = line.split(",");

      if (line.contains(":")
        (title,borrower,date) = title.split(":");

      /*** Do what you need to do with the values here ***/
    }

    in.close();

} catch (Exception e) {
    e.printStackTrace();
}


问:
Android reset Counter
I want to reset counter.I have a TextView=TV and a  Button=Btn . I am writing here some important part of my code.

```<code>int Counter=1;

 TV.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(getApplicationContext(),"Clicked"
                    ,Toast.LENGTH_SHORT).show();
            Counter--;
            if (Counter == 0) {
                TV.setClickable(false);
            }
        }
    });

 Btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            }
 };
</code>```

Now what is the soluation that when i click on BTN i can get a one more chance for click

i know we inrease value of int counter but this is not correct soluation Because i want that TV is disabled after one click till button is not clicked.

答:
Try this one

```<code>TV.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Toast.makeText(getApplicationContext(),"Clicked"
                ,Toast.LENGTH_SHORT).show();
        TV.setEnabled(false);
      }
});

Btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
          TV.setEnabled(true);
        }
};
</code>```

Title: Android reset Counter

Body:
I want to reset counter.I have a TextView=TV and a  Button=Btn . I am writing here some important part of my code.

int Counter=1;

 TV.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(getApplicationContext(),"Clicked"
                    ,Toast.LENGTH_SHORT).show();
            Counter--;
            if (Counter == 0) {
                TV.setClickable(false);
            }
        }
    });

 Btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            }
 };

Now what is the soluation that when i click on BTN i can get a one more chance for click

i know we inrease value of int counter but this is not correct soluation Because i want that TV is disabled after one click till button is not clicked.

Body:
Try this one

TV.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Toast.makeText(getApplicationContext(),"Clicked"
                ,Toast.LENGTH_SHORT).show();
        TV.setEnabled(false);
      }
});

Btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
          TV.setEnabled(true);
        }
};


问:
ios : Assertion failure UITableView dataSource is not set
Why I am getting an error like this? In my appicaction I am loading webview inside a table view.</p>

```<code>*** Assertion failure in -[UITableView _createPreparedCellForGlobalRow:withIndexPath:], /SourceCache/UIKit_Sim/UIKit-1914.84/UITableView.m:6048
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource is not set'
</code>```

答:
In my case, it was a DatePicker throwing the error when I set it's .date property in viewDidLoad. When I moved the code to viewDidAppear, the issue gone.

This error happen only in iPhone 4s, not other later models, iPhone nor iPad.

Body:
Why I am getting an error like this? In my appicaction I am loading webview inside a table view.

*** Assertion failure in -[UITableView _createPreparedCellForGlobalRow:withIndexPath:], /SourceCache/UIKit_Sim/UIKit-1914.84/UITableView.m:6048
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource is not set'


问:
Float value gets incremented by 2 [ANDROID]
In my app, i am getting some item price from web in double, then i have to multiply it with item quantity and display on a textview.
The original value in double is 0.65340002596378299
As i want it as 0.65 only i use this statement for this purpose

```<code>float itemprice = Float.valueOf(String.format("%.2f", price));
</code>```

Next when i multiplied it with 6(quantity of item) i got this result 3.8999999

```<code> float total=no_of_items*itemprice;
</code>```

So i used Math.round function to get my required result which is 0.65*6=3.90

```<code>float total=Math.round(((no_of_items * itemprice) * 100.0) / 100.0);
</code>```

and i got 4.0 as final result but i want exact 3.90
How this can be achieved?
Any help will be appreciated.

答:
try this its result is 3.9 :</p>

```<code> double price = 0.65340002596378299;
 float itemprice = Float.valueOf(String.format("%.2f", price));
 float no_of_items = 6;
 float total=(no_of_items * itemprice);
 float itemp = Float.valueOf(String.format("%.2f", total));
</code>```

Body:
In my app, i am getting some item price from web in double, then i have to multiply it with item quantity and display on a textview.
The original value in double is 0.65340002596378299
As i want it as 0.65 only i use this statement for this purpose

float itemprice = Float.valueOf(String.format("%.2f", price));

Next when i multiplied it with 6(quantity of item) i got this result 3.8999999

 float total=no_of_items*itemprice;

So i used Math.round function to get my required result which is 0.65*6=3.90

float total=Math.round(((no_of_items * itemprice) * 100.0) / 100.0);

and i got 4.0 as final result but i want exact 3.90
How this can be achieved?
Any help will be appreciated.

Body:
try this its result is 3.9 :

 double price = 0.65340002596378299;
 float itemprice = Float.valueOf(String.format("%.2f", price));
 float no_of_items = 6;
 float total=(no_of_items * itemprice);
 float itemp = Float.valueOf(String.format("%.2f", total));


问:
Text becomes "Red" color; Can't find the code that makes it "Red"
I have a simple php page which outputs a table (which has been created dynamically).

The text on the page is all red marked, unless you specifically put a font color element and force it to become black.

I use FF and have Firebug installed, so I wonder if you guys have any tips on how to troubleshoot why this text isn't black?

I have tried:

1- Setting the body text color to 000 both with css and html... Didn't work!

2- Checking all classes.

Any tips???

All I have figured out is that when I DONT include my css files, the text becomes black standard. And I have looked at the css files without finding anything suspicious.

How should I troubleshoot?

Isn't there any way to check which styles if any, a text has applied to it somehow?

答: You could also use chromes development by just simply  right clicking the text and inspecting element.  Its not as developed as firebug, however, its very easy to use.</p>


问:
Changing font size in skin
I am writing a game using libgdx, and I borrowed the skin.json (and related files) from a tutorial.

The font being used (default) was scaling in an ugly manner on denser screens, so I generated by own very large font - and in the game itself, I scale it to a reasonable size (basically I use BitmapFont.scale). The font I'm now using is 3 times as large as the previous one.

I changed the reference to which font to use in the skin.json file, and as a result, all my buttons, titles and other things have a massive font being shown.

Is there a way of scaling the font in the .json file? Or anywhere else in the code? Skin doesn't have a setFont() functionality, so I can't create a scaled BitmapFont and assign it)

答:
As of 2017 i had to use

```<code>skin.getFont("default-font").getData().setScale(0.5f);
</code>```

for future users.

Title: Changing font size in skin

Body:
As of 2017 i had to use

skin.getFont("default-font").getData().setScale(0.5f);

for future users.


问:
Checking if an element exists in Protractor
There is a particular page having a number - which is a link to a list. I want to be able to search for the count. If the count is 0, then do nothing, else click on on the number to open the list.

I am using the isPresent() function in Protractor to search for it.

My code is

```<code>$('cda-e2e-softwareCountZero').isPresent().then(function(result) {

if ( result ) {
    // No Software
} else {
    element(by.id('cda-e2e-softwareCount')).click();
}

});
</code>```

However, this always returns the following error

Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

How do I solve this issue?

Edit:

The HTML Code for the same is

```<code><span class="panelHead">
                            Softwares
                            <a ng-if="summaryMetaDataList.softwares.length != 0"
                                ng-href="/application/application/{{summaryMetaDataInfo.entityId || alternateText}}/software/list{{dateParamsUrl}}">
                                <span style="text-decoration: none; color: black;">(</span><span class="textUnderlineBlue" id="cda-e2e-softwareCount">{{summaryMetaDataList.softwares.length}}</span><span style="text-decoration: none; color: black;">)</span>
                            </a>
                            <a ng-if="summaryMetaDataList.softwares.length == 0">
                                <span style="color: black" id="cda-e2e-softwareCountZero">({{summaryMetaDataList.softwares.length}})</span>
                            </a>
</span>
</code>```

答:
Increase Jasmine time out on conf.js file. Follow the below code</p>

```<code>  allScriptsTimeout: 60000,

  jasmineNodeOpts: {
    // Default time to wait in ms before a test fails.
    defaultTimeoutInterval: 12000
  },
</code>```

Body:
There is a particular page having a number - which is a link to a list. I want to be able to search for the count. If the count is 0, then do nothing, else click on on the number to open the list.

I am using the isPresent() function in Protractor to search for it.

My code is

$('cda-e2e-softwareCountZero').isPresent().then(function(result) {

if ( result ) {
    // No Software
} else {
    element(by.id('cda-e2e-softwareCount')).click();
}

});

However, this always returns the following error

Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

How do I solve this issue?

Edit:

The HTML Code for the same is

                            Softwares

                                ({{summaryMetaDataList.softwares.length}})

                                ({{summaryMetaDataList.softwares.length}})

Body:
Increase Jasmine time out on conf.js file. Follow the below code

  allScriptsTimeout: 60000,

  jasmineNodeOpts: {
    // Default time to wait in ms before a test fails.
    defaultTimeoutInterval: 12000
  },


问:
jBCrypt dependency not working
I am using heroku embedded tomcat for my web application.

In my user registration page, I have function :

```<code>private static String hashPwd(String pwd) {
    return BCrypt.hashpw(pwd, BCrypt.gensalt());
}
</code>```

I added this dependency in pom.xml:

```<code><dependency>
    <groupId>org.mindrot</groupId>
    <artifactId>jbcrypt</artifactId>
    <version>0.3m</version>
</dependency>
</code>```

But when I try to git push my changes, I get an error:

```<code>cannot find symbol : variable BCrypt
</code>```

at my function call. What am I missing?

My import looks like this:

```<code>import org.mindrot.*;
</code>```

答:
I found the problem. Apparently I had to import :

```<code>import org.mindrot.jbcrypt.*
</code>```

instead of

```<code>import org.mindrot.*
</code>```

Title: jBCrypt dependency not working

Body:
I am using heroku embedded tomcat for my web application.

In my user registration page, I have function :

private static String hashPwd(String pwd) {
    return BCrypt.hashpw(pwd, BCrypt.gensalt());
}

I added this dependency in pom.xml:

<dependency>
    <groupId>org.mindrot</groupId>
    <artifactId>jbcrypt</artifactId>
    <version>0.3m</version>
</dependency>

But when I try to git push my changes, I get an error:

cannot find symbol : variable BCrypt

at my function call. What am I missing?

My import looks like this:

import org.mindrot.*;

Body:
I found the problem. Apparently I had to import :

import org.mindrot.jbcrypt.*

instead of

import org.mindrot.*


问:
ionic 1 check internet when app is working
I try to check if internet is working when I run the app. It works well on my computer but after compiling apk and running the app on my smartphone, this code doesn't work properly; could you help me ?

.run(function($window, $rootScope) {
 console.log($cordovaNetwork.getNetwork());
 $rootScope.online = navigator.onLine;
 $window.addEventListener("offline", function() {
  $rootScope.$apply(function() {
   $rootScope.online = false;
  });
 }, false);
 $window.addEventListener("online", function() {
  $rootScope.$apply(function() {
   $rootScope.online = true;
  });
 }, false);
})```

regards

答:
You can Use cordova network Plugin(Cordova Network Plugin). Use can use the code below</p>

```<code>.run(function($ionicPlatform, $ionicPopup) {
  $ionicPlatform.ready(function() {

    // Check for network connection
    if(window.Connection) {
      if(navigator.connection.type == Connection.NONE) {
        $ionicPopup.confirm({
          title: 'No Internet Connection',
          content: 'Sorry, no Internet connectivity detected. Please reconnect and try again.'
        })
        .then(function(result) {
          if(!result) {
            ionic.Platform.exitApp();
          }
        });
      }
    }

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

Body:
I try to check if internet is working when I run the app. It works well on my computer but after compiling apk and running the app on my smartphone, this code doesn't work properly; could you help me ?

.run(function($window, $rootScope) {
 console.log($cordovaNetwork.getNetwork());
 $rootScope.online = navigator.onLine;
 $window.addEventListener("offline", function() {
  $rootScope.$apply(function() {
   $rootScope.online = false;
  });
 }, false);
 $window.addEventListener("online", function() {
  $rootScope.$apply(function() {
   $rootScope.online = true;
  });
 }, false);
})

regards

Body:
You can Use cordova network Plugin(Cordova Network Plugin). Use can use the code below

.run(function($ionicPlatform, $ionicPopup) {
  $ionicPlatform.ready(function() {

    // Check for network connection
    if(window.Connection) {
      if(navigator.connection.type == Connection.NONE) {
        $ionicPopup.confirm({
          title: 'No Internet Connection',
          content: 'Sorry, no Internet connectivity detected. Please reconnect and try again.'
        })
        .then(function(result) {
          if(!result) {
            ionic.Platform.exitApp();
          }
        });
      }
    }

  });
})


问:
Nice way for accesing interface path
Please help to find a  solution, for having nice looking code.

So in my code I have to do several forcing, as the same wire is being driven by tb and other part of design. As a result I have lots of force statements like this:

force TOP.u_proto_mc_top.gtx_rx_reset = TOP.u_proto_mc_top.u_GTX_RXB.gtxMaster_itf_inst.rstn;

force TOP.u_proto_mc_top.gtx_tx_reset = TOP.u_proto_mc_top.u_GTX_RXB.gtxMaster_itf_inst.txstn;

So I am just copy pasting the same interface path again and again, I mean this path:
TOP.u_proto_mc_top.u_GTX_RXB.gtxMaster_itf_inst

Each time I need to force a interface signal, I have to copy and paste this path.
This is ugly to me.
Can someone please suggest another solution to this, for I don’t copy/paste the interface path again and again.

Thanks

答:
First I would try to find out why the structure of your testbench requires a force with an interface. Better planing could possibly avoid this.

A quick solutions use to use a text macro.

```<code>`define uTOP TOP.u_proto_mc_top
`define GTXMaster `uTOP.u_GTX_RXB.gtxMaster_itf_inst
force `uTOP.gtx_tx_reset = `GTXMaster.txstn;
</code>```

Title: Nice way for accesing interface path

Body:
First I would try to find out why the structure of your testbench requires a force with an interface. Better planing could possibly avoid this.

A quick solutions use to use a text macro.

`define uTOP TOP.u_proto_mc_top
`define GTXMaster `uTOP.u_GTX_RXB.gtxMaster_itf_inst
force `uTOP.gtx_tx_reset = `GTXMaster.txstn;


问:
How does AuthenticationManager implementation gets instantiated in SpringBoot App
Including spring security starter dependency makes AuthenticationManager available in a spring boot application. I can simply Autowire the AuthenticationManager. How does SpringBoot understand to automatically instantiate the bean for AuthenticationManager though it is in a very different jar file ?

for e.g.

I can simply write

@Autowire
AuthenticationManager authManager;

in my SpringBoot App after including the dependency. How does spring know that it is supposed to instantiate which class and how ?

答: The class org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration imports the configuration class org.springframework.boot.autoconfigure.security.AuthenticationManagerConfiguration, which then provides the bean for the AuthenticationManager (it will use a builder to build the authentication manager according to the configuration which is provided).


问:
How to expend a div to alway be 100% of the page?
I want to expand my menu height to always take 100% of the visible height.

For the moment it only take the 100% at the loading, then if I scroll down there is a white block and it's ugly.

I can't post images because I haven't 10points

The CSS of my menu is the following one:

```<code>.nav-sm .container.body .col-md-3.left_col {
    min-height: 100%;
    width: 70px;
    padding: 0;
    z-index: 9999;
    position: absolute;
}
</code>```

The thing I want to achieve is to have my menu who always took all the visible height and I can't find how to do that.

答:
.demo{
  width:100%;
  height:100%;
  background:#e0e0e0;
}

body {
  height:2000px;
  margin:0px;
  padding:0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="demo">
    <span>Hello World</span>
  </div>
</body></code>```

Body:
I want to expand my menu height to always take 100% of the visible height.

For the moment it only take the 100% at the loading, then if I scroll down there is a white block and it's ugly.

I can't post images because I haven't 10points

The CSS of my menu is the following one:

.nav-sm .container.body .col-md-3.left_col {
    min-height: 100%;
    width: 70px;
    padding: 0;
    z-index: 9999;
    position: absolute;
}

The thing I want to achieve is to have my menu who always took all the visible height and I can't find how to do that.

Body:
.demo{
  width:100%;
  height:100%;
  background:#e0e0e0;
}

body {
  height:2000px;
  margin:0px;
  padding:0px;
}

<body>
  <div class="demo">
    <span>Hello World</span>
  </div>
</body>


问:
iPhone application crash on launch
We are receiving a crash log from iTunes connect that is a little strange.

We were preivously having problems with our app taking to long to return from ApplicationDidFinishLaunching. This was caused by doing a too much work inside of applicationDidFinishLaunching and we exceeded the 20 second time out on slower devices.

To fix this we moved all of our setup code out of ApplicationDidFinishLaunching and moved it into a special secondaryLoadingController. On top of that we moved the setup code inside of that controller to a separate thread.

However, we are still seeing crash logs that say our app failed to launch in time even though the crash log shows a call to [UIApplication _reportAppLaunchFinished]. To me, this indicates that the app has finished launching and we should be free to take as long as we want to run our setup code.  Below is the crash log.

Thanks for any help you can offer.

```<code>Incident Identifier: 429360D5-6B02-49BE-9A0F-164DC521BE36
Hardware Model:      iPod2,1
Process:         XYZ [357]
Path:            /var/mobile/Applications/D5038F26-CC5B-48E5-824E-090163B5C0C4/XYZ.app/XYZ
Identifier:      XYZ
Version:         ??? (???)
Code Type:       ARM (Native)
Parent Process:  launchd [1]

Date/Time:       2010-09-28 13:35:25.138 -0700
OS Version:      iPhone OS 4.0 (8A293)
Report Version:  104

Exception Type:  00000020
Exception Codes: 0x8badf00d
Highlighted Thread:  0

Application Specific Information:
com.xyz.xyz failed to launch in time
elapsed total CPU time (seconds): 20.180 (user 15.910, system 4.270), 100% CPU
elapsed application CPU time (seconds): 10.960, 54% CPU

Thread 0:
0   libobjc.A.dylib                   0x3523a50c objc_msgSend + 44
1   CoreFoundation                    0x363bf568 -[__NSArrayM addObject:]
2   XYZ                        0x0000a152 -[Database fetchDrinks:] + 290
3   XYZ                        0x0000677c -[Database getAllDrinks] + 136
4   XYZ                        0x0003a164 -[SecondaryLoadingViewController viewDidLoad] + 208
5   UIKit                             0x323e582c -[UIViewController view]
6   UIKit                             0x323f9628 -[UIViewController viewControllerForRotation]
7   UIKit                             0x323f9574 -[UIViewController _visibleView]
8   UIKit                             0x323f94fc -[UIViewController rotatingContentViewForWindow:]
9   UIKit                             0x3249a514 -[UIClientRotationContext initWithClient:toOrientation:duration:andWindow:]
10  UIKit                             0x32499314 -[UIWindow _setRotatableClient:toOrientation:duration:force:]
11  UIKit                             0x32497d78 -[UIWindowController transition:fromViewController:toViewController:target:didEndSelector:]
12  UIKit                             0x32497534 -[UIViewController presentModalViewController:withTransition:]
13  UIKit                             0x324977fc -[UIViewController _tryRecursivelyPresentModalViewController:withTransition:]
14  UIKit                             0x324977c0 -[UIViewController _tryRecursivelyPresentModalViewController:withTransition:]
15  UIKit                             0x32496e00 -[UIViewController presentModalViewController:withTransition:]
16  UIKit                             0x3249699c -[UIViewController presentModalViewController:animated:]
17  XYZ                        0x000044a2 -[HomeViewController viewDidLoad] + 82
18  UIKit                             0x323e582c -[UIViewController view]
19  UIKit                             0x323fd68c -[UIViewController contentScrollView]
20  UIKit                             0x323fd4ac -[UINavigationController _computeAndApplyScrollContentInsetDeltaForViewController:]
21  UIKit                             0x323fd358 -[UINavigationController _layoutViewController:]
22  UIKit                             0x323fccb8 -[UINavigationController _startTransition:fromViewController:toViewController:]
23  UIKit                             0x323fca1c -[UINavigationController _startDeferredTransitionIfNeeded]
24  UIKit                             0x323fc90c -[UINavigationController viewWillLayoutSubviews]
25  UIKit                             0x323fc43c -[UILayoutContainerView layoutSubviews]
26  UIKit                             0x32370ab0 -[UIView(CALayerDelegate) _layoutSublayersOfLayer:]
27  CoreFoundation                    0x363c85ba -[NSObject(NSObject) performSelector:withObject:]
28  QuartzCore                        0x30c8c61c 0x30c82000 + 42524
29  QuartzCore                        0x30c8c2a4 0x30c82000 + 41636
30  QuartzCore                        0x30c8bbb0 0x30c82000 + 39856
31  QuartzCore                        0x30c8b7d8 0x30c82000 + 38872
32  QuartzCore                        0x30c8b684 0x30c82000 + 38532
33  UIKit                             0x323d99d4 -[UIApplication _reportAppLaunchFinished]
34  UIKit                             0x3251d77c -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:]
35  UIKit                             0x323d87b8 -[UIApplication handleEvent:withNewEvent:]
36  UIKit                             0x323d7eb4 -[UIApplication sendEvent:]
37  UIKit                             0x323d77e8 _UIApplicationHandleEvent
38  GraphicsServices                  0x33c4dedc PurpleEventCallback
39  CoreFoundation                    0x364142ac __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__
40  CoreFoundation                    0x364161d6 __CFRunLoopDoSource1
41  CoreFoundation                    0x3641718e __CFRunLoopRun
42  CoreFoundation                    0x363be0bc CFRunLoopRunSpecific
43  CoreFoundation                    0x363bdfca CFRunLoopRunInMode
44  UIKit                             0x32363b18 -[UIApplication _run]
45  UIKit                             0x32361fb8 UIApplicationMain
46  XYZ                        0x00002b20 main + 36
47  XYZ                        0x00002af0 start + 32
</code>```

UPDATE
I am attempting to run the time consuming import code (only happens on an application update) on a separate thread. I am even updating the GUI using an AlertView with an embedded progress bar so the user knows something is still happening. During our testing process this works fine. Below is the thread code that seems to not be working. The crash log seems to indicate that all work is being done on the main thread.

```<code>    if ([database appDidUpdate] == YES) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    dbImportThread = [[NSThread alloc] initWithTarget:self selector:@selector(import) object:nil];
    [dbImportThread start];
    [pool release];

- (void)import {
 //do importing work and update the gui with the progress
}
</code>```

答:
its setting off a watchdog timer.
its blocking the main thread for more than 20 seconds.
as has been said, you need to lazy load. only load up something that will be visible on the first screen.

run some time profiles on it using instruments,
 try and fix anything that is particularly inefficient and try to kick as much as you can get away with onto a background thread.(IE anything that is not going to be updating the UI)
you can load lots of data on a background thread, and once the data objects have been set up pass them back to the main thread, and run an update selector from there.

Title: iPhone application crash on launch

Body:
We are receiving a crash log from iTunes connect that is a little strange.

We were preivously having problems with our app taking to long to return from ApplicationDidFinishLaunching. This was caused by doing a too much work inside of applicationDidFinishLaunching and we exceeded the 20 second time out on slower devices.

To fix this we moved all of our setup code out of ApplicationDidFinishLaunching and moved it into a special secondaryLoadingController. On top of that we moved the setup code inside of that controller to a separate thread.

However, we are still seeing crash logs that say our app failed to launch in time even though the crash log shows a call to [UIApplication _reportAppLaunchFinished]. To me, this indicates that the app has finished launching and we should be free to take as long as we want to run our setup code.  Below is the crash log.

Thanks for any help you can offer.

Incident Identifier: 429360D5-6B02-49BE-9A0F-164DC521BE36
Hardware Model:      iPod2,1
Process:         XYZ [357]
Path:            /var/mobile/Applications/D5038F26-CC5B-48E5-824E-090163B5C0C4/XYZ.app/XYZ
Identifier:      XYZ
Version:         ??? (???)
Code Type:       ARM (Native)
Parent Process:  launchd [1]

Date/Time:       2010-09-28 13:35:25.138 -0700
OS Version:      iPhone OS 4.0 (8A293)
Report Version:  104

Exception Type:  00000020
Exception Codes: 0x8badf00d
Highlighted Thread:  0

Application Specific Information:
com.xyz.xyz failed to launch in time
elapsed total CPU time (seconds): 20.180 (user 15.910, system 4.270), 100% CPU
elapsed application CPU time (seconds): 10.960, 54% CPU

Thread 0:
0   libobjc.A.dylib                   0x3523a50c objc_msgSend + 44
1   CoreFoundation                    0x363bf568 -[__NSArrayM addObject:]
2   XYZ                        0x0000a152 -[Database fetchDrinks:] + 290
3   XYZ                        0x0000677c -[Database getAllDrinks] + 136
4   XYZ                        0x0003a164 -[SecondaryLoadingViewController viewDidLoad] + 208
5   UIKit                             0x323e582c -[UIViewController view]
6   UIKit                             0x323f9628 -[UIViewController viewControllerForRotation]
7   UIKit                             0x323f9574 -[UIViewController _visibleView]
8   UIKit                             0x323f94fc -[UIViewController rotatingContentViewForWindow:]
9   UIKit                             0x3249a514 -[UIClientRotationContext initWithClient:toOrientation:duration:andWindow:]
10  UIKit                             0x32499314 -[UIWindow _setRotatableClient:toOrientation:duration:force:]
11  UIKit                             0x32497d78 -[UIWindowController transition:fromViewController:toViewController:target:didEndSelector:]
12  UIKit                             0x32497534 -[UIViewController presentModalViewController:withTransition:]
13  UIKit                             0x324977fc -[UIViewController _tryRecursivelyPresentModalViewController:withTransition:]
14  UIKit                             0x324977c0 -[UIViewController _tryRecursivelyPresentModalViewController:withTransition:]
15  UIKit                             0x32496e00 -[UIViewController presentModalViewController:withTransition:]
16  UIKit                             0x3249699c -[UIViewController presentModalViewController:animated:]
17  XYZ                        0x000044a2 -[HomeViewController viewDidLoad] + 82
18  UIKit                             0x323e582c -[UIViewController view]
19  UIKit                             0x323fd68c -[UIViewController contentScrollView]
20  UIKit                             0x323fd4ac -[UINavigationController _computeAndApplyScrollContentInsetDeltaForViewController:]
21  UIKit                             0x323fd358 -[UINavigationController _layoutViewController:]
22  UIKit                             0x323fccb8 -[UINavigationController _startTransition:fromViewController:toViewController:]
23  UIKit                             0x323fca1c -[UINavigationController _startDeferredTransitionIfNeeded]
24  UIKit                             0x323fc90c -[UINavigationController viewWillLayoutSubviews]
25  UIKit                             0x323fc43c -[UILayoutContainerView layoutSubviews]
26  UIKit                             0x32370ab0 -[UIView(CALayerDelegate) _layoutSublayersOfLayer:]
27  CoreFoundation                    0x363c85ba -[NSObject(NSObject) performSelector:withObject:]
28  QuartzCore                        0x30c8c61c 0x30c82000 + 42524
29  QuartzCore                        0x30c8c2a4 0x30c82000 + 41636
30  QuartzCore                        0x30c8bbb0 0x30c82000 + 39856
31  QuartzCore                        0x30c8b7d8 0x30c82000 + 38872
32  QuartzCore                        0x30c8b684 0x30c82000 + 38532
33  UIKit                             0x323d99d4 -[UIApplication _reportAppLaunchFinished]
34  UIKit                             0x3251d77c -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:]
35  UIKit                             0x323d87b8 -[UIApplication handleEvent:withNewEvent:]
36  UIKit                             0x323d7eb4 -[UIApplication sendEvent:]
37  UIKit                             0x323d77e8 _UIApplicationHandleEvent
38  GraphicsServices                  0x33c4dedc PurpleEventCallback
39  CoreFoundation                    0x364142ac __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__
40  CoreFoundation                    0x364161d6 __CFRunLoopDoSource1
41  CoreFoundation                    0x3641718e __CFRunLoopRun
42  CoreFoundation                    0x363be0bc CFRunLoopRunSpecific
43  CoreFoundation                    0x363bdfca CFRunLoopRunInMode
44  UIKit                             0x32363b18 -[UIApplication _run]
45  UIKit                             0x32361fb8 UIApplicationMain
46  XYZ                        0x00002b20 main + 36
47  XYZ                        0x00002af0 start + 32

UPDATE
I am attempting to run the time consuming import code (only happens on an application update) on a separate thread. I am even updating the GUI using an AlertView with an embedded progress bar so the user knows something is still happening. During our testing process this works fine. Below is the thread code that seems to not be working. The crash log seems to indicate that all work is being done on the main thread.

    if ([database appDidUpdate] == YES) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    dbImportThread = [[NSThread alloc] initWithTarget:self selector:@selector(import) object:nil];
    [dbImportThread start];
    [pool release];

- (void)import {
 //do importing work and update the gui with the progress
}


问:
How to avoid overflow in realloc?
One can safely allocate x elements of size y in C by using calloc(x, y) and calloc() will take care of the multiplication x*y.

However realloc() for example only takes the new size as parameter and I was wondering how I could safely realloc x*y bytes using realloc().

What if x*y doesn't fit in size_t? How does calloc() handle this?

答:
size_t is an unsigned type.

For unsigned types overflow behaviour is deterministic, as mentioned in C11

[....] because a result that cannot be represented by the resulting unsigned integer type is
  reduced modulo the number that is one greater than the largest value that can be
  represented by the resulting type.

So, as long as you make sure the operation which produces the value to be stored in the variable type size_t does not overflow in the process, passing that variable to realloc() has no impact. At most, realloc() will fail to allocate that memory.

Title: How to avoid overflow in realloc?


问:
org.postgresql.util.PSQLException: No value specified for parameter 1
The query runs perfectly fine when directly executed in database but it gives me above error..I Have gone through similar questions but couldnt find any sol..

My Dao code

```<code>public String BASshiftingStudentsUpdate(HttpServletRequest request)
        {
            String sql="",msg="";
            String[] checkedApps = request.getParameter("checkedApps") != null&& request.getParameter("checkedApps")!=""?request.getParameter("checkedApps").split("\\,") : null;
            String ac_year=request.getParameter("acyear");

            try
            {
                if (checkedApps != null)
                {

                    for (int i = 0; i < checkedApps.length; i++)
                    {

                        sql=" insert into pmss_school_students_details(admission_no,student_name,parent_name,native_dist,native_mandal,address,caste_code,subcaste_code,admission_year,"
                            + "admission_dt,admission_class,present_class,student_photo,entered_by,entered_dt,stu_subcaste_new,mobilenumber,parent_proffession,annual_income,date_of_birth,"
                            + "pre_quarterly_marks,pre_annual_marks,achievements,health_problems,height,weight,blood_group,fresh_renewal,identification_marks,orphan,semi_orphan,"
                            + "rescued_child,victim,handycapped,school_code,class_promoted,dept_code,dist_office_code,applied_date,stu_id,status,pre_halfyearly_marks,ac_year,"
                            + "pre_quarterly_marks_max,pre_halfyearly_marks_max,pre_annual_marks_max,gender,boaders,from_school) "

                            + " select admission_no,student_name,parent_name,native_dist,"
                            + "native_mandal,address,caste_code,subcaste_code,admission_year,admission_dt,admission_class,present_class+1  as present_class,student_photo,entered_by,entered_dt,"
                            + "stu_subcaste_new,mobilenumber,parent_proffession,annual_income,date_of_birth,pre_quarterly_marks,pre_annual_marks,achievements,health_problems,"
                            + "height,weight,blood_group,'R' as fresh_renewal,identification_marks,orphan,semi_orphan,rescued_child,victim,handycapped,'"+request.getParameter("to_schools_selected")+"' as school_code,class_promoted,"
                            + "dept_code,dist_office_code,applied_date,(substring(stu_id,1,4))::int+1||substr(stu_id,5) as stu_id,'3' as status,pre_halfyearly_marks,(substring(stu_id,1,4))::int+1||'-'||(substring(stu_id,3,2))::int+2 as ac_year,pre_quarterly_marks_max,"
                            + "pre_halfyearly_marks_max,pre_annual_marks_max,gender,boaders,school_code from pmss_school_students_details "
                            + " where stu_id='"+checkedApps[i]+ "' and school_code='"+  Integer.parseInt(request.getParameter("schoolcode").trim())
                            + "' and ac_year=int4(substring('"+ac_year+"',1,4))-1||'-'||int4(substring('"+ac_year+"',6,2))-1";

                        gen.executeUpdate(sql);
                    }

                }
</code>```

executeUpdate Method

```<code>public int executeUpdate(String sql)
    {
        Session session = sessionfactory.openSession();
        SQLQuery  query=null;
        int result=0;
        try
        {
            result=session.createSQLQuery(sql).executeUpdate();

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (session.isOpen())
            {
                session.close();
            }
        }

        return result;
    }
</code>```

The columns in query are same in number.

答: The colon (:) is a prefix for named parameters in Hibernate. Make sure you escape them, e.g. \:\:int+1.

Body:
The query runs perfectly fine when directly executed in database but it gives me above error..I Have gone through similar questions but couldnt find any sol..

My Dao code

public String BASshiftingStudentsUpdate(HttpServletRequest request)
        {
            String sql="",msg="";
            String[] checkedApps = request.getParameter("checkedApps") != null&& request.getParameter("checkedApps")!=""?request.getParameter("checkedApps").split("\\,") : null;
            String ac_year=request.getParameter("acyear");

            try
            {
                if (checkedApps != null)
                {

                    for (int i = 0; i < checkedApps.length; i++)
                    {

                        sql=" insert into pmss_school_students_details(admission_no,student_name,parent_name,native_dist,native_mandal,address,caste_code,subcaste_code,admission_year,"
                            + "admission_dt,admission_class,present_class,student_photo,entered_by,entered_dt,stu_subcaste_new,mobilenumber,parent_proffession,annual_income,date_of_birth,"
                            + "pre_quarterly_marks,pre_annual_marks,achievements,health_problems,height,weight,blood_group,fresh_renewal,identification_marks,orphan,semi_orphan,"
                            + "rescued_child,victim,handycapped,school_code,class_promoted,dept_code,dist_office_code,applied_date,stu_id,status,pre_halfyearly_marks,ac_year,"
                            + "pre_quarterly_marks_max,pre_halfyearly_marks_max,pre_annual_marks_max,gender,boaders,from_school) "

                            + " select admission_no,student_name,parent_name,native_dist,"
                            + "native_mandal,address,caste_code,subcaste_code,admission_year,admission_dt,admission_class,present_class+1  as present_class,student_photo,entered_by,entered_dt,"
                            + "stu_subcaste_new,mobilenumber,parent_proffession,annual_income,date_of_birth,pre_quarterly_marks,pre_annual_marks,achievements,health_problems,"
                            + "height,weight,blood_group,'R' as fresh_renewal,identification_marks,orphan,semi_orphan,rescued_child,victim,handycapped,'"+request.getParameter("to_schools_selected")+"' as school_code,class_promoted,"
                            + "dept_code,dist_office_code,applied_date,(substring(stu_id,1,4))::int+1||substr(stu_id,5) as stu_id,'3' as status,pre_halfyearly_marks,(substring(stu_id,1,4))::int+1||'-'||(substring(stu_id,3,2))::int+2 as ac_year,pre_quarterly_marks_max,"
                            + "pre_halfyearly_marks_max,pre_annual_marks_max,gender,boaders,school_code from pmss_school_students_details "
                            + " where stu_id='"+checkedApps[i]+ "' and school_code='"+  Integer.parseInt(request.getParameter("schoolcode").trim())
                            + "' and ac_year=int4(substring('"+ac_year+"',1,4))-1||'-'||int4(substring('"+ac_year+"',6,2))-1";

                        gen.executeUpdate(sql);
                    }

                }

executeUpdate Method

public int executeUpdate(String sql)
    {
        Session session = sessionfactory.openSession();
        SQLQuery  query=null;
        int result=0;
        try
        {
            result=session.createSQLQuery(sql).executeUpdate();

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (session.isOpen())
            {
                session.close();
            }
        }

        return result;
    }

The columns in query are same in number.


问:
What is the use of "ADD CX,0F830H" in 8086 system date assembly language program
To get the date from the system we use

```<code>mov ah,2ah
int 21h
</code>```

ADD CX,0F830H  is used for the year part in the code.

What does the hexadecimal number 0F830h has to do with the year part here?

What is the significance of add cx,0f830h ?

Source for the code- https://github.com/kingspp/8086-MicroProcessor/blob/master/Date-Program.asm

答: That's a confusing way of writing sub cx, 2000, which in turn is done to get the last two digits of the year as the comment says later.

Body:
To get the date from the system we use

mov ah,2ah
int 21h

ADD CX,0F830H  is used for the year part in the code.

What does the hexadecimal number 0F830h has to do with the year part here?

What is the significance of add cx,0f830h ?

Source for the code- https://github.com/kingspp/8086-MicroProcessor/blob/master/Date-Program.asm


问:
Do Redis's GetDatabase() method caches all database tables?
I have cached my database using following code for Redis operations:

```<code>  public bool InitialiseCache()
    {
        try
        {
            _cache = Connection.GetDatabase();
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }
</code>```

I tried to debug and preview value of _cache but it does not display cached data (tables). I wanted to confirm that GetDatabase() method caches all tables. Is there any way to preview all Redis keys, or values?

答:
Short Answer :

No, Redis's GetDatabase() method DOES NOT caches all database tables

Long Answer :

As Per StackExchange.Redis on Github :

Using a redis database

Accessing a redis database is as simple as:

```<code>IDatabase db = redis.GetDatabase();
</code>```

The object returned from GetDatabase is a cheap pass-thru object, and does not need to be stored. Note that redis supports multiple
  databases (although this is not supported on "cluster"); this can be
  optionally specified in the call to GetDatabase. Additionally, if you
  plan to make use of the asynchronous API and you require the
  Task.AsyncState to have a value, this can also be specified:

```<code>int databaseNumber = ...
object asyncState = ...
IDatabase db = redis.GetDatabase(databaseNumber, asyncState);
</code>```

Once you have the IDatabase, it is simply a case of using the redis
  API. Note that all methods have both synchronous and asynchronous
  implementations. In line with Microsoft's naming guidance, the
  asynchronous methods all end ...Async(...), and are fully await-able
  etc.

Body:
I have cached my database using following code for Redis operations:

  public bool InitialiseCache()
    {
        try
        {
            _cache = Connection.GetDatabase();
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }

I tried to debug and preview value of _cache but it does not display cached data (tables). I wanted to confirm that GetDatabase() method caches all tables. Is there any way to preview all Redis keys, or values?

Body:
Short Answer :

No, Redis's GetDatabase() method DOES NOT caches all database tables

Long Answer :

As Per StackExchange.Redis on Github :

Using a redis database

Accessing a redis database is as simple as:

IDatabase db = redis.GetDatabase();

The object returned from GetDatabase is a cheap pass-thru object, and does not need to be stored. Note that redis supports multiple
  databases (although this is not supported on "cluster"); this can be
  optionally specified in the call to GetDatabase. Additionally, if you
  plan to make use of the asynchronous API and you require the
  Task.AsyncState to have a value, this can also be specified:

int databaseNumber = ...
object asyncState = ...
IDatabase db = redis.GetDatabase(databaseNumber, asyncState);

Once you have the IDatabase, it is simply a case of using the redis
  API. Note that all methods have both synchronous and asynchronous
  implementations. In line with Microsoft's naming guidance, the
  asynchronous methods all end ...Async(...), and are fully await-able
  etc.


问:
Java: Subtract '0' from char to get an int... why does this work?
This works fine:

```<code>int foo = bar.charAt(1) - '0';
</code>```

Yet this doesn't - because bar.charAt(x) returns a char:

```<code>int foo = bar.charAt(1);
</code>```

It seems that subtracting '0' from the char is casting it to an integer.

Why, or how,  does subtracting the string '0' (or is it a char?) convert another char in to an integer?

答:
The following code works perfectly fine!

```<code>int foo = bar.charAt(1);
</code>```

Similar to reference types, any Java primitive can be assigned without casting to another primitive of a type it is considered a subtype of. The subtyping rules for primitives are given by JLS section 4.10.1. char is considered a subtype of int, so any char may be assigned to an int.

Body:
This works fine:

int foo = bar.charAt(1) - '0';

Yet this doesn't - because bar.charAt(x) returns a char:

int foo = bar.charAt(1);

It seems that subtracting '0' from the char is casting it to an integer.

Why, or how,  does subtracting the string '0' (or is it a char?) convert another char in to an integer?

Body:
The following code works perfectly fine!

int foo = bar.charAt(1);

Similar to reference types, any Java primitive can be assigned without casting to another primitive of a type it is considered a subtype of. The subtyping rules for primitives are given by JLS section 4.10.1. char is considered a subtype of int, so any char may be assigned to an int.


问:
MFC CImage alpha blending gone wrong
I have to present images on a picture control that are a composition of two PNG files, where the top image has transparent pixels on certain positions.

The result should of plotter.png

with bar.png

overlapped on its top appears as (Notice the strange white contours on the bar):

but it should be:

The code I made for it is simple as

```<code>    CImage image;
    if (FAILED(image.Load(L"plotter.png")))
        return false;

    CImage imageBar;
    if (FAILED(imageBar.Load(L"bar.png")))
        return false;

    imageBar.AlphaBlend(image.GetDC(), CPoint());
    image.ReleaseDC();

    ((CStatic*)GetDlgItem(IDC_PICTURE))->SetBitmap(image);
</code>```

I have read the MSDN documentation on Alpha Blending a Bitmap and BLENDFUNCTION structure and did some experiments. A detail made me stare on the text I am quoting:

This flag is set when the bitmap has an Alpha channel (that is,
  per-pixel alpha). Note that the APIs use premultiplied alpha, which
  means that the red, green and blue channel values in the bitmap must
  be premultiplied with the alpha channel value. For example, if the
  alpha channel value is x, the red, green and blue channels must be
  multiplied by x and divided by 0xff prior to the call.

Alphablend uses premultiplied alpha, which means after loading I have to go to the bitmap and multiply every pixel by its own alpha. So I tried

```<code>for (int i = 0; i < imageBar.GetWidth(); i++)
{
    for (int j = 0; j < imageBar.GetHeight(); j++)
    {
        BYTE* ptr = (BYTE*) imageBar.GetPixelAddress(i, j);
        ptr[0] = (ptr[0] * ptr[3]) / 255;
        ptr[1] = (ptr[1] * ptr[3]) / 255;
        ptr[2] = (ptr[2] * ptr[3]) / 255;
    }
}
</code>```

before the AlphaBlendline and what I've got is still not satisfactory :(

So, how can I get a correctly composed image?

答:
After some days and night of desperation, I've finally found http://forums.codeguru.com/showthread.php?420631-setting-CImage-alpha-values&p=1560260#post1560260 which a solution similar to what I've tried, but with the addition of 127 to every pixel, which is a thing that worked but I've not understood at the time, nor I had made any effort to understand it yet. So before the AlphaBlend line now there is:

```<code>for (int i = 0; i < imageBar.GetWidth(); i++)
{
    for (int j = 0; j < imageBar.GetHeight(); j++)
    {
        BYTE* ptr = (BYTE*)imageBar.GetPixelAddress(i, j);
        ptr[0] = ((ptr[0] * ptr[3]) + 127) / 255;
        ptr[1] = ((ptr[1] * ptr[3]) + 127) / 255;
        ptr[2] = ((ptr[2] * ptr[3]) + 127) / 255;
    }
}
</code>```

and now the displayed image is well composed.

Title: MFC CImage alpha blending gone wrong

Body:
I have to present images on a picture control that are a composition of two PNG files, where the top image has transparent pixels on certain positions.

The result should of plotter.png

with bar.png

overlapped on its top appears as (Notice the strange white contours on the bar):

but it should be:

The code I made for it is simple as

    CImage image;
    if (FAILED(image.Load(L"plotter.png")))
        return false;

    CImage imageBar;
    if (FAILED(imageBar.Load(L"bar.png")))
        return false;

    imageBar.AlphaBlend(image.GetDC(), CPoint());
    image.ReleaseDC();

    ((CStatic*)GetDlgItem(IDC_PICTURE))->SetBitmap(image);

I have read the MSDN documentation on Alpha Blending a Bitmap and BLENDFUNCTION structure and did some experiments. A detail made me stare on the text I am quoting:

This flag is set when the bitmap has an Alpha channel (that is,
  per-pixel alpha). Note that the APIs use premultiplied alpha, which
  means that the red, green and blue channel values in the bitmap must
  be premultiplied with the alpha channel value. For example, if the
  alpha channel value is x, the red, green and blue channels must be
  multiplied by x and divided by 0xff prior to the call.

Alphablend uses premultiplied alpha, which means after loading I have to go to the bitmap and multiply every pixel by its own alpha. So I tried

for (int i = 0; i < imageBar.GetWidth(); i++)
{
    for (int j = 0; j < imageBar.GetHeight(); j++)
    {
        BYTE* ptr = (BYTE*) imageBar.GetPixelAddress(i, j);
        ptr[0] = (ptr[0] * ptr[3]) / 255;
        ptr[1] = (ptr[1] * ptr[3]) / 255;
        ptr[2] = (ptr[2] * ptr[3]) / 255;
    }
}

before the AlphaBlendline and what I've got is still not satisfactory :(

So, how can I get a correctly composed image?

Body:
After some days and night of desperation, I've finally found http://forums.codeguru.com/showthread.php?420631-setting-CImage-alpha-values&p=1560260#post1560260 which a solution similar to what I've tried, but with the addition of 127 to every pixel, which is a thing that worked but I've not understood at the time, nor I had made any effort to understand it yet. So before the AlphaBlend line now there is:

for (int i = 0; i < imageBar.GetWidth(); i++)
{
    for (int j = 0; j < imageBar.GetHeight(); j++)
    {
        BYTE* ptr = (BYTE*)imageBar.GetPixelAddress(i, j);
        ptr[0] = ((ptr[0] * ptr[3]) + 127) / 255;
        ptr[1] = ((ptr[1] * ptr[3]) + 127) / 255;
        ptr[2] = ((ptr[2] * ptr[3]) + 127) / 255;
    }
}

and now the displayed image is well composed.


问:
Generate random number between two numbers in JavaScript
Is there a way to generate a random number in a specified range with JavaScript ?

For example: a specified range from 1 to 6 were the random number could be either 1, 2, 3, 4, 5, or 6.

答:
TL;DR

```<code>function generateRandomInteger(min, max) {
  return Math.floor(min + Math.random()*(max - min + 1))
}
</code>```

To get the random number
generateRandomInteger(-20, 20);

EXPLANATION BELOW

integer - A number which is not a fraction; a whole number

We need to get a random number , say X between min and max.
X, min and max are all integers

i.e
min <= X <= max

If we subtract min from the equation, this is equivalent to

0 <= (X - min) <= (max - min)

Now, lets multiply this with a random number r
which is

0 <= (X - min) * r <= (max - min) * r

Now, lets add back min to the equation

min <= min + (X - min) * r <= min + (max - min) * r

For, any given X, the above equation satisfies only when r has range of [0,1] For any other values of r the above equation is unsatisfied.

Learn more about ranges [x,y] or (x,y) here

Our next step is to find a function which always results in a value which has a range of [0,1]

Now, the range of r i.e [0,1] is very similar to Math.random() function in Javascript. Isn't it?

The Math.random() function returns a floating-point, pseudo-random
number in the range [0, 1); that is, from 0 (inclusive) up to but not
including 1 (exclusive)

Random Function using Math.random() 0 <= r < 1

Notice that in Math.random() left bound is inclusive and the right bound is exclusive. This means min + (max - min) * r will evaluate to having a range from [min, max)

To include our right bound i.e [min,max] we increase the right bound by 1 and floor the result.

```<code>function generateRandomInteger(min, max) {
  return Math.floor(min + Math.random()*(max - min + 1))
}
</code>```

To get the random number

generateRandomInteger(-20, 20);

Body:
TL;DR

function generateRandomInteger(min, max) {
  return Math.floor(min + Math.random()*(max - min + 1))
}

To get the random number
generateRandomInteger(-20, 20);

EXPLANATION BELOW

integer - A number which is not a fraction; a whole number

We need to get a random number , say X between min and max.
X, min and max are all integers

i.e
min <= X <= max

If we subtract min from the equation, this is equivalent to

0 <= (X - min) <= (max - min)

Now, lets multiply this with a random number r
which is

0 <= (X - min) * r <= (max - min) * r

Now, lets add back min to the equation

min <= min + (X - min) * r <= min + (max - min) * r

For, any given X, the above equation satisfies only when r has range of [0,1] For any other values of r the above equation is unsatisfied.

Learn more about ranges [x,y] or (x,y) here

Our next step is to find a function which always results in a value which has a range of [0,1]

Now, the range of r i.e [0,1] is very similar to Math.random() function in Javascript. Isn't it?

The Math.random() function returns a floating-point, pseudo-random
number in the range [0, 1); that is, from 0 (inclusive) up to but not
including 1 (exclusive)

Random Function using Math.random() 0 <= r < 1

Notice that in Math.random() left bound is inclusive and the right bound is exclusive. This means min + (max - min) * r will evaluate to having a range from [min, max)

To include our right bound i.e [min,max] we increase the right bound by 1 and floor the result.

function generateRandomInteger(min, max) {
  return Math.floor(min + Math.random()*(max - min + 1))
}

To get the random number

generateRandomInteger(-20, 20);


问:
JMockit and parameterized tests (JUnit parameterized or JUnitParams)
I was wondering if JMockit is compatible with JUnit parameterized tests or JUnitParams, because I haven't found a way to make them work together so far, since you can only specify one JUnit runner, and both JMockit, JUnitParams and Parameterized require you to use their own runner. </p>

答: JMockit does not require you to use an own runner. Using an own runner is just one of the possible ways to make sure JMockit got initialized properly before your tests run. You can also add JMockit as Java agent via commandline parameters, depend on classpath ordering (having JMockit in the classpath before JUnit) or call the JMockit initialization method manually before the actual tests start if you have such a place where you can call it, e.g. if you use an own JUnit runner.


问:
Can not get checkbox text from ListView CheckBox?
Firstly, let me tell what I am trying to do...

Please,see the screenshot.When user select a checkbox,I want to add the digit given in the left and show the total on top.example: if user select 3 boxes named chairman,auditor and jr. officer,it will add 3 digits from the left of checkbox. that is 1+1+1=3 and this total will take place on top instead of 0.

I have implemented using listview with checkbox.But now can't add the digits.This values are coming from database.
Let me show you my code.

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

    // Sets the Toolbar to act as the ActionBar for this Activity window.
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Remove default title text
    getSupportActionBar().setDisplayShowTitleEnabled(false);
    // Get access to the custom title view
    TextView mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);

    contactList = new ArrayList<>();

    lv = (ListView) findViewById(R.id.list);

    new GetContacts().execute();
    openInfo();

}

private class GetContacts extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(GroupSms.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url);

        Log.e(TAG, "Response from url: " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                JSONArray contacts = jsonObj.getJSONArray("all_group");

                // looping through All Contacts
                for (int i = 0; i < contacts.length(); i++) {
                    JSONObject c = contacts.getJSONObject(i);

                    gid = c.getString("group_id");
                    groupName = c.getString("group_name");
                    total = c.getString("total");

                    // tmp hash map for single contact
                    HashMap<String, String> contact = new HashMap<>();

                    contact.put("group_id", gid);
                    contact.put("group_name", groupName);
                    contact.put("total", total);
                    //contact.put("mobile", mobile);

                    // adding contact to contact list
                    contactList.add(contact);

                    Log.d("Contactlist", String.valueOf(contactList));

                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
        } else {
            Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Couldn't get json from server. Check LogCat for possible errors!",
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        if (pDialog.isShowing())
            pDialog.dismiss();
        /* *
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(
                GroupSms.this,
                contactList,
                R.layout.groups,
                new String[]{
                        "group_name","total"},
                new int[]{R.id.check,R.id.groupsNo});

        lv.setAdapter(adapter);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                CheckBox cb = (CheckBox) view.findViewById(R.id.check);

                cb.setChecked(!cb.isChecked());
                if(cb.isChecked())
                {
                    //TextView cTotal = (TextView) findViewById(R.id.idTotal);
                    Toast.makeText(GroupSms.this,cb.getText(),Toast.LENGTH_SHORT).show();
                }

            }
        });

    }

}
</code>```

答: Try On lv.setOnItemClickListener event on AdapterClass.</p>

Body:
Firstly, let me tell what I am trying to do...

Please,see the screenshot.When user select a checkbox,I want to add the digit given in the left and show the total on top.example: if user select 3 boxes named chairman,auditor and jr. officer,it will add 3 digits from the left of checkbox. that is 1+1+1=3 and this total will take place on top instead of 0.

I have implemented using listview with checkbox.But now can't add the digits.This values are coming from database.
Let me show you my code.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_group_sms);

    // Sets the Toolbar to act as the ActionBar for this Activity window.
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Remove default title text
    getSupportActionBar().setDisplayShowTitleEnabled(false);
    // Get access to the custom title view
    TextView mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);

    contactList = new ArrayList<>();

    lv = (ListView) findViewById(R.id.list);

    new GetContacts().execute();
    openInfo();

}

private class GetContacts extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(GroupSms.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url);

        Log.e(TAG, "Response from url: " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                JSONArray contacts = jsonObj.getJSONArray("all_group");

                // looping through All Contacts
                for (int i = 0; i < contacts.length(); i++) {
                    JSONObject c = contacts.getJSONObject(i);

                    gid = c.getString("group_id");
                    groupName = c.getString("group_name");
                    total = c.getString("total");

                    // tmp hash map for single contact
                    HashMap<String, String> contact = new HashMap<>();

                    contact.put("group_id", gid);
                    contact.put("group_name", groupName);
                    contact.put("total", total);
                    //contact.put("mobile", mobile);

                    // adding contact to contact list
                    contactList.add(contact);

                    Log.d("Contactlist", String.valueOf(contactList));

                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
        } else {
            Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Couldn't get json from server. Check LogCat for possible errors!",
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        if (pDialog.isShowing())
            pDialog.dismiss();
        /* *
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(
                GroupSms.this,
                contactList,
                R.layout.groups,
                new String[]{
                        "group_name","total"},
                new int[]{R.id.check,R.id.groupsNo});

        lv.setAdapter(adapter);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                CheckBox cb = (CheckBox) view.findViewById(R.id.check);

                cb.setChecked(!cb.isChecked());
                if(cb.isChecked())
                {
                    //TextView cTotal = (TextView) findViewById(R.id.idTotal);
                    Toast.makeText(GroupSms.this,cb.getText(),Toast.LENGTH_SHORT).show();
                }

            }
        });

    }

}


答:
You are still blocking the main thread too long - be it during launch or later. Only do lightweight GUI work on the main thread. The main thread is also blocked if you perform work on a second thread but wait in your main thread for the results.

Instruments is your friend here.

Title: iPhone application crash on launch


问:
How can I create Min stl priority_queue?
The default stl priority queue is a Max one (Top function returns the largest element).

Say, for simplicity, that it is a priority queue of int values.

答:
You can do it in multiple ways:

1. Using greater as comparison function :

```<code> #include <bits/stdc++.h>

using namespace std;

int main()
{
    priority_queue<int,vector<int>,greater<int> >pq;
    pq.push(1);
    pq.push(2);
    pq.push(3);

    while(!pq.empty())
    {
        int r = pq.top();
        pq.pop();
        cout<<r<< " ";
    }
    return 0;
}
</code>```

2. Inserting values by changing their sign (using minus (-) for positive number and using plus (+) for negative number :

```<code>int main()
{
    priority_queue<int>pq2;
    pq2.push(-1); //for +1
    pq2.push(-2); //for +2
    pq2.push(-3); //for +3
    pq2.push(4);  //for -4

    while(!pq2.empty())
    {
        int r = pq2.top();
        pq2.pop();
        cout<<-r<<" ";
    }

    return 0;
}
</code>```

3. Using custom structure or class :

```<code>struct compare
{
    bool operator()(const int & a, const int & b)
    {
        return a>b;
    }
};

int main()
{

    priority_queue<int,vector<int>,compare> pq;
    pq.push(1);
    pq.push(2);
    pq.push(3);

    while(!pq.empty())
    {
        int r = pq.top();
        pq.pop();
        cout<<r<<" ";
    }

    return 0;
}
</code>```

4. Using custom structure or class you can use priority_queue in any order.
   Suppose, we want to sort people in descending order according to their salary and if tie then according to their age.

```<code>    struct people
    {
        int age,salary;

    };
    struct compare{
    bool operator()(const people & a, const people & b)
        {
            if(a.salary==b.salary)
            {
                return a.age>b.age;
            }
            else
            {
                return a.salary>b.salary;
            }

    }
    };
    int main()
    {

        priority_queue<people,vector<people>,compare> pq;
        people person1,person2,person3;
        person1.salary=100;
        person1.age = 50;
        person2.salary=80;
        person2.age = 40;
        person3.salary = 100;
        person3.age=40;

        pq.push(person1);
        pq.push(person2);
        pq.push(person3);

        while(!pq.empty())
        {
            people r = pq.top();
            pq.pop();
            cout<<r.salary<<" "<<r.age<<endl;
    }
</code>```

Same result can be obtained by operator overloading :

```<code>struct people
{
int age,salary;

bool operator< (const people & p)const
{
    if(salary==p.salary)
    {
        return age>p.age;
    }
    else
    {
        return salary>p.salary;
    }
}};
</code>```

In main function :

```<code>priority_queue<people> pq;
people person1,person2,person3;
person1.salary=100;
person1.age = 50;
person2.salary=80;
person2.age = 40;
person3.salary = 100;
person3.age=40;

pq.push(person1);
pq.push(person2);
pq.push(person3);

while(!pq.empty())
{
    people r = pq.top();
    pq.pop();
    cout<<r.salary<<" "<<r.age<<endl;
}
</code>```

Body:
You can do it in multiple ways:

1. Using greater as comparison function :

 #include <bits/stdc++.h>

using namespace std;

int main()
{
    priority_queue<int,vector<int>,greater<int> >pq;
    pq.push(1);
    pq.push(2);
    pq.push(3);

    while(!pq.empty())
    {
        int r = pq.top();
        pq.pop();
        cout<<r<< " ";
    }
    return 0;
}

2. Inserting values by changing their sign (using minus (-) for positive number and using plus (+) for negative number :

int main()
{
    priority_queue<int>pq2;
    pq2.push(-1); //for +1
    pq2.push(-2); //for +2
    pq2.push(-3); //for +3
    pq2.push(4);  //for -4

    while(!pq2.empty())
    {
        int r = pq2.top();
        pq2.pop();
        cout<<-r<<" ";
    }

    return 0;
}

3. Using custom structure or class :

struct compare
{
    bool operator()(const int & a, const int & b)
    {
        return a>b;
    }
};

int main()
{

    priority_queue<int,vector<int>,compare> pq;
    pq.push(1);
    pq.push(2);
    pq.push(3);

    while(!pq.empty())
    {
        int r = pq.top();
        pq.pop();
        cout<<r<<" ";
    }

    return 0;
}

4. Using custom structure or class you can use priority_queue in any order.
   Suppose, we want to sort people in descending order according to their salary and if tie then according to their age.

    struct people
    {
        int age,salary;

    };
    struct compare{
    bool operator()(const people & a, const people & b)
        {
            if(a.salary==b.salary)
            {
                return a.age>b.age;
            }
            else
            {
                return a.salary>b.salary;
            }

    }
    };
    int main()
    {

        priority_queue<people,vector<people>,compare> pq;
        people person1,person2,person3;
        person1.salary=100;
        person1.age = 50;
        person2.salary=80;
        person2.age = 40;
        person3.salary = 100;
        person3.age=40;

        pq.push(person1);
        pq.push(person2);
        pq.push(person3);

        while(!pq.empty())
        {
            people r = pq.top();
            pq.pop();
            cout<<r.salary<<" "<<r.age<<endl;
    }

Same result can be obtained by operator overloading :

struct people
{
int age,salary;

bool operator< (const people & p)const
{
    if(salary==p.salary)
    {
        return age>p.age;
    }
    else
    {
        return salary>p.salary;
    }
}};

In main function :

priority_queue<people> pq;
people person1,person2,person3;
person1.salary=100;
person1.age = 50;
person2.salary=80;
person2.age = 40;
person3.salary = 100;
person3.age=40;

pq.push(person1);
pq.push(person2);
pq.push(person3);

while(!pq.empty())
{
    people r = pq.top();
    pq.pop();
    cout<<r.salary<<" "<<r.age<<endl;
}


问:
Convert hex string to int
I am trying to convert a string that is 8 characters long of hex code into an integer so that I can do int comparison instead of string comparisons over a lot of different values.

I know this is fairly trivial in C++ but I need to do it in Java.  The test case I need to satisfy is essentially to Convert "AA0F245C" to int and then back to that string so that I know it is converting right.

I have tried the following:

```<code>int decode = Integer.decode("0xAA0F245C");  // NumberFormatException
int decode2 = Integer.decode("AA0F245C"); //NumberFormatException
int parseInt = Integer.parseInt("AA0F245C", 16); //NumberFormatException
int valueOf = Integer.valueOf("AA0F245C", 16); //NumberFormatException
</code>```

I have also tried doing it two characters at a time and multiplying the results, which the conversion works but the number is not right.

```<code>int id = 0;
for (int h = 0; h < hex.length(); h= h+2)
{
    String sub = hex.subSequence(h, h+2).toString();

if (id == 0)
    id = Integer.valueOf(sub, 16);
else
    id *= Integer.valueOf(sub, 16);
 }
//ID = 8445600 which = 80DEA0 if I convert it back.
</code>```

I can not use third party libraries just so you know, so this has to be done in Java standard libraries.

Thank you for your help in advance.

答:
This is the right answer:

myPassedColor = "#ffff8c85"
int colorInt = Color.parseColor(myPassedColor)

Title: Convert hex string to int

Body:
I am trying to convert a string that is 8 characters long of hex code into an integer so that I can do int comparison instead of string comparisons over a lot of different values.

I know this is fairly trivial in C++ but I need to do it in Java.  The test case I need to satisfy is essentially to Convert "AA0F245C" to int and then back to that string so that I know it is converting right.

I have tried the following:

int decode = Integer.decode("0xAA0F245C");  // NumberFormatException
int decode2 = Integer.decode("AA0F245C"); //NumberFormatException
int parseInt = Integer.parseInt("AA0F245C", 16); //NumberFormatException
int valueOf = Integer.valueOf("AA0F245C", 16); //NumberFormatException

I have also tried doing it two characters at a time and multiplying the results, which the conversion works but the number is not right.

int id = 0;
for (int h = 0; h < hex.length(); h= h+2)
{
    String sub = hex.subSequence(h, h+2).toString();

if (id == 0)
    id = Integer.valueOf(sub, 16);
else
    id *= Integer.valueOf(sub, 16);
 }
//ID = 8445600 which = 80DEA0 if I convert it back.

I can not use third party libraries just so you know, so this has to be done in Java standard libraries.

Thank you for your help in advance.


问:
Redirect output to two files in python
I am writing code where i want to redirect output two different files in python

one for log purpose and another for fabric code creation.

Below is the code which redirect output to two different files:

```<code>import sys
print('###################################Creating storage commands         Variables##########################')
storage_file = open("Storage-output.txt", 'w')
sys.stdout = storage_file
print ('network port show')
print ('Storage Commands are completed')
storage_file.close()
sys.stdout = sys.__stdout__

# write fabric code
fabric_file = open("Fabric_code.py", 'w')
print"from fabric.api import run"
print"def host_type():"
print"    run('rows 0', shell=False)"
print"    run('networ port show', shell=false)"
fabric_file.close()
sys.stdout = sys.__stdout__
storage_file = open("Storage-output.txt", 'a')
sys.stdout = storage_file
print('###############Genarating aggregate command#############')
print ('storage aggregate create -aggregate aggr_fab -diskcount 6 -raidtype    raid_dp", shell=False')
storage_file.close()
sys.stdout = sys.__stdout__
# write fabric code
fabric_file = open("Fabric_code.py", 'a')
print"   run('storage aggregate create -aggregate aggr_fab -diskcount 6 -  raidtype raid_dp', shell=False) "
fabric_file.close()
sys.stdout = sys.__stdout__
</code>```

In Above code creating one for log file Storage_file to store this file for records and  Fabric_code file to genarate fabric code.

My code generates 1000's of commands I do not want to open and close multiple times for two different files again and again in the python code.

Instead of this is there any solution where i can redirect print output to two direct files without opening and closing

答:
You should refactor your code by opening the files once in the beginning, then writing your files and closing the files in the end. From the above example we can do the following:</p>

```<code>import sys

# Open files
storage_file = open("Storage-output.txt", 'w')
fabric_file = open("Fabric_code.py", 'w')

# ===================
# Write Block
# ===================
print('###################################Creating storage commands         Variables##########################')
sys.stdout = storage_file
print ('network port show')
print ('Storage Commands are completed')
sys.stdout = sys.__stdout__

# write fabric code
print"from fabric.api import run"
print"def host_type():"
print"    run('rows 0', shell=False)"
print"    run('networ port show', shell=false)"
sys.stdout = sys.__stdout__
sys.stdout = storage_file
print('###############Genarating aggregate command#############')
print ('storage aggregate create -aggregate aggr_fab -diskcount 6 -raidtype    raid_dp", shell=False')
sys.stdout = sys.__stdout__
# write fabric code
print"   run('storage aggregate create -aggregate aggr_fab -diskcount 6 -  raidtype raid_dp', shell=False) "
sys.stdout = sys.__stdout__

# closing files
storage_file.close()
fabric_file.close()
</code>```

Title: Redirect output to two files in python

Body:
I am writing code where i want to redirect output two different files in python

one for log purpose and another for fabric code creation.

Below is the code which redirect output to two different files:

import sys
print('###################################Creating storage commands         Variables##########################')
storage_file = open("Storage-output.txt", 'w')
sys.stdout = storage_file
print ('network port show')
print ('Storage Commands are completed')
storage_file.close()
sys.stdout = sys.__stdout__

# write fabric code
fabric_file = open("Fabric_code.py", 'w')
print"from fabric.api import run"
print"def host_type():"
print"    run('rows 0', shell=False)"
print"    run('networ port show', shell=false)"
fabric_file.close()
sys.stdout = sys.__stdout__
storage_file = open("Storage-output.txt", 'a')
sys.stdout = storage_file
print('###############Genarating aggregate command#############')
print ('storage aggregate create -aggregate aggr_fab -diskcount 6 -raidtype    raid_dp", shell=False')
storage_file.close()
sys.stdout = sys.__stdout__
# write fabric code
fabric_file = open("Fabric_code.py", 'a')
print"   run('storage aggregate create -aggregate aggr_fab -diskcount 6 -  raidtype raid_dp', shell=False) "
fabric_file.close()
sys.stdout = sys.__stdout__

In Above code creating one for log file Storage_file to store this file for records and  Fabric_code file to genarate fabric code.

My code generates 1000's of commands I do not want to open and close multiple times for two different files again and again in the python code.

Instead of this is there any solution where i can redirect print output to two direct files without opening and closing

Body:
You should refactor your code by opening the files once in the beginning, then writing your files and closing the files in the end. From the above example we can do the following:

import sys

# Open files
storage_file = open("Storage-output.txt", 'w')
fabric_file = open("Fabric_code.py", 'w')

# ===================
# Write Block
# ===================
print('###################################Creating storage commands         Variables##########################')
sys.stdout = storage_file
print ('network port show')
print ('Storage Commands are completed')
sys.stdout = sys.__stdout__

# write fabric code
print"from fabric.api import run"
print"def host_type():"
print"    run('rows 0', shell=False)"
print"    run('networ port show', shell=false)"
sys.stdout = sys.__stdout__
sys.stdout = storage_file
print('###############Genarating aggregate command#############')
print ('storage aggregate create -aggregate aggr_fab -diskcount 6 -raidtype    raid_dp", shell=False')
sys.stdout = sys.__stdout__
# write fabric code
print"   run('storage aggregate create -aggregate aggr_fab -diskcount 6 -  raidtype raid_dp', shell=False) "
sys.stdout = sys.__stdout__

# closing files
storage_file.close()
fabric_file.close()


问:
What is theorem of arrest?
Someone mentioned it to me as something important related to the Turing machine but I can't find anything related to such theorem anywhere... Can someone help me or is the said theorem with the wrong name?</p>

答:
In context, it sounds like a mistranslation of the halting problem.

To be sure, you will have to ask the person who said it to you. They are the only ones who know what they intended to say, particularly as the only result on Google for "theorem of arrest" is this page.

Title: What is theorem of arrest?


问:
Why we use superclass type object that reference to subclass object
I might sound dumb asking this question or internet would have lot of reference about this question. But trust me I din't find any answer that answer properly. So I decided to ask this question

So here is
why do we declare object this way eg
    Map m = new HashMap()
why not
    HashMap m = new HashMap()

in general why we declare object of superclass type that reference to subclass object.

答:
Well, this let you to change the implementation without to relay on a specific class.

Please consider just the example you've done, we prefer to use

```<code>Map<String, String> m2 = new HashMap<>();
</code>```

over

```<code>HashMap<String, String> m2 = new HashMap<>();
</code>```

This let you the freedom to choose another implementation which could be more performing.

```<code>Map<String, String> m2 = new TreeMap<>();
</code>```

Body:
Well, this let you to change the implementation without to relay on a specific class.

Please consider just the example you've done, we prefer to use

Map<String, String> m2 = new HashMap<>();

over

HashMap<String, String> m2 = new HashMap<>();

This let you the freedom to choose another implementation which could be more performing.

Map<String, String> m2 = new TreeMap<>();


问:
How to find all rows with background-color yellow using jquery?
I would like to find all rows with attribute background-color=rgb(255, 255, 0).
Pressing on the button 'Search' should do this. I don't understand why this is not working. Nothing is found. Code for searching:

```<code>$("#btnSearch").click(function(){
  var rows = $("#tbl1 tr[style='background-color:rgb(255, 255, 0)']");
})
</code>```

Whole example is here

答:
Use jQuery .filter() to filtering selected tr and select only tr has target background color. In function callback get background-color of tr using this.style.backgroundColor and check that is equal to  rgb(255, 255, 0) or not.

```<code>$("#btnSearch").click(function(){
  var trs = $("#tbl1 tr").filter(function(){
    return this.style.backgroundColor == "rgb(255, 255, 0)";
  });
});
</code>```

Note that in the bottom example after click, color of target tr changed to red.

$("#btnSearch").click(function(){
  $("#tbl1 tr").filter(function(){
    return this.style.backgroundColor == "rgb(255, 255, 0)";
  }).css("color", "red");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='tbl1' class="table table-hover table-bordered">
  <tr style="background-color: rgb(255, 255, 0);">
    <td>1</td><td>2</td><td>3</td>
  </tr>
  <tr style="background-color: rgb(255, 255, 255);">
    <td>1</td><td>2</td><td>3</td>
  </tr>
  <tr style="background-color: rgb(0, 0, 0);">
    <td>1</td><td>2</td><td>3</td>
  </tr>
  <tr style="background-color: rgb(255, 255, 0);">
    <td>1</td><td>2</td><td>3</td>
  </tr>
  <tr>
   <td>1</td><td>2</td><td>3</td>
  </tr>
</table>
<button id="btnSearch">Search</button></code>```

Check result of code on full html in demo

Body:
I would like to find all rows with attribute background-color=rgb(255, 255, 0).
Pressing on the button 'Search' should do this. I don't understand why this is not working. Nothing is found. Code for searching:

$("#btnSearch").click(function(){
  var rows = $("#tbl1 tr[style='background-color:rgb(255, 255, 0)']");
})

Whole example is here

Body:
Use jQuery .filter() to filtering selected tr and select only tr has target background color. In function callback get background-color of tr using this.style.backgroundColor and check that is equal to  rgb(255, 255, 0) or not.

$("#btnSearch").click(function(){
  var trs = $("#tbl1 tr").filter(function(){
    return this.style.backgroundColor == "rgb(255, 255, 0)";
  });
});

Note that in the bottom example after click, color of target tr changed to red.

$("#btnSearch").click(function(){
  $("#tbl1 tr").filter(function(){
    return this.style.backgroundColor == "rgb(255, 255, 0)";
  }).css("color", "red");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='tbl1' class="table table-hover table-bordered">
  <tr style="background-color: rgb(255, 255, 0);">
    <td>1</td><td>2</td><td>3</td>
  </tr>
  <tr style="background-color: rgb(255, 255, 255);">
    <td>1</td><td>2</td><td>3</td>
  </tr>
  <tr style="background-color: rgb(0, 0, 0);">
    <td>1</td><td>2</td><td>3</td>
  </tr>
  <tr style="background-color: rgb(255, 255, 0);">
    <td>1</td><td>2</td><td>3</td>
  </tr>
  <tr>
   <td>1</td><td>2</td><td>3</td>
  </tr>
</table>
<button id="btnSearch">Search</button>

Check result of code on full html in demo


问:
How do I get document height using vh units in jQuery?
```<code>$(window).scroll(function() {
   $scrollingDiv.css("display", (($(window).scrollTop() / $(document).height()) > 0.1) ? "block" : "");
});
</code>```

How can I change the unit $(document).height()) > 0.1) to 100vh? I don't have much jQuery experience.

答:
VH : Viewport Height is similar to $(window).height(); Source

So you can check the condition if (windowHeight > 0.1) then

```<code>$("body").height(windowHeight);
</code>```

Code:

```<code>$(document).ready(function() {
  var windowHeight = $(window).height();

  if (windowHeight > 0.1) {
    alert("height is greater than 0.1");
    $("body").height(windowHeight);
  } else {
    alert("height is less than 0.1");
  }

});
</code>```

Codepen link: https://codepen.io/anon/pen/GWzVwO

Body:
$(window).scroll(function() {
   $scrollingDiv.css("display", (($(window).scrollTop() / $(document).height()) > 0.1) ? "block" : "");
});

How can I change the unit $(document).height()) > 0.1) to 100vh? I don't have much jQuery experience.

Body:
VH : Viewport Height is similar to $(window).height(); Source

So you can check the condition if (windowHeight > 0.1) then

$("body").height(windowHeight);

Code:

$(document).ready(function() {
  var windowHeight = $(window).height();

  if (windowHeight > 0.1) {
    alert("height is greater than 0.1");
    $("body").height(windowHeight);
  } else {
    alert("height is less than 0.1");
  }

});

Codepen link: https://codepen.io/anon/pen/GWzVwO