问:
Laravel 5.0 Undefined variable result
I have a form that a user enters and takes the entry and queries the database and returns to a view. I have managed to get one query working but when trying to work on another query it returns an undefined variable error in the view. See below:

Routes

```<code>Route::get('/shopsales', 'shopsalescontroller@index');
</code>```

Controller

```<code>class shopsalescontroller extends Controller
</code>```

{

```<code> public function index()
{
    $storeNum = request('storeNum');

   $result = shopsales::where('StoreNumber','=',$storeNum)
        ->get();

    return view('shopsales',compact('result'));

}
</code>```

}

shopsales view

```<code><section>
  <center><h1><STRONG>Query Data</STRONG></h1></center>
    <ul>
      @foreach ($result as $results)
        <li>Report Name = {{ $results->ReportName}} | Report ID = {{ $results->ReportID}} | Store Number = {{ $results->StoreNumber}} | Store Name = {{ $results->StoreName}} | Week Number = {{ $results->WeekNumber}} |
            Year = {{ $results->Year}} | PerfumeName = {{ $results->PerfumeName}} | Units Sold = {{ $results->UnitsSold}} | Sales = {{ $results->Sales}}
        </li>
        <br>
      @endforeach
    </ul>

</section>
</code>```

I have used the exact code for the query that is working, struggling to understand why this is not.

答:
try this

in App\Route

```<code>Route::resource('/shopsales','ShopSalecontroller');
</code>```

This routes the following actions: index, create, store, show, edit, update and destroy.

add this function to shopsales model

```<code>public function scopeNumber($query, $number){
    if($number != null){
        $query->where('storeNumber','=', "$number");
    }
}
</code>```

in ShopSalesController index:

```<code>public function index(Request $request){
   $result = shopsales::get()->number($request->storeNumber)->all();
   return view('shopsales',compact('result'));
}
</code>```

Remember to have in the index view a form with the field storeNumber

Title: Laravel 5.0 Undefined variable result

Body:
I have a form that a user enters and takes the entry and queries the database and returns to a view. I have managed to get one query working but when trying to work on another query it returns an undefined variable error in the view. See below:

Routes

Route::get('/shopsales', 'shopsalescontroller@index');

Controller

class shopsalescontroller extends Controller

{

 public function index()
{
    $storeNum = request('storeNum');

   $result = shopsales::where('StoreNumber','=',$storeNum)
        ->get();

    return view('shopsales',compact('result'));

}

}

shopsales view

Query Data

      @foreach ($result as $results)

Report Name = {{ $results->ReportName}} | Report ID = {{ $results->ReportID}} | Store Number = {{ $results->StoreNumber}} | Store Name = {{ $results->StoreName}} | Week Number = {{ $results->WeekNumber}} |
            Year = {{ $results->Year}} | PerfumeName = {{ $results->PerfumeName}} | Units Sold = {{ $results->UnitsSold}} | Sales = {{ $results->Sales}}

      @endforeach

I have used the exact code for the query that is working, struggling to understand why this is not.

Body:
try this

in App\Route

Route::resource('/shopsales','ShopSalecontroller');

This routes the following actions: index, create, store, show, edit, update and destroy.

add this function to shopsales model

public function scopeNumber($query, $number){
    if($number != null){
        $query->where('storeNumber','=', "$number");
    }
}

in ShopSalesController index:

public function index(Request $request){
   $result = shopsales::get()->number($request->storeNumber)->all();
   return view('shopsales',compact('result'));
}

Remember to have in the index view a form with the field storeNumber


来源: stackexchange

问:
How to define a field & group by within Select Query in SQL
At present have a column with status types, and a separate column with dates. What I would like to do is create new columns for each status type. Have created column names by using case when statements, but cannot then group by those.

At present, the table kicks out the following:

```<code>Reference |   Status    | Date
    ----- | ----------- | -----
        1 | Approve     | 1/1/2017
        1 | In Progress | 1/2/2017
        2 | Approve     | 1/1/2017
        2 | In Progress | 1/2/2017
        2 | Close       | 1/3/2017
</code>```

Would like to take this and make:

```<code>Reference | Approve  | In Progress | Close
--------- | -------- | ----------- | -----
        1 | 1/1/2017 | 1/2/2017    |
        2 | 1/1/2017 | 1/2/2017    | 1/3/2017
</code>```

Have a lot of other selects, and intention is to export to excel/run automatically, so trying to avoid temp tables.

I don't know that case when is appropriate, but am struggling to find a better solution.

答:
Something like this should work based on the table you've provided (I've also handled null values to get you the output you need):-</p>

```<code>select
    Reference,
    isnull(convert(varchar(10),[Approve],103),'') [Approve],
    isnull(convert(varchar(10),[In Progress],103),'') [In Progress],
    isnull(convert(varchar(10),[Close],103),'') [Close]
from
(
select
    Reference,
    Status,
    Date
from YourTableName
) d
pivot (min([Date]) for Status in ([Approve],[In Progress],[Close])) p
</code>```

ContentLicense: CC BY-SA 3.0

Body:
At present have a column with status types, and a separate column with dates. What I would like to do is create new columns for each status type. Have created column names by using case when statements, but cannot then group by those.

At present, the table kicks out the following:

Reference |   Status    | Date
    ----- | ----------- | -----
        1 | Approve     | 1/1/2017
        1 | In Progress | 1/2/2017
        2 | Approve     | 1/1/2017
        2 | In Progress | 1/2/2017
        2 | Close       | 1/3/2017

Would like to take this and make:

Reference | Approve  | In Progress | Close
--------- | -------- | ----------- | -----
        1 | 1/1/2017 | 1/2/2017    |
        2 | 1/1/2017 | 1/2/2017    | 1/3/2017

Have a lot of other selects, and intention is to export to excel/run automatically, so trying to avoid temp tables.

I don't know that case when is appropriate, but am struggling to find a better solution.

Body:
Something like this should work based on the table you've provided (I've also handled null values to get you the output you need):-

select
    Reference,
    isnull(convert(varchar(10),[Approve],103),'') [Approve],
    isnull(convert(varchar(10),[In Progress],103),'') [In Progress],
    isnull(convert(varchar(10),[Close],103),'') [Close]
from
(
select
    Reference,
    Status,
    Date
from YourTableName
) d
pivot (min([Date]) for Status in ([Approve],[In Progress],[Close])) p


问:
Write code that takes a non-empty list of integers from the user, as well as a width
So, the problem states that I have to do the following:

Write code that takes a non-empty list of integers from the user, as well as a width. Return a new list where the original list has been converted into a two dimensional list with the specified width, padded with zeroes at the end as needed. You may not use any built-in functions/methods besides len() and .append().

I tried to resolve it and I am still hung up on one line, he is what I have right now:

```<code>def chop(l1, w):

    list1 = l1
    width = w
    list2 = []
    size = len(list1)
    i = 0
    j = 0
    k = 0
    a = width - size % width

    while i < a:
        list1.append(0)
        i = i + 1
    i = 0
    size = size + a

    height = size // width
    k = 0
    while i < height:
        while j < width:
            list2[i][j] = list1[k]
            k = k + 1
            j = j + 1
        j = 0
        i = i + 1

    return list1
</code>```

But when I try to run the code, I get an error on the line with this code:  list2[i][j] = list1[k] giving me an index error.

答:
Here's the code (note that it could look a lot nicer - and shorter - as Python has lots of (powerful) features, but due to the imposed constraints, this is the outcome):

```<code>def chop(initial_list, width):
    if width <= 0:
        return None
    ret_list = []
    size = len(initial_list)
    height = size // width
    i = 0
    j = 0
    while i < height:  # Handling the integral (complete/full) rows (if any)
        tmp_list = []
        j = 0
        while j < width:
            tmp_list.append(initial_list[i * width + j])
            j += 1
        ret_list.append(tmp_list)
        i += 1
    remainder = size % width
    tmp_list = []
    if remainder:  # Handling the last(incomplete) row (if any)
        j = i * width
        while j < size:  # Fill the last row with the last elements from initial_list
            tmp_list.append(initial_list[j])
            j += 1
        j = remainder
        while j < width:  # Append 0s till the last row length is equal to width
            tmp_list.append(0)
            j += 1
        ret_list.append(tmp_list)
    elif not height:  # Handle empty list's case
        j = 0
        while j < width:
            tmp_list.append(0)
            j += 1
        ret_list.append(tmp_list)
    return ret_list

if __name__ == "__main__":
    #  Test our function a little bit...
    l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    print(chop(l1, 2))
    print(chop(l1, 3))
    print(chop(l1, 12))
    print(chop(l1, 1))
    print(chop([], 4))
    print(chop([], 0))
</code>```

And the output is:

```<code>[[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0]]
[[1], [2], [3], [4], [5], [6], [7], [8], [9]]
[[0, 0, 0, 0]]
None
</code>```

@EDIT0: Added support for empty lists.

Body:
So, the problem states that I have to do the following:

Write code that takes a non-empty list of integers from the user, as well as a width. Return a new list where the original list has been converted into a two dimensional list with the specified width, padded with zeroes at the end as needed. You may not use any built-in functions/methods besides len() and .append().

I tried to resolve it and I am still hung up on one line, he is what I have right now:

def chop(l1, w):

    list1 = l1
    width = w
    list2 = []
    size = len(list1)
    i = 0
    j = 0
    k = 0
    a = width - size % width

    while i < a:
        list1.append(0)
        i = i + 1
    i = 0
    size = size + a

    height = size // width
    k = 0
    while i < height:
        while j < width:
            list2[i][j] = list1[k]
            k = k + 1
            j = j + 1
        j = 0
        i = i + 1

    return list1

But when I try to run the code, I get an error on the line with this code:  list2[i][j] = list1[k] giving me an index error.

Body:
Here's the code (note that it could look a lot nicer - and shorter - as Python has lots of (powerful) features, but due to the imposed constraints, this is the outcome):

def chop(initial_list, width):
    if width <= 0:
        return None
    ret_list = []
    size = len(initial_list)
    height = size // width
    i = 0
    j = 0
    while i < height:  # Handling the integral (complete/full) rows (if any)
        tmp_list = []
        j = 0
        while j < width:
            tmp_list.append(initial_list[i * width + j])
            j += 1
        ret_list.append(tmp_list)
        i += 1
    remainder = size % width
    tmp_list = []
    if remainder:  # Handling the last(incomplete) row (if any)
        j = i * width
        while j < size:  # Fill the last row with the last elements from initial_list
            tmp_list.append(initial_list[j])
            j += 1
        j = remainder
        while j < width:  # Append 0s till the last row length is equal to width
            tmp_list.append(0)
            j += 1
        ret_list.append(tmp_list)
    elif not height:  # Handle empty list's case
        j = 0
        while j < width:
            tmp_list.append(0)
            j += 1
        ret_list.append(tmp_list)
    return ret_list

if __name__ == "__main__":
    #  Test our function a little bit...
    l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    print(chop(l1, 2))
    print(chop(l1, 3))
    print(chop(l1, 12))
    print(chop(l1, 1))
    print(chop([], 4))
    print(chop([], 0))

And the output is:

[[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0]]
[[1], [2], [3], [4], [5], [6], [7], [8], [9]]
[[0, 0, 0, 0]]
None

@EDIT0: Added support for empty lists.


问:
Drools how to derive smaller readable rules from a big rule
the facts used by my rule are aggregating other object. The problem I want to solve is a chain of minimum and maximums. Find the group of people(these are facts) having the highest average iq and the lowest age and...and and and..various other criteria.

Look at the rule below, if I would have 2-3 more such criteria the LHS would become unreadable.

How can I do better?

rule "Find thet group with the highest average iq and the lowest average age"
when

```<code>$options: PeopleGroup(

        $averageIq : getAverageIg(this),

        $averagAge : getAverageAge(this),

)

not (   PeopleGroup(getAverageIg(this) > $averageIq )

        or PeopleGroup(getAverageIg(this) == $averageIq, getAverageAge(this) < $averagAge  )
</code>```

)

then

// add the PeopletGroup to the result

end.

Thanks

答:
The description of your problem is too vague, but I'll discuss the a couple of options you have anyway.

First, if you are looking for "the best group" you should define a method PeopleGroup.compareTo( PeopleGroup pg ) so that PeopleGroup implements Comparable<PeopleGroup>. A rule finding the best group should be simple. (Of course, you have the option of writing any number of static methods comparing two PeopleGroup objects for any kind of ranking you might dream up.) In any case, the rule will be very simple.

```<code>rule "best group"
when
    $pg1: PeopleGroup()
    not PeopleGroup( this.compareTo( $pg1 ) > 0 )
then
    // $pg1 is best PeopleGroup
end
</code>```

Another approach is to filter facts, either by retracting unqualified facts or by marking them. So, in the first pass, you retract any group that does not have the maximum IQ. Next, you disqualify any remaining group that doesn't have the minimum age. You'll need to order the rules, using agenda-group or salience or additional logic for controlling the order. But the individual rules will be simple.

Body:
the facts used by my rule are aggregating other object. The problem I want to solve is a chain of minimum and maximums. Find the group of people(these are facts) having the highest average iq and the lowest age and...and and and..various other criteria.

Look at the rule below, if I would have 2-3 more such criteria the LHS would become unreadable.

How can I do better?

rule "Find thet group with the highest average iq and the lowest average age"
when

$options: PeopleGroup(

        $averageIq : getAverageIg(this),

        $averagAge : getAverageAge(this),

)

not (   PeopleGroup(getAverageIg(this) > $averageIq )

        or PeopleGroup(getAverageIg(this) == $averageIq, getAverageAge(this) < $averagAge  )

)

then

// add the PeopletGroup to the result

end.

Thanks

Body:
The description of your problem is too vague, but I'll discuss the a couple of options you have anyway.

First, if you are looking for "the best group" you should define a method PeopleGroup.compareTo( PeopleGroup pg ) so that PeopleGroup implements Comparable<PeopleGroup>. A rule finding the best group should be simple. (Of course, you have the option of writing any number of static methods comparing two PeopleGroup objects for any kind of ranking you might dream up.) In any case, the rule will be very simple.

rule "best group"
when
    $pg1: PeopleGroup()
    not PeopleGroup( this.compareTo( $pg1 ) > 0 )
then
    // $pg1 is best PeopleGroup
end

Another approach is to filter facts, either by retracting unqualified facts or by marking them. So, in the first pass, you retract any group that does not have the maximum IQ. Next, you disqualify any remaining group that doesn't have the minimum age. You'll need to order the rules, using agenda-group or salience or additional logic for controlling the order. But the individual rules will be simple.


问:
Wrapping container for containers providing diffrent interfaces
I want to create universal "wrapper" for stl containers, something like:

```<code>template<template <typename, typename...> class Container = std::vector >
class ContainerWrapper{
  add();
  size();
  find();
  resize();
  sort();
  /**/
}
</code>```

+iterators.
I would want member functions to have different implementations, depending on Container provided methods. Is C++ template system enough to create this? Is this even possible, using only standard (no boost, no messing with preprocessor)?

I know how to do it the hard way - write template specialization for each stl container. But I would want it to work with other containers too, and also i'm looking for more universal way to do it.

Also, what is better here? Inheriting from Container or having Container as component?

答:
STL containers are not meant to be inherited. They do not have virtual destructors. It was discussed having the containers as final, but it was not done because it would a breaking change.

So using composition is your best bet.

Body:
I want to create universal "wrapper" for stl containers, something like:

template<template <typename, typename...> class Container = std::vector >
class ContainerWrapper{
  add();
  size();
  find();
  resize();
  sort();
  /**/
}

+iterators.
I would want member functions to have different implementations, depending on Container provided methods. Is C++ template system enough to create this? Is this even possible, using only standard (no boost, no messing with preprocessor)?

I know how to do it the hard way - write template specialization for each stl container. But I would want it to work with other containers too, and also i'm looking for more universal way to do it.

Also, what is better here? Inheriting from Container or having Container as component?


问:
Creating h2o dataframe from pandas and unicode error
How can I convert pandas object to h2o dataframe safely?

```<code>import h2o
import pandas as pd

df = pd.DataFrame({'col1': [1,1,2], 'col2': ['César Chávez Day', 'César Chávez Day', 'César Chávez Day']})
hf = h2o.H2OFrame(df)  #gives error
</code>```

UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in
  position 4: ordinal not in range(128)

Environment: Python 3.5, h2o 3.10.4.2

答:
I agree that this is not an H2O-specific issue.  This works for me (same H2O and Python version):

```<code>import h2o
import pandas as pd

df = pd.DataFrame({'col1': [1,1,2], 'col2': ['César Chávez Day', 'César Chávez Day', 'César Chávez Day']})
hf = h2o.H2OFrame(df)

## -- End pasted text --
Parse progress: |█████████████████████████████████████████████████████████| 100%

In [4]: hf
Out[4]:   col1  col2
------  ----------------
     1  César Chávez Day
     1  César Chávez Day
     2  César Chávez Day

[3 rows x 2 columns]

In [5]: type('César Chávez Day')
Out[5]: str
</code>```

My specs (you may need to change your default encoding):

```<code>In [6]: import sys

In [7]: sys.getdefaultencoding()
Out[7]: 'utf-8'
</code>```

This thread may help: How do I check if a string is unicode or ascii?

Body:
How can I convert pandas object to h2o dataframe safely?

import h2o
import pandas as pd

df = pd.DataFrame({'col1': [1,1,2], 'col2': ['César Chávez Day', 'César Chávez Day', 'César Chávez Day']})
hf = h2o.H2OFrame(df)  #gives error

UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in
  position 4: ordinal not in range(128)

Environment: Python 3.5, h2o 3.10.4.2

Body:
I agree that this is not an H2O-specific issue.  This works for me (same H2O and Python version):

import h2o
import pandas as pd

df = pd.DataFrame({'col1': [1,1,2], 'col2': ['César Chávez Day', 'César Chávez Day', 'César Chávez Day']})
hf = h2o.H2OFrame(df)

## -- End pasted text --
Parse progress: |█████████████████████████████████████████████████████████| 100%

In [4]: hf
Out[4]:   col1  col2
------  ----------------
     1  César Chávez Day
     1  César Chávez Day
     2  César Chávez Day

[3 rows x 2 columns]

In [5]: type('César Chávez Day')
Out[5]: str

My specs (you may need to change your default encoding):

In [6]: import sys

In [7]: sys.getdefaultencoding()
Out[7]: 'utf-8'

This thread may help: How do I check if a string is unicode or ascii?


问:
Canada Post 'lookup postal code' screen scrape code
I don't want to reinvent the wheel.

Is anyone aware of php/curl code to populate address data in Canada Post's 'Find a Postal Code' page http://www.canadapost.ca/cpotools/apps/fpc/personal/findByAdvanced?execution=e1s1
and return the valid postal code.

I thought it would make a great address verification routine.

答:
Check out http://www.geocoder.ca too. They have a postal code lookup web service. They also have free postalcode/city data here:

http://geocoder.ca/?freedata=1

ContentLicense: CC BY-SA 2.5


问:
How do I get all the fields and value from a PDF file using iText?
Using the code below, I'm trying to get all the fields and their values, but it's only returning the field values.  What do I need to do to get both?</p>

```<code>   package PrintFiled;
    /*

        Usage: java TestDocument <pdf file>

    */

    import java.io.File;
    import java.io.FileOutputStream;
    import java.util.Collection;

    import java.util.HashMap;
    import java.util.List;
    import java.util.Iterator;
    import java.util.Map;

    import org.pdfbox.pdmodel.interactive.form.PDField;

    import com.lowagie.text.pdf.AcroFields;
    import com.lowagie.text.pdf.MultiColumnText;
    import com.lowagie.text.pdf.PdfDictionary;
    import com.lowagie.text.pdf.RadioCheckField;
    import com.lowagie.text.pdf.PdfSignature;

    import com.lowagie.text.pdf.PdfReader;
    import com.lowagie.text.pdf.PdfStamper;
    import com.lowagie.text.pdf.AcroFields;
    import com.lowagie.text.pdf.AcroFields.*;

    public class TestDocument
    {
        public static void main(String[] args) throws Exception
        {

            // get the destination

            String location = "test/";

            if (location != null && !location.endsWith(File.separator))

            {

            location = location + File.separator;

            }

            PdfReader reader = new PdfReader(location + "acc.pdf");

            String name = "Output.pdf";

            PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(location + name));

            AcroFields form = stamp.getAcroFields();

            String last = "subform[0].LastName[0]";

            String first = "subform[0].FirstName[0]";

            String ProcessDate="subform[0].ProcessDate[0]";

            form.setField(last, "HRISTOV");

            form.setField(first, "NEDKO");
            form.setField(ProcessDate, "Process");

            System.out.println("last Name  :"+last.toString());

            Map val =new HashMap();
            //val=form.getFieldCache();
            //System.out.println("Value   :"+val);
             Iterator it = val.entrySet().iterator();
             while (it.hasNext())
                {
                    Map.Entry pairs = (Map.Entry)it.next();
                    System.out.println("Key   :"+pairs.getKey() + " = "+"Value  :" + pairs.getValue());
                }

                    Collection fieldlist = form.getFields().keySet();
    //              for (Iterator i = val.iterator(); i.hasNext(); )
                         for (Iterator i = fieldlist.iterator(); i.hasNext(); )
                                {

                                    System.out.println(i.next().toString());

                                System.out.println("Value    :"+val);
                                }
            /*List fields = form.getFields();
            Iterator fieldsIter = fields.iterator();

            System.out.println(new Integer(fields.size()).toString()
                    + " top-level fields were found on the form");

         while (fieldsIter.hasNext()) {
                PDField field = (PDField) fieldsIter.next();
               // processField(field, "|--", field.getPartialName());
                System.out.println("Field  :"+fieldsIter);
           }
             */
            System.out.println("First Name:"+form.getField(first));
            System.out.println("LastName  :"+form.getField(last));
            System.out.println("ProcessDate :"+form.getField(ProcessDate));

            // close pdf stamper
            stamp.setFormFlattening(true);
            stamp.close();
            reader.close();
        }
    }
</code>```

答:
Here's the answer updated for iText version 7.0.2:</p>

```<code>PdfReader reader = new PdfReader( pdfPath );
PdfDocument document = new PdfDocument(reader);
PdfAcroForm acroForm = PdfAcroForm.getAcroForm(document, false);
Map<String,PdfFormField> fields = acroForm.getFormFields();
for (String fldName : fields.keySet()) {
  System.out.println( fldName + ": " + fields.get( fldName ).getValueAsString() );
}
document.close();
reader.close();
</code>```

Body:
Using the code below, I'm trying to get all the fields and their values, but it's only returning the field values.  What do I need to do to get both?

   package PrintFiled;
    /*

        Usage: java TestDocument <pdf file>

    */

    import java.io.File;
    import java.io.FileOutputStream;
    import java.util.Collection;

    import java.util.HashMap;
    import java.util.List;
    import java.util.Iterator;
    import java.util.Map;

    import org.pdfbox.pdmodel.interactive.form.PDField;

    import com.lowagie.text.pdf.AcroFields;
    import com.lowagie.text.pdf.MultiColumnText;
    import com.lowagie.text.pdf.PdfDictionary;
    import com.lowagie.text.pdf.RadioCheckField;
    import com.lowagie.text.pdf.PdfSignature;

    import com.lowagie.text.pdf.PdfReader;
    import com.lowagie.text.pdf.PdfStamper;
    import com.lowagie.text.pdf.AcroFields;
    import com.lowagie.text.pdf.AcroFields.*;

    public class TestDocument
    {
        public static void main(String[] args) throws Exception
        {

            // get the destination

            String location = "test/";

            if (location != null && !location.endsWith(File.separator))

            {

            location = location + File.separator;

            }

            PdfReader reader = new PdfReader(location + "acc.pdf");

            String name = "Output.pdf";

            PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(location + name));

            AcroFields form = stamp.getAcroFields();

            String last = "subform[0].LastName[0]";

            String first = "subform[0].FirstName[0]";

            String ProcessDate="subform[0].ProcessDate[0]";

            form.setField(last, "HRISTOV");

            form.setField(first, "NEDKO");
            form.setField(ProcessDate, "Process");

            System.out.println("last Name  :"+last.toString());

            Map val =new HashMap();
            //val=form.getFieldCache();
            //System.out.println("Value   :"+val);
             Iterator it = val.entrySet().iterator();
             while (it.hasNext())
                {
                    Map.Entry pairs = (Map.Entry)it.next();
                    System.out.println("Key   :"+pairs.getKey() + " = "+"Value  :" + pairs.getValue());
                }

                    Collection fieldlist = form.getFields().keySet();
    //              for (Iterator i = val.iterator(); i.hasNext(); )
                         for (Iterator i = fieldlist.iterator(); i.hasNext(); )
                                {

                                    System.out.println(i.next().toString());

                                System.out.println("Value    :"+val);
                                }
            /*List fields = form.getFields();
            Iterator fieldsIter = fields.iterator();

            System.out.println(new Integer(fields.size()).toString()
                    + " top-level fields were found on the form");

         while (fieldsIter.hasNext()) {
                PDField field = (PDField) fieldsIter.next();
               // processField(field, "|--", field.getPartialName());
                System.out.println("Field  :"+fieldsIter);
           }
             */
            System.out.println("First Name:"+form.getField(first));
            System.out.println("LastName  :"+form.getField(last));
            System.out.println("ProcessDate :"+form.getField(ProcessDate));

            // close pdf stamper
            stamp.setFormFlattening(true);
            stamp.close();
            reader.close();
        }
    }

Body:
Here's the answer updated for iText version 7.0.2:

PdfReader reader = new PdfReader( pdfPath );
PdfDocument document = new PdfDocument(reader);
PdfAcroForm acroForm = PdfAcroForm.getAcroForm(document, false);
Map<String,PdfFormField> fields = acroForm.getFormFields();
for (String fldName : fields.keySet()) {
  System.out.println( fldName + ": " + fields.get( fldName ).getValueAsString() );
}
document.close();
reader.close();


问:
Unable to connect to mysql on digitalocean using workbench over ssh
I have got my droplet set with the laravel app and database. Created my db while on putty ssh. Now when I am trying to connect to my mysql database as in image, i am getting error.

Error: Authentication error, unhandled exception caught in tunnel manager, plese refer to logs for details.

Note that my credentials are right, as that what I use to connect through putty. Any help on how can I see view my database?

答:
Got this solved like this.

Turns out this is an ssh level issue. The digital ocean server doesn't have the support for the Kex algorithm as mentioned in the error the following can be done to fix this.

Following steps needs to be done on the digital ocean server itself

1- Add the following lines to this file on the digital ocean server

$ sudo vim /etc/ssh/sshd_config

```<code>Ciphers aes256-gcm@openssh.com,aes128-gcm@openssh.com,aes256-ctr,aes128-ctr
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-512,hmac-sha2-256,hmac-ripemd160,hmac-sha1
KexAlgorithms diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha1,diffie-hellman-group-exchange-sha1
</code>```

2- Restart the ssh service on the server

$ sudo service ssh restart

Now try connecting with mysql workbench again you should see that error gone. Check the logs for more errors if not successful but this did the trick for me.

Body:
Got this solved like this.

Turns out this is an ssh level issue. The digital ocean server doesn't have the support for the Kex algorithm as mentioned in the error the following can be done to fix this.

Following steps needs to be done on the digital ocean server itself

1- Add the following lines to this file on the digital ocean server

$ sudo vim /etc/ssh/sshd_config

Ciphers aes256-gcm@openssh.com,aes128-gcm@openssh.com,aes256-ctr,aes128-ctr
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-512,hmac-sha2-256,hmac-ripemd160,hmac-sha1
KexAlgorithms diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha1,diffie-hellman-group-exchange-sha1

2- Restart the ssh service on the server

$ sudo service ssh restart

Now try connecting with mysql workbench again you should see that error gone. Check the logs for more errors if not successful but this did the trick for me.


问:
PreferenceFragment crashing, Null object Reference
I have a simple ActionBarActivity which holds a PreferenceFragment as follows:

```<code>import android.app.Activity;
import android.os.Bundle;
import android.preference.PreferenceFragment;

public class SettingsActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_settings);
    // Display the fragment as the main content.
    getFragmentManager().beginTransaction()
            .replace(R.id.fra_settings_container, new SettingsFragment()).commit();
}
public static class SettingsFragment extends PreferenceFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Load the preferences from an XML resource
        addPreferencesFromResource(R.xml.preferences);
    }
}
}
</code>```

Here is my preferences.xml:

```<code><PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

<ListPreference
    android:defaultValue="15"
    android:dialogTitle="@string/settings_heading_alarm_interval"
    android:entries="@array/alarm_interval_entries"
    android:entryValues="@array/alarm_interval_values"
    android:key="alarm_interval"
    android:title="@string/settings_heading_alarm_interval" />
<ListPreference
    android:defaultValue="1"
    android:dialogTitle="@string/settings_heading_alarm_type"
    android:entries="@array/alarm_type_entries"
    android:entryValues="@array/alarm_type_values"
    android:key="alarm_type"
    android:title="@string/settings_heading_alarm_type"
/>

<CheckBoxPreference
    android:key="alarm_vibrate_only"
    android:title="@string/settings_heading_silent" />

<RingtonePreference
    android:dependency="alarm_vibrate_only"
    android:key="alarm_tone"
    android:title="@string/settings_heading_alarm_tone"
    android:showDefault="true"
    android:showSilent="true"/>

</PreferenceScreen>
</code>```

When I navigate to SettingsActivity I get the following error log:

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Object.equals(java.lang.Object)' on a null object reference
        at android.preference.ListPreference.findIndexOfValue(ListPreference.java:231)
        at android.preference.ListPreference.getValueIndex(ListPreference.java:240)
        at android.preference.ListPreference.getEntry(ListPreference.java:218)
        at android.preference.ListPreference.getSummary(ListPreference.java:164)
        at android.preference.Preference.onBindView(Preference.java:550)
        at android.preference.Preference.getView(Preference.java:489)
        at android.preference.PreferenceGroupAdapter.getView(PreferenceGroupAdapter.java:246)
        at android.widget.AbsListView.obtainView(AbsListView.java:2344)
        at android.widget.ListView.makeAndAddView(ListView.java:1864)
        at android.widget.ListView.fillDown(ListView.java:698)
        at android.widget.ListView.fillFromTop(ListView.java:759)
        at android.widget.ListView.layoutChildren(ListView.java:1659)
        at android.widget.AbsListView.onLayout(AbsListView.java:2148)
        at android.view.View.layout(View.java:15596)
        at android.view.ViewGroup.layout(ViewGroup.java:4966)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1466)
        at android.view.View.layout(View.java:15596)
        at android.view.ViewGroup.layout(ViewGroup.java:4966)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
        at android.view.View.layout(View.java:15596)
        at android.view.ViewGroup.layout(ViewGroup.java:4966)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
        at android.view.View.layout(View.java:15596)
        at android.view.ViewGroup.layout(ViewGroup.java:4966)
        at com.android.internal.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:494)
        at android.view.View.layout(View.java:15596)
        at android.view.ViewGroup.layout(ViewGroup.java:4966)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
        at android.view.View.layout(View.java:15596)
        at android.view.ViewGroup.layout(ViewGroup.java:4966)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2072)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1829)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1054)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5779)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
        at android.view.Choreographer.doCallbacks(Choreographer.java:580)
        at android.view.Choreographer.doFrame(Choreographer.java:550)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
</code>```

From my understanding, I'm implementing a PreferenceFragment exactly as per the Android guide, and I can't find anything in the error log that tells me where to look for a problem (most likely because I'm still a beginner). Since I've seen just about every Question remotely related to what I'm dealing with, it may be worth noting that I'm running Lollipop, and I'm using Theme.Appcompat.Light. The rest of my App works well, so I don't understand how the theme could be the problem.

Thanks, and let me know if I can provide more info.

Edit:

Here are the are the values taken from my string_arrays.xml file:

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>

<string-array name="alarm_type_entries">
    <item name="alarm_continuous">Continuous</item>
    <item name="alarm_single">Sound Once</item>
    <item name="alarm_minute">Sound Each Minute</item>
</string-array>

<string-array name="alarm_type_values">

    <item name="continuous">1</item>
    <item name="single">2</item>
    <item name="minute">3</item>

</string-array>

<string-array name="alarm_interval_entries">

    <item name="interval_fifteen">15 Minutes</item>
    <item name="interval_thirty">30 Minutes</item>
    <item name="interval_forty_five">45 Minutes</item>
    <item name="interval_one_hour">1 Hour</item>
    <item name="interval_two_hours">2 Hours</item>
    <item name="interval_three_hours">3 Hours</item>

</string-array>

<integer-array name="alarm_interval_values">

    <item name="fifteen">15</item>
    <item name="thirty">30</item>
    <item name="forty_five">45</item>
    <item name="one_hour">60</item>
    <item name="two_hours">120</item>
    <item name="three_hours">180</item>

</integer-array>
</resources>
</code>```

答:
Change all items from

```<code><integer-array ...
</code>```

to

```<code><string-array ...
</code>```

Work for me.

Body:
I have a simple ActionBarActivity which holds a PreferenceFragment as follows:

import android.app.Activity;
import android.os.Bundle;
import android.preference.PreferenceFragment;

public class SettingsActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_settings);
    // Display the fragment as the main content.
    getFragmentManager().beginTransaction()
            .replace(R.id.fra_settings_container, new SettingsFragment()).commit();
}
public static class SettingsFragment extends PreferenceFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Load the preferences from an XML resource
        addPreferencesFromResource(R.xml.preferences);
    }
}
}

Here is my preferences.xml:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

<ListPreference
    android:defaultValue="15"
    android:dialogTitle="@string/settings_heading_alarm_interval"
    android:entries="@array/alarm_interval_entries"
    android:entryValues="@array/alarm_interval_values"
    android:key="alarm_interval"
    android:title="@string/settings_heading_alarm_interval" />
<ListPreference
    android:defaultValue="1"
    android:dialogTitle="@string/settings_heading_alarm_type"
    android:entries="@array/alarm_type_entries"
    android:entryValues="@array/alarm_type_values"
    android:key="alarm_type"
    android:title="@string/settings_heading_alarm_type"
/>

<CheckBoxPreference
    android:key="alarm_vibrate_only"
    android:title="@string/settings_heading_silent" />

<RingtonePreference
    android:dependency="alarm_vibrate_only"
    android:key="alarm_tone"
    android:title="@string/settings_heading_alarm_tone"
    android:showDefault="true"
    android:showSilent="true"/>

</PreferenceScreen>

When I navigate to SettingsActivity I get the following error log:

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Object.equals(java.lang.Object)' on a null object reference
        at android.preference.ListPreference.findIndexOfValue(ListPreference.java:231)
        at android.preference.ListPreference.getValueIndex(ListPreference.java:240)
        at android.preference.ListPreference.getEntry(ListPreference.java:218)
        at android.preference.ListPreference.getSummary(ListPreference.java:164)
        at android.preference.Preference.onBindView(Preference.java:550)
        at android.preference.Preference.getView(Preference.java:489)
        at android.preference.PreferenceGroupAdapter.getView(PreferenceGroupAdapter.java:246)
        at android.widget.AbsListView.obtainView(AbsListView.java:2344)
        at android.widget.ListView.makeAndAddView(ListView.java:1864)
        at android.widget.ListView.fillDown(ListView.java:698)
        at android.widget.ListView.fillFromTop(ListView.java:759)
        at android.widget.ListView.layoutChildren(ListView.java:1659)
        at android.widget.AbsListView.onLayout(AbsListView.java:2148)
        at android.view.View.layout(View.java:15596)
        at android.view.ViewGroup.layout(ViewGroup.java:4966)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1466)
        at android.view.View.layout(View.java:15596)
        at android.view.ViewGroup.layout(ViewGroup.java:4966)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
        at android.view.View.layout(View.java:15596)
        at android.view.ViewGroup.layout(ViewGroup.java:4966)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
        at android.view.View.layout(View.java:15596)
        at android.view.ViewGroup.layout(ViewGroup.java:4966)
        at com.android.internal.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:494)
        at android.view.View.layout(View.java:15596)
        at android.view.ViewGroup.layout(ViewGroup.java:4966)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
        at android.view.View.layout(View.java:15596)
        at android.view.ViewGroup.layout(ViewGroup.java:4966)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2072)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1829)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1054)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5779)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
        at android.view.Choreographer.doCallbacks(Choreographer.java:580)
        at android.view.Choreographer.doFrame(Choreographer.java:550)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

From my understanding, I'm implementing a PreferenceFragment exactly as per the Android guide, and I can't find anything in the error log that tells me where to look for a problem (most likely because I'm still a beginner). Since I've seen just about every Question remotely related to what I'm dealing with, it may be worth noting that I'm running Lollipop, and I'm using Theme.Appcompat.Light. The rest of my App works well, so I don't understand how the theme could be the problem.

Thanks, and let me know if I can provide more info.

Edit:

Here are the are the values taken from my string_arrays.xml file:

<?xml version="1.0" encoding="utf-8"?>
<resources>

<string-array name="alarm_type_entries">
    <item name="alarm_continuous">Continuous</item>
    <item name="alarm_single">Sound Once</item>
    <item name="alarm_minute">Sound Each Minute</item>
</string-array>

<string-array name="alarm_type_values">

    <item name="continuous">1</item>
    <item name="single">2</item>
    <item name="minute">3</item>

</string-array>

<string-array name="alarm_interval_entries">

    <item name="interval_fifteen">15 Minutes</item>
    <item name="interval_thirty">30 Minutes</item>
    <item name="interval_forty_five">45 Minutes</item>
    <item name="interval_one_hour">1 Hour</item>
    <item name="interval_two_hours">2 Hours</item>
    <item name="interval_three_hours">3 Hours</item>

</string-array>

<integer-array name="alarm_interval_values">

    <item name="fifteen">15</item>
    <item name="thirty">30</item>
    <item name="forty_five">45</item>
    <item name="one_hour">60</item>
    <item name="two_hours">120</item>
    <item name="three_hours">180</item>

</integer-array>
</resources>

Body:
Change all items from

<integer-array ...

to

<string-array ...

Work for me.


问:
End Keyframe Animation Using CSS3
I've created a simple bar animation using keyframes in CSS and applying it to an id tag

#progress-skill {
    animation: color-bar 2s, animate-bar 2s;
    animation-fill-mode: forwards;
    position: relative;
    border-radius: 3px;
    width: 400px;
}

@keyframes color-bar {
   5% { background-color: red;}
   25% { background-color: orange;}
   50% { background-color: yellow;}
   75% { background-color: green;}
   100% { background-color: blue;}
}

@keyframes animate-bar {
   from {width: 0px; }
   to {width: 200px; }
} ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="progress">
   <div class="progress-title"><span>SKILL NAME</span></div>
   <div class="progress-bar" id="progress-skill"><span>50%</span></div>
</div></code>```

The animation works fine, with the exception that the color will always end up being the 100% background-color no matter what the percentage is. Is there any way to force the animation to stop at certain percentages? Basically what I'm looking for here is an animation background-color triggered by the width of the bar. If the bar is 50% long then it should be the 50% background-color and stop at that point. The same should hold true for 25% or 75%.

I'm not looking for a javascript solution, but I'm willing to compromise if that's the only method possible.

答:
javascript would make it much easier.
but I started playing with the CSS, and kinda made some progress.
gotta go home now, so i can't finish it.
https://jsfiddle.net/L9bznjLb/ </p>

```<code>@keyframes color-bar {
    from {width: 0px; }
    to {width: 20px; }
</code>```

Title: End Keyframe Animation Using CSS3

Body:
I've created a simple bar animation using keyframes in CSS and applying it to an id tag

#progress-skill {
    animation: color-bar 2s, animate-bar 2s;
    animation-fill-mode: forwards;
    position: relative;
    border-radius: 3px;
    width: 400px;
}

@keyframes color-bar {
   5% { background-color: red;}
   25% { background-color: orange;}
   50% { background-color: yellow;}
   75% { background-color: green;}
   100% { background-color: blue;}
}

@keyframes animate-bar {
   from {width: 0px; }
   to {width: 200px; }
}

SKILL NAME

50%

The animation works fine, with the exception that the color will always end up being the 100% background-color no matter what the percentage is. Is there any way to force the animation to stop at certain percentages? Basically what I'm looking for here is an animation background-color triggered by the width of the bar. If the bar is 50% long then it should be the 50% background-color and stop at that point. The same should hold true for 25% or 75%.

I'm not looking for a javascript solution, but I'm willing to compromise if that's the only method possible.

Body:
javascript would make it much easier.
but I started playing with the CSS, and kinda made some progress.
gotta go home now, so i can't finish it.
https://jsfiddle.net/L9bznjLb/

@keyframes color-bar {
    from {width: 0px; }
    to {width: 20px; }


问:
Java regex - alphanumeric, at most one hyphen, period or underscore, seven characters long
I'm new to the regex tool in Java, and despite their great potential I'm having a hard time accomplishing this task. I want to write a regex to validate an input string which respects the following syntax:

any combination of lowercase letters and digits

only one underscore, one dash or one period (no other special characters)

minimum length of 5

I came up with the following solution:

([/./-_]{0,1}[a-z0-9]){5,}

but in some cases it still doesn't work, for example it does not match a string where one of the special characters allowed is in the middle (such as he-llo). Where did I go wrong? Is there any other pattern better than this for my purpose?

答:
How about this one? You use look ahead to verify there are at least 5 characters.</p>

```<code>^(?=.{5})[a-z0-9]*([-_.][a-z0-9]*)?$
</code>```

Body:
How about this one? You use look ahead to verify there are at least 5 characters.

^(?=.{5})[a-z0-9]*([-_.][a-z0-9]*)?$


问:
RxJS: Observable.create() vs. Observable.from()
What's the difference between these two?

```<code>return Observable.create(function(observer) {
    if (array)
        observer.next([]);
    else
        observer.next(null);
    observer.complete();
});
</code>```

and

```<code>return Observable.from( array ? [] : null );
</code>```

I thought it could be the same but didn't work the same.

答:
When you are returning an array, the difference is that 'create/next' will emit the whole array at once but 'from' will emit each item as many times as its length, so to subscriber,

Observable.create(observer => observer.next(myArray)) will fire onNext event once to return myArray whereas Observable.from(myArray) will emit many onNext events to return one item each time.

Body:
What's the difference between these two?

return Observable.create(function(observer) {
    if (array)
        observer.next([]);
    else
        observer.next(null);
    observer.complete();
});

and

return Observable.from( array ? [] : null );

I thought it could be the same but didn't work the same.

ContentLicense: CC BY-SA 4.0


问:
Section information from a JSON Object in a section
I find this quite hard to explain as you can see in the title but let's say this is how my object looks like,

```<code>{
   "success":true,
   "objects":[
      {
         "name":"Stick",
         "value":"wood",
         "size":"large"
      }...
    ]
}
</code>```

Now I'm trying to get all the data where the objects name is Stick, so basically if it's "name" is stick it should return, name, value and size.

答:
Here is what I would do given the constraints you've laid out.

yourObject = {
   "success":true,
   "objects":[
      {
         "name":"Stick",
         "value":"wood",
         "size":"large"
      },
      {
         "name":"another",
         "value":"object",
         "size":"kindaBig"
      },
      {
         "name":"Rock",
         "value":"mineral",
         "size":"huge"
      }
    ]
};

arr = yourObject.objects.filter((innerObject) => innerObject.name === "Stick");

console.log(arr);```

Body:
I find this quite hard to explain as you can see in the title but let's say this is how my object looks like,

{
   "success":true,
   "objects":[
      {
         "name":"Stick",
         "value":"wood",
         "size":"large"
      }...
    ]
}

Now I'm trying to get all the data where the objects name is Stick, so basically if it's "name" is stick it should return, name, value and size.


问:
Manufacturing an array - why is it different?
consider I declare two variables like this (done within REPL, with node v7.7.2), which I expect to be arrays:

```<code>var x = Array(4)
var y = Array.from({length: 4})
</code>```

then the following should work identically, but it doesn't:

```<code>x.map(Math.random)
[ , , ,  ]
y.map(Math.random)
[ 0.46597917021676816,
  0.3348459056304458,
  0.2913995519428412,
  0.8683430009997699 ]
</code>```

in looking, it seems x and y are both identical:

```<code>> typeof x
'object'
> typeof y
'object'
> Array.isArray(x)
true
> Array.isArray(y)
true
> x.length
4
> y.length
4
> typeof x[0]
'undefined'
> typeof y[0]
'undefined'
</code>```

so why the difference?

答:
Actually, it should not have the same results fot both cases. See the manual here about Array:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

If the only argument passed to the Array constructor is an integer
  between 0 and 232-1 (inclusive), this returns a new JavaScript array
  with its length property set to that number (Note: this implies an
  array of arrayLength empty slots, not slots with actual undefined
  values). If the argument is any other number, a RangeError exception
  is thrown.

And here about the Array.from() method

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from

Check the following example on the page linked above:

```<code>// Generate a sequence of numbers
// Since the array is initialized with `undefined` on each position,
// the value of `v` below will be `undefined`
Array.from({length: 5}, (v, i) => i);
// [0, 1, 2, 3, 4]
</code>```

Body:
consider I declare two variables like this (done within REPL, with node v7.7.2), which I expect to be arrays:

var x = Array(4)
var y = Array.from({length: 4})

then the following should work identically, but it doesn't:

x.map(Math.random)
[ , , ,  ]
y.map(Math.random)
[ 0.46597917021676816,
  0.3348459056304458,
  0.2913995519428412,
  0.8683430009997699 ]

in looking, it seems x and y are both identical:

> typeof x
'object'
> typeof y
'object'
> Array.isArray(x)
true
> Array.isArray(y)
true
> x.length
4
> y.length
4
> typeof x[0]
'undefined'
> typeof y[0]
'undefined'

so why the difference?

Body:
Actually, it should not have the same results fot both cases. See the manual here about Array:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

If the only argument passed to the Array constructor is an integer
  between 0 and 232-1 (inclusive), this returns a new JavaScript array
  with its length property set to that number (Note: this implies an
  array of arrayLength empty slots, not slots with actual undefined
  values). If the argument is any other number, a RangeError exception
  is thrown.

And here about the Array.from() method

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from

Check the following example on the page linked above:

// Generate a sequence of numbers
// Since the array is initialized with `undefined` on each position,
// the value of `v` below will be `undefined`
Array.from({length: 5}, (v, i) => i);
// [0, 1, 2, 3, 4]


问:
Media Query Struggles
So I'm working on making my site responsive and am having issues past the 1700px breakpoint.

My Problem

Here's my html:

```<code><div class="container-1">
<div class="header">
  <h2>OneDrive/ODB</h2><br><a class="one" href="#Anchor">Report a SharePoint bug here</a>
 </div>
 <div class="table-col-1">
  <div class="border-1">
 <div class="table-head-1">
   <h1>Issues with OneDrive/ODB on the web?</h1>
  </div>
<div class="text-container">
 <p class="table-text">Post and vote on feature suggestions & improvements on UserVoice:</p>
    <br><a href="#" class="button">ODC/ODB web</a>
    </div>
</div>
</div>
</code>```

My CSS for previous breakpoint:

```<code>.table-col-1{
padding: 1.5em;
display: inline-block;
width: 20%;
}

.table-head-1{
padding: 1.5em;
background-color: #515251;
display: inline-block;
border-bottom: 2px solid #000000;
}

.table-text{
font-size: 15px;
line-height: 18px;
padding-bottom: 1.5em;
}

.text-container{
padding-top: 1.5em;
padding-bottom: 3em;
}

.border-1{
border: 2px solid #000000;
}
</code>```

My CSS for the breakpoint that's not working:

```<code>@media screen and (min-width: 1700px) and (max-width: 4000px){
.table-head-1{
padding: 1.3em;
background-color: #515251;
display: inline-block;
border-bottom: 2px solid #000000;
}
}
</code>```

If I try and add a width, let's say 100%, to that or even to .table-col-1 I get this issue.

Please help. Thanks!

答: Add box-sizing: border-box to that rule - this will include the padding in the 100% width which is otherwise added, summing up to 100% PLUS the given padding.

Title: Media Query Struggles

Body:
So I'm working on making my site responsive and am having issues past the 1700px breakpoint.

My Problem

Here's my html:

OneDrive/ODB

Report a SharePoint bug here

Issues with OneDrive/ODB on the web?

Post and vote on feature suggestions & improvements on UserVoice:

ODC/ODB web

My CSS for previous breakpoint:

.table-col-1{
padding: 1.5em;
display: inline-block;
width: 20%;
}

.table-head-1{
padding: 1.5em;
background-color: #515251;
display: inline-block;
border-bottom: 2px solid #000000;
}

.table-text{
font-size: 15px;
line-height: 18px;
padding-bottom: 1.5em;
}

.text-container{
padding-top: 1.5em;
padding-bottom: 3em;
}

.border-1{
border: 2px solid #000000;
}

My CSS for the breakpoint that's not working:

@media screen and (min-width: 1700px) and (max-width: 4000px){
.table-head-1{
padding: 1.3em;
background-color: #515251;
display: inline-block;
border-bottom: 2px solid #000000;
}
}

If I try and add a width, let's say 100%, to that or even to .table-col-1 I get this issue.

Please help. Thanks!


问:
Removing spacing between input fields
There is some small spacing between the input fields that I have. How can I remove this? Additionaly the confirm button seems to have a different vertical position than the other elements, why is this? Screenshot below:

.stockWrapper {
    position: absolute;
    display: block;
    top: 10px;
    margin: 0 auto;
    width: 250px;
    left: calc(50% - 75px);
    padding: 0px;
}

.stock {
    box-sizing: border-box;
    width: 75px;
    font-size: 2em;
    margin: 0px;
    width: 100px;
    height: 50px;
}

.confirmBtn, .clearBtn {
    box-sizing: border-box;
    color: white;
    font-weight: bold;
    border: 1px solid black;
    font-size: 2em;
    margin: 0px;
    width: 50px;
    height: 50px;
    padding: 0px;
}

.clearBtn {
    background-color: red;
}

.confirmBtn {
    background-color: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="stockWrapper">
    <input type="button" class="clearBtn" value="X">
    <input type="number" class="stock">
    <input type="button" class="confirmBtn" value="✓">
</div></code>```

答:
The spacing between the inputs is because of the new lines

To align the buttons vertically add line-height to .confirmBtn and .clearBtn

For the tick sign use the appropriate HTML code ✓

Example:

.stockWrapper {
    position: absolute;
    display: block;
    bottom: 10px;
    margin: 0 auto;
    width: 250px;
    left: calc(50% - 75px);
    padding: 0px;
}

.stock {
    box-sizing: border-box;
    width: 75px;
    font-size: 2em;
    margin: 0px;
    width: 100px;
    height: 50px;
}

.confirmBtn, .clearBtn {
    box-sizing: border-box;
    color: white;
    font-weight: bold;
    border: 1px solid black;
    font-size: 2em;
    margin: 0px;
    width: 50px;
    height: 50px;
    padding: 0px;
  line-height:48px;
}

.clearBtn {
    background-color: red;
}

.confirmBtn {
    background-color: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="stockWrapper">
    <input type="button" class="clearBtn" value="X"><input type="number" class="stock"><input type="button" class="confirmBtn" value="✔">
</div></code>```

Title: Removing spacing between input fields

Body:
There is some small spacing between the input fields that I have. How can I remove this? Additionaly the confirm button seems to have a different vertical position than the other elements, why is this? Screenshot below:

.stockWrapper {
    position: absolute;
    display: block;
    top: 10px;
    margin: 0 auto;
    width: 250px;
    left: calc(50% - 75px);
    padding: 0px;
}

.stock {
    box-sizing: border-box;
    width: 75px;
    font-size: 2em;
    margin: 0px;
    width: 100px;
    height: 50px;
}

.confirmBtn, .clearBtn {
    box-sizing: border-box;
    color: white;
    font-weight: bold;
    border: 1px solid black;
    font-size: 2em;
    margin: 0px;
    width: 50px;
    height: 50px;
    padding: 0px;
}

.clearBtn {
    background-color: red;
}

.confirmBtn {
    background-color: green;
}

    <input type="button" class="clearBtn" value="X">
    <input type="number" class="stock">
    <input type="button" class="confirmBtn" value="✓">

Body:
The spacing between the inputs is because of the new lines

To align the buttons vertically add line-height to .confirmBtn and .clearBtn

For the tick sign use the appropriate HTML code &#10003;

Example:

.stockWrapper {
    position: absolute;
    display: block;
    bottom: 10px;
    margin: 0 auto;
    width: 250px;
    left: calc(50% - 75px);
    padding: 0px;
}

.stock {
    box-sizing: border-box;
    width: 75px;
    font-size: 2em;
    margin: 0px;
    width: 100px;
    height: 50px;
}

.confirmBtn, .clearBtn {
    box-sizing: border-box;
    color: white;
    font-weight: bold;
    border: 1px solid black;
    font-size: 2em;
    margin: 0px;
    width: 50px;
    height: 50px;
    padding: 0px;
  line-height:48px;
}

.clearBtn {
    background-color: red;
}

.confirmBtn {
    background-color: green;
}

<div class="stockWrapper">
    <input type="button" class="clearBtn" value="X"><input type="number" class="stock"><input type="button" class="confirmBtn" value="&#10004;">
</div>


问:
XML to XSD to .NET class object and accessing the object
My overall goal is to be able return an XML response from my REST API to .NET clients. Before I do that, I need to understand how to classify this data, such that the clients can understand it. I plan on deserializing XML into a class object. I am using an example of Cars at the moment.

I have the following XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<CarCollection>
<Cars>
  <Car>
    <StockNumber>1020</StockNumber>
    <Make>Nissan</Make>
    <Model>Sentra</Model>
  </Car>
  <Car>
    <StockNumber>1010</StockNumber>
    <Make>Toyota</Make>
    <Model>Corolla</Model>
  </Car>
  <Car>
    <StockNumber>1111</StockNumber>
    <Make>Honda</Make>
    <Model>Accord</Model>
  </Car>
</Cars>
</CarCollection>
</code>```

I generated the following XSD via the XSD.exe tool (using the xml file above):

```<code><?xml version="1.0" encoding="utf-8"?>
<xs:schema id="CarCollection" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
  <xs:element name="CarCollection" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
    <xs:complexType>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="Cars">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="Car" minOccurs="0" maxOccurs="unbounded">
                <xs:complexType>
                  <xs:sequence>
                    <xs:element name="StockNumber" type="xs:string" minOccurs="0" />
                    <xs:element name="Make" type="xs:string" minOccurs="0" />
                    <xs:element name="Model" type="xs:string" minOccurs="0" />
                  </xs:sequence>
                </xs:complexType>
              </xs:element>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:choice>
    </xs:complexType>
  </xs:element>
</xs:schema>
</code>```

By which, I generated the following C# class (command: xsd.exe carcollection.xsd /c):

```<code>//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Xml.Serialization;

//
// This source code was auto-generated by xsd, Version=4.6.1586.0.
//

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1586.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class CarCollection {

    private CarCollectionCars[] itemsField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("Cars", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public CarCollectionCars[] Items {
        get {
            return this.itemsField;
        }
        set {
            this.itemsField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1586.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class CarCollectionCars {

    private CarCollectionCarsCar[] carField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("Car", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public CarCollectionCarsCar[] Car {
        get {
            return this.carField;
        }
        set {
            this.carField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1586.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class CarCollectionCarsCar {

    private string stockNumberField;

    private string makeField;

    private string modelField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string StockNumber {
        get {
            return this.stockNumberField;
        }
        set {
            this.stockNumberField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string Make {
        get {
            return this.makeField;
        }
        set {
            this.makeField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string Model {
        get {
            return this.modelField;
        }
        set {
            this.modelField = value;
        }
    }
}
</code>```

I added the XML file and XSD above to my project. Here is my main class:

```<code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.Reflection;
using System.Xml;

namespace xmlToClass
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlSerializer ser = new XmlSerializer(typeof(CarCollection));
            CarCollection collection;

            var dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var file = dir + @"\test.xml";

            using (XmlReader reader = XmlReader.Create(file))
            {
                collection = (CarCollection)ser.Deserialize(reader);
            }

            //I can access these directly
            Console.WriteLine(collection.Car[0].StockNumber);
            Console.WriteLine(collection.Car[1].StockNumber);
            Console.WriteLine(collection.Car[2].StockNumber);

            //TODO: How to iterate over this collection?

            Console.ReadLine();
        }
    }
}
</code>```

I want to be able to iterate over this collection as well as access the properties at the same time. I've tried a foreach loop, but the console only printed the namespace and the object name "xmlToClass.CarCollection+CarsRow" (the default toString() method).

```<code>    foreach(var car in con.Cars)
    {
        Console.WriteLine(car);
    }
</code>```

I would use a for loop, but I cannot get the length of the collection. I suppose I do not understand the generated class properties or fields... I would SUPER appreciate some direction! Bonus question(s) (after I understand how to properly accessing these objects that are XML deserialized to classes):

What if I wanted to StockNumber to be of type "int" or "integer" INSTEAD of string? I've tried adding a type attribute to the XML document and regenerating the XSD to no avail.

Thank you for your time! If you want the project files, I can send them to you.

Notes

I don't want to edit the XSD or .CS file directly, since both are generated from an XML document. Any changes that need to be made to the XML document will warrant a re-generation of the XSD/CS files.

答:
"I've tried a foreach loop, but the console only printed the namespace
  and the object name "xmlToClass.CarCollection+CarsRow":"

Your for each is working, the issue is you are seeing the default implementation of ToString().  If you implement your own you can control the output - e.g.

```<code>public override string ToString()
{
  return $"stock:{stockNumberField} make: {makeField}";
}
</code>```

What if I wanted to StockNumber to be of type "int" or "integer"
  INSTEAD of string?

Then change the declaration and regenerate your classes

```<code><xs:element name="StockNumber" type="xs:int" minOccurs="0" />
</code>```

Body:
My overall goal is to be able return an XML response from my REST API to .NET clients. Before I do that, I need to understand how to classify this data, such that the clients can understand it. I plan on deserializing XML into a class object. I am using an example of Cars at the moment.

I have the following XML:

<?xml version="1.0" encoding="utf-8"?>
<CarCollection>
<Cars>
  <Car>
    <StockNumber>1020</StockNumber>
    <Make>Nissan</Make>
    <Model>Sentra</Model>
  </Car>
  <Car>
    <StockNumber>1010</StockNumber>
    <Make>Toyota</Make>
    <Model>Corolla</Model>
  </Car>
  <Car>
    <StockNumber>1111</StockNumber>
    <Make>Honda</Make>
    <Model>Accord</Model>
  </Car>
</Cars>
</CarCollection>

I generated the following XSD via the XSD.exe tool (using the xml file above):

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="CarCollection" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
  <xs:element name="CarCollection" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
    <xs:complexType>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="Cars">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="Car" minOccurs="0" maxOccurs="unbounded">
                <xs:complexType>
                  <xs:sequence>
                    <xs:element name="StockNumber" type="xs:string" minOccurs="0" />
                    <xs:element name="Make" type="xs:string" minOccurs="0" />
                    <xs:element name="Model" type="xs:string" minOccurs="0" />
                  </xs:sequence>
                </xs:complexType>
              </xs:element>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:choice>
    </xs:complexType>
  </xs:element>
</xs:schema>

By which, I generated the following C# class (command: xsd.exe carcollection.xsd /c):

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Xml.Serialization;

//
// This source code was auto-generated by xsd, Version=4.6.1586.0.
//

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1586.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class CarCollection {

    private CarCollectionCars[] itemsField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("Cars", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public CarCollectionCars[] Items {
        get {
            return this.itemsField;
        }
        set {
            this.itemsField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1586.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class CarCollectionCars {

    private CarCollectionCarsCar[] carField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("Car", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public CarCollectionCarsCar[] Car {
        get {
            return this.carField;
        }
        set {
            this.carField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1586.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class CarCollectionCarsCar {

    private string stockNumberField;

    private string makeField;

    private string modelField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string StockNumber {
        get {
            return this.stockNumberField;
        }
        set {
            this.stockNumberField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string Make {
        get {
            return this.makeField;
        }
        set {
            this.makeField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string Model {
        get {
            return this.modelField;
        }
        set {
            this.modelField = value;
        }
    }
}

I added the XML file and XSD above to my project. Here is my main class:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.Reflection;
using System.Xml;

namespace xmlToClass
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlSerializer ser = new XmlSerializer(typeof(CarCollection));
            CarCollection collection;

            var dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var file = dir + @"\test.xml";

            using (XmlReader reader = XmlReader.Create(file))
            {
                collection = (CarCollection)ser.Deserialize(reader);
            }

            //I can access these directly
            Console.WriteLine(collection.Car[0].StockNumber);
            Console.WriteLine(collection.Car[1].StockNumber);
            Console.WriteLine(collection.Car[2].StockNumber);

            //TODO: How to iterate over this collection?

            Console.ReadLine();
        }
    }
}

I want to be able to iterate over this collection as well as access the properties at the same time. I've tried a foreach loop, but the console only printed the namespace and the object name "xmlToClass.CarCollection+CarsRow" (the default toString() method).

    foreach(var car in con.Cars)
    {
        Console.WriteLine(car);
    }

I would use a for loop, but I cannot get the length of the collection. I suppose I do not understand the generated class properties or fields... I would SUPER appreciate some direction! Bonus question(s) (after I understand how to properly accessing these objects that are XML deserialized to classes):

What if I wanted to StockNumber to be of type "int" or "integer" INSTEAD of string? I've tried adding a type attribute to the XML document and regenerating the XSD to no avail.

Thank you for your time! If you want the project files, I can send them to you.

Notes

I don't want to edit the XSD or .CS file directly, since both are generated from an XML document. Any changes that need to be made to the XML document will warrant a re-generation of the XSD/CS files.

Body:
"I've tried a foreach loop, but the console only printed the namespace
  and the object name "xmlToClass.CarCollection+CarsRow":"

Your for each is working, the issue is you are seeing the default implementation of ToString().  If you implement your own you can control the output - e.g.

public override string ToString()
{
  return $"stock:{stockNumberField} make: {makeField}";
}

What if I wanted to StockNumber to be of type "int" or "integer"
  INSTEAD of string?

Then change the declaration and regenerate your classes

<xs:element name="StockNumber" type="xs:int" minOccurs="0" />


问:
How to define a field & group by within Select Query in SQL
At present have a column with status types, and a separate column with dates. What I would like to do is create new columns for each status type. Have created column names by using case when statements, but cannot then group by those.

At present, the table kicks out the following:

```<code>Reference |   Status    | Date
    ----- | ----------- | -----
        1 | Approve     | 1/1/2017
        1 | In Progress | 1/2/2017
        2 | Approve     | 1/1/2017
        2 | In Progress | 1/2/2017
        2 | Close       | 1/3/2017
</code>```

Would like to take this and make:

```<code>Reference | Approve  | In Progress | Close
--------- | -------- | ----------- | -----
        1 | 1/1/2017 | 1/2/2017    |
        2 | 1/1/2017 | 1/2/2017    | 1/3/2017
</code>```

Have a lot of other selects, and intention is to export to excel/run automatically, so trying to avoid temp tables.

I don't know that case when is appropriate, but am struggling to find a better solution.

答:
You can use pivot in sql server

```<code>select * from #yourStatus
pivot( max(date) for [Status] in ([Approve], [In Progress],[Close])) p
</code>```

Your table:

```<code>create table #yourStatus (Reference int, Status varchar(20), Date date)

insert into #yourstatus (
Reference   ,   Status  ,   Date ) values
 ( 1  ,'Approve','1/1/2017')
,( 1  ,'In Progress','1/2/2017')
,( 2  ,'Approve','1/1/2017')
,( 2  ,'In Progress','1/2/2017')
,( 2  ,'Close','1/3/2017')
</code>```

Body:
At present have a column with status types, and a separate column with dates. What I would like to do is create new columns for each status type. Have created column names by using case when statements, but cannot then group by those.

At present, the table kicks out the following:

Reference |   Status    | Date
    ----- | ----------- | -----
        1 | Approve     | 1/1/2017
        1 | In Progress | 1/2/2017
        2 | Approve     | 1/1/2017
        2 | In Progress | 1/2/2017
        2 | Close       | 1/3/2017

Would like to take this and make:

Reference | Approve  | In Progress | Close
--------- | -------- | ----------- | -----
        1 | 1/1/2017 | 1/2/2017    |
        2 | 1/1/2017 | 1/2/2017    | 1/3/2017

Have a lot of other selects, and intention is to export to excel/run automatically, so trying to avoid temp tables.

I don't know that case when is appropriate, but am struggling to find a better solution.

Body:
You can use pivot in sql server

select * from #yourStatus
pivot( max(date) for [Status] in ([Approve], [In Progress],[Close])) p

Your table:

create table #yourStatus (Reference int, Status varchar(20), Date date)

insert into #yourstatus (
Reference   ,   Status  ,   Date ) values
 ( 1  ,'Approve','1/1/2017')
,( 1  ,'In Progress','1/2/2017')
,( 2  ,'Approve','1/1/2017')
,( 2  ,'In Progress','1/2/2017')
,( 2  ,'Close','1/3/2017')


问:
How do I get Ionide to see .net core Linq and AspNetCore namespaces?
I recently installed dotnet core 1.0.0-rc4-004771. After generating a new fsharp project with the following command: "dotnet new mvc -lang f#"
Ionide complains that it can't find the Linq and AspNetCore namespaces even though "dotnet build" builds just fine.

Has anyone else run into this issue?

答:
should be fixed now, with

ionide >= 2.25.1

.net core sdk rtm (1.0.1)

see https://github.com/dotnet/netcorecli-fsc/wiki/.NET-Core-SDK-1.0.1 for more info

```<code>dotnet new mvc -lang f#
dotnet restore
code .
</code>```

restore can be done after open code too, but is required to make intellisense work

Body:
should be fixed now, with

ionide >= 2.25.1

.net core sdk rtm (1.0.1)

see https://github.com/dotnet/netcorecli-fsc/wiki/.NET-Core-SDK-1.0.1 for more info

dotnet new mvc -lang f#
dotnet restore
code .

restore can be done after open code too, but is required to make intellisense work


问:
Use guard statement to see there is error
We use guard to make sure some useful data exist before we progress deeper, can we use guard to check for error existence and exit early? or just standard if statement.

```<code>endpoint?.getArray() { data, error in
    guard error == nil else {
      print(error!)
      return
    }

    guard let data = data else {
      print("no data")
      return
    }

     print(data[0])
}
</code>```

EDIT

If using if statement, does it read better?

```<code>endpoint?.getArray() { data, error in
    if error != nil {
      print(error!)
      return
    }

    guard let data = data else {
      print("no data")
      return
    }

     print(data[0])
}
</code>```

答: guard requires a "return", which this is what you want. Using 'if' could be a problem if you "forgot" the return...</p>

Body:
We use guard to make sure some useful data exist before we progress deeper, can we use guard to check for error existence and exit early? or just standard if statement.

endpoint?.getArray() { data, error in
    guard error == nil else {
      print(error!)
      return
    }

    guard let data = data else {
      print("no data")
      return
    }

     print(data[0])
}

EDIT

If using if statement, does it read better?

endpoint?.getArray() { data, error in
    if error != nil {
      print(error!)
      return
    }

    guard let data = data else {
      print("no data")
      return
    }

     print(data[0])
}


问:
Printing the second half of a linked list in reverse order
I want to print the elements of a linked list, first in their order and then, once I reach the middle, in reverse order (from the last one backwards). For example:

If the elements are: 1 2 3 4 5 6

It should print: 1 2 3 6 5 4

But it's printing: 1 2 3 5 4

Why isn't it printing the last element? How can this be solved?

```<code>void reverse()
{
    int c=1;
    node *current,*prev,*temp;
    current=head;
    prev=NULL;
    std::stack<int>s;
    while(current->next!=NULL)
    {
        c++;
        s.push(current->data);
        current=current->next;
    }

    int mid=0;
    if((c%2)==0)
    {
        mid=c/2;
    }
    else
    {
        mid=(c+1)/2;
    }
    current=head;
    for(int i=0;i<mid;i++)
    {
        cout<<current->data<<"\t";
        current=current->next;
    }

    for(int i=mid;i>1;i--)
    {
       std::cout<<s.top()<<"\t";
       s.pop();
    }
    std::cout << '\n';
}
</code>```

答:
In a typical linked list implementation the last node points to nothing (typically nullptr). Your stop condition for adding the existing elements (current->next!=nullptr) to the stack therefore doesn't include the last element.

Iterating over current would be a better approach as that would stop one after the last node.

Also note that this will have an impact on your mid-point calculation as it is off by one from the start.

Body:
I want to print the elements of a linked list, first in their order and then, once I reach the middle, in reverse order (from the last one backwards). For example:

If the elements are: 1 2 3 4 5 6

It should print: 1 2 3 6 5 4

But it's printing: 1 2 3 5 4

Why isn't it printing the last element? How can this be solved?

void reverse()
{
    int c=1;
    node *current,*prev,*temp;
    current=head;
    prev=NULL;
    std::stack<int>s;
    while(current->next!=NULL)
    {
        c++;
        s.push(current->data);
        current=current->next;
    }

    int mid=0;
    if((c%2)==0)
    {
        mid=c/2;
    }
    else
    {
        mid=(c+1)/2;
    }
    current=head;
    for(int i=0;i<mid;i++)
    {
        cout<<current->data<<"\t";
        current=current->next;
    }

    for(int i=mid;i>1;i--)
    {
       std::cout<<s.top()<<"\t";
       s.pop();
    }
    std::cout << '\n';
}


答:
Don't do it with regex. Because of the fact that things can appear in any order, it's easier without:</p>

```<code>if (str.length() < 5) {
  return false;
}
int specialCharacterCount = 0;
for (int i = 0; i < str.length(); ++i) {
  char c = str.charAt(i);
  if (Character.isLowerCase(c)) {
    // A lowercase letter.
  } else if (Character.isDigit(c)) {
    // A number.
  } else if ("_.-".indexOf(c) >= 0) {
    // An allowed special character.
    ++specialCharacterCount;
  } else {
    // Some other character - immediately invalid.
    return false;
  }
}
// Return true if there is at most one of _, . and -.
return specialCharacterCount <= 1;
</code>```

Title: Java regex - alphanumeric, at most one hyphen, period or underscore, seven characters long

Body:
I'm new to the regex tool in Java, and despite their great potential I'm having a hard time accomplishing this task. I want to write a regex to validate an input string which respects the following syntax:

any combination of lowercase letters and digits

only one underscore, one dash or one period (no other special characters)

minimum length of 5

I came up with the following solution:

([/./-_]{0,1}[a-z0-9]){5,}

but in some cases it still doesn't work, for example it does not match a string where one of the special characters allowed is in the middle (such as he-llo). Where did I go wrong? Is there any other pattern better than this for my purpose?

Body:
Don't do it with regex. Because of the fact that things can appear in any order, it's easier without:

if (str.length() < 5) {
  return false;
}
int specialCharacterCount = 0;
for (int i = 0; i < str.length(); ++i) {
  char c = str.charAt(i);
  if (Character.isLowerCase(c)) {
    // A lowercase letter.
  } else if (Character.isDigit(c)) {
    // A number.
  } else if ("_.-".indexOf(c) >= 0) {
    // An allowed special character.
    ++specialCharacterCount;
  } else {
    // Some other character - immediately invalid.
    return false;
  }
}
// Return true if there is at most one of _, . and -.
return specialCharacterCount <= 1;


问:
Python - Remove white space using only loops
I want to remove extra spaces in a string using only for/while loops, and if statements; NO split/replace/join.

like this:

```<code>mystring = 'Here is  some   text   I      wrote   '

while '  ' in mystring:
    mystring = mystring.replace('  ', ' ')

print(mystring)
</code>```

output:

```<code>Here is some text I wrote
</code>```

Here's what I tried.  Unfortunately, it doesn't quite work.

```<code>def cleanupstring(S):
    lasti = ""
    result = ""

    for i in S:
        if lasti == " " and i == " ":
            i = ""

        lasti = i
        result += i

    print(result)

cleanupstring("Hello      my name    is    joe")
</code>```

output:

```<code>Hello   my name  is  joe
</code>```

My attempt doesn't remove all the extra spaces.

答:
Change your code to this:</p>

```<code>    for i in S:
        if lasti == " " and i == " ":
            i = ""
        else:
            lasti = i
        result += i

    print(result)
</code>```

Body:
I want to remove extra spaces in a string using only for/while loops, and if statements; NO split/replace/join.

like this:

mystring = 'Here is  some   text   I      wrote   '

while '  ' in mystring:
    mystring = mystring.replace('  ', ' ')

print(mystring)

output:

Here is some text I wrote

Here's what I tried.  Unfortunately, it doesn't quite work.

def cleanupstring(S):
    lasti = ""
    result = ""

    for i in S:
        if lasti == " " and i == " ":
            i = ""

        lasti = i
        result += i

    print(result)

cleanupstring("Hello      my name    is    joe")

output:

Hello   my name  is  joe

My attempt doesn't remove all the extra spaces.

Body:
Change your code to this:

    for i in S:
        if lasti == " " and i == " ":
            i = ""
        else:
            lasti = i
        result += i

    print(result)


答:
Check that the current character and the next one are spaces, and if not, add them to a clean string. There really is no need for an and in this case, since we are comparing to the same value

```<code>def cleanWhiteSpaces(str):
  clean = ""
  for i in range(len(str)):
    if not str[i]==" "==str[i-1]:
      clean += str[i]
  return clean
</code>```

Title: Python - Remove white space using only loops

Body:
Check that the current character and the next one are spaces, and if not, add them to a clean string. There really is no need for an and in this case, since we are comparing to the same value

def cleanWhiteSpaces(str):
  clean = ""
  for i in range(len(str)):
    if not str[i]==" "==str[i-1]:
      clean += str[i]
  return clean


问:
setq: wrong type argument: listp 1
My group and I are trying to create a list of cons lists. It might look something like this

```<code>((2 100032) (4 32413) (6 2131251) ... (232 12))
</code>```

Unfortunately, we keep getting a "wrong type argument". It might be something simple but I also wonder if we are doing something wrong with cons.

Any responses appreciated:

```<code>(defun find-diffs ()
    (let ((diffs (list))
          (index 0)
          (previous 0))
         (while (< index (length first-ten-million-primes))
           ; Add the difference to the list of diffs.
           (setq diff (- (aref first-ten-million-primes index) previous))
           ; We only want to bother recording it if the index is above zero and
           ; the difference is odd.
           (if (and (> index 0) (evenp diff))
             (setq diffs
               ; Can we find this one in our list of diffs?
               (if (cdr (assoc diff diffs))

                 ; Yes
                 ; ERROR happens when we call this statement
                 (setq diffs
                   (append (cons diff (1+ (car (cdr (assq diff diffs)))))
                           (assq-delete-all diff diffs)))
                 ; No
                 (setq diffs (plist-put diffs diff 1)))))
           ; Set previous value to this one.
           (setq previous (aref first-ten-million-primes index))
           ; Increment the index.
           (setq index (1+ index)))
         diffs)
</code>```

Commenting out the (setq diffs) will fix it, but I don't see anything wrong with how we are setting our variables.

Thanks!

The backtrace is huge so I will only post the first part. My team is still confused as to what's wrong so any responses appreciated.

Debugger Backtrace:

```<code>Debugger entered--Lisp error: (wrong-type-argument listp 1)
  append((2 . 1) nil)
  (setq diffs (append (cons diff 1) diffs))
  (if (cdr (assoc diff diffs)) (setq diffs (append (cons diff (1+ (car (cdr (assq diff diffs)))))
</code>```

答:
Your problem is in:

```<code>               (append (cons diff (1+ (car (cdr (assq diff diffs)))))
                       (assq-delete-all diff diffs)))
</code>```

The cons up there create a cell of the form (DIFF . N) which is not a proper list.  It's a pair of two element rather than a list of two elements.  A list of two elements would have the form (DIFF N) which is a shorthand for (DIFF . (N . nil)).

I haven't tried to understand what is your overall goal, but there are two ways to fix your problem:  Either replace

```<code>(append (cons diff FOO)
        ...)
</code>```

with

```<code>(append (list diff FOO)
        ...)
</code>```

or with

```<code>(cons (cons diff FOO)
      ...)
</code>```

Title: setq: wrong type argument: listp 1

Body:
My group and I are trying to create a list of cons lists. It might look something like this

((2 100032) (4 32413) (6 2131251) ... (232 12))

Unfortunately, we keep getting a "wrong type argument". It might be something simple but I also wonder if we are doing something wrong with cons.

Any responses appreciated:

(defun find-diffs ()
    (let ((diffs (list))
          (index 0)
          (previous 0))
         (while (< index (length first-ten-million-primes))
           ; Add the difference to the list of diffs.
           (setq diff (- (aref first-ten-million-primes index) previous))
           ; We only want to bother recording it if the index is above zero and
           ; the difference is odd.
           (if (and (> index 0) (evenp diff))
             (setq diffs
               ; Can we find this one in our list of diffs?
               (if (cdr (assoc diff diffs))

                 ; Yes
                 ; ERROR happens when we call this statement
                 (setq diffs
                   (append (cons diff (1+ (car (cdr (assq diff diffs)))))
                           (assq-delete-all diff diffs)))
                 ; No
                 (setq diffs (plist-put diffs diff 1)))))
           ; Set previous value to this one.
           (setq previous (aref first-ten-million-primes index))
           ; Increment the index.
           (setq index (1+ index)))
         diffs)

Commenting out the (setq diffs) will fix it, but I don't see anything wrong with how we are setting our variables.

Thanks!

The backtrace is huge so I will only post the first part. My team is still confused as to what's wrong so any responses appreciated.

Debugger Backtrace:

Debugger entered--Lisp error: (wrong-type-argument listp 1)
  append((2 . 1) nil)
  (setq diffs (append (cons diff 1) diffs))
  (if (cdr (assoc diff diffs)) (setq diffs (append (cons diff (1+ (car (cdr (assq diff diffs)))))

Body:
Your problem is in:

               (append (cons diff (1+ (car (cdr (assq diff diffs)))))
                       (assq-delete-all diff diffs)))

The cons up there create a cell of the form (DIFF . N) which is not a proper list.  It's a pair of two element rather than a list of two elements.  A list of two elements would have the form (DIFF N) which is a shorthand for (DIFF . (N . nil)).

I haven't tried to understand what is your overall goal, but there are two ways to fix your problem:  Either replace

(append (cons diff FOO)
        ...)

with

(append (list diff FOO)
        ...)

or with

(cons (cons diff FOO)
      ...)