问:
Typesafety with Function varargs as parametrs
I need to write a class with function like this

```<code>class Converter <T>{

    public <R> R convertBy(Function<T,?>... args){
        Function<T,?> function = args[0];
        // doing something
        return function.apply(t);
    }
}
</code>```

I need this method to be type safe i.e first Function need from args needs to have the same argument type as this class type. For example, if my Converter would be Converter<String> I need to check (at the compile time) if the first function has String parameter.

Also, when I wrote method like that is saying that it returns object, and I cannot do

```<code>int a = converter.convertBy(func1,func2);
</code>```

because is saying that Object is not convertible to int.

-- Edit

Maybe with bigger picture will be easier to get what is it about. So the meaning of convertBy function is that it can with easy combine diffrent operation on different types.

This is working, when I define function like

```<code>public <R> R convertBy(Function... args)
</code>```

but then It is not type safe. What I need, is to make sure If my Converter is 'Converter ' user cannot pass as first parametr function like
    Function func = (string)->{ return (String)string.length();}

Also I cannot change paramters from

```<code>convertBy(Function... args)
</code>```

to
    convertBy(Function first, Function... rest)

edit.
Well I what appeared later is that I can do that. But it still doesn't check.

Thank You.

答:
You could make it without varargs quite easily actually, all you need to do is to make several methods with different amount of functions in those. This approach is often used for optimization anyway, as varargs aren't nearly as optimized as normal methods.

```<code><R> R convertBy(Function<T, R> fnc);
<R,U> R convertBy(Function<T, U> fnc1, Function<U, R> fnc2);
// etc.
</code>```

You can't ensure type safety in an array of Function, that is just impossible task. You lose type information there, and the best you could do would be checking the type using reflections, which happens at runtime, thus type safety is not checked compile time.

So I advise just sticking to the andThen or compose methods unless you have plenty functions and the utility brings you enough syntax sugar to be worth doing it that way.

Body:
I need to write a class with function like this

class Converter <T>{

    public <R> R convertBy(Function<T,?>... args){
        Function<T,?> function = args[0];
        // doing something
        return function.apply(t);
    }
}

I need this method to be type safe i.e first Function need from args needs to have the same argument type as this class type. For example, if my Converter would be Converter<String> I need to check (at the compile time) if the first function has String parameter.

Also, when I wrote method like that is saying that it returns object, and I cannot do

int a = converter.convertBy(func1,func2);

because is saying that Object is not convertible to int.

-- Edit

Maybe with bigger picture will be easier to get what is it about. So the meaning of convertBy function is that it can with easy combine diffrent operation on different types.

This is working, when I define function like

public <R> R convertBy(Function... args)

but then It is not type safe. What I need, is to make sure If my Converter is 'Converter ' user cannot pass as first parametr function like
    Function func = (string)->{ return (String)string.length();}

Also I cannot change paramters from

convertBy(Function... args)

to
    convertBy(Function first, Function... rest)

edit.
Well I what appeared later is that I can do that. But it still doesn't check.

Thank You.

Body:
You could make it without varargs quite easily actually, all you need to do is to make several methods with different amount of functions in those. This approach is often used for optimization anyway, as varargs aren't nearly as optimized as normal methods.

<R> R convertBy(Function<T, R> fnc);
<R,U> R convertBy(Function<T, U> fnc1, Function<U, R> fnc2);
// etc.

You can't ensure type safety in an array of Function, that is just impossible task. You lose type information there, and the best you could do would be checking the type using reflections, which happens at runtime, thus type safety is not checked compile time.

So I advise just sticking to the andThen or compose methods unless you have plenty functions and the utility brings you enough syntax sugar to be worth doing it that way.


来源: stackexchange

问:
adding keys in nested dictionary in python
```<code>elements = {'hydrogen': {'number': 1, 'weight': 1.00794, 'symbol': 'H'},
            'helium': {'number': 2, 'weight': 4.002602, 'symbol': 'He'}}
</code>```

Add an is_noble_gas boolean entry to the hydrogen and helium dictionaries.

答:
```<code>elements = {'hydrogen': {'number': 1, 'weight': 1.00794, 'symbol': 'H'}, 'helium': {'number': 2, 'weight': 4.002602, 'symbol': 'He'}}
noble_dict = { "hydrogen": False, "helium": True }
for noble in noble_dict:
    elements[ noble ][ "is_noble_gas" ] = noble_dict[ noble ]
</code>```

{'helium': {'symbol': 'He', 'number': 2, 'weight': 4.002602, 'is_noble_gas': True}, 'hydrogen': {'symbol': 'H', 'number': 1, 'weight': 1.00794, 'is_noble_gas': False}}

ContentLicense: CC BY-SA 3.0

Body:
elements = {'hydrogen': {'number': 1, 'weight': 1.00794, 'symbol': 'H'},
            'helium': {'number': 2, 'weight': 4.002602, 'symbol': 'He'}}

Add an is_noble_gas boolean entry to the hydrogen and helium dictionaries.

Body:
elements = {'hydrogen': {'number': 1, 'weight': 1.00794, 'symbol': 'H'}, 'helium': {'number': 2, 'weight': 4.002602, 'symbol': 'He'}}
noble_dict = { "hydrogen": False, "helium": True }
for noble in noble_dict:
    elements[ noble ][ "is_noble_gas" ] = noble_dict[ noble ]

{'helium': {'symbol': 'He', 'number': 2, 'weight': 4.002602, 'is_noble_gas': True}, 'hydrogen': {'symbol': 'H', 'number': 1, 'weight': 1.00794, 'is_noble_gas': False}}


问:
Async communication between ViewModel and Model using MVVM-Light messaging?
I am starting off writing an app for WP7 that involves retrieving data via an HTTPWebRequest, I am trying to find the best way to get the data back to the ViewModel once the async request has returned with the data.

The Model and ViewModel are split into seperate projects in their own namespaces, so am not sure if the MVVM-Light can work in this way.  Or should I just use a lightweight IoC implementation and delegates/events to call back to the ViewModel once the call in the Model has returned?

答:
Are you sure you're making the request in the right place? Typically the Model contains simply the data that you want to store/transfer and the View Model would handle transforming that Model's properties so that a View can display (or edit) that Model. I would imagine that Model objects are what you're going to get back from the HttpWebRequest, and so you may want to consider using a Service class to handle retrieving the data, though that may be overkill for your application.

Either way, I'd highly reccomend that you handle the request and the parsing of the response in the same place; otherwise you are spreading the logic across multiple places, which is just going to get confusing and hard to maintain.

If you need some help understanding MVVM, here are a number of resources that you may find helpf

Laurent Bugnions MIX10 presentation: Understanding the MVVM Pattern

Josh Smith's MSDN Magazine article: WPF Apps With The Model-View-ViewModel Design Pattern

Shawn Wildermuth's MSDN Magazine article: Model-View-ViewModel In Silverlight 2 Apps

Dan Wahlin's blog post: Getting Started with the MVVM Pattern in Silverlight Applications

ContentLicense: CC BY-SA 2.5


问:
preg_replace add space before and after of punctuation characters
I have a word filled with some punctuations.

```<code>$word = "'Ankara'da!?'";
</code>```

I want to put spaces before or after punctuation characters.
Except apostrophe character which is in the middle of word.
At the result there must be only one space between letters or punctuations.

Required result: ' Ankara'da ! ? '

I tried below and Added accent Turkish chars. ( because \w didnt work)

```<code>preg_replace('/(?![a-zA-Z0-9ğüışöçİĞÜŞÖÇ])/ig', " ", $word);
</code>```

Result: 'Ankara 'da ! ? '

答:
If you need to only add single spaces between punctuation symbols and avoid adding them at the start/end of the string, you may use the following solution:

```<code>$word = "'Ankara'da!?'";
echo trim(preg_replace_callback('~\b\'\b(*SKIP)(*F)|\s*(\p{P}+)\s*~u', function($m) {
    return ' ' . preg_replace('~\X(?=\X)~u', '$0 ', $m[1]) . ' ';
}, $word)); // => ' Ankara'da ! ? '
</code>```

See the PHP demo.

The \b\'\b(*SKIP)(*F) part matches and skips all ' that are enclosed with word chars (letters, digits, underscores, and some more rarely used word chars). The \s*(\p{P}+)\s* part matches 0+ whitespaces, then captures 1+ punctuation symbols (including _!) into Group 1 and then any 0+ whitespaces are  matched. Then, single spaces are added after each Unicode character (\X) that is followed with another Unicode character ((?=\X)). The outer leading/trailing spaces are later removed with trim()).

There is a way to do that with

```<code>$word = "'Ankara'da!?'";
echo preg_replace('~^\s+|\s+$|(\s){2,}~u', '$1',
    preg_replace('~(?!\b\'\b)\p{P}~u', ' $0 ', $word)
);
</code>```

See another PHP demo

The '~(?!\b\'\b)\p{P}~u' pattern matches any punctuation that is not ' enclosed with word chars, and this symbol is enclosed with spaces, and then '~^\s+|\s+$|(\s){2,}~u' pattern is used to remove all whitespaces at the start/end of the string and shrinks all whitespaces into 1 in all other locations.

Body:
I have a word filled with some punctuations.

$word = "'Ankara'da!?'";

I want to put spaces before or after punctuation characters.
Except apostrophe character which is in the middle of word.
At the result there must be only one space between letters or punctuations.

Required result: ' Ankara'da ! ? '

I tried below and Added accent Turkish chars. ( because \w didnt work)

preg_replace('/(?![a-zA-Z0-9ğüışöçİĞÜŞÖÇ])/ig', " ", $word);

Result: 'Ankara 'da ! ? '

Body:
If you need to only add single spaces between punctuation symbols and avoid adding them at the start/end of the string, you may use the following solution:

$word = "'Ankara'da!?'";
echo trim(preg_replace_callback('~\b\'\b(*SKIP)(*F)|\s*(\p{P}+)\s*~u', function($m) {
    return ' ' . preg_replace('~\X(?=\X)~u', '$0 ', $m[1]) . ' ';
}, $word)); // => ' Ankara'da ! ? '

See the PHP demo.

The \b\'\b(*SKIP)(*F) part matches and skips all ' that are enclosed with word chars (letters, digits, underscores, and some more rarely used word chars). The \s*(\p{P}+)\s* part matches 0+ whitespaces, then captures 1+ punctuation symbols (including _!) into Group 1 and then any 0+ whitespaces are  matched. Then, single spaces are added after each Unicode character (\X) that is followed with another Unicode character ((?=\X)). The outer leading/trailing spaces are later removed with trim()).

There is a way to do that with

$word = "'Ankara'da!?'";
echo preg_replace('~^\s+|\s+$|(\s){2,}~u', '$1',
    preg_replace('~(?!\b\'\b)\p{P}~u', ' $0 ', $word)
);

See another PHP demo

The '~(?!\b\'\b)\p{P}~u' pattern matches any punctuation that is not ' enclosed with word chars, and this symbol is enclosed with spaces, and then '~^\s+|\s+$|(\s){2,}~u' pattern is used to remove all whitespaces at the start/end of the string and shrinks all whitespaces into 1 in all other locations.


问:
Auto select when there is only one option in dropdown using ajax and liferay
I've created one drop down box in that I have some options. If I have only one option it should select automatically.

Below is the dropdown box:

```<code><select id="pubType" name="pubType" onchange="setUsageVars('_searchtabs_WAR_searchportlet_INSTANCE_1soVeAY6cpIy_', this)">
</code>```

答:
Go through following example,

 how to auto select & disable a dropdownlist item if only one option is in dropdownlist, using Ajax Call.

I'm sure it 'll help you.

```<code>   success: function (response) {
       var $select = $('#ddlSchoolList');
       $select.empty();

      for (var i = 0; i < response.length; i++) {
          if (response.length == 1) {

               $('#ddlSchoolList').append($("<option>", {
                   value:response[i].InstanceId,
                   text: response[i].InstanceName,
                   selected: "selected",
                   disabled: "disabled",
               }));

           }
       else {
           $select.empty();
           $('<option>', {
               value: 0
           }).html("------Select------").appendTo($select);
           $.each(response, function (i, state) {
               $('<option>', {
                   value: state.InstanceId

               }).html(state.InstanceName).appendTo($select);
           });
        }
    }
</code>```

Body:
I've created one drop down box in that I have some options. If I have only one option it should select automatically.

Below is the dropdown box:

<select id="pubType" name="pubType" onchange="setUsageVars('_searchtabs_WAR_searchportlet_INSTANCE_1soVeAY6cpIy_', this)">

Body:
Go through following example,

 how to auto select & disable a dropdownlist item if only one option is in dropdownlist, using Ajax Call.

I'm sure it 'll help you.

   success: function (response) {
       var $select = $('#ddlSchoolList');
       $select.empty();

      for (var i = 0; i < response.length; i++) {
          if (response.length == 1) {

               $('#ddlSchoolList').append($("<option>", {
                   value:response[i].InstanceId,
                   text: response[i].InstanceName,
                   selected: "selected",
                   disabled: "disabled",
               }));

           }
       else {
           $select.empty();
           $('<option>', {
               value: 0
           }).html("------Select------").appendTo($select);
           $.each(response, function (i, state) {
               $('<option>', {
                   value: state.InstanceId

               }).html(state.InstanceName).appendTo($select);
           });
        }
    }


问:
how to get Information of camera android
how i can get information of Camera android like list of parameters:
enter image description here

please help.

答:
You first need to have the camera instance. This can be done by opening the camera:

```<code>Camera camera = Camera.open();
</code>```

From there you can get the parameters by calling the getParameters() method on the camera instance.

Body:
You first need to have the camera instance. This can be done by opening the camera:

Camera camera = Camera.open();

From there you can get the parameters by calling the getParameters() method on the camera instance.


答:
You should access the dictionary and add is_noble_gas as a new key to the dictionary as follows.

```<code>>>> elements['hydrogen']['is_noble_gas'] = False
>>> elements['helium']['is_noble_gas'] = True
</code>```

Title: adding keys in nested dictionary in python

Body:
You should access the dictionary and add is_noble_gas as a new key to the dictionary as follows.

>>> elements['hydrogen']['is_noble_gas'] = False
>>> elements['helium']['is_noble_gas'] = True


问:
Image to the left, text centered (in page)
I am trying to align an about me page, where i would like an image to the left of the container and the text to the right aligned centered to the page.
this is what i've got

```<code><img link img>
<h2>
jack
</h2>
<p>
dummy text
</p>
</code>```

https://jsfiddle.net/a0sozwjk/1/

article#main-col {
  float: left;
  width: 65%;
}

.dark {
  padding: 15px;
  background: #35424a;
  color: #fff;
  margin-top: 10px;
  margin-bottom: 10px;
}

.container {
  width: 80%;
  margin: auto;
  overflow: hidden;
}

article#main-col {
  float: left;
  width: 65%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><center>
  <Section id="main">
    <div class="container">
      <article id="main-About-Col">
        <h1 class="PTitle">About us</h1>
        <div class="dark">
          <img style="float:left; vertical-align:center;" alt="Jack Picture" width="125px" src="https://thumb1.shutterstock.com/display_pic_with_logo/1000172/291874463/stock-vector-notebook-template-vector-example-of-using-hand-drawn-food-pattern-for-cover-of-cooking-book-291874463.jpg">
          <h2>
            Jack
          </h2>
          <p>
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis,
            sem.
          </p>
        </div>
      </article>
    </div>
  </Section>
</center></code>```

答:
Use display flex to make image as vertical center

https://jsfiddle.net/a0sozwjk/4/

article#main-col {
  float: left;
  width: 65%;
}

.dark {
  padding: 15px;
  background: #35424a;
  color: #fff;
  margin-top: 10px;
  margin-bottom: 10px;
  height: 250px;
}

.dark .imagediv{
    height: 100%;
    float: left;
    display: flex;
    align-items: center;
}

.container {
  width: 80%;
  margin: auto;
  overflow: hidden;
}

article#main-col {
  float: left;
  width: 65%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><center>
  <Section id="main">
    <div class="container">
      <article id="main-About-Col">
        <h1 class="PTitle">About us</h1>
        <div class="dark">
          <div class="imagediv">
          <img style="float:left; vertical-align:center;" alt="Jack Picture" width="125px" src="https://thumb1.shutterstock.com/display_pic_with_logo/1000172/291874463/stock-vector-notebook-template-vector-example-of-using-hand-drawn-food-pattern-for-cover-of-cooking-book-291874463.jpg">
          </div>
          <h2>
          Jack
         </h2>
          <p>
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis,
            sem.
          </p>
        </div>
      </article>
    </div>
  </Section>
</center></code>```

Body:
I am trying to align an about me page, where i would like an image to the left of the container and the text to the right aligned centered to the page.
this is what i've got

jack

dummy text

https://jsfiddle.net/a0sozwjk/1/

article#main-col {
  float: left;
  width: 65%;
}

.dark {
  padding: 15px;
  background: #35424a;
  color: #fff;
  margin-top: 10px;
  margin-bottom: 10px;
}

.container {
  width: 80%;
  margin: auto;
  overflow: hidden;
}

article#main-col {
  float: left;
  width: 65%;
}

About us

            Jack

            Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis,
            sem.

Body:
Use display flex to make image as vertical center

https://jsfiddle.net/a0sozwjk/4/

article#main-col {
  float: left;
  width: 65%;
}

.dark {
  padding: 15px;
  background: #35424a;
  color: #fff;
  margin-top: 10px;
  margin-bottom: 10px;
  height: 250px;
}

.dark .imagediv{
    height: 100%;
    float: left;
    display: flex;
    align-items: center;
}

.container {
  width: 80%;
  margin: auto;
  overflow: hidden;
}

article#main-col {
  float: left;
  width: 65%;
}

<center>
  <Section id="main">
    <div class="container">
      <article id="main-About-Col">
        <h1 class="PTitle">About us</h1>
        <div class="dark">
          <div class="imagediv">
          <img style="float:left; vertical-align:center;" alt="Jack Picture" width="125px" src="https://thumb1.shutterstock.com/display_pic_with_logo/1000172/291874463/stock-vector-notebook-template-vector-example-of-using-hand-drawn-food-pattern-for-cover-of-cooking-book-291874463.jpg">
          </div>
          <h2>
          Jack
         </h2>
          <p>
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis,
            sem.
          </p>
        </div>
      </article>
    </div>
  </Section>
</center>


问:
Reducing spaces between the character python
I am trying to print the staircase pattern. I have written the code as follows:

```<code>def StairCase(n):
    for i in range(1, n + 1):
        stair_array = []
        j = 1
        while (j <= n):
            if (j <= i):
                stair_array.append('#')
            else:
                stair_array.append(' ')
            j = j + 1

        reversed_array = list(reversed(stair_array))
        for element in reversed_array:
            print "{}".format(element),
        print

_n = int(raw_input().strip("\n"))
StairCase(_n)
</code>```

I got the output as:

```<code>6
          #
        # #
      # # #
    # # # #
  # # # # #
# # # # # #
</code>```

The expected output is:

```<code>6
     #
    ##
   ###
  ####
 #####
######
</code>```

As one can see my output is with spaces and is not acceptable as per original pattern. Kindly help.

答: You have the answer, but in the original code you use the terminal ',' to suppress newlines.  That adds a space after the thing you print.  In python 2, of course.</p>

Body:
I am trying to print the staircase pattern. I have written the code as follows:

def StairCase(n):
    for i in range(1, n + 1):
        stair_array = []
        j = 1
        while (j <= n):
            if (j <= i):
                stair_array.append('#')
            else:
                stair_array.append(' ')
            j = j + 1

        reversed_array = list(reversed(stair_array))
        for element in reversed_array:
            print "{}".format(element),
        print

_n = int(raw_input().strip("\n"))
StairCase(_n)

I got the output as:

6
          #
        # #
      # # #
    # # # #
  # # # # #
# # # # # #

The expected output is:

6
     #
    ##
   ###
  ####
 #####
######

As one can see my output is with spaces and is not acceptable as per original pattern. Kindly help.


问:
Take action when an image on a webpage is loaded and seen by the user
I need to take an action (Call a WEB URL) when an image on a webpage is loaded and is seen by the user (image is not hidden in a scrollable area). If the user scrolls down, and the image gets displayed, then we take the same action.

Is this possible? Using AJAX and Javascript focus? Does focus differentiate between (a) images that are loaded and displayed on screen and (b) images that are loaded but not displayed (because they are still down the scrollable page).

Would really appreciate your help.

Thanks

答:
Maybe this answer could help you:

Get image size when it loads from an extern URL in Javascript


问:
Properly use Scrollify on my Wordpress Template
I'm not good with programming PHP and JS. But I'm trying to install and use Scrollify on my own theme for Wordpress. jQuery should also be loaded properly.
Unfortunately I cannot figure out how to make scrollify work, mostly out of lack of understanding how things react to each other or are properly loaded.

As it seems, I can load scrollify with this code in my functions.php:

```<code>function scrollify() {
    wp_register_script( 'jquery-scrollify', get_template_directory_uri() . '/js/scrollify/jquery.scrollify.js', array('jquery'));
    wp_enqueue_script( 'jquery-scrollify' );

    wp_register_script( 'jquery-scrollifymin', get_template_directory_uri() . '/js/scrollify/jquery.scrollify.min.js', array('jquery'));
    wp_enqueue_script( 'jquery-scrollifymin' );

    wp_register_script( 'Gruntfile', get_template_directory_uri() . '/js/scrollify/Gruntfile.js', array('jquery'));
    wp_enqueue_script( 'Grundtfile' ); }

add_action( 'wp_enqueue_scripts', 'scrollify' );
</code>```

My HTML structure is like this:

```<code><section id="portfolio" class="fullscreen" data-section-name="portfolio"></section>
<section id="about" class="fullscreen" data-section-name="about"></section>
</code>```

Configuration in jquery.scrollify.js:

```<code>    //section should be an identifier that is the same for each section
    section: "fullscreen",
    sectionName: "section-name",
    interstitialSection: "",
    easing: "easeOutExpo",
    scrollSpeed: 1100,
    offset: 0,
    scrollbars: true,
    target:"html,body",
    standardScrollElements: false,
    setHeights: true,
    overflowScroll:true,
    updateHash: true,
    touchScroll:true,
    before:function() {},
    after:function() {},
    afterResize:function() {},
    afterRender:function() {}
};
</code>```

And the script in the Header:

```<code>$(function() {
  $.scrollify({
    section : ".fullscreen",
    sectionName : "section-name"
  });
});
</code>```

If you want to have a look at the page, the link is: http://kraftsy2017.ch.176-10-116-204.artemis.hostingmanager.ch

I would really appreciate your help, I'm feeling hopeless.
Thanks.

答:
Looks like the $ isn't referencing jQuery on your page.
Try this instead:

jQuery(function() {
  jQuery.scrollify({
    section : ".fullscreen",
    sectionName : "section-name"
  });
});

Body:
I'm not good with programming PHP and JS. But I'm trying to install and use Scrollify on my own theme for Wordpress. jQuery should also be loaded properly.
Unfortunately I cannot figure out how to make scrollify work, mostly out of lack of understanding how things react to each other or are properly loaded.

As it seems, I can load scrollify with this code in my functions.php:

function scrollify() {
    wp_register_script( 'jquery-scrollify', get_template_directory_uri() . '/js/scrollify/jquery.scrollify.js', array('jquery'));
    wp_enqueue_script( 'jquery-scrollify' );

    wp_register_script( 'jquery-scrollifymin', get_template_directory_uri() . '/js/scrollify/jquery.scrollify.min.js', array('jquery'));
    wp_enqueue_script( 'jquery-scrollifymin' );

    wp_register_script( 'Gruntfile', get_template_directory_uri() . '/js/scrollify/Gruntfile.js', array('jquery'));
    wp_enqueue_script( 'Grundtfile' ); }

add_action( 'wp_enqueue_scripts', 'scrollify' );

My HTML structure is like this:

Configuration in jquery.scrollify.js:

    //section should be an identifier that is the same for each section
    section: "fullscreen",
    sectionName: "section-name",
    interstitialSection: "",
    easing: "easeOutExpo",
    scrollSpeed: 1100,
    offset: 0,
    scrollbars: true,
    target:"html,body",
    standardScrollElements: false,
    setHeights: true,
    overflowScroll:true,
    updateHash: true,
    touchScroll:true,
    before:function() {},
    after:function() {},
    afterResize:function() {},
    afterRender:function() {}
};

And the script in the Header:

$(function() {
  $.scrollify({
    section : ".fullscreen",
    sectionName : "section-name"
  });
});

If you want to have a look at the page, the link is: http://kraftsy2017.ch.176-10-116-204.artemis.hostingmanager.ch

I would really appreciate your help, I'm feeling hopeless.
Thanks.


问:
How open tab in Espresso
How can i open tab in Espresso test? I  tried to do Espresso.onView(ViewMatchers.withId(R.id.practice_results_tab)).perform(ViewActions.click());, but that doesn't working. In that code i opened Layout of this tab.
There is the XML file:

```<code>    <TabHost
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/practice_tabHost">

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical">

            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content">
            </TabWidget>

            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent">

                <LinearLayout
                    android:id="@+id/practice_settings_tab"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:orientation="vertical">

                </LinearLayout>

                <LinearLayout
                    android:id="@+id/practice_results_tab"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:orientation="vertical">

                </LinearLayout>
            </FrameLayout>
        </LinearLayout>
    </TabHost>
</code>```

What ID should I use to open tab?

Error in logcat:

```<code>Caused by: java.lang.RuntimeException: Action will not be performed because the target     view does not match one or more of the following constraints:
at least 90 percent of the view's area is displayed to the user.
Target view: "LinearLayout{id=2131296384, res-name=practice_results_tab, visibility=GONE, width=0, height=0, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=true, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=1}"
</code>```

答:
the only thing that works for me is:

```<code>public void clickOnTab(String tabText) {
    Matcher<View> matcher = allOf(withText(tabText),
                                  isDescendantOfA(withId(R.id.ll_tab_container)));
    onView(matcher).perform(click());
}
</code>```

where ll_tab_container is the linearlayout for my custom tab layout.  and if you had a tab called "shopping" then you would pass that as the tabText.

Title: How open tab in Espresso

Body:
How can i open tab in Espresso test? I  tried to do Espresso.onView(ViewMatchers.withId(R.id.practice_results_tab)).perform(ViewActions.click());, but that doesn't working. In that code i opened Layout of this tab.
There is the XML file:

    <TabHost
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/practice_tabHost">

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical">

            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content">
            </TabWidget>

            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent">

                <LinearLayout
                    android:id="@+id/practice_settings_tab"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:orientation="vertical">

                </LinearLayout>

                <LinearLayout
                    android:id="@+id/practice_results_tab"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:orientation="vertical">

                </LinearLayout>
            </FrameLayout>
        </LinearLayout>
    </TabHost>

What ID should I use to open tab?

Error in logcat:

Caused by: java.lang.RuntimeException: Action will not be performed because the target     view does not match one or more of the following constraints:
at least 90 percent of the view's area is displayed to the user.
Target view: "LinearLayout{id=2131296384, res-name=practice_results_tab, visibility=GONE, width=0, height=0, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=true, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=1}"

Body:
the only thing that works for me is:

public void clickOnTab(String tabText) {
    Matcher<View> matcher = allOf(withText(tabText),
                                  isDescendantOfA(withId(R.id.ll_tab_container)));
    onView(matcher).perform(click());
}

where ll_tab_container is the linearlayout for my custom tab layout.  and if you had a tab called "shopping" then you would pass that as the tabText.


问:
SQL query to find top 2 customers done max amount of transaction( oracle db)
I want to get TOP  2 customers done maximum amount transaction from below the table.I am working on oracle db.

my table transactions:

```<code> tranID       PROD_ID       QTY      PRICE        CID
      1       100            5         10000      1000
      2       103            16        5000       1001
      3       102            8         5000       1003
      4       200            10        9000       1002
      5       204            8        9000         1002
      6       207            4         8000        1002
</code>```

CUSTOMERS

```<code>CID CNAME
1001  X
1002  Y
1003  Z
</code>```

答:
If Oracle 12c , you can use this.</p>

```<code>SELECT a.CID, b.CNAME, SUM (a.QTY * a.PRICE) amount
       FROM transactions a JOIN CUSTOMERS b ON a.CID = b.CID
   GROUP BY a.CID, b.CNAME
   ORDER BY amount DESC
FETCH FIRST 2 ROWS ONLY
</code>```

Body:
I want to get TOP  2 customers done maximum amount transaction from below the table.I am working on oracle db.

my table transactions:

 tranID       PROD_ID       QTY      PRICE        CID
      1       100            5         10000      1000
      2       103            16        5000       1001
      3       102            8         5000       1003
      4       200            10        9000       1002
      5       204            8        9000         1002
      6       207            4         8000        1002

CUSTOMERS

CID CNAME
1001  X
1002  Y
1003  Z

Body:
If Oracle 12c , you can use this.

SELECT a.CID, b.CNAME, SUM (a.QTY * a.PRICE) amount
       FROM transactions a JOIN CUSTOMERS b ON a.CID = b.CID
   GROUP BY a.CID, b.CNAME
   ORDER BY amount DESC
FETCH FIRST 2 ROWS ONLY


问:
FlatList pull up from bottom of list
I'm using the FlatList component of React-Native, which be default refreshes when pulled down at the top of the list.

```<code><FlatList
    data={reviews}
    keyExtractor={item=> item.review_id}
    renderItem={({item}) => (
      <ReviewItem
        review = {item}
      />
    )}
    refreshing = {true}
    onRefresh = {refreshReviews}
    ItemSeparatorComponent={() => <ListSeperator />}
  />
</code>```

The way I want to show reviews is the latest appears on top of the list and when I reach the bottom of the list and I pull up then it should load the next batch of reviews.

How can I do this? Will the behaviour be the same in iOS and Android ?

答:
Check this:

```<code>onEndReached={this.loadPosts.bind(this)}
onEndReachedThreshold={0}
ListFooterComponent={this.renderFooter(this.props.loading)}
</code>```

are useful to load the next contents when the list reaches the end.

ListFooterComponent is here to show an activity indicator to tell the user that something is loading

If you want to show new content when the user gets to the bottom and then pull to refresh, imho is not very clear for the user as UX.
Is more obvious load new contents scrolling to bottom

Title: FlatList pull up from bottom of list

Body:
I'm using the FlatList component of React-Native, which be default refreshes when pulled down at the top of the list.

<FlatList
    data={reviews}
    keyExtractor={item=> item.review_id}
    renderItem={({item}) => (
      <ReviewItem
        review = {item}
      />
    )}
    refreshing = {true}
    onRefresh = {refreshReviews}
    ItemSeparatorComponent={() => <ListSeperator />}
  />

The way I want to show reviews is the latest appears on top of the list and when I reach the bottom of the list and I pull up then it should load the next batch of reviews.

How can I do this? Will the behaviour be the same in iOS and Android ?

Body:
Check this:

onEndReached={this.loadPosts.bind(this)}
onEndReachedThreshold={0}
ListFooterComponent={this.renderFooter(this.props.loading)}

are useful to load the next contents when the list reaches the end.

ListFooterComponent is here to show an activity indicator to tell the user that something is loading

If you want to show new content when the user gets to the bottom and then pull to refresh, imho is not very clear for the user as UX.
Is more obvious load new contents scrolling to bottom


问:
Django: Filtering Distinct Data
I'm trying to build a messaging app. Here's my model,

```<code>class Message(models.Model):
sender = models.ForeignKey(User, related_name="sender")
receiver = models.ForeignKey(User, related_name="receiver")
msg_content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
</code>```

This is what I tried in view,

```<code>data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user)).order_by('-created_at')
</code>```

In my template,

```<code>{% for abc in data %}
    {{ abc.receiver }}<br />
{% endfor %}
</code>```

How can I print out the distinct users?

答:
You could query the senders and receivers separately and then use set() to get the distinct values

```<code>users = set([x.receiver for x in Message.objects.filter(sender = request.user)] + [x.sender for x in Message.objects.filter(receiver = request.user)])
</code>```

Title: Django: Filtering Distinct Data

Body:
I'm trying to build a messaging app. Here's my model,

class Message(models.Model):
sender = models.ForeignKey(User, related_name="sender")
receiver = models.ForeignKey(User, related_name="receiver")
msg_content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)

This is what I tried in view,

data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user)).order_by('-created_at')

In my template,

{% for abc in data %}
    {{ abc.receiver }}

{% endfor %}

How can I print out the distinct users?

Body:
You could query the senders and receivers separately and then use set() to get the distinct values

users = set([x.receiver for x in Message.objects.filter(sender = request.user)] + [x.sender for x in Message.objects.filter(receiver = request.user)])


问:
How can I split a string with occurrence of "users/" from a URL?
I Am using this method, this is my URL "https://www.youtube.com/user/myYoutubeChennal". and i want to get "myYoutubeChennal" from this.</p>

```<code>func splitVideoUrl(videoUrl:String) -> String {

    //let token = videoUrl.split(separator: "user/")
    let ttstr:String = " https://www.youtube.com/user/myYoutubeChennal"
    if let range = ttstr.range(of: "user/") {
        let firstPart = String(describing: ttstr.startIndex..<range.lowerBound)
        print(firstPart) // print Hello
        return firstPart
    }
    return ""
}
</code>```

答:
You can get the last component of URL using following code</p>

```<code>let url = URL(string:"https://www.youtube.com/user/myYoutubeChennal")
let lastComponent = url?.lastPathComponent
</code>```

Body:
I Am using this method, this is my URL "https://www.youtube.com/user/myYoutubeChennal". and i want to get "myYoutubeChennal" from this.

func splitVideoUrl(videoUrl:String) -> String {

    //let token = videoUrl.split(separator: "user/")
    let ttstr:String = " https://www.youtube.com/user/myYoutubeChennal"
    if let range = ttstr.range(of: "user/") {
        let firstPart = String(describing: ttstr.startIndex..<range.lowerBound)
        print(firstPart) // print Hello
        return firstPart
    }
    return ""
}

Body:
You can get the last component of URL using following code

let url = URL(string:"https://www.youtube.com/user/myYoutubeChennal")
let lastComponent = url?.lastPathComponent


答:
```<code>elements['hydrogen']['is_noble_gas'] = False
elements['hydrogen']['is_noble_gas'] = True
</code>```

Body:
elements = {'hydrogen': {'number': 1, 'weight': 1.00794, 'symbol': 'H'},
            'helium': {'number': 2, 'weight': 4.002602, 'symbol': 'He'}}

Add an is_noble_gas boolean entry to the hydrogen and helium dictionaries.


问:
How do I export my java project so it can run without the help of the IDE (netbeans)?
I recently completed a java project using Netbeans.After pushing clean and build button it creates a jar file.the problem is that the jar file won't connect with database(MySQL).It works perfectly while it's still in the IDE.How do I solve this problem so that I can install my software into another machine?</p>

答:
Checking the suggestions below might help.

Since your jar file connects to a database file, you need to read the
parameters like "url", "username" , "password" from some file(this is
called externalization)

Also check if you are having the database driver jar in your "lib"
while you try to run the jar outside of your IDE.


问:
Which one is better to iterate through each entry in HashMap?
I have two ways we can iterate through each entry in hashmap, can you explain which one is to be preferred over other and why ?

```<code>HashMap m = new HashMap();
m.put("A",100);
m.put("B",100);
m.put("C",100);
m.put("D",100);
</code>```

One way to iterate

```<code>Set s1 = m.entrySet();
Iterator itr = s1.iterate();
while(itr.hasNext()) {
Map.Entry m1 = (Map.Entry)s1.next();
System.out.println(m1.getKey()+"..."+m1.getValue);
}
</code>```

Second Way to iterate

```<code>Set<Map.Entry<String,Integer>> s1 = m.entrySet();
for(Map.Entry<String,Integer> m1:s1){
System.out.println(m1.getKey()+"..."+m1.getValue);
}
</code>```

答:
NOTE: for a simpler comparison of the real differences I rewrote the code

if you want just work on the elements forgetting that they belongs to a container... the second way is better because more concise and clearer to read

```<code>for (Map.Entry<String,Integer> elem : m.entrySet()) {
  System.out.println(elem.getKey() + "..." + elem.getValue());
}
</code>```

but, if you need to operate on the container structure itself (e.g., add, delete elements)...  the first way is the correct one

```<code>for (Iterator<Map.Entry<String, Integer>> itr = m.entrySet().iterator();
     itr.hasNext();) {
  Map.Entry<String, Integer> elem = itr.next();
  System.out.println(elem.getKey() + "..." + elem.getValue());
}
</code>```

Body:
I have two ways we can iterate through each entry in hashmap, can you explain which one is to be preferred over other and why ?

HashMap m = new HashMap();
m.put("A",100);
m.put("B",100);
m.put("C",100);
m.put("D",100);

One way to iterate

Set s1 = m.entrySet();
Iterator itr = s1.iterate();
while(itr.hasNext()) {
Map.Entry m1 = (Map.Entry)s1.next();
System.out.println(m1.getKey()+"..."+m1.getValue);
}

Second Way to iterate

Set<Map.Entry<String,Integer>> s1 = m.entrySet();
for(Map.Entry<String,Integer> m1:s1){
System.out.println(m1.getKey()+"..."+m1.getValue);
}

Body:
NOTE: for a simpler comparison of the real differences I rewrote the code

if you want just work on the elements forgetting that they belongs to a container... the second way is better because more concise and clearer to read

for (Map.Entry<String,Integer> elem : m.entrySet()) {
  System.out.println(elem.getKey() + "..." + elem.getValue());
}

but, if you need to operate on the container structure itself (e.g., add, delete elements)...  the first way is the correct one

for (Iterator<Map.Entry<String, Integer>> itr = m.entrySet().iterator();
     itr.hasNext();) {
  Map.Entry<String, Integer> elem = itr.next();
  System.out.println(elem.getKey() + "..." + elem.getValue());
}


问:
Yum, How to install package in other directory?
According to our systemadmins, all the package I need for my work will have to be installed in /appl.

Is it possible, using 'yum' as packagemanager, to install packages into another directory as defaulted by the package?

答: As for rpm, it has --relocate OLDPATH=NEWPATH and --prefix NEWPATH which will allow you to change the install path for rpms marked as relocatable which will not apply to all packages. In general, it is not considered a good idea.</p>


问:
isset($_POST['submit'] not set after submitting my form
I'm new to php and I'm trying to register a user to a database using a form.

This is the code for the form (using the bootstrap framework):

```<code><form class="form-horizontal" role="form" method="POST" action="connectivity-reserve.php">
                <div class="form-group">
                    <label class="col-sm-2 control-label">Customer's name</label>
                    <div class="col-sm-6">
                        <div class="input-group">
                        <input type="text" class="form-control" id="Customername" name="Customername" placeholder="Customer name">
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <label class="col-sm-2 control-label">Password</label>
                    <div class="col-sm-6">
                        <div class="input-group">
                        <input type="password" class="form-control" id="pwd" name="pwd" placeholder="Password">
                        </div>
                    </div>
                </div>

                </div>
                 <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                    <button type="submit" name ="submit" class="btn btn-primary">Reserve</button>
                    <button type="button" class="btn btn-default btn-sm"
                   data-dismiss="modal">Cancel</button>
                    </div>
                </div>
                <div class="form-group">
                <div class="alert alert-warning alert-dismissible" role="alert">
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">×</span>
                    </button>
                    <strong>Warning:</strong>: Please <a href="tel:+85212345678" class="alert-link">
                    call</a> us to reserve for more than six guests.
                </div>
                </div>
            </form>
</code>```

Here is the file (mysqli_connect.php) for connecting to the database. This is working:

```<code><?php
// This provides the information for accessing the database.
// It also creates a connection to MySQL,
// It selects the database, and sets the encoding.
// Set the database access information as constants:
DEFINE ('DB_USER', 'xxxx');
DEFINE ('DB_PASSWORD', 'xxxx');
DEFINE ('DB_HOST', 'xxxx');
DEFINE ('DB_NAME', 'xxxx');
// Make the connection:
$dbcon = @mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die ('Could not connect to MySQL: ' . mysqli_connect_error() );
// Set the encoding...
mysqli_set_charset($dbcon, 'utf8');
</code>```

The file connectivity-reserve.php is what I'm using to add the user into the database.
Here is the code:

```<code><?php
require ('mysqli_connect.php');

echo "yay";

if(isset($_POST['submit']))
{

$Customername = $_POST['Customername'];
$pwd  = $_POST['pwd'];
$q = "INSERT INTO users (user_id, cname, psword, ) VALUES (' ', '$Customername', '$pwd')";

 $result = @mysqli_query ($dbcon, $q);

 if($result)
    {
        echo "YOUR REGISTRATION IS COMPLETED...";
    }
    else
    {
        echo "nah";
    }
}

?>
</code>```

I'm able to connect to the database since the code echo "yay" is displayed on the browser. The issue is with the if(isset($_POST['submit'])) condition. I thought it should work since my button's type and name are 'submit' on the form:

```<code><button type="submit" name ="submit" class="btn btn-primary">Reserve</button>
</code>```

Help will be greatly appreciated.

Edit: Thanks guys! It was the , after psword. Also I know the code isn't secure. I'm just starting out with php so that isn't really a priority for me right now.

答:
```<code>$q = "INSERT INTO users (user_id, cname, psword ) VALUES (' ', '$Customername', '$pwd')";
</code>```

Remove the comma from psword. Tested your code in my local db and is working just fine.

Body:
I'm new to php and I'm trying to register a user to a database using a form.

This is the code for the form (using the bootstrap framework):

<form class="form-horizontal" role="form" method="POST" action="connectivity-reserve.php">

                    Customer's name

                        <input type="text" class="form-control" id="Customername" name="Customername" placeholder="Customer name">

                    Password

                        <input type="password" class="form-control" id="pwd" name="pwd" placeholder="Password">

                    <button type="submit" name ="submit" class="btn btn-primary">Reserve</button>
                    <button type="button" class="btn btn-default btn-sm"
                   data-dismiss="modal">Cancel</button>

                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    ×
                    </button>
                    Warning:: Please
                    call us to reserve for more than six guests.

            </form>

Here is the file (mysqli_connect.php) for connecting to the database. This is working:

<?php
// This provides the information for accessing the database.
// It also creates a connection to MySQL,
// It selects the database, and sets the encoding.
// Set the database access information as constants:
DEFINE ('DB_USER', 'xxxx');
DEFINE ('DB_PASSWORD', 'xxxx');
DEFINE ('DB_HOST', 'xxxx');
DEFINE ('DB_NAME', 'xxxx');
// Make the connection:
$dbcon = @mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die ('Could not connect to MySQL: ' . mysqli_connect_error() );
// Set the encoding...
mysqli_set_charset($dbcon, 'utf8');

The file connectivity-reserve.php is what I'm using to add the user into the database.
Here is the code:

<?php
require ('mysqli_connect.php');

echo "yay";

if(isset($_POST['submit']))
{

$Customername = $_POST['Customername'];
$pwd  = $_POST['pwd'];
$q = "INSERT INTO users (user_id, cname, psword, ) VALUES (' ', '$Customername', '$pwd')";

 $result = @mysqli_query ($dbcon, $q);

 if($result)
    {
        echo "YOUR REGISTRATION IS COMPLETED...";
    }
    else
    {
        echo "nah";
    }
}

?>

I'm able to connect to the database since the code echo "yay" is displayed on the browser. The issue is with the if(isset($_POST['submit'])) condition. I thought it should work since my button's type and name are 'submit' on the form:

<button type="submit" name ="submit" class="btn btn-primary">Reserve</button>

Help will be greatly appreciated.

Edit: Thanks guys! It was the , after psword. Also I know the code isn't secure. I'm just starting out with php so that isn't really a priority for me right now.

Body:
$q = "INSERT INTO users (user_id, cname, psword ) VALUES (' ', '$Customername', '$pwd')";

Remove the comma from psword. Tested your code in my local db and is working just fine.


问:
How can I center a text and keep being left align?
Here is a simplified of my code:

.wrapper{
  border: 1px solid gray;
  width: 30%;
  margin: 20px auto;
}
.icon{
  text-align: center;
}

.icon i{
  font-size: 100px;
  color: gray;
}
.text{
  text-align: center;
}
.text span{
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

<div class="wrapper">

  <div class="icon">
    <i class="fa fa-home" aria-hidden="true"></i>
  </div>
  <div class="text">
    <span><i class="fa fa-check-square" aria-hidden="true"></i> Something </span>
    <span><i class="fa fa-check-square" aria-hidden="true"></i> Something Else </span>
    <span><i class="fa fa-check-square" aria-hidden="true"></i> Some </span>
  </div>

</div></code>```

All I want to do is putting all check icons exactly under each other vertically. How can I do that?

答:
Use text-align:left; instead, and adjust the width or margin of .text to center it

.wrapper{
  border: 1px solid gray;
  width: 30%;
  margin: 20px auto;
}
.icon{
  text-align: center;
}

.icon i{
  font-size: 100px;
  color: gray;
}
.text{
  text-align: left;
  width: 70%;
  margin: 0 auto;
}
.text span{
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

<div class="wrapper">

  <div class="icon">
    <i class="fa fa-home" aria-hidden="true"></i>
  </div>
  <div class="text">
    <span><i class="fa fa-check-square" aria-hidden="true"></i> Something </span>
    <span><i class="fa fa-check-square" aria-hidden="true"></i> Something Else </span>
    <span><i class="fa fa-check-square" aria-hidden="true"></i> Some </span>
  </div>

</div></code>```

Body:
Here is a simplified of my code:

.wrapper{
  border: 1px solid gray;
  width: 30%;
  margin: 20px auto;
}
.icon{
  text-align: center;
}

.icon i{
  font-size: 100px;
  color: gray;
}
.text{
  text-align: center;
}
.text span{
  display: block;
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

     Something
     Something Else
     Some

All I want to do is putting all check icons exactly under each other vertically. How can I do that?

Body:
Use text-align:left; instead, and adjust the width or margin of .text to center it

.wrapper{
  border: 1px solid gray;
  width: 30%;
  margin: 20px auto;
}
.icon{
  text-align: center;
}

.icon i{
  font-size: 100px;
  color: gray;
}
.text{
  text-align: left;
  width: 70%;
  margin: 0 auto;
}
.text span{
  display: block;
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

<div class="wrapper">

  <div class="icon">
    <i class="fa fa-home" aria-hidden="true"></i>
  </div>
  <div class="text">
    <span><i class="fa fa-check-square" aria-hidden="true"></i> Something </span>
    <span><i class="fa fa-check-square" aria-hidden="true"></i> Something Else </span>
    <span><i class="fa fa-check-square" aria-hidden="true"></i> Some </span>
  </div>

</div>


问:
How to find class name from inspected code
When I inspected my web page I got this code

```<code><li id="SR_R1_tab" class="t-Tabs-item a-Tabs-before a-Tabs-selected is-active" aria-controls="SR_R1" role="tab" aria-selected="true">
</code>```

It is an oracle apex tabular region's sub region. I want to perform some css modifications and javascript actions in this class(sub regions of tabular region). How to find the exact class from this inspected code?. Should I use the class 't-Tabs-item' or 't-Tabs-item a-Tabs-before a-Tabs-selected is-active' ?

答:
The li element you posted has the class attribute:

```<code>class="t-Tabs-item a-Tabs-before a-Tabs-selected is-active"
</code>```

This means it has the following class names:

```<code>t-Tabs-item
a-Tabs-before
a-Tabs-selected
is-active
</code>```

If you want to target only this li, by class name, and considering no other HTML elements have the same exact class t-Tabs-item a-Tabs-before a-Tabs-selected is-active, use this class name for selection:

```<code>.t-Tabs-item.a-Tabs-before.a-Tabs-selected.is-active { ... }
</code>```

If you want to select any element which has the class name t-Tabs-item, use it as a selector, but consider that if other HTML elements in your page have this class, your selection would return multiple elements.

As per @str's comment to your question, if you want to target this specific li element, it's best to use an id selector:

```<code>#SR_R1_tab  { ... }
</code>```

Body:
When I inspected my web page I got this code

It is an oracle apex tabular region's sub region. I want to perform some css modifications and javascript actions in this class(sub regions of tabular region). How to find the exact class from this inspected code?. Should I use the class 't-Tabs-item' or 't-Tabs-item a-Tabs-before a-Tabs-selected is-active' ?

Body:
The li element you posted has the class attribute:

class="t-Tabs-item a-Tabs-before a-Tabs-selected is-active"

This means it has the following class names:

t-Tabs-item
a-Tabs-before
a-Tabs-selected
is-active

If you want to target only this li, by class name, and considering no other HTML elements have the same exact class t-Tabs-item a-Tabs-before a-Tabs-selected is-active, use this class name for selection:

.t-Tabs-item.a-Tabs-before.a-Tabs-selected.is-active { ... }

If you want to select any element which has the class name t-Tabs-item, use it as a selector, but consider that if other HTML elements in your page have this class, your selection would return multiple elements.

As per @str's comment to your question, if you want to target this specific li element, it's best to use an id selector:

#SR_R1_tab  { ... }


问:
Permission denied, error log
I'm trying to create a simple error log that write down php errors in case these cannot be reported to the admin (with a database connection). I wrote this:

```<code>function errorLog($array)
{
    $time = date("F j, Y, g:i a");
    $ip = $_SERVER['REMOTE_ADDR'];
    $no = $array['e-no'];
    $string = $array['e-string'];
    $file = $array['e-file'];
    $line = $array['e-line'];
    $context = $array['e-context'];

    $string = "TIME {$time} IP {$ip} ERROR {$no} | {$string} | {$file} | {$line} | {$context}";
    if ($handler = fopen('log/log-file.txt', 'a'))
    {
        fwrite($handler, $string);
        fclose($handler);
    }
    else
    {
        exit('Fatal Error #0002');
    }
}
</code>```

START EDIT

Function had became

```<code>function errorLog($array)
{
    $time = date("F j, Y, g:i a");
    $ip = $_SERVER['REMOTE_ADDR'];
    $type = $array['e-type'];
    $string = $array['e-string'];
    $file = $array['e-file'];
    $line = $array['e-line'];
    $context = $array['e-context']
    $string = "ON {$time} IP {$ip} ERROR {$type} | {$string} | {$file} | {$line} | {$context}";
    if (!error_log($string, 3, 'log/log-file.txt')) { exit('Fatal Error #0002'); }
}
</code>```

END EDIT

But when i run it i get

```<code>Warning: fopen(log/log-file.txt) [function.fopen]: failed to open stream: Permission denied in myfile.php on line 17
</code>```

I got this is a server permission problem, but i am working on a localhost (Xampp on Mac os x) and i'd like to manage these permissions. How can i place log/ to be writable only? Is there any better ways of doing what i am trying to do?

答:
I got this is a server permission problem, but i am working on a localhost (Xampp on Mac os
  x) and i'd like to manage these permissions. How can i place log/ to be writable only? Is
  there any better ways of doing what i am trying to do?

You might want to checkout set_error_handler, to make sure all errors are automatically sent through your custom function. Anyway, that's not the source of your problem, your issue is actually the permissions on the server. Now, the first thing to do is to determine as what user PHP is running. This can be very simple to determine, you just have to run this script:

```<code><?php
echo `whoami`;
</code>```

In case of your Mac, that probably is 'www-data'. If you want to change that (possibly), you should delve into how (f.e.) Apache MPM ITK works. If you're fine with 'www-data' running your scripts, you should give 'www-data' access to the log directory. First, go to the parent directory and issue command 'ls -laF', to see detailed information about the log directory. Let's say the output is the following:

rwxr-xr-x   2 berry berry      4096 2011-01-18 16:53 log/

In this case, I (the user "berry") would be the owner. The group that I'm primarily in (namely, "berry") is the group that owns the directory. Now, you can tell by the rwx r-x r-x, that the owner (first rwx) can read, write and execute. The second (the group) can read and execute. The others (everyone else) can read and execute.

"www-data" is probably not in the group "berry". To fix this, you want to issue the command: chgrp -R www-data log/, followed by chmod -R g+x log/. That means: change the owning group to "www-data", and give the group (g) execute permission (+x), do that recursively (-R) on directory "log/".

Good luck.

Title: Permission denied, error log

Body:
I'm trying to create a simple error log that write down php errors in case these cannot be reported to the admin (with a database connection). I wrote this:

function errorLog($array)
{
    $time = date("F j, Y, g:i a");
    $ip = $_SERVER['REMOTE_ADDR'];
    $no = $array['e-no'];
    $string = $array['e-string'];
    $file = $array['e-file'];
    $line = $array['e-line'];
    $context = $array['e-context'];

    $string = "TIME {$time} IP {$ip} ERROR {$no} | {$string} | {$file} | {$line} | {$context}";
    if ($handler = fopen('log/log-file.txt', 'a'))
    {
        fwrite($handler, $string);
        fclose($handler);
    }
    else
    {
        exit('Fatal Error #0002');
    }
}

START EDIT

Function had became

function errorLog($array)
{
    $time = date("F j, Y, g:i a");
    $ip = $_SERVER['REMOTE_ADDR'];
    $type = $array['e-type'];
    $string = $array['e-string'];
    $file = $array['e-file'];
    $line = $array['e-line'];
    $context = $array['e-context']
    $string = "ON {$time} IP {$ip} ERROR {$type} | {$string} | {$file} | {$line} | {$context}";
    if (!error_log($string, 3, 'log/log-file.txt')) { exit('Fatal Error #0002'); }
}

END EDIT

But when i run it i get

Warning: fopen(log/log-file.txt) [function.fopen]: failed to open stream: Permission denied in myfile.php on line 17

I got this is a server permission problem, but i am working on a localhost (Xampp on Mac os x) and i'd like to manage these permissions. How can i place log/ to be writable only? Is there any better ways of doing what i am trying to do?

Body:
I got this is a server permission problem, but i am working on a localhost (Xampp on Mac os
  x) and i'd like to manage these permissions. How can i place log/ to be writable only? Is
  there any better ways of doing what i am trying to do?

You might want to checkout set_error_handler, to make sure all errors are automatically sent through your custom function. Anyway, that's not the source of your problem, your issue is actually the permissions on the server. Now, the first thing to do is to determine as what user PHP is running. This can be very simple to determine, you just have to run this script:

<?php
echo `whoami`;

In case of your Mac, that probably is 'www-data'. If you want to change that (possibly), you should delve into how (f.e.) Apache MPM ITK works. If you're fine with 'www-data' running your scripts, you should give 'www-data' access to the log directory. First, go to the parent directory and issue command 'ls -laF', to see detailed information about the log directory. Let's say the output is the following:

rwxr-xr-x   2 berry berry      4096 2011-01-18 16:53 log/

In this case, I (the user "berry") would be the owner. The group that I'm primarily in (namely, "berry") is the group that owns the directory. Now, you can tell by the rwx r-x r-x, that the owner (first rwx) can read, write and execute. The second (the group) can read and execute. The others (everyone else) can read and execute.

"www-data" is probably not in the group "berry". To fix this, you want to issue the command: chgrp -R www-data log/, followed by chmod -R g+x log/. That means: change the owning group to "www-data", and give the group (g) execute permission (+x), do that recursively (-R) on directory "log/".

Good luck.


问:
Download large zip file using web Api and angular 2
Get Web-API method to download zip file

This code is not working

Please help me out on this.

```<code>public HttpResponseMessage SampleDownload()
            {
                try {
                    HttpResponseMessage result = null;
                    var path = @"D:\sample\sample.zip";
                    var filename = "sample.zip";
                    if (File.Exists(path))
                    {
                        result = new HttpResponseMessage(HttpStatusCode.OK);
                        var stream = new FileStream(path, FileMode.Open);
                        result.Content = new StreamContent(stream);
                        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                        result.Content.Headers.ContentDisposition.FileName = filename;
                    }
                    return result;
    }
</code>```

答:
C# Web API Code:

```<code>public IActionResult GetZipFile(string filename)
{
    // It can be zip file or pdf but we need to change contentType respectively
    const string contentType ="application/zip";
    HttpContext.Response.ContentType = contentType;
    var result = new FileContentResult(System.IO.File.ReadAllBytes(@"{path_to_files}\file.zip"), contentType)
    {
         // It can be zip file or pdf but we need to change the extension respectively
        FileDownloadName = $"{filename}.zip"
    };

    return result;
}
</code>```

Angular Code:

Requirement: FileSaver ( Install file saver package)

import * as FileSaver from 'file-saver';

```<code> this.http.get(url,{ responseType: ResponseContentType.Blob }).subscribe((response)=>{
             var blob = new Blob([response['_body']], {type: "application/zip"});
              FileSaver.saveAs(blob,dlData.file_name);
        }).catch((error) => {
           // Error code
        });
</code>```

Reference url :  How to download a ZipFile from a dotnet core webapi?

Body:
Get Web-API method to download zip file

This code is not working

Please help me out on this.

public HttpResponseMessage SampleDownload()
            {
                try {
                    HttpResponseMessage result = null;
                    var path = @"D:\sample\sample.zip";
                    var filename = "sample.zip";
                    if (File.Exists(path))
                    {
                        result = new HttpResponseMessage(HttpStatusCode.OK);
                        var stream = new FileStream(path, FileMode.Open);
                        result.Content = new StreamContent(stream);
                        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                        result.Content.Headers.ContentDisposition.FileName = filename;
                    }
                    return result;
    }

Body:
C# Web API Code:

public IActionResult GetZipFile(string filename)
{
    // It can be zip file or pdf but we need to change contentType respectively
    const string contentType ="application/zip";
    HttpContext.Response.ContentType = contentType;
    var result = new FileContentResult(System.IO.File.ReadAllBytes(@"{path_to_files}\file.zip"), contentType)
    {
         // It can be zip file or pdf but we need to change the extension respectively
        FileDownloadName = $"{filename}.zip"
    };

    return result;
}

Angular Code:

Requirement: FileSaver ( Install file saver package)

import * as FileSaver from 'file-saver';

 this.http.get(url,{ responseType: ResponseContentType.Blob }).subscribe((response)=>{
             var blob = new Blob([response['_body']], {type: "application/zip"});
              FileSaver.saveAs(blob,dlData.file_name);
        }).catch((error) => {
           // Error code
        });

Reference url :  How to download a ZipFile from a dotnet core webapi?


问:
The model backing the '--Context' context has changed since the database was created - but db is new production database
I've got this error for the 762nd time but this time I am getting it as soon as I attempt to access my Production site, straight after deleting the 'production' database on Azure and then publishing my site.

```<code>The model backing the 'PropertyContext' context has changed since the database was created. Consider using Code First Migrations to update the database
</code>```

I deleted the database because I couldn't fix this issue any other way but it still doesn't work.

Some important points:

I'm using EF6 and publishing to Azure.

This is 1 of 2 projects/sites that uses the same Repo project. I have no

problems with the other one, just this one.

I have tried publishing the problem project first (after deleting the db) and
second with the same result.

I have tried deleting both WEBSITES and the DB from Azure and starting again

I have tried deleting all migrations and starting with a fresh data model

I have tried the following in my Global.asax (in both projects)

Database.SetInitializer PropertyContext>(null);  <-- SO won't let me put the first <

and

```<code>Database.SetInitializer(new MigrateDatabaseToLatestVersion<PropertyContext, MyConfiguration>());
new PropertyContext().Database.Initialize(true);
</code>```

I'm using .net 4.5

Why am I getting this error on a new database and how can I get this site to work?

答:
I have spent some hours trying to solve this problem. One project was working, the other one wasn't.

I had different projects referencing different versions of Entity Framework. In my case, I had a Console app and a Windows Service app, both referencing a third project containing code first classes and DbContext.

After running Update-Package EntityFramework everything worked fine in both projects.

Body:
I've got this error for the 762nd time but this time I am getting it as soon as I attempt to access my Production site, straight after deleting the 'production' database on Azure and then publishing my site.

The model backing the 'PropertyContext' context has changed since the database was created. Consider using Code First Migrations to update the database

I deleted the database because I couldn't fix this issue any other way but it still doesn't work.

Some important points:

I'm using EF6 and publishing to Azure.

This is 1 of 2 projects/sites that uses the same Repo project. I have no

problems with the other one, just this one.

I have tried publishing the problem project first (after deleting the db) and
second with the same result.

I have tried deleting both WEBSITES and the DB from Azure and starting again

I have tried deleting all migrations and starting with a fresh data model

I have tried the following in my Global.asax (in both projects)

Database.SetInitializer PropertyContext>(null);  <-- SO won't let me put the first <

and

Database.SetInitializer(new MigrateDatabaseToLatestVersion<PropertyContext, MyConfiguration>());
new PropertyContext().Database.Initialize(true);

I'm using .net 4.5

Why am I getting this error on a new database and how can I get this site to work?


问:
C++ comparing Char to Strings
I'm trying to loop through a word but only vowels are working for some reason. The other type prints out the amount of words in total. Please excuse my poor choise of words mixed with Swedish and English.</p>

```<code>#include <iostream>

using namespace std;

int main()
{
    int vo = 0;
    int ko = 0;

    char vocals[7]
    {
        'A','O','U','E','I','Y'
    };

    char konsonanter[19]
    {
        'B','C','D','F','G','H','J','K','L','M','N','P','Q','R','S','T','V','X','Z'
    };

    string word = "Toysoldier";

    for(int i = 0; i < word.length(); i++)
    {
        for(int v = 0; v < vocals[v]; v++)
        {
            if(vocals[v] == word[i])
                vo++;
        }

        for(int k = 0; k < konsonanter[k]; k++)
        {
            if(konsonanter[k] == word[i])
                ko++;
        }
    }

    cout << "Konsonanter = " << ko << " Vokaler = " << vo << endl;
}
</code>```

答:
Your error is in the tests used in the "for" loops:
v < vocals[v] will compare the integer v to the integer value of the character vocals[v], which happens to be the ASCII code of that character (in practice, that'll be something between 65 and 90, look up "Ascii table" on the web).

To fix your code, you should modify your "for" loops like this:

```<code>for (char vocal : vocals) {
  if (word[i] == vocal) vo++;
}
for (char konsonant : konsonanter) {
  if (word[i] == vocal) ko++;
}
</code>```

Also, note that you got the number of vocals wrong in your "vocals" array: it's 6, not 7.

Title: C++ comparing Char to Strings

Body:
I'm trying to loop through a word but only vowels are working for some reason. The other type prints out the amount of words in total. Please excuse my poor choise of words mixed with Swedish and English.

#include <iostream>

using namespace std;

int main()
{
    int vo = 0;
    int ko = 0;

    char vocals[7]
    {
        'A','O','U','E','I','Y'
    };

    char konsonanter[19]
    {
        'B','C','D','F','G','H','J','K','L','M','N','P','Q','R','S','T','V','X','Z'
    };

    string word = "Toysoldier";

    for(int i = 0; i < word.length(); i++)
    {
        for(int v = 0; v < vocals[v]; v++)
        {
            if(vocals[v] == word[i])
                vo++;
        }

        for(int k = 0; k < konsonanter[k]; k++)
        {
            if(konsonanter[k] == word[i])
                ko++;
        }
    }

    cout << "Konsonanter = " << ko << " Vokaler = " << vo << endl;
}

Body:
Your error is in the tests used in the "for" loops:
v < vocals[v] will compare the integer v to the integer value of the character vocals[v], which happens to be the ASCII code of that character (in practice, that'll be something between 65 and 90, look up "Ascii table" on the web).

To fix your code, you should modify your "for" loops like this:

for (char vocal : vocals) {
  if (word[i] == vocal) vo++;
}
for (char konsonant : konsonanter) {
  if (word[i] == vocal) ko++;
}

Also, note that you got the number of vocals wrong in your "vocals" array: it's 6, not 7.


答:
There is an error in your query:

Below statement:

```<code>$q = "INSERT INTO users (user_id, cname, psword, ) VALUES (' ', '$Customername', '$pwd')";
</code>```

should be:

```<code>$q = "INSERT INTO users (user_id, cname, psword) VALUES (' ', '$Customername', '$pwd')";
</code>```

There was an additional comma which would fail the query and result in error.

Secondly, instead of checking if(isset($_POST['submit'])), you should check for Customername and pwd

```<code>if(isset($_POST['Customername']) && isset($_POST['pwd'])) {
</code>```

Title: isset($_POST['submit'] not set after submitting my form

Body:
There is an error in your query:

Below statement:

$q = "INSERT INTO users (user_id, cname, psword, ) VALUES (' ', '$Customername', '$pwd')";

should be:

$q = "INSERT INTO users (user_id, cname, psword) VALUES (' ', '$Customername', '$pwd')";

There was an additional comma which would fail the query and result in error.

Secondly, instead of checking if(isset($_POST['submit'])), you should check for Customername and pwd

if(isset($_POST['Customername']) && isset($_POST['pwd'])) {


问:
how to write if else under return react native
hope you are doing well.

I am stuck in little problem is i want to pass a  tag only if my condition goes true.

for ex:

```<code>render(
   return(
     <View>
         {
          if(data==='test')
            {
              <Text>Hello this is Test Execution </Text>
            }
         }
     </View>
   )
)
</code>```

i want to do exactly like above example.

i get some errors i can't understand what to do so please help me.

Thank you

答:
A short and safe way would be to use a ternary operator and render null if false:

```<code>{ data === 'test' ? <Text>Hello this is Test Execution </Text> : null }
</code>```

Body:
hope you are doing well.

I am stuck in little problem is i want to pass a  tag only if my condition goes true.

for ex:

render(
   return(
     <View>
         {
          if(data==='test')
            {
              <Text>Hello this is Test Execution </Text>
            }
         }
     </View>
   )
)

i want to do exactly like above example.

i get some errors i can't understand what to do so please help me.

Thank you

Body:
A short and safe way would be to use a ternary operator and render null if false:

{ data === 'test' ? <Text>Hello this is Test Execution </Text> : null }


问:
EF4 Unable to load one or more of the requested types on test server
I developed an ASP.NET v4 application using Entity Framework 4. I'm deploying it to the test server (Windows 2008 R2 with .NET Framework 4 installed).

The application throws this error:

[ReflectionTypeLoadException: Unable
  to load one or more of the requested
  types. Retrieve the LoaderExceptions
  property for more information.]

  System.Reflection.RuntimeModule.GetTypes(RuntimeModule
  module) +0

  System.Reflection.Assembly.GetTypes()
  +144    System.Data.Metadata.Edm.ObjectItemConventionAssemblyLoader.LoadTypesFromAssembly()
  +45    System.Data.Metadata.Edm.ObjectItemAssemblyLoader.Load()
  +34    System.Data.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly
  assembly, Boolean
  loadReferencedAssemblies,
  ObjectItemLoadingSessionData
  loadingData) +130

  System.Data.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly
  assembly, Boolean
  loadReferencedAssemblies,
  KnownAssembliesSet knownAssemblies,
  EdmItemCollection edmItemCollection,
  Action1 logLoadMessage, Object&
  loaderCookie, Dictionary2&
  typesInLoading, List1& errors) +248

  System.Data.Metadata.Edm.ObjectItemCollection.LoadAssemblyFromCache(ObjectItemCollection
  objectItemCollection, Assembly
  assembly, Boolean
  loadReferencedAssemblies,
  EdmItemCollection edmItemCollection,
  Action1 logLoadMessage) +580

  System.Data.Metadata.Edm.ObjectItemCollection.ImplicitLoadAssemblyForType(Type
  type, EdmItemCollection
  edmItemCollection) +121

  System.Data.Metadata.Edm.MetadataWorkspace.ImplicitLoadAssemblyForType(Type
  type, Assembly callingAssembly) +178

  System.Data.Objects.ObjectContext.GetTypeUsage(Type
  entityCLRType) +49

  System.Data.Objects.ObjectContext.CreateObjectSet(String
  entitySetName) +163

  PageManager.FetchDefaultPage()
  +114

When I look on my development PC I see this directory with assemblies:

C:\Program Files (x86)\Reference
  Assemblies\Microsoft\Framework.NETFramework\v4.0

But on the server the whole .NETFramework directory is missing, there is just a v3.0 and v3.5 directory. I assume the server is using the assembly from one of these directories which are version 3.5.0.0 and not 4.0.0.0 (what my app is referencing).

What do I need to install? .NET 4 is installed on the server i'm 100% sure.

答: I believe your question is answered here: http://msdn.microsoft.com/en-us/library/cc656912.aspx</p>


问:
regexp for checking the full name
I would like to write a regexp to check if the user inserted at least two words separated by at least one empty space:

Example:

```<code>var regexp = new RegExp(/^[a-z,',-]+(\s)[a-z,',-]+$/i);

regexp.test("D'avid Camp-Bel"); // true
regexp.test("John ---"); // true // but it should be false!
</code>```

Title: regexp for checking the full name

Body:
I would like to write a regexp to check if the user inserted at least two words separated by at least one empty space:

Example:

var regexp = new RegExp(/^[a-z,',-]+(\s)[a-z,',-]+$/i);

regexp.test("D'avid Camp-Bel"); // true
regexp.test("John ---"); // true // but it should be false!

Body: /^[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*$/g


答:
Just add text-align:left; to .text span class.

.wrapper{
  border: 1px solid gray;
  width: 30%;
  margin: 20px auto;
  padding:10px;
}
.icon{
  text-align: center;
}

.icon i{
  font-size: 100px;
  color: gray;
}
.text{
  text-align: center;
}
.text span{
  display: block;
  text-align:left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

<div class="wrapper">

  <div class="icon">
    <i class="fa fa-home" aria-hidden="true"></i>
  </div>
  <div class="text">
    <span><i class="fa fa-check-square" aria-hidden="true"></i> Something </span>
    <span><i class="fa fa-check-square" aria-hidden="true"></i> Something Else </span>
    <span><i class="fa fa-check-square" aria-hidden="true"></i> Some </span>
  </div>

</div></code>```

Title: How can I center a text and keep being left align?

Body:
Just add text-align:left; to .text span class.

.wrapper{
  border: 1px solid gray;
  width: 30%;
  margin: 20px auto;
  padding:10px;
}
.icon{
  text-align: center;
}

.icon i{
  font-size: 100px;
  color: gray;
}
.text{
  text-align: center;
}
.text span{
  display: block;
  text-align:left;
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

<div class="wrapper">

  <div class="icon">
    <i class="fa fa-home" aria-hidden="true"></i>
  </div>
  <div class="text">
    <span><i class="fa fa-check-square" aria-hidden="true"></i> Something </span>
    <span><i class="fa fa-check-square" aria-hidden="true"></i> Something Else </span>
    <span><i class="fa fa-check-square" aria-hidden="true"></i> Some </span>
  </div>

</div>


问:
how to get Information of camera android
how i can get information of Camera android like list of parameters:
enter image description here

please help.

答:
```<code>Camera mcamera = Camera.open();
Camera.Parameters p= mCamera.getParameters();

String flashMode = p.getFlashMode();
</code>```

Like this, you can get all the parameters you need.

Body:
Camera mcamera = Camera.open();
Camera.Parameters p= mCamera.getParameters();

String flashMode = p.getFlashMode();

Like this, you can get all the parameters you need.


问:
C# Parse XML to Object and store into Database
I'm currently working on an ASP.NET MVC 4.6 application using SQL Server 2014 as a data storage.

I need to parse a XML document from an URL, transform the XML into an object and store it into the database using Entity Framework 6.

I need to parse the XML from an URL like this:

http: //api.myserver.com/notes.xml

My XML looks like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<notes>
    <note>
      <to>Tove</to>
      <from>Jane</from>
      <heading>Reminder</heading>
      <body>Don't forget me this weekend!</body>
    </note>
    <note>
      <to>Doe</to>
      <from>John</from>
      <heading>Meeting</heading>
      <body>Hello Monday!</body>
    </note>
<notes>
</code>```

My model class note looks like this:

```<code>public class Note
{
    public string To { get; set; }
    public string From { get; set; }
    public string Heading { get; set; }
    public string Body { get; set; }
}
</code>```

My current test implementation looks like this, BUT I'm not so happy about the parsing of the XML:

```<code>namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            String url = "https://www.w3schools.com/xml/note.xml";
            XmlDocument doc = new XmlDocument();
            doc.Load(url);
            XmlElement root = doc.DocumentElement;

            StringBuilder sb = new StringBuilder();
            sb.Append("<note>");

            foreach (XmlNode item in root)
            {
                sb.Append(item.OuterXml);
            }
            sb.Append("</note>");

            var result = Deserialize<Note>(sb.ToString());

            // further processing of result using EF 6

            Console.ReadKey();
        }

        public static T Deserialize<T>(string xmlText)
        {
            try
            {
                var stringReader = new StringReader(xmlText);
                var serializer = new XmlSerializer(typeof(T));
                return (T)serializer.Deserialize(stringReader);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
    }

    [XmlRoot(ElementName = "note", Namespace = "")]
    public class Note
    {
        [XmlElement("to")]
        public string To { get; set; }
        [XmlElement("from")]
        public string From { get; set; }
        [XmlElement("heading")]
        public string Heading { get; set; }
        [XmlElement("body")]
        public string Body { get; set; }
    }

}
</code>```

As far as I noticed, .NET provides several approaches on how to parse XML:

XmlReader Class

XPath

XDocument

DataSet

LINQ

I was wondering, what would you use and how would u solve the parsing of the XML document from an URL using .NET and converting into an object to store it in a SQL Server DB?

Thanks for your help and consideration!!

答:
This might help you, a serialize method and a Deserialize method.

```<code>public static string Serialize<T>(T dataToSerialize)
{
    try
    {
        var stringwriter = new ISOEncodingStringWriter();
        var serializer = new XmlSerializer(typeof(T));

        var xns = new XmlSerializerNamespaces();
        xns.Add(string.Empty, string.Empty);

        serializer.Serialize(stringwriter, dataToSerialize, xns);
        return stringwriter.ToString();
    }
    catch
    {
        throw;
    }
}

public static T Deserialize<T>(string xmlText)
{
    try
    {
        var stringReader = new System.IO.StringReader(xmlText);
        var serializer = new XmlSerializer(typeof(T));
        return (T)serializer.Deserialize(stringReader);
    }
    catch
    {
        throw;
    }
}
</code>```

You use the method like this:

```<code> Note result = Deserialize<Note>(xmlstring);

 Note note = new Note(){...};
 string convertedToXML = Serialize<Note>(note);
</code>```

Just remember that you need to add some data to your note class so it can actually serialize the data:

```<code>[XmlRoot(ElementName = "root", Namespace = "")]
public class Note
{
    [XmlElementAttribute("To")]
    public string To { get; set; }

    [XmlElementAttribute("From")]
    public string From { get; set; }

    [XmlElementAttribute("Heading")]
    public string Heading { get; set; }

    [XmlElementAttribute("Body")]
    public string Body { get; set; }
}
</code>```

I hope it helps :)

Body:
I'm currently working on an ASP.NET MVC 4.6 application using SQL Server 2014 as a data storage.

I need to parse a XML document from an URL, transform the XML into an object and store it into the database using Entity Framework 6.

I need to parse the XML from an URL like this:

http: //api.myserver.com/notes.xml

My XML looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<notes>
    <note>
      <to>Tove</to>
      <from>Jane</from>
      <heading>Reminder</heading>
      Don't forget me this weekend!
    </note>
    <note>
      <to>Doe</to>
      <from>John</from>
      <heading>Meeting</heading>
      Hello Monday!
    </note>
<notes>

My model class note looks like this:

public class Note
{
    public string To { get; set; }
    public string From { get; set; }
    public string Heading { get; set; }
    public string Body { get; set; }
}

My current test implementation looks like this, BUT I'm not so happy about the parsing of the XML:

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            String url = "https://www.w3schools.com/xml/note.xml";
            XmlDocument doc = new XmlDocument();
            doc.Load(url);
            XmlElement root = doc.DocumentElement;

            StringBuilder sb = new StringBuilder();
            sb.Append("<note>");

            foreach (XmlNode item in root)
            {
                sb.Append(item.OuterXml);
            }
            sb.Append("</note>");

            var result = Deserialize<Note>(sb.ToString());

            // further processing of result using EF 6

            Console.ReadKey();
        }

        public static T Deserialize<T>(string xmlText)
        {
            try
            {
                var stringReader = new StringReader(xmlText);
                var serializer = new XmlSerializer(typeof(T));
                return (T)serializer.Deserialize(stringReader);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
    }

    [XmlRoot(ElementName = "note", Namespace = "")]
    public class Note
    {
        [XmlElement("to")]
        public string To { get; set; }
        [XmlElement("from")]
        public string From { get; set; }
        [XmlElement("heading")]
        public string Heading { get; set; }
        [XmlElement("body")]
        public string Body { get; set; }
    }

}

As far as I noticed, .NET provides several approaches on how to parse XML:

XmlReader Class

XPath

XDocument

DataSet

LINQ

I was wondering, what would you use and how would u solve the parsing of the XML document from an URL using .NET and converting into an object to store it in a SQL Server DB?

Thanks for your help and consideration!!

Body:
This might help you, a serialize method and a Deserialize method.

public static string Serialize<T>(T dataToSerialize)
{
    try
    {
        var stringwriter = new ISOEncodingStringWriter();
        var serializer = new XmlSerializer(typeof(T));

        var xns = new XmlSerializerNamespaces();
        xns.Add(string.Empty, string.Empty);

        serializer.Serialize(stringwriter, dataToSerialize, xns);
        return stringwriter.ToString();
    }
    catch
    {
        throw;
    }
}

public static T Deserialize<T>(string xmlText)
{
    try
    {
        var stringReader = new System.IO.StringReader(xmlText);
        var serializer = new XmlSerializer(typeof(T));
        return (T)serializer.Deserialize(stringReader);
    }
    catch
    {
        throw;
    }
}

You use the method like this:

 Note result = Deserialize<Note>(xmlstring);

 Note note = new Note(){...};
 string convertedToXML = Serialize<Note>(note);

Just remember that you need to add some data to your note class so it can actually serialize the data:

[XmlRoot(ElementName = "root", Namespace = "")]
public class Note
{
    [XmlElementAttribute("To")]
    public string To { get; set; }

    [XmlElementAttribute("From")]
    public string From { get; set; }

    [XmlElementAttribute("Heading")]
    public string Heading { get; set; }

    [XmlElementAttribute("Body")]
    public string Body { get; set; }
}

I hope it helps :)


问:
How to find the Nth number in a fractal sequence?
The assignment is to write a C++ program which takes the input number n and outputs the nth number in the sequence:

1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6 ...

This is what I've come up with so far:

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

int main()
{
    long long n,k=1,result;
    cin >> n;
    if(n==1){
        result=1;
    }else{
        for(int i=1,j=1;;i=j,j=j+k){
            if(n>i&&n<=j){
                result=n-i;
                break;
            }else{
                k++;
            }
        }
    }
    cout << result << endl;
}
</code>```

This is also what I've written before:

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

int main()
{
    long long n,count=0,result;
    cin >> n;
    for(int i=1;;i++){
        for(int j=1;j<=i;j++){
            count=count+1;
            if(count==n){
                result=j;
                break;
            }
        }
        if(count>=n){
            break;
        }
    }
    cout << result << endl;
}
</code>```

Both of these work properly for smaller numbers, but the problem is I have to follow the constraint:

1 <= n <= 10^12

So when bigger numbers are inputted, the programs both take too long to output the solution and exceed the time limit, which is 2 seconds. I've been working on this for 5 hours now and I don't know how to improve these programs so they are faster. I also thought about a certain formula that could help determine the nth number in such a sequence, but I can't seem to find anything about it on the internet or in my math books. Could somebody point me to the solution? I would be very grateful.

答:
We can group numbers in your sequence:

```<code>(1) (1, 2) (1, 2, 3) ...
</code>```

The overall amount of numbers is

```<code>1 + 2 + 3 + ...
</code>```

The latter is an arithmetic progression, its sum equals to x*(x+1)/2.

We'll find the number of full groups k that go before n+1-th number in the sequence. k equals to the maximal integer such that k*(k+1)/2 <= n. To find it we'll solve the quadratic equation:

```<code>x*(x+1)/2 = n
x^2 + x - 2*n = 0
</code>```

Let's assume that positive root of this equation is x'. We round it down to the nearest integer k. If x' == k (x' is a whole number) it is the answer. Otherwise, the answer is n - k*(k+1)/2.

Exemplary c++ implementation:

```<code>double d = 1 + 8.0 * n;
double x = (-1 + sqrt(d)) / 2;

long long k = floor(x);
long long m = k*(k+1) / 2;
if (m == n) {
    return k;
} else {
    return n - m;
}
</code>```

The solution has O(1) time complexity.

Body:
The assignment is to write a C++ program which takes the input number n and outputs the nth number in the sequence:

1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6 ...

This is what I've come up with so far:

#include <iostream>
using namespace std;

int main()
{
    long long n,k=1,result;
    cin >> n;
    if(n==1){
        result=1;
    }else{
        for(int i=1,j=1;;i=j,j=j+k){
            if(n>i&&n<=j){
                result=n-i;
                break;
            }else{
                k++;
            }
        }
    }
    cout << result << endl;
}

This is also what I've written before:

#include <iostream>
using namespace std;

int main()
{
    long long n,count=0,result;
    cin >> n;
    for(int i=1;;i++){
        for(int j=1;j<=i;j++){
            count=count+1;
            if(count==n){
                result=j;
                break;
            }
        }
        if(count>=n){
            break;
        }
    }
    cout << result << endl;
}

Both of these work properly for smaller numbers, but the problem is I have to follow the constraint:

1 <= n <= 10^12

So when bigger numbers are inputted, the programs both take too long to output the solution and exceed the time limit, which is 2 seconds. I've been working on this for 5 hours now and I don't know how to improve these programs so they are faster. I also thought about a certain formula that could help determine the nth number in such a sequence, but I can't seem to find anything about it on the internet or in my math books. Could somebody point me to the solution? I would be very grateful.

Body:
We can group numbers in your sequence:

(1) (1, 2) (1, 2, 3) ...

The overall amount of numbers is

1 + 2 + 3 + ...

The latter is an arithmetic progression, its sum equals to x*(x+1)/2.

We'll find the number of full groups k that go before n+1-th number in the sequence. k equals to the maximal integer such that k*(k+1)/2 <= n. To find it we'll solve the quadratic equation:

x*(x+1)/2 = n
x^2 + x - 2*n = 0

Let's assume that positive root of this equation is x'. We round it down to the nearest integer k. If x' == k (x' is a whole number) it is the answer. Otherwise, the answer is n - k*(k+1)/2.

Exemplary c++ implementation:

double d = 1 + 8.0 * n;
double x = (-1 + sqrt(d)) / 2;

long long k = floor(x);
long long m = k*(k+1) / 2;
if (m == n) {
    return k;
} else {
    return n - m;
}

The solution has O(1) time complexity.


问:
Change in for loops in java 8
Consider this code :

```<code>public class Test
{
        static final Collection<String> info = new ArrayList<>();

        public static void main(String... args) {
                for (String info : info) {
                        System.out.println(info);
                }
        }
}
</code>```

It compiles fine in java 8, but results in a compile-time error with java 7 :

```<code>Test.java:8: error: for-each not applicable to expression type
                for (String info : info) {
                                   ^
  required: array or java.lang.Iterable
  found:    String
</code>```

Of course I should not write such code. The real class in much bigger, and a rename of the field lead to something like this...

My question is : why is this happening ?
What evolution of the language made this legal in java 8 ?
I checked various java 8 changes lists, but couldn't find anything explaining this behaviour.

Can anyone point me to the change in java 8 that is responsible for this ?

答:
The compiler is interpreting info as String and that's why it isn't Iterable

In the scope of the for loop, it already exist a variable with the same name of your array

Title: Change in for loops in java 8

Body:
Consider this code :

public class Test
{
        static final Collection<String> info = new ArrayList<>();

        public static void main(String... args) {
                for (String info : info) {
                        System.out.println(info);
                }
        }
}

It compiles fine in java 8, but results in a compile-time error with java 7 :

Test.java:8: error: for-each not applicable to expression type
                for (String info : info) {
                                   ^
  required: array or java.lang.Iterable
  found:    String

Of course I should not write such code. The real class in much bigger, and a rename of the field lead to something like this...

My question is : why is this happening ?
What evolution of the language made this legal in java 8 ?
I checked various java 8 changes lists, but couldn't find anything explaining this behaviour.

Can anyone point me to the change in java 8 that is responsible for this ?

ContentLicense: CC BY-SA 4.0