问:
How can I format output in jquery to a div?
I have created a form maker that allows me to create a form but can't format the output in a similar fashion to pretty print.

Tried using \n and pre tags too

```<code>    allCont += "<label>"+insCleaned+"</label><input type='text' name='"+dval+insCleaned+"' /><p><?php echo "<?php if(isset(\$GLOBALS['postErrArray']['"?>"+ dval + insCleaned + "<?php echo "'])){echo \$GLOBALS['postErrArray']['"; ?>" + dval + insCleaned + "<?php echo "'];} ?>";?></p><br>";

                    $('#makeForm').append("<label>"+insCleaned+"</label><input type='text' name='"+insCleaned+"' /><br>");
                });

$('#showCode').text("<form method='post' action='ADD PATH' id='" + myForm +"'>" + allCont +"<input type='submit' value='Submit' id='" + myForm +"Submit' /><form>");
</code>```

the output comes as one long line, I would like a way to format it and include line breaks.

答:
If you just need it formatted clearly because you want to check once the code, I would use the features of the code editors to reformat it just once to check it; for example, the free editor PsPad has a "reformat HTML" command which reorders the code in a clear manner.

If on the other side you want to view in the page the generated code as viewed through an editor, remember you should escape all < to < and > to > , and surround this in PRE tags.

Body:
I have created a form maker that allows me to create a form but can't format the output in a similar fashion to pretty print.

Tried using \n and pre tags too

    allCont += ""+insCleaned+"<input type='text' name='"+dval+insCleaned+"' />
<?php echo "<?php if(isset(\$GLOBALS['postErrArray']['"?>"+ dval + insCleaned + "<?php echo "'])){echo \$GLOBALS['postErrArray']['"; ?>" + dval + insCleaned + "<?php echo "'];} ?>";?>

";

                    $('#makeForm').append(""+insCleaned+"<input type='text' name='"+insCleaned+"' />
");
                });

$('#showCode').text("<form method='post' action='ADD PATH' id='" + myForm +"'>" + allCont +"<input type='submit' value='Submit' id='" + myForm +"Submit' /><form>");

the output comes as one long line, I would like a way to format it and include line breaks.

Body:
If you just need it formatted clearly because you want to check once the code, I would use the features of the code editors to reformat it just once to check it; for example, the free editor PsPad has a "reformat HTML" command which reorders the code in a clear manner.

If on the other side you want to view in the page the generated code as viewed through an editor, remember you should escape all < to &lt; and > to &gt; , and surround this in PRE tags.


来源: stackexchange

问:
Android, delete files in my data directory?
My application stores some files that are required for it to run in the data directory of the app

```<code>/data/data/com.example.myapp/files/filehere.file
</code>```

When my application is updated from the market, it is important that I clear the files in the data directory, and update them to the latest ones from the new package that has just been downloaded.

My question is, how do I programatically delete the files in the directory in question?

Alternatively, is there an alternative directory that I can store the files in that are persistent across the lifetime of my application version, but will be cleared once an update is installed?

答:
```<code>File file = new File(FILEPATH);
if(file.exists())
  file.delete();
</code>```

As for your last question, my guess is you'll have to control that on your upgrade process. f.e., create a directory for each version and manage the files inside when the user upgrades.

ContentLicense: CC BY-SA 3.0

Body:
My application stores some files that are required for it to run in the data directory of the app

/data/data/com.example.myapp/files/filehere.file

When my application is updated from the market, it is important that I clear the files in the data directory, and update them to the latest ones from the new package that has just been downloaded.

My question is, how do I programatically delete the files in the directory in question?

Alternatively, is there an alternative directory that I can store the files in that are persistent across the lifetime of my application version, but will be cleared once an update is installed?

Body:
File file = new File(FILEPATH);
if(file.exists())
  file.delete();

As for your last question, my guess is you'll have to control that on your upgrade process. f.e., create a directory for each version and manage the files inside when the user upgrades.


问:
How do I make changes to a "live database"?
I have already created a vehicle_unit table

```<code> CREATE TABLE vehicle_unit (
 garage_code NUMERIC(2) NOT NULL,
 vunit_id  NUMERIC(6) NOT NULL,
 vunit_purchase_price NUMERIC(7,2),
 vunit_exhibition_flag CHAR(1) NOT NULL,
 vehicle_insurance_id VARCHAR(20) NOT NULL,
 vunit_rego VARCHAR(8) NOT NULL
);
</code>```

And inserted some values in them:

```<code>INSERT INTO vehicle_unit(vunit_purchase_price,vunit_exhibition_flag,vehicle_insurance_id,vunit_rego,vunit_id, garage_code)
SELECT 50000.00, 'R', 'sports-ute-449-12b', 'RD3161',garage_count_vehicles, garage_code
FROM garage
WHERE garage_email='caulfield@rdbms.example.com';
</code>```

If I want to add a NON NULL column called condition_flag how do I change this live database? Do I use alter table?But how do I insert this new value?

EDIT: I tried 'Alter table" but I got an error saying table must be empty to add mandatory (NOT NULL) column.

答: Before the ALTER ... NOT NULL statement, update all existing records to have a value (if they already don't). Then issue your ALTER ... NOT NULL, or as already recommended by JNevill, also add a DEFAULT clause as well (that will save you from modifying code that may not be providing values during INSERTs).

ContentLicense: CC BY-SA 4.0

Body:
I have already created a vehicle_unit table

 CREATE TABLE vehicle_unit (
 garage_code NUMERIC(2) NOT NULL,
 vunit_id  NUMERIC(6) NOT NULL,
 vunit_purchase_price NUMERIC(7,2),
 vunit_exhibition_flag CHAR(1) NOT NULL,
 vehicle_insurance_id VARCHAR(20) NOT NULL,
 vunit_rego VARCHAR(8) NOT NULL
);

And inserted some values in them:

INSERT INTO vehicle_unit(vunit_purchase_price,vunit_exhibition_flag,vehicle_insurance_id,vunit_rego,vunit_id, garage_code)
SELECT 50000.00, 'R', 'sports-ute-449-12b', 'RD3161',garage_count_vehicles, garage_code
FROM garage
WHERE garage_email='caulfield@rdbms.example.com';

If I want to add a NON NULL column called condition_flag how do I change this live database? Do I use alter table?But how do I insert this new value?

EDIT: I tried 'Alter table" but I got an error saying table must be empty to add mandatory (NOT NULL) column.


问:
How to deserialize an api response given dynamic column list? C# .NET Core 2.2
Say you have an endpoint that returns a JSON response with a dynamic list of indexed columns, in the following format:

```<code>"columnNames": [
  "date",
  "value",
  "someOtherValue"
],
"data": [
  [
    "2019-05-29",
    1.23,
    2.34
  ],
  [
    "2019-05-28",
    0.20,
    1.34
  ],
  [
    "2019-05-27,
    2.99,
    1.94
  ]
]
</code>```

What would be the most optimal way to deserialize such a response? I could try mapping it to some class which would contain both the columnNames and the data and afterwards just map it out, more or less like this (pseudo code):

```<code>var apiResponseContent = await response.Content.ReadAsAsync<ApiResponse>();
foreach(var responseData in apiResponseContent.data) {
  var model = new Model();
  model.date = responseData[apiResponseContent.columnNames.First(v => v == "date").index]
  ..
}
</code>```

But this seems to be such typical scenario, that there should be a more efficient alternative that is not prone to break if the endpoint response changes. Of course I could use reflection and create an extension method to automatically map out the columns to classes but it seems odd for me to do it.

答:
This is a peculiar format, especially with the data arrays containing varying types. However, you could use a simple class like this:

```<code>public class ApiResponse
{
    public IEnumerable<string> ColumnNames { get; set; }
    public IEnumerable<List<object>> Data { get; set; }
}
</code>```

If you want to map this object to another set of object, you could use a generic function that uses reflection, for example:

```<code>public List<T> MapTo<T>(ApiResponse source)
    where T : new()
{
    var properties = typeof(T).GetProperties();

    foreach (var datum in source.Data)
    {
        var t = new T();

        for(var colIndex = 0; colIndex < source.ColumnNames.Count; colIndex++)
        {
            var property = properties.SingleOrDefault(p => p.Name.Equals(source.ColumnNames[colIndex], StringComparison.InvariantCultureIgnoreCase));
            if (property != null)
            {
                property.SetValue(t, Convert.ChangeType(datum[colIndex], property.PropertyType));
            }
        }
        yield return t;
    }
}
</code>```

And your final code could look something like this:

```<code>public class Foo
{
    public string Date { get; set; }
    public double Value { get; set; }
    public double SomeOtherValue { get; set; }
}

var apiResponseContent = await response.Content.ReadAsAsync<ApiResponse>();
var actualData = MapTo<Foo>(apiResponseContent);
</code>```

Body:
Say you have an endpoint that returns a JSON response with a dynamic list of indexed columns, in the following format:

"columnNames": [
  "date",
  "value",
  "someOtherValue"
],
"data": [
  [
    "2019-05-29",
    1.23,
    2.34
  ],
  [
    "2019-05-28",
    0.20,
    1.34
  ],
  [
    "2019-05-27,
    2.99,
    1.94
  ]
]

What would be the most optimal way to deserialize such a response? I could try mapping it to some class which would contain both the columnNames and the data and afterwards just map it out, more or less like this (pseudo code):

var apiResponseContent = await response.Content.ReadAsAsync<ApiResponse>();
foreach(var responseData in apiResponseContent.data) {
  var model = new Model();
  model.date = responseData[apiResponseContent.columnNames.First(v => v == "date").index]
  ..
}

But this seems to be such typical scenario, that there should be a more efficient alternative that is not prone to break if the endpoint response changes. Of course I could use reflection and create an extension method to automatically map out the columns to classes but it seems odd for me to do it.

Body:
This is a peculiar format, especially with the data arrays containing varying types. However, you could use a simple class like this:

public class ApiResponse
{
    public IEnumerable<string> ColumnNames { get; set; }
    public IEnumerable<List<object>> Data { get; set; }
}

If you want to map this object to another set of object, you could use a generic function that uses reflection, for example:

public List<T> MapTo<T>(ApiResponse source)
    where T : new()
{
    var properties = typeof(T).GetProperties();

    foreach (var datum in source.Data)
    {
        var t = new T();

        for(var colIndex = 0; colIndex < source.ColumnNames.Count; colIndex++)
        {
            var property = properties.SingleOrDefault(p => p.Name.Equals(source.ColumnNames[colIndex], StringComparison.InvariantCultureIgnoreCase));
            if (property != null)
            {
                property.SetValue(t, Convert.ChangeType(datum[colIndex], property.PropertyType));
            }
        }
        yield return t;
    }
}

And your final code could look something like this:

public class Foo
{
    public string Date { get; set; }
    public double Value { get; set; }
    public double SomeOtherValue { get; set; }
}

var apiResponseContent = await response.Content.ReadAsAsync<ApiResponse>();
var actualData = MapTo<Foo>(apiResponseContent);


问:
Using Dense Rank to simulate Count(Distinct) but running into a problem
Since SQL doesn't allow me to do count Distinct over Window functions, I have to use dense rank to achieve what I am trying to do.

My statement is:

```<code>,DENSE_RANK() over (partition by CustomerEmail order by Date_Created asc)
+DENSE_RANK() over (partition by CustomerEmail order by Date_Created desc)
-1 as AmountOrdersOverRangeByCustomer
</code>```

This gives me how much time a customer (using email to identify) places an order. So if he places 5 orders over a period of time, it would go 5,5,5,5, and 5.

The problem is, if he places two orders on the same day (Date_Created). Then instead of counting it as 2,2,  Dense_Rank counts it as 1,1... which I think is how it is supposed to act, but not how I want it. Does anyone know a fix? Would using Row_Number instead of Dense_Rank fix this?

答:
Your code should work, although I more typically use a subquery for this purpose:

```<code>SELECT . . .
       MAX(dr) OVER (PARTITION BY CustomerEmail) as AmountOrdersOverRangeByCustomer
FROM (SELECT . . .,
             DENSE_RANK() over (partition by CustomerEmail order by Date_Created asc) as dr
      . . .
     ) . . .
</code>```

However, if you want to count two orders on the same day as two, rather than one, then perhaps you don't want COUNT(DISTINCT) at all, simply:

```<code>COUNT(*) OVER (PARTITION BY CustomerEmail)
</code>```

Body:
Since SQL doesn't allow me to do count Distinct over Window functions, I have to use dense rank to achieve what I am trying to do.

My statement is:

,DENSE_RANK() over (partition by CustomerEmail order by Date_Created asc)
+DENSE_RANK() over (partition by CustomerEmail order by Date_Created desc)
-1 as AmountOrdersOverRangeByCustomer

This gives me how much time a customer (using email to identify) places an order. So if he places 5 orders over a period of time, it would go 5,5,5,5, and 5.

The problem is, if he places two orders on the same day (Date_Created). Then instead of counting it as 2,2,  Dense_Rank counts it as 1,1... which I think is how it is supposed to act, but not how I want it. Does anyone know a fix? Would using Row_Number instead of Dense_Rank fix this?

Body:
Your code should work, although I more typically use a subquery for this purpose:

SELECT . . .
       MAX(dr) OVER (PARTITION BY CustomerEmail) as AmountOrdersOverRangeByCustomer
FROM (SELECT . . .,
             DENSE_RANK() over (partition by CustomerEmail order by Date_Created asc) as dr
      . . .
     ) . . .

However, if you want to count two orders on the same day as two, rather than one, then perhaps you don't want COUNT(DISTINCT) at all, simply:

COUNT(*) OVER (PARTITION BY CustomerEmail)


问:
Correct location of MSBuild.exe to build .net 4.5 application using command line
I have asp.net web api application targeting 4.5 framework.

I am trying to create a docker image for my application. In order to build the application, I can use MSBuild.exe available in C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe or C:\Program Files (x86)\MSBuild\14.0\Bin\MSBuild.exe locations.

When I build using C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe location, I get error saying "
C:\MyApp-Api\MyApp-Api.csproj(985,3)
: error MSB4019: The imported project "C:\Program Files (x86)\MSBuild\Microsoft
\VisualStudio\v11.0\WebApplications\Microsoft.WebApplication.targets" was not f
ound. Confirm that the path in the  declaration is correct, and that th
e file exists on disk."

I am able to build my application using C:\Program Files (x86)\MSBuild\14.0\Bin\MSBuild.exe location.

Questions:

What is the difference between the MsBuild.Exe available in these two folders?

Ideally I think using  C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe location is the right approach as it comes with default location and I think MSBuild in program files comes due to installation of Visual Studio. and on my Build server I will not have visual studio installed.

In order to build the application on container, I need to specify SDK which will allow me to build the application. Which version of SDK, I need to build .net 4.5 application.

答:
I was browsing web with a similar query today and stumbled upon this random link to a Veracode extension which lists nicely the difference.

Visual Studio 2017

The first two paths below that contain Professional differ based on the edition of Visual Studio you have installed. Replace Professional with Enterprise or Community, when appropriate.

Note: the Visual Studio Preview install also changes the path based on Enterprise, Professional, or Community.

Standard Visual Studio Paths

C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\

C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\amd64\

Visual Studio Preview Paths

C:\Program Files (x86)\Microsoft Visual Studio\Preview\Professional\MSBuild\15.0\Bin

MSBuild Tools Paths

C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin\

C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin\amd64\

Visual Studio 2015

C:\Program Files (x86)\MSBuild\14.0\Bin\
C:\Program Files (x86)\MSBuild\14.0\Bin\amd64\

Visual Studio 2013

C:\Program Files (x86)\MSBuild\12.0\Bin\
C:\Program Files (x86)\MSBuild\12.0\Bin\amd64\

Visual Studio 2012

C:\Windows\Microsoft.NET\Framework\v4.0.30319\
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\

It seems like you have both VS2012 and VS2015 installed.
I dont know much about ASP.NET and docker but will try to answer your questions:

I think the difference is explained above.
The problem you are experiencing there is explained better in here:
The imported project Microsoft.WebApplications.targets was not found Maybe give it a go?

Relying on https://dotnet.microsoft.com/download/visual-studio-sdks and
https://learn.microsoft.com/en-us/dotnet/framework/install/guide-for-developers it seems like there is no SDK for .net 4.5 as it is included in VS2012. But any higher version should build your project to 4.5 anyway.

Reading (3) I would use VS2015 msbuild if VS2012 gives you a headache.

If you dont mind me asking - Why not switching to ASP.NET Core ?


问:
Android and .NET Webservice - parsing the returned xml
So I have done a few "minor" things with web services and had some success, but when I attempted to tinker around with some stuff for fun I was encountering what I believe is me incorrectly parsing out the data to get the information that I need.  I can get the entire xml as a string but not just the 3 programs that I need.  The getPrograms and getInstitutions are similar enough that if I can get the programs part parsed right I can get the institutions.  Where I am getting confused is what I believe is the "tags" and how much they differ from any tutorials to what I am actually using.  I also went the way of the XmlPullParser but do not know if this is the best way about doing this (is it?). The format of what I am accessing is as follows:

```<code><DataSet>
<xs:schema id="NewDataSet">
<xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="tblPrograms">
<xs:complexType>
<xs:sequence>
<xs:element name="Program" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
<diffgr:diffgram>
<NewDataSet>
<tblPrograms diffgr:id="tblPrograms1" msdata:rowOrder="0">
<Program>Ancillary</Program>
</tblPrograms>
<tblPrograms diffgr:id="tblPrograms2" msdata:rowOrder="1">
<Program>Ancillary ESY</Program>
</tblPrograms>
<tblPrograms diffgr:id="tblPrograms3" msdata:rowOrder="2">
<Program>REAP</Program>
</tblPrograms>
</NewDataSet>
</diffgr:diffgram>
</DataSet>
</code>```

And my source code is as follows:

```<code>public class FirstScreen extends Activity {
    /** Called when the activity is first created. */

    private static final String NAMESPACE = "http://tempuri.org/";
    private static final String URL = "http://www.ces.org/android/android.asmx";//must point to where service is located

    /** HelloAndroid method */
    //SOAP_ACTION = NAMESPACE + METHODNAME
    private static final String SOAP_ACTION = "http://tempuri.org/HelloAndroid";
    private static final String METHOD_NAME = "HelloAndroid";

    /** SelectInstitutionTypes method */
    //SOAP_ACTION = NAMESPACE + METHODNAME
    private static final String SOAP_ACTION_INSTITUTIONS = "http://tempuri.org/SelectInstitutionTypes";
    private static final String METHOD_NAME_INSTITUTIONS = "SelectInstitutionTypes";

    /** SelectPrograms method */
    //SOAP_ACTION = NAMESPACE + METHODNAME
    private static final String SOAP_ACTION_PROGRAMS = "http://tempuri.org/SelectPrograms";
    private static final String METHOD_NAME_PROGRAMS = "SelectPrograms";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        getHelloAndroid();
        //getInstitutionTypes();
        getPrograms();

    }//end of onCreate

    private void getPrograms() {
        TextView tv3 = (TextView)findViewById(R.id.TextView03);//contains SelectInstitutionTypes information

        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME_PROGRAMS);

        //soap serialization
        SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);//running 1.1
        soapEnvelope.dotNet=true;//to handle .net services asmx/aspx
        soapEnvelope.setOutputSoapObject(request);//package request

        //create transport object(s)
        HttpTransportSE aht = new HttpTransportSE(URL);

        try
        {
            aht.debug = true;
            //make the call

            aht.call(SOAP_ACTION_PROGRAMS, soapEnvelope); //in/out

            SoapObject resultString = (SoapObject)soapEnvelope.getResponse();

            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            factory.setNamespaceAware(true);
            XmlPullParser xpp = factory.newPullParser();
            xpp.setInput(new StringReader (resultString.toString()));
            int eventType = xpp.getEventType();
            while(eventType != XmlPullParser.END_DOCUMENT){
                 if(eventType == XmlPullParser.START_DOCUMENT) {
                     System.out.println("Start document");
                 } else if(eventType == XmlPullParser.START_TAG) {
                     if(xpp.getName().equals("Program"))
                     System.out.println("Start tag "+xpp.getName());
                     System.out.println("Program"+ xpp.getAttributeName(0));
                 } else if(eventType == XmlPullParser.END_TAG) {
                     System.out.println("End tag "+xpp.getName());
                 } else if(eventType == XmlPullParser.TEXT) {
                     System.out.println("Text "+xpp.getText());
                 }
                 eventType = xpp.next();
                }
                System.out.println("End document");

            tv3.setBackgroundColor(Color.BLUE);
            tv3.setText("STATUS: " + resultString /*ks.toString()*/ + "\n\n" + "AHTHOST:  " +
                    aht.getHost() + "\n\n" + "NAHT STRING:  " + aht.toString());
        }
        catch(Exception e)
        {
            e.toString();
            e.printStackTrace();

            tv3.setText("EXCEPTION NAME:  " + e.toString().toString() +
                    "\n\n" + "EXCEPTION MESSAGE:  " + e.getMessage() + " ");
        }
    }//end of getPrograms

    private void getInstitutionTypes() {

        TextView tv2 = (TextView)findViewById(R.id.TextView02);//contains SelectInstitutionTypes information
        //tv2.setText("TODO: SelectInstitutionTypes");

        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME_INSTITUTIONS);

        //soap serialization
        SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);//running 1.1
        soapEnvelope.dotNet=true;//to handle .net services asmx/aspx
        soapEnvelope.setOutputSoapObject(request);//package request

        //create transport object(s)
        HttpTransportSE aht = new HttpTransportSE(URL);

        try
        {
            aht.debug = true;
            //make the call
            aht.call(SOAP_ACTION_INSTITUTIONS, soapEnvelope); //in/out
            SoapObject resultString = (SoapObject)soapEnvelope.getResponse();

            tv2.setText("STATUS: " + resultString /*ks.toString()*/ + "\n\n" + "AHTHOST:  " +
                    aht.getHost() + "\n\n" + "NAHT STRING:  " + aht.toString());

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

            tv2.setText("EXCEPTION NAME:  " + e.toString().toString() +
                    "\n\n" + "EXCEPTION MESSAGE:  " + e.getMessage() + " ");
        }
    }//end of getInstitutionTypes

    public void getHelloAndroid() {

        TextView tv = (TextView)findViewById(R.id.TextView01);//contains HelloAndroid information

        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

        //soap serialization
        SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);//running 1.1
        soapEnvelope.dotNet=true;//to handle .net services asmx/aspx
        soapEnvelope.setOutputSoapObject(request);//package request

        //create transport object(s)
        HttpTransportSE aht = new HttpTransportSE(URL);

        try
        {
            aht.debug = true;
            //make the call
            aht.call(SOAP_ACTION, soapEnvelope); //in/out
            SoapPrimitive resultString = (SoapPrimitive)soapEnvelope.getResponse();

            tv.setBackgroundColor(Color.BLUE);

            tv.setText("STATUS: " + resultString + "\n\n" + "AHTHOST:  " +
                    aht.getHost() + "\n\n" + "NAHT STRING:  " + aht.toString());

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

            tv.setText("EXCEPTION NAME:  " + e.toString().toString() +
                    "\n\n" + "EXCEPTION MESSAGE:  " + e.getMessage() + " ");
        }
    }//end of getHelloAndroid

}//end of activity
</code>```

答:
So after much research I was able to get this parsed correctly so I figured I would answer my own question.  I also had to change the structure of my program to get what I needed...or at least understand what I was doing before I started to implement it in the code above.  So the 3 classes that are below are the ones I used to get what I needed...for now.

```<code>public class MyXMLHandler extends DefaultHandler {

    Boolean currentElement = false;
    String currentValue = null;
    public static ProgramList programList = null;

    public static ProgramList getProgramList() {
        return programList;
    }

    public static void setProgramList(ProgramList programList) {
        MyXMLHandler.programList = programList;
    }

    //called when tag starts ( ex:- <tblPrograms>diffgr:id="tblPrograms1" msdata:rowOrder="0"</tblPrograms>  -- <tblPrograms> )
    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {

        currentElement = true;

        //set up for hierarchy scan to place data within category
        if (localName.equals("DataSet"))
        {
            /** Start */
            programList = new ProgramList();
        } else if (localName.equals("tblPrograms")){//"NewDataSet" - DOES NOT WORK - F.C.
            /** Get attribute value */
            String attr = attributes.getValue(0);
            String attr2 = attributes.getValue(1);
            programList.setTable(attr);
            programList.setRowOrder(attr2);
        }

    }

    //called when tag closing ( ex:- <Program>Ancillary</Program>  -- </Program> )
    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {

        currentElement = false;

        /** set value */
        if (localName.equalsIgnoreCase("Program"))
            programList.setProgram(currentValue);
        //else if (localName.equalsIgnoreCase("tblPrograms"))
            //programList.setWebsite(currentValue);

    }

    //called to get tag characters ( ex:- <Program>Ancillary</Program> -- to get Ancillary character )
    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {

        if (currentElement) {
            currentValue = new String(ch, start, length);
            currentElement = false;
        }

    }

}
</code>```

Then I have my getter and setter methods for the variables within my program list.

```<code>//contains getter and setter method for variables
public class ProgramList {

    //variables
    private ArrayList<String> program = new ArrayList<String>();
    private ArrayList<String> rowOrder = new ArrayList<String>();
    private ArrayList<String> table = new ArrayList<String>();

    //in Setter method default it will return arraylist change that to add

    public ArrayList<String> getProgram() {
        return program;
    }

    public void setProgram(String program) {
        this.program.add(program);
    }

    public ArrayList<String> getRowOrder() {
        return rowOrder;
    }

    public void setRowOrder(String rowOrder) {
        this.rowOrder.add(rowOrder);
    }

    public ArrayList<String> getTable() {
        return table;
    }

    public void setTable(String table) {
        this.table.add(table);
    }

}
</code>```

Finally main

```<code>public class XMLParsingExample extends Activity {

    //create object For SiteList class
    ProgramList programList = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //create a new layout to display the view
        //LinearLayout layout = new LinearLayout(this);
        //layout.setOrientation(1);

        LinearLayout ll = (LinearLayout)findViewById(R.id.LL01);

        //create a new textview array to display the results
        //TextView name[];
        //TextView website[];
        //TextView category[];

        try {

            //handle XML
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();

            //URL to parse XML Tags
            URL sourceUrl = new URL(
                    "http://www.ces.org/android/android.asmx/SelectPrograms");

            //Create handler to handle XML Tags ( extends DefaultHandler )
            MyXMLHandler myXMLHandler = new MyXMLHandler();
            xr.setContentHandler(myXMLHandler);
            xr.parse(new InputSource(sourceUrl.openStream()));

        } catch (Exception e) {
            System.out.println("XML Pasing Excpetion = " + e);
        }

        //get result from MyXMLHandler SitlesList Object
        programList = MyXMLHandler.programList;

        //assign a textview array length by arraylist size
        TextView name[] = new TextView[programList.getProgram().size()];
        TextView website[] = new TextView[programList.getProgram().size()];
        TextView category[] = new TextView[programList.getProgram().size()];

        //set the result text in textview and add it to layout
        for (int i = 0; i < programList.getProgram().size(); i++) {
            name[i] = new TextView(this);
            name[i].setText("Program = "+programList.getProgram().get(i));
            name[i].setBackgroundColor(Color.BLUE);

            website[i] = new TextView(this);
            website[i].setText("Row Order = "+programList.getRowOrder().get(i));

            category[i] = new TextView(this);
            category[i].setText("Program Table = "+programList.getTable().get(i));

            //layout.addView(name[i]);
            //layout.addView(website[i]);
            //layout.addView(category[i]);
            ll.addView(name[i]);
            ll.addView(website[i]);
            ll.addView(category[i]);

        }

        //set the layout view to display
        //setContentView(layout);
        setContentView(ll);

    }
}
</code>```

Body:
So I have done a few "minor" things with web services and had some success, but when I attempted to tinker around with some stuff for fun I was encountering what I believe is me incorrectly parsing out the data to get the information that I need.  I can get the entire xml as a string but not just the 3 programs that I need.  The getPrograms and getInstitutions are similar enough that if I can get the programs part parsed right I can get the institutions.  Where I am getting confused is what I believe is the "tags" and how much they differ from any tutorials to what I am actually using.  I also went the way of the XmlPullParser but do not know if this is the best way about doing this (is it?). The format of what I am accessing is as follows:

<DataSet>
<xs:schema id="NewDataSet">
<xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="tblPrograms">
<xs:complexType>
<xs:sequence>
<xs:element name="Program" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
<diffgr:diffgram>
<NewDataSet>
<tblPrograms diffgr:id="tblPrograms1" msdata:rowOrder="0">
<Program>Ancillary</Program>
</tblPrograms>
<tblPrograms diffgr:id="tblPrograms2" msdata:rowOrder="1">
<Program>Ancillary ESY</Program>
</tblPrograms>
<tblPrograms diffgr:id="tblPrograms3" msdata:rowOrder="2">
<Program>REAP</Program>
</tblPrograms>
</NewDataSet>
</diffgr:diffgram>
</DataSet>

And my source code is as follows:

public class FirstScreen extends Activity {
    /** Called when the activity is first created. */

    private static final String NAMESPACE = "http://tempuri.org/";
    private static final String URL = "http://www.ces.org/android/android.asmx";//must point to where service is located

    /** HelloAndroid method */
    //SOAP_ACTION = NAMESPACE + METHODNAME
    private static final String SOAP_ACTION = "http://tempuri.org/HelloAndroid";
    private static final String METHOD_NAME = "HelloAndroid";

    /** SelectInstitutionTypes method */
    //SOAP_ACTION = NAMESPACE + METHODNAME
    private static final String SOAP_ACTION_INSTITUTIONS = "http://tempuri.org/SelectInstitutionTypes";
    private static final String METHOD_NAME_INSTITUTIONS = "SelectInstitutionTypes";

    /** SelectPrograms method */
    //SOAP_ACTION = NAMESPACE + METHODNAME
    private static final String SOAP_ACTION_PROGRAMS = "http://tempuri.org/SelectPrograms";
    private static final String METHOD_NAME_PROGRAMS = "SelectPrograms";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        getHelloAndroid();
        //getInstitutionTypes();
        getPrograms();

    }//end of onCreate

    private void getPrograms() {
        TextView tv3 = (TextView)findViewById(R.id.TextView03);//contains SelectInstitutionTypes information

        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME_PROGRAMS);

        //soap serialization
        SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);//running 1.1
        soapEnvelope.dotNet=true;//to handle .net services asmx/aspx
        soapEnvelope.setOutputSoapObject(request);//package request

        //create transport object(s)
        HttpTransportSE aht = new HttpTransportSE(URL);

        try
        {
            aht.debug = true;
            //make the call

            aht.call(SOAP_ACTION_PROGRAMS, soapEnvelope); //in/out

            SoapObject resultString = (SoapObject)soapEnvelope.getResponse();

            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            factory.setNamespaceAware(true);
            XmlPullParser xpp = factory.newPullParser();
            xpp.setInput(new StringReader (resultString.toString()));
            int eventType = xpp.getEventType();
            while(eventType != XmlPullParser.END_DOCUMENT){
                 if(eventType == XmlPullParser.START_DOCUMENT) {
                     System.out.println("Start document");
                 } else if(eventType == XmlPullParser.START_TAG) {
                     if(xpp.getName().equals("Program"))
                     System.out.println("Start tag "+xpp.getName());
                     System.out.println("Program"+ xpp.getAttributeName(0));
                 } else if(eventType == XmlPullParser.END_TAG) {
                     System.out.println("End tag "+xpp.getName());
                 } else if(eventType == XmlPullParser.TEXT) {
                     System.out.println("Text "+xpp.getText());
                 }
                 eventType = xpp.next();
                }
                System.out.println("End document");

            tv3.setBackgroundColor(Color.BLUE);
            tv3.setText("STATUS: " + resultString /*ks.toString()*/ + "\n\n" + "AHTHOST:  " +
                    aht.getHost() + "\n\n" + "NAHT STRING:  " + aht.toString());
        }
        catch(Exception e)
        {
            e.toString();
            e.printStackTrace();

            tv3.setText("EXCEPTION NAME:  " + e.toString().toString() +
                    "\n\n" + "EXCEPTION MESSAGE:  " + e.getMessage() + " ");
        }
    }//end of getPrograms

    private void getInstitutionTypes() {

        TextView tv2 = (TextView)findViewById(R.id.TextView02);//contains SelectInstitutionTypes information
        //tv2.setText("TODO: SelectInstitutionTypes");

        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME_INSTITUTIONS);

        //soap serialization
        SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);//running 1.1
        soapEnvelope.dotNet=true;//to handle .net services asmx/aspx
        soapEnvelope.setOutputSoapObject(request);//package request

        //create transport object(s)
        HttpTransportSE aht = new HttpTransportSE(URL);

        try
        {
            aht.debug = true;
            //make the call
            aht.call(SOAP_ACTION_INSTITUTIONS, soapEnvelope); //in/out
            SoapObject resultString = (SoapObject)soapEnvelope.getResponse();

            tv2.setText("STATUS: " + resultString /*ks.toString()*/ + "\n\n" + "AHTHOST:  " +
                    aht.getHost() + "\n\n" + "NAHT STRING:  " + aht.toString());

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

            tv2.setText("EXCEPTION NAME:  " + e.toString().toString() +
                    "\n\n" + "EXCEPTION MESSAGE:  " + e.getMessage() + " ");
        }
    }//end of getInstitutionTypes

    public void getHelloAndroid() {

        TextView tv = (TextView)findViewById(R.id.TextView01);//contains HelloAndroid information

        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

        //soap serialization
        SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);//running 1.1
        soapEnvelope.dotNet=true;//to handle .net services asmx/aspx
        soapEnvelope.setOutputSoapObject(request);//package request

        //create transport object(s)
        HttpTransportSE aht = new HttpTransportSE(URL);

        try
        {
            aht.debug = true;
            //make the call
            aht.call(SOAP_ACTION, soapEnvelope); //in/out
            SoapPrimitive resultString = (SoapPrimitive)soapEnvelope.getResponse();

            tv.setBackgroundColor(Color.BLUE);

            tv.setText("STATUS: " + resultString + "\n\n" + "AHTHOST:  " +
                    aht.getHost() + "\n\n" + "NAHT STRING:  " + aht.toString());

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

            tv.setText("EXCEPTION NAME:  " + e.toString().toString() +
                    "\n\n" + "EXCEPTION MESSAGE:  " + e.getMessage() + " ");
        }
    }//end of getHelloAndroid

}//end of activity

Body:
So after much research I was able to get this parsed correctly so I figured I would answer my own question.  I also had to change the structure of my program to get what I needed...or at least understand what I was doing before I started to implement it in the code above.  So the 3 classes that are below are the ones I used to get what I needed...for now.

public class MyXMLHandler extends DefaultHandler {

    Boolean currentElement = false;
    String currentValue = null;
    public static ProgramList programList = null;

    public static ProgramList getProgramList() {
        return programList;
    }

    public static void setProgramList(ProgramList programList) {
        MyXMLHandler.programList = programList;
    }

    //called when tag starts ( ex:- <tblPrograms>diffgr:id="tblPrograms1" msdata:rowOrder="0"</tblPrograms>  -- <tblPrograms> )
    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {

        currentElement = true;

        //set up for hierarchy scan to place data within category
        if (localName.equals("DataSet"))
        {
            /** Start */
            programList = new ProgramList();
        } else if (localName.equals("tblPrograms")){//"NewDataSet" - DOES NOT WORK - F.C.
            /** Get attribute value */
            String attr = attributes.getValue(0);
            String attr2 = attributes.getValue(1);
            programList.setTable(attr);
            programList.setRowOrder(attr2);
        }

    }

    //called when tag closing ( ex:- <Program>Ancillary</Program>  -- </Program> )
    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {

        currentElement = false;

        /** set value */
        if (localName.equalsIgnoreCase("Program"))
            programList.setProgram(currentValue);
        //else if (localName.equalsIgnoreCase("tblPrograms"))
            //programList.setWebsite(currentValue);

    }

    //called to get tag characters ( ex:- <Program>Ancillary</Program> -- to get Ancillary character )
    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {

        if (currentElement) {
            currentValue = new String(ch, start, length);
            currentElement = false;
        }

    }

}

Then I have my getter and setter methods for the variables within my program list.

//contains getter and setter method for variables
public class ProgramList {

    //variables
    private ArrayList<String> program = new ArrayList<String>();
    private ArrayList<String> rowOrder = new ArrayList<String>();
    private ArrayList<String> table = new ArrayList<String>();

    //in Setter method default it will return arraylist change that to add

    public ArrayList<String> getProgram() {
        return program;
    }

    public void setProgram(String program) {
        this.program.add(program);
    }

    public ArrayList<String> getRowOrder() {
        return rowOrder;
    }

    public void setRowOrder(String rowOrder) {
        this.rowOrder.add(rowOrder);
    }

    public ArrayList<String> getTable() {
        return table;
    }

    public void setTable(String table) {
        this.table.add(table);
    }

}

Finally main

public class XMLParsingExample extends Activity {

    //create object For SiteList class
    ProgramList programList = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //create a new layout to display the view
        //LinearLayout layout = new LinearLayout(this);
        //layout.setOrientation(1);

        LinearLayout ll = (LinearLayout)findViewById(R.id.LL01);

        //create a new textview array to display the results
        //TextView name[];
        //TextView website[];
        //TextView category[];

        try {

            //handle XML
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();

            //URL to parse XML Tags
            URL sourceUrl = new URL(
                    "http://www.ces.org/android/android.asmx/SelectPrograms");

            //Create handler to handle XML Tags ( extends DefaultHandler )
            MyXMLHandler myXMLHandler = new MyXMLHandler();
            xr.setContentHandler(myXMLHandler);
            xr.parse(new InputSource(sourceUrl.openStream()));

        } catch (Exception e) {
            System.out.println("XML Pasing Excpetion = " + e);
        }

        //get result from MyXMLHandler SitlesList Object
        programList = MyXMLHandler.programList;

        //assign a textview array length by arraylist size
        TextView name[] = new TextView[programList.getProgram().size()];
        TextView website[] = new TextView[programList.getProgram().size()];
        TextView category[] = new TextView[programList.getProgram().size()];

        //set the result text in textview and add it to layout
        for (int i = 0; i < programList.getProgram().size(); i++) {
            name[i] = new TextView(this);
            name[i].setText("Program = "+programList.getProgram().get(i));
            name[i].setBackgroundColor(Color.BLUE);

            website[i] = new TextView(this);
            website[i].setText("Row Order = "+programList.getRowOrder().get(i));

            category[i] = new TextView(this);
            category[i].setText("Program Table = "+programList.getTable().get(i));

            //layout.addView(name[i]);
            //layout.addView(website[i]);
            //layout.addView(category[i]);
            ll.addView(name[i]);
            ll.addView(website[i]);
            ll.addView(category[i]);

        }

        //set the layout view to display
        //setContentView(layout);
        setContentView(ll);

    }
}


问:
Animate moving an element using append
I want an element on the page to move from the Jumbotron to the navbar with a "moving" animation when you scroll to a certain height.

i have managed to accomplish that by setting up a div class="logo-top" in the navbar, and a div class="logo-hero" inside the jumbotron, and i'm using append to change the parent class of the image (#logo) to move it from the jumbotron to the navbar and likewise and change its size accordingly

I have tried to append.animate with no success.

```<code>var moved = false;
var logo = $("#logo");
var logo1 = logo.clone();

$(window).scroll(function () {
    var vertical_position = 0;
    if (pageYOffset)//usual
        vertical_position = pageYOffset;
    else if (document.documentElement.clientHeight)//ie
        vertical_position = document.documentElement.scrollTop;
    else if (document.body)//ie quirks
        vertical_position = document.body.scrollTop;

    if (vertical_position > 120) {
        moveLogoUp(moved);
        moved = true;
    }
    else if (vertical_position < 120 && moved === true) {
        moveLogoDown(moved);
        moved = false;
    }
});

function moveLogoUp(moved) {
    if (!moved) {
        logo.animate({
            "width": 125
        }, "slow");
        logo1.css("visibility", "hidden");
        $(".logo-top").append(logo);
        $(".logo-hero").append(logo1);
    }
}

function moveLogoDown(moved) {
    if (moved) {
        $(".logo-hero").append(logo);
        logo.animate({
            "width": "20rem"
        }, "slow");
        logo1.remove();
        $(".logo-hero").append(logo);
        console.log("moveLogoDown done");
    }
}
</code>```

The problem is the animation are not "moving" but just resizing. how can i accomplish the "move" animation effect?

答:
Move? Did you mean from left to rigth? This u can to with "left"
e.g.

```<code>logo.animate({
    top: 400,
    width: 125,
    left: 100,
}, "slow");
</code>```

// update:
i´ve made a little example for all who can need somthing like this, just handle to your needs...

https://jsfiddle.net/o5hjrbcd/6/

Title: Animate moving an element using append

Body:
I want an element on the page to move from the Jumbotron to the navbar with a "moving" animation when you scroll to a certain height.

i have managed to accomplish that by setting up a div class="logo-top" in the navbar, and a div class="logo-hero" inside the jumbotron, and i'm using append to change the parent class of the image (#logo) to move it from the jumbotron to the navbar and likewise and change its size accordingly

I have tried to append.animate with no success.

var moved = false;
var logo = $("#logo");
var logo1 = logo.clone();

$(window).scroll(function () {
    var vertical_position = 0;
    if (pageYOffset)//usual
        vertical_position = pageYOffset;
    else if (document.documentElement.clientHeight)//ie
        vertical_position = document.documentElement.scrollTop;
    else if (document.body)//ie quirks
        vertical_position = document.body.scrollTop;

    if (vertical_position > 120) {
        moveLogoUp(moved);
        moved = true;
    }
    else if (vertical_position < 120 && moved === true) {
        moveLogoDown(moved);
        moved = false;
    }
});

function moveLogoUp(moved) {
    if (!moved) {
        logo.animate({
            "width": 125
        }, "slow");
        logo1.css("visibility", "hidden");
        $(".logo-top").append(logo);
        $(".logo-hero").append(logo1);
    }
}

function moveLogoDown(moved) {
    if (moved) {
        $(".logo-hero").append(logo);
        logo.animate({
            "width": "20rem"
        }, "slow");
        logo1.remove();
        $(".logo-hero").append(logo);
        console.log("moveLogoDown done");
    }
}

The problem is the animation are not "moving" but just resizing. how can i accomplish the "move" animation effect?

Body:
Move? Did you mean from left to rigth? This u can to with "left"
e.g.

logo.animate({
    top: 400,
    width: 125,
    left: 100,
}, "slow");

// update:
i´ve made a little example for all who can need somthing like this, just handle to your needs...

https://jsfiddle.net/o5hjrbcd/6/


问:
Enumerable.Repeat for reference type objects initialization
I have a question about Enumerable.Repeat function.

If I will have a class:

```<code>class A
{
//code
}
</code>```

And I will create an array, of that type objects:

```<code>A [] arr = new A[50];
</code>```

And next, I will want to initialize those objects, calling Enumerable.Repeat:

```<code>arr = Enumerable.Repeat(new A(), 50);
</code>```

Will those objects have the same address in memory?
If I will want to check their hash code, for example in that way:

```<code>bool theSameHashCode = questions[0].GetHashCode() == questions[1].GetHashCode();
</code>```

This will return me true, and if I will change one object properties, all other objects will change it too.

So my question is: is that properly way, to initialize reference type objects? If not, then what is a better way?

答:
When using the following code to create an array:

```<code>var foos = Enumerable.Repeat(new Foo(), 2).ToArray();
</code>```

The reason why each location in the array is the same is because you are passing an object, and not a function that creates an object, the code above is the same as:

```<code>var foo = new Foo();
var foos = Enumerable.Repeat(foo , 2).ToArray();
</code>```

The reason above also explains why using a Select statement, like in the code below, creates a new object for each entry, because you are passing a function that dictates how each object is created, rather than the object itself.

```<code>Enumerable.Range(1, 2).Select(i => new Foo()).ToArray();
</code>```

I would use a simple for loop to populate an array with new reference types.

Body:
I have a question about Enumerable.Repeat function.

If I will have a class:

class A
{
//code
}

And I will create an array, of that type objects:

A [] arr = new A[50];

And next, I will want to initialize those objects, calling Enumerable.Repeat:

arr = Enumerable.Repeat(new A(), 50);

Will those objects have the same address in memory?
If I will want to check their hash code, for example in that way:

bool theSameHashCode = questions[0].GetHashCode() == questions[1].GetHashCode();

This will return me true, and if I will change one object properties, all other objects will change it too.

So my question is: is that properly way, to initialize reference type objects? If not, then what is a better way?

Body:
When using the following code to create an array:

var foos = Enumerable.Repeat(new Foo(), 2).ToArray();

The reason why each location in the array is the same is because you are passing an object, and not a function that creates an object, the code above is the same as:

var foo = new Foo();
var foos = Enumerable.Repeat(foo , 2).ToArray();

The reason above also explains why using a Select statement, like in the code below, creates a new object for each entry, because you are passing a function that dictates how each object is created, rather than the object itself.

Enumerable.Range(1, 2).Select(i => new Foo()).ToArray();

I would use a simple for loop to populate an array with new reference types.


问:
Why am I being displayed "TypeError: a float is required"?
My main issue is this error being displayed:

```<code>TypeError: a float is required
</code>```

I haven't tried much as I don't really know what I'm doing, being very new to coding and all, so I would appreciate some patient advice on the matter.

```<code>from math import sqrt

n = raw_input('Type number here: ')

def square_root(n):
  """Returns the square root of a number."""
  square_rooted = sqrt(n)
  print "%d square rooted is %d." % (n, square_rooted)
  return square_rooted

square_root(n)
</code>```

I want to be able to type in a number and it display the square root of it.

答:
As mentioned above perhaps python3 is the better python version to be using if you are new but the python 2 solution would look like below. Where we use %f to indicate our number is a float. In addition on line 2 we wrap the raw_input() statement in a float() function. This allows the python interpreter to understand we expect a float value.

```<code>from math import sqrt

n =float(raw_input('Type number here: '))

def square_root(n):
  """Returns the square root of a number."""
  square_rooted = sqrt(n)
  print "%f square rooted is %f." % (n, square_rooted)
  return square_rooted

square_root(n)
</code>```

The python 3 version would be below just a few minor edits. The input line would now become input() not raw_input()... Also the print statement would use parentheses on the sides:

```<code>from math import sqrt

n =float(input('Type number here: '))

def square_root(n):
  """Returns the square root of a number."""
  square_rooted = sqrt(n)
  print("%f square rooted is %f." % (n, square_rooted))
  return square_rooted

square_root(n)
</code>```

Body:
My main issue is this error being displayed:

TypeError: a float is required

I haven't tried much as I don't really know what I'm doing, being very new to coding and all, so I would appreciate some patient advice on the matter.

from math import sqrt

n = raw_input('Type number here: ')

def square_root(n):
  """Returns the square root of a number."""
  square_rooted = sqrt(n)
  print "%d square rooted is %d." % (n, square_rooted)
  return square_rooted

square_root(n)

I want to be able to type in a number and it display the square root of it.

Body:
As mentioned above perhaps python3 is the better python version to be using if you are new but the python 2 solution would look like below. Where we use %f to indicate our number is a float. In addition on line 2 we wrap the raw_input() statement in a float() function. This allows the python interpreter to understand we expect a float value.

from math import sqrt

n =float(raw_input('Type number here: '))

def square_root(n):
  """Returns the square root of a number."""
  square_rooted = sqrt(n)
  print "%f square rooted is %f." % (n, square_rooted)
  return square_rooted

square_root(n)

The python 3 version would be below just a few minor edits. The input line would now become input() not raw_input()... Also the print statement would use parentheses on the sides:

from math import sqrt

n =float(input('Type number here: '))

def square_root(n):
  """Returns the square root of a number."""
  square_rooted = sqrt(n)
  print("%f square rooted is %f." % (n, square_rooted))
  return square_rooted

square_root(n)


问:
Why would one ever want to compile with -O2 instead of -O3
We usually compile with -O2 because -O3 would "trigger subtle bugs".

For our GCC version -O3 enables more aggressive inlining which would actually reveal bugs otherwise unnoticed (e.g. use of uninitialized values from functions taking them as reference arguments or out-of-bounds access for arrays). It seems to me this aggressive inlining also allows a more expressive way of coding with smaller functions and -funswitch-loops helps keeping variable definitions more local in loops.

Given that bugs in our code are orders of magnitude more likely than compiler bugs and that we use -Wall -Wextra without any issues what kind of bugs should we be looking for?

If it matters we use gcc-4.3.2. Compile time is not a major issue for us.

答:
Sometimes aggressive optimisation can break code just like you mentioned. If this is a project you are currently working on, then perhaps this is not a problem. However, if the code in question is legacy code that is fragile, poorly written, and not well-understood, then you want to take as few chances as possible.

Also, not all optimisations are formally proven. That means that they may alter the behaviour of programs in undesirable ways.

The best example I can think of is a Java one, but it should illustrate my point about optimisations in general.

It is common to have code like this

```<code> while( keepGoing ){
      doStuff();
 }
</code>```

Then value of keepGoing gets modified by another thread. Well one optimisation that the JVM will do, is see that keepGoing is not modified within the body of the loop, so it "elevates" it and checks before the loop, essentially transforming the code into:

```<code> if( keepGoing ){
      while( true ){
           doStuff();
      }
 }
</code>```

Which in a multi-threaded environment is not the same thing, but in a single-threaded it is. These are the kinds of things that can break with optimisations. This is a frequent source of "Heisenbugs".

PS- In Java the proper answer is the make keepGoing "volatile" so it cannot presume cached values and would do what you intend.

Body:
Sometimes aggressive optimisation can break code just like you mentioned. If this is a project you are currently working on, then perhaps this is not a problem. However, if the code in question is legacy code that is fragile, poorly written, and not well-understood, then you want to take as few chances as possible.

Also, not all optimisations are formally proven. That means that they may alter the behaviour of programs in undesirable ways.

The best example I can think of is a Java one, but it should illustrate my point about optimisations in general.

It is common to have code like this

 while( keepGoing ){
      doStuff();
 }

Then value of keepGoing gets modified by another thread. Well one optimisation that the JVM will do, is see that keepGoing is not modified within the body of the loop, so it "elevates" it and checks before the loop, essentially transforming the code into:

 if( keepGoing ){
      while( true ){
           doStuff();
      }
 }

Which in a multi-threaded environment is not the same thing, but in a single-threaded it is. These are the kinds of things that can break with optimisations. This is a frequent source of "Heisenbugs".

PS- In Java the proper answer is the make keepGoing "volatile" so it cannot presume cached values and would do what you intend.


问:
How to get the index of an numpy.ndarray
I would to print the images on index i but I get an error of only integer scalar arrays can be converted to a scalar index. How can I convert I to int for each iteration

I have tried replacing images[i] with images[n] it worked but not the result I want.

```<code>c = [1 1 1 0 1 2 2 3 4 1 3]
#c here is list of cluster labels obtained after Affinity propagation
num_clusters = len(set(c))
images = os.listdir(DIR_NAME)

for n in range(num_clusters):
   print("\n --- Images from cluster #%d ---" % n)
   for i in np.argwhere(c == n):
     if i != -1:
        print("Image %s" % images[i])
</code>```

I expect the output to be the name of the image, but I instead get TypeError: only integer scalar arrays can be converted to a scalar index that is because i is of type numpy.ndarray

答:
Look at the doc of np.argwhere, it does not return a list of integers, but a list of lists

x = array([[0, 1, 2], [3, 4, 5]])
np.argwhere(x>1)
>>> array([[0, 2], [1, 0], [1, 1], [1, 2]])

y = np.array([0, 1, 2, 3, 4, 6, 7])
np.argwhere(y>3)
>>> array([[4], [5], [6]])
```

so without knowing what your c looks like, I assume your i will be of the form np.array([[3]]) instead of an integer, and therefore your code fails. Print i for testing and extract (e.g. i[0][0] and a test that it is non-empty) the desired index first before you do i != -1.

Meta

It is best practise to post a minimal reconstructable example, i.e. other people should be able to copy-paste the code and run it. Moreover, if you post at least a couple lines of the traceback (instead of just the error), we would be able to tell where exactly the error is happening.

Body:
I would to print the images on index i but I get an error of only integer scalar arrays can be converted to a scalar index. How can I convert I to int for each iteration

I have tried replacing images[i] with images[n] it worked but not the result I want.

c = [1 1 1 0 1 2 2 3 4 1 3]
#c here is list of cluster labels obtained after Affinity propagation
num_clusters = len(set(c))
images = os.listdir(DIR_NAME)

for n in range(num_clusters):
   print("\n --- Images from cluster #%d ---" % n)
   for i in np.argwhere(c == n):
     if i != -1:
        print("Image %s" % images[i])

I expect the output to be the name of the image, but I instead get TypeError: only integer scalar arrays can be converted to a scalar index that is because i is of type numpy.ndarray

Body:
Look at the doc of np.argwhere, it does not return a list of integers, but a list of lists

x = array([[0, 1, 2], [3, 4, 5]])
np.argwhere(x>1)
>>> array([[0, 2], [1, 0], [1, 1], [1, 2]])

y = np.array([0, 1, 2, 3, 4, 6, 7])
np.argwhere(y>3)
>>> array([[4], [5], [6]])

so without knowing what your c looks like, I assume your i will be of the form np.array([[3]]) instead of an integer, and therefore your code fails. Print i for testing and extract (e.g. i[0][0] and a test that it is non-empty) the desired index first before you do i != -1.

Meta

It is best practise to post a minimal reconstructable example, i.e. other people should be able to copy-paste the code and run it. Moreover, if you post at least a couple lines of the traceback (instead of just the error), we would be able to tell where exactly the error is happening.


问:
Cant install allennlp with pip on mac
I am trying to install allennlp on my mac. I have tried installing macOS headers which solved the missing headers problem but now i am experiencing new problems.

The error when i run pip install allennlp:

```<code>Running setup.py bdist_wheel for jsonnet ... error
  Complete output from command /anaconda3/bin/python -u -c "import setuptools, tokenize;__file__='/private/var/folders/qf/jkn4v43j08xgst0r9yxyl0dc0000gn/T/pip-install-i4nyb384/jsonnet/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /private/var/folders/qf/jkn4v43j08xgst0r9yxyl0dc0000gn/T/pip-wheel-eof7cc6k --python-tag cp37:
  running bdist_wheel
  running build
  running build_ext
  x86_64-apple-darwin13.4.0-clang++ -c -march=core2 -mtune=haswell -mssse3 -ftree-vectorize -fPIC -fPIE -fstack-protector-strong -O2 -pipe -stdlib=libc++ -fvisibility-inlines-hidden -std=c++14 -fmessage-length=0 core/desugarer.cpp -o core/desugarer.o
  In file included from core/desugarer.cpp:17:
  In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/cassert:21:
  In file included from /Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/usr/include/assert.h:44:
  /Library/Developer/CommandLineTools/usr/include/c++/v1/stdlib.h:111:82: error: use of undeclared identifier 'labs'; did you mean 'abs'?
  inline _LIBCPP_INLINE_VISIBILITY long      abs(     long __x) _NOEXCEPT {return  labs(__x);}
                                                                                ^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/stdlib.h:111:44: note: 'abs' declared here
  inline _LIBCPP_INLINE_VISIBILITY long      abs(     long __x) _NOEXCEPT {return  labs(__x);}
                                             ^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/stdlib.h:113:81: error: use of undeclared identifier 'llabs'
  inline _LIBCPP_INLINE_VISIBILITY long long abs(long long __x) _NOEXCEPT {return llabs(__x);}
                                                                                ^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/stdlib.h:116:35: error: unknown type name 'ldiv_t'
  inline _LIBCPP_INLINE_VISIBILITY  ldiv_t div(     long __x,      long __y) _NOEXCEPT {return  ldiv(__x, __y);}
                                    ^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/stdlib.h:116:95: error: use of undeclared identifier 'ldiv'; did you mean 'div'?
  inline _LIBCPP_INLINE_VISIBILITY  ldiv_t div(     long __x,      long __y) _NOEXCEPT {return  ldiv(__x, __y);}
                                                                                ^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/stdlib.h:116:42: note: 'div' declared here
  inline _LIBCPP_INLINE_VISIBILITY  ldiv_t div(     long __x,      long __y) _NOEXCEPT {return  ldiv(__x, __y);}
                                           ^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/stdlib.h:118:34: error: unknown type name 'lldiv_t'
  inline _LIBCPP_INLINE_VISIBILITY lldiv_t div(long long __x, long long __y) _NOEXCEPT {return lldiv(__x, __y);}
                                   ^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/stdlib.h:118:94: error: use of undeclared identifier 'lldiv'
  inline _LIBCPP_INLINE_VISIBILITY lldiv_t div(long long __x, long long __y) _NOEXCEPT {return lldiv(__x, __y);}
                                                                                ^
  In file included from core/desugarer.cpp:19:
  In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/algorithm:642:
  In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/cstring:61:
  /Library/Developer/CommandLineTools/usr/include/c++/v1/string.h:74:64: error: use of undeclared identifier 'strchr'
  char* __libcpp_strchr(const char* __s, int __c) {return (char*)strchr(__s, __c);}
                                                                 ^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/string.h:81:75: error: use of undeclared identifier 'strpbrk'
  char* __libcpp_strpbrk(const char* __s1, const char* __s2) {return (char*)strpbrk(__s1, __s2);}
                                                                            ^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/string.h:88:65: error: use of undeclared identifier 'strrchr'; did you mean 'strchr'?
  char* __libcpp_strrchr(const char* __s, int __c) {return (char*)strrchr(__s, __c);}
                                                                  ^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/string.h:76:13: note: 'strchr' declared here
  const char* strchr(const char* __s, int __c) {return __libcpp_strchr(__s, __c);}
              ^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/string.h:95:76: error: use of undeclared identifier 'memchr'
  void* __libcpp_memchr(const void* __s, int __c, size_t __n) {return (void*)memchr(__s, __c, __n);}
                                                                             ^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/string.h:102:74: error: use of undeclared identifier 'strstr'; did you mean 'strchr'?
  char* __libcpp_strstr(const char* __s1, const char* __s2) {return (char*)strstr(__s1, __s2);}
                                                                           ^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/string.h:78:13: note: 'strchr' declared here
        char* strchr(      char* __s, int __c) {return __libcpp_strchr(__s, __c);}
              ^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/string.h:102:74: error: no matching function for call to 'strchr'
  char* __libcpp_strstr(const char* __s1, const char* __s2) {return (char*)strstr(__s1, __s2);}
                                                                           ^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/string.h:78:13: note: candidate disabled: <no message provided>
        char* strchr(      char* __s, int __c) {return __libcpp_strchr(__s, __c);}
              ^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/string.h:102:81: error: cannot initialize a parameter of type 'char *' with an lvalue of type 'const char *'
  char* __libcpp_strstr(const char* __s1, const char* __s2) {return (char*)strstr(__s1, __s2);}
                                                                                ^~~~
  /Library/Developer/CommandLineTools/usr/include/c++/v1/string.h:78:32: note: passing argument to parameter '__s' here
        char* strchr(      char* __s, int __c) {return __libcpp_strchr(__s, __c);}
                                 ^
  In file included from core/desugarer.cpp:19:
  In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/algorithm:642:
  /Library/Developer/CommandLineTools/usr/include/c++/v1/cstring:70:9: error: no member named 'memcpy' in the global namespace; did you mean 'memchr'?
  using ::memcpy;
        ~~^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/string.h:97:13: note: 'memchr' declared here
  const void* memchr(const void* __s, int __c, size_t __n) {return __libcpp_memchr(__s, __c, __n);}
              ^
  In file included from core/desugarer.cpp:19:
  In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/algorithm:642:
  /Library/Developer/CommandLineTools/usr/include/c++/v1/cstring:71:9: error: no member named 'memmove' in the global namespace
  using ::memmove;
        ~~^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/cstring:72:9: error: no member named 'strcpy' in the global namespace; did you mean 'strchr'?
  using ::strcpy;
        ~~^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/string.h:76:13: note: 'strchr' declared here
  const char* strchr(const char* __s, int __c) {return __libcpp_strchr(__s, __c);}
              ^
  In file included from core/desugarer.cpp:19:
  In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/algorithm:642:
  /Library/Developer/CommandLineTools/usr/include/c++/v1/cstring:73:9: error: no member named 'strncpy' in the global namespace
  using ::strncpy;
        ~~^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/cstring:74:9: error: no member named 'strcat' in the global namespace; did you mean 'strchr'?
  using ::strcat;
        ~~^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/string.h:76:13: note: 'strchr' declared here
  const char* strchr(const char* __s, int __c) {return __libcpp_strchr(__s, __c);}
              ^
  In file included from core/desugarer.cpp:19:
  In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/algorithm:642:
  /Library/Developer/CommandLineTools/usr/include/c++/v1/cstring:75:9: error: no member named 'strncat' in the global namespace
  using ::strncat;
        ~~^
  fatal error: too many errors emitted, stopping now [-ferror-limit=]
  20 errors generated.
  make: *** [Makefile:118: core/desugarer.o] Error 1
  Traceback (most recent call last):
    File "<string>", line 1, in <module>
    File "/private/var/folders/qf/jkn4v43j08xgst0r9yxyl0dc0000gn/T/pip-install-i4nyb384/jsonnet/setup.py", line 75, in <module>
      test_suite="python._jsonnet_test",
    File "/anaconda3/lib/python3.7/site-packages/setuptools/__init__.py", line 143, in setup
      return distutils.core.setup(**attrs)
    File "/anaconda3/lib/python3.7/distutils/core.py", line 148, in setup
      dist.run_commands()
    File "/anaconda3/lib/python3.7/distutils/dist.py", line 966, in run_commands
      self.run_command(cmd)
    File "/anaconda3/lib/python3.7/distutils/dist.py", line 985, in run_command
      cmd_obj.run()
    File "/anaconda3/lib/python3.7/site-packages/wheel/bdist_wheel.py", line 188, in run
      self.run_command('build')
    File "/anaconda3/lib/python3.7/distutils/cmd.py", line 313, in run_command
      self.distribution.run_command(command)
    File "/anaconda3/lib/python3.7/distutils/dist.py", line 985, in run_command
      cmd_obj.run()
    File "/anaconda3/lib/python3.7/distutils/command/build.py", line 135, in run
      self.run_command(cmd_name)
    File "/anaconda3/lib/python3.7/distutils/cmd.py", line 313, in run_command
      self.distribution.run_command(command)
    File "/anaconda3/lib/python3.7/distutils/dist.py", line 985, in run_command
      cmd_obj.run()
    File "/private/var/folders/qf/jkn4v43j08xgst0r9yxyl0dc0000gn/T/pip-install-i4nyb384/jsonnet/setup.py", line 54, in run
      raise Exception('Could not build %s' % (', '.join(LIB_OBJECTS)))
  Exception: Could not build core/desugarer.o, core/formatter.o, core/libjsonnet.o, core/lexer.o, core/parser.o, core/pass.o, core/static_analysis.o, core/string_utils.o, core/vm.o, third_party/md5/md5.o

  ----------------------------------------
  Failed building wheel for jsonnet
  Running setup.py clean for jsonnet
Failed to build jsonnet
</code>```

My compiler and gcc:

```<code>(base) Sakets-MacBook-Pro:usr saketkhandelwal$ gcc -v
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 10.0.1 (clang-1001.0.46.4)
Target: x86_64-apple-darwin18.5.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
(base) Sakets-MacBook-Pro:usr saketkhandelwal$ clang --version
clang version 4.0.1 (tags/RELEASE_401/final)
Target: x86_64-apple-darwin18.5.0
Thread model: posix
InstalledDir: /anaconda3/bin
</code>```

How do i fix this, i have tried reinstalling command line tools and package headers but still no luck.

答:
I suppose you can resolve this by updating to latest version of
anaconda

Try to install jsonnet separately using conda install -c
conda-forge jsonnet and then pip install allennlp

Please refer to this issue on allennlp github for more details :

Pip3 install failing on jsonnet

Title: Cant install allennlp with pip on mac

Body:
I am trying to install allennlp on my mac. I have tried installing macOS headers which solved the missing headers problem but now i am experiencing new problems.

The error when i run pip install allennlp:

Running setup.py bdist_wheel for jsonnet ... error
  Complete output from command /anaconda3/bin/python -u -c "import setuptools, tokenize;__file__='/private/var/folders/qf/jkn4v43j08xgst0r9yxyl0dc0000gn/T/pip-install-i4nyb384/jsonnet/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /private/var/folders/qf/jkn4v43j08xgst0r9yxyl0dc0000gn/T/pip-wheel-eof7cc6k --python-tag cp37:
  running bdist_wheel
  running build
  running build_ext
  x86_64-apple-darwin13.4.0-clang++ -c -march=core2 -mtune=haswell -mssse3 -ftree-vectorize -fPIC -fPIE -fstack-protector-strong -O2 -pipe -stdlib=libc++ -fvisibility-inlines-hidden -std=c++14 -fmessage-length=0 core/desugarer.cpp -o core/desugarer.o
  In file included from core/desugarer.cpp:17:
  In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/cassert:21:
  In file included from /Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/usr/include/assert.h:44:
  /Library/Developer/CommandLineTools/usr/include/c++/v1/stdlib.h:111:82: error: use of undeclared identifier 'labs'; did you mean 'abs'?
  inline _LIBCPP_INLINE_VISIBILITY long      abs(     long __x) _NOEXCEPT {return  labs(__x);}
                                                                                ^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/stdlib.h:111:44: note: 'abs' declared here
  inline _LIBCPP_INLINE_VISIBILITY long      abs(     long __x) _NOEXCEPT {return  labs(__x);}
                                             ^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/stdlib.h:113:81: error: use of undeclared identifier 'llabs'
  inline _LIBCPP_INLINE_VISIBILITY long long abs(long long __x) _NOEXCEPT {return llabs(__x);}
                                                                                ^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/stdlib.h:116:35: error: unknown type name 'ldiv_t'
  inline _LIBCPP_INLINE_VISIBILITY  ldiv_t div(     long __x,      long __y) _NOEXCEPT {return  ldiv(__x, __y);}
                                    ^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/stdlib.h:116:95: error: use of undeclared identifier 'ldiv'; did you mean 'div'?
  inline _LIBCPP_INLINE_VISIBILITY  ldiv_t div(     long __x,      long __y) _NOEXCEPT {return  ldiv(__x, __y);}
                                                                                ^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/stdlib.h:116:42: note: 'div' declared here
  inline _LIBCPP_INLINE_VISIBILITY  ldiv_t div(     long __x,      long __y) _NOEXCEPT {return  ldiv(__x, __y);}
                                           ^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/stdlib.h:118:34: error: unknown type name 'lldiv_t'
  inline _LIBCPP_INLINE_VISIBILITY lldiv_t div(long long __x, long long __y) _NOEXCEPT {return lldiv(__x, __y);}
                                   ^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/stdlib.h:118:94: error: use of undeclared identifier 'lldiv'
  inline _LIBCPP_INLINE_VISIBILITY lldiv_t div(long long __x, long long __y) _NOEXCEPT {return lldiv(__x, __y);}
                                                                                ^
  In file included from core/desugarer.cpp:19:
  In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/algorithm:642:
  In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/cstring:61:
  /Library/Developer/CommandLineTools/usr/include/c++/v1/string.h:74:64: error: use of undeclared identifier 'strchr'
  char* __libcpp_strchr(const char* __s, int __c) {return (char*)strchr(__s, __c);}
                                                                 ^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/string.h:81:75: error: use of undeclared identifier 'strpbrk'
  char* __libcpp_strpbrk(const char* __s1, const char* __s2) {return (char*)strpbrk(__s1, __s2);}
                                                                            ^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/string.h:88:65: error: use of undeclared identifier 'strrchr'; did you mean 'strchr'?
  char* __libcpp_strrchr(const char* __s, int __c) {return (char*)strrchr(__s, __c);}
                                                                  ^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/string.h:76:13: note: 'strchr' declared here
  const char* strchr(const char* __s, int __c) {return __libcpp_strchr(__s, __c);}
              ^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/string.h:95:76: error: use of undeclared identifier 'memchr'
  void* __libcpp_memchr(const void* __s, int __c, size_t __n) {return (void*)memchr(__s, __c, __n);}
                                                                             ^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/string.h:102:74: error: use of undeclared identifier 'strstr'; did you mean 'strchr'?
  char* __libcpp_strstr(const char* __s1, const char* __s2) {return (char*)strstr(__s1, __s2);}
                                                                           ^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/string.h:78:13: note: 'strchr' declared here
        char* strchr(      char* __s, int __c) {return __libcpp_strchr(__s, __c);}
              ^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/string.h:102:74: error: no matching function for call to 'strchr'
  char* __libcpp_strstr(const char* __s1, const char* __s2) {return (char*)strstr(__s1, __s2);}
                                                                           ^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/string.h:78:13: note: candidate disabled: <no message provided>
        char* strchr(      char* __s, int __c) {return __libcpp_strchr(__s, __c);}
              ^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/string.h:102:81: error: cannot initialize a parameter of type 'char *' with an lvalue of type 'const char *'
  char* __libcpp_strstr(const char* __s1, const char* __s2) {return (char*)strstr(__s1, __s2);}
                                                                                ^~~~
  /Library/Developer/CommandLineTools/usr/include/c++/v1/string.h:78:32: note: passing argument to parameter '__s' here
        char* strchr(      char* __s, int __c) {return __libcpp_strchr(__s, __c);}
                                 ^
  In file included from core/desugarer.cpp:19:
  In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/algorithm:642:
  /Library/Developer/CommandLineTools/usr/include/c++/v1/cstring:70:9: error: no member named 'memcpy' in the global namespace; did you mean 'memchr'?
  using ::memcpy;
        ~~^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/string.h:97:13: note: 'memchr' declared here
  const void* memchr(const void* __s, int __c, size_t __n) {return __libcpp_memchr(__s, __c, __n);}
              ^
  In file included from core/desugarer.cpp:19:
  In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/algorithm:642:
  /Library/Developer/CommandLineTools/usr/include/c++/v1/cstring:71:9: error: no member named 'memmove' in the global namespace
  using ::memmove;
        ~~^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/cstring:72:9: error: no member named 'strcpy' in the global namespace; did you mean 'strchr'?
  using ::strcpy;
        ~~^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/string.h:76:13: note: 'strchr' declared here
  const char* strchr(const char* __s, int __c) {return __libcpp_strchr(__s, __c);}
              ^
  In file included from core/desugarer.cpp:19:
  In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/algorithm:642:
  /Library/Developer/CommandLineTools/usr/include/c++/v1/cstring:73:9: error: no member named 'strncpy' in the global namespace
  using ::strncpy;
        ~~^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/cstring:74:9: error: no member named 'strcat' in the global namespace; did you mean 'strchr'?
  using ::strcat;
        ~~^
  /Library/Developer/CommandLineTools/usr/include/c++/v1/string.h:76:13: note: 'strchr' declared here
  const char* strchr(const char* __s, int __c) {return __libcpp_strchr(__s, __c);}
              ^
  In file included from core/desugarer.cpp:19:
  In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/algorithm:642:
  /Library/Developer/CommandLineTools/usr/include/c++/v1/cstring:75:9: error: no member named 'strncat' in the global namespace
  using ::strncat;
        ~~^
  fatal error: too many errors emitted, stopping now [-ferror-limit=]
  20 errors generated.
  make: *** [Makefile:118: core/desugarer.o] Error 1
  Traceback (most recent call last):
    File "<string>", line 1, in <module>
    File "/private/var/folders/qf/jkn4v43j08xgst0r9yxyl0dc0000gn/T/pip-install-i4nyb384/jsonnet/setup.py", line 75, in <module>
      test_suite="python._jsonnet_test",
    File "/anaconda3/lib/python3.7/site-packages/setuptools/__init__.py", line 143, in setup
      return distutils.core.setup(**attrs)
    File "/anaconda3/lib/python3.7/distutils/core.py", line 148, in setup
      dist.run_commands()
    File "/anaconda3/lib/python3.7/distutils/dist.py", line 966, in run_commands
      self.run_command(cmd)
    File "/anaconda3/lib/python3.7/distutils/dist.py", line 985, in run_command
      cmd_obj.run()
    File "/anaconda3/lib/python3.7/site-packages/wheel/bdist_wheel.py", line 188, in run
      self.run_command('build')
    File "/anaconda3/lib/python3.7/distutils/cmd.py", line 313, in run_command
      self.distribution.run_command(command)
    File "/anaconda3/lib/python3.7/distutils/dist.py", line 985, in run_command
      cmd_obj.run()
    File "/anaconda3/lib/python3.7/distutils/command/build.py", line 135, in run
      self.run_command(cmd_name)
    File "/anaconda3/lib/python3.7/distutils/cmd.py", line 313, in run_command
      self.distribution.run_command(command)
    File "/anaconda3/lib/python3.7/distutils/dist.py", line 985, in run_command
      cmd_obj.run()
    File "/private/var/folders/qf/jkn4v43j08xgst0r9yxyl0dc0000gn/T/pip-install-i4nyb384/jsonnet/setup.py", line 54, in run
      raise Exception('Could not build %s' % (', '.join(LIB_OBJECTS)))
  Exception: Could not build core/desugarer.o, core/formatter.o, core/libjsonnet.o, core/lexer.o, core/parser.o, core/pass.o, core/static_analysis.o, core/string_utils.o, core/vm.o, third_party/md5/md5.o

  ----------------------------------------
  Failed building wheel for jsonnet
  Running setup.py clean for jsonnet
Failed to build jsonnet

My compiler and gcc:

(base) Sakets-MacBook-Pro:usr saketkhandelwal$ gcc -v
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 10.0.1 (clang-1001.0.46.4)
Target: x86_64-apple-darwin18.5.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
(base) Sakets-MacBook-Pro:usr saketkhandelwal$ clang --version
clang version 4.0.1 (tags/RELEASE_401/final)
Target: x86_64-apple-darwin18.5.0
Thread model: posix
InstalledDir: /anaconda3/bin

How do i fix this, i have tried reinstalling command line tools and package headers but still no luck.


问:
JavaFX line chart change color shape
I have this window:

```<code>@Override
public void start(Stage primaryStage){

    NumberAxis xAxis = new NumberAxis(1960, 2020, 10);
    xAxis.setLabel("Years");

    NumberAxis yAxis = new NumberAxis(0, 350, 50);
    yAxis.setLabel("No.of schools");

    LineChart<Number, Number> lineChart = new LineChart<>(xAxis, yAxis);
    lineChart.setTitle("Chart");

    XYChart.Series<Number, Number> series = new XYChart.Series<>();
    series.setName("No of schools in an year");
    Platform.runLater(() ->
        series.getNode().lookup(".chart-series-line").setStyle("-fx-stroke: black;")
    );

    series.getData().add(new XYChart.Data<>(1970, 15));
    series.getData().add(new XYChart.Data<>(1980, 30));
    series.getData().add(new XYChart.Data<>(1990, 60));
    series.getData().add(new XYChart.Data<>(2000, 120));
    series.getData().add(new XYChart.Data<>(2013, 240));
    series.getData().add(new XYChart.Data<>(2014, 300));

    lineChart.getData().add(series);

    var scene = new Scene(lineChart);

    primaryStage.setScene(scene);
    primaryStage.show();

}
</code>```

This is how it looks:

I want to change the color of series, but what I can achieve is to change color of line, but shape not.

How I can change the color of shape?

答:
I would suggest using CSS. The key here is looking up all the nodes associated with a series and changing the color of the nodes. The first series is .series0.

Key Code:

```<code>Set<Node> nodes = lineChart.lookupAll(".series" + 0);
for (Node n : nodes) {
    n.setStyle("-fx-background-color: black, white;\n"
            + "    -fx-background-insets: 0, 2;\n"
            + "    -fx-background-radius: 5px;\n"
            + "    -fx-padding: 5px;");
}
</code>```

Full Code

```<code>import java.util.Set;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.stage.Stage;

public class ScatterChartSample extends Application {

    @Override
    public void start(Stage stage) {
        NumberAxis xAxis = new NumberAxis(1960, 2020, 10);
        xAxis.setLabel("Years");

        NumberAxis yAxis = new NumberAxis(0, 350, 50);
        yAxis.setLabel("No.of schools");

        LineChart<Number, Number> lineChart = new LineChart<>(xAxis, yAxis);
        lineChart.setTitle("Chart");

        XYChart.Series<Number, Number> series = new XYChart.Series<>();
        series.setName("No of schools in an year");
        Platform.runLater(()
                -> {

            Set<Node> nodes = lineChart.lookupAll(".series" + 0);
            for (Node n : nodes) {
                n.setStyle("-fx-background-color: black, white;\n"
                        + "    -fx-background-insets: 0, 2;\n"
                        + "    -fx-background-radius: 5px;\n"
                        + "    -fx-padding: 5px;");
            }

            series.getNode().lookup(".chart-series-line").setStyle("-fx-stroke: black;");
        });

        series.getData().add(new XYChart.Data<>(1970, 15));
        series.getData().add(new XYChart.Data<>(1980, 30));
        series.getData().add(new XYChart.Data<>(1990, 60));
        series.getData().add(new XYChart.Data<>(2000, 120));
        series.getData().add(new XYChart.Data<>(2013, 240));
        series.getData().add(new XYChart.Data<>(2014, 300));

        lineChart.getData().add(series);

        var scene = new Scene(lineChart);

        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

Update: Try this!

```<code>for (Data<Number, Number> entry : series.getData()) {
    entry.getNode().setStyle("-fx-background-color: black, white;\n"
        + "    -fx-background-insets: 0, 2;\n"
        + "    -fx-background-radius: 5px;\n"
        + "    -fx-padding: 5px;");
}
</code>```

Title: JavaFX line chart change color shape

Body:
I have this window:

@Override
public void start(Stage primaryStage){

    NumberAxis xAxis = new NumberAxis(1960, 2020, 10);
    xAxis.setLabel("Years");

    NumberAxis yAxis = new NumberAxis(0, 350, 50);
    yAxis.setLabel("No.of schools");

    LineChart<Number, Number> lineChart = new LineChart<>(xAxis, yAxis);
    lineChart.setTitle("Chart");

    XYChart.Series<Number, Number> series = new XYChart.Series<>();
    series.setName("No of schools in an year");
    Platform.runLater(() ->
        series.getNode().lookup(".chart-series-line").setStyle("-fx-stroke: black;")
    );

    series.getData().add(new XYChart.Data<>(1970, 15));
    series.getData().add(new XYChart.Data<>(1980, 30));
    series.getData().add(new XYChart.Data<>(1990, 60));
    series.getData().add(new XYChart.Data<>(2000, 120));
    series.getData().add(new XYChart.Data<>(2013, 240));
    series.getData().add(new XYChart.Data<>(2014, 300));

    lineChart.getData().add(series);

    var scene = new Scene(lineChart);

    primaryStage.setScene(scene);
    primaryStage.show();

}

This is how it looks:

I want to change the color of series, but what I can achieve is to change color of line, but shape not.

How I can change the color of shape?

Body:
I would suggest using CSS. The key here is looking up all the nodes associated with a series and changing the color of the nodes. The first series is .series0.

Key Code:

Set<Node> nodes = lineChart.lookupAll(".series" + 0);
for (Node n : nodes) {
    n.setStyle("-fx-background-color: black, white;\n"
            + "    -fx-background-insets: 0, 2;\n"
            + "    -fx-background-radius: 5px;\n"
            + "    -fx-padding: 5px;");
}

Full Code

import java.util.Set;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.stage.Stage;

public class ScatterChartSample extends Application {

    @Override
    public void start(Stage stage) {
        NumberAxis xAxis = new NumberAxis(1960, 2020, 10);
        xAxis.setLabel("Years");

        NumberAxis yAxis = new NumberAxis(0, 350, 50);
        yAxis.setLabel("No.of schools");

        LineChart<Number, Number> lineChart = new LineChart<>(xAxis, yAxis);
        lineChart.setTitle("Chart");

        XYChart.Series<Number, Number> series = new XYChart.Series<>();
        series.setName("No of schools in an year");
        Platform.runLater(()
                -> {

            Set<Node> nodes = lineChart.lookupAll(".series" + 0);
            for (Node n : nodes) {
                n.setStyle("-fx-background-color: black, white;\n"
                        + "    -fx-background-insets: 0, 2;\n"
                        + "    -fx-background-radius: 5px;\n"
                        + "    -fx-padding: 5px;");
            }

            series.getNode().lookup(".chart-series-line").setStyle("-fx-stroke: black;");
        });

        series.getData().add(new XYChart.Data<>(1970, 15));
        series.getData().add(new XYChart.Data<>(1980, 30));
        series.getData().add(new XYChart.Data<>(1990, 60));
        series.getData().add(new XYChart.Data<>(2000, 120));
        series.getData().add(new XYChart.Data<>(2013, 240));
        series.getData().add(new XYChart.Data<>(2014, 300));

        lineChart.getData().add(series);

        var scene = new Scene(lineChart);

        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Update: Try this!

for (Data<Number, Number> entry : series.getData()) {
    entry.getNode().setStyle("-fx-background-color: black, white;\n"
        + "    -fx-background-insets: 0, 2;\n"
        + "    -fx-background-radius: 5px;\n"
        + "    -fx-padding: 5px;");
}


问:
Making nginx check parameter in url
I want to check if a parameter is present in a url in nginx and then rewrite.How can i do that?

For e.g if url is http://website.com/?mobile then redirect user to http://m.website.com

答:
If you know you have only 1 parameter {{variable}} to switch, you can detect if exist like this

```<code>if ($request_uri ~ '\?{{variable}}') {
    ...
}
</code>```

for example

```<code>if ($request_uri ~ '\?mobile') {
    return 302 https://m.example.com;
}
</code>```

Also I suggest consider use this redirection

http://{{domain}}.{{tld}}/mobile -> http://m.{{domain}}.{{tld}}

```<code>location ~ '/mobile'
    return 301 'https://m.{{domain}}.{{tld}}';
}
</code>```

for example

```<code>location ~ '/mobile'
    return 301 'https://m.example.com';
}
</code>```

Title: Making nginx check parameter in url

Body:
If you know you have only 1 parameter {{variable}} to switch, you can detect if exist like this

if ($request_uri ~ '\?{{variable}}') {
    ...
}

for example

if ($request_uri ~ '\?mobile') {
    return 302 https://m.example.com;
}

Also I suggest consider use this redirection

http://{{domain}}.{{tld}}/mobile -> http://m.{{domain}}.{{tld}}

location ~ '/mobile'
    return 301 'https://m.{{domain}}.{{tld}}';
}

for example

location ~ '/mobile'
    return 301 'https://m.example.com';
}