问:
One page menu on scroll with underline sliding links as active
I have a one page scroll menu with an underline sliding in from left to right when hovering a link. I need help on how to make a link active (meaning the line full) when in specific section such as "About".

Heres a picture that might help to show what I'm talking about (notice the link "Run" being highlighted):

I've seen many examples of a link being active online but its very confusing cause I haven't found one with my specific problem.

The closest example I found online was this http://jsfiddle.net/mdesdev/zkrh7/ but i still can't figure out how to fix the underline active.

I have created a js fiddle to show what I have so far:
    https://jsfiddle.net/rsrsrs/36rtdboh/

HTML:

```<code><div id="nav_Wrapper_dk">
<nav id="dk_Nav" role="navigation" class="cf">

    <div><a href="#home" class="link_Button sliding-u-l-r scroll">Home</a>      </div>
    <div><a href="#about" class="link_Button sliding-u-l-r scroll">About us</a></div>
    <div><a href="#link3" class="link_Button sliding-u-l-r">Gallery</a></div>
    <div><a href="#link4" class="link_Button sliding-u-l-r">Find Us</a></div>
    <div><a href="#link5" class="link_Button sliding-u-l-r">Contact</a></div>
    <div><a href="#link6" class="link_Button sliding-u-l-r">Catering</a></div>
    <div><a href="#link7" class="link_Button sliding-u-l-r">Blog</a></div>

</nav>

</div>

<div id="home"></div>

<div id="about"></div>
</code>```

CSS:

```<code>#nav_Wrapper_dk {
  position: fixed;
  width: 100%;
  height: 50px;
  background: white;
  border-bottom: 1px solid #f1f1f1;
}

#dk_Nav {
    width: 742.6167px;
    height: 50px;
    margin-left: auto;
    margin-right: auto;
    top: 0;
    right: 0;
    left: 0;
    z-index: 2001;
    background: white;
}

    #dk_Nav div {
        margin-top: 11px;
    }

    .link_Button {
        display: block;
        float: left;
        height: 40px;
        font-family: 'Open Sans', sans-serif;
        font-size: .7em;
        color: black;
        line-height: 3.3em;
        text-transform: uppercase;
        letter-spacing: .2em;
        margin-right: 44.8px;
    }

#dk_Nav div a {
  text-decoration: none
}

    /* LEFT TO RIGHT */
    .sliding-u-l-r {
        display: inline-block;
    }

    .sliding-u-l-r:after {
        content: '';
        display: block;
        height: 3px;
        width: 0;
        background: transparent;
        transition: width .3s ease, background-color .3s ease;
    }

    .sliding-u-l-r:hover:after {
        width: 100%;
        background: black;
    }

#home {
  width: 100%;
  height: 1000px;
  background: #ccc;
}

#about {
  width: 100%;
  height: 1000px;
  background: white;
}
</code>```

Javascript:

```<code>// Scroll Menu
jQuery(document).ready(function($) {
  $(".scroll").click(function(event) {
  event.preventDefault();
  $('html,body').animate( { scrollTop:$(this.hash).offset().top } , 1000);
  });
});
</code>```

Any sort of help would be highly appreciated, thanks!

答:
Here is the working example of what you want :

Basically on click of menu 2 interactions are happening-

The elements scroll smoothly to the given id definite point.(The scroll is smoother now.)

```<code>if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      if (target.length) {
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
</code>```

The current menu item gets the active class .

JS-

```<code>$(this).addClass('active').parent().siblings().children().removeClass('active');
</code>```

Css-

```<code>.sliding-u-l-r.active:after {
  width: 100%;
  background: black;
}
</code>```

Below is the compiled snippet of the above explanations :)

// Scroll Menu
$(function() {

  $("nav  a").click(function() {
    //**Add class active to current clicked menu item  and remove class active from other menu item**//
    $(this).addClass('active').parent().siblings().children().removeClass('active');
    //** Smooth scroll Logic **?
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      if (target.length) {
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#nav_Wrapper_dk {
  position: fixed;
  width: 100%;
  height: 50px;
  background: white;
  border-bottom: 1px solid #f1f1f1;
}

body {
  margin: 0px;
}

#dk_Nav {
  width: 742.6167px;
  height: 50px;
  margin-left: auto;
  margin-right: auto;
  top: 0;
  right: 0;
  left: 0;
  z-index: 2001;
  background: white;
}

#dk_Nav div {
  margin-top: 11px;
}

.link_Button {
  display: block;
  float: left;
  height: 40px;
  font-family: 'Open Sans', sans-serif;
  font-size: .7em;
  color: black;
  line-height: 3.3em;
  text-transform: uppercase;
  letter-spacing: .2em;
  margin-right: 44.8px;
}

#dk_Nav div a {
  text-decoration: none
}

/* LEFT TO RIGHT */

.sliding-u-l-r {
  display: inline-block;
}

.sliding-u-l-r:after {
  content: '';
  display: block;
  height: 3px;
  width: 0;
  background: transparent;
  transition: width .3s ease, background-color .3s ease;
}

.sliding-u-l-r:hover:after {
  width: 100%;
  background: black;
}

.sliding-u-l-r.active:after {
  width: 100%;
  background: black;
}

#home {
  width: 100%;
  height: 1000px;
  background: #ccc;
}

#about {
  width: 100%;
  height: 1000px;
  background: white;
}</code>```

Home

About us

Gallery

Find Us

Contact

Catering

Blog

```

Body:
I have a one page scroll menu with an underline sliding in from left to right when hovering a link. I need help on how to make a link active (meaning the line full) when in specific section such as "About".

Heres a picture that might help to show what I'm talking about (notice the link "Run" being highlighted):

I've seen many examples of a link being active online but its very confusing cause I haven't found one with my specific problem.

The closest example I found online was this http://jsfiddle.net/mdesdev/zkrh7/ but i still can't figure out how to fix the underline active.

I have created a js fiddle to show what I have so far:
    https://jsfiddle.net/rsrsrs/36rtdboh/

HTML:

Home

About us

Gallery

Find Us

Contact

Catering

Blog

CSS:

#nav_Wrapper_dk {
  position: fixed;
  width: 100%;
  height: 50px;
  background: white;
  border-bottom: 1px solid #f1f1f1;
}

#dk_Nav {
    width: 742.6167px;
    height: 50px;
    margin-left: auto;
    margin-right: auto;
    top: 0;
    right: 0;
    left: 0;
    z-index: 2001;
    background: white;
}

    #dk_Nav div {
        margin-top: 11px;
    }

    .link_Button {
        display: block;
        float: left;
        height: 40px;
        font-family: 'Open Sans', sans-serif;
        font-size: .7em;
        color: black;
        line-height: 3.3em;
        text-transform: uppercase;
        letter-spacing: .2em;
        margin-right: 44.8px;
    }

#dk_Nav div a {
  text-decoration: none
}

    /* LEFT TO RIGHT */
    .sliding-u-l-r {
        display: inline-block;
    }

    .sliding-u-l-r:after {
        content: '';
        display: block;
        height: 3px;
        width: 0;
        background: transparent;
        transition: width .3s ease, background-color .3s ease;
    }

    .sliding-u-l-r:hover:after {
        width: 100%;
        background: black;
    }

#home {
  width: 100%;
  height: 1000px;
  background: #ccc;
}

#about {
  width: 100%;
  height: 1000px;
  background: white;
}

Javascript:

// Scroll Menu
jQuery(document).ready(function($) {
  $(".scroll").click(function(event) {
  event.preventDefault();
  $('html,body').animate( { scrollTop:$(this.hash).offset().top } , 1000);
  });
});

Any sort of help would be highly appreciated, thanks!

Body:
Here is the working example of what you want :

Basically on click of menu 2 interactions are happening-

The elements scroll smoothly to the given id definite point.(The scroll is smoother now.)

if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      if (target.length) {
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }

The current menu item gets the active class .

JS-

$(this).addClass('active').parent().siblings().children().removeClass('active');

Css-

.sliding-u-l-r.active:after {
  width: 100%;
  background: black;
}

Below is the compiled snippet of the above explanations :)

// Scroll Menu
$(function() {

  $("nav  a").click(function() {
    //**Add class active to current clicked menu item  and remove class active from other menu item**//
    $(this).addClass('active').parent().siblings().children().removeClass('active');
    //** Smooth scroll Logic **?
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      if (target.length) {
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});

#nav_Wrapper_dk {
  position: fixed;
  width: 100%;
  height: 50px;
  background: white;
  border-bottom: 1px solid #f1f1f1;
}

body {
  margin: 0px;
}

#dk_Nav {
  width: 742.6167px;
  height: 50px;
  margin-left: auto;
  margin-right: auto;
  top: 0;
  right: 0;
  left: 0;
  z-index: 2001;
  background: white;
}

#dk_Nav div {
  margin-top: 11px;
}

.link_Button {
  display: block;
  float: left;
  height: 40px;
  font-family: 'Open Sans', sans-serif;
  font-size: .7em;
  color: black;
  line-height: 3.3em;
  text-transform: uppercase;
  letter-spacing: .2em;
  margin-right: 44.8px;
}

#dk_Nav div a {
  text-decoration: none
}

/* LEFT TO RIGHT */

.sliding-u-l-r {
  display: inline-block;
}

.sliding-u-l-r:after {
  content: '';
  display: block;
  height: 3px;
  width: 0;
  background: transparent;
  transition: width .3s ease, background-color .3s ease;
}

.sliding-u-l-r:hover:after {
  width: 100%;
  background: black;
}

.sliding-u-l-r.active:after {
  width: 100%;
  background: black;
}

#home {
  width: 100%;
  height: 1000px;
  background: #ccc;
}

#about {
  width: 100%;
  height: 1000px;
  background: white;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="nav_Wrapper_dk">
  <nav id="dk_Nav" role="navigation" class="cf">

    <div><a href="#home" class="link_Button sliding-u-l-r scroll">Home</a></div>
    <div><a href="#about" class="link_Button sliding-u-l-r scroll">About us</a></div>
    <div><a href="#link3" class="link_Button sliding-u-l-r">Gallery</a></div>
    <div><a href="#link4" class="link_Button sliding-u-l-r">Find Us</a></div>
    <div><a href="#link5" class="link_Button sliding-u-l-r">Contact</a></div>
    <div><a href="#link6" class="link_Button sliding-u-l-r">Catering</a></div>
    <div><a href="#link7" class="link_Button sliding-u-l-r">Blog</a></div>

  </nav>

</div>

<div id="home"></div>

<div id="about"></div>


来源: stackexchange

问:
Old EntityFramework DLL referenced somewhere in project
I am currently receiving the following error when I build my MVC 5 project.

"Failed to resolve assembly reference. The path 'D:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools..\IDE\EntityFramework.dll' must be either local to this computer or part of your trusted zone. If you have downloaded this template, you may need to 'Unblock' it using the properties page for the template file in File Explorer"

The problem started after I had an issue with my hard drive and had to re-install VS 2013. It is no longer installed on the D drive. I salvaged the project and simply reused it with the new installation of VS (on Windows 7).

I have also removed Entity Framework 6.1.1 from the project and re-installed to no avail. I seem to have a reference somewhere in the project and so far unable to find it.

I am relatively new to Visual Studio and any assistance would be appreciated.

答: The answer is posted in the comments of the original question. The reference was in the registry.</p>

ContentLicense: CC BY-SA 3.0


问:
php allow access to pages to only logged in users
I have 3 pages have html code similar to just example

<!DOCTYPE html>

html code

html code

html code

```

and have 2 php files login.php and logout.php , is it possible to strict access to the 3 pages only to login users

答:
This answer assumes that you have 3 php files and not html. You need to save those files as .php if you want to manage this using PHP.

Yes you can manage that using a variable or session.

You can redirect the user if they are not logged in. Or, you can show the part of the text and link only if they are logged in.

```<code><?php
    if($logged_in) {
?>
  <a href="hidddenpage">Only for logged in users</a>
<?php
    }
?>
</code>```

Body:
I have 3 pages have html code similar to just example

<!DOCTYPE html>

html code

html code

html code

and have 2 php files login.php and logout.php , is it possible to strict access to the 3 pages only to login users

Body:
This answer assumes that you have 3 php files and not html. You need to save those files as .php if you want to manage this using PHP.

Yes you can manage that using a variable or session.

You can redirect the user if they are not logged in. Or, you can show the part of the text and link only if they are logged in.

<?php
    if($logged_in) {
?>
  <a href="hidddenpage">Only for logged in users</a>
<?php
    }
?>


问:
Calculate the time stamp of year
Given that I have $num_years, how can I add it to Time()  to get a time stamp $num_years hence?

答:
try</p>

```<code>echo strtotime("now + $num_years years");
</code>```

ContentLicense: CC BY-SA 2.5

Title: Calculate the time stamp of year

Body:
try

echo strtotime("now + $num_years years");


问:
How to sort a HashMap by it amount of value in Java
I have declared a HashMap like this:

```<code>Map<Integer,ArrayList<Integer>> numbers = new HashMap<Integer,ArrayList<Integer>>();
</code>```

It has an output like this:

{64=[61, 68, 77], 65=[63, 66, 66, 70], 66=[69, 75, 2], 2=[4], 67=[65, 77], 4=[2]}

How do I count an value amount of its key?

So for 64 will be 3, 65 will be 4 and 66 will be 3

And then get a keys which has top 3 value amount
So the output in this case be like 65 64 66

答:
First: you cannot sort a HashMap, it's unsorted by nature and for performance reasons, you should use a LinkedHashMap for that, here's a java8 example which should solve your problem: </p>

```<code>class SortALinkedHashMapByTheSizeOfItsContainedArrayList {
LinkedHashMap<Integer,ArrayList<Integer>> numbers = new LinkedHashMap<>();

 void sortTheMap(){
    numbers.entrySet().stream()
            .sorted(Map.Entry.comparingByValue())
            .forEach(entry -> entry.getValue().size() );

 }
}
</code>```

Body:
I have declared a HashMap like this:

Map<Integer,ArrayList<Integer>> numbers = new HashMap<Integer,ArrayList<Integer>>();

It has an output like this:

{64=[61, 68, 77], 65=[63, 66, 66, 70], 66=[69, 75, 2], 2=[4], 67=[65, 77], 4=[2]}

How do I count an value amount of its key?

So for 64 will be 3, 65 will be 4 and 66 will be 3

And then get a keys which has top 3 value amount
So the output in this case be like 65 64 66

Body:
First: you cannot sort a HashMap, it's unsorted by nature and for performance reasons, you should use a LinkedHashMap for that, here's a java8 example which should solve your problem:

class SortALinkedHashMapByTheSizeOfItsContainedArrayList {
LinkedHashMap<Integer,ArrayList<Integer>> numbers = new LinkedHashMap<>();

 void sortTheMap(){
    numbers.entrySet().stream()
            .sorted(Map.Entry.comparingByValue())
            .forEach(entry -> entry.getValue().size() );

 }
}


问:
ASP.NET application architecture: bet practice for lenghty background processes?
I'll try to be brief.

What is the best practice for calling a routine from an asp.net web application that initiates a lengthy 'background' process that must be run?

For example, I want to click a button on my webpage that says "Run data conversion" (for example). This data conversion routine may take 20-40 minutes to run, so it seems to me putting all that code into a asp.net web page is not the way to go....there is no need to run this background process thru the IIS server. A sperate service or app etc seemx the way to go...

The web app, and the background process will both run on my dedicated Win2003 server so I have lots of options - but what is the best one?

答:
There are quite a few options, basically it boils down to you needing any sort of process that you can communicate with. The options I can think of off the top of my head are; a web-service running under another application pool; a windows service; a command-line process started by your ASP.NET code.

The next question is how to communicate with the other process. If you're using a database you could set up two common-tables that both processes can access. The website would place the request for work into a table that the second process would monitor. A second table could then be used for the results, which the web-site would monitor. Another option would be to use something like the Windows Communication Foundation (WCF) or .NET remoting to send events between the processes.

OwnerDisplayName: MrEd

LastEditorDisplayName: splattne

OwnerDisplayName: MattF


问:
CRM opportunity entity will not open "New Opportunity Product"
I am currently experiencing an issue within my Microsoft Dynamics CRM 4.0 Opportunity entity. When I try to input a new opportunity product. I select the button on the form “New Opportunity Product,” but instead of opening this, it does nothing at all. What could cause this to happen? And how would I go about fixing this issue for it is a critical part of our business. If you need a screen shot please let me know. Thank you for your help. I appreciate it.
Software/Hardware used:
Microsoft Dynamics CRM 4.0</p>

答: Do you have any products in the crm product catalog? Perhaps you need to add some.  </p>


问:
Do function x times in one minute (BPM)
Working out a BPM function in JS, where I'm playing a short sound for x times in one minute.

But it's not working for me, and this is what I have.
Can't find anything on this either.

The math should be simple: L*BPM/M, Length * How many times / 60 seconds.

I have tried with something like this:

```<code>var length = 0.5;
var bpm = 60;
var minute = 60;

for(var i = 0; i < bpm; i++) {
  setTimeout(function() {
    console.log('test');
  }, ((length*bpm) / minute * 1000 ) * i);
}
</code>```

答:
The math should be:
(60 / bpm) * 1000

I don't know what the length variable is, you didn't explain it.
The following will cause the "test" to run 180 times in a minute

```<code>var bpm = 180;
var interval = (60 / bpm) * 1000;
var ranTimes = 0;
var myTimeout = setInterval(function() {
    console.log('test' + ranTimes);
    ranTimes++;
    if (ranTimes >= bpm) {
        clearInterval(myTimeout);
    }
}, interval);
</code>```

Title: Do function x times in one minute (BPM)

Body:
Working out a BPM function in JS, where I'm playing a short sound for x times in one minute.

But it's not working for me, and this is what I have.
Can't find anything on this either.

The math should be simple: L*BPM/M, Length * How many times / 60 seconds.

I have tried with something like this:

var length = 0.5;
var bpm = 60;
var minute = 60;

for(var i = 0; i < bpm; i++) {
  setTimeout(function() {
    console.log('test');
  }, ((length*bpm) / minute * 1000 ) * i);
}

Body:
The math should be:
(60 / bpm) * 1000

I don't know what the length variable is, you didn't explain it.
The following will cause the "test" to run 180 times in a minute

var bpm = 180;
var interval = (60 / bpm) * 1000;
var ranTimes = 0;
var myTimeout = setInterval(function() {
    console.log('test' + ranTimes);
    ranTimes++;
    if (ranTimes >= bpm) {
        clearInterval(myTimeout);
    }
}, interval);


问:
XMLQUERY() WITHIN XMLATTRIBUTES()
I am doing some basic tasks using, sql/xml. I am currently working on an error message that I get when trying to compute a XMLQUERY() within a XMLATTRIBUTES() function. (See code below)

```<code>SELECT XMLELEMENT(NAME "Nodename",
       XMLATTRIBUTES(XMLQUERY('$t//Element/text()' PASSING Info AS "t") AS "hello"))
FROM Kurs
</code>```

The error message that I get, says that there is no qualified routine that can run the function. I cant copy-paste the error message because its in Swedish, but this should be enough.

Also this might help: SQLCODE=-440, SQLSTATE=42884, DRIVER=4.18.60

So my question is (I have been looking for the answer), why doesn't this work? I will always get a value from that XMLQUERY, and it should simply translate into a value and used by XMLATTRIBUTES()

Any documentation, or link, is welcomed as well!

Thank you in advance!

答:
The scalar function XMLQUERY returns an XML value. The function XMLATTRIBUTES expects an expression that returns a value of any type, but XML and some other types.

Thus, the functions are not compatible the way you are using them. DB2 cannot find a routine with that function signature. It results in that error -440.

How about wrapping a CAST/XMLCAST around it...?

Title: XMLQUERY() WITHIN XMLATTRIBUTES()

Body:
I am doing some basic tasks using, sql/xml. I am currently working on an error message that I get when trying to compute a XMLQUERY() within a XMLATTRIBUTES() function. (See code below)

SELECT XMLELEMENT(NAME "Nodename",
       XMLATTRIBUTES(XMLQUERY('$t//Element/text()' PASSING Info AS "t") AS "hello"))
FROM Kurs

The error message that I get, says that there is no qualified routine that can run the function. I cant copy-paste the error message because its in Swedish, but this should be enough.

Also this might help: SQLCODE=-440, SQLSTATE=42884, DRIVER=4.18.60

So my question is (I have been looking for the answer), why doesn't this work? I will always get a value from that XMLQUERY, and it should simply translate into a value and used by XMLATTRIBUTES()

Any documentation, or link, is welcomed as well!

Thank you in advance!


答:
Is this what you're after?</p>

```<code>$num_years = 5;
$future = strtotime("+{$num_years} years");
</code>```

Title: Calculate the time stamp of year

Body: Given that I have $num_years, how can I add it to Time()  to get a time stamp $num_years hence?

Body:
Is this what you're after?

$num_years = 5;
$future = strtotime("+{$num_years} years");


问:
app crashes when I hit the back button
I was trying to do some modifications to my AndroidManifest.xml but now when I go to the second activity(page) and then hit the back button, the app crashes.

Hers's is my MainActivity.java:

```<code>package com.example.ananaybatra.rape_freeindia;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

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

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void onGetNameClick(View view) {

        Intent getNameScreenIntent = new Intent(this, SecondScreen.class);
                // We ask for the Activity to start and don't expect a result to be sent back
               // startActivity(getNameScreenIntent);

                    final int result = 1;

                // To send data use putExtra with a String name followed by its value

                    getNameScreenIntent.putExtra("callingActivity", "MainActivity");

                    startActivityForResult(getNameScreenIntent, result);

    }

    @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                    super.onActivityResult(requestCode, resultCode, data);

                    // Create the TextView so I can put the users name on it
                    TextView usersNameMessage = (TextView) findViewById(R.id.textView2);

                    // Get the users name from the previous Activity
                    String nameSentBack = data.getStringExtra("UsersName");

                    // Add the users name to the end of the textView
                    usersNameMessage.append(" " + nameSentBack);

           }

}
</code>```

Here's my SecondScreen.java :

```<code>package com.example.ananaybatra.rape_freeindia;

import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.widget.TextView;
import android.view.View;
import android.widget.EditText;

public class SecondScreen extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second_layout1);

        Intent activityThatCalled = getIntent();
                    String previousActivity = activityThatCalled.getExtras().getString("callingActivity");

                    TextView callingActivityMessage = (TextView)

                                    findViewById(R.id.textView7);

                callingActivityMessage.append(" " + previousActivity);
            }

                public void onSendUsersName(View view) {

                // Get the users name from the EditText
                    EditText usersNameET = (EditText) findViewById(R.id.textView4);

                    // Get the name typed into the EditText
                    String usersName = String.valueOf(usersNameET.getText());

                    // Define our intention to go back to ActivityMain
                    Intent goingBack = new Intent();

                    // Define the String name and the value to assign to it
                    goingBack.putExtra("UsersName", usersName);

                    // Sends data back to the parent and can use RESULT_CANCELED, RESULT_OK, or any
                    // custom values starting at RESULT_FIRST_USER. RESULT_CANCELED is sent if
                    // this Activity crashes
                    setResult(RESULT_OK, goingBack);

                    // Close this Activity
                    this.finish();

                }
        }
</code>```

Here's my AndroidManifest.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.ananaybatra.rape_freeindia" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/Theme.AppCompat.Light.DarkActionBar">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".SecondScreen"
            android:label = "Get Name"
            android:theme = "@style/AppTheme"/>
    </application>

</manifest>
</code>```

What is my Error ??
Please reply, any help would be appreciated.

Thanks,
Regards.

答:
just Override the onBackPressed() function in your SecondScreen.class and add this..

```<code>@Override
    public void onBackPressed() {
        //pass whatevere you want
        intent.putExtra("result","Back Press");
        setResult(Activity.RESULT_CANCELED,intent);
        finish();
        super.onBackPressed();
    }
</code>```

And in The MainActivity.class file, check this

```<code> if (resultCode == Activity.RESULT_CANCELED) {
            //Write code if there's no result
            String result=data.getStringExtra("result");
        }
</code>```

in onActivityResult function

Title: app crashes when I hit the back button

Body:
I was trying to do some modifications to my AndroidManifest.xml but now when I go to the second activity(page) and then hit the back button, the app crashes.

Hers's is my MainActivity.java:

package com.example.ananaybatra.rape_freeindia;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

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

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void onGetNameClick(View view) {

        Intent getNameScreenIntent = new Intent(this, SecondScreen.class);
                // We ask for the Activity to start and don't expect a result to be sent back
               // startActivity(getNameScreenIntent);

                    final int result = 1;

                // To send data use putExtra with a String name followed by its value

                    getNameScreenIntent.putExtra("callingActivity", "MainActivity");

                    startActivityForResult(getNameScreenIntent, result);

    }

    @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                    super.onActivityResult(requestCode, resultCode, data);

                    // Create the TextView so I can put the users name on it
                    TextView usersNameMessage = (TextView) findViewById(R.id.textView2);

                    // Get the users name from the previous Activity
                    String nameSentBack = data.getStringExtra("UsersName");

                    // Add the users name to the end of the textView
                    usersNameMessage.append(" " + nameSentBack);

           }

}

Here's my SecondScreen.java :

package com.example.ananaybatra.rape_freeindia;

import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.widget.TextView;
import android.view.View;
import android.widget.EditText;

public class SecondScreen extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second_layout1);

        Intent activityThatCalled = getIntent();
                    String previousActivity = activityThatCalled.getExtras().getString("callingActivity");

                    TextView callingActivityMessage = (TextView)

                                    findViewById(R.id.textView7);

                callingActivityMessage.append(" " + previousActivity);
            }

                public void onSendUsersName(View view) {

                // Get the users name from the EditText
                    EditText usersNameET = (EditText) findViewById(R.id.textView4);

                    // Get the name typed into the EditText
                    String usersName = String.valueOf(usersNameET.getText());

                    // Define our intention to go back to ActivityMain
                    Intent goingBack = new Intent();

                    // Define the String name and the value to assign to it
                    goingBack.putExtra("UsersName", usersName);

                    // Sends data back to the parent and can use RESULT_CANCELED, RESULT_OK, or any
                    // custom values starting at RESULT_FIRST_USER. RESULT_CANCELED is sent if
                    // this Activity crashes
                    setResult(RESULT_OK, goingBack);

                    // Close this Activity
                    this.finish();

                }
        }

Here's my AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.ananaybatra.rape_freeindia" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/Theme.AppCompat.Light.DarkActionBar">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".SecondScreen"
            android:label = "Get Name"
            android:theme = "@style/AppTheme"/>
    </application>

</manifest>

What is my Error ??
Please reply, any help would be appreciated.

Thanks,
Regards.

Body:
just Override the onBackPressed() function in your SecondScreen.class and add this..

@Override
    public void onBackPressed() {
        //pass whatevere you want
        intent.putExtra("result","Back Press");
        setResult(Activity.RESULT_CANCELED,intent);
        finish();
        super.onBackPressed();
    }

And in The MainActivity.class file, check this

 if (resultCode == Activity.RESULT_CANCELED) {
            //Write code if there's no result
            String result=data.getStringExtra("result");
        }

in onActivityResult function


问:
how to add localization in ionic popup
i had completed ionic project. i would like to change lanaguages in this code. project title, place holder , button it had changed but popup was doesn't changed. i used this code in controller and language change file.

farmer-ctrl.js :

```<code>function showPopup () {
  $scope.data = {};
  var myPopup = $ionicPopup.show({
    template: '<input type="text" ng-model="data.category">',
    title: '{{"farmers_message" | translate}}', //'Enter CoconutType',
    scope: $scope,
    buttons: [
     { text: 'Cancel' },
      {
        text: '<b>{{"save_message" | translate}}</b>',
        type: 'button-positive',
        onTap: function (e) {
          if (!$scope.data.category) {
            //don't allow the user to close unless he enters producttype
            e.preventDefault();

          } else {
            $log.log('yes clicked: ', $scope.data.category);
            addProductType();
            return $scope.data.category;
          }
        }
      },
    ]
  });
  myPopup.then(function (res) {
    $log.log('Tapped!', res);
  });
}
</code>```

答:
To add localization in popup you need something like this:

```<code> var alertPopup = $ionicPopup.alert({
              title: $translate.instant('networkerror'),
                template: '<div><p  translate="onlinemessagepois"></p></div>'
      });
</code>```

where networkerror and onlinemessagepois exist in your local js files. (Example: "networkerror":"sometext","onlinemessagepois":"someothertext"  )

Note: you have to inject $translate in your controller.

Title: how to add localization in ionic popup

Body:
i had completed ionic project. i would like to change lanaguages in this code. project title, place holder , button it had changed but popup was doesn't changed. i used this code in controller and language change file.

farmer-ctrl.js :

function showPopup () {
  $scope.data = {};
  var myPopup = $ionicPopup.show({
    template: '<input type="text" ng-model="data.category">',
    title: '{{"farmers_message" | translate}}', //'Enter CoconutType',
    scope: $scope,
    buttons: [
     { text: 'Cancel' },
      {
        text: '{{"save_message" | translate}}',
        type: 'button-positive',
        onTap: function (e) {
          if (!$scope.data.category) {
            //don't allow the user to close unless he enters producttype
            e.preventDefault();

          } else {
            $log.log('yes clicked: ', $scope.data.category);
            addProductType();
            return $scope.data.category;
          }
        }
      },
    ]
  });
  myPopup.then(function (res) {
    $log.log('Tapped!', res);
  });
}

Body:
To add localization in popup you need something like this:

 var alertPopup = $ionicPopup.alert({
              title: $translate.instant('networkerror'),
                template: '<div><p  translate="onlinemessagepois"></p></div>'
      });

where networkerror and onlinemessagepois exist in your local js files. (Example: "networkerror":"sometext","onlinemessagepois":"someothertext"  )

Note: you have to inject $translate in your controller.


问:
how to adjust the height of a selectbox child control list in qooxdoo
I have a select box with exactyl 9 items and would like to adjust the hight in a manner that all items are shown. By default the ninth element ist hidden and the user needs to scroll down.

I have the following code:

```<code>var selectbox = new qx.ui.form.SelectBox());
var list = selectbox.getChildControl( 'list' );
list.setHeight( 600 );
</code>```

This code has no effect to the child control list

答:
The maxListHeight property should do what you need

http://www.qooxdoo.org/current/api/#qx.ui.form.AbstractSelectBox~maxListHeight

Body:
I have a select box with exactyl 9 items and would like to adjust the hight in a manner that all items are shown. By default the ninth element ist hidden and the user needs to scroll down.

I have the following code:

var selectbox = new qx.ui.form.SelectBox());
var list = selectbox.getChildControl( 'list' );
list.setHeight( 600 );

This code has no effect to the child control list


问:
Firebase Storage Custom metadata security rule for list of uids
I'm developing a messaging iOS app, where a user can send the same message to multiple people. The message is saved in firebase storage. I want to only enable the users who have been sent the message to be able to read it from storage. I am already implementing this rule structure in my firebase database.

In order to implement this for storage I add a list of uids to the message file customMetadata, including a fromUid key for the person who composed the message. I do the following in my iOS app:

```<code>    var metadataValues = [String:String]()

    for friendUid in friendsSelected.keys {
        metadataValues.updateValue(friendUid, forKey: friendUid) // how do I access these values in my security rules
    }
    metadataValues.updateValue(senderUid, forKey: "fromUid") // how do I access this in security rules
    let messageMetadata = FIRStorageMetadata()
    messageMetadata.customMetadata = metadataValues
</code>```

This was my attempt for my read and write security rules for the messages node in Firebase Storage but it doesn't work and the documentation is of no help.

```<code>    match /messages/{messageId} {

        allow read: if request.auth.uid == resource.metadata.request.auth.uid; // I want all friend uids to be able to read file
        allow write: if request.auth.uid == resource.metadata.fromUid; // only the person who create the message can access it

}
</code>```

My attempt doesn't work. How do I access the customMetadata variable with the keys 'fromUid' and the friends uids 'request.auth.uid' in my security rules??

As a sidenote, I assume there is no limit on how many keys I add to customMetadata?

答:
So I have managed to solve it. The problem I had was that I wasn't familiar with Javascript and so I was getting the syntax wrong. After looking into Javascript I was soon able to work it out.

Hope my answer helps anyone else but would recommend learning the basics of Javascript if you are in a similar position to me.

It's also worth noting that to access the file metadata you use request.resource.metadata before the write is executed and resource.metadata to access once uploaded.

```<code>    match /messages/{messageId} {

        allow write: if request.resource.metadata['fromUid'] == request.auth.uid;
        allow read: if resource.metadata[request.auth.uid] == request.auth.uid;
    }
</code>```

Body:
I'm developing a messaging iOS app, where a user can send the same message to multiple people. The message is saved in firebase storage. I want to only enable the users who have been sent the message to be able to read it from storage. I am already implementing this rule structure in my firebase database.

In order to implement this for storage I add a list of uids to the message file customMetadata, including a fromUid key for the person who composed the message. I do the following in my iOS app:

    var metadataValues = [String:String]()

    for friendUid in friendsSelected.keys {
        metadataValues.updateValue(friendUid, forKey: friendUid) // how do I access these values in my security rules
    }
    metadataValues.updateValue(senderUid, forKey: "fromUid") // how do I access this in security rules
    let messageMetadata = FIRStorageMetadata()
    messageMetadata.customMetadata = metadataValues

This was my attempt for my read and write security rules for the messages node in Firebase Storage but it doesn't work and the documentation is of no help.

    match /messages/{messageId} {

        allow read: if request.auth.uid == resource.metadata.request.auth.uid; // I want all friend uids to be able to read file
        allow write: if request.auth.uid == resource.metadata.fromUid; // only the person who create the message can access it

}

My attempt doesn't work. How do I access the customMetadata variable with the keys 'fromUid' and the friends uids 'request.auth.uid' in my security rules??

As a sidenote, I assume there is no limit on how many keys I add to customMetadata?

Body:
So I have managed to solve it. The problem I had was that I wasn't familiar with Javascript and so I was getting the syntax wrong. After looking into Javascript I was soon able to work it out.

Hope my answer helps anyone else but would recommend learning the basics of Javascript if you are in a similar position to me.

It's also worth noting that to access the file metadata you use request.resource.metadata before the write is executed and resource.metadata to access once uploaded.

    match /messages/{messageId} {

        allow write: if request.resource.metadata['fromUid'] == request.auth.uid;
        allow read: if resource.metadata[request.auth.uid] == request.auth.uid;
    }

ContentLicense: CC BY-SA 4.0


问:
Beautifulsoup - Getting values from a script tag
I'd like to extract the file links from a script tag.

How can i do it in python 2.7?

The structure is:

```<code><more script tags>
<script>
var settings=
    {
    primary: 'user-o',
    opt: window.userfiles,
    files:  [
                    {
                        //title: "PDF File",
                        image: 'http://url.com/num-001/cover.jpg',
                        sources:
                            [
                                {
                                    'label': '',
                                    'file': 'http://url.com/user/0054552/file-1.pdf',
                                    'type': 'user-o'
                                },
                                {
                                    'label': '',
                                    'file': 'http://url.com/user/0054552/file-2.pdf'
                                }

                            ],

                        other:
                            [
                                {
                                    file: 'http://url.com/user/0054552/other-file-0.pdf',
                                    kind: 'other-files'
                                }
                            ]
                    }

            ]
    };
</script>
<more script tags>
</code>```

I need all file links:

...url.com//user/0054552/file-1.pdf

...url.com//user/0054552/file-2.pdf

...url.com//user/0054552/other-file-0.pdf

I hope your support.

Thanks!

答:
Since you already got to this script, you just need to transform it in text and proccess it.

This code will:

split this script text block at each \n

for each string, search for substring .pdf

if string contains substring .pdf, split it at ': 'and replace ' and ,

append url part to a list called files

done

Code:

```<code>s = '''<more script tags>
<script>
var settings=
    {
    primary: 'user-o',
    opt: window.userfiles,
    files:  [
                    {
                        //title: "PDF File",
                        image: 'http://url.com/num-001/cover.jpg',
                        sources:
                            [
                                {
                                    'label': '',
                                    'file': 'http://url.com/user/0054552/file-1.pdf',
                                    'type': 'user-o'
                                },
                                {
                                    'label': '',
                                    'file': 'http://url.com/user/0054552/file-2.pdf'
                                }

                            ],

                        other:
                            [
                                {
                                    file: 'http://url.com/user/0054552/other-file-0.pdf',
                                    kind: 'other-files'
                                }
                            ]
                    }

            ]
    };
</script>
<more script tags>'''

files = []
data = s.split('\n')
for d in data:
    if '.pdf' in d:
        url = d.split(": ")[1].replace("'", "").replace(",", "")
        print(url)
        files.append(url)
</code>```

Output:

```<code>'http://url.com/user/0054552/file-1.pdf'
'http://url.com/user/0054552/file-2.pdf'
'http://url.com/user/0054552/other-file-0.pdf'
</code>```

Body:
I'd like to extract the file links from a script tag.

How can i do it in python 2.7?

The structure is:

<more script tags>

<more script tags>

I need all file links:

...url.com//user/0054552/file-1.pdf

...url.com//user/0054552/file-2.pdf

...url.com//user/0054552/other-file-0.pdf

I hope your support.

Thanks!

Body:
Since you already got to this script, you just need to transform it in text and proccess it.

This code will:

split this script text block at each \n

for each string, search for substring .pdf

if string contains substring .pdf, split it at ': 'and replace ' and ,

append url part to a list called files

done

Code:

s = '''<more script tags>
<script>
var settings=
    {
    primary: 'user-o',
    opt: window.userfiles,
    files:  [
                    {
                        //title: "PDF File",
                        image: 'http://url.com/num-001/cover.jpg',
                        sources:
                            [
                                {
                                    'label': '',
                                    'file': 'http://url.com/user/0054552/file-1.pdf',
                                    'type': 'user-o'
                                },
                                {
                                    'label': '',
                                    'file': 'http://url.com/user/0054552/file-2.pdf'
                                }

                            ],

                        other:
                            [
                                {
                                    file: 'http://url.com/user/0054552/other-file-0.pdf',
                                    kind: 'other-files'
                                }
                            ]
                    }

            ]
    };
</script>
<more script tags>'''

files = []
data = s.split('\n')
for d in data:
    if '.pdf' in d:
        url = d.split(": ")[1].replace("'", "").replace(",", "")
        print(url)
        files.append(url)

Output:

'http://url.com/user/0054552/file-1.pdf'
'http://url.com/user/0054552/file-2.pdf'
'http://url.com/user/0054552/other-file-0.pdf'


问:
Need XSLT template to convert docx file table styles to html
I am using xslt1.0 to convert docx file to html..i need a xslt template to handle table styles and themes applied in docx files to reproduce it in html..please help me....</p>

答: Here is one example of Docx2HTML http://openxmlviewer.codeplex.com/Thread/View.aspx?ThreadId=54508 using XSLT (and an earlier approach).</p>


问:
How to disable Escape Key for Twitter Bootstrap Dropdowns?
I do not want  Bootstrap Dropdowns to close when the ESC-Key is being pressed.

I tried the following snippet without any success:

```<code>$(document).on('shown.bs.dropdown', function (e) {
    $(document).on("keydown", $button, function (e) {
        var code = e.keyCode || e.which;
        if (code === 27) {
            e.preventDefault();
        }
    });
});
</code>```

I found a similar Question, which is about disabling the Key for Bootstraps Modals. The solution for that seems to be data-keyboard="false". Is there a similar solution for Dropdowns?

Edit:
See JSFiddle

答:
I use following:

```<code>$('#dropdown_id').on('hide.bs.dropdown', function (e) {
  if ($(this).hasClass('keepopen')) {
      $(this).removeClass('keepopen')
      e.preventDefault();
      e.stopPropagation();
      return false;
  }
});
</code>```

Add class 'keepopen' when you expect dropdown to close and want to prevent it. In my case it is typing in the input element inside the dropdown:

```<code>$('#input_id').on('keydown', function(e){
  if (e.which == 27) {
    $('#dropdown_id').addClass('keepopen');
  }
});
</code>```

Body:
I do not want  Bootstrap Dropdowns to close when the ESC-Key is being pressed.

I tried the following snippet without any success:

$(document).on('shown.bs.dropdown', function (e) {
    $(document).on("keydown", $button, function (e) {
        var code = e.keyCode || e.which;
        if (code === 27) {
            e.preventDefault();
        }
    });
});

I found a similar Question, which is about disabling the Key for Bootstraps Modals. The solution for that seems to be data-keyboard="false". Is there a similar solution for Dropdowns?

Edit:
See JSFiddle

Body:
I use following:

$('#dropdown_id').on('hide.bs.dropdown', function (e) {
  if ($(this).hasClass('keepopen')) {
      $(this).removeClass('keepopen')
      e.preventDefault();
      e.stopPropagation();
      return false;
  }
});

Add class 'keepopen' when you expect dropdown to close and want to prevent it. In my case it is typing in the input element inside the dropdown:

$('#input_id').on('keydown', function(e){
  if (e.which == 27) {
    $('#dropdown_id').addClass('keepopen');
  }
});


问:
Identify similar entries based on two criteria
I'm trying identify different status of a product for same colour by using the below formula

=IF(B6&J6=B5&J5,IF(OR(B6&J6&L6=B5&J5&L5,B6&J6&L6=B7&J7&L7),"True","False"),"True")

Result

Expected Result

However, unable to achieve the expected result. I completely lost here kindly lend me a hand :)

答:
Here is a possible answer. Count how many times the most common status (Seasonal) occurs for the current product and colour, then count how many times the status in the current row occurs. If the counts are the same, then this is the most common status so set the result to TRUE, otherwise FALSE.

```<code>=COUNTIFS($A$2:$A$20,A2,$B$2:$B$20,B2,$C$2:$C$20,C2)=MAX(COUNTIFS($A$2:$A$20,A2,$B$2:$B$20,B2,$C$2:$C$20,$C$2:$C$20))
</code>```

Must be entered as an array formula using CtrlShiftEnter

or you can try

```<code>=COUNTIFS($A$2:$A$20,A2,$B$2:$B$20,B2,$C$2:$C$20,C2)=AGGREGATE(14,0,COUNTIFS($A$2:$A$20,A2,$B$2:$B$20,B2,$C$2:$C$20,$C$2:$C$20),1)
</code>```

entered as a normal formula.

Here is a screen shot using your specified columns

Body:
Here is a possible answer. Count how many times the most common status (Seasonal) occurs for the current product and colour, then count how many times the status in the current row occurs. If the counts are the same, then this is the most common status so set the result to TRUE, otherwise FALSE.

=COUNTIFS($A$2:$A$20,A2,$B$2:$B$20,B2,$C$2:$C$20,C2)=MAX(COUNTIFS($A$2:$A$20,A2,$B$2:$B$20,B2,$C$2:$C$20,$C$2:$C$20))

Must be entered as an array formula using CtrlShiftEnter

or you can try

=COUNTIFS($A$2:$A$20,A2,$B$2:$B$20,B2,$C$2:$C$20,C2)=AGGREGATE(14,0,COUNTIFS($A$2:$A$20,A2,$B$2:$B$20,B2,$C$2:$C$20,$C$2:$C$20),1)

entered as a normal formula.

Here is a screen shot using your specified columns


问:
How can I test raise exception in JUnit5?
I want to test whether exception works well or not using JUnit5.

For example, let say I test queue.

```<code>public class ArrayCircleQueue {
    .
    .
    .
    public void enQueue(char item) {
        if (isFull()) {
            throw new IndexOutOfBoundsException("Queue is full now!");
        } else {
            itemArray[rear++] = item;
        }
    }
}
</code>```

TestClass

```<code>class ArrayCircleQueueTest {
    .
    .
    .
    @org.junit.jupiter.api.Test
    void testEnQueueOverflow() {
        for (int i=0; i<100; i++) {
            queue.enQueue('c');  # test for 10-size queue. It should catch exception
        }
    }
}
</code>```

I search it in google, but there are only answer for JUnit4:
@Test(expected=NoPermissionException.class)

but it doesn't work on JUnit5.

How can I deal with it?

答:
```<code>@Test
void exceptionTesting() {
    Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
        arrayCircleQueue.enQueue('a') ;
    });
    assertEquals("Queue is full now!", exception.getMessage());
}
</code>```

<p>Or you can try it. </p>

Body:
I want to test whether exception works well or not using JUnit5.

For example, let say I test queue.

public class ArrayCircleQueue {
    .
    .
    .
    public void enQueue(char item) {
        if (isFull()) {
            throw new IndexOutOfBoundsException("Queue is full now!");
        } else {
            itemArray[rear++] = item;
        }
    }
}

TestClass

class ArrayCircleQueueTest {
    .
    .
    .
    @org.junit.jupiter.api.Test
    void testEnQueueOverflow() {
        for (int i=0; i<100; i++) {
            queue.enQueue('c');  # test for 10-size queue. It should catch exception
        }
    }
}

I search it in google, but there are only answer for JUnit4:
@Test(expected=NoPermissionException.class)

but it doesn't work on JUnit5.

How can I deal with it?

Body:
@Test
void exceptionTesting() {
    Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
        arrayCircleQueue.enQueue('a') ;
    });
    assertEquals("Queue is full now!", exception.getMessage());
}

Or you can try it.


问:
How to take array as an input in android?
Actually I am designing an android application in which I would be taking array as an input by using EditText.  so the thing is I am trying a lot by I am not getting how to do it so. Can anyone help me please.
I don't have a proper code so I am not attaching that but please help me with your code.

How can I take input as an array using EditText in android.
I want to insert n elements by EditText and than want to convert them in a single array.
like if I give input 1 and 2 and 3 and 4. than I can have a array like a[4] = {1,2,3,4}

答:
You can use following code to convert String to array:</p>

```<code>EditText ed = (EditText) findViewById(R.id.edittext);
String text = ed.getText().toString();
int arr[] = new int[text.length()/2];//Assuming no spaces and user is using one comma between numbers
    int i=0;
    while(text!=null && text.length()>0) {
        arr[i] = Integer.parseInt(text.substring(0,1));
        text = text.substring(text.indexOf(",")+1);
        i++;
    }
</code>```

Body:
You can use following code to convert String to array:

EditText ed = (EditText) findViewById(R.id.edittext);
String text = ed.getText().toString();
int arr[] = new int[text.length()/2];//Assuming no spaces and user is using one comma between numbers
    int i=0;
    while(text!=null && text.length()>0) {
        arr[i] = Integer.parseInt(text.substring(0,1));
        text = text.substring(text.indexOf(",")+1);
        i++;
    }


问:
How to internet explorer properties window in C#
I am working on a windows application, where i have to provide the user, a way to change the proxy settings by opening the IE settings window. Google chrome uses the same method, when you try to change the proxy settings in chrome, it will open internet explorer properties window with the connection tab selected.

I have observed that chrome is running run32dll.exe to achieve this, but it is also passing some arguments along with it

System.Diagnostics.Process.Start("rundll32.exe", "SomeArgumentsHere");

my only problem is i don't know what arguments it is passing.

To simplify my question, i want to know a way to open IE settings window with the connection tab selected, from my C#.net application

Update the following code worked for me

```<code>System.Diagnostics.Process.Start("inetcpl.cpl", ",4");
</code>```

答:
This is the complete command passed by Google chrome (obtained using Process Explorer):</p>

```<code>"C:\Windows\system32\rundll32.exe" C:\Windows\system32\shell32.dll,Control_RunDLL C:\Windows\system32\inetcpl.cpl,,4
</code>```

Body:
I am working on a windows application, where i have to provide the user, a way to change the proxy settings by opening the IE settings window. Google chrome uses the same method, when you try to change the proxy settings in chrome, it will open internet explorer properties window with the connection tab selected.

I have observed that chrome is running run32dll.exe to achieve this, but it is also passing some arguments along with it

System.Diagnostics.Process.Start("rundll32.exe", "SomeArgumentsHere");

my only problem is i don't know what arguments it is passing.

To simplify my question, i want to know a way to open IE settings window with the connection tab selected, from my C#.net application

Update the following code worked for me

System.Diagnostics.Process.Start("inetcpl.cpl", ",4");

Body:
This is the complete command passed by Google chrome (obtained using Process Explorer):

"C:\Windows\system32\rundll32.exe" C:\Windows\system32\shell32.dll,Control_RunDLL C:\Windows\system32\inetcpl.cpl,,4


问:
property list from object of type id
How to get property list from object of type id using class_copyPropertyList.

```<code>properties = class_copyPropertyList([WSAT_SignIN class], &count);
</code>```

Instead of model class name, I have an id of type WSAT_SignIN. Beside the  class_copyPropertyList method, is there a way to get property from an id?

答:
i got the answer,

```<code>   Class classname=id;

  properties = class_copyPropertyList([classname class], &count);
</code>```

without using classname i got the property list

Title: property list from object of type id

Body:
How to get property list from object of type id using class_copyPropertyList.

properties = class_copyPropertyList([WSAT_SignIN class], &count);

Instead of model class name, I have an id of type WSAT_SignIN. Beside the  class_copyPropertyList method, is there a way to get property from an id?

Body:
i got the answer,

   Class classname=id;

  properties = class_copyPropertyList([classname class], &count);

without using classname i got the property list


问:
Android - control an led with button in android
is there a way of building a simple circuit with an led bulb, and somehow control it with an android device. if so, how. is it possible to do this without Arduino, I don't know much about Arduino, but I'm looking for a pure solution.</p>

答:
Micro controller and communication medium both are important for controlling any hardware device.
You can use any micro controller or you can design your own by using 8051 IC</p>


问:
CSS Grids and Fraction Unit
I'm trying to understand the basics of CSS grids but have a problem with fraction grid-template: repeat(4, 1fr) / repeat(3, 1fr); unit.

.grid-container {
  display: grid;
  grid-template: repeat(4, 1fr) / repeat(3, 1fr);
  grid-gap: 20px;
  grid-template-areas: 'header header header' 'sidebar content content' 'sidebar content content' 'footer footer footer';
}

.item-1 {
  grid-area: content;
  background: #000;
  color: #ffffff;
  text-align: justify;
  padding: 10px;
}

.item-2 {
  grid-area: sidebar;
  background: #852021;
  color: #ffffff;
  padding: 10px;
}

.item-3 {
  grid-area: header;
  background: yellow;
  text-align: center;
  padding: 10px;
}

.item-4 {
  grid-area: footer;
  background: gray;
  color: #fff;
  text-align: center;
  padding: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid-container">
  <div class="item-1">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Non nulla sapiente cumque ratione quas consequatur, quaerat qui possimus et voluptatibus expedita tempore porro fuga aliquam, cum aut rerum perspiciatis blanditiis.
  </div>
  <div class="item-2">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Non nulla sapiente cumque ratione quas consequatur, quaerat qui possimus et voluptatibus expedita tempore porro fuga aliquam, cum aut rerum perspiciatis blanditiis.
  </div>
  <div class="item-3">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Non nulla sapiente cumque ratione quas consequatur, quaerat qui possimus et voluptatibus expedita tempore porro fuga aliquam, cum aut rerum perspiciatis blanditiis.
  </div>
  <div class="item-4">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Non nulla sapiente cumque ratione quas consequatur, quaerat qui possimus et voluptatibus expedita tempore porro fuga aliquam, cum aut rerum perspiciatis blanditiis.
  </div>

</div></code>```

答:
The first part defines 4 rows, each with 1 fr, so each row will get 25% of the total height

The second part defines 3 columns, each with 1 fr, so each column will get 33% of the total width.

THis agrees with the following definition of areas, where there are 4 strings, one for each row, with 3 names in every string, one for each column.

Title: CSS Grids and Fraction Unit

Body:
I'm trying to understand the basics of CSS grids but have a problem with fraction grid-template: repeat(4, 1fr) / repeat(3, 1fr); unit.

.grid-container {
  display: grid;
  grid-template: repeat(4, 1fr) / repeat(3, 1fr);
  grid-gap: 20px;
  grid-template-areas: 'header header header' 'sidebar content content' 'sidebar content content' 'footer footer footer';
}

.item-1 {
  grid-area: content;
  background: #000;
  color: #ffffff;
  text-align: justify;
  padding: 10px;
}

.item-2 {
  grid-area: sidebar;
  background: #852021;
  color: #ffffff;
  padding: 10px;
}

.item-3 {
  grid-area: header;
  background: yellow;
  text-align: center;
  padding: 10px;
}

.item-4 {
  grid-area: footer;
  background: gray;
  color: #fff;
  text-align: center;
  padding: 10px;
}

    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Non nulla sapiente cumque ratione quas consequatur, quaerat qui possimus et voluptatibus expedita tempore porro fuga aliquam, cum aut rerum perspiciatis blanditiis.

    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Non nulla sapiente cumque ratione quas consequatur, quaerat qui possimus et voluptatibus expedita tempore porro fuga aliquam, cum aut rerum perspiciatis blanditiis.

    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Non nulla sapiente cumque ratione quas consequatur, quaerat qui possimus et voluptatibus expedita tempore porro fuga aliquam, cum aut rerum perspiciatis blanditiis.

    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Non nulla sapiente cumque ratione quas consequatur, quaerat qui possimus et voluptatibus expedita tempore porro fuga aliquam, cum aut rerum perspiciatis blanditiis.


问:
How can a struct inherits itself?
```<code>template <bool condition>
struct when;

template <typename It, typename = void>
struct at_impl : at_impl<It, when<true>> { };

struct at_t {
    template <typename Xs, typename N>
    constexpr decltype(auto) operator()(Xs&& xs, N const& n) const;
};

constexpr at_t at{};

int main()
{
}
</code>```

How could this program compiled? How can a struct inherits itself?!
I don't know what's going on here. Is this a new feture in c++?

答:
at_impl is a struct/class template, from which a struct/class is generated.

Different template arguments to at_impl generate different structs. Inheriting from a different struct/class is allowed.

Title: How can a struct inherits itself?

Body:
template <bool condition>
struct when;

template <typename It, typename = void>
struct at_impl : at_impl<It, when<true>> { };

struct at_t {
    template <typename Xs, typename N>
    constexpr decltype(auto) operator()(Xs&& xs, N const& n) const;
};

constexpr at_t at{};

int main()
{
}

How could this program compiled? How can a struct inherits itself?!
I don't know what's going on here. Is this a new feture in c++?


问:
java adding cdata to xml string
I need to add CDATA to xml string for sign it with certificate.

String looks like:

```<code><SignedContent>someparametres</SignedContent>
</code>```

Result must be like:

```<code><![CDATA[<SignedContent>someparametres</SignedContent>]]>
</code>```

How can i do this? Pls help

P.S. Xml string has only one row (removed all tabs, all spaces, BOM)

答:
This post may be hold but i feel i should respond, this may help someone else.

```<code>        JAXBContext context = JAXBContext.newInstance(SignedContent.class);
        Marshaller marshallerObj = context.createMarshaller();
        marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        StringWriter sw = new StringWriter();
        marshallerObj.marshal(signedContentObj, sw);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(true);
        factory.setExpandEntityReferences(false);
        Document doc = factory.newDocumentBuilder().newDocument();
        doc.createCDATASection(sw.toString()).getData();
</code>```

You can play around from here...

Title: java adding cdata to xml string

Body:
I need to add CDATA to xml string for sign it with certificate.

String looks like:

<SignedContent>someparametres</SignedContent>

Result must be like:

<![CDATA[<SignedContent>someparametres</SignedContent>]]>

How can i do this? Pls help

P.S. Xml string has only one row (removed all tabs, all spaces, BOM)

Body:
This post may be hold but i feel i should respond, this may help someone else.

        JAXBContext context = JAXBContext.newInstance(SignedContent.class);
        Marshaller marshallerObj = context.createMarshaller();
        marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        StringWriter sw = new StringWriter();
        marshallerObj.marshal(signedContentObj, sw);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(true);
        factory.setExpandEntityReferences(false);
        Document doc = factory.newDocumentBuilder().newDocument();
        doc.createCDATASection(sw.toString()).getData();

You can play around from here...


问:
Usage of NSException in iPhone Apps
One of my friends asked me not to use NSException in iPhone Apps. The reason he gave was "performance bottleneck". But I am not convinced of it.

Can someone confirm me that we should restrain from using NSException in iPhone App? If you have best practices for using NSException, please provide that too.

UPDATE:

This link requests us to use Exception handling at the app level. Have someone ever done it? Please give the advantages of it and any other performance hitches it could create.

答:
In short:

Do not use exceptions to indicate anything but unrecoverable errors

It is only appropriate to use @try/@catch to deal with unrecoverable errors.  It is never appropriate to use @throw/@try/@catch to do control-flow like operations on iOS or Mac OS X.   Even then, consider carefully whether you are better off using an exception to indicate an unrecoverable error or simply crashing (call abort());  a crash often leaves behind significantly more evidence.

For example, it would not be appropriate to use for catching out-of-bounds exceptions unless your goal is to catch them and somehow report the error, then -- typically -- crash or, at the least, warn the user that your app is in an inconsistent state and may lose data.

Behavior of any exception thrown through system framework code is undefined.

Can you explain the "Behavior of any
  exception thrown through system
  framework code is undefined." in
  detail?

Sure.

The system frameworks use a design where any exception is considered to be a fatal, non-recoverable, error;  a programmer error, for all intents and purposes.   There are a very limited number of exceptions (heh) to this rule.

Thus, in their implementation, the system frameworks will not ensure that everything is necessarily properly cleaned up if an exception is tossed that passes through system framework code.  Sine the exception is, by definition, unrecoverable, why pay the cost of cleanup?

Consider this call stack:

```<code>your-code-1()
    system-code()
        your-code-2()
</code>```

I.e. code where your code calls into system code which calls into more of your code (a very common pattern, though the call stacks are obviously significantly deeper).

If your-code-2 throws an exception, that the exceptions passes over system-code means the behavior is undefined;  system-code may or may not leave your application in an undefined, potentially crashy or data-lossy, state.

Or, more strongly:   You can't throw an exception in your-code-2 with the expectation that you can catch and handle it in your-code-1.

Title: Usage of NSException in iPhone Apps

Body:
In short:

Do not use exceptions to indicate anything but unrecoverable errors

It is only appropriate to use @try/@catch to deal with unrecoverable errors.  It is never appropriate to use @throw/@try/@catch to do control-flow like operations on iOS or Mac OS X.   Even then, consider carefully whether you are better off using an exception to indicate an unrecoverable error or simply crashing (call abort());  a crash often leaves behind significantly more evidence.

For example, it would not be appropriate to use for catching out-of-bounds exceptions unless your goal is to catch them and somehow report the error, then -- typically -- crash or, at the least, warn the user that your app is in an inconsistent state and may lose data.

Behavior of any exception thrown through system framework code is undefined.

Can you explain the "Behavior of any
  exception thrown through system
  framework code is undefined." in
  detail?

Sure.

The system frameworks use a design where any exception is considered to be a fatal, non-recoverable, error;  a programmer error, for all intents and purposes.   There are a very limited number of exceptions (heh) to this rule.

Thus, in their implementation, the system frameworks will not ensure that everything is necessarily properly cleaned up if an exception is tossed that passes through system framework code.  Sine the exception is, by definition, unrecoverable, why pay the cost of cleanup?

Consider this call stack:

your-code-1()
    system-code()
        your-code-2()

I.e. code where your code calls into system code which calls into more of your code (a very common pattern, though the call stacks are obviously significantly deeper).

If your-code-2 throws an exception, that the exceptions passes over system-code means the behavior is undefined;  system-code may or may not leave your application in an undefined, potentially crashy or data-lossy, state.

Or, more strongly:   You can't throw an exception in your-code-2 with the expectation that you can catch and handle it in your-code-1.


问:
How can I make bazel use external storage when building?
When building certain code with bazel I'm running out of storage space. I'd like bazel to store its things on a USB drive instead of in my ~/.cache folder. How can I tell bazel to do this?

答:
Use the --output_user_root flag.

Example:

```<code>bazel --output_user_root=/path/to/directory build //foo:bar
</code>```

Body:
Use the --output_user_root flag.

Example:

bazel --output_user_root=/path/to/directory build //foo:bar


问:
Android facebook login with phone number returns null username
I'm using the Facebook login code, it works well when trying to login with email.
I'm now trying to login by account with phone number.

```<code>private FacebookCallback<LoginResult> mCallBack = new FacebookCallback<LoginResult>() {
    @Override
    public void onSuccess(LoginResult loginResult) {

        progressDialog.dismiss();

        // App code
        GraphRequest request = GraphRequest.newMeRequest(
                loginResult.getAccessToken(),
                new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(
                            JSONObject object,
                            GraphResponse response) {

                        Log.e("response: ", response + "");
                        Log.e("object: ", object + "");

                            try {
                                user = new User();
                                user.facebookID = object.getString("id").toString();
                                user.email = object.getString("email").toString();
                                user.name = object.getString("name").toString();
                                user.gender = object.getString("gender").toString();
                                PrefUtils.setCurrentUser(user,LoginActivity.this);

                            }catch (Exception e){
                                e.printStackTrace();
                            }
                          Toast.makeText(LoginActivity.this,"welcome "+user.name,Toast.LENGTH_LONG).show();
                           System.out.println("UserID: "+user.facebookID+" Name: "+user.name);
                            Intent intent=new Intent(LoginActivity.this,LogoutActivity.class);
                            startActivity(intent);
                            finish();

                    }

                });

        Bundle parameters = new Bundle();
        parameters.putString("fields", "id,name,email,gender, birthday");
        request.setParameters(parameters);
        request.executeAsync();
    }

    @Override
    public void onCancel() {
        progressDialog.dismiss();
    }

    @Override
    public void onError(FacebookException e) {
        progressDialog.dismiss();
    }
};
</code>```

in LogCat:

```<code>     E/response:: {Response:  responseCode: 200, graphObject: {"id":"101371863742753","name":"Hammody Elhossiny","gender":"male"}, error: null}
 E/object:: {"id":"101371863742753","name":"Hammody Elhossiny","gender":"male"}
 W/System.err: org.json.JSONException: No value for email
 W/System.err:     at org.json.JSONObject.get(JSONObject.java:389)
 W/System.err:     at org.json.JSONObject.getString(JSONObject.java:550)
 W/System.err:     at com.example.android.facebookloginsample.LoginActivity$2$1.onCompleted(LoginActivity.java:111)
 W/System.err:     at com.facebook.GraphRequest$1.onCompleted(GraphRequest.java:295)
 W/System.err:     at com.facebook.GraphRequest$5.run(GraphRequest.java:1243)
 W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
 W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
 W/System.err:     at android.os.Looper.loop(Looper.java:148)
 W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
 W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
 W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
 W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
 10710-10710/com.example.android.facebookloginsample I/System.out: UserID: 101371863742753 Name: null
 2312-2324/? I/ActivityManager: START u0 {cmp=com.example.android.facebookloginsample/.LogoutActivity} from uid 10060 on display 0
 1177-1177/? W/SurfaceFlinger: couldn't log to binary event log: overflow.
</code>```

I know that the exception is because there is no email.
But why in Toast it gives (Welcome null)
and the Name in output returns Null ??

Hint: When login by other account with email, it gives me the Name normally.

答:
It is because of the code execution style: Java execute code line by line:

so in your code:

```<code> try {
            user = new User();
            user.facebookID = object.getString("id").toString();
            user.email = object.getString("email").toString();
            user.name = object.getString("name").toString();
            user.gender = object.getString("gender").toString();
            PrefUtils.setCurrentUser(user,LoginActivity.this);

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

it stops excecution in this line: user.email = object.getString("email").toString();  because of JsonException. so the below code is not executed.

to resolve null error for name pull the code of your name, others ahead. use:

```<code> try {
            user = new User();
            user.facebookID = object.getString("id").toString();
            user.name = object.getString("name").toString();
            user.gender = object.getString("gender").toString();
            user.email = object.getString("email").toString();
            PrefUtils.setCurrentUser(user,LoginActivity.this);

        }catch (Exception e){
            e.printStackTrace();
            PrefUtils.setCurrentUser(user,LoginActivity.this);
        }
</code>```

Second Option

Even better to use has() method of your JSonObject like object.has("email"); so that you can parse the data more accurately according to your need.

Body:
I'm using the Facebook login code, it works well when trying to login with email.
I'm now trying to login by account with phone number.

private FacebookCallback<LoginResult> mCallBack = new FacebookCallback<LoginResult>() {
    @Override
    public void onSuccess(LoginResult loginResult) {

        progressDialog.dismiss();

        // App code
        GraphRequest request = GraphRequest.newMeRequest(
                loginResult.getAccessToken(),
                new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(
                            JSONObject object,
                            GraphResponse response) {

                        Log.e("response: ", response + "");
                        Log.e("object: ", object + "");

                            try {
                                user = new User();
                                user.facebookID = object.getString("id").toString();
                                user.email = object.getString("email").toString();
                                user.name = object.getString("name").toString();
                                user.gender = object.getString("gender").toString();
                                PrefUtils.setCurrentUser(user,LoginActivity.this);

                            }catch (Exception e){
                                e.printStackTrace();
                            }
                          Toast.makeText(LoginActivity.this,"welcome "+user.name,Toast.LENGTH_LONG).show();
                           System.out.println("UserID: "+user.facebookID+" Name: "+user.name);
                            Intent intent=new Intent(LoginActivity.this,LogoutActivity.class);
                            startActivity(intent);
                            finish();

                    }

                });

        Bundle parameters = new Bundle();
        parameters.putString("fields", "id,name,email,gender, birthday");
        request.setParameters(parameters);
        request.executeAsync();
    }

    @Override
    public void onCancel() {
        progressDialog.dismiss();
    }

    @Override
    public void onError(FacebookException e) {
        progressDialog.dismiss();
    }
};

in LogCat:

     E/response:: {Response:  responseCode: 200, graphObject: {"id":"101371863742753","name":"Hammody Elhossiny","gender":"male"}, error: null}
 E/object:: {"id":"101371863742753","name":"Hammody Elhossiny","gender":"male"}
 W/System.err: org.json.JSONException: No value for email
 W/System.err:     at org.json.JSONObject.get(JSONObject.java:389)
 W/System.err:     at org.json.JSONObject.getString(JSONObject.java:550)
 W/System.err:     at com.example.android.facebookloginsample.LoginActivity$2$1.onCompleted(LoginActivity.java:111)
 W/System.err:     at com.facebook.GraphRequest$1.onCompleted(GraphRequest.java:295)
 W/System.err:     at com.facebook.GraphRequest$5.run(GraphRequest.java:1243)
 W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
 W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
 W/System.err:     at android.os.Looper.loop(Looper.java:148)
 W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
 W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
 W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
 W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
 10710-10710/com.example.android.facebookloginsample I/System.out: UserID: 101371863742753 Name: null
 2312-2324/? I/ActivityManager: START u0 {cmp=com.example.android.facebookloginsample/.LogoutActivity} from uid 10060 on display 0
 1177-1177/? W/SurfaceFlinger: couldn't log to binary event log: overflow.

I know that the exception is because there is no email.
But why in Toast it gives (Welcome null)
and the Name in output returns Null ??

Hint: When login by other account with email, it gives me the Name normally.

Body:
It is because of the code execution style: Java execute code line by line:

so in your code:

 try {
            user = new User();
            user.facebookID = object.getString("id").toString();
            user.email = object.getString("email").toString();
            user.name = object.getString("name").toString();
            user.gender = object.getString("gender").toString();
            PrefUtils.setCurrentUser(user,LoginActivity.this);

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

it stops excecution in this line: user.email = object.getString("email").toString();  because of JsonException. so the below code is not executed.

to resolve null error for name pull the code of your name, others ahead. use:

 try {
            user = new User();
            user.facebookID = object.getString("id").toString();
            user.name = object.getString("name").toString();
            user.gender = object.getString("gender").toString();
            user.email = object.getString("email").toString();
            PrefUtils.setCurrentUser(user,LoginActivity.this);

        }catch (Exception e){
            e.printStackTrace();
            PrefUtils.setCurrentUser(user,LoginActivity.this);
        }

Second Option

Even better to use has() method of your JSonObject like object.has("email"); so that you can parse the data more accurately according to your need.


问:
Centering div vertically and horizontally
Is there any way to center .polygon_container and .polygon vertically and horizontally? Also is there a possibility to make the size of it responsive like the  tag below?

http://cichyone.linuxpl.eu/ranestwen/ex/

I've tried text-align, margin auto etc and nothing works.

When I set it in the middle using margin-left and margin-top it is working only for one resolution.

答:
You can easily use flexbox.</p>

```<code>.owl-item > div {
    display: flex;
    justify-content: center;
    align-items: center;
}
</code>```

Body:
You can easily use flexbox.

.owl-item > div {
    display: flex;
    justify-content: center;
    align-items: center;
}


问:
Decting the End of User input in console application in c#
what i am Expecting from program is that after user press the Enter key , program detects as End of input and breaks the loop but in the list first item it receives is correct but the later items that we input , the first letter of every input was cropped from the word , for example :-

1st input => India
2nd input => China but following program takes hina
later all inputs are in the above way . guys i am stuck here in this point of my program .

```<code>       List<String> keyss = new List<string>();
        do
        {
            item = Console.ReadLine();
            keyss.Add(item);
        } while (Console.ReadKey().Key != ConsoleKey.Enter);

        foreach (var item in keyss)
        {
            Console.WriteLine(item);
        }
</code>```

答:
Try this:</p>

```<code>string item = string.Empty;
List<string> keyss = new List<string>();

while (!string.IsNullOrWhiteSpace(item = Console.ReadLine()))
{
    keyss.Add(item);
}

foreach (var itm in keyss)
{
    Console.WriteLine(itm);
}
</code>```

Body:
what i am Expecting from program is that after user press the Enter key , program detects as End of input and breaks the loop but in the list first item it receives is correct but the later items that we input , the first letter of every input was cropped from the word , for example :-

1st input => India
2nd input => China but following program takes hina
later all inputs are in the above way . guys i am stuck here in this point of my program .

       List<String> keyss = new List<string>();
        do
        {
            item = Console.ReadLine();
            keyss.Add(item);
        } while (Console.ReadKey().Key != ConsoleKey.Enter);

        foreach (var item in keyss)
        {
            Console.WriteLine(item);
        }

Body:
Try this:

string item = string.Empty;
List<string> keyss = new List<string>();

while (!string.IsNullOrWhiteSpace(item = Console.ReadLine()))
{
    keyss.Add(item);
}

foreach (var itm in keyss)
{
    Console.WriteLine(itm);
}


问:
Dropzone - Server responded with 0 code
Ubuntuu - ssh - Symfony3 - Angular-seed - Dropzone

I'm working on a task which upload a excel file from dropzone to a web service realized with symfony3.
When the uploading is finished, the web-service start to parsing file in order to return a success for the dorpzone's success event, which is waiting for a signal from the php-part of the result of parsing.

I'm in the deployment phase, and working with the ssh-server of my client.
Everythings work fine (upload , parsing , return success message) when i run my web-service with

php bin/console server:start myserverurl:port

but when i use a virtual-host created by the client, there's the issue now :

after uploding file, immediately i got the dropzone's error "Server responded with 0 code." but the file has been got by the web-service and the process is successfully completed, of course it tried to return the successful end-message to dropzone, but it's already down.
I have been tested files with those sizes (2.4M / 8.9M / 14.5M).

In contrary, everything work well with some file (207K / 50K).

I can't conclude if this problem due to a extern parameter (apache-limit, ...), i'm not sure if the server block the waiting event of dropzone because of time-limit or something else.

This is my dropzone configuration :

```<code>$scope.dropzoneConfig = {
            'options': { // passed into the Dropzone constructor
                'url': $rootScope.baseUrl + 'admin/surveys/updates?access_token=' + $auth.getToken(),
                'maxFiles': 1,
                'uploadMultiple': false,
                'autoProcessQueue': false,
                'maxFileSize': 30
            },
            'eventHandlers': {
                'addedfile': function (file) {
                    if (!$scope.dropzone) {
                        $scope.dropzone = this;
                    }

                    if (!(vm.allowedExt.indexOf(vm.getFileExt(file.name)) > -1 )) {
                        $scope.resetForm();
                        vm.showErrorAlert('L\'extension de votre fichier est invalide , SVP veuilez choisir une extension .xlsx ou .xls');
                        return;
                    }

                    if ($scope.surveyCreate) {
                        if ($scope.surveyCreate.$valid) {
                            vm.enableBtn();
                        } else {
                            vm.disableBtn();
                        }
                    }

                    // survey edit
                    if ($scope.surveyEdit && $scope.selectedSurvey != undefined) {
                        vm.enableBtn();
                    }

                },
                'maxfilesexceeded': function (file) {
                    this.removeAllFiles();
                    this.addFile(file);
                },
                'sending': function (file, xhr, formData) {
                    if ($scope.survey != undefined && $scope.survey.name) {
                        formData.append('name', $scope.survey.name);
                    }

                    if ($scope.selectedSurvey != undefined) {
                        formData.append('survey_id', $scope.selectedSurvey.id);
                    }
                },
                'success': function (file, response) {
                    vm.hideSpinner();
                    $scope.resetForm();
                    if (response.success) {
                        vm.showSuccessAlert();
                        $scope.updateSurveysArray(response.data);
                    } else {
                        vm.showErrorAlert(response.errorMsg);
                    }
                },
                "error": function (file, error, xhr) {
                    vm.hideSpinner();
                    $scope.resetForm();
                    if (error.hasOwnProperty('message'))
                        vm.showErrorAlert(error.message);
                    else
                        vm.showErrorAlert('file transfer error');
                }
            }
        };
</code>```

Any ideas ?

答:
first check php.ini and check is upload_max_filesize if it small than make it 1000M

add event listener on submit button :

submitButton.addEventListener("click", function (file) {

```<code>    if (myDropzone.getAcceptedFiles().length > 0) {
        if (submitfiles === true) {
            submitfiles = false;
            return;
        }

        file.preventDefault();
        myDropzone.processQueue();

        myDropzone.on("complete", function () {
            submitfiles = true;
            $('#submit_button').trigger('click');
        });
    }
});
</code>```

Title: Dropzone - Server responded with 0 code

Body:
Ubuntuu - ssh - Symfony3 - Angular-seed - Dropzone

I'm working on a task which upload a excel file from dropzone to a web service realized with symfony3.
When the uploading is finished, the web-service start to parsing file in order to return a success for the dorpzone's success event, which is waiting for a signal from the php-part of the result of parsing.

I'm in the deployment phase, and working with the ssh-server of my client.
Everythings work fine (upload , parsing , return success message) when i run my web-service with

php bin/console server:start myserverurl:port

but when i use a virtual-host created by the client, there's the issue now :

after uploding file, immediately i got the dropzone's error "Server responded with 0 code." but the file has been got by the web-service and the process is successfully completed, of course it tried to return the successful end-message to dropzone, but it's already down.
I have been tested files with those sizes (2.4M / 8.9M / 14.5M).

In contrary, everything work well with some file (207K / 50K).

I can't conclude if this problem due to a extern parameter (apache-limit, ...), i'm not sure if the server block the waiting event of dropzone because of time-limit or something else.

This is my dropzone configuration :

$scope.dropzoneConfig = {
            'options': { // passed into the Dropzone constructor
                'url': $rootScope.baseUrl + 'admin/surveys/updates?access_token=' + $auth.getToken(),
                'maxFiles': 1,
                'uploadMultiple': false,
                'autoProcessQueue': false,
                'maxFileSize': 30
            },
            'eventHandlers': {
                'addedfile': function (file) {
                    if (!$scope.dropzone) {
                        $scope.dropzone = this;
                    }

                    if (!(vm.allowedExt.indexOf(vm.getFileExt(file.name)) > -1 )) {
                        $scope.resetForm();
                        vm.showErrorAlert('L\'extension de votre fichier est invalide , SVP veuilez choisir une extension .xlsx ou .xls');
                        return;
                    }

                    if ($scope.surveyCreate) {
                        if ($scope.surveyCreate.$valid) {
                            vm.enableBtn();
                        } else {
                            vm.disableBtn();
                        }
                    }

                    // survey edit
                    if ($scope.surveyEdit && $scope.selectedSurvey != undefined) {
                        vm.enableBtn();
                    }

                },
                'maxfilesexceeded': function (file) {
                    this.removeAllFiles();
                    this.addFile(file);
                },
                'sending': function (file, xhr, formData) {
                    if ($scope.survey != undefined && $scope.survey.name) {
                        formData.append('name', $scope.survey.name);
                    }

                    if ($scope.selectedSurvey != undefined) {
                        formData.append('survey_id', $scope.selectedSurvey.id);
                    }
                },
                'success': function (file, response) {
                    vm.hideSpinner();
                    $scope.resetForm();
                    if (response.success) {
                        vm.showSuccessAlert();
                        $scope.updateSurveysArray(response.data);
                    } else {
                        vm.showErrorAlert(response.errorMsg);
                    }
                },
                "error": function (file, error, xhr) {
                    vm.hideSpinner();
                    $scope.resetForm();
                    if (error.hasOwnProperty('message'))
                        vm.showErrorAlert(error.message);
                    else
                        vm.showErrorAlert('file transfer error');
                }
            }
        };

Any ideas ?

Body:
first check php.ini and check is upload_max_filesize if it small than make it 1000M

add event listener on submit button :

submitButton.addEventListener("click", function (file) {

    if (myDropzone.getAcceptedFiles().length > 0) {
        if (submitfiles === true) {
            submitfiles = false;
            return;
        }

        file.preventDefault();
        myDropzone.processQueue();

        myDropzone.on("complete", function () {
            submitfiles = true;
            $('#submit_button').trigger('click');
        });
    }
});