问:
App crashes when when back button is pressed (Android Studio)
I am programming an android app in Android Studio using a thread in a fragment to graph 100 random values, but when the back button is pressed before all the values are graphed the app crashes.

Can somebody tell me how can I stop the thread when the back button is pressed.

```<code>public class fragment_Usuario_Mediciones extends Fragment{
//variables para grafica
private static final Random RANDOM= new Random();
private LineGraphSeries<DataPoint> series;
private int x = 0;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_usuario_mediciones,container,false);

    //instancia del GraphView
    GraphView graph = (GraphView) rootView.findViewById(R.id.graphView);

    //datos
    series = new LineGraphSeries<DataPoint>();
    graph.addSeries(series);

    Viewport viewport = graph.getViewport();
    viewport.setXAxisBoundsManual(true);
    viewport.setMinX(0);
    viewport.setMaxX(100);
    viewport.setScrollable(true);

    return rootView;
}

@Override
public void onResume() {
    super.onResume();
    //Simulacion en tiempo real con hilo
    new Thread(new Runnable() {
        @Override
        public void run() {
            //añade 100 nuevas entradas

            for (int i=0;i<100;i++){
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        AniadirEntrada();
                    }
                });
                //consumir pulsos de reloj
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    //manejar el error
                    e.printStackTrace();
                }

            }
        }
    }).start();
}

private void AniadirEntrada()
{
    series.appendData(new DataPoint(x++,RANDOM.nextDouble()*10d),true,100);
}

public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if(keyCode == KeyEvent.KEYCODE_BACK)
    {
    //    getActivity().finish();
        return true;
    }
    return false;

}
</code>```

}

答:
You can fetch data using AsyncTask like this:

```<code>private class fetchData extends AsyncTask<URL, Integer, Long> {

     protected Long doInBackground(URL... urls) {
        // your code here
         return someValue;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         // update the UI here
     }
 }
</code>```

Further, you can enhance the whole code using callbacks.

Body:
I am programming an android app in Android Studio using a thread in a fragment to graph 100 random values, but when the back button is pressed before all the values are graphed the app crashes.

Can somebody tell me how can I stop the thread when the back button is pressed.

public class fragment_Usuario_Mediciones extends Fragment{
//variables para grafica
private static final Random RANDOM= new Random();
private LineGraphSeries<DataPoint> series;
private int x = 0;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_usuario_mediciones,container,false);

    //instancia del GraphView
    GraphView graph = (GraphView) rootView.findViewById(R.id.graphView);

    //datos
    series = new LineGraphSeries<DataPoint>();
    graph.addSeries(series);

    Viewport viewport = graph.getViewport();
    viewport.setXAxisBoundsManual(true);
    viewport.setMinX(0);
    viewport.setMaxX(100);
    viewport.setScrollable(true);

    return rootView;
}

@Override
public void onResume() {
    super.onResume();
    //Simulacion en tiempo real con hilo
    new Thread(new Runnable() {
        @Override
        public void run() {
            //añade 100 nuevas entradas

            for (int i=0;i<100;i++){
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        AniadirEntrada();
                    }
                });
                //consumir pulsos de reloj
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    //manejar el error
                    e.printStackTrace();
                }

            }
        }
    }).start();
}

private void AniadirEntrada()
{
    series.appendData(new DataPoint(x++,RANDOM.nextDouble()*10d),true,100);
}

public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if(keyCode == KeyEvent.KEYCODE_BACK)
    {
    //    getActivity().finish();
        return true;
    }
    return false;

}

}

Body:
You can fetch data using AsyncTask like this:

private class fetchData extends AsyncTask<URL, Integer, Long> {

     protected Long doInBackground(URL... urls) {
        // your code here
         return someValue;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         // update the UI here
     }
 }

Further, you can enhance the whole code using callbacks.


来源: stackexchange

问:
Chaining Mysql Queries for Insertion
I am trying to insert a row only if two conditions are true. I want to do this in one statement. My table looks like:

```<code>             [Table]
id, userId, locationId, type, timestamp
---------------------------------------
1   5   19   0   2017-03-28 03:05:48
2   5   19   1   2017-03-29 00:57:57
</code>```

Is there a way to perform a sql that:

LIRFU = Last Inserted Row For User = SELECT * FROM Table WHERE userId = $userId ORDER BY timestamp DESC LIMIT 1.

Inserts a row ($userId, $locationId, 1) if LIRFU.type = 0.

Inserts a row ($userId, $locationId, 0) if LIRFU.type = 1 AND LIRFU.locationId != $locationId.

答:
Let's call your table, User_Types.

Here's the statement to insert a row with sample data (5,19,1) if LIRFU.type = 0:

```<code>INSERT INTO User_Types (userId, locationId, type)
SELECT @userId:=5, 19, 1 from dual
WHERE (SELECT type FROM User_Types WHERE userId = @userId ORDER BY timestamp DESC LIMIT 1) = 0;
</code>```

You can make this into a prepared statement in PHP by replacing the data with ?.

```<code>$stmt = $db->prepare("INSERT INTO User_Types (userId, locationId, type) SELECT @userId:=?, ?, 1 from dual WHERE (SELECT type FROM User_Types WHERE userId = @userId ORDER BY timestamp DESC LIMIT 1) = 0");

$stmt->bind_param('ii', $user_id, $location_id);
//if LIRFU.type = 0

$stmt->execute();
</code>```

Here's the statement to insert a row with sample data (5,19,0) if LIRFU.type = 1 AND LIRFU.locationId != 19:

```<code>INSERT INTO User_Types (userId, locationId, type)
SELECT @userId:=5, @locationId:=19, 0 from dual
WHERE (SELECT type FROM User_Types WHERE userId = @userId ORDER BY timestamp DESC LIMIT 1) = 1
AND   (SELECT locationId FROM User_Types WHERE userId = @userId ORDER BY timestamp DESC LIMIT 1) <> @locationId;
</code>```

The same idea when it is prepared in PHP:

```<code>$stmt = $db->prepare("INSERT INTO User_Types (userId, locationId, type) SELECT @userId:=?, @locationId:=?, 0 from dual WHERE (SELECT type FROM User_Types WHERE userId = @userId ORDER BY timestamp DESC LIMIT 1) = 1 AND (SELECT locationId FROM User_Types WHERE userId = @userId ORDER BY timestamp DESC LIMIT 1) <> @locationId");

$stmt->bind_param('ii', $user_id, $location_id);
//if LIRFU.type = 1 and LIRFU.locationId != $location_id

$stmt->execute();
</code>```

ContentLicense: CC BY-SA 3.0

Title: Chaining Mysql Queries for Insertion

Body:
I am trying to insert a row only if two conditions are true. I want to do this in one statement. My table looks like:

             [Table]
id, userId, locationId, type, timestamp
---------------------------------------
1   5   19   0   2017-03-28 03:05:48
2   5   19   1   2017-03-29 00:57:57

Is there a way to perform a sql that:

LIRFU = Last Inserted Row For User = SELECT * FROM Table WHERE userId = $userId ORDER BY timestamp DESC LIMIT 1.

Inserts a row ($userId, $locationId, 1) if LIRFU.type = 0.

Inserts a row ($userId, $locationId, 0) if LIRFU.type = 1 AND LIRFU.locationId != $locationId.

Body:
Let's call your table, User_Types.

Here's the statement to insert a row with sample data (5,19,1) if LIRFU.type = 0:

INSERT INTO User_Types (userId, locationId, type)
SELECT @userId:=5, 19, 1 from dual
WHERE (SELECT type FROM User_Types WHERE userId = @userId ORDER BY timestamp DESC LIMIT 1) = 0;

You can make this into a prepared statement in PHP by replacing the data with ?.

$stmt = $db->prepare("INSERT INTO User_Types (userId, locationId, type) SELECT @userId:=?, ?, 1 from dual WHERE (SELECT type FROM User_Types WHERE userId = @userId ORDER BY timestamp DESC LIMIT 1) = 0");

$stmt->bind_param('ii', $user_id, $location_id);
//if LIRFU.type = 0

$stmt->execute();

Here's the statement to insert a row with sample data (5,19,0) if LIRFU.type = 1 AND LIRFU.locationId != 19:

INSERT INTO User_Types (userId, locationId, type)
SELECT @userId:=5, @locationId:=19, 0 from dual
WHERE (SELECT type FROM User_Types WHERE userId = @userId ORDER BY timestamp DESC LIMIT 1) = 1
AND   (SELECT locationId FROM User_Types WHERE userId = @userId ORDER BY timestamp DESC LIMIT 1) <> @locationId;

The same idea when it is prepared in PHP:

$stmt = $db->prepare("INSERT INTO User_Types (userId, locationId, type) SELECT @userId:=?, @locationId:=?, 0 from dual WHERE (SELECT type FROM User_Types WHERE userId = @userId ORDER BY timestamp DESC LIMIT 1) = 1 AND (SELECT locationId FROM User_Types WHERE userId = @userId ORDER BY timestamp DESC LIMIT 1) <> @locationId");

$stmt->bind_param('ii', $user_id, $location_id);
//if LIRFU.type = 1 and LIRFU.locationId != $location_id

$stmt->execute();


问:
informatica min and max value dynamically fetch from database
I have a requirement to fetch records from a table in oracle database with the id in search condition .I need to take min and max value of the id and need to compare against another table and store the missing id .This need to be done on a daily basis and the current run max value will become the min value of next day run.

Kindly let me know how to achieve the get the min and max value as parameter in Informatica and assign on  daily basis

Thanks

答: same topic was discussed here  https://network.informatica.com/thread/38783 where the following detailed blog http://informatica-kareem.blogspot.in/2012/11/change-data-capture-cdc.html outlines all your options (incuding saved session variables). For future reference, what you're referring to is commonly  called incremental load and CDC.</p>


问:
Hibernate: Multiple FK relationships
I'm kinda stuck defining a Hibernate Entity:

Assuming I have the following two tables in a database:

(A)

fromCompany

toCompany

viaCompany

(B)

companyID (PK)

description

where the elements of (A) point to the primary key of (B); so there are 3 one-to-one relationships between the FKs and the PK.
I assume 3 OneToOne statements with different mappedBy conditions are not the way to go, mh? Has been a long day - I probably just don't get it ;)

Thanks for your help!

答:
You certainly can do this with one-to-one relationships.  You would have three Company objects in your A class, and appropriate mappings.

It would help if we could see the code and the hibernate mappings.

ContentLicense: CC BY-SA 2.5

Title: Hibernate: Multiple FK relationships


问:
CSS4 solution for transition 0 to auto?
I was going through the CSS4 articles but I was not able to find it.

In CSS3, when transitions were introduced, one of the popular issues was transitioning height from 0 to auto without having to use JavaScript.

We did have the max-height solution, but that will only have an accurate transition-duration for that height. If auto of that element is say double the max-height then we will see a noticeable jump.

Does CSS4 provide a solution for this 0 to auto issue? Especially for height/width?

答:
there is great article about this on css trick https://css-tricks.com/using-css-transitions-auto-dimensions/

i hope this will help you.

Title: CSS4 solution for transition 0 to auto?


问:
routerLink not working in innerHTML with angular2&4.0.0+
I'm using:[angular-cli=1.0.0+ node=7.7.4+ angular=4.0.0+]
in my html page i use code

ts: htmlWrite=''
but when i use 'npm start' start my serve,in html i just see ,there is no link with '/user/list'.
I search answer much about this and I tried much times but still failed,could you tell me how to solve this ? by using NgComponentOutlet? or others? please tell me the detail.thanks. PS:angular2(4.0.0+)

答:
You don't need the href in your  tag when using the routerlink.

Before

```<code><a href="#" routerLink="/user/list"></a>
</code>```

After

```<code><a routerLink="/user/list"></a>
</code>```

Body:
You don't need the href in your <a> tag when using the routerlink.

Before

<a href="#" routerLink="/user/list"></a>

After

<a routerLink="/user/list"></a>


问:
Run Command after generation step in CMake
I have a command line tool that should be run after CMake created my .sln-file. Is there any way to do that using CMake?

Using execute_process(COMMAND ..) at the end of the CMakeLists.txt does not help because this is executed after the Configure step, however, the .sln-file is created in the generation step.

Thanks a lot!

答:
A rather horrifying way to do it is by calling cmake from cmake and doing the post-generate stuff on the way out of the parent script.

```<code>option(RECURSIVE_GENERATE "Recursive call to cmake" OFF)

if(NOT RECURSIVE_GENERATE)
    message(STATUS "Recursive generate started")
    execute_process(COMMAND ${CMAKE_COMMAND}
        -G "${CMAKE_GENERATOR}"
        -T "${CMAKE_GENERATOR_TOOLSET}"
        -A "${CMAKE_GENERATOR_PLATFORM}"
        -DRECURSIVE_GENERATE:BOOL=ON
        ${CMAKE_SOURCE_DIR})
    message(STATUS "Recursive generate done")

    # your post-generate steps here

    # exit without doing anything else, since it already happened
    return()
endif()

# The rest of the script is only processed by the executed cmake, as it
# sees RECURSIVE_GENERATE true

# all your normal configuration, targets, etc go here
</code>```

This method doesn't work well if you need to invoke cmake with various combinations of command line options like "-DTHIS -DTHAT", but is probably acceptable for many projects. It works fine with the persistently cached variables, including all the cmake compiler detection when they're initially generated.

Body:
A rather horrifying way to do it is by calling cmake from cmake and doing the post-generate stuff on the way out of the parent script.

option(RECURSIVE_GENERATE "Recursive call to cmake" OFF)

if(NOT RECURSIVE_GENERATE)
    message(STATUS "Recursive generate started")
    execute_process(COMMAND ${CMAKE_COMMAND}
        -G "${CMAKE_GENERATOR}"
        -T "${CMAKE_GENERATOR_TOOLSET}"
        -A "${CMAKE_GENERATOR_PLATFORM}"
        -DRECURSIVE_GENERATE:BOOL=ON
        ${CMAKE_SOURCE_DIR})
    message(STATUS "Recursive generate done")

    # your post-generate steps here

    # exit without doing anything else, since it already happened
    return()
endif()

# The rest of the script is only processed by the executed cmake, as it
# sees RECURSIVE_GENERATE true

# all your normal configuration, targets, etc go here

This method doesn't work well if you need to invoke cmake with various combinations of command line options like "-DTHIS -DTHAT", but is probably acceptable for many projects. It works fine with the persistently cached variables, including all the cmake compiler detection when they're initially generated.


问:
How to create image or pdf from html having css filters?
I want to create an image or pdf from a html. The html consist of images with css filters like sepia, gray-scale etc. So it would be better if anyone have worked on that.

```<code><img class="dj_rot" src="/940/images/photos.png" style="filter: sepia(1);">
<img class="dj_rot" src="/940/images/photos.png" style="filter: grayscale(1);">
</code>```

Thanks
Deepak

答:
You could use "html2canvas" is a opensource script that allows you to take "screenshots" of webpages or parts of it

https://html2canvas.hertzen.com/

You will see many examples of how to use in the same webpage

If you want to create a PDF you could use a jsPDF is another option based on Javascript

http://rawgit.com/MrRio/jsPDF/master/

Also you will find the documentation with examples and source code

If it is not enough you could use and API that allow that, You only need to establish a URL and then you receive the image

```<code>https://screenshotlayer.com/
</code>```

Screenshotlayer (Free, Powerful Screenshot API)
url2png (Screenshots as a Service)
urlbox.io (Website Screenshot as a Service API urlbox)
screenshotmachine (Screenshot machine)
Browshot (Service for real time website screenshots)

You could review a link with more information
What's the best website screenshot capture API?

```<code>https://www.quora.com/Whats-the-best-website-screenshot-capture-API
</code>```

Body:
I want to create an image or pdf from a html. The html consist of images with css filters like sepia, gray-scale etc. So it would be better if anyone have worked on that.

Thanks
Deepak

Body:
You could use "html2canvas" is a opensource script that allows you to take "screenshots" of webpages or parts of it

https://html2canvas.hertzen.com/

You will see many examples of how to use in the same webpage

If you want to create a PDF you could use a jsPDF is another option based on Javascript

http://rawgit.com/MrRio/jsPDF/master/

Also you will find the documentation with examples and source code

If it is not enough you could use and API that allow that, You only need to establish a URL and then you receive the image

https://screenshotlayer.com/

Screenshotlayer (Free, Powerful Screenshot API)
url2png (Screenshots as a Service)
urlbox.io (Website Screenshot as a Service API urlbox)
screenshotmachine (Screenshot machine)
Browshot (Service for real time website screenshots)

You could review a link with more information
What's the best website screenshot capture API?

https://www.quora.com/Whats-the-best-website-screenshot-capture-API


问:
Do not update or delete data from the database
I have doman class:

```<code>package testgrails12
class Teams {
String name
static mapping = {
version false
}
static constraints = {
name nullable: true
}
}
</code>```

I'm trying to delete or update data from a table In my controller:

```<code>def team = Teams.get(1)
team.delete()
</code>```

Update:

```<code>team.name = '123'
team.save()
</code>```

I do not get a result either in the first or in the second cases. Also I do not get any errors. I'm confused. It just does not work. I see the result in the database.

答: for committing result to database use special method of session - flush()</p>

Body:
I have doman class:

package testgrails12
class Teams {
String name
static mapping = {
version false
}
static constraints = {
name nullable: true
}
}

I'm trying to delete or update data from a table In my controller:

def team = Teams.get(1)
team.delete()

Update:

team.name = '123'
team.save()

I do not get a result either in the first or in the second cases. Also I do not get any errors. I'm confused. It just does not work. I see the result in the database.


问:
C# - Is it possible (and how) to perform XSL transformations using SgmlReader
I needed to transform the contents of an HTML web page using XSLT
. Hence I used SgmlReader and wrote the snippet shown below (I
thought, in the end, it's an XmlReader too ...)

```<code>XmlReader xslr = XmlReader.Create(new StringReader(
    "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
    "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">" +
    "<xsl:output method=\"xml\" encoding=\"UTF-8\" version=\"1.0\" />" +
    "<xsl:template match=\"/\">" +
    "<XXX xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><xsl:value-of select=\"count(//br)\" /></XXX>" +
    "</xsl:template>" +
    "</xsl:stylesheet>"));

XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(xslr);

using (SgmlReader html = new SgmlReader())
{
    StringBuilder sb = new StringBuilder();
    using (TextWriter sw = new StringWriter(sb))
    using (XmlWriter xw = new XmlTextWriter(sw))
    {
        html.InputStream = new StringReader(Resources.html_orig);
        html.DocType = "HTML";

        try
        {
            xslt.Transform(html, xw);
            string output = sb.ToString();
            System.Console.WriteLine(output);
        }
        catch (Exception exc)
        {
            System.Console.WriteLine("{0} : {1}", exc.GetType().Name, exc.Message);
            System.Console.WriteLine(exc.StackTrace);
        }
    }
}
</code>```

Nonetheless , I get thos error message

```<code>NullReferenceException : Object reference not set to an instance of an object.
   at MS.Internal.Xml.Cache.XPathDocumentBuilder.Initialize(XPathDocument doc, IXmlLineInfo lineInfo, String baseUri, LoadFlags flags)
   at MS.Internal.Xml.Cache.XPathDocumentBuilder..ctor(XPathDocument doc, IXmlLineInfo lineInfo, String baseUri, LoadFlags flags)
   at System.Xml.XPath.XPathDocument.LoadFromReader(XmlReader reader, XmlSpace space)
   at System.Xml.XPath.XPathDocument..ctor(XmlReader reader, XmlSpace space)
   at System.Xml.Xsl.Runtime.XmlQueryContext.ConstructDocument(Object dataSource, String uriRelative, Uri uriResolved)
   at System.Xml.Xsl.Runtime.XmlQueryContext..ctor(XmlQueryRuntime runtime, Object defaultDataSource, XmlResolver dataSources, XsltArgumentList argList, WhitespaceRuleLookup wsRules)
   at System.Xml.Xsl.Runtime.XmlQueryRuntime..ctor(XmlQueryStaticData data, Object defaultDataSource, XmlResolver dataSources, XsltArgumentList argList, XmlSequenceWriter seqWrt)
   at System.Xml.Xsl.XmlILCommand.Execute(Object defaultDocument, XmlResolver dataSources, XsltArgumentList argumentList, XmlSequenceWriter results)
   at System.Xml.Xsl.XmlILCommand.Execute(Object defaultDocument, XmlResolver dataSources, XsltArgumentList argumentList, XmlWriter writer, Boolean closeWriter)
   at System.Xml.Xsl.XmlILCommand.Execute(XmlReader contextDocument, XmlResolver dataSources, XsltArgumentList argumentList, XmlWriter results)
   at System.Xml.Xsl.XslCompiledTransform.Transform(XmlReader input, XmlWriter results)
</code>```

I found a way to work around this by converting the HTML to XML and then applying the transform , but that's an inefficient solution because :

Intermediate XHTML output goes to a buffer , so extra memory is needed

Conversion process needs extra CPU processing
and the same hierarchy is traversed twice (in theory unnecessarily).

So (since I know StackOverflow community always provides great answers whereas other C# forums have completely disappointed me ;o) I'll be looking for feedback and suggestions so as to perform XSL transformations using HTML directly (even if SgmlReader needs to be replaced by another similar library).

答:
Have you tried using the HTML Agility Pack instead of SgmlReader?  You can load the html into it, and run a transform against it directly.  I'm not positive if an XML document is created internally, though - although it seems as though one is not you would probably want to compare memory and CPU usage against the conversion method you tried and discarded.

```<code>//You already have your xslt loaded into var xslt...

HtmlDocument doc = new HtmlDocument();
doc.Load( ... );  //load your HTML doc, or use LoadXML from a string, etc
xslt.Transform(doc, xw);
</code>```

See also this question: How to use HTML Agility pack

ContentLicense: CC BY-SA 4.0

Body:
I needed to transform the contents of an HTML web page using XSLT
. Hence I used SgmlReader and wrote the snippet shown below (I
thought, in the end, it's an XmlReader too ...)

XmlReader xslr = XmlReader.Create(new StringReader(
    "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
    "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">" +
    "<xsl:output method=\"xml\" encoding=\"UTF-8\" version=\"1.0\" />" +
    "<xsl:template match=\"/\">" +
    "<XXX xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><xsl:value-of select=\"count(//br)\" /></XXX>" +
    "</xsl:template>" +
    "</xsl:stylesheet>"));

XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(xslr);

using (SgmlReader html = new SgmlReader())
{
    StringBuilder sb = new StringBuilder();
    using (TextWriter sw = new StringWriter(sb))
    using (XmlWriter xw = new XmlTextWriter(sw))
    {
        html.InputStream = new StringReader(Resources.html_orig);
        html.DocType = "HTML";

        try
        {
            xslt.Transform(html, xw);
            string output = sb.ToString();
            System.Console.WriteLine(output);
        }
        catch (Exception exc)
        {
            System.Console.WriteLine("{0} : {1}", exc.GetType().Name, exc.Message);
            System.Console.WriteLine(exc.StackTrace);
        }
    }
}

Nonetheless , I get thos error message

NullReferenceException : Object reference not set to an instance of an object.
   at MS.Internal.Xml.Cache.XPathDocumentBuilder.Initialize(XPathDocument doc, IXmlLineInfo lineInfo, String baseUri, LoadFlags flags)
   at MS.Internal.Xml.Cache.XPathDocumentBuilder..ctor(XPathDocument doc, IXmlLineInfo lineInfo, String baseUri, LoadFlags flags)
   at System.Xml.XPath.XPathDocument.LoadFromReader(XmlReader reader, XmlSpace space)
   at System.Xml.XPath.XPathDocument..ctor(XmlReader reader, XmlSpace space)
   at System.Xml.Xsl.Runtime.XmlQueryContext.ConstructDocument(Object dataSource, String uriRelative, Uri uriResolved)
   at System.Xml.Xsl.Runtime.XmlQueryContext..ctor(XmlQueryRuntime runtime, Object defaultDataSource, XmlResolver dataSources, XsltArgumentList argList, WhitespaceRuleLookup wsRules)
   at System.Xml.Xsl.Runtime.XmlQueryRuntime..ctor(XmlQueryStaticData data, Object defaultDataSource, XmlResolver dataSources, XsltArgumentList argList, XmlSequenceWriter seqWrt)
   at System.Xml.Xsl.XmlILCommand.Execute(Object defaultDocument, XmlResolver dataSources, XsltArgumentList argumentList, XmlSequenceWriter results)
   at System.Xml.Xsl.XmlILCommand.Execute(Object defaultDocument, XmlResolver dataSources, XsltArgumentList argumentList, XmlWriter writer, Boolean closeWriter)
   at System.Xml.Xsl.XmlILCommand.Execute(XmlReader contextDocument, XmlResolver dataSources, XsltArgumentList argumentList, XmlWriter results)
   at System.Xml.Xsl.XslCompiledTransform.Transform(XmlReader input, XmlWriter results)

I found a way to work around this by converting the HTML to XML and then applying the transform , but that's an inefficient solution because :

Intermediate XHTML output goes to a buffer , so extra memory is needed

Conversion process needs extra CPU processing
and the same hierarchy is traversed twice (in theory unnecessarily).

So (since I know StackOverflow community always provides great answers whereas other C# forums have completely disappointed me ;o) I'll be looking for feedback and suggestions so as to perform XSL transformations using HTML directly (even if SgmlReader needs to be replaced by another similar library).

Body:
Have you tried using the HTML Agility Pack instead of SgmlReader?  You can load the html into it, and run a transform against it directly.  I'm not positive if an XML document is created internally, though - although it seems as though one is not you would probably want to compare memory and CPU usage against the conversion method you tried and discarded.

//You already have your xslt loaded into var xslt...

HtmlDocument doc = new HtmlDocument();
doc.Load( ... );  //load your HTML doc, or use LoadXML from a string, etc
xslt.Transform(doc, xw);

See also this question: How to use HTML Agility pack


问:
Make small changes to multiple functions without affecting cell reference
What is the best way to change ">" to ">=" in 100+ formulas such as:

```<code>=IF(INDEX($B$2:$B$46,MATCH(A3,$D$2:$D$46,0))**>**$A$2),"1","0")

=IF(INDEX($B$2:$B$46,MATCH(A3,$D$2:$D$46,0))**>**$B$2),"1","0")

=IF(INDEX($B$2:$B$46,MATCH(A3,$D$2:$D$46,0))**>**$C$2),"1","0")
</code>```

Would I need some VBA code?

答:
I would suggest one more idea if you are not comfortable doing the find and replace in excel.

Press the key combination Ctrl+`  (BackQuote symbol)

Now you will have all the formulas visible in the cells.

Copy the range or columns in which you need to modify the formula

Paste it in a .txt file and then do the find and replace

Once it is done copy all the formula and paste it back to the same range.

Press Ctrl+` again and now you have got all the formulas changed as per your need

As long suggested, take a backup of your worksheet before you do these modifications

Body:
What is the best way to change ">" to ">=" in 100+ formulas such as:

=IF(INDEX($B$2:$B$46,MATCH(A3,$D$2:$D$46,0))**>**$A$2),"1","0")

=IF(INDEX($B$2:$B$46,MATCH(A3,$D$2:$D$46,0))**>**$B$2),"1","0")

=IF(INDEX($B$2:$B$46,MATCH(A3,$D$2:$D$46,0))**>**$C$2),"1","0")

Would I need some VBA code?


问:
Failing to send data from Action Controller to AJAX Caller ,Serializing context model of a dynamic proxy property
I'm trying to send the queried data gathered from the context back to the ajax caller with the following status

1-The source code server side succeeds querying the data.
2-The source code server side succeeds sending the data in case HTTPPOST or HTTPGET is used
3-No exceptions or errors at the source code
4-applying  JSON(queried object) method doesn't make a change
The scenario goes as follow:-
using ajax call as follows

```<code>$.ajax({
                    type: "POST",
                    url: '@Url.Action("MainCatItems", "Cachier")',
                    contentType: "application/json; charset=utf-8",
                    data: datas,
                    dataType: "json",
                    success: successFunc,
                    error: function (xhr) {
                        alert('Error: ' + xhr.statusText);
                    },
                });
</code>```

calling an Action Controller

```<code>[HttpPost]
    public ActionResult MainCatItems(int mainCatNo)
    {
        var results = ......//fetching data from Context
        return Json(new { data = results }, JsonRequestBehavior.AllowGet);
    }
</code>```

, the call succeeds sending my parameters to the action but sending a response back to the ajax call from the controller is a little bit confusing as I have two cases:

The First: (working perfectly)
I'm returning data queried from a table class in my Entity Framework (RegisterNotification Class)

```<code>public partial class RegisterNotification
{
    //setters and getters
}
</code>```

which is a single class with no navigational property declared inside

The Second(where the problem is.)
I'm returning data queried from a table class in my Entity Framework
(Item Class"partial class")

Part One:-

```<code>public *partial* class Item
{
    // setters and getters
}
</code>```

Part Two:-

```<code> public *partial* class Item
{
    //setters and getters
}
</code>```

which is a partial class with navigational properties declared inside

This case doesn't work and when getting back to the ajax call it alerts the error function message saying an "internal server error 500"
I have tried parsing the queried data to a JSON Object in my controller:-

```<code>var t = Json(res,"application/json; charset=utf-8",JsonRequestBehavior.AllowGet);
</code>```

Queried Data at source code server side Watch:

Client Side error message details

But again with failure.
Thanks for concerning.

答:
```<code>public JsonResult GetCatItems(int mainCatNo)
    {
        var results = ......//fetching data from Context
        return Json(new { data = results }, JsonRequestBehavior.AllowGet);
    }
</code>```

Try This .. It might Help You And you can call this method from an action controller.

```<code>$.ajax({
                    type: "POST",
                    url: '@Url.Action("GetCatItems", "Cachier")',
                    contentType: "application/json; charset=utf-8",
                    data: datas,
                    dataType: "json",
                    success: successFunc,
                    error: function (xhr) {
                        alert('Error: ' + xhr.statusText);
                    },
                });
</code>```

Body:
I'm trying to send the queried data gathered from the context back to the ajax caller with the following status

1-The source code server side succeeds querying the data.
2-The source code server side succeeds sending the data in case HTTPPOST or HTTPGET is used
3-No exceptions or errors at the source code
4-applying  JSON(queried object) method doesn't make a change
The scenario goes as follow:-
using ajax call as follows

$.ajax({
                    type: "POST",
                    url: '@Url.Action("MainCatItems", "Cachier")',
                    contentType: "application/json; charset=utf-8",
                    data: datas,
                    dataType: "json",
                    success: successFunc,
                    error: function (xhr) {
                        alert('Error: ' + xhr.statusText);
                    },
                });

calling an Action Controller

[HttpPost]
    public ActionResult MainCatItems(int mainCatNo)
    {
        var results = ......//fetching data from Context
        return Json(new { data = results }, JsonRequestBehavior.AllowGet);
    }

, the call succeeds sending my parameters to the action but sending a response back to the ajax call from the controller is a little bit confusing as I have two cases:

The First: (working perfectly)
I'm returning data queried from a table class in my Entity Framework (RegisterNotification Class)

public partial class RegisterNotification
{
    //setters and getters
}

which is a single class with no navigational property declared inside

The Second(where the problem is.)
I'm returning data queried from a table class in my Entity Framework
(Item Class"partial class")

Part One:-

public *partial* class Item
{
    // setters and getters
}

Part Two:-

 public *partial* class Item
{
    //setters and getters
}

which is a partial class with navigational properties declared inside

This case doesn't work and when getting back to the ajax call it alerts the error function message saying an "internal server error 500"
I have tried parsing the queried data to a JSON Object in my controller:-

var t = Json(res,"application/json; charset=utf-8",JsonRequestBehavior.AllowGet);

Queried Data at source code server side Watch:

Client Side error message details

But again with failure.
Thanks for concerning.

Body:
public JsonResult GetCatItems(int mainCatNo)
    {
        var results = ......//fetching data from Context
        return Json(new { data = results }, JsonRequestBehavior.AllowGet);
    }

Try This .. It might Help You And you can call this method from an action controller.

$.ajax({
                    type: "POST",
                    url: '@Url.Action("GetCatItems", "Cachier")',
                    contentType: "application/json; charset=utf-8",
                    data: datas,
                    dataType: "json",
                    success: successFunc,
                    error: function (xhr) {
                        alert('Error: ' + xhr.statusText);
                    },
                });


答:
In your android manifest declare your earlier activity as parent activity.</p>

```<code><activity
        android:name=".activities.Detail"
        android:label="Detail"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="adjustPan">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.xyz.app.MainActivity" />
    </activity>
</code>```

Title: App crashes when when back button is pressed (Android Studio)

Body:
In your android manifest declare your earlier activity as parent activity.

<activity
        android:name=".activities.Detail"
        android:label="Detail"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="adjustPan">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.xyz.app.MainActivity" />
    </activity>


问:
NetworkStatsManager for get mobile data Android issue
i am using NetworkStatsManager in 6.0 for getting mobile data and using this method

```<code> public long getAllRxBytesMobile1(Context context) {
    NetworkStats.Bucket bucket;
    try {
        bucket = networkStatsManager.querySummaryForDevice(ConnectivityManager.TYPE_MOBILE,
                getSubscriberId(context, ConnectivityManager.TYPE_MOBILE),
                0,
                System.currentTimeMillis());
    } catch (RemoteException e) {
        return -1;
    }
    return bucket.getRxBytes();
}
</code>```

and

```<code>private String getSubscriberId(Context context, int networkType) {
    if (ConnectivityManager.TYPE_MOBILE == networkType) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        return tm.getSubscriberId();
    }
    return "";
}
</code>```

but returning always zero. how to resolved that?

答:
Try this:</p>

```<code>TelephonyManager telephonyManager = (TelephonyManager) mContext
        .getSystemService(Context.TELEPHONY_SERVICE);
int slotIndex = 1;
int subscriptionId = SubscriptionManager.from(mContext).getActiveSubscriptionInfoForSimSlotIndex(slotIndex).getSubscriptionId();
try {
    Class c = Class.forName("android.telephony.TelephonyManager");
    Method m = c.getMethod("getSubscriberId", new Class[] {int.class});
    Object o = m.invoke(telephonyManager, new Object[]{subscriptionId});

    String subscriberId = (String) o;
} catch (Exception e) {
    e.printStackTrace();
}
</code>```

Body:
i am using NetworkStatsManager in 6.0 for getting mobile data and using this method

 public long getAllRxBytesMobile1(Context context) {
    NetworkStats.Bucket bucket;
    try {
        bucket = networkStatsManager.querySummaryForDevice(ConnectivityManager.TYPE_MOBILE,
                getSubscriberId(context, ConnectivityManager.TYPE_MOBILE),
                0,
                System.currentTimeMillis());
    } catch (RemoteException e) {
        return -1;
    }
    return bucket.getRxBytes();
}

and

private String getSubscriberId(Context context, int networkType) {
    if (ConnectivityManager.TYPE_MOBILE == networkType) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        return tm.getSubscriberId();
    }
    return "";
}

but returning always zero. how to resolved that?

Body:
Try this:

TelephonyManager telephonyManager = (TelephonyManager) mContext
        .getSystemService(Context.TELEPHONY_SERVICE);
int slotIndex = 1;
int subscriptionId = SubscriptionManager.from(mContext).getActiveSubscriptionInfoForSimSlotIndex(slotIndex).getSubscriptionId();
try {
    Class c = Class.forName("android.telephony.TelephonyManager");
    Method m = c.getMethod("getSubscriberId", new Class[] {int.class});
    Object o = m.invoke(telephonyManager, new Object[]{subscriptionId});

    String subscriberId = (String) o;
} catch (Exception e) {
    e.printStackTrace();
}


问:
How do I install libsvm in a conda environment so that I can import svm in anaconda?
I have tried installing libsvm using conda as well as pip commands. pip commands are not installing libsvm for conda environment and  when I install it for conda environment using the command - 'conda install -c conda-forge libsvm=3.21' (recommended on various sites) I'm still not able to import svm in my program.
It shows the error - 'ImportError: No module named svm'

In conda list libsvm is shown as follows
maybe it has to do something with vc9_1 build instead py27_0/py27_1/py27_21

P.S. I'm using python 2.7

答:
The libsvm package from conda-forge channel provides only the shared library, and not the python bindings. If you want both, I'd suggest you do the following:

```<code>conda remove libsvm
conda install pip
</code>```

Visit http://www.lfd.uci.edu/~gohlke/pythonlibs and download the latest version of libsvm for your version of python and system architecture:

```<code>pip install /path/to/downloaded/libsvm-3.21-cp27-cp27m-win_amd64.whl
</code>```

This wheel package contains the following files:

```<code>libsvm-3.21.data/data/Lib/site-packages/libsvm.dll
libsvm-3.21.data/data/Lib/site-packages/svm.py
libsvm-3.21.data/data/Lib/site-packages/svmutil.py
libsvm-3.21.dist-info/DESCRIPTION.rst
libsvm-3.21.dist-info/metadata.json
libsvm-3.21.dist-info/top_level.txt
libsvm-3.21.dist-info/WHEEL
libsvm-3.21.dist-info/METADATA
libsvm-3.21.dist-info/RECORD
</code>```

Body:
The libsvm package from conda-forge channel provides only the shared library, and not the python bindings. If you want both, I'd suggest you do the following:

conda remove libsvm
conda install pip

Visit http://www.lfd.uci.edu/~gohlke/pythonlibs and download the latest version of libsvm for your version of python and system architecture:

pip install /path/to/downloaded/libsvm-3.21-cp27-cp27m-win_amd64.whl

This wheel package contains the following files:

libsvm-3.21.data/data/Lib/site-packages/libsvm.dll
libsvm-3.21.data/data/Lib/site-packages/svm.py
libsvm-3.21.data/data/Lib/site-packages/svmutil.py
libsvm-3.21.dist-info/DESCRIPTION.rst
libsvm-3.21.dist-info/metadata.json
libsvm-3.21.dist-info/top_level.txt
libsvm-3.21.dist-info/WHEEL
libsvm-3.21.dist-info/METADATA
libsvm-3.21.dist-info/RECORD


问:
Flex DisplayObject in fullscreen mode
I would like to make a display object fullscreen in my Flex application. I understand it is easy to make the complete Stage fullscreen in flex (example). But I have two charts on my Stage and I would like to make one of the charts full screen on clicking a button (or on double clicking on the chart area) and as per my understanding a ColumnChart is a DisplayObject (API reference).

Is it possible to do so? and if it is possible then please post the code snippet.

Thanks

答:
You can try something like this ...</p>

```<code>
private var myLeftColumnChart : ColumnChart;
private var myRightColumnChart : ColumnChart;

private function onButtonClick() : void{
   myRightColumnChart.visible = myRightColumnChart.includeInLayout = false;

   myLeftColumnChart.y = myLeftColumnChart.x = 0;
   myLeftColumnChart.width = Application.application.width;
   myRightColumnChart.height = Application.application.height;
}
</code>```

OwnerDisplayName: andHapp

Title: Flex DisplayObject in fullscreen mode

Body:
You can try something like this ...

private var myLeftColumnChart : ColumnChart;
private var myRightColumnChart : ColumnChart;

private function onButtonClick() : void{
   myRightColumnChart.visible = myRightColumnChart.includeInLayout = false;

   myLeftColumnChart.y = myLeftColumnChart.x = 0;
   myLeftColumnChart.width = Application.application.width;
   myRightColumnChart.height = Application.application.height;
}

OwnerDisplayName: ForYouOwnGood


问:
How to access telerik ajax radgrid values in the controller?
I am new to using Telerik and asp.net.
The application I'm trying to build uses telerik ajax controls in asp.net MVC2 application.
I have used a Telerik RadGrid of Ajax in my view of the mvc2 application as follows:

```<code>    <form runat="server" id="form1" method="post">

<telerik:RadScriptManager ID="RadScriptManager1" runat="server">

</telerik:RadScriptManager>

<h2>Index</h2>

<telerik:RadGrid ID="RadGrid1" runat="server"

DataSourceID="SqlDataSource1" AllowPaging="True" GridLines="None"

AllowMultiRowSelection="True" Skin="Web20" AutoGenerateColumns="False">

<MasterTableView DataSourceID="SqlDataSource1" AllowFilteringByColumn="True"

DataKeyNames="Val1">

<CommandItemSettings ExportToPdfText="Export to Pdf"></CommandItemSettings>

<RowIndicatorColumn>

<HeaderStyle Width="20px"></HeaderStyle>

</RowIndicatorColumn>

<ExpandCollapseColumn>

<HeaderStyle Width="20px"></HeaderStyle>

</ExpandCollapseColumn>

<Columns>

<telerik:GridBoundColumn DataField="Val1" HeaderText="Val1"

SortExpression="Val1" UniqueName="Val1">

</telerik:GridBoundColumn>

<telerik:GridBoundColumn DataField="Val2" HeaderText="Val2" ReadOnly="True"

SortExpression="Val2" UniqueName="Val2">

</telerik:GridBoundColumn>

</Columns>

</MasterTableView>

<ClientSettings ActiveRowIndex="0" AllowKeyboardNavigation="True" >

<Selecting AllowRowSelect="True" />

</ClientSettings>

</telerik:RadGrid>

<asp:SqlDataSource ID="SqlDataSource1" runat="server"

ConnectionString="<%$ ConnectionStrings:SomeConnectionString %>"

SelectCommand="SELECT * FROM [someTable]"></asp:SqlDataSource>

<input type="submit" value="Submit"/>

</form>
</code>```

I want to access the selected values from the RadGrid in my controller(atleast the key value). How can I do that?

Thanks in advance,
Hilda

答:
My guess is that you can do that using the SelectedItems collection of the grid, then fetch the key values from the selected rows from there as done here.

Still if you rely on the pure MVC concept, think about switching the telerik ajax grid with their mvc grid extension which is pure mvc component.

Body:
I am new to using Telerik and asp.net.
The application I'm trying to build uses telerik ajax controls in asp.net MVC2 application.
I have used a Telerik RadGrid of Ajax in my view of the mvc2 application as follows:

    <form runat="server" id="form1" method="post">

<telerik:RadScriptManager ID="RadScriptManager1" runat="server">

</telerik:RadScriptManager>

Index

<telerik:RadGrid ID="RadGrid1" runat="server"

DataSourceID="SqlDataSource1" AllowPaging="True" GridLines="None"

AllowMultiRowSelection="True" Skin="Web20" AutoGenerateColumns="False">

<MasterTableView DataSourceID="SqlDataSource1" AllowFilteringByColumn="True"

DataKeyNames="Val1">

<CommandItemSettings ExportToPdfText="Export to Pdf"></CommandItemSettings>

<RowIndicatorColumn>

<HeaderStyle Width="20px"></HeaderStyle>

</RowIndicatorColumn>

<ExpandCollapseColumn>

<HeaderStyle Width="20px"></HeaderStyle>

</ExpandCollapseColumn>

<Columns>

<telerik:GridBoundColumn DataField="Val1" HeaderText="Val1"

SortExpression="Val1" UniqueName="Val1">

</telerik:GridBoundColumn>

<telerik:GridBoundColumn DataField="Val2" HeaderText="Val2" ReadOnly="True"

SortExpression="Val2" UniqueName="Val2">

</telerik:GridBoundColumn>

</Columns>

</MasterTableView>

<ClientSettings ActiveRowIndex="0" AllowKeyboardNavigation="True" >

<Selecting AllowRowSelect="True" />

</ClientSettings>

</telerik:RadGrid>

<asp:SqlDataSource ID="SqlDataSource1" runat="server"

ConnectionString="<%$ ConnectionStrings:SomeConnectionString %>"

SelectCommand="SELECT * FROM [someTable]"></asp:SqlDataSource>

<input type="submit" value="Submit"/>

</form>

I want to access the selected values from the RadGrid in my controller(atleast the key value). How can I do that?

Thanks in advance,
Hilda


问:
The target type of this expression must be a functional interface -Java 8 Functoinal Interface
I just have a small doubt on lambdas.I'm getting the below error with the following code.If i'm calling a method which returns boolean or other type, I don't see this issue.How can i solve this problem?

Error:

Exception in thread "main" java.lang.Error: Unresolved compilation problems:
          The method forEach(Consumer) in the type Iterable is not applicable for the arguments (( bean) -> {})
          The target type of this expression must be a functional interface

at com.wipro.MethodReference.main(MethodReference.java:18)

```<code>package com.sample;

import com.student.MockClass;

import java.util.ArrayList;
import java.util.List;

public class MethodReference {
    public static void main(String[] args) {
        MockClass obj = new MockClass("JSP", 2);
        MockClass obj1 = new MockClass("Java", 8);
        List<MockClass> listofBeans = new ArrayList<MockClass>();
        listofBeans.add(obj);
        listofBeans.add(obj1);
        listofBeans.forEach(bean -> MethodReference::call);
    }

     public static void call(){
        System.out.println("Hii!!!");
    }
}
</code>```

答:
JLS described Method Reference Expression:

A method reference expression is compatible in an assignment context, invocation context, or casting context with a target type T if T is a functional interface type (§9.8) and the expression is congruent with the function type of the ground target type derived from T.

So you must assign/cast it to a function interface.

```<code>listofBeans.forEach(bean-> ((Runnable)MethodReference::call).run());
</code>```

is equivalent to :

```<code>listofBeans.forEach(bean-> call());
</code>```

Body:
I just have a small doubt on lambdas.I'm getting the below error with the following code.If i'm calling a method which returns boolean or other type, I don't see this issue.How can i solve this problem?

Error:

Exception in thread "main" java.lang.Error: Unresolved compilation problems:
          The method forEach(Consumer) in the type Iterable is not applicable for the arguments (( bean) -> {})
          The target type of this expression must be a functional interface

at com.wipro.MethodReference.main(MethodReference.java:18)

package com.sample;

import com.student.MockClass;

import java.util.ArrayList;
import java.util.List;

public class MethodReference {
    public static void main(String[] args) {
        MockClass obj = new MockClass("JSP", 2);
        MockClass obj1 = new MockClass("Java", 8);
        List<MockClass> listofBeans = new ArrayList<MockClass>();
        listofBeans.add(obj);
        listofBeans.add(obj1);
        listofBeans.forEach(bean -> MethodReference::call);
    }

     public static void call(){
        System.out.println("Hii!!!");
    }
}

Body:
JLS described Method Reference Expression:

A method reference expression is compatible in an assignment context, invocation context, or casting context with a target type T if T is a functional interface type (§9.8) and the expression is congruent with the function type of the ground target type derived from T.

So you must assign/cast it to a function interface.

listofBeans.forEach(bean-> ((Runnable)MethodReference::call).run());

is equivalent to :

listofBeans.forEach(bean-> call());


问:
Calculating error in PCA
I have a question about a result which I did not expect when doing PCA.

I have successfully calculated the principal components using reference data, and then as a check to ensure that what's going on is what I think is going on, I've projected the reference data onto the entire basis of its eigenfucntions (kept all components) and then transformed back, (this is in python, so it's pca.fit(ref_data) followed by ref_data_transform =pca.transform.(ref_data) followed by pca.inverse_transform(ref_data_transform) I get the exact same data. This is not a surprise.

What is also not a surprise is that as I choose fewer and fewer principle components, the point to point difference between the original data and that which has been projected onto a smaller basis and then projected back increases. That is, if you plot the original data and "filtered" data, it looks different, with the difference increasing as you reduce the size of the subspace onto which you're projecting. I can capture the difference between each data point in a vector called, say, difference_vec.

What IS a surprise (to me at least) is that when I sum over any column of difference_vec it always equals zero. That is, while the actual differences between any original data point and the corresponding one filtered by some number of principal components grow larger as I project onto a smaller and smaller subspace, the TOTAL error is always zero.

I very much appreciate any insight that one my have into if I'm making some mistake here and if not, why this erstwhile "projection induced error" metric doesn't work.

Thanks.

答:
This happens because ref_data and what I’ll call inv_data = pca.inverse_transform(pca.transform(ref_data)) both have the same mean (taken along the second dimension, i.e., averaging over samples).

To see this, take a look at the code for transform:

```<code>transform = lambda X: dot(X - mu, V.T)
</code>```

whereas inverse_transform can be defined as:

```<code>inverse_transform = lambda X: dot(X, V) + mu
</code>```

where mu is the mean of ref_data and V are the first N eigenvectors of covariance(ref_data).

So if you follow the chain of data and its mean:

ref_data with mean mu;

transform(ref_data) has mean 0 (see the equivalent definition above: X-mu has zero mean, then projecting the result linearly onto some coordinate reference only rotates/shears/flips those zero-mean points, doesn’t alter their mean;

Finally, inv_data = inverse_transform(transform(ref_data)) adds mu back so it has mu-mean;

you see that ref_data and inv_data both have mean mu.

Finally, sum(ref_data - inv_data) can be seen as sum(mean(ref_data - inv_data) * num_samples), which by linearity simplifies to sum(mu - mu), which is 0.

That’s a lot of words, sorry, but the idea, now that I see it, is really simple. As I mentioned in my comment, in cases like this you want to use a matrix norm, like the Frobenius norm, to measure a distance between two matrixes, not just sum(A - B) !

Sample code:

```<code>import numpy as np
from sklearn.decomposition import PCA

ref_data = np.random.randn(20, 3)
pca = PCA(n_components=1)
pca.fit(ref_data)
trans_data = pca.transform(ref_data)
inv_data = pca.inverse_transform(trans_data)

np.mean(inv_data, 0)   # array([ 0.03664149,  0.51348007,  0.0360179 ])
np.mean(ref_data, 0)   # array([ 0.03664149,  0.51348007,  0.0360179 ])
np.mean(trans_data, 0) # array([ -2.49800181e-17]) meanwhile ...
np.sum(inv_data - ref_data) # -1.3877787807814457e-15 !
</code>```

Title: Calculating error in PCA

Body:
This happens because ref_data and what I’ll call inv_data = pca.inverse_transform(pca.transform(ref_data)) both have the same mean (taken along the second dimension, i.e., averaging over samples).

To see this, take a look at the code for transform:

transform = lambda X: dot(X - mu, V.T)

whereas inverse_transform can be defined as:

inverse_transform = lambda X: dot(X, V) + mu

where mu is the mean of ref_data and V are the first N eigenvectors of covariance(ref_data).

So if you follow the chain of data and its mean:

ref_data with mean mu;

transform(ref_data) has mean 0 (see the equivalent definition above: X-mu has zero mean, then projecting the result linearly onto some coordinate reference only rotates/shears/flips those zero-mean points, doesn’t alter their mean;

Finally, inv_data = inverse_transform(transform(ref_data)) adds mu back so it has mu-mean;

you see that ref_data and inv_data both have mean mu.

Finally, sum(ref_data - inv_data) can be seen as sum(mean(ref_data - inv_data) * num_samples), which by linearity simplifies to sum(mu - mu), which is 0.

That’s a lot of words, sorry, but the idea, now that I see it, is really simple. As I mentioned in my comment, in cases like this you want to use a matrix norm, like the Frobenius norm, to measure a distance between two matrixes, not just sum(A - B) !

Sample code:

import numpy as np
from sklearn.decomposition import PCA

ref_data = np.random.randn(20, 3)
pca = PCA(n_components=1)
pca.fit(ref_data)
trans_data = pca.transform(ref_data)
inv_data = pca.inverse_transform(trans_data)

np.mean(inv_data, 0)   # array([ 0.03664149,  0.51348007,  0.0360179 ])
np.mean(ref_data, 0)   # array([ 0.03664149,  0.51348007,  0.0360179 ])
np.mean(trans_data, 0) # array([ -2.49800181e-17]) meanwhile ...
np.sum(inv_data - ref_data) # -1.3877787807814457e-15 !


问:
Unable to Click via xpath,classname,location or index
I am working to automate an android app which have some screen of webview too. I am unable to click the right element through xpath class, with index or even with giving name text.

If you see these screenshots it is visible that when I inspect element i get link to somewhere else. i tried using getlocation and then pass it for click but it also getting me wrong click.

I tried touchaction class methods but they are not working. My code get pass through appium but the methods tap or press nothing.

I tried this way too but no luck.

```<code>WebElement Quiz1 = (new WebDriverWait(driver , 20))
 .until(ExpectedConditions.presenceOfElementLocated(By.xpath("//android.view.View[contains(@content-desc,'Die Wish App')]")));
Quiz1.click();
</code>```

Any help would be appreciated. Also how can I use webview rather than webelement? and which one is preferable?

答:
You can click on the element which you have highlighted in the screenshot.Below is the locator to identify that element</p>

```<code>By.accessibilityId("Die Wish App")
</code>```

Body:
I am working to automate an android app which have some screen of webview too. I am unable to click the right element through xpath class, with index or even with giving name text.

If you see these screenshots it is visible that when I inspect element i get link to somewhere else. i tried using getlocation and then pass it for click but it also getting me wrong click.

I tried touchaction class methods but they are not working. My code get pass through appium but the methods tap or press nothing.

I tried this way too but no luck.

WebElement Quiz1 = (new WebDriverWait(driver , 20))
 .until(ExpectedConditions.presenceOfElementLocated(By.xpath("//android.view.View[contains(@content-desc,'Die Wish App')]")));
Quiz1.click();

Any help would be appreciated. Also how can I use webview rather than webelement? and which one is preferable?

Body:
You can click on the element which you have highlighted in the screenshot.Below is the locator to identify that element

By.accessibilityId("Die Wish App")


问:
why lazy loaded module has to import commonModule? Angular 2
When we import BrowserModule in root module of application ,we can use NgIf and NgFor( in eagerly loaded component). But for lazy loaded modules I have to import CommonModule which has been exported by BrowserModule of root. SO why do we have to import it again in lazy loaded module?

答:
The Browser module is used in the root module of the app and when we are using modules the imports are specific to the modules.
When using feature modules for lazy loading components we have to import common module in the feature module, so as to tell Angular that the browser modules whixh contains some build in directives like ngFor and ngIf to be available in the feature module too.

Remember that the import for browser module will be only used only once in the app.module and where ever else we want to use these built in directives in our feature or shared modules we need to import the common module.


问:
Overlapping buttons with different states in Android
I'm making a Piano application for Android. Using xml, I've made two rectangular buttons, a white key and a black key. I need the black key to overlap the two white keys like a normal piano.

I have two different states(pressed and unpressed) for the button in which I have created two different drawable xml files. On pressing the black key, it works fine. However when I press a white key, the new drawable shape overlaps the black key.

Normal

White Pressed

From my knowledge, by default, the black key is on top of the other two white keys since I defined it last in the XML. Maybe since I'm accessing a new drawable file as source to the button when pressing it, it's drawing the view on top? Is there anyway to prevent this? I've provided the code for each XML file below. Thanks for the help!

Main XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"      android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:background="#ffcccccc"
android:gravity="top|center"
tools:context=".MainActivity">
<Button
    android:layout_width="45dp"
    android:layout_height="150dp"
    android:layout_marginTop="100dp"
    android:background="@drawable/wselector"
    android:id="@+id/button1"

    />

<Button
    android:layout_width="45dp"
    android:layout_height="150dp"
    android:layout_marginTop="100dp"
    android:background="@drawable/wselector"
    android:id="@+id/button2"
    android:layout_toRightOf="@id/button1"

    />
<Button
    android:layout_width="40dp"
    android:layout_height="100dp"
    android:layout_marginTop="100dp"
    android:background="@drawable/selector"
    android:id="@+id/button3"
    android:layout_toRightOf="@id/button1"
    android:layout_marginLeft="-20dp"
    android:onClick="soundmmm"
    />
</code>```

Selector XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/wpressed"
    android:paddingTop="10sp"></item>
<item android:drawable="@drawable/wnormal" android:layout_marginTop="50dp">
</item>
</selector>
</code>```

Unpressed XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/shadow" />

<item android:bottom="@dimen/layer_padding">
    <shape android:shape="rectangle">
        <corners android:radius="@dimen/corner_radius" />
        <solid android:color="#ffffffff"/>
    </shape>
</item>
</layer-list>
</code>```

Pressed XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <shape android:shape="rectangle">
        <solid android:color="#00000000"/>
    </shape>
</item>
<item android:top="@dimen/layer_padding">
    <shape android:shape="rectangle">
        <corners android:radius="@dimen/corner_radius" />
        <solid android:color="#ffffffff" />
    </shape>
</item>
</layer-list>
</code>```

答:
android:stateListAnimator="@null"

Don't bring button to foreground on click

This worked for me. Turns out it was not related to the button states at all, but instead the default Android button animations.

Body:
I'm making a Piano application for Android. Using xml, I've made two rectangular buttons, a white key and a black key. I need the black key to overlap the two white keys like a normal piano.

I have two different states(pressed and unpressed) for the button in which I have created two different drawable xml files. On pressing the black key, it works fine. However when I press a white key, the new drawable shape overlaps the black key.

Normal

White Pressed

From my knowledge, by default, the black key is on top of the other two white keys since I defined it last in the XML. Maybe since I'm accessing a new drawable file as source to the button when pressing it, it's drawing the view on top? Is there anyway to prevent this? I've provided the code for each XML file below. Thanks for the help!

Main XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"      android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:background="#ffcccccc"
android:gravity="top|center"
tools:context=".MainActivity">
<Button
    android:layout_width="45dp"
    android:layout_height="150dp"
    android:layout_marginTop="100dp"
    android:background="@drawable/wselector"
    android:id="@+id/button1"

    />

<Button
    android:layout_width="45dp"
    android:layout_height="150dp"
    android:layout_marginTop="100dp"
    android:background="@drawable/wselector"
    android:id="@+id/button2"
    android:layout_toRightOf="@id/button1"

    />
<Button
    android:layout_width="40dp"
    android:layout_height="100dp"
    android:layout_marginTop="100dp"
    android:background="@drawable/selector"
    android:id="@+id/button3"
    android:layout_toRightOf="@id/button1"
    android:layout_marginLeft="-20dp"
    android:onClick="soundmmm"
    />

Selector XML:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/wpressed"
    android:paddingTop="10sp"></item>
<item android:drawable="@drawable/wnormal" android:layout_marginTop="50dp">
</item>
</selector>

Unpressed XML:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/shadow" />

<item android:bottom="@dimen/layer_padding">
    <shape android:shape="rectangle">
        <corners android:radius="@dimen/corner_radius" />
        <solid android:color="#ffffffff"/>
    </shape>
</item>
</layer-list>

Pressed XML:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <shape android:shape="rectangle">
        <solid android:color="#00000000"/>
    </shape>
</item>
<item android:top="@dimen/layer_padding">
    <shape android:shape="rectangle">
        <corners android:radius="@dimen/corner_radius" />
        <solid android:color="#ffffffff" />
    </shape>
</item>
</layer-list>


问:
Store a signature image in Active Directory
As a part of a PDF signing system solution it is required to capture and store the signature image in a data store.I was thinking of recommending the LDAP user object jpegPhoto to store the signature jpeg file (encryption can be applied).Rather than a database since then the question is who would take ownership of the database (IT-POLICY-DEPT thinge).The AD is already owned and secure (assuming).So it would be a matter of the admins give access on SELF or appropriate permission to update  to user object for a period and then once the signatures are stored then later only retrieval permission given.I am not a system admin and we are just taking about 100 users,it this a big job ? The admins are just brushing off the suggestion without giving any proper explanation ! Can some give the pros and cons if any ....:-(</p>

答: Our requirements and solution are different but we did use jpegPhoto, we store a photo of the user in the thumbnailPhoto attribute and their signature in the jpegPhoto attribute. Our admin imported the images using a program called AD Photos, this then resized the images before importing into them into AD. We sent everyone an email and asked them to print it off and sign it in the box provided, we then loaded all the papers into a sheet fed scanner and captured just the signature. The images were all small >10k grey scale and we've seen no complaints from Active Directory (300 users). </p>


问:
Uncaught Exception ERROR - When running a JMeter Via JENKINS
I am trying to run a very simple test in Jenkins using JMeter.

JMeter Version 2.13 & Running Jenkins Locally and JMeter is also stored locally.

Executing in Jenkins using windows batch command.

when running the job in Jenkins i get the following error message in Console Output:

Uncaught Exception java.lang.ExceptionInInitializerError. See log file for details.
  Uncaught Exception java.lang.NoClassDefFoundError: Could not initialise class org.apache.jmeter.gui.util.MenuFactory. See log file for details.

I went to manage Jenkins and system logs but no information in there.

Any ideas?

答:
As it is java related exception, please check your jdk settings in jenkins by follwing below steps

Manage Jenkins -> Global Tool Configuration. You can find JDK tab.

Under JDK give the path of jdk folder for Java_Home variable

Please take free style project in jenkins and configure as in below images

In the place of directory under custom work space give the path of bin folder of jmeter

In the place of Test.jmx give your jmx file name

When you build the project you can see the console output as below image


问:
plotting cumulative density plot using fitdistrplus object without a histogram
The R package fitdistrplus has a denscomp function that plots the fitted cumulative density curve along with a histogram of the data. As an R newbie, I appreciate all the plots available in this package.

Is there a simple way to just plot the curve without the histogram?

I couldn't find an option like histogram = FALSE in the denscomp function in the documentation.

How should I use the fitdist$estimate to plot just the cumulative density curve?

答:
I'm not sure if there's an easy way to change the behavior of denscomp, but you can roll your own density plot using the distribution parameters returned by fitdist. Here's an example:

Set up to plot three plots in a single window:

```<code>par(mfrow=c(3,1), mar=c(4,4,3,1))
library(fitdistrplus)
</code>```

Create a fitdist object using an example adpated from the help for denscomp:

```<code>data(groundbeef)
serving <- groundbeef$serving
fitW <- fitdist(serving, "weibull")
</code>```

Now let's make a standard denscomp plot:

```<code>denscomp(fitW, plotstyle="graphics", main="denscomp Version")
</code>```

Now we'll roll our own Weibull density using the parameters returned by fitdist. fitW$estimate contains the shape and scale parameters of the fitted Weibull distribution for the serving data. Below we generate the same plot as above using these parameters:

```<code>x=seq(0, max(serving), length=100)
serving_dwei = dweibull(x, shape=fitW$estimate["shape"], scale=fitW$estimate["scale"])

hist(serving, freq=FALSE, main="Roll Your Own")
lines(x=x, y=serving_dwei, col="red")
</code>```

And finally, the density plot alone:

```<code>plot(x=x, y=serving_dwei, type="l", main="Density alone", xlab="Serving", ylab="Density")
</code>```

All three plots are shown below:

If you want to compare the Weibull fit with the empirical kernel density, you can do this:

```<code>plot(x=x, y=serving_dwei, type="l", main="Weibull fit plus empirical density",
     xlab="Serving", ylab="Density",
     ylim=c(0,max(c(serving_dwei, density(serving)$y))))
lines(density(serving), col="red")
</code>```

Body:
I'm not sure if there's an easy way to change the behavior of denscomp, but you can roll your own density plot using the distribution parameters returned by fitdist. Here's an example:

Set up to plot three plots in a single window:

par(mfrow=c(3,1), mar=c(4,4,3,1))
library(fitdistrplus)

Create a fitdist object using an example adpated from the help for denscomp:

data(groundbeef)
serving <- groundbeef$serving
fitW <- fitdist(serving, "weibull")

Now let's make a standard denscomp plot:

denscomp(fitW, plotstyle="graphics", main="denscomp Version")

Now we'll roll our own Weibull density using the parameters returned by fitdist. fitW$estimate contains the shape and scale parameters of the fitted Weibull distribution for the serving data. Below we generate the same plot as above using these parameters:

x=seq(0, max(serving), length=100)
serving_dwei = dweibull(x, shape=fitW$estimate["shape"], scale=fitW$estimate["scale"])

hist(serving, freq=FALSE, main="Roll Your Own")
lines(x=x, y=serving_dwei, col="red")

And finally, the density plot alone:

plot(x=x, y=serving_dwei, type="l", main="Density alone", xlab="Serving", ylab="Density")

All three plots are shown below:

If you want to compare the Weibull fit with the empirical kernel density, you can do this:

plot(x=x, y=serving_dwei, type="l", main="Weibull fit plus empirical density",
     xlab="Serving", ylab="Density",
     ylim=c(0,max(c(serving_dwei, density(serving)$y))))
lines(density(serving), col="red")


问:
find employees who do not receive commission in sql from emp table
find employees who do not receive commission in sql from emp table</p>

答: SELECT ENAME,COMM FROM EMP WHERE COMM IS NULL OR COMM=0; </p>


问:
 to external link returns link/Error in webapp, even though the server is not dead
I've got 3 links in the header of a .net C# MVC, with the following .cshtml file:

```<code><div id="header">
<div id="manag-nav">
    <a class="manag-page" href="https://EXAMPLE-LINK.com/Account">@Resources.label-A</a>
    <a class="manag-page" href="https://backoffice.EXAMPLE-LINK.com/Sitefinity">@Resources.label-B</a>
    <a class="manag-page website-page" href="http://www.EXAMPLE-LINK.com">@Resources.label-C</a>
</div>
<div id="logo">
    <img src="@Url.Content("~/Content/Images/logo.png")" alt="" />
</div>
<div id="user-login">

</div>
</code>```

Label1 and label3 links work fine, but my 2nd link, label2, when you click it, it returns "http://backoffice.blabla.com/Error" instead of "http://backoffice.blabla.com/Sitefinity".

Does anyone have any idea why this is happening?

I forgot to mention that when I go to this link directly, it works. Or when I write the link for this url in a simple .html file, it also works. It just stops working in the project.

答:
It might be because you are already logged in with a user and when you try to access /Sitefinity that user might not have backend access permissions, or is redirected to another page based on its role and there is an issue with that page, etc.

Long and short - make sure you are not logged in to Sitefinity and then try the link.

If you still face the issue - then better examine the rendered html output - it may have been modified by an external javascript, or there might be a javascript click handler for that html element, could be many things.

Title: <a href> to external link returns link/Error in webapp, even though the server is not dead

Body:
I've got 3 links in the header of a .net C# MVC, with the following .cshtml file:

    @Resources.label-A
    @Resources.label-B
    @Resources.label-C

Label1 and label3 links work fine, but my 2nd link, label2, when you click it, it returns "http://backoffice.blabla.com/Error" instead of "http://backoffice.blabla.com/Sitefinity".

Does anyone have any idea why this is happening?

I forgot to mention that when I go to this link directly, it works. Or when I write the link for this url in a simple .html file, it also works. It just stops working in the project.


问:
Recursive Synchronization vs Recursive Reentrant Lock
I know  thread is allowed to acquire a monitor owned by itself i.e. In Java, synchronized locks are reentrant as shown in example below.

My query is if i use java.util.concurrent.locks.ReentrantLock API it will produce the same result or not, Can we have dead lock in synchronized but never in java.util.concurrent.locks.ReentrantLock

e.g.

```<code>  final Object[] objects = new Object[10]

    public synchronized Object setAndReturnPrevious(int index, Object val) {
        lock.lock();//If i use this will it be same as above synchronization
        set(index, val);
        lock.unlock()//;
    }

    public synchronized void set(int index, Object val) {
        lock.lock();//
        objects[index] = val;
        lock.unlock();//
    }
</code>```

答:
Both synchronized and reentrant locks are same . if you want more control and want to solve complex synchronization problems than Reentrant Lock is the best choice. it adds additional functionality to the implicit synchronization like ** support for Condition variables , Lock Fairness etc.**
As a Reference Check Java Threads 3rd Ed - Chapter 3 and Onwards

Body:
I know  thread is allowed to acquire a monitor owned by itself i.e. In Java, synchronized locks are reentrant as shown in example below.

My query is if i use java.util.concurrent.locks.ReentrantLock API it will produce the same result or not, Can we have dead lock in synchronized but never in java.util.concurrent.locks.ReentrantLock

e.g.

  final Object[] objects = new Object[10]

    public synchronized Object setAndReturnPrevious(int index, Object val) {
        lock.lock();//If i use this will it be same as above synchronization
        set(index, val);
        lock.unlock()//;
    }

    public synchronized void set(int index, Object val) {
        lock.lock();//
        objects[index] = val;
        lock.unlock();//
    }


问:
push local variables
Alo

After I have read about function and stack from http://en.wikibooks.org/wiki/X86_Disassembly/Functions_and_Stack_Frames I have a question about local variables.

Snapshot from the article:

```<code>push ebp     ; save the value of ebp
mov ebp, esp ; ebp now points to the top of the stack
sub esp, 12  ; space allocated on the stack for the local variables
</code>```

This means local variables can be accessed by referencing ebp. Consider the following C code fragment and corresponding assembly code:

```<code>a = 10;
b = 5;
c = 2;

mov [ebp -  4], 10  ; location of variable a
mov [ebp -  8], 5   ; location of b
mov [ebp - 12], 2   ; location of c
</code>```

Remember that pushing basically does this:

```<code>sub esp, 4   ; "allocate" space for the new stack item
mov [esp], X ; put new stack item value X in
</code>```

Why are local variables not push into the stack like this:

```<code>push 10
push 5
push 2
</code>```

instead of

```<code>sub esp, 12

mov [ebp -  4], 10  ; location of variable a
mov [ebp -  8], 5   ; location of b
mov [ebp - 12], 2   ; location of c
</code>```

答: Practically speaking, if you know how much stack space you need and reserve it in a single operation you can then use the mov instruction which executes faster than a push immed (especially now that the offset calculation has dedicated hardware).  There's also perhaps a legacy component having to do with the fact that push immed didn't become available on the x86 until the release of the 80186/80188 processors.  By that time, the sub/mov convention had become a well established pattern.</p>

Title: push local variables

Body:
Alo

After I have read about function and stack from http://en.wikibooks.org/wiki/X86_Disassembly/Functions_and_Stack_Frames I have a question about local variables.

Snapshot from the article:

push ebp     ; save the value of ebp
mov ebp, esp ; ebp now points to the top of the stack
sub esp, 12  ; space allocated on the stack for the local variables

This means local variables can be accessed by referencing ebp. Consider the following C code fragment and corresponding assembly code:

a = 10;
b = 5;
c = 2;

mov [ebp -  4], 10  ; location of variable a
mov [ebp -  8], 5   ; location of b
mov [ebp - 12], 2   ; location of c

Remember that pushing basically does this:

sub esp, 4   ; "allocate" space for the new stack item
mov [esp], X ; put new stack item value X in

Why are local variables not push into the stack like this:

push 10
push 5
push 2

instead of

sub esp, 12

mov [ebp -  4], 10  ; location of variable a
mov [ebp -  8], 5   ; location of b
mov [ebp - 12], 2   ; location of c


问:
adding rows after for loop in python
Hi I am new to python if I want to add row to an empty matrix after for loop in python how would I be able to do so. This is how I do it in Matlab.</p>

```<code>n = 10000;
tic
A = [];
for i = 1:n
  Ai = rand(1,3);
  A = [A;Ai];
end
toc
</code>```

答:
A one-liner:

```<code>import random

matrix = [[random.randint(1, 3) for _ in range(10)]]
</code>```

I wonder why would you need a one-row "matrix", as opposed to just a list of random numbers.

If you want a matrix with 1000 identical rows, create a row and add it 1000 times.

```<code>row = [random.randint(1, 3) for _ in range(10)]
matrix = [row for _ in range(1000)]
</code>```

Or a funny syntax-sugared version:

```<code>matrix = [row] * 1000
</code>```

Please note that the matrix will have 1000 references to the same row, not 1000 different copies of the row. If you mutate any value in any row, it will affect every row.

If you want a mutable matrix initially filled with 1000 identical rows, make a copy of the row each time:

```<code>matrix = [list(row) for _ in range(1000)]
</code>```

Each invocation of list creates a new list filled with numbers from row.

Title: adding rows after for loop in python

Body:
Hi I am new to python if I want to add row to an empty matrix after for loop in python how would I be able to do so. This is how I do it in Matlab.

n = 10000;
tic
A = [];
for i = 1:n
  Ai = rand(1,3);
  A = [A;Ai];
end
toc

Body:
A one-liner:

import random

matrix = [[random.randint(1, 3) for _ in range(10)]]

I wonder why would you need a one-row "matrix", as opposed to just a list of random numbers.

If you want a matrix with 1000 identical rows, create a row and add it 1000 times.

row = [random.randint(1, 3) for _ in range(10)]
matrix = [row for _ in range(1000)]

Or a funny syntax-sugared version:

matrix = [row] * 1000

Please note that the matrix will have 1000 references to the same row, not 1000 different copies of the row. If you mutate any value in any row, it will affect every row.

If you want a mutable matrix initially filled with 1000 identical rows, make a copy of the row each time:

matrix = [list(row) for _ in range(1000)]

Each invocation of list creates a new list filled with numbers from row.


问:
How to create custom helper functions in Laravel
I would like to create helper functions to avoid repeating code between views in Laravel. For example:

view.blade.php

```<code><p>Foo Formated text: {{ fooFormatText($text) }}</p>
</code>```

They're basically text formatting functions. How should I define globally available helper functions like fooFormatText()?

答:
in dir bootstrap\autoload.php

```<code>require __DIR__.'/../vendor/autoload.php';
require __DIR__.'/../app/Helpers/function.php'; //add
</code>```

add this file

```<code>app\Helpers\function.php
</code>```

Body:
I would like to create helper functions to avoid repeating code between views in Laravel. For example:

view.blade.php

Foo Formated text: {{ fooFormatText($text) }}

They're basically text formatting functions. How should I define globally available helper functions like fooFormatText()?

Body:
in dir bootstrap\autoload.php

require __DIR__.'/../vendor/autoload.php';
require __DIR__.'/../app/Helpers/function.php'; //add

add this file

app\Helpers\function.php


问:
When should you check if a view != null before implementing it?
I am looking at Cheesesquare to learn some new design tools and I came across this bit of code that left me wondering. The code finds a view, then checks if it is null before continuing its setup.

Why would the view ever return null, assuming it exists and the id matches?

I trust the expertise of the person who wrote this code and I assume it is not a mistake, but what is its purpose? When should I check for null values and when is it unnecessary?

```<code>    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    if (navigationView != null) {
        setupDrawerContent(navigationView);
    }

    ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
    if (viewPager != null) {
        setupViewPager(viewPager);
    }
</code>```

...

```<code>private void setupViewPager(ViewPager viewPager) {
    Adapter adapter = new Adapter(getSupportFragmentManager());
    adapter.addFragment(new CheeseListFragment(), "Category 1");
    adapter.addFragment(new CheeseListFragment(), "Category 2");
    adapter.addFragment(new CheeseListFragment(), "Category 3");
    viewPager.setAdapter(adapter);
}

private void setupDrawerContent(NavigationView navigationView) {
    navigationView.setNavigationItemSelectedListener(
            new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {
            menuItem.setChecked(true);
</code>```

答:
The main purpose of using the below mentioned code is to make sure that the viewPager is never returning a null value before setting up which will result in the app crash. The person using this code is trying to play safe with the code and making sure that the app will work as expected and will not crash under any circumstances due to viewPager returning null value.    </p>

```<code>if (viewPager != null) {
   setupViewPager(viewPager);
}
</code>```

Body:
I am looking at Cheesesquare to learn some new design tools and I came across this bit of code that left me wondering. The code finds a view, then checks if it is null before continuing its setup.

Why would the view ever return null, assuming it exists and the id matches?

I trust the expertise of the person who wrote this code and I assume it is not a mistake, but what is its purpose? When should I check for null values and when is it unnecessary?

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    if (navigationView != null) {
        setupDrawerContent(navigationView);
    }

    ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
    if (viewPager != null) {
        setupViewPager(viewPager);
    }

...

private void setupViewPager(ViewPager viewPager) {
    Adapter adapter = new Adapter(getSupportFragmentManager());
    adapter.addFragment(new CheeseListFragment(), "Category 1");
    adapter.addFragment(new CheeseListFragment(), "Category 2");
    adapter.addFragment(new CheeseListFragment(), "Category 3");
    viewPager.setAdapter(adapter);
}

private void setupDrawerContent(NavigationView navigationView) {
    navigationView.setNavigationItemSelectedListener(
            new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {
            menuItem.setChecked(true);

Body:
The main purpose of using the below mentioned code is to make sure that the viewPager is never returning a null value before setting up which will result in the app crash. The person using this code is trying to play safe with the code and making sure that the app will work as expected and will not crash under any circumstances due to viewPager returning null value.

if (viewPager != null) {
   setupViewPager(viewPager);
}


问:
List of all special characters that need to be escaped in a regex
I am trying to create an application that matches a message template with a message that a user is trying to send. I am using Java regex for matching the message. The template/message may contain special characters.

How would I get the complete list of special characters that need to be escaped in order for my regex to work and match in the maximum possible cases?

Is there a universal solution for escaping all special characters in Java regex?

答:
Combining what everyone said, I propose the following, to keep the list of characters special to RegExp clearly listed in their own String, and to avoid having to try to visually parse thousands of "\\"'s.  This seems to work pretty well for me:</p>

```<code>final String regExSpecialChars = "<([{\\^-=$!|]})?*+.>";
final String regExSpecialCharsRE = regExSpecialChars.replaceAll( ".", "\\\\$0");
final Pattern reCharsREP = Pattern.compile( "[" + regExSpecialCharsRE + "]");

String quoteRegExSpecialChars( String s)
{
    Matcher m = reCharsREP.matcher( s);
    return m.replaceAll( "\\\\$0");
}
</code>```

Body:
Combining what everyone said, I propose the following, to keep the list of characters special to RegExp clearly listed in their own String, and to avoid having to try to visually parse thousands of "\\"'s.  This seems to work pretty well for me:

final String regExSpecialChars = "<([{\\^-=$!|]})?*+.>";
final String regExSpecialCharsRE = regExSpecialChars.replaceAll( ".", "\\\\$0");
final Pattern reCharsREP = Pattern.compile( "[" + regExSpecialCharsRE + "]");

String quoteRegExSpecialChars( String s)
{
    Matcher m = reCharsREP.matcher( s);
    return m.replaceAll( "\\\\$0");
}


答:
As Ward Bell said(https://devchat.tv/adv-in-angular/119-aia-avoiding-common-pitfalls-in-angular2):

As long as you only have one module in your application and you threw
  everything in there, you were benefiting from the common module hiding
  inside the browser module. The minute you create a new module, lazy or
  not, any new module and you declare anything into it, that new module
  has a clean state. It has no knowledge of anything, Angular or
  anything. It’s any module, not a lazy module in which you declare
  something, you’re going to have to import everything that you actually
  need for any of the component you declared in it. That’s why you
  needed common module

Modules don't inherit access to the components, directives, or pipes that are declared in other modules. (https://angular.io/guide/ngmodule#add-the-contactmodule see orange block)

That's why you have to import CommonModule to have access to ngIf, ngFor and so on directives. Your module doesn't know anything about directives from other modules. It only looks at its declarations and exports from imported modules

See also:

Angular 2 Use component from another module

Title: why lazy loaded module has to import commonModule? Angular 2

Body: When we import BrowserModule in root module of application ,we can use NgIf and NgFor( in eagerly loaded component). But for lazy loaded modules I have to import CommonModule which has been exported by BrowserModule of root. SO why do we have to import it again in lazy loaded module?


问:
How to edit and update table row dynamically in jquery and HTML
I am adding rows to table dynamically,now i am trying to edit table rows.

I click on edit, values are getting in text boxes after edit values i am clicking the add button but i created like new row not updated.

Any mistakes in my code

```<code><form class="form-horizontal" role="form" id="chargesForm">
            <div class="col-md-6">
                 <div class="form-group ">
                    <label for="minAmt" class="col-lg-4 control-label">MinAmmount</label>
                    <div class="col-lg-6">
                       <input type="text" class="form-control" id="minAmt" name="minAmt" />
                    </div>
                 </div>
                 <div class="form-group ">
                    <label for="maxAmt" class="col-lg-4 control-label">MaxAmmount</label>
                    <div class="col-lg-6">
                       <input type="text" class="form-control" id="maxAmt" name="maxAmt"/>
                    </div>
                 </div>

              </div>
              <div class="col-md-6">
                 <div class="form-group ">
                    <label for="type" class="col-lg-4 control-label">Type</label>
                    <select size="1" id="type" name="type">
                       <option value="Flat" selected="selected">
                          Flat
                       </option>
                       <option value="Percentage">
                          Percentage
                       </option>
                    </select>
                 </div>

              </div>

              <div class="col-md-12">
                 <div class="form-actions btnzone">
                    <button type="button" class="btn btn-success savebtn" style="padding: 6px 12px;margin-left: 40%;" id="savebutton" ><i class="icon-check-sign" aria-hidden="false"></i>Add</button>
                    <a class="btn btn-danger" ><i class=""></i>Back</a>

                 </div>
              </div>
           </form>
           <form  class="form-horizontal" role="form" id="chargestableForm">
              <div class="col-md-12" style="height:150px;overflow:auto;margin-top:5px;">
                 <table id="charges" class="table table-hover" width="100%" cellspacing="0" style="border: 1px; height:10px;" >
                    <thead style="background-color:#CCE5FF">
                       <tr>
                          <th>MinAmmount</th>
                          <th>MaxAmmount</th>
                          <th>Type</th>
                          <th></th>
                          <th></th>
                       </tr>
                    </thead>
                    <tbody>
                    </tbody>
                 </table>
              </div>
           </form>
</code>```

i added rows with the help of jquery

```<code>var i=0;
                            $("button#savebutton").click(function(){
                                var minAmt=$("#minAmt").val();
                                var maxAmt=$("#maxAmt").val();
                                var type=$("#type").val();
                                i++;
                                var new_row = "<tr id='row"+i+"' class='info'><td class='minAmt'>" + minAmt + "</td><td class='maxAmt'>" + maxAmt + "</td><td class='type'>" + type + "</td><td><span class='editrow'><a class='fa fa-edit' href='javascript: void(0);'></a></span></td><td><span class='deleterow'><a class='glyphicon glyphicon-trash' href=''></a></span></tr>";
                                 $("table tbody").append(new_row);
                                 $("#minAmt").val($('td.maxAmt').last().text()).prop("disabled","disabled");
                                 $("#maxAmt").val('');
                                 //$("#type").val('');
                            });

                        $(document).on('click', 'span.deleterow', function () {
                                $(this).parents('tr').remove();
                               return false;
                        });
                        $(document).on('click', 'span.editrow', function () {
                        $("#minAmt").val($(this).closest('tr').find('td.minAmt').text()).prop("disabled","disabled");
                        $("#maxAmt").val($(this).closest('tr').find('td.maxAmt').text()).prop("disabled","disabled");
                        $("#type").val($(this).closest('tr').find('td.type').text());
                        });
</code>```

答:
Hi you can follow this link, I have used your code and updated it a lil.

link: https://jsfiddle.net/u7ycrxph/

Updated Code :

```<code> currentRow = null;
 $("button#savebutton").click(function(){
 //....

 if(currentRow){

                  $("table tbody").find($(currentRow)).replaceWith(new_row);
                              currentRow = null;
                             }
                             else{
                             $("table tbody").append(new_row);
                             }
....//
});

$(document).on('click', 'span.editrow', function () {
 currentRow= $(this).parents('tr');
//....
});
</code>```

Body:
I am adding rows to table dynamically,now i am trying to edit table rows.

I click on edit, values are getting in text boxes after edit values i am clicking the add button but i created like new row not updated.

Any mistakes in my code

<form class="form-horizontal" role="form" id="chargesForm">

                    MinAmmount

                       <input type="text" class="form-control" id="minAmt" name="minAmt" />

                    MaxAmmount

                       <input type="text" class="form-control" id="maxAmt" name="maxAmt"/>

                    Type
                    <select size="1" id="type" name="type">
                       <option value="Flat" selected="selected">
                          Flat
                       </option>
                       <option value="Percentage">
                          Percentage
                       </option>
                    </select>

                    <button type="button" class="btn btn-success savebtn" style="padding: 6px 12px;margin-left: 40%;" id="savebutton" >Add</button>
                    Back

           </form>
           <form  class="form-horizontal" role="form" id="chargestableForm">

                          MinAmmount
                          MaxAmmount
                          Type

           </form>

i added rows with the help of jquery

var i=0;
                            $("button#savebutton").click(function(){
                                var minAmt=$("#minAmt").val();
                                var maxAmt=$("#maxAmt").val();
                                var type=$("#type").val();
                                i++;
                                var new_row = "
" + minAmt + "	" + maxAmt + "	" + type + "
";
                                 $("table tbody").append(new_row);
                                 $("#minAmt").val($('td.maxAmt').last().text()).prop("disabled","disabled");
                                 $("#maxAmt").val('');
                                 //$("#type").val('');
                            });

                        $(document).on('click', 'span.deleterow', function () {
                                $(this).parents('tr').remove();
                               return false;
                        });
                        $(document).on('click', 'span.editrow', function () {
                        $("#minAmt").val($(this).closest('tr').find('td.minAmt').text()).prop("disabled","disabled");
                        $("#maxAmt").val($(this).closest('tr').find('td.maxAmt').text()).prop("disabled","disabled");
                        $("#type").val($(this).closest('tr').find('td.type').text());
                        });

Body:
Hi you can follow this link, I have used your code and updated it a lil.

link: https://jsfiddle.net/u7ycrxph/

Updated Code :

 currentRow = null;
 $("button#savebutton").click(function(){
 //....

 if(currentRow){

                  $("table tbody").find($(currentRow)).replaceWith(new_row);
                              currentRow = null;
                             }
                             else{
                             $("table tbody").append(new_row);
                             }
....//
});

$(document).on('click', 'span.editrow', function () {
 currentRow= $(this).parents('tr');
//....
});