问:
library not recognised in reactjs
clicke here to see pondjs folder inside node-modulesI've installed pondjs(https://www.npmjs.com/package/pondjs) using npm install pondjs --save in my react application. It's also present in package.json. I couldn't understand why in App. js when I'm doing :

```<code>import { TimeSeries , TimeRange} from 'pondjs';
</code>```

it says module not installed and hence unable to recognise it's functions.

Also, I have a js file which contains lots of data in Object form  and I'm trying to import that file in App.js using :

```<code>import pathtofile/inputdata.js';
</code>```

and storing in the variable as below :

```<code>var input_data = data;
</code>```

IS this the right way to do in react App.js file?  Please suggest

答:
As there are 2 parts to your question. I will answer them in order.

Your first question was you weren't able to call the methods of pondjs even though you installed it.

For that make sure that there is your pondjs folder inside the node_modules folder that will be created when you install some packages in your repository.

EDIT :

Are you only having issues with pondjs or are you facing issues with
  all packages?

If you can find the installed package in node_modules folder and is
  facing the same issue for all packages, upgrade npm. Your problem is
  that it doesn't search in the right folder. Try upgrading npm so
  that it places files in the right spots.

If it's only for pondjs issue might be with the package rather that
  with your npm package. Make sure you read documentation right and
  are doing in the right way.

Coming to your second problem.

Export the variable you want to access in the other file.

```<code>var obj = {
    a : [1, 2, 3, 4],
    b : { c : 'Hello World!' }
}

export var obj;
</code>```

And call it like,

```<code>import { obj } from './path/to/the/file.js'
</code>```

Title: library not recognised in reactjs

Body:
clicke here to see pondjs folder inside node-modulesI've installed pondjs(https://www.npmjs.com/package/pondjs) using npm install pondjs --save in my react application. It's also present in package.json. I couldn't understand why in App. js when I'm doing :

import { TimeSeries , TimeRange} from 'pondjs';

it says module not installed and hence unable to recognise it's functions.

Also, I have a js file which contains lots of data in Object form  and I'm trying to import that file in App.js using :

import pathtofile/inputdata.js';

and storing in the variable as below :

var input_data = data;

IS this the right way to do in react App.js file?  Please suggest

Body:
As there are 2 parts to your question. I will answer them in order.

Your first question was you weren't able to call the methods of pondjs even though you installed it.

For that make sure that there is your pondjs folder inside the node_modules folder that will be created when you install some packages in your repository.

EDIT :

Are you only having issues with pondjs or are you facing issues with
  all packages?

If you can find the installed package in node_modules folder and is
  facing the same issue for all packages, upgrade npm. Your problem is
  that it doesn't search in the right folder. Try upgrading npm so
  that it places files in the right spots.

If it's only for pondjs issue might be with the package rather that
  with your npm package. Make sure you read documentation right and
  are doing in the right way.

Coming to your second problem.

Export the variable you want to access in the other file.

var obj = {
    a : [1, 2, 3, 4],
    b : { c : 'Hello World!' }
}

export var obj;

And call it like,

import { obj } from './path/to/the/file.js'


来源: stackexchange

问:
Spark streaming application configuration with YARN
I'm trying to squeeze every single bit from my cluster when configuring the spark application but it seems I'm not understanding everything completely right. So I'm running the application on an AWS EMR cluster with 1 master and 2 core nodes from type m3.xlarge(15G ram and 4 vCPU for every node). This means that by default 11.25 GB are reserved on every node for applications scheduled by yarn. So the master node is used only by the resource manager(yarn) and that means the remaining 2 core nodes will be used to schedule applications(so we have 22.5G for that purpose). So far so good. But here comes the part which I don't get. I'm starting the spark application with the following parameters:

--driver-memory 4G --num-executors 4 --executor-cores 7 --executor-memory 4G

What this means by my perceptions(from what I found as information) is that for the driver will be allocated 4G and 4 executors will be launched with 4G every one of them. So a rough estimate makes it 5*4=20G(lets make them 21G with the expected memory reserves), which should be fine as we have 22.5G for applications. Here's a screenshot from the UI of the hadoop yarn after the launch:

What we can see is that 17.63 are used by the application but this a little bit less than the expected ~21G and this triggers the first question- what did happen here?

Then I go to the spark UI's executors page. Here comes the bigger question:

The executors are 3(not 4), the memory allocated for them and the driver  is 2.1G(not the specified 4G). So hadoop yarn says 17.63G are used, but the spark says 8.4G are allocated. So, what is happening here? Is this related to the Capacity Scheduler(from the documentation I couldn't come up with this conclusion)?

答:
Can you check whether spark.dynamicAllocation.enabled is turned on. If that is the case then spark your application may give resources back to the cluster if they are no longer used. The minimum number of executors to be launched at the startup will be decided by spark.executor.instances.

If that is not the case, what is your source for spark application and what is the partition size set for that, spark will literally map the partition size to the spark cores, if your source has only 10 partitions, and when you try to allocate 15 cores it will only use 10 cores because that is what is needed. I guess this might be the cause that spark has launched 3 executors instead of 4. Regarding memory i would recommend to revisit because you are asking for 4 executors and 1 driver with 4Gb each which would be 5*4+5*384MB approx equals to 22GB and you are trying to use up everything and not much is left for your OS and nodemanager to run that would not be the ideal way to do.

ContentLicense: CC BY-SA 3.0


问:
Python Parsing Framework
If I needed facilitate the extraction of data from various (non-API) internet sources, is there a framework-type solution that would streamline the process of having developers write reusable, yet source specific parsers on a large scale?</p>

答: For *ML screen scraping, look no further than Beautiful Soup.</p>

ContentLicense: CC BY-SA 2.5

Title: Python Parsing Framework


问:
How to prevent opening external app by change location.href in WKWebView?
E.g. Aliexpress. If i have installed aliexpress app - it runs by clicking links on website, with javascript code: location.href = aliexpress://.....

I need open app-scheme:// manually, by calling UIApplication.shared.openURL(), but not need auto-opening through WKWebView.

答:
Most probably external URLs are thrown to createWebViewWith Configuration: method.
Check this once, set your WKUIDelegate as self,

```<code>webview.UIDelegate = self
</code>```

then implement the following delegate and handle the URL load properly,

```<code>public func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView?
    {
           //check the URL, either block it or handle it here.
            webView.load(navigationAction.request)
            return nil
    }
</code>```

Refer: Apple Docs

Body:
Most probably external URLs are thrown to createWebViewWith Configuration: method.
Check this once, set your WKUIDelegate as self,

webview.UIDelegate = self

then implement the following delegate and handle the URL load properly,

public func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView?
    {
           //check the URL, either block it or handle it here.
            webView.load(navigationAction.request)
            return nil
    }

Refer: Apple Docs


问:
How to install FireBase Server Sdk in Android?
I'm trying to add firebase server sdk library in my android app.
I inserted this code

```<code>dependencies {
  compile 'com.google.firebase:firebase-server-sdk:[3.0.0,)'
}
</code>```

into build.gradle(app).
Then when I sync gradle, there comes an error message.

```<code>Error:Conflict with dependency 'com.google.code.findbugs:jsr305' in project
':app'. Resolved versions for app (1.3.9) and test app (2.0.1) differ. See
http://g.co/androidstudio/app-test-app-conflict for details.
</code>```

How can I solve this problem?
Thank you!

答:
You need to make sure that both main APK and test APK share the same version of Firebase SDK.

For future reference use the error message that is provided and check out App test conflict as instructed.

Body:
I'm trying to add firebase server sdk library in my android app.
I inserted this code

dependencies {
  compile 'com.google.firebase:firebase-server-sdk:[3.0.0,)'
}

into build.gradle(app).
Then when I sync gradle, there comes an error message.

Error:Conflict with dependency 'com.google.code.findbugs:jsr305' in project
':app'. Resolved versions for app (1.3.9) and test app (2.0.1) differ. See
http://g.co/androidstudio/app-test-app-conflict for details.

How can I solve this problem?
Thank you!


问:
How does akka compare to Erlang?
I've been looking at akka recently and it's pretty impressive. It looks like it has most of the killer features of erlang - location transparency, supervision hierarchies, and more. Are there any features erlang has that akka doesn't?</p>

答:
For me, hot code swapping in an entire Erlang cluster without downtime (for example: make:all([netload]) is one of the Erlang killer features.

But let's reverse your question: What does akka have that Erlang doesn't?
Of course you can add dozens of extensions and libraries (scala, akka, spring, osgi, ...) to Java to try to come close to Erlang. But where is the point? In sum all these extensions are much more complex than learning the simple Erlang language that now has proven for over 2 decades that it can do the job offering top scalability with zero downtime.

Title: How does akka compare to Erlang?


问:
Process returned an error (exit code -3) in cake execution
While executing the cake script for test projects i'm getting,

```<code>    An error occurred when executing task 'test'.
    Error: System.Exception: DotCover: Process returned an error (exit code -3).
       at Submission#0.<.ctor>b__29(Exception exception)
       at Cake.Core.DefaultExecutionStrategy.HandleErrors(Action`1 action, Exception exception)
       at Cake.Core.CakeEngine.HandleErrors(IExecutionStrategy strategy, Action`1 errorHandler, Exception exception)
       at Cake.Core.CakeEngine.ExecuteTask(ICakeContext context, IExecutionStrategy strategy, Stopwatch stopWatch, CakeTask task, CakeReport report)
       at Cake.Core.CakeEngine.RunTarget(ICakeContext context, IExecutionStrategy strategy, String target)
       at Cake.Scripting.BuildScriptHost.RunTarget(String target)
       at Submission#0.<.ctor>b__31()
       at Cake.Core.ActionTask.Execute(ICakeContext context)
       at Cake.Core.DefaultExecutionStrategy.Execute(CakeTask task, ICakeContext context)
       at Cake.Core.CakeEngine.ExecuteTask(ICakeContext context, IExecutionStrategy strategy, Stopwatch stopWatch, CakeTask task, CakeReport report)
       at Cake.Core.CakeEngine.RunTarget(ICakeContext context, IExecutionStrategy strategy, String target)
       at Cake.Scripting.BuildScriptHost.RunTarget(String target)
       at Submission#0..ctor(Session session, Object& submissionResult)
       at Submission#0.<Factory>(Session session)
       at Roslyn.Scripting.CommonScriptEngine.Execute[T](String code, String path, DiagnosticBag diagnostics, Session session, Boolean isInteractive)
       at Roslyn.Scripting.Session.Execute(String code)
       at Cake.Core.Scripting.ScriptRunner.Run(IScriptHost host, FilePath scriptPath, IDictionary`2 arguments)
       at Cake.Commands.BuildCommand.Execute(CakeOptions options)
       at Cake.CakeApplication.Run(CakeOptions options)
       at Cake.Program.Main()
</code>```

How can i solve this problem?

答:
Cake simply returns the exit code from the underlying tool, in this case DotCover.  If you run Cake in diagnostic mode:

How to enable diagnostic verbosity for Cake

You should be able to grab the exact DotCover command that is being executed, and then you can run it manually at the command line.  At which point, the output will likely again be -3.

What I am saying is, this is most likely an issue with DotCover analysing your application, rather than an issue with Cake.

Body:
While executing the cake script for test projects i'm getting,

    An error occurred when executing task 'test'.
    Error: System.Exception: DotCover: Process returned an error (exit code -3).
       at Submission#0.<.ctor>b__29(Exception exception)
       at Cake.Core.DefaultExecutionStrategy.HandleErrors(Action`1 action, Exception exception)
       at Cake.Core.CakeEngine.HandleErrors(IExecutionStrategy strategy, Action`1 errorHandler, Exception exception)
       at Cake.Core.CakeEngine.ExecuteTask(ICakeContext context, IExecutionStrategy strategy, Stopwatch stopWatch, CakeTask task, CakeReport report)
       at Cake.Core.CakeEngine.RunTarget(ICakeContext context, IExecutionStrategy strategy, String target)
       at Cake.Scripting.BuildScriptHost.RunTarget(String target)
       at Submission#0.<.ctor>b__31()
       at Cake.Core.ActionTask.Execute(ICakeContext context)
       at Cake.Core.DefaultExecutionStrategy.Execute(CakeTask task, ICakeContext context)
       at Cake.Core.CakeEngine.ExecuteTask(ICakeContext context, IExecutionStrategy strategy, Stopwatch stopWatch, CakeTask task, CakeReport report)
       at Cake.Core.CakeEngine.RunTarget(ICakeContext context, IExecutionStrategy strategy, String target)
       at Cake.Scripting.BuildScriptHost.RunTarget(String target)
       at Submission#0..ctor(Session session, Object& submissionResult)
       at Submission#0.<Factory>(Session session)
       at Roslyn.Scripting.CommonScriptEngine.Execute[T](String code, String path, DiagnosticBag diagnostics, Session session, Boolean isInteractive)
       at Roslyn.Scripting.Session.Execute(String code)
       at Cake.Core.Scripting.ScriptRunner.Run(IScriptHost host, FilePath scriptPath, IDictionary`2 arguments)
       at Cake.Commands.BuildCommand.Execute(CakeOptions options)
       at Cake.CakeApplication.Run(CakeOptions options)
       at Cake.Program.Main()

How can i solve this problem?


问:
Excel if Function,select cell in line with match
Here is my problem .

I have an excel workbook with 2 sheets with the same fields but different amount of records. Both sheets have an ID field and date field.

If the ID from column a of sheet 2 exists in column a of sheet 1 then I want to use the date field from sheet 2 to populate the date field in sheet 1 for that matching ID.

Please help me figure this out. I can post sample data.

Thank you

答:
As suggested by @L42 VLOOKUP  can be used for your situation. A simple example mentioned below can guide you to adopt it to your situation.
There are four pieces of information that you will need in order to build the VLOOKUP syntax:

The value you want to look up, also called the lookup value.

The range where the lookup value is located. Remember that the lookup value should always be in the first column in the range for VLOOKUP to work correctly. For example, if your lookup value is in cell C2 then your range should start with C.

The column number in the range that contains the return value. For example, if you specify B2: D11 as the range, you should count B as the first column, C as the second, and so on.

Optionally, you can specify TRUE if you want an approximate match or FALSE if you want an exact match of the return value. If you don't specify anything, the default value will always be TRUE or approximate match.

Now put all of the above together as follows:

```<code>=VLOOKUP(lookup value, range containing the lookup value, the column number in the range containing the return value, optionally specify TRUE for approximate match or FALSE for an exact match).
</code>```

In the sample data shown in the sheet1 and sheet2. Shee2 has ID column and Date column. Formula to be put in cell B2 of Sheet1 is:

```<code>   =VLOOKUP($A2, Sheet2!$A$2:$B$6,2,0)
</code>```

Fill down the formula and it will correctly pick dates from Sheet2 and fill in sheet1. Sample data screenshots are placed below.

Body:
As suggested by @L42 VLOOKUP  can be used for your situation. A simple example mentioned below can guide you to adopt it to your situation.
There are four pieces of information that you will need in order to build the VLOOKUP syntax:

The value you want to look up, also called the lookup value.

The range where the lookup value is located. Remember that the lookup value should always be in the first column in the range for VLOOKUP to work correctly. For example, if your lookup value is in cell C2 then your range should start with C.

The column number in the range that contains the return value. For example, if you specify B2: D11 as the range, you should count B as the first column, C as the second, and so on.

Optionally, you can specify TRUE if you want an approximate match or FALSE if you want an exact match of the return value. If you don't specify anything, the default value will always be TRUE or approximate match.

Now put all of the above together as follows:

=VLOOKUP(lookup value, range containing the lookup value, the column number in the range containing the return value, optionally specify TRUE for approximate match or FALSE for an exact match).

In the sample data shown in the sheet1 and sheet2. Shee2 has ID column and Date column. Formula to be put in cell B2 of Sheet1 is:

   =VLOOKUP($A2, Sheet2!$A$2:$B$6,2,0)

Fill down the formula and it will correctly pick dates from Sheet2 and fill in sheet1. Sample data screenshots are placed below.


问:
Index numbers for row-wise duplicate entries using numpy/pandas in python
I have a numpy array/pandas data frame

```<code>[[0 0 0 1],
 [1 0 0 1],
 [0 0 0 1],
 [1 0 0 1],
 [0 0 0 1],
 [0 0 1 0],
 [0 0 1 0]]
</code>```

I need index number of row duplicates for this array. The results should be something like (0,2,4), (1,3), (5,6).

So far I have a work around, like I am running loops, one with unique values of the array rows against the actual array rows. That gives me results but not in the fashion I would want them to be.
This is the code I have made which gives me pairs but for a large array, this is very messy.

```<code>for i, row in enumerate(array):
    for j, row1 in enumerate(unique(array)):
        if tuple(row)==tuple(row1):
            pair.append(tuple([j,i]))
</code>```

my results looks like this:

```<code> [(0, 276),(1, 2931),(2, 3891),(3, 2165),(4, 1822),(5, 1241),
 (5, 2635),(5, 2644),(5, 2862),(5, 3296)]
</code>```

My array is very big, so this way I am manually choosing tuples based on the first value as the indicator for duplicates, then I choose the actual row number which is a duplicate. for Ex. - tuples having 5 as their first value mean row 1241 is duplicated at 2635, 2644, 2862 and 3296.

Can anyone suggest me a better way to work on this problem.
I have looked around here but nothing concrete I could get.

答:
The numpy_indexed package (disclaimer: I am its author) aims to enrich numpy with functionality of this kind, and using it, your problem can be written as a simple and readable one-liner:

```<code>import numpy_indexed as npi
idx_groups = npi.group_by(array).split(np.arange(len(array)))
</code>```

Note that chances are, these indices are not actually the end result you are after, but are needed for a subsequent calculation; numpy_indexed has a lot of functionality for those type of common situations as well; so perhaps if you give some more context to your question, a more refined solution could be given too.

Body:
I have a numpy array/pandas data frame

[[0 0 0 1],
 [1 0 0 1],
 [0 0 0 1],
 [1 0 0 1],
 [0 0 0 1],
 [0 0 1 0],
 [0 0 1 0]]

I need index number of row duplicates for this array. The results should be something like (0,2,4), (1,3), (5,6).

So far I have a work around, like I am running loops, one with unique values of the array rows against the actual array rows. That gives me results but not in the fashion I would want them to be.
This is the code I have made which gives me pairs but for a large array, this is very messy.

for i, row in enumerate(array):
    for j, row1 in enumerate(unique(array)):
        if tuple(row)==tuple(row1):
            pair.append(tuple([j,i]))

my results looks like this:

 [(0, 276),(1, 2931),(2, 3891),(3, 2165),(4, 1822),(5, 1241),
 (5, 2635),(5, 2644),(5, 2862),(5, 3296)]

My array is very big, so this way I am manually choosing tuples based on the first value as the indicator for duplicates, then I choose the actual row number which is a duplicate. for Ex. - tuples having 5 as their first value mean row 1241 is duplicated at 2635, 2644, 2862 and 3296.

Can anyone suggest me a better way to work on this problem.
I have looked around here but nothing concrete I could get.

Body:
The numpy_indexed package (disclaimer: I am its author) aims to enrich numpy with functionality of this kind, and using it, your problem can be written as a simple and readable one-liner:

import numpy_indexed as npi
idx_groups = npi.group_by(array).split(np.arange(len(array)))

Note that chances are, these indices are not actually the end result you are after, but are needed for a subsequent calculation; numpy_indexed has a lot of functionality for those type of common situations as well; so perhaps if you give some more context to your question, a more refined solution could be given too.


问:
calling ajax before submitting the form
I want to create a login screen in which,on the click of button the ajax verify the password and then then submit the form.but when i click submit button the form is submitted before the ajax call
in short the action method and ajax both call on the same button click,but i want to call ajax before action method

View

```<code>@using (Html.BeginForm("Login", "AccountAP", FormMethod.Post))

{

@Html.AntiForgeryToken()
        <div class="login-box">
            <div class="login-logo">
                <!-- /.login-logo -->
                <div class="login-box-body">
                    <center><a href="#"><img src="img/ra_logo.png" class="img-responsive" width="128" height="128" /></a></center>
                    <br />
                    <p class="login-box-msg" style="font-size:20px !important;">Sign in to start your session</p>
                    <div class="form-group has-feedback">
                        @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control", @placeholder = "Email" } })
                        @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
                    </div>
                    <div class="form-group has-feedback">
                        @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control", @placeholder = "Password" } })
                        @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
                    </div>

                    <div class="row">
                        <!-- /.col -->
                        <div class="col-xs-12">
                            <input type="submit" class="btn btn-primary pull-right btn-block btn-flat" value="Sign In" id="btnSave"/>
                        </div>
                        <!-- /.col -->
                    </div>
                </div>
                <!-- /.login-box-body -->
            </div>
        </div>
}
<script type="text/javascript">
        $('#btnSave').click(function (e) {
            e.preventDefault();
            e.alert("what's up");
        });
    </script>
</code>```

答:
Check below code for that :

First Method :

@using (Html.BeginForm("Login", "AccountAP", FormMethod.Post,new { id= "submitForm" }))
{

  <input type="submit" class="btn btn-primary pull-right btn-block btn-flat" value="Sign In" id="btnSave"/>

}

```
</div>
</div>
</p>

<p><strong>Second Method :</strong>
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>@using (Html.BeginForm("Login","AccountAP",FormMethod.Post, new { onsubmit = "myJsFunction()" }))</code>```

Your jquery code should be :

```<code><script>
    $(function () {
        $("#btnSave").submit(function (event) {
            event.preventDefault();
           e.alert("what's up");
          //Code for ajax verify the password then call below myJsFunction after validation
           myJsFunction();
        });
    });
</script>
</code>```

Title: calling ajax before submitting the form

Body:
I want to create a login screen in which,on the click of button the ajax verify the password and then then submit the form.but when i click submit button the form is submitted before the ajax call
in short the action method and ajax both call on the same button click,but i want to call ajax before action method

View

@using (Html.BeginForm("Login", "AccountAP", FormMethod.Post))

{

@Html.AntiForgeryToken()

Sign in to start your session

                        @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control", @placeholder = "Email" } })
                        @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })

                        @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control", @placeholder = "Password" } })
                        @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })

                            <input type="submit" class="btn btn-primary pull-right btn-block btn-flat" value="Sign In" id="btnSave"/>

}

Body:
Check below code for that :

First Method :

@using (Html.BeginForm("Login", "AccountAP", FormMethod.Post,new { id= "submitForm" }))
{
 <div class="col-xs-12">
  <input type="submit" class="btn btn-primary pull-right btn-block btn-flat" value="Sign In" id="btnSave"/>
  </div>
}

<script>
$(function () {
 $("#btnSave").click(function(){
 //Code for ajax verify the password then call below submitForm after validation

       $("#submitForm").submit();
    });
});
</script>

Second Method :

@using (Html.BeginForm("Login","AccountAP",FormMethod.Post, new { onsubmit = "myJsFunction()" }))

Your jquery code should be :

<script>
    $(function () {
        $("#btnSave").submit(function (event) {
            event.preventDefault();
           e.alert("what's up");
          //Code for ajax verify the password then call below myJsFunction after validation
           myJsFunction();
        });
    });
</script>


问:
What is the point of this line of code?
I found this line of code in the Virtuemart plugin for Joomla on line 2136 in administrator/components/com_virtuemart/classes/ps_product.php</p>

```<code>eval ("\$text_including_tax = \"$text_including_tax\";");
</code>```

答: Perhaps it's an attempt to cast the variable as a string? Just a guess.</p>

OwnerDisplayName: mk

Title: What is the point of this line of code?

Body:
I found this line of code in the Virtuemart plugin for Joomla on line 2136 in administrator/components/com_virtuemart/classes/ps_product.php

eval ("\$text_including_tax = \"$text_including_tax\";");

OwnerDisplayName: Tim Lytle


问:
Cordova dialog plugin not working
I've been stuck on this issue for 10+ hours now and I'm having no luck in fixing it by myself. The problem is that I'm trying to use this dialog plugin on my Cordova app but its not working. I don't even think that the deviceready script is working.

Any questions feel free to ask

www/index.html:

```<code><!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Security-Policy" content=".." />
        <meta name="format-detection" content="telephone=no">
        <meta name="msapplication-tap-highlight" content="no">
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
        <link rel="stylesheet" type="text/css" href="css/index.css">
        <link href="css/layout-styles.css" rel="stylesheet" type="text/css">
        <link href="css/bootstrap-3.3.7.css" rel="stylesheet" type="text/css">
        <script src="cordova_plugins.js"></script>
        <script src="cordova.js"></script>
        <script src="js/index.js"></script>
        <script src="js/jquery-3.1.1.min.js"></script>
        <script src="js/bootstrap.js"></script>
        <title>Plugins Not Working</title>

        <script src="cordova.js">

            document.addEventListener("deviceready", onDeviceReady(), false)

            function onDeviceReady() {
                navigator.notification.alert(
                    'Script has loaded',  // message
                    alertDismissed,       // callback
                    'Loaded',             // title
                    'Done'                // buttonName
                );
            };

            function alertDismissd() {
                // do something
            };

         </script>
    </head>
</html>
</code>```

The <plugin name="cordova-plugin-dialogs" spec="^1.3.3" /> is in config.xml

答:
Your code in
```

If it still doesn't work, can you inspect in Google Chrome, see and list the error messages under Console tab? There might be some error before that  That's not required. Plugins are directly called from js.

Cannot read property 'alert' of undefined => the plugin is not properly installed. Install it first using cordova plugin add cordova-plugin-dialogs in cmd.

Remove . As you are doing everything inside

Title: Cordova dialog plugin not working

Body:
I've been stuck on this issue for 10+ hours now and I'm having no luck in fixing it by myself. The problem is that I'm trying to use this dialog plugin on my Cordova app but its not working. I don't even think that the deviceready script is working.

Any questions feel free to ask

www/index.html:

<!DOCTYPE html>

        <meta http-equiv="Content-Security-Policy" content=".." />
        <meta name="format-detection" content="telephone=no">
        <meta name="msapplication-tap-highlight" content="no">
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
        <link rel="stylesheet" type="text/css" href="css/index.css">
        <link href="css/layout-styles.css" rel="stylesheet" type="text/css">
        <link href="css/bootstrap-3.3.7.css" rel="stylesheet" type="text/css">

        <title>Plugins Not Working</title>

The <plugin name="cordova-plugin-dialogs" spec="^1.3.3" /> is in config.xml

Body:
Your code in <script> tag seems alright. If you have added the dialogs plugin using -

cordova plugin add cordova-plugin-dialogs

that should work fine.

And don't add src="cordova.js" for the script containing your code. Just do this -

<script>
document.addEventListener("deviceready", onDeviceReady(), false)

function onDeviceReady() {
navigator.notification.alert(
   'Script has loaded',  // message
    alertDismissed,       // callback
    'Loaded',             // title
    'Done'                // buttonName
    );
};

function alertDismissd() {
     // do something
};

</script>

If it still doesn't work, can you inspect in Google Chrome, see and list the error messages under Console tab? There might be some error before that <script> if that onDeviceReady() is not triggered.

UPDATE after seeing error messages from here -

Remove <script src="cordova_plugins.js"></script> That's not required. Plugins are directly called from js.

Cannot read property 'alert' of undefined => the plugin is not properly installed. Install it first using cordova plugin add cordova-plugin-dialogs in cmd.

Remove <script src="js/index.js"></script>. As you are doing everything inside <script> tag, you don't need index.js or its js contents (has errors).


问:
JS Script link accepting PHP variables and showing %27
I have a
```

答:
You can use like this .remove space if it is present . </p>

```<code><?php
$price = 27;
?>
<script src="http://testSite.com/resources/js/animatedcollapse.js?type=calculator&min=50&max=400&amount=<?php echo $price;?>" type="text/javascript"></script>
</code>```

Body: I have a

Body:
You can use like this .remove space if it is present .

<?php
$price = 27;
?>
<script src="http://testSite.com/resources/js/animatedcollapse.js?type=calculator&min=50&max=400&amount=<?php echo $price;?>" type="text/javascript"></script>


问:
Download documents from SharePoint using office 365 API
I have a office 365 SharePoint site as https://myCorporateSharePoint.sharepoint.com/sites/MyApplication

I need to download some documents uploaded in this location with my application > I have already done the application configuration in the Azure AD and got the client ID and the key . Now I have to download the file from the sharepoint location . Any code snippets on this on how this can be done ?

答:
You can get the App only context using a SharePoint helper class. To Get the App only context refer here. Also refer the AddIn Authorization Policies.

To download a document from SharePoint, refer here


问:
Can I increase linux entropy by using rng-daemon without hardware generator?
I want to continuously increase /prco/sys/random/entropy_avail when it reduced.

I first check the rngd (https://wiki.archlinux.org/index.php/Rng-tools)

It says /dev/random is very slow since it only collects entropy from device drivers and other (slow) sources and I think that is why we use rngd.

And it says rngd mainly uses hardware random number generators (TRNG), present in modern hardware like recent AMD/Intel processors, VIA Nano or even Raspberry Pi.

However, when I start rngd it says

```<code>[root@localhost init.d]# rngd
can't open entropy source(tpm or intel/amd rng)
Maybe RNG device modules are not loaded
</code>```

But I don't have Intel RDRAND confirmed by cat /proc/cpuinfo | grep rdrand:

```<code>[root@localhost init.d]# cat /proc/cpuinfo | grep rdrand | wc -l
0
</code>```

If there is any possible resources that I can use?

Alternatively, is it possible making script to increase /proc/sys/random/entropy_avail?

答:
Try this:

sudo apt-get install haveged

Body:
I want to continuously increase /prco/sys/random/entropy_avail when it reduced.

I first check the rngd (https://wiki.archlinux.org/index.php/Rng-tools)

It says /dev/random is very slow since it only collects entropy from device drivers and other (slow) sources and I think that is why we use rngd.

And it says rngd mainly uses hardware random number generators (TRNG), present in modern hardware like recent AMD/Intel processors, VIA Nano or even Raspberry Pi.

However, when I start rngd it says

[root@localhost init.d]# rngd
can't open entropy source(tpm or intel/amd rng)
Maybe RNG device modules are not loaded

But I don't have Intel RDRAND confirmed by cat /proc/cpuinfo | grep rdrand:

[root@localhost init.d]# cat /proc/cpuinfo | grep rdrand | wc -l
0

If there is any possible resources that I can use?

Alternatively, is it possible making script to increase /proc/sys/random/entropy_avail?

Body:
Try this:

sudo apt-get install haveged


问:
OracleDataAdapter, Fill method hangs, how do I handle connection terminations/drop offs/cut outs?
I have a C# program that connects to a remote server to query data. The data is quite big so the query takes about 2 mins to finish. During this 2 min window, the internet went down. This resulted in the job being unable to finish with the program stuck in the getting data routine.

It established connection but during the select query it was cut off. Setting the command timeout to 30 seconds did not work. I need the query to fail when encountering this error because the program can handle failure but it cannot handle being stuck. Thanks!

UPDATE: included code

```<code>OracleConnection connection = new OracleConnection(connectionstring);
OracleDataAdapter oracleDataAdapter = new OracleDataAdapter(new OracleCommand(query, connection));
oracleDataAdapter.SelectCommand.CommandTimeout = 30;

  DataSet dataSet = new DataSet();
  try
  {
    oracleDataAdapter.Fill(dataSet, table); //Hangs on this line when connection is lost
    return dataSet;
  }
  catch
  {
    throw;
  }
  finally
  {
    dataSet.Dispose();
    oracleDataAdapter.Dispose();
  }
</code>```

UPDATE AGAIN:

What I need to do is handle this situation because I don't want a dangling process.

Simplest would be once the connection is lost is that the program will throw an error. That is what I don't know how to do. I assumed that the commandtimeout will fix it but it did not.

答:
Updated answer:  </p>

```<code>        DataSet dataset = new DataSet();

        using (OracleConnection connection = new OracleConnection(connection))
        {
            using (OracleDataAdapter oracleDataAdapter = new OracleDataAdapter(new OracleCommand(query, connection)))
            {
                oracleDataAdapter.SelectCommand.CommandTimeout = 30;
                connection.Open();
                oracleDataAdapter.Fill(dataset, table);
            }
        }

        return dataset;
</code>```

Body:
I have a C# program that connects to a remote server to query data. The data is quite big so the query takes about 2 mins to finish. During this 2 min window, the internet went down. This resulted in the job being unable to finish with the program stuck in the getting data routine.

It established connection but during the select query it was cut off. Setting the command timeout to 30 seconds did not work. I need the query to fail when encountering this error because the program can handle failure but it cannot handle being stuck. Thanks!

UPDATE: included code

OracleConnection connection = new OracleConnection(connectionstring);
OracleDataAdapter oracleDataAdapter = new OracleDataAdapter(new OracleCommand(query, connection));
oracleDataAdapter.SelectCommand.CommandTimeout = 30;

  DataSet dataSet = new DataSet();
  try
  {
    oracleDataAdapter.Fill(dataSet, table); //Hangs on this line when connection is lost
    return dataSet;
  }
  catch
  {
    throw;
  }
  finally
  {
    dataSet.Dispose();
    oracleDataAdapter.Dispose();
  }

UPDATE AGAIN:

What I need to do is handle this situation because I don't want a dangling process.

Simplest would be once the connection is lost is that the program will throw an error. That is what I don't know how to do. I assumed that the commandtimeout will fix it but it did not.

Body:
Updated answer:

        DataSet dataset = new DataSet();

        using (OracleConnection connection = new OracleConnection(connection))
        {
            using (OracleDataAdapter oracleDataAdapter = new OracleDataAdapter(new OracleCommand(query, connection)))
            {
                oracleDataAdapter.SelectCommand.CommandTimeout = 30;
                connection.Open();
                oracleDataAdapter.Fill(dataset, table);
            }
        }

        return dataset;


问:
How to solve Timeout FeignClient
My application is getting below error when consuming a service that performs queries in SQL Server using FeignClient.

ERROR:

Exception in thread "pool-10-thread-14" feign.RetryableException: Read timed out executing GET
  http://127.0.0.1:8876/processoData/search/buscaProcessoPorCliente?cliente=ELEKTRO+-+TRABALHISTA&estado=SP

My Consumer Service:

```<code>@FeignClient(url="http://127.0.0.1:8876")
public interface ProcessoConsumer {

@RequestMapping(method = RequestMethod.GET, value = "/processoData/search/buscaProcessoPorCliente?cliente={cliente}&estado={estado}")
public PagedResources<ProcessoDTO> buscaProcessoClienteEstado(@PathVariable("cliente") String cliente, @PathVariable("estado") String estado);

}
</code>```

My YML:

```<code>server:
  port: 8874

endpoints:
  restart:
    enabled: true
  shutdown:
    enabled: true
  health:
    sensitive: false

eureka:
  client:
  serviceUrl:
    defaultZone: ${vcap.services.eureka-service.credentials.uri:http://xxx.xx.xxx.xx:8764}/eureka/
  instance:
    preferIpAddress: true

ribbon:
  eureka:
    enabled: true

spring:
  application:
    name: MyApplication
  data:
    mongodb:
      host: xxx.xx.xxx.xx
      port: 27017
      uri: mongodb://xxx.xx.xxx.xx/recortesExtrator
      repositories.enabled: true
    solr:
      host: http://xxx.xx.xxx.xx:8983/solr
      repositories.enabled: true
</code>```

Anyone know how to solve this?

Thanks.

答:
```<code>hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=6000
ribbon.ReadTimeout=60000
ribbon.ConnectTimeout=60000
</code>```

make sure ribbon's timeout is bigger than hystrix

Title: How to solve Timeout FeignClient

Body:
My application is getting below error when consuming a service that performs queries in SQL Server using FeignClient.

ERROR:

Exception in thread "pool-10-thread-14" feign.RetryableException: Read timed out executing GET
  http://127.0.0.1:8876/processoData/search/buscaProcessoPorCliente?cliente=ELEKTRO+-+TRABALHISTA&estado=SP

My Consumer Service:

@FeignClient(url="http://127.0.0.1:8876")
public interface ProcessoConsumer {

@RequestMapping(method = RequestMethod.GET, value = "/processoData/search/buscaProcessoPorCliente?cliente={cliente}&estado={estado}")
public PagedResources<ProcessoDTO> buscaProcessoClienteEstado(@PathVariable("cliente") String cliente, @PathVariable("estado") String estado);

}

My YML:

server:
  port: 8874

endpoints:
  restart:
    enabled: true
  shutdown:
    enabled: true
  health:
    sensitive: false

eureka:
  client:
  serviceUrl:
    defaultZone: ${vcap.services.eureka-service.credentials.uri:http://xxx.xx.xxx.xx:8764}/eureka/
  instance:
    preferIpAddress: true

ribbon:
  eureka:
    enabled: true

spring:
  application:
    name: MyApplication
  data:
    mongodb:
      host: xxx.xx.xxx.xx
      port: 27017
      uri: mongodb://xxx.xx.xxx.xx/recortesExtrator
      repositories.enabled: true
    solr:
      host: http://xxx.xx.xxx.xx:8983/solr
      repositories.enabled: true

Anyone know how to solve this?

Thanks.

Body:
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=6000
ribbon.ReadTimeout=60000
ribbon.ConnectTimeout=60000

make sure ribbon's timeout is bigger than hystrix


问:
Android - Resuming Camera Activity gets delayed
I was working on Camera Modules, and the only issue here is when I try to retake the camera, it will get delayed for a few secs before opening the Camera Preview again (see First image). Please take a look at my Camera Preview looks below

This is after i took the photo

When I click the retake button (middle one), it will take some times to reload the Camera Preview (first image). I've tried another app and found that when it retakes the photo, it will go to previous Camera Preview instantly (without delay), its like going back to previous page.

In Camera Preview, I implemented some canvas draw to create the overlay view. But I think it's not the problem, because the other app that i said previously also takes some times to load the Camera Preview at first. But, the only different is when they retake the photo, the Camera Preview will load instantly, while my app takes some times to reload the Camera Preview.

I implemented SurfaceHolder.Callback in my Class. I've tried to remove onResume and tweak some of the methods and it didn't help much.

Any idea how to handle this delay?

Thanks

答:
You need to create another activity which shows preview of your capture photo. Your preview activity XML layout looks same as your capture activity the only difference between both XML Layout is ImageView which you used for preview activity.

Now, how to do that? Here is the simple solution. As you mentioned You used SurfaceHolder.Callback so you have to use the method Camera.PictureCallback which save your photo to your storage directory.

```<code>Camera.PictureCallback mPicture = new Camera.PictureCallback()
{
    @Override
    public void onPictureTaken(byte[] data, Camera camera)
    {
      // Logic to Save your Photo to your storage directory.
      Intent intent = new Intent(YouActivity.this, PreviewActivity.class);
      // Pass the saved image path to preview activity.
      intent.putExtra("ImagePath", youSavedImagePath);
      startActivity(intent);
    }
};
</code>```

Now, on PreviewActivity just get the value from Intent.

```<code>String imagePath = getIntent().getStringExtra("ImagePath");
</code>```

After getting the path of image set the image to your imageView.

```<code>Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
yourImageView.setImageBitmap(bitmap);
</code>```

Now, When you press back to the CaptureActivity or click on retake your preview will show instantly and not taking time.Please make sure you do not finish the CaptureActivity.

Body:
You need to create another activity which shows preview of your capture photo. Your preview activity XML layout looks same as your capture activity the only difference between both XML Layout is ImageView which you used for preview activity.

Now, how to do that? Here is the simple solution. As you mentioned You used SurfaceHolder.Callback so you have to use the method Camera.PictureCallback which save your photo to your storage directory.

Camera.PictureCallback mPicture = new Camera.PictureCallback()
{
    @Override
    public void onPictureTaken(byte[] data, Camera camera)
    {
      // Logic to Save your Photo to your storage directory.
      Intent intent = new Intent(YouActivity.this, PreviewActivity.class);
      // Pass the saved image path to preview activity.
      intent.putExtra("ImagePath", youSavedImagePath);
      startActivity(intent);
    }
};

Now, on PreviewActivity just get the value from Intent.

String imagePath = getIntent().getStringExtra("ImagePath");

After getting the path of image set the image to your imageView.

Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
yourImageView.setImageBitmap(bitmap);

Now, When you press back to the CaptureActivity or click on retake your preview will show instantly and not taking time.Please make sure you do not finish the CaptureActivity.


问:
PHP date function is returning wrong month and date
I have been working in PHP Development for 5 years but never seen this type of error before.

I have a date which is the last day of the month and I am going to change its format with using below code :

```<code>$data['toDate'] = "2017-04-31";
echo $data['toDate']." : ".date('d-m-Y',strtotime($data['toDate']))." ### ";
die;
</code>```

It outputs :

2017-04-31 00:00:00 : 01-05-2017 ###

I am working on PHP version 5.6.25.
Is there anyone can help me in this??

答:
tl;dr

04-31 is valid but not technically a date in April, since April only has 30 days and thus strtotime() yields 05-01.

Documentation

If you look at the documentation for strtotime() you will see the first parameter is:

time

  A date/time string. Valid formats are explained in Date and Time Formats.

If you follow the link for the date and time formats and go to Date Formats you will see:

Thus for the date format (I.e. DD), 01-31 is valid    (since a 3 can only be followed by a 0 or 1) despite the month. Depending on the supplied month and date value the date will be adjusted.

Also found in the notes on that same page:

Note:

  It is possible to over- and underflow the dd and DD format. Day 0 means the last day of previous month, whereas overflows count into the next month. This makes "2008-08-00" equivalent to "2008-07-31" and "2008-06-31" equivalent to "2008-07-01" (June only has 30 days).1

Hence 04-31 is valid but overflows.

Additionally, in the User Contributed Notes section, the note by Mirek at 2015-04-01 01:14 might be useful/interesting:

Note: the day (dd or DD) is first checked for range 0..31 and only if it fits, the overflow and underflow mechanism may apply. If not, strtotime() simply returns false.
  If you need unlimited over/underflow for date calculations (for example 2015-01-40 to 2015-02-09), use mktime() instead.2

1http://php.net/manual/en/datetime.formats.date.php

2http://php.net/manual/en/datetime.formats.date.php#Hcom117014

Body:
I have been working in PHP Development for 5 years but never seen this type of error before.

I have a date which is the last day of the month and I am going to change its format with using below code :

$data['toDate'] = "2017-04-31";
echo $data['toDate']." : ".date('d-m-Y',strtotime($data['toDate']))." ### ";
die;

It outputs :

2017-04-31 00:00:00 : 01-05-2017 ###

I am working on PHP version 5.6.25.
Is there anyone can help me in this??


答:
You have mentioned the single quotes in code block.But there is not single quotes in script attributes.And also you need to remove dot and try like this:</p>

```<code><script async src="widget-0.1.0.js?type=calculator&min=50&max=400&amount="<?=$price?>" type="application/javascript"></script>
</code>```

Title: JS Script link accepting PHP variables and showing %27

Body: I have a

Body:
You have mentioned the single quotes in code block.But there is not single quotes in script attributes.And also you need to remove dot and try like this:

<script async src="widget-0.1.0.js?type=calculator&min=50&max=400&amount="<?=$price?>" type="application/javascript"></script>


问:
Regex Expression, that picks value/values within inverted double quotes only
I am trying to make a form validator using a javascript;

Value is itself a specific format it can be present 1 or more times, now when the value is tested I need to make sure if the value entered is enclosed within inverted double quotes.
Eg.

```<code>one value :- "C:GSMXXXX&T:GSMXXXX;"
</code>```

more than one, here its 3..

```<code>"C:GSMXXXX&T:GSMXXXX; C:GSMXXXX&T:GSMXXXX; C:GSMXXXX&T:GSMXXXX;"
</code>```

答:
You can use
"(.*?[^\\])"
Here are all tested possibilities.

Body:
I am trying to make a form validator using a javascript;

Value is itself a specific format it can be present 1 or more times, now when the value is tested I need to make sure if the value entered is enclosed within inverted double quotes.
Eg.

one value :- "C:GSMXXXX&T:GSMXXXX;"

more than one, here its 3..

"C:GSMXXXX&T:GSMXXXX; C:GSMXXXX&T:GSMXXXX; C:GSMXXXX&T:GSMXXXX;"


问:
Android Internet connectivity check better method
According to the Android developer site, Determining and Monitoring the Connectivity Status, we can check there is an active Internet connection. But this is not working if even only Wi-Fi is connected and not Internet available (it notifies there is an Internet connection).

Now I ping a website and check whether Internet connections are available or not. And this method needs some more processing time. Is there a better method for checking Internet connectivity than this to avoid the time delay in ping the address?

答:
Try this:

It's really simple and fast:

```<code>public boolean isInternetAvailable(String address, int port, int timeoutMs) {
    try {
        Socket sock = new Socket();
        SocketAddress sockaddr = new InetSocketAddress(address, port);

        sock.connect(sockaddr, timeoutMs); // This will block no more than timeoutMs
        sock.close();

        return true;

    } catch (IOException e) { return false; }
}
</code>```

Then wherever you want to check just use this:

```<code>if (isInternetAvailable("8.8.8.8", 53, 1000)) {
     // Internet available, do something
} else {
     // Internet not available
}
</code>```

Body:
Try this:

It's really simple and fast:

public boolean isInternetAvailable(String address, int port, int timeoutMs) {
    try {
        Socket sock = new Socket();
        SocketAddress sockaddr = new InetSocketAddress(address, port);

        sock.connect(sockaddr, timeoutMs); // This will block no more than timeoutMs
        sock.close();

        return true;

    } catch (IOException e) { return false; }
}

Then wherever you want to check just use this:

if (isInternetAvailable("8.8.8.8", 53, 1000)) {
     // Internet available, do something
} else {
     // Internet not available
}


问:
why these code work but dont add record to my database
```<code>SqlConnection conn = new SqlConnection();
conn.ConnectionString = @"Data Source=CASPER_NIRVANA\FARID;Initial Catalog=proje;Integrated Security=True";
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO projetablosu(basvuru_no)VALUES(@basvuru_no)";
cmd.Parameters.AddWithValue("basvuru_no", textBox1.Text);
cmd.ExecuteNonQuery();
</code>```

答:
```<code>SqlConnection conn = new SqlConnection(@"Data Source=CASPER_NIRVANA\FARID;Initial Catalog=proje;Integrated Security=True");
string query = "INSERT INTO projetablosu(basvuru_no)VALUES('"+textBox1.Text+"')";
SqlCommand cmd = new SqlCommand(query,conn);
cmd.ExecuteNonQuery();
</code>```

<p>// Try This Code, This Will Definately works for u</p>

Body:
SqlConnection conn = new SqlConnection(@"Data Source=CASPER_NIRVANA\FARID;Initial Catalog=proje;Integrated Security=True");
string query = "INSERT INTO projetablosu(basvuru_no)VALUES('"+textBox1.Text+"')";
SqlCommand cmd = new SqlCommand(query,conn);
cmd.ExecuteNonQuery();

// Try This Code, This Will Definately works for u


问:
Configure firewall to enable XAMPP working over LAN
When I turn off the firewall, I can access my XAMPP website through other LAN computers.  When I turn on firewall then I cannot connect to the machine anymore.   Could someone tell me what's happening?  </p>

<p>my os is windows xp.  thanks. </p>

答:
I understand this is an old question and related to Windows XP but now for users using current OS like Windows 10 the option that worked for me is that Inbound Rules Profile could be set to Public for Apache Http Server which is set to Private by default.

The profile could be set in 'Advanced' tab of Apache Http Server Inbound Rules properties as shown below (Properties Dialog box could be opened by Right Clicking on Apache Http Server and select Properties):

Body:
When I turn off the firewall, I can access my XAMPP website through other LAN computers.  When I turn on firewall then I cannot connect to the machine anymore.   Could someone tell me what's happening?

my os is windows xp.  thanks.


问:
ng-model for input type 'number' not working angularjs
I have integrated requirejs with angular app.. before intregrating requirejs,

```<code><input type="number" value="{{cart.quantity}}" ng-model="cart.quantity" />
</code>```

was showing the value in input box.

But after integrating with requirejs, input box with type="number" not showing me the value..
input box with type="text" is working.

How can I show value with type="number" ?

Thanks

答:
Strange, in my case, removing min and max attributes from the input type="number" worked for me. I mean the ng-model worked!!

Seems completely opposite to what arpit kumar posted above.

AngularJS version: 1.6.1

Body:
I have integrated requirejs with angular app.. before intregrating requirejs,

<input type="number" value="{{cart.quantity}}" ng-model="cart.quantity" />

was showing the value in input box.

But after integrating with requirejs, input box with type="number" not showing me the value..
input box with type="text" is working.

How can I show value with type="number" ?

Thanks


问:
Error: app:mergeClient_flavourDebugResources
I am building an adroid project using clean assemble command on Jenkins.

My build is failing each time I run showing this error. Can anyone help me or tell me how can I resolve error related to app: and proguard.
Here is the part of log that shows error.

```<code>Error: Some file crunching failed, see logs for details
:app:mergeClient_flavourDebugResources FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:mergeClient_flavourDebugResources'.
> Error: Some file crunching failed, see logs for details
</code>```

答:
You must be using some resource with unsupported characters in the file name. Check the names of your files in res folder of your project.

It can also happen sometimes if you are using 9-patch image in your project.

If you are using 9-patch image in the project then modify that image slightly with 9-patch editor of android studio and then try to build project.

Body:
I am building an adroid project using clean assemble command on Jenkins.

My build is failing each time I run showing this error. Can anyone help me or tell me how can I resolve error related to app: and proguard.
Here is the part of log that shows error.

Error: Some file crunching failed, see logs for details
:app:mergeClient_flavourDebugResources FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:mergeClient_flavourDebugResources'.
> Error: Some file crunching failed, see logs for details


问:
CDI: observing select/unselect of a specific type of entity (datatable hierarchies)
I have a hierarchy of datatables displayed on a page.

There's a list of CashValueCalculation entities that can be selected at the top. If you select one, another datatable of selectable Paymentstream entities is shown underneath it. Then again a third time, if you select that kind of entity, a last datatable of Payment entities is shown.

There are 3 CDI beans for this: CashValueCalculationManager, PaymentStreamManager and PaymentManager, forming a hierarchy:

```<code>`CashValueCalculationManager`
    |
    +- `PaymentstreamManager`
        |
        +- `PaymentstreamManager`
</code>```

These beans are supposed to react to their parent bean on select/unselect events (UI actually done via a PrimeFaces p:dataTable using JSF of course).

Each of the beans inherits from framework classes that have the entity's PK and the entity class itself as generic. Here's some relevant code:

```<code>public abstract class BaseManager<K, T extends Entity<K>> extends BaseCdiViewBean implements Manager<K, T>
{
    private static final long serialVersionUID = 1L;

    private List<T> entities;

    private T selectedEntity;
    private EMode mode; // VIEW, ADD, EDIT, REMOVE

    // CDI event producers

    @Inject
    @SingleSelect
    private Event<T> selectEvent;

    @Inject
    @SingleUnselect
    private Event<T> unselectEvent;

    ...

    @Override
    public void setSelectedEntity(T selectedEntity)
    {
        if (selectedEntity == null)
        {
            // null entity not really selectable, interpret as clear selection command
            this.setSelectedEntity(null);

            // fire CDI event to 0-n observers
            this.unselectEvent.fire(this.newEntity()); // cannot pass null to CDI events, use a new entity created from a concrete bean
            return;
        }

        // here we have a non-null selected entity
        this.selectedEntity = selectedEntity;

        // fire CDI event to 0-n observers
        this.selectEvent.fire(selectedEntity);
    }

    ...
}
</code>```

The Entity interface is just:

```<code>public interface Entity<K>
{
    public K getPk();
    public void setPk(K pk);
}
</code>```

The two sub managers PaymentStreamManager and PaymentManager inherit from BaseSubManager and act as observers to their parent managers CashValueCalculationManager and PaymentStreamManager respectively (that's what they're supposed to):

```<code>public abstract class BaseSubManager<K, T extends Entity<K>, P extends Entity<?>> extends BaseManager<K, T> implements SubManager<K, T, P>
{
    private static final long serialVersionUID = 1L;

    private P parentEntity;

    @Override
    public P getParentEntity()
    {
        return this.parentEntity;
    }

    @Override
    public void setParentEntity(P parentEntity)
    {
        this.parentEntity = parentEntity;
    }

    public void onSelect(@Observes @SingleSelect P selectedParentEntity)
    {
        System.out.println(this.getClass().getSimpleName() + ": selected parent entity: " + selectedParentEntity);
        this.setParentEntity(selectedParentEntity);
    }

    public void onUnselect(@Observes @SingleUnselect P unselectedParentEntity)
    {
        System.out.println(this.getClass().getSimpleName() + ": unselected parent entity: " + unselectedParentEntity);
        this.setParentEntity(null);
    }
}
</code>```

@SingleSelect annotation:

```<code>@Qualifier
@Retention(RUNTIME)
@Target({FIELD, PARAMETER})
public @interface SingleSelect
{
    // no additional interface
}
</code>```

@SingleUnselect annotation:

```<code>@Qualifier
@Retention(RUNTIME)
@Target({FIELD, PARAMETER})
public @interface SingleUnselect
{
    // no additional interface
}
</code>```

What I want now is that PaymentstreamManager receives events from CashValueCalculationManager and PaymentManager receives events from PaymentstreamManager only.

However, each time I select an entity of the top level manager CashValueCalculationManager then both sub managers' @Observer methods receive the event (and the method call of course, which is not what I need):

On select test:

```<code>21:17:34,310 INFO  [stdout] PaymentManager: selected parent entity: CashValueCalculation[pk=2]
21:17:34,312 INFO  [stdout] PaymentStreamManager: selected parent entity: CashValueCalculation[pk=2]
</code>```

On unselect test:

```<code>21:19:20,176 INFO  [stdout] PaymentStreamManager: unselected parent entity: CashValueCalculation[pk=null]
21:19:20,177 INFO  [stdout] PaymentManager: unselected parent entity: CashValueCalculation[pk=null]
</code>```

Q:

Why isn't this working right away? What do I need to change in the code to make it work?

Thanks

答:
Educated guess:

As generics are implemented via type-erasure, you basically have the following events in BaseManager at runtime:

```<code>@Inject
@SingleSelect
private Event<Object> selectEvent;

@Inject
@SingleUnselect
private Event<Object> unselectEvent;
</code>```

on the other hand, you observe the following:

```<code>public void onSelect(@Observes @SingleSelect Object selectedParentEntity)
public void onUnselect(@Observes @SingleUnselect Object unselectedParentEntity)
</code>```

... which obviously matches every event.

What I'd try out is, add a class value to the qualifier annotations, something like:

```<code>@Qualifier
@Retention(RUNTIME)
@Target({FIELD, PARAMETER})
public @interface SingleSelect
{
    public Class<?> value();
}

@Inject
@SingleSelect(SomeConcreteType.class)
private Event<Object> selectEvent;

public void onSelect(@Observes @SingleSelect(SomeConcreteType.class) P selectedParentEntity)
</code>```

This way, your container should be able to distinguish the various events at runtime.

Body:
I have a hierarchy of datatables displayed on a page.

There's a list of CashValueCalculation entities that can be selected at the top. If you select one, another datatable of selectable Paymentstream entities is shown underneath it. Then again a third time, if you select that kind of entity, a last datatable of Payment entities is shown.

There are 3 CDI beans for this: CashValueCalculationManager, PaymentStreamManager and PaymentManager, forming a hierarchy:

`CashValueCalculationManager`
    |
    +- `PaymentstreamManager`
        |
        +- `PaymentstreamManager`

These beans are supposed to react to their parent bean on select/unselect events (UI actually done via a PrimeFaces p:dataTable using JSF of course).

Each of the beans inherits from framework classes that have the entity's PK and the entity class itself as generic. Here's some relevant code:

public abstract class BaseManager<K, T extends Entity<K>> extends BaseCdiViewBean implements Manager<K, T>
{
    private static final long serialVersionUID = 1L;

    private List<T> entities;

    private T selectedEntity;
    private EMode mode; // VIEW, ADD, EDIT, REMOVE

    // CDI event producers

    @Inject
    @SingleSelect
    private Event<T> selectEvent;

    @Inject
    @SingleUnselect
    private Event<T> unselectEvent;

    ...

    @Override
    public void setSelectedEntity(T selectedEntity)
    {
        if (selectedEntity == null)
        {
            // null entity not really selectable, interpret as clear selection command
            this.setSelectedEntity(null);

            // fire CDI event to 0-n observers
            this.unselectEvent.fire(this.newEntity()); // cannot pass null to CDI events, use a new entity created from a concrete bean
            return;
        }

        // here we have a non-null selected entity
        this.selectedEntity = selectedEntity;

        // fire CDI event to 0-n observers
        this.selectEvent.fire(selectedEntity);
    }

    ...
}

The Entity interface is just:

public interface Entity<K>
{
    public K getPk();
    public void setPk(K pk);
}

The two sub managers PaymentStreamManager and PaymentManager inherit from BaseSubManager and act as observers to their parent managers CashValueCalculationManager and PaymentStreamManager respectively (that's what they're supposed to):

public abstract class BaseSubManager<K, T extends Entity<K>, P extends Entity<?>> extends BaseManager<K, T> implements SubManager<K, T, P>
{
    private static final long serialVersionUID = 1L;

    private P parentEntity;

    @Override
    public P getParentEntity()
    {
        return this.parentEntity;
    }

    @Override
    public void setParentEntity(P parentEntity)
    {
        this.parentEntity = parentEntity;
    }

    public void onSelect(@Observes @SingleSelect P selectedParentEntity)
    {
        System.out.println(this.getClass().getSimpleName() + ": selected parent entity: " + selectedParentEntity);
        this.setParentEntity(selectedParentEntity);
    }

    public void onUnselect(@Observes @SingleUnselect P unselectedParentEntity)
    {
        System.out.println(this.getClass().getSimpleName() + ": unselected parent entity: " + unselectedParentEntity);
        this.setParentEntity(null);
    }
}

@SingleSelect annotation:

@Qualifier
@Retention(RUNTIME)
@Target({FIELD, PARAMETER})
public @interface SingleSelect
{
    // no additional interface
}

@SingleUnselect annotation:

@Qualifier
@Retention(RUNTIME)
@Target({FIELD, PARAMETER})
public @interface SingleUnselect
{
    // no additional interface
}

What I want now is that PaymentstreamManager receives events from CashValueCalculationManager and PaymentManager receives events from PaymentstreamManager only.

However, each time I select an entity of the top level manager CashValueCalculationManager then both sub managers' @Observer methods receive the event (and the method call of course, which is not what I need):

On select test:

21:17:34,310 INFO  [stdout] PaymentManager: selected parent entity: CashValueCalculation[pk=2]
21:17:34,312 INFO  [stdout] PaymentStreamManager: selected parent entity: CashValueCalculation[pk=2]

On unselect test:

21:19:20,176 INFO  [stdout] PaymentStreamManager: unselected parent entity: CashValueCalculation[pk=null]
21:19:20,177 INFO  [stdout] PaymentManager: unselected parent entity: CashValueCalculation[pk=null]

Q:

Why isn't this working right away? What do I need to change in the code to make it work?

Thanks

Body:
Educated guess:

As generics are implemented via type-erasure, you basically have the following events in BaseManager at runtime:

@Inject
@SingleSelect
private Event<Object> selectEvent;

@Inject
@SingleUnselect
private Event<Object> unselectEvent;

on the other hand, you observe the following:

public void onSelect(@Observes @SingleSelect Object selectedParentEntity)
public void onUnselect(@Observes @SingleUnselect Object unselectedParentEntity)

... which obviously matches every event.

What I'd try out is, add a class value to the qualifier annotations, something like:

@Qualifier
@Retention(RUNTIME)
@Target({FIELD, PARAMETER})
public @interface SingleSelect
{
    public Class<?> value();
}

@Inject
@SingleSelect(SomeConcreteType.class)
private Event<Object> selectEvent;

public void onSelect(@Observes @SingleSelect(SomeConcreteType.class) P selectedParentEntity)

This way, your container should be able to distinguish the various events at runtime.


问:
changing values directly on the destination system instead of copying file from the source
using ansible looking for some idea for changing values directly on the destination system instead of copying files from source.

example:

I have many files in tmpl format on the destination system and would like to change the values related to this <%= applicationname_zk_quorum %> by using ansible variable's dynamically.

```<code>/applactionname/conf/zk.properties.tmpl

[root@applicationname-7 ~]# cat /applicationname/conf/zk.properties.tmpl
#nodes in quorum

applicationname.zk.quorum=<%= applicationname_zk_quorum %>
#applicationname.zk.quorum=zook1:6666,zook2:6666,zook3:6666

applicationname.zk.node=/applicationnames/node/

#Session timeout in milliseconds
applicationname.zk.sessionTimeout=72000
</code>```

I understand that ansible variables only support for handling yaml and don't have any idea if anything it is possible to apply something for tmpl file.

thanks a lot for all your support and guidance!!!.

答:
Please go through jinja2 documents and Ansible template module

Suppose you have this file conf/zk.properties.tmpl.j2 in your current ansible module's templates folder

```<code>- template:
    src: conf/zk.properties.tmpl.j2
    dest: /applicationname/conf/zk.properties.tmpl
    owner: root
    group: root
    mode: 0644
</code>```

You can define the variable in conf/zk.properties.tmpl.j2. For example:

```<code>#nodes in quorum

applicationname.zk.quorum=<%= {{ applicationname_zk_quorum }} %>

applicationname.zk.node=/applicationnames/node/

#Session timeout in milliseconds
applicationname.zk.sessionTimeout=72000
</code>```

In vars folder, you can define this variable applicationname_zk_quorum as a yml file, for example, tmpl.yml.

```<code>applicationname.zk.quorum: "zook1:6666,zook2:6666,zook3:6666"
</code>```

Body:
using ansible looking for some idea for changing values directly on the destination system instead of copying files from source.

example:

I have many files in tmpl format on the destination system and would like to change the values related to this <%= applicationname_zk_quorum %> by using ansible variable's dynamically.

/applactionname/conf/zk.properties.tmpl

[root@applicationname-7 ~]# cat /applicationname/conf/zk.properties.tmpl
#nodes in quorum

applicationname.zk.quorum=<%= applicationname_zk_quorum %>
#applicationname.zk.quorum=zook1:6666,zook2:6666,zook3:6666

applicationname.zk.node=/applicationnames/node/

#Session timeout in milliseconds
applicationname.zk.sessionTimeout=72000

I understand that ansible variables only support for handling yaml and don't have any idea if anything it is possible to apply something for tmpl file.

thanks a lot for all your support and guidance!!!.

Body:
Please go through jinja2 documents and Ansible template module

Suppose you have this file conf/zk.properties.tmpl.j2 in your current ansible module's templates folder

- template:
    src: conf/zk.properties.tmpl.j2
    dest: /applicationname/conf/zk.properties.tmpl
    owner: root
    group: root
    mode: 0644

You can define the variable in conf/zk.properties.tmpl.j2. For example:

#nodes in quorum

applicationname.zk.quorum=<%= {{ applicationname_zk_quorum }} %>

applicationname.zk.node=/applicationnames/node/

#Session timeout in milliseconds
applicationname.zk.sessionTimeout=72000

In vars folder, you can define this variable applicationname_zk_quorum as a yml file, for example, tmpl.yml.

applicationname.zk.quorum: "zook1:6666,zook2:6666,zook3:6666"


问:
jQuery or CSS: replacing the ® mark with ®
I have this HTML heading:

```<code><h1>Time Matters®</h1> (equals to: Time Matters®)
</code>```

I need a way to control the '&reg ;' mark either by CSS or jQuery. As far as I know, I don't think it's possible to target '&reg ;' with CSS, is there?

Now, if jQuery is used, I need to enclose '&reg ;' in  tags, like this:

```<code><h1>Time Matters<sup>®</sup></h1>
</code>```

...this way I can target the element via CSS.

I tried adapting this tutorial but the code encapsulates all words in  tags.

Any idea how to accomplish this? Any help would be greatly appreciated.

Thanks.

答:
There is a Javascript function for doing this called replace(). More info here

I would recommend assigning the contents of the element to a variable, using the replace function to swap out the symbol for the  enclosed symbol, then appending it to the document using DOM

Title: jQuery or CSS: replacing the ® mark with <sup>®</sup>

Body:
I have this HTML heading:

Time Matters®
 (equals to: Time Matters®)

I need a way to control the '&reg ;' mark either by CSS or jQuery. As far as I know, I don't think it's possible to target '&reg ;' with CSS, is there?

Now, if jQuery is used, I need to enclose '&reg ;' in  tags, like this:

Time Matters®

...this way I can target the element via CSS.

I tried adapting this tutorial but the code encapsulates all words in  tags.

Any idea how to accomplish this? Any help would be greatly appreciated.

Thanks.

Body:
There is a Javascript function for doing this called replace(). More info here

I would recommend assigning the contents of the element to a variable, using the replace function to swap out the symbol for the <sup> enclosed symbol, then appending it to the document using DOM


问:
echo HTML with php variable
I'm trying to display the following and I have a css code for it but it doesn't work. Any help would be appreciated.

HTML/PHP

```<code> $var = "Hello World";
    echo '<p>' . 'the value of the variable is : ' . $var . '</p>';
</code>```

CSS

```<code>p
{
    text-align: center;
    color: red;
}
</code>```

Thanks for your help

答:
Use as below

```<code><?php
$var = "Hello World";
echo "<p>The value of the variable is : " . $var . "</p>";
?>
</code>```

Or like below in your HTML code where you want the php variable

```<code><p>The value of the variable is : <?php echo $var;?></p>
</code>```

Title: echo HTML with php variable

Body:
I'm trying to display the following and I have a css code for it but it doesn't work. Any help would be appreciated.

HTML/PHP

 $var = "Hello World";
    echo '
' . 'the value of the variable is : ' . $var . '
';

CSS

p
{
    text-align: center;
    color: red;
}

Thanks for your help

Body:
Use as below

<?php
$var = "Hello World";
echo "<p>The value of the variable is : " . $var . "</p>";
?>

Or like below in your HTML code where you want the php variable

<p>The value of the variable is : <?php echo $var;?></p>


问:
Lubridate fix the time units
When we take the difference of two time, there is something going on automatically there in units.

```<code>> ymd_hms("2016-05-09 15:17:03") - ymd_hms("2016-05-09 15:17:04")
Time difference of -1 secs
> ymd_hms("2016-05-09 16:17:03") - ymd_hms("2016-05-09 15:17:04")
Time difference of 59.98333 mins
> ymd_hms("2016-05-10 16:17:03") - ymd_hms("2016-05-09 15:17:04")
Time difference of 1.041655 days
</code>```

How can I fix the units without using difftime function.

So I can do the following:

```<code>VECTOR = c(ymd_hms("2016-05-10 16:17:03"),
           ymd_hms("2016-05-10 17:19:33"),
           ymd_hms("2016-05-10 19:55:03")
         )

diffs = diff(VECTOR)

IntervalsInHours = toHours(diffs)
</code>```

Additionally, is there any way to know the units being used in a lubridate time object. For example,

```<code>> ymd_hms("2016-05-09 15:17:03") - ymd_hms("2016-05-09 15:17:04")
Time difference of -1 secs
</code>```

The units used here are seconds.

答:
I wrote two functions in case anyone might find useful.</p>

```<code>timeDiffUnitConvert = function(Diffs, to="day", roundingN = 1){
  if(to == "day"){
    R = round(as.numeric(as.duration(Diffs))/3600/24,roundingN)
  } else if (to == "hour") {
    R = round(as.numeric(as.duration(Diffs))/3600, roundingN)
  } else if (to == "min") {
    R = round(as.numeric(as.duration(Diffs))/60, roundingN)
  } else if (to == "sec"){
    R = round(as.numeric(as.duration(Diffs)), roundingN)
  } else {
    stop("to which unit? it must be `day`, `hour`, `min` or `sec`.")
  }
  R
}

timeDiffVector = function(TimeVector, to="day", roundingN = 1, attachNaMode = "none"){
  R = timeDiffUnitConvert(diff(TimeVector), to = to, roundingN = roundingN)
  if(attachNaMode == "leading"){
    R = c(NA,R)
  } else if(attachNaMode == "trailing"){
    R = c(R,NA)
  } else{
    stop("check your attachNaMode: shall be either `leading` or `trailing`")
  }
  R
}
</code>```

Title: Lubridate fix the time units

Body:
When we take the difference of two time, there is something going on automatically there in units.

> ymd_hms("2016-05-09 15:17:03") - ymd_hms("2016-05-09 15:17:04")
Time difference of -1 secs
> ymd_hms("2016-05-09 16:17:03") - ymd_hms("2016-05-09 15:17:04")
Time difference of 59.98333 mins
> ymd_hms("2016-05-10 16:17:03") - ymd_hms("2016-05-09 15:17:04")
Time difference of 1.041655 days

How can I fix the units without using difftime function.

So I can do the following:

VECTOR = c(ymd_hms("2016-05-10 16:17:03"),
           ymd_hms("2016-05-10 17:19:33"),
           ymd_hms("2016-05-10 19:55:03")
         )

diffs = diff(VECTOR)

IntervalsInHours = toHours(diffs)

Additionally, is there any way to know the units being used in a lubridate time object. For example,

> ymd_hms("2016-05-09 15:17:03") - ymd_hms("2016-05-09 15:17:04")
Time difference of -1 secs

The units used here are seconds.

Body:
I wrote two functions in case anyone might find useful.

timeDiffUnitConvert = function(Diffs, to="day", roundingN = 1){
  if(to == "day"){
    R = round(as.numeric(as.duration(Diffs))/3600/24,roundingN)
  } else if (to == "hour") {
    R = round(as.numeric(as.duration(Diffs))/3600, roundingN)
  } else if (to == "min") {
    R = round(as.numeric(as.duration(Diffs))/60, roundingN)
  } else if (to == "sec"){
    R = round(as.numeric(as.duration(Diffs)), roundingN)
  } else {
    stop("to which unit? it must be `day`, `hour`, `min` or `sec`.")
  }
  R
}

timeDiffVector = function(TimeVector, to="day", roundingN = 1, attachNaMode = "none"){
  R = timeDiffUnitConvert(diff(TimeVector), to = to, roundingN = roundingN)
  if(attachNaMode == "leading"){
    R = c(NA,R)
  } else if(attachNaMode == "trailing"){
    R = c(R,NA)
  } else{
    stop("check your attachNaMode: shall be either `leading` or `trailing`")
  }
  R
}


问:
Is it possible to git stash an interactive rebase in progress?
I am currently rebasing origin/master onto a branch that was created from origin/master a while ago and the developer that worked on the branch is not available right now.

I have resolved some conflicts on the first commits of the feature branch but come to a point where I must wait for the developer to know how to finalize the rebase.

Is there a way to keep the conflict resolution I already did (~30 minutes) so that I can move on to another task?

答: Another brain-dead simple solution is to simply copy the entire folder containing the git repository, mid-rebase. This should always work. May be a good idea to delete that folder when done (rebased and pushed).</p>


问:
Wrong layout in QMainWindow?
I am getting wrong layout in PyQT5. What am I doing wrong? Is there some predefined small field size or similar? I created main window as QMainWindow and inside it a widget as central widget. This is how it looks like:

```<code>class Main(QWidget):
    """The main widget with label and LineEdit"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.initUi()

    def initUi(self):
        """Initialize the UI of the main widget"""
        self.mySourceLabel = QLabel("Select your file:")
        self.mySourceLine = QLineEdit()
        self.mySourceLine.setPlaceholderText("File name here")

        # Set layout
        grid = QGridLayout()
        #grid.setSpacing(5)
        grid.addWidget(self.mySourceLabel, 0, 0)
        grid.addWidget(self.mySourceLine, 1, 0)
        self.setLayout(grid)

class MyApp(QMainWindow):
    """Main application class"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.initUi()

    def initUi(self):
        """Initialize UI of an application"""
        # main window size, title
        self.setGeometry(400, 300, 400, 300)
        self.setWindowTitle("Version upgrade ")

        # create instance of a class Main
        self.main = Main(self)

        # create central widget, create grid layout
        centralWidget = QWidget()
        centralLayout = QGridLayout()
        centralWidget.setLayout(centralLayout)
</code>```

答:
When you pass the parent to a QWidget this will locate a position with respect to its parent and generate widgets like the ones you have obtained, to solve this, layouts are used, QMainWindow is a special QWidget since it has predefined elements, so it already has a layout:

In QMainWindow the widget must be added to the centralwidget with the setCentralWidget function, in your case:

```<code>class MyApp(QMainWindow):
    """Main application class"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.initUi()

    def initUi(self):
        [...]
        centralWidget = Main(self)
        self.setCentralWidget(centralWidget)
</code>```

complete code:

```<code>class Main(QWidget):
    """The main widget with label and LineEdit"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.initUi()

    def initUi(self):
        """Initialize the UI of the main widget"""
        self.mySourceLabel = QLabel("Select your file:")
        self.mySourceLine = QLineEdit()
        self.mySourceLine.setPlaceholderText("File name here")

        # Set layout
        grid = QGridLayout()
        #grid.setSpacing(5)
        grid.addWidget(self.mySourceLabel, 0, 0)
        grid.addWidget(self.mySourceLine, 1, 0)
        self.setLayout(grid)

class MyApp(QMainWindow):
    """Main application class"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.initUi()

    def initUi(self):
        """Initialize UI of an application"""
        # main window size, title
        self.setGeometry(400, 300, 400, 300)
        self.setWindowTitle("Version upgrade ")

        # create central widget, create grid layout
        centralWidget = Main(self)
        self.setCentralWidget(centralWidget)
</code>```

Screenshot:

ContentLicense: CC BY-SA 4.0

Title: Wrong layout in QMainWindow?

Body:
I am getting wrong layout in PyQT5. What am I doing wrong? Is there some predefined small field size or similar? I created main window as QMainWindow and inside it a widget as central widget. This is how it looks like:

class Main(QWidget):
    """The main widget with label and LineEdit"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.initUi()

    def initUi(self):
        """Initialize the UI of the main widget"""
        self.mySourceLabel = QLabel("Select your file:")
        self.mySourceLine = QLineEdit()
        self.mySourceLine.setPlaceholderText("File name here")

        # Set layout
        grid = QGridLayout()
        #grid.setSpacing(5)
        grid.addWidget(self.mySourceLabel, 0, 0)
        grid.addWidget(self.mySourceLine, 1, 0)
        self.setLayout(grid)

class MyApp(QMainWindow):
    """Main application class"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.initUi()

    def initUi(self):
        """Initialize UI of an application"""
        # main window size, title
        self.setGeometry(400, 300, 400, 300)
        self.setWindowTitle("Version upgrade ")

        # create instance of a class Main
        self.main = Main(self)

        # create central widget, create grid layout
        centralWidget = QWidget()
        centralLayout = QGridLayout()
        centralWidget.setLayout(centralLayout)

Body:
When you pass the parent to a QWidget this will locate a position with respect to its parent and generate widgets like the ones you have obtained, to solve this, layouts are used, QMainWindow is a special QWidget since it has predefined elements, so it already has a layout:

In QMainWindow the widget must be added to the centralwidget with the setCentralWidget function, in your case:

class MyApp(QMainWindow):
    """Main application class"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.initUi()

    def initUi(self):
        [...]
        centralWidget = Main(self)
        self.setCentralWidget(centralWidget)

complete code:

class Main(QWidget):
    """The main widget with label and LineEdit"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.initUi()

    def initUi(self):
        """Initialize the UI of the main widget"""
        self.mySourceLabel = QLabel("Select your file:")
        self.mySourceLine = QLineEdit()
        self.mySourceLine.setPlaceholderText("File name here")

        # Set layout
        grid = QGridLayout()
        #grid.setSpacing(5)
        grid.addWidget(self.mySourceLabel, 0, 0)
        grid.addWidget(self.mySourceLine, 1, 0)
        self.setLayout(grid)

class MyApp(QMainWindow):
    """Main application class"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.initUi()

    def initUi(self):
        """Initialize UI of an application"""
        # main window size, title
        self.setGeometry(400, 300, 400, 300)
        self.setWindowTitle("Version upgrade ")

        # create central widget, create grid layout
        centralWidget = Main(self)
        self.setCentralWidget(centralWidget)

Screenshot:


问:
Is there an optimized method for finding the farthest corner of a cube in 3D
If a have a cube C with 8 corners ( not axis aligned ) and a random point P can I do better than just checking all the corners and picking the corner with the greatest distance from P or is it possible to reduce the number of checks by taking into account the symmetrical nature of the cube?

答:
@spug triggered my realization that I already had most of the code I needed.

I had previously developed an optimal way of solving the closest point ( not necessarily a corner) on a cube. That code required only minor modifications to return the closest corner on the cube. Logically the furthest away point on a cube is the opposite corner to the closest corner.

The principle is to project the point onto the three principle axis and test how far along each axis the projection is. If it is greater than half way then set the index of that axis to false otherwise set it to true. After doing this for three axis you have three boolean variables you can use to pick the corner.

After profiling over 10 million random points the following data is available.

Naive Linear Search Algorithm - 643ms
Fast Algorithm                - 481ms

The C# code I ended up using was

```<code>    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public Vector3 FurthestPointFromFast(Vector3 q)
    {
        //BasisVectors( TransformMatrix, out var vx, out var vy, out var vz );
        var origin = BoxCorners.V000;

        // Get the pre-calculated principle
        // axes of the box with origin at V000
        Vector3 vx = BoxCorners.Px;
        Vector3 vy = BoxCorners.Py;
        Vector3 vz = BoxCorners.Pz;

        // Get the pre-calculated prinicple
        // axes lengths squared of the box at V000
        double lx = BoxCorners.Lx2;
        double ly = BoxCorners.Ly2;
        double lz = BoxCorners.Lz2;

        var d = q - origin;
        double tx = Vector3.Dot( d, vx );
        double ty = Vector3.Dot( d, vy );
        double tz = Vector3.Dot( d, vz );

        bool ix = tx < lx / 2;
        bool iy = ty < ly / 2;
        bool iz = tz < lz / 2;

        return ix
            ? (iy
                ? (iz
                    ? BoxCorners.V111
                    : BoxCorners.V110)
                : (iz
                    ? BoxCorners.V101
                    : BoxCorners.V100))
            : (iy
                ? (iz
                    ? BoxCorners.V011
                    : BoxCorners.V010)
                : (iz
                    ? BoxCorners.V001
                    : BoxCorners.V000));
    }
</code>```

where an instance of BoxCorners is from the following class. It is assumed that a box is relatively static compared to the number of checks made against it so calculated values such as the side lengths of the box are stored along with the coordinates of each corner.

```<code>public class BoxCorners
{
    public Vector3 V111;
    public Vector3 V110;
    public Vector3 V101;
    public Vector3 V100;
    public Vector3 V011;
    public Vector3 V010;
    public Vector3 V001;
    public Vector3 V000;

    // These are the vectors starting at the box origin (V000)
    // They are precalculated and usefull in other algorithms
    #region Principle Axis
    public Vector3 Origin;
    public Vector3 Px;
    public Vector3 Py;
    public Vector3 Pz;
    /// <summary>
    /// Px length squared
    /// </summary>
    public double Lx2;
    /// <summary>
    /// Py length squared
    /// </summary>
    public double Ly2;
    /// <summary>
    /// Pz length squared
    /// </summary>
    public double Lz2;
    #endregion

    public BoxCorners(Vector3 v000, Vector3 v001, Vector3 v010, Vector3 v011, Vector3 v100, Vector3 v101, Vector3 v110, Vector3 v111)
    {
        V000 = v000;
        V001 = v001;
        V010 = v010;
        V011 = v011;
        V100 = v100;
        V101 = v101;
        V110 = v110;
        V111 = v111;

        Origin = V000;

        Px = (V100 - Origin);
        Py = (V010 - Origin);
        Pz = (V001 - Origin);

        Lx2 = Px.LengthSquared();
        Ly2 = Py.LengthSquared();
        Lz2 = Py.LengthSquared();
    }

}
</code>```

The original naive algorith is below

```<code>    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    void Acc(ref Vector3 v, ref Vector3 q, ref double max, ref Vector3 maxV)
    {
        var m = Vector3.DistanceSquared(v, q);
        if (!(m > max))
            return;
        max = m;
        maxV = v;
    }

    /// <summary>
    /// Return the furthest point on the box from the point
    /// </summary>
    /// <param name="q"></param>
    /// <returns></returns>
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public Vector3 FurthestPointFrom(Vector3 q)
    {

        var max = 0.0;
        var bc = BoxCorners;
        var r = Vector3.Zero;

        Acc(ref bc.V111, ref q, ref max, ref r);
        Acc(ref bc.V110, ref q, ref max, ref r);
        Acc(ref bc.V101, ref q, ref max, ref r);
        Acc(ref bc.V100, ref q, ref max, ref r);
        Acc(ref bc.V011, ref q, ref max, ref r);
        Acc(ref bc.V010, ref q, ref max, ref r);
        Acc(ref bc.V001, ref q, ref max, ref r);
        Acc(ref bc.V000, ref q, ref max, ref r);

        return r;
    }
</code>```

The double numerics nuget package is used for 3D vector primitives.

Body:
@spug triggered my realization that I already had most of the code I needed.

I had previously developed an optimal way of solving the closest point ( not necessarily a corner) on a cube. That code required only minor modifications to return the closest corner on the cube. Logically the furthest away point on a cube is the opposite corner to the closest corner.

The principle is to project the point onto the three principle axis and test how far along each axis the projection is. If it is greater than half way then set the index of that axis to false otherwise set it to true. After doing this for three axis you have three boolean variables you can use to pick the corner.

After profiling over 10 million random points the following data is available.

Naive Linear Search Algorithm - 643ms
Fast Algorithm                - 481ms

The C# code I ended up using was

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public Vector3 FurthestPointFromFast(Vector3 q)
    {
        //BasisVectors( TransformMatrix, out var vx, out var vy, out var vz );
        var origin = BoxCorners.V000;

        // Get the pre-calculated principle
        // axes of the box with origin at V000
        Vector3 vx = BoxCorners.Px;
        Vector3 vy = BoxCorners.Py;
        Vector3 vz = BoxCorners.Pz;

        // Get the pre-calculated prinicple
        // axes lengths squared of the box at V000
        double lx = BoxCorners.Lx2;
        double ly = BoxCorners.Ly2;
        double lz = BoxCorners.Lz2;

        var d = q - origin;
        double tx = Vector3.Dot( d, vx );
        double ty = Vector3.Dot( d, vy );
        double tz = Vector3.Dot( d, vz );

        bool ix = tx < lx / 2;
        bool iy = ty < ly / 2;
        bool iz = tz < lz / 2;

        return ix
            ? (iy
                ? (iz
                    ? BoxCorners.V111
                    : BoxCorners.V110)
                : (iz
                    ? BoxCorners.V101
                    : BoxCorners.V100))
            : (iy
                ? (iz
                    ? BoxCorners.V011
                    : BoxCorners.V010)
                : (iz
                    ? BoxCorners.V001
                    : BoxCorners.V000));
    }

where an instance of BoxCorners is from the following class. It is assumed that a box is relatively static compared to the number of checks made against it so calculated values such as the side lengths of the box are stored along with the coordinates of each corner.

public class BoxCorners
{
    public Vector3 V111;
    public Vector3 V110;
    public Vector3 V101;
    public Vector3 V100;
    public Vector3 V011;
    public Vector3 V010;
    public Vector3 V001;
    public Vector3 V000;

    // These are the vectors starting at the box origin (V000)
    // They are precalculated and usefull in other algorithms
    #region Principle Axis
    public Vector3 Origin;
    public Vector3 Px;
    public Vector3 Py;
    public Vector3 Pz;
    /// <summary>
    /// Px length squared
    /// </summary>
    public double Lx2;
    /// <summary>
    /// Py length squared
    /// </summary>
    public double Ly2;
    /// <summary>
    /// Pz length squared
    /// </summary>
    public double Lz2;
    #endregion

    public BoxCorners(Vector3 v000, Vector3 v001, Vector3 v010, Vector3 v011, Vector3 v100, Vector3 v101, Vector3 v110, Vector3 v111)
    {
        V000 = v000;
        V001 = v001;
        V010 = v010;
        V011 = v011;
        V100 = v100;
        V101 = v101;
        V110 = v110;
        V111 = v111;

        Origin = V000;

        Px = (V100 - Origin);
        Py = (V010 - Origin);
        Pz = (V001 - Origin);

        Lx2 = Px.LengthSquared();
        Ly2 = Py.LengthSquared();
        Lz2 = Py.LengthSquared();
    }

}

The original naive algorith is below

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    void Acc(ref Vector3 v, ref Vector3 q, ref double max, ref Vector3 maxV)
    {
        var m = Vector3.DistanceSquared(v, q);
        if (!(m > max))
            return;
        max = m;
        maxV = v;
    }

    /// <summary>
    /// Return the furthest point on the box from the point
    /// </summary>
    /// <param name="q"></param>
    /// <returns></returns>
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public Vector3 FurthestPointFrom(Vector3 q)
    {

        var max = 0.0;
        var bc = BoxCorners;
        var r = Vector3.Zero;

        Acc(ref bc.V111, ref q, ref max, ref r);
        Acc(ref bc.V110, ref q, ref max, ref r);
        Acc(ref bc.V101, ref q, ref max, ref r);
        Acc(ref bc.V100, ref q, ref max, ref r);
        Acc(ref bc.V011, ref q, ref max, ref r);
        Acc(ref bc.V010, ref q, ref max, ref r);
        Acc(ref bc.V001, ref q, ref max, ref r);
        Acc(ref bc.V000, ref q, ref max, ref r);

        return r;
    }

The double numerics nuget package is used for 3D vector primitives.


答:
Try the following:

```<code>public boolean checkOnlineState() {
    ConnectivityManager CManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo NInfo = CManager.getActiveNetworkInfo();
    if (NInfo != null && NInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}
</code>```

Don't forget the access:

```<code> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</code>```

Else:

```<code>if (InetAddress.getByName("www.google.com").isReachable(timeout))
{    }
else
{    }
</code>```

Title: Android Internet connectivity check better method

Body:
According to the Android developer site, Determining and Monitoring the Connectivity Status, we can check there is an active Internet connection. But this is not working if even only Wi-Fi is connected and not Internet available (it notifies there is an Internet connection).

Now I ping a website and check whether Internet connections are available or not. And this method needs some more processing time. Is there a better method for checking Internet connectivity than this to avoid the time delay in ping the address?

Body:
Try the following:

public boolean checkOnlineState() {
    ConnectivityManager CManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo NInfo = CManager.getActiveNetworkInfo();
    if (NInfo != null && NInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

Don't forget the access:

 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Else:

if (InetAddress.getByName("www.google.com").isReachable(timeout))
{    }
else
{    }


问:
floating point in verilog
I have floating point number in verilog , I wanna shift it to right to make IEEE standard, but I don't know where the point is, to understand if it is standard or not(to stop shifting) .

what can I do?

second question:
if i shift floating point like this: 10001.11 to right what does happen in verilog? 0100.111 or 0100.11 ?

IEEE standard

答:
To make it IEEE standard. you need to follow IEEE-754 format for representing floating point numbers. There are different types of floating point representations in the standard.

half precision(or FP16), where you can have 1 bit for sign, 5-bits for exponent and 10 bits for mantissa.

full precision(or FP32), where you can have 1 bit for sign, 8-bits for exponent and 23-bits for mantissa
 and so on.

You can perform any kind of operations with FP16 and FP32 representations, like addition, subtraction, multiplication etc.

Title: floating point in verilog