text:
Q: Return an indicator if the process is succeed or not I have member function that looks like:
Point find_the_special_point(Image img);

However, this function may fail to find the point (for example the img does not contain a special point at all).
What is the right way to make the function return in some way that the point was not found?
I thought of some solutions but not sure which one the best or if there is a better approach:
1. Throwing exception if the point is not found:
I think it is just stupid because exceptions are not mean to control the flow. Furthermore, not finding a point is an expected behavior not an exception.
2. Alter the declaration to:
Bool find_the_special_point(Image img , Point& pnt);

Although it seems correct way, I think (not sure) that it is not so good to return the actual output via arguments.
3. Wrapping the out put:
struct find_the_special_point_result{
    bool is found;
    Point special_point;
};
find_the_special_point_result find_the_special_point(Image img);

It seems to be nice solution. However, I suspect that it is a bit overkill.
4. Returning pointer instead:
std::shared_ptr<Point> find_the_special_point(Image img);

and if it is not found return nullptr. However, I think dynamic allocation was not made for this case. It is kind of using the wrong tool to achieve another goal.
What is the convention way to solve this issue?

A: In C++, this question is not trivial because of object lifetimes and constructors/destructors. That doesn't matter for POD types. But it is relevant for other types, and crucially important when writing templated code.
If you return by value (even if wrapped in a struct or in a tuple), you will always have to instantiate this object. This may not be feasible for objects that acquire a resource in their constructor, or that are not default-constructible.
If you return by output-parameter, this is even worse. The caller must instantiate an empty object, and you must copy the return value into that object. This means the object must have an "empty" state, and be mutable. This empty state may be at odds with RAII, and makes the code more fragile.
The three robust solutions are:

*

*use exceptions,

*use an optional<T> type, or

*return by pointer.

These are all very good, but have different tradeoffs.
Exceptions allow you to write your code as if the return value will always be there. However, C++ exceptions are unsuitable for a kind of return code. Only use them if the output will usually be there, and its absence is an error of some kind. E.g. std::vector::at() uses exceptions when no result can be returned because a bounds check failed.
An optional type lets you return by value, but the value may be uninitialized. This sidesteps the problems mentioned above regarding construction of the returned object. An optional type can be thought of as a type-safe tagged union with a single member.
Returning by a pointer-like type is the most general solution, because this can handle objects that cannot be copied or moved. By using smart pointers, you can specify ownership semantics (unique, shared, or plain pointers for unspecified/borrowed). This is done very commonly with iterator-based algorithms, as iterators are somewhat pointer-like. The advantage of using types that have a boolean conversion is that you can easily check the return value in a conditional:
if (auto result = some_function()) {
  result->foo();  // statically known that result != nullptr
}

Pointers or references are necessary anyway when returning polymorphic types, so using pointers might not be a big change.
The disadvantage is of course when you create a new object that you want the caller to own. You should then return an unique_ptr. But if you would otherwise return by value, returning an optional would be better, as it avoids unnecessary indirection and heap allocations.

A: Returning something if that something is there, and nothing otherwise, is exactly what std::optional is made for.
If your compiler doesn't yet have this type and you can't upgrade, you can use the Boost version.

A: I would argue that option #2 is the way to go. As you stated in Option #1, exceptions aren't meant to control flow of the program; especially if failure is an expected option. (which it is in your case)
Booleans are, and they're used for it frequently. ie:

if(flag)
    #do something
else
    #do other thing

A: 1. Throwing exception if the point is not found:
This is dangerous because exceptions are gotos in disguise. It takes experience with them to get them correct. If you are writing this for others, then I recommend you avoid this option.
2. Alter the declaration to:
A viable option but other developers will ignore the bool.
3. Wrapping the out put:
Same as #2; the bool part is likely to be ignored. Also, perhaps you would want to use and object instead of a struct.
4. Returning pointer instead:
A combination of the above. Most developers will simply assume that nullptr will never be returned.

A fifth option: 5. Return a guard value.
Since the point is in an image, its coordinates are always zero or positive. Returning a guard value, say (-1,-1), is common but can cause errors later in the code since the guard value too will most likely be ignored.

There is no good answer to this. All options have problems. The best you can do is to follow the most common practice of those who will be using the function.


text:
Q: Eigenvalues of $8\times8$ non-diagonal matrix $A$ satisfying $A^2 - 6A + 9I_8 = 0_8$ In an exam today I had the following problem:

Let $A \in M_{8}(\mathbb{R})$ ($8\times8$ matrix with real entries) satisfying $$A^2 - 6A + 9I_8 = 0_8$$ Find the eigenvalues of $A$.

My approach
If $\lambda$ is an eigenvalue and $v$ is an eigenvector with eigenvalue $\lambda$, dotting both sides of the equation with $v$ gives
$$\lambda^2 + 6\lambda + 9 = 0 \implies (\lambda - 3)^2 = 0 \implies \lambda = 3.$$
On the other hand the given relation reads $(A - 3I_8)^2 = 0_8$ so
$$\det(A - 3I_8)^2 = 0 \implies \det(A - 3I_8) = 0.$$
Thus $3$ is always an eigenvalue of A, so we get $\text{Spec} A = {3}.$
My question
Why is it relevant that $A$ is nondiagonal? The only implication I could find is that considering the minimal polynomial $p(x)$ of $A$, we have
$$p(x) \mid (x - 3)^2 \Rightarrow p(x) = x-3 \text{  or  } p(x) = (x-3)^2.$$
But since $A$ is nondiagonal we can't have $p(x) = x - 3$ so $p(x) = (x-3)^2$. But I don't see why this would influence the eigenvalues of $A$.
So is the fact that $A$ is diagonal relevant?

A: The matrix is similar to one or more little blocks on the diagonal, each
$$
\left(
\begin{array}{cc}
3&1 \\
0&3
\end{array}
\right)
$$
Whatever is left over is diagonal $3$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Merge two SQL data tables in asp.net website using vb.net in code behind I can't seem to find a solution that fits.
Here is the situation. I have a two SQL queries from the same table each with a different where clause.
Table A uses this SQL statement:
Select   jo.AssemblySeq As Assm,
         jo.OprSeq As [OP Center #],
         jo.WCCode As WC,
         Convert(Varchar, jo.DueDate, 101) As [Due Date],
         ja.RequiredQty As Qty,
         jo.QtyCompleted As [Qty Comp],
         jo.OpComplete As OpComplete
From     JobOper jo
Join     JobAsmbl ja
    On jo.JobNum = ja.JobNum
       And jo.AssemblySeq = ja.AssemblySeq
Where    jo.JobNum Like '236087.%'
         And ja.AssemblySeq <> 0
Order By jo.AssemblySeq;

And returns this data:

Table B uses this SQL query:
Select   jo.AssemblySeq As Assm,
         jo.OprSeq As [OP Center #],
         jo.WCCode As WC,
         Convert(Varchar, jo.DueDate, 101) As [Due Date],
         jo.QtyPer As QTY,
         jo.QtyCompleted As [Qty Comp],
         jo.OpComplete As OpComplete
From     JobOper jo
Join     JobAsmbl ja
    On jo.JobNum = ja.JobNum
       And jo.AssemblySeq = ja.AssemblySeq
Where    jo.JobNum Like '236087.%'
         And ja.AssemblySeq = 0
Order By jo.AssemblySeq;

And returns this data:

What I need to do is merge these two tables so that I have columns called Assm, OP Center #, WC, Due Date, Qty, Qty Completed, OpComplete. My problem is that the where clause for the query for table A has ja.AssemblySeq <> 0 and the where clause for the query for table B has ja.AssemblySeq = 0.
I need all the lines from both queries. I am not sure if I need some type of Join or if it would involve sub queries?

A: A simple UNION ALL will help as below:
Select * from Query1
  Union All
Select * from Query2

A: You don't need to do a UNION ALL at all.  You can do this with one single query, without the need to hit the table twice.
Your queries are identical with the exception of the column selected based on the value of ja.AssemblySeq.  You can just remove the WHERE clause altogether and make the Qty column a CASE expression.
Select   jo.AssemblySeq As Assm,
         jo.OprSeq As [OP Center #],
         jo.WCCode As WC,
         Convert(Varchar, jo.DueDate, 101) As [Due Date],
         Case When ja.AssemblySeq = 0
             Then jo.QtyPer
             Else ja.RequiredQty
         End As Qty,
         jo.QtyCompleted As [Qty Comp],
         jo.OpComplete As OpComplete
From     JobOper jo
Join     JobAsmbl ja
    On jo.JobNum = ja.JobNum
       And jo.AssemblySeq = ja.AssemblySeq
Where    jo.JobNum Like '236087.%'
Order By jo.AssemblySeq;


text:
Q: Turn inputs into objects in an array with a loop how do I turn this
 <input class="optionsGraph" name="name1" value="value1">
 <input class="optionsGraph" name="name2" value="value2">
 <input class="optionsGraph" name="name3" value="value3">
 <input class="optionsGraph" name="name4" value="value4">
 <input class="optionsGraph" name="name5" value="value5">

into this (with a loop)?
var example = [
            { label: "name1",  y: value1, x: 1  },
            { label: "name2", y: value2, x: 2  },
            { label: "name3", y: value3, x: 3  },
            { label: "name4",  y: value4, x: 4  },
            { label: "name5",  y: value5, x: 5  }
          ];

I was thinking with something like this?
$(".optionsGraph").each(function(key) {
           //another loop

          });

I'm really struggling with this

A: You can use .map() along with .get()

As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array.

var arr = $('.optionsGraph').map(function(index) {
  return {
    label: $(this).attr('name'), //Get attribute
    y: $(this).val(), //Get elements value
    x: index + 1
  }
}).get();

console.log(arr)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="optionsGraph" name="name1" value="value1">
<input class="optionsGraph" name="name2" value="value2">
<input class="optionsGraph" name="name3" value="value3">
<input class="optionsGraph" name="name4" value="value4">
<input class="optionsGraph" name="name5" value="value5">

A: Adding a line to your loop.
var output =[];
$(".optionsGraph").each(function(key) {
    output.push({label : $(this).attr("name"), y: $(this).val(), x : key+1 );
});

https://jsfiddle.net/La25kkqz/

A: Try this :
var res = [], i = 0;
$(".optionsGraph").each(function(key) {
           //another loop
        res.push({
        label: $(this).attr('name'),
      y : $(this).val(),
      x: ++i
    });
});

https://jsfiddle.net/8qqphkpf/

A: Pure js solution, using Array#map.

var elems = document.getElementsByClassName('optionsGraph'),
    res = Array.from(elems).map((v,i) => ({label: v.name, y: v.value, x: i+1}));

    console.log(res);
<input class="optionsGraph" name="name1" value="value1">
<input class="optionsGraph" name="name2" value="value2">
<input class="optionsGraph" name="name3" value="value3">
<input class="optionsGraph" name="name4" value="value4">
<input class="optionsGraph" name="name5" value="value5">

A: Try this Array#push

var example=[]
$(".optionsGraph").each(function(a,b) {
example.push({label:$(this).attr('name'),  y:$(this).val(), x: a+1})
 });
 console.log(example)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="optionsGraph" name="name1" value="value1">
 <input class="optionsGraph" name="name2" value="value2">
 <input class="optionsGraph" name="name3" value="value3">
 <input class="optionsGraph" name="name4" value="value4">
 <input class="optionsGraph" name="name5" value="value5">


text:
Q: Unable to run VMware on RHEL 8 after signing vmmon and vmnet After installing RHEL 8 with the required libraries and signed vmmon & vmnet, then imported the mok I am still unable to run a virtual machine in VMWare Workstation (the same goes for VMWare Player)
This is how I am signing vmmon and vmnet:
openssl req -new -x509 -newkey rsa:2048 -keyout VMWare.priv -outform DEF -out VMWare.der -nodes -days 36500 -subj "/CN=VMware/"

/usr/src/kernels/$(uname -r)/scripts/sign-file sha256 ./VMWare.priv ./VMWare.der $(modinfo -n vmmon)
/usr/src/kernels/$(uname -r)/scripts/sign-file sha256 ./VMWare.priv ./VMWare.der $(modinfo -n vmnet)

mokutil --import VMWare.der

I successfully import VMWare.der on reboot but I still get the following error:

Could not open /dev/vmmon: No such file or directory. Please make sure
that the kernel module `vmmon' is loaded.

Thanks
Graham Harris
Update 1:
I have reverted back to RHEL 7.8, updated, and signed the VMMON & VMNET files, got "Can't read private key", imported the MOK and the installation was borked.
Update 2:
On the boot screen the system says
Red Hat Enterprise Linux Server (3.10.0-1127.e17.x86_64) 7.8 (Maipo)

If I update to the latest that is when the system cannot get past the UEFI splash screen.
Update 2
Switched back to RHEL 8, and after importing the MOK I run mokutil -l and the key is not found.
However a recent search found this article on git MOK enrollment silently fails #105
Summary of the issue:

When writing MokList with EFI_VARIABLE_APPEND_WRITE, some HP laptops
may just return EFI_SUCCESS without writing the content into the flash,
so we have no way to detect if MokList is updated or not. Now we always
read MokList first and write it back with the new content.

A: After many attempts (even after looking at the source of MOKUTIL) I have disabled secure boot on the UEFI boot settings on the computer and VMWare worked. This is the configuration that allows me to run  VMWare on RHEL 8. Using BIOS Mode to boot still requires the drivers to be signed, however, disabling secure mode for UEFI boot mode vmmon and vmnet do not need to be sigend.
For those who want to know the BIOS information here they are, to get this information I used sudo dmidecode :
# dmidecode 3.2
Getting SMBIOS data from sysfs.
SMBIOS 2.7 present.
---%<-------------

BIOS Information
    Vendor: Dell Inc.
    Version: A05
    Release Date: 07/26/2012
    Address: 0x00000
    Runtime Size: 64 kB
    ROM Size: 8 MB
    Characteristics:
        PCI is supported
        BIOS is upgradeable
        BIOS shadowing is allowed
        Boot from CD is supported
        Selectable boot is supported
        BIOS ROM is socketed
        EDD is supported
        5.25"/1.2 MB floppy services are supported (int 13h)
        3.5"/720 kB floppy services are supported (int 13h)
        3.5"/2.88 MB floppy services are supported (int 13h)
        Print screen service is supported (int 5h)
        8042 keyboard services are supported (int 9h)
        Serial services are supported (int 14h)
        Printer services are supported (int 17h)
        ACPI is supported
        USB legacy is supported
        BIOS boot specification is supported
        Targeted content distribution is supported
        UEFI is supported
    BIOS Revision: 4.6

    ---%<-------------

A: I'm running Fedora 36, and I was able to get VMware to boot up a virtual machine without needing to disable secure boot.
I followed the steps from this VMware knowledge base article.
However, I was not able to follow step 2 because I do not have /usr/src/linux-headers because I installed "Development Tools" and "Development Libraries" as suggested by this answer.
Instead, I scrolled down to the Related Information section from that VMware knowledge base article and signed the kernel files at /usr/src/kernels/.
For the mokutil public key importing step, I needed superuser privileges. Note this step involves creating a new password.
And most importantly, for the MOK enrollment screen to show up in the UEFI console, I needed to use the command reboot from my terminal as opposed to restarting the computer from the start menu. I followed the steps in the UEFI console which prompted for the new password that I created when I imported the public key to the system's MOK list. These steps eventually prompted me to reboot my computer again, which I did.
And voila! I am now able to run my Kali VM on VMware.


text:
Q: Identifying the list of test cases failed in testng Could you please tell me how I can identify the list of test cases failed in suite execution using testng. I need to rerun the failed test cases Automatically.
Thanks in advance!

A: As part of the execution, testng generates a file called testng-failed.xml which contains all the details of methods that failed. If you are just looking for re-running failed tests, you can find this file (In a maven project it resides under the target folder.
You can do the following (I am going to assume that you are using maven):

*

*Accept the suite name in your surefire plugin via a Maven property.

*Modify the surefire plugin to refer to the maven property for the suite name.

*Create a shell script or a batch file which does the following:

*

*Checks if the file testng-failed.xml exists in the target folder.

*If found then a rerun can be done.

*Take back-up of the surefire reports folder to some other place, this is because if its not done then the old reports gets overwritten.

*Re-run the tests by passing the testng-failed.xml location to the Maven property that is being used in your surefire plugin.

That should do.
The other option is to basically build an implementation of org.testng.IRetryAnalyzer and bind that with your @Test method. This will cause TestNG to try invoking the @Test method once again if it fails, till the IRetryAnalyzer implementation returns back a false indicating TestNG not to try any more.
Here's a sample
public class MyRetry implements IRetryAnalyzer {

  private int retryCount=0;
  private int maxRetryCount=1;

  @Override
  public boolean retry(ITestResult result) {
    if (retryCount < maxRetryCount) {
      retryCount++;
      return true;
    }
    return false;
  }
}

public class GitHub1241Sample {

  @Test(retryAnalyzer = MyRetry.class)
  public void test2() {
    Assert.fail();
  }
}

If you use a retry analyzer, you dont need to take backup of the reports etc.,


text:
Q: Use emacs to copy kill-ring to window/buffer based on position This may be too involved.
Considering:
In emacs in r-mode or lisp mode (etc) information can be sent directly (copied, pasted, evaluated) from one buffer to the the R or Lisp interpreter.
I typically configure an emacs session to have 3 windows - a large horizontal window on top and two windows beneath it. (How) could I configure, which keys/ commands might I use to send the kill-ring to the last cursor position of the top window / buffer?
The buffer / window will not always necessarily have the same contents/file. (How) could I name it upon initialization?
Similar to C-X, C-B or C-X, B how might I specify which of the three window positions to go to (based on position)?

A: I think you're going to have to write lisp code to do this effectively.  Basically, you'd want a minor mode that sets up the two subwindows -- which isn't hard, it happens in compile mode from M-x compile -- and then make special keybindings for the keys you want to use.

A: See window-at.  For example,

(defun yank-into-top-window (&optional arg)
  (interactive "*P")
  (with-selected-window (window-at 0 0)
    (yank arg)))


text:
Q: How to deduce the formula for quadratic form? I almost every book about quadratic form we can see it described as following function:
$$
f(x) = \frac{1}{2}x^T A x - b^Tx + c
$$
My question is:
How can we deduce this formula?

I understand, that the quadratic form is the following product:
$$
Q( \boldsymbol{x} ) = \boldsymbol{x}^TA \boldsymbol{x}
$$
where $\boldsymbol{x}$ is a vector, $A$ is a symmetric matrix and $\boldsymbol{x},A$ are defined over $F$, where $F$ is some arbitrary field (except those, who have a characteristic $2$).
This product can be rewritten by summation like this:
$$
Q \left(\boldsymbol{x} = (x_1, \ldots, x_n) \right) = \sum^n_{i=1} \sum^n_{j=1} A_{ij}x_i x_j
$$
I understand, that because the matrix is symmetric $A_{ij} = A_{ji}$, so when I want to get the value for one $x$, I must divide it by $2$. That's exactly the first part of the polynomial:
$$
\frac{1}{2}x^T A x
$$
But, where do $-b^T + c$ come from? I think, that it's related with the linear system $A \boldsymbol{x} = \boldsymbol{b}$, but I have no idea, how to use it in this deduction...

A: Suppose we have two variables $x_1$ and $x_2$. Then the general quadratic function is:
$f(x_1,x_2)=a_1x_1^2+a_2x_2^2+a_{12}x_1x_2+b_1x_1+b_2x_2+c$
The first three summnads can be expressed by $\frac12 x^TAx$ with $A=\begin{pmatrix}{} 2a_1 &a_{12} \\ a_{12} & 2a_2\end{pmatrix}$
The fourth and the fifth summand are $b^Tx=\begin{pmatrix}{}b_1 & b_2\end{pmatrix}\cdot  \begin{pmatrix}{} x_1 \\ x_2\end{pmatrix}$
And $c$ is a scalar (constant).
Calculate $\frac12x^TAx+b^Tx+c$ and you´ll get $f(x_1,x_2)$.


text:
Q: Imported global variable from dll not updated I am exporting a global variable from a dll using __declspec(dllexport) and importing the same in the client exe using __declspec(dllimport).
The global variable in the dll is being updated with time in a separate thread. I want to receive this updated data in my client .exe, but I am not getting it. What I get is the only initial value of the global variable every time I read the data using a timer in the client exe.
What is the explanation of such a behavior? and what can I do to achieve what I want to achieve? Is there an option without including get() and set() exported functions from the dll?
Here is the code that is exported from dll:
typedef struct{
    int iTotalQueues;
    int iCurrentQueue;
    wchar_t szQueueName[100];
}UPDATE_STATUS_DATA;

__declspec(dllexport) UPDATE_STATUS_DATA UpdateStatusData;

This structure members are updated in a loop for a long time. The updating code is in the dll itself.
Here is the code that is imported in the exe:
typedef struct{
    int iTotalQueues;
    int iCurrentQueue;
    wchar_t szQueueName[100];
}UPDATE_STATUS_DATA;

__declspec(dllimport) UPDATE_STATUS_DATA UpdateStatusData;

I am reading this data inside a timer response and not getting the updated values.

A: The code in your question as you would expect when built into a simple test project. So, here are the two explanations that I can concoct:

*

*You are taking a copy of UpdateStatusData in your executable. And so the changes to the value of UpdateStatusData made in the DLL do not get reflected in the copy.

*Your DLL is, for some reason, not modifying the struct.


text:
Q: Spotify Play Button and Google Analytics I'm trying to track clicks in the Spotify Play Button iframe using Google Analytics, without much success so far. I'm attempting to use jQuery to capture the click.
The code
$('iframe .clickable.play-pause-btn').click(function(){
    alert('foo');
});

obviously doesn't work as it's cross domain. Is there any alternative that can capture these clicks? Or do I just live safe in the knowledge that I'll never know how many users hit play?
Thanks in advance!

A: I think that the cross domain policy wont let you track an event on an element inside an iframe that's running on a different domain.
I dont think we have a solution to send tracking info to the parent window.


text:
Q: Which Bluetooth library is stack independent I making a windows application that needs to use Bluetooth for communication so far as now I have tried blue cove for Java.
It seems to be limited to few stacks only.. I have a Toshiba stack, but I still want a library that could handle most popular stacks.
Doesn't matter if its for C, C++ or Java.

A: Bluecove is already as good as it gets.
This is due to the unfortunate fact of how Bluetooth is handled on Windows. Instead of agreeing on a single implementation for the whole platform, vendors tend to ship their own stack with the device driver software. This is partly due to historical reasons and partly because hardware vendors don't care enough about this to do anything about it.
Bluecove provides implementations for the Microsoft, Broadcom WIDCOMM and BlueSoleil stacks, which should cover >90% of all available devices. In your case, I see three options:

*

*Try to get your device to work with a different stack. I know for a fact that BlueSoleil works with certain Toshiba-based devices, google should give a good overview of the options for your specific device.

*Get another device. Bluetooth dongles are ridiculously cheap these days, so this is a valid option. It's a bit more messy than using a build-in device, but then again, what good is a build-in device if the software doesn't work?

*Try to write an implementation for Toshiba devices for Bluecove yourself. IIRC Toshiba does provide an SDK upon request. You might run into legal issues though if the license forbids integration with Bluecove in some way.
Morale of the story: Bluetooth drivers are a mess, especially on Windows. Be sure to check your software's requirements before you buy your next device.


text:
Q: Submitting Json to Spring MVC Controller returning jsp as ajax response string I am creating Spring mvc app. I am submitting JSON string to controller through AJAX. What I want is to redirect the page to different JSP page.
Right now I am returning the view from controller but instead of redirecting it is returning response to previous AJAX request.
Spring Controller
@RequestMapping("/hello")
public String hello() {
    return "powerseries";
}

Javascript/Ajax
$(document).ready(function(){
        $('#getData').click(function(){
            var aa=JSON.stringify(answer);
            $.ajax({
    type: "POST",
    url: "hello",
    contentType: "application/json",
    dataType:'json',
    data:aa,
    cache: false,
    processData:false,
    success: function(status){
        console.log("Entered",status);
    },
    error:function(error){
        console.log("error",error);
    }
});
        });
});
console.dir(answer);

Browser Console

A: When you are using AJAX, your MVC should return a special JSON response.
eg:
@RequestMapping("/hello")
@ResponseBody
public Map hello() {
    m.put('my_redirect', 'the new url');
    return m;
}

then handle this response in your AJAX's handler. Use javascript's window.location.href = resp.my_redirect; to go to the new url.

A: If you want to redirect to other jsp page ,  use redirect inside controller method.
@RequestMapping("/hello")
 public String hello() {
   // return "powerseries";
   return "redirect:powerseries";
}

// Add method to controller .
@RequestMapping("/powerseries")
 public String returnPowerseries() {
  return "powerseries";
}

or just use $("html").html(response); if you want to entirely change your document html.


text:
Q: Error: This Operation cannot be performed after request has been submitted I've written code about httpwebrequest and httpwebresponse . I need to send data to server but got this exception "This operation cannot be performed after request has been submitted". see the following code:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://"+remoteServer+":8080/");
request.Credentials = CredentialCache.DefaultCredentials;
//Stream NewReqstream = request.GetRequestStream();
request.Method = "POST";
//request.ContentLength = cmd.Length;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.WriteLine("Connected..");

// Send the command
//clientSocket.Send(cmd);

Stream NewReqstream = request.GetRequestStream(); //<-- Error here
NewReqstream.Write(cmd, 0, cmd.Length);
NewReqstream.Close();

A: when you get the response stream the request is submitted so you can not the operation there...
Try it like:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://"+remoteServer+":8080/");
request.Credentials = CredentialCache.DefaultCredentials;
//Stream NewReqstream = request.GetRequestStream();
request.Method = "POST";
//request.ContentLength = cmd.Length;

// Send the command
//clientSocket.Send(cmd);

Stream NewReqstream = request.GetRequestStream(); //<-- Error here
NewReqstream.Write(cmd, 0, cmd.Length);
NewReqstream.Close();

// Get the response
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.WriteLine("Connected..");

A: The exception tells you what you need to know; HTTP is request => response, so if you have asked for the response (GetResponse()) you have implicitly said "my request is complete; give me the response". Move the GetRequestStream() code above the GetResponse().

A: Make request before response. For anyone needs multiple requests and responses make sure using different variables for each request and response such as req1 res1, req2 res2...


text:
Q: Dificuldade em posicionar tabela na tela com bootstrap - layout apenas Preciso fazer um layout em minha página, da seguinte forma. Que eu eu tenha três controles textbox, um em baixo do outro e pegando do outro lado todo o restante com uma table. Veja abaixo como eu preciso.

Tentei de várias formas, diminuindo o meu grid de 12 para 6 e o que acontece quando eu coloco a imagem é o seguinte: A imagem realmente fica à direita dos controles, mas empurra os controles para baixo. A tabela que eu fiz é apenas um exemplo.
Veja abaixo como ficou a tela

Esse é meu cshtml. Essa tabela é apenas para testes, os valores não tem nada a ver, apenas estou testando o layout da tela.
@{
    ViewBag.Title = "CadastroAcesso";
    Layout = "~/Views/Shared/_LayoutBase.cshtml";
}

Cadastro de Acesso ao Sistema

                Usuário de Rede:

                <input type="text" class="form-control col-md-6" name="txtUsuarioRede" id="txtUsuarioRede" placeholder="Digite um usuáruo da rede">

                        Item ID
                        Item Name
                        Item Price

                        Item ID

                            Item Name

                            Item Price

                        Item ID

                            Item Name

                            Item Price

                        Item ID

                            Item Name

                            Item Price

                Usuário de Rede:

                <input type="text" class="form-control col-md-6" name="txtUsuarioRede" id="txtUsuarioRede2" placeholder="Digite um usuáruo da rede">

A: Eu colocaria a tabela em uma coluna e as inputs em outra, pra dividir a tela. Não sei se é o que você quer mas ficaria assim:

                Usuário de Rede:

                <input type="text" class="form-control col-md-6" name="txtUsuarioRede" id="txtUsuarioRede" placeholder="Digite um usuáruo da rede">

                Usuário de Rede:

                <input type="text" class="form-control col-md-6" name="txtUsuarioRede" id="txtUsuarioRede2" placeholder="Digite um usuáruo da rede">

                    Item ID
                    Item Name
                    Item Price

                    Item ID

                        Item Name

                        Item Price

                    Item ID

                        Item Name

                        Item Price

                    Item ID

                        Item Name

                        Item Price


text:
Q: The number of context switches as reported by vmstat doesn't match up with the total of pidstat I am monitoring the number of context switches in a java application. vmstat 1 gives cs per second globally. pidstat -wt also reports the cs per second for all the threads. This doesn't match up at all. The former is of the order of 40k whereas the latter is around 20-40 per second at max for a given process (much lower around 1 for most processes).
What is the reason for this mismatch? What is getting missed in the pidstat output?


text:
Q: Connect-PnPOnline -Url https://.sharepoint.com.eu.cas.ms -UseWebLogin hangs with a blank window I'm trying to connect to a site where I'll try to upload some documents, here is what I try to do:
Connect-PnPOnline -Url  https://<mysite>.sharepoint.com.eu.cas.ms -UseWebLogin

What happens is it just opens a blank window and hangs.
What I have tried to do:

*

*Connect-PnPOnline -Url  https://<mysite>.sharepoint.com.eu.cas.ms/sites/<my-site> -UseWebLogin (use the full pat h to the site)

*Connect-PnPOnline -Url  https://<mysite>.sharepoint.com/sites/<my-site> -UseWebLogin  (use that path before it was redirected)

*Connect-PnPOnline -Url  https://<mysite>.sharepoint.com.eu.cas.ms -UseWebLogin (same only with the root)

Logging into the site on the web works fine however, as does Connect-PnPOnline -Url  https://<mysite>.sharepoint.com.eu.cas.ms/sites/<my-site> -Credentials (Get-Credential)
I'm on Windows 10, PowerShell version 5.1 and I'm using SharePointPnPPowerShellOnline version 3.13.1909.0.
Any ideas on what I can do to fix this would be appreciated.
Any ideas?


text:
Q: "someone nodded abstractly" for the first time, I read something using the 2 words "nodded abstractly". I Google  it. People use it quiet often...
I read it there:

"Welcome aboard," said Justin, one of the programmers. He stood up and grabbed a rubber chicken from a nearby desk. "Kevin and I are going to integrate our changes now," he announced to the rest of the group. A few people nodded abstractly, already intent on their work.

My question is, how can a person nod abstractly or in an abstract way...?

A: One of the meanings of "abstract" given in the OED (though marked as "archaic") is:

*

*Withdrawn from the contemplation of present objects; = abstracted adj. 2. arch.

That is how I would understand "nodded abstractly" - "nodded as though with his mind on other things".

A: As Colin quoted, the use of abstractly in the sense "absent-mindedly" is now archaic—I don't remember ever seeing it. Such an archaic word would not fit the rest of the text. It is most likely that this writer intended abstractedly, which means the same and is in current use.

A: Distractedly might be what they mean.

A: The adjective abstract is defined here as:

5. Impersonal, as in attitude or views

An Ngram shows that nod abstractly and nodding abstractly seem to never be used, and nodded abstractly only began to be used recently (a little in the 1930's and increasingly in the 1980's and 1990's).  I agree that it probably derives from mistaking the word with distractedly.
Given all of that, I expect it would refer to an impersonal nod, a simple acknowledgement of another.

A: I did a quick Google and most of the instances of this I found were in fan fictions and amateur short stories. I'm not sure it's a proper turn of phrase, probably someone misheard Nodded Distractedly and got it wrong.
It just doesn't make sense...

A: I've seen it written as someone nodded 'absently','perfunctorily' or 'distractedly' but never 'abstractly'.
Like the others noted, it suggests impersonality, distractedness. Basically someone's nodding at you, but not necessarily paying attention to what you've been saying.


text:
Q: Laravel 5.0 folder structure: public vs. resources In Laravel 4.2, I used public folder to store all my CSS, JS, images and uploads. Currently, there's a new resources folder with assets folder in it coming with Laravel 5.0 installation:
/public/resources/assets
This is confusing to me, especially because resources also holds views in it.
Via Laravel's upgrade guide (4.2 to 5.0):

Copy your application's public assets from your 4.2 application's
  public directory to your new application's public directory.

and further:

You may move your Sass, Less, or CoffeeScript to any location you
  wish. The resources/assets directory could be a good default location.

Question: What is the actual difference between public and resources folders in Laravel 5.0 folder structure?

A: The big difference here is that everything in public is... well public. resources aren't. What you put in where is up to you.
Generally you would have everything the browser needs to access directly in the public directory. Which usually means: JavaScript, CSS, images, maybe some videos or audio files.
resources/assets is meant for things that have to be compiled or minified first. So you would have a few LESS or SASS files in resources/assets and they would get compiled and minified into one CSS file that's put in the public directory.

A: Laravel elixir, by default uses the /resources/assets folder as the base directory for scripts to be compiled, minified and so on. So you should put your raw sass, less, coffeescript, js and css files in there to let elixir do it's work. A good place for the files you are using is the public folder.
When working this way, you can have all your files concatenated and minified with gulp and less effort. Simply include them from your public folder.

A: You can think of them as being separate folders for development and production. In resources you have all your development files that'll not ship off into production (SASS, Coffeescript, Babel, Jade, etc). But when they're compiled (or piped through something like Gulp) you can configure them to output to public, the production folder.

A: In laravel public folder is best for Image, CSS, and Javascripts. In public folder we can use for uploaded images, videos, text files etc.


text:
Q: ASP.NET MVC - ModelState is invalid but form content is acessible I am trying to pass some input from the "Create" view to my controller but the ModelState is returning error:
The Controller:
[Route("Create")]
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create([Bind("Name, Location, MaxCapacity")] Warehouse warehouse)
{

    if (ModelState.IsValid)
    {
        _Db.Add(warehouse);
        _Db.SaveChanges();
        return RedirectToAction("Index");
    }

    return BadRequest();
}

The view:
@model InventoryManSys.Models.Warehouse

@{
    ViewData["Title"] = "Create";
}

Create

Warehouse

        <form asp-action="Create">

                <input asp-for="Name" class="form-control" />

                <input asp-for="Location" class="form-control" />

                <input asp-for="MaxCapacity" class="form-control" />

                <input type="submit" value="Create" class="btn btn-primary" />

        </form>

The model:
public class Warehouse
{
    [Key]
    public int Id { get; set; }
    [Required]
    [StringLength(30, ErrorMessage = "Name should have less than 30 characters")]
    [DisplayName("Warehouse Name")]
    public string Name { get; set; }
    [Required]
    public string Location { get; set; }
    [Required]
    public int MaxCapacity { get; set; }

    //Navigation Property
    public ICollection<Category> Categories { get; set; }

}

But when I do a "Console.WriteLine(warehouse.Name)" the input is being passed correctly. How to solve that? is the "bind[]"attribute a problem?

A:
ModelState is invalid but form content is acessible

You may add the client validation js library jquery.validate.js and jquery.validate.unobtrusive.js.
Check this document:
https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-6.0#client-side-validation
If Name/Location/MaxCapacity are received value, it should work fine, suggest you can check the ModelState or just return BadRequest(ModelState); to see what's the detailed error.
But if you use .NET 6, as this document said:

Beginning with .NET 6, new projects include the
<Nullable>enable</Nullable> element in the project file. Once the
feature is turned on, existing reference variable declarations become
non-nullable reference types.

So that the non-nullable property must be required in ASP.NET 6, otherwise the ModelState will be invalid.
One way is to remove <Nullable>enable</Nullable> from your project file.
Another way is to add ? like below:
public class Warehouse
{
    [Key]
    public int? Id { get; set; }
    [Required]
    [StringLength(30, ErrorMessage = "Name should have less than 30 characters")]
    [DisplayName("Warehouse Name")]
    public string Name { get; set; }
    [Required]
    public string Location { get; set; }
    [Required]
    public int MaxCapacity { get; set; }

    //Navigation Property
    public ICollection<Category>? Categories { get; set; }

}


text:
Q: How to fix "Memory Error" while fetching feeds from hailataxii service? I am fetching feeds from Hailataxii service using Python's libtaxii library. It has 9 feeds, I have successfully fetched 6 feeds but 3 of the feeds are giving me Memory Error.
I have run this program on Linux with 15GB RAM, I tracked it for 6 hours and the memory utilization was exceeding and after 12 hours when I checked the progress again, it was displaying Memory Error.
import libtaxii as t
import libtaxii.messages_11 as tm11
import libtaxii.clients as tc
from libtaxii.common import generate_message_id
from libtaxii.constants import *

RESULTING_FOLDER = 'results'

FEEDS = [
    'Abuse_ch',
    'CyberCrime_Tracker',
    'EmergingThreats_rules',
    'Lehigh_edu',
    'MalwareDomainList_Hostlist',
    'blutmagie_de_torExits',
    'dataForLast_7daysOnly',
    'dshield_BlockList',
    'phishtank_com'
]

USERNAME = 'guest'

PASSWORD = 'guest'

def main(username, password, feeds, result_folder):
    client = tc.HttpClient()
    client.set_auth_type(tc.HttpClient.AUTH_BASIC)
    client.set_auth_credentials({'username': username, 'password': password})
    client.set_use_https(False)

    for feed in feeds:
        print('Start extracting `{}` feed ({}/{})'.format(feed, feeds.index(feed)+1, len(feeds)))
        #print('Start extracting `'+str(feed)+'` feed ('+str(feeds.index(feed)+1)+'/'+str(len(feeds))+')')
        poll_request = tm11.PollRequest(generate_message_id(),
                                        collection_name=feed,
                                        subscription_id=generate_message_id())
        poll_xml = poll_request.to_xml(pretty_print=True)
        http_resp = client.call_taxii_service2('hailataxii.com', '/taxii-data', VID_TAXII_XML_11, poll_xml)
        taxii_message = t.get_message_from_http_response(http_resp, poll_request.message_id)

I expected creation of an XML file in results directory because the code after get_message_from_http_response() function writes the response in an XML format. All feeds were extracted successfully except blutmagie_de_torExits, dataForLast_7daysOnly and phishtank_com.
Error in console is
Traceback (most recent call last):
 File "hailataxii_feeds_saver.py", line 63, in <module>
    feeds.feeds_arg, result_folder.result_folder_arg)
 File "hailataxii_feeds_saver.py", line 31, in main
    http_resp, poll_request.message_id)
 File "/home/bscs8/.local/lib/python2.7/site-packages/libtaxii/ init .py", li ne 47, in get_message_from_http_response
    return get_message_from_urllib_addinfourl(http_response, in_response_to)
 File "/home/bscs8/.local/lib/python2.7/site-packages/libtaxii/ init .py", li ne 109, in get_message_from_urllib_addinfourl
    return tmll.get_message_from_xml(response_message, encoding)
 File "/home/bscs8/.local/lib/python2.7/site-packages/libtaxii/messages_11.py", line 75, in get_message_from_xml
    xml_string = xml_string.decode(encoding, 'replace')
 File "/usr/lib/python2.7/encodings/utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
MemoryError


text:
Q: Copy values from a ListBox to worksheet cells I'm working with VBA and have a problem I just can't find a solution for. I created a UserForm with a TextBox, a ListBox, and two Buttons. If you enter a text to the TextBox and click the Button1, then the text of the TextBox will be added via the command ListBox.AddItem to the Listbox. This part works perfectly fine.
If you click on Button2, it shall copy the entries of the ListBox to the Excel Sheet. I'm having a problem with this part. The code is as follows:
For i = 0 To ListBox1.ListCount - 1
    ListBox1.Selected(i) = True
    ActiveSheet.Cells(2, 3) = ListBox1.Value
    ListBox1.Selected(i) = False
Next i

This code works perfectly fine if I open the UserForm and click once just anywhere in the ListBox. From then the code works without problems. I also can close the UserForm and open it again. It will still work.
The problem appears if I open the whole Excel File and the UserForm and don't click once somewhere in the ListBox, it just doesn't copy the content. The code itself still works and is performed. It just seems as the command ListBox1.Value has no content. Is there a better way to solve my issue?

A: If you want to place the items from the already populated ListBox onto the Sheet, you may try something like this...
Dim x
x = Me.ListBox1.List
Range("C2").Resize(UBound(x) + 1, 1).Value = x

Tweak it as per your requirement.


text:
Q: voltage drop alternative to resistor My application requires me to drop voltage from 12v to 6v or any other lower voltage.
I have used resistors but they are not efficient for prolonged use as they tend to heat up and burn my fuse.
I want to know whether there are any other IC or a simple circuit which 'll be small in size, inexpensive, efficient and does not heat up much to cause problem.

A: I presume this would be for a power supply?  If the voltage drop from 12v to 6v releases too much heat, then I would recommend using a DC to DC converter of some sort.  A linear regulator is basically just a glorified resistor, so converting 12V to 6V would make a linear converter 50% efficient.  A switching power supply can be 70% to 90+% efficient, and as a result will produce far less heat.  A buck power supply would be the way to go, and you can either build one yourself with an off-the-shelf controller chip or just buy a complete module.

A: you can use regulator for this with heat sink and you have 6volt constant in output.


text:
Q: Which is best to Use for creating a file from byte[]? I want to create a file using byte[], which one is best.
byte[] content=File.ReadAllBytes(@"C:\ServiceLog.txt");

FileStream stream = new FileStream(@"C:\ServiceLog1.txt", FileMode.Create, FileAccess.ReadWrite);
stream.Write(content, 0, content.Length);
stream.Close();

or
 File.WriteAllBytes(@"C:\12.txt",content);

A: If you have a byte[], you might as well just use WriteAllBytes and let the wrapper method worry about the rest. The Stream approach is useful when you are (oddly enough) streaming the data, meaning: you might not know it all when you start writing. Since you do have the byte[], just us it. However, in the general case, note that byte[]-based APIs may have more impact on memory than Stream-based APIs, especially for large content.

A: All your bytes are already in memory, so as well use:
File.WriteAllBytes(@"C:\12.txt",content);

Stream methods are useful when you are dealing with very large files, and don't want to keep everything in memory.


text:
Q: Unable to bind event to datetimepicker in javascript I'm running django-bootstrap-datepicker-plus==3.0.5.
I'm attempting to bind an event to the datetimepicker so that that on a certain action, an attribute changes. The list of attributes that can be changed are found here:
https://eonasdan.github.io/bootstrap-datetimepicker/
As the page above shows, I should just be able to use the following code to set inline to true (note: I'm able to set this attribute to true on the initialization of the form in forms.py and it works fine).
 $(document).ready(function() {

    $('#datetimepicker').datetimepicker({
    inline: true
    });

 });

Unfortunately, this code doesn't do anything. Should I be using '.datetimepicker' in the code above? Is there anything different about the django version of this datetimepicker that is causing this code not to work?
Not sure if this makes a difference, but the following code does work:
 $('.input-group').on("dp.change", function(e){
   console.log('There was a change to the date');
 });

Thanks for the help!


text:
Q: How to Search and Remove Specific Anchor Tag from Specific Span Class I have the following list. How do I remove specific options according to their text values in the anchor tag and the text value from the group-lable class? Say I want to remove Option 1 from Group 1, how can that be done?
:

All options

    Group1
    Option1
    Option2

    Group2
    Option1
    Option2
    Option3

    Group3
    Option1
    Option2

A: To specifically do what you are asking, you would use this code:
$("span.group-label:contains('Group1')").closest(".item-group").find("a.item:contains('Option1')").remove()

To make it more generic, you will need to understand these selectors.  Basically, I am finding a span with class 'group-label' which contains text "Group1".  From there, I am traversing up to its parent "item-group".  Within that, I am finding an anchor of class "item" which contains the text "Option1" and removing it.
You could of course add whatever logic you needed to this, if you don't specifically want to remove that one item.

A: Using vanilla Javascript:

const labels = [...document.querySelectorAll('.group-label')];
const groupToRemoveFrom = "Group1";
const optionToRemove = "Option1";

const target = [
  ...labels
    .filter(x => x.textContent === groupToRemoveFrom)[0]
    .parentNode.querySelectorAll('a')
  ].filter(x => x.textContent === optionToRemove)[0];

target.parentNode.removeChild(target);

All options

    Group1
    Option1
    Option2

    Group2
    Option1
    Option2
    Option3

    Group3
    Option1
    Option2


text:
Q: Why isn't the foreign key field of a Many-to-One relationship being set on insert? My Spring web application allows users to update "Employee" records to change the fields or add new "Phone" records related to this "Employee" record. However, when the "Employee" record is submitted for update after adding a new "Phone" record, it's throwing a SQL error exception.
The problem is that the "employee_id" foreign key on "Phone" table to the "Employee" table isn't set in the eventual SQL insert statement submitted to the database. However, in the "PhoneEntity" JPA entity object that is referenced by the updated/merged "EmployeeEntity" object, the property associated with the employee_id database field isn't null, it's set to the "EmployeeEnity" Object being updated/merged.
From my understanding of JPA, having the entity property associated with a database field should set it when the insert statement for the entity's record is submitted to the database, but in this case it isn't which is causing this error.
I've tried stepping through with a debugger, and I have verified that the created PhoneEntity object is a member of EmployeeEntity's phones property, and that the same PhoneEntity's employee property is set to the same EmployeeEntity object (with the same object IDs) in a bidirectional relationship.
I've also set the hibernate.show_sql=true to see the SQL statement being submitted to the database and it includes the statement (with the ellipses being more fields):
Hibernate:
    insert
    into
        phone
        (id, employee_id, ...)
    values
        (?, ?, ...)

Which means that it is inserting a new phone for the new PhoneEntity object.
After trying to running this insert statement it gives the SQL error "Column 'employee_id' cannot be null". However like I said before, I've checked with the debugger and the employee property is indeed set to the EmployeeEntity object.
this is a simplified example of what my code looks like:
@Entity
@Table(name = "employee")
public class EmployeeEntity implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    private Integer id;

    @OneToMany(mappedBy="employee", cascade = {CascadeType.PERSIST})
    private Set<PhoneEntity> phones = new HashSet<>();

...
}

@Entity
@Table(name = "phone")
public class PhoneEntity implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    private Integer id;

    @ManyToOne
    @JoinColumn(name = "employee_id", nullable = false)
    private EmployeeEntity employee;

...
}

With tables that have the structure created by the following SQL statements.
CREATE TABLE employee (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
...
);

CREATE TABLE phone (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    employee_id INT NOT NULL,
...
    FOREIGN KEY(employee_id) REFERENCES employee(id)
);

And the following is where it actually submits the updates to the entity manager to make updates to the database.
    public void update(EmployeeDomain employee) {
        EmployeeEntity entity = employeeDomainToEntity.transform(employee)
        getEntityManager().merge(entity);
    }

The EmployeeEntity and PhoneEntity objects are created by converting similar domain objects that were in turn deserialized from a http request. I'd include more of this section of the code but, as I've mentioned, I've already confirmed with my debugger that the actual entity objects being submitted to the merge are already in the form that we expected with the phones fields and employee fields being set correctly, so the end entities should be correct.

A: In the official JPA specification document (version 2.1) in section "3.2.7.1 Merging Detached Entity State" (page 85) we find:

For all entities Y referenced by relationships from X having the cascade element value cascade=MERGE or cascade=ALL, Y is merged recursively as Y'. For all such Y referenced by X, X' is set to reference Y'. (Note that if X is managed then X is the same object as X'.)

This explains that you are lacking cascade=MERGE for the annotation of the phones field.
As proposed in thanh ngo's answer, the aforementioned definition (or: explanation) thus translates to:
@OneToMany(mappedBy="employee", cascade = {CascadeType.PERSIST, CascadeType.MERGE})
private Set<PhoneEntity> phones = new HashSet<>();

Alternatively, you could also make use of cascade=CascadeType.ALL. However, this would also include operations such as CascadeType.REMOVE which might not always be intended.
Hope it helps.

A: I think the problem is that you are using merge.
The cascade type setting for the entity should be:
@OneToMany(mappedBy="employee", cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    private Set<PhoneEntity> phones = new HashSet<>();


text:
Q: Problema para actualizar tabla de BD con JAVA/Struts leyendo excel con POI Amigos de la comunidad, estoy desarrollando un modulo que lee/carga un archivo excel y su contenido lo debe guardar en variables (en el Action) para luego llamar a un SP que realiza un update en la tabla de la base de datos.
El problema es que utilizando POI lee el archivo, genera la lista de datos a enviar al SP, se recibe respuesta del SP indicando correcto, sin embargo al hacer la consulta en la tabla el update no fue realizado.
Si genero la lista con datos en duro y la paso al SP se realiza el update correctamente.
Que puede estar fallando?
PD: por razones de confidencialidad no puedo subir el codigo. Lo intentare tal vez.
Adjunto codigo del Action que lee el archivo excel, y pasa los valores a las variables titulo, codigo y usuario, las cuales concatena en una linea y lista (si viene mas de 1 fila en el excel) la cual envia al SP que actualiza la tabla.

  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,

                             HttpServletResponse response) throws IOException, ServletException, SQLException  {

    Log.info("RealizarUpdateAction inicio Action");

    InputStream is = null;
    Sheet sheet = null;
    int rows = 0;

    RealizarUpdateActionForm f = (RealizarUpdateActionForm) form;
    User    doingUsr= null;
    doingUsr    = (Usuarios) request.getSession().getAttribute("UsuariosSesion");
    String pkuser  = doingUsr.getPkUser();

    FormFile archivo = f.getFileupload();
    ActionErrors errors = new ActionErrors();

    CallableStatement proc    = null;
    String procedure = "";
    String mensaje = "";
    Connection con = Pool.getInstancia().getConnection();

    int estado = 0;

    String titulo       = "";
    String codigo       = "";
    String usuario      = "";
    String lista        = "";
    String linea        = "";

    if (archivo != null && !archivo.toString().equals("")) {

        String extension = archivo.toString().substring(archivo.toString().lastIndexOf("."));
        String tipoArchivo = "excel";

        if (!FormatoArchivo.extArchivo(extension, tipoArchivo)) {
              errors.add("errorarchivo", new ActionError("error.mensaje", "Archivo no es Excel."));
        }else{
            int i = 0;
            try{
                is = archivo.getInputStream();
                Workbook wb = WorkbookFactory.create(is);
                sheet = wb.getSheetAt(0);
                rows = sheet.getPhysicalNumberOfRows();

                for (i = 1; i < rows; i++){
                    org.apache.poi.ss.usermodel.Row row = sheet.getRow(i);
                    Cell cell_titulo          = row.getCell(0);
                    Cell cell_codigo           = row.getCell(1);
                    Cell cell_usuario        = row.getCell(2);

                    cell_titulo.setCellType(Cell.CELL_TYPE_STRING);
                    cell_codigo.setCellType(Cell.CELL_TYPE_STRING);
                    cell_usuario.setCellType(Cell.CELL_TYPE_STRING);

                    titulo           = cell_titulo.getStringCellValue();
                    codigo          = cell_codigo.getStringCellValue();
                    usuario       = cell_usuario.getStringCellValue();

                    if(i > 0){
                        linea = titulo+","+codigo+","+usuario;
                    }
                    if(i == 1){
                        lista = linea;
                    }else if (i > 1){
                        lista = lista+";"+linea;
                    }
                }
            }catch(Exception e){
                //Log.info("Ocurrio la siguiente excepcion : " + e.getMessage());
                if(i==1){
                    Log.info("RealizarUpdateAction error: Archivo no contiene datos para procesar.");
                    return mapping.findForward("error");
                }else{
                    Log.info("RealizarUpdateAction error "+e.getMessage()); //arroja un nullPointerException dado que llega al ultimo registro en el excel y no tiene datos
                }
            }

            // Llamado al SP para procesar los datos
            try{
                procedure = "{call SP_UPD_TABLATITULOS (?,?,?,?)}";
                proc = con.prepareCall(procedure);
                proc.registerOutParameter(3, Types.INTEGER);
                proc.registerOutParameter(4, Types.VARCHAR);
                proc.setString(1,lista);
                proc.setInt(2,Integer.valueOf(pkuser));
                proc.executeUpdate();
                estado   = proc.getInt(3);
                mensaje  = proc.getString(4);
            }catch(SQLException e){
                Log.info("RealizarUpdateAction.cargarArchivo.proc Exception =  "+e.getMessage());
            }

            if(estado == 0){
                request.setAttribute("DATOSUPD","TRUE");
                con.close();
                return mapping.findForward("ok");
            }else if(estado == 1){
                request.setAttribute("DATOSUPD","FALSE");
                request.setAttribute("MENSAJE",mensaje);
                con.close();
                return mapping.findForward("ok");
            }
        }
    }
    return mapping.findForward("ok");
}


text:
Q: Setting header in Web.HttpClient to contain quotations I'm trying to make a POST request using Web.HttpClient (JavaScript)
var uri = new Windows.Foundation.Uri(baseURL);
var hc = new Web.HttpClient();
var authHeader = "OAuth authSig=\"dsadsASD\", timestamp=\"123132\"";
var request = new Web.HttpRequestMessage(Web.HttpMethod.post, uri);

request.headers.insert("Authorization", authHeader);

hc.sendRequestAsync(request);

However this is setting the Authorization header to:
authSig=dsadsASD, timestamp=123132

instead of:
authSig="dsadsASD", timestamp="123132"

Any thoughts why? or how I can get around this?

A: If you set the authorization this way:
var WebHttp = Windows.Web.Http; // just to fit in StackOverflow :)
var authHdr = new WebHttp.Headers.HttpCredentialsHeaderValue("OAuth",
                   authHeader);

request.headers.authorization = authHdr;

The quotes are not stripped from the value.
Depending on what you're trying to do, you may want to take a look at the WebAuthenticationBroker sample.


text:
Q: Completion block/callback on FetchRequest completion I have a FetchRequest in my model class named ContentManager.  It fetches quite a lot of data, so the screen is blank until it's completion. In the ViewController that displays the fetched results, I would like to show a loading indicator, so I would like to get a callback when the FetchRequest has completed and pass that to the ViewController to stop the loading indicator. Is this possible?
Here is the FetchRequest from the ContentManager class:
- (NSArray*)recipesForMagazine
{
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Recipe" inManagedObjectContext:managedObjectContext];
    [request setEntity:entity];

    NSString* path = [[NSBundle mainBundle] pathForResource:@"magazine_recipe_guids" ofType:@"plist"];
    NSArray* recipeGuids = [NSArray arrayWithContentsOfFile:path];

    NSPredicate* predicate = [NSPredicate predicateWithFormat:@"guid IN %@",recipeGuids];
    [request setPredicate:predicate];

    NSSortDescriptor* sort = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)];
    [request setSortDescriptors:[NSArray arrayWithObject:sort]];

    [sort release];

    NSError* error = nil;
    NSArray* fetchResults = [managedObjectContext executeFetchRequest:request error:&error];
    [request release];

    return fetchResults;
}

Here I set it up in the ViewController
self.magazineRecipes = [[ContentManager defaultManager] recipesForMagazine];
I want to set up the fetchrequest method like this:
- (NSArray*)recipesForMagazine:(void (^)(BOOL success))block or something, so in the viewcontroller I can call it like this
self.magazineRecipes = [[CTContentManager defaultManager] recipesForMagazine:^(BOOL success) {
    if (success) {
        //stop activity indicator view
    }
}];

I don't know if I'm at all in the right way of thinking, thanks for your help in advance!

A: I would make the viewController a delegate of the ContentManager class. So in the ContentManager.h I would do something like:
    @protocol ContentManagerDelegate()
      -(void) didFetchResults:(NSArray *) results;
      -(void) didResultsFail: (NSError *) error;
    @end

    @interface ContentManager : <SuperClass Name>
    -(id) initWithDelegate: (id<ContentManagerDelegate>) delegate;
    @property (nonatomic, strong) id<ContentManagerDelegate> delegate;
    @end

and in the implementation:
   -(id) initWithDelegate: (id<ContentManagerDelegate>) delegate
    {
        self = [super init];
        if(self)
        {
           _delegate = delegate;
         }
        return self;
    }

and in your recipesForMagazine method you can use the delegate [_delegate didFetchResults: fetchResults], you can implement a method to pass errors to the delegate if you want as well. In your ViewController.h do @interface ViewController.h : UIViewController <ContentManagerDelegate> and in the implementation you should be able to implement the didFetchResults: method that will give you the results and in that method you can stop the activity indicator from animating.


text:
Q: Sending array of Json data along with image file with ajax in asp.net mvc I am trying to send array of json data and image file with ajax but i can only get image file and not getting json data and i can see json data sent properly in fiddler though.In action method, collection parameter for json data  says count=0. How can i get array of json data?
@using (Ajax.BeginForm("GetData", "Home", new AjaxOptions
{
    InsertionMode = InsertionMode.Replace
}, new { @id = "form_", enctype = "multipart/form-data" }))
{
    @Html.TextBox("imagefile", null, new { @type="file"})
    @Html.Hidden("formdata", null, new { @data_formdatajson = "" }))
    @Html.TextBox("submit", null, new { @id = "button", @value = "upload", @type = "submit"})
}

    var DataClass = {
            data1: data1value,
            data2: data2value
        }

dataArray=[];
dataArray.push(DataClass);
dataArrayJson = JSON.stringify(dataArray);
$('#formdata').data("formdatajson ", dataArrayJson);

           $('#form_').on('submit', function (e) {
                var dataArray_ = $('#formdata ').data("formdatajson");
                var formdata = new FormData($(this)[0]);
                formdata.append('formdata', dataArray_);
                        $.ajax({
                            url: '/GetData/Home/',
                            type: 'POST',
                            data: formdata,
                            processData: false,
                            contentType: false,
                            dataType: "json",
                            success: function (data) {
                            },
                            error: function () { },
                        });
                    });
public class DataClass
{
     public string data1 { get; set; }
        public string data2 { get; set; }
}

        [HttpPost]
        public JsonResult GetData(IEnumerable<DataClass> formdata, HttpPostedFileBase imagefile)
        {
                    return Json(new { success = true },  JsonRequestBehavior.AllowGet);
        }

A: i fixed the problem...I dont know why but Asp.Mvc gets json data and add an empty element to outside of json array for no reason.I used request.form to get json and i eliminated this additional data by using substring.Now it works.


text:
Q: Cudamemcpy function usage How will the cudaMemcpy function work in this case?
I have declared a matrix like this
float imagen[par->N][par->M];

and I want to copy it to the cuda device so I did this
float *imagen_cuda;

int tam_cuda=par->M*par->N*sizeof(float);

cudaMalloc((void**) &imagen_cuda,tam_cuda);
cudaMemcpy(imagen_cuda,imagen,tam_cuda,cudaMemcpyHostToDevice);

Will this copy the 2d array into a 1d array fine?
And how can I copy to another 2d array? can I change this and will it work?
float **imagen_cuda;

A: It's not trivial to handle a doubly-subscripted C array when copying data between host and device.  For the most part, cudaMemcpy (including cudaMemcpy2D) expect an ordinary pointer for source and destination, not a pointer-to-pointer.
The simplest approach (I think) is to "flatten" the 2D arrays, both on host and device, and use index arithmetic to simulate 2D coordinates:
float imagen[par->N][par->M];
float *myimagen = &(imagen[0][0]);
float myval = myimagen[(rowsize*row) + col];

You can then use ordinary cudaMemcpy operations to handle the transfers (using the myimagen pointer):
float *d_myimagen;
cudaMalloc((void **)&d_myimagen, (par->N * par->M)*sizeof(float));
cudaMemcpy(d_myimagen, myimagen, (par->N * par->M)*sizeof(float), cudaMemcpyHostToDevice);

If you really want to handle dynamically sized (i.e. not known at compile time) doubly-subscripted arrays, you can review this question/answer.


text:
Q: objective-c , Finding objects from array I have an array that contains some objects;
example:
 NSArray*arr=[NSMutableArray arrayWithObjects:@1,@5,@7,@6 nil];
How I could find, for example if the array contains the number 1 and 7 without creating a loop.
Is there such a function?
For example returns a Boolean value or something?

A: Use indexOfObject to find if an element is present in your array or not :
NSNumber *num=[NSNumber numberWithInteger:7];
NSInteger anIndex=[myArray indexOfObject:num];
if(NSNotFound == anIndex) {
    NSLog(@"not found");
}

Hope this helps.

A: Sure thing!
You can use this method

*

*(BOOL)containsObject:(ObjectType)anObject;

or somethings else:

*

*(NSUInteger)indexOfObject:(ObjectType)anObject;

*(NSUInteger)indexOfObject:(ObjectType)anObject inRange:(NSRange)range;

Have fun.


text:
Q: Как копировать файлы с заменой в Linux тем же методом, что и в Windows? (без учёта регистра) У меня есть Morrowind и куча модов к нему. Я хочу эти моды установить. Как вам известно, Morrowind писался под винду и моды к нему соответственно тоже, но я использую кроссплатформенный движок OpenMW, что позволяет нативно запускать игру в линуксе.
Так вот в чём моя проблема: установка модов обычно сводится к распаковке файлов из архива мода в директорию игры с заменой. Беда в том, что если оригинальная папка называется "Sound", а в архиве находится папка "sound", то никакой замены не произойдёт (аналогично и с файлами)! У меня просто будет 2 разных папки/файла, потому что линукс чувствителен к регистру. В итоге мод установится криво (а таких модов очень много и вручную я всё проследить не могу).

A: специализированного средства для исправления подобной эксклюзивной «кривизны», конечно, нет.
но такое средство несложно написать на любом подходящем языке программирования, или даже обойтись оболочкой и утилитами из gnu/coreutils.

например, у нас есть «базовый» каталог 1:
$ tree 1
1
└── Sound
    ├── File
    └── File2

и есть распакованный (или любым другим образом полученный) каталог 2, в котором есть некоторые файлы/каталоги, отличающиеся от аналогичных файлов/каталогов из каталога 1 регистром имени:
$ tree 2
2
└── sound
    ├── file
    └── file3

фактически, нам надо привести имена таких файлов/каталогов к тому же регистру, что и в каталоге 1. т.е., sound/file переименовать в sound/File и sound переименовать в Sound.

*

*сохраним имя «базового» каталога в переменной base, а имя «переименовываемого» каталога — в ren:
$ base=1 ren=2

*составим список файлов/каталогов, совпадающих при преобразовании их в нижний регистр (с таким же успехом можно было и в верхний):
$ comm -1 -2 \
<(cd "$base"; find -mindepth 1 | tr '[:upper:]' '[:lower:]' | sort) \
<(cd "$ren"; find -mindepth 1 | tr '[:upper:]' '[:lower:]' | sort)

получаем:
./sound
./sound/file

*в цикле будем читать имена, находить исходные (без преобразования регистра) имена, сравнивать их и, если не совпадают, переименовывать и сообщать об этом:
$ comm -1 -2 \
<(cd "$base"; find -mindepth 1 | tr '[:upper:]' '[:lower:]' | sort) \
<(cd "$ren"; find -mindepth 1 | tr '[:upper:]' '[:lower:]' | sort) | \
while read n; do \
 c1=$(cd "$base"; find -iwholename "$n"); \
 c2=$(cd "$ren"; find -iwholename "$n"); \
 if [[ "$c1" != "$c2" ]]; then \
  echo "переименовываем $ren/$c2 в $ren/$c1"; \
  mv "$ren/$c2" "$ren/$c1"; \
 fi; \
done

получаем:
переименовываем 2/./sound в 2/./Sound
переименовываем 2/./Sound/file в 2/./Sound/File

а внутри каталога 2 — имена в нужном регистре:
$ tree 2
2
└── Sound
    ├── File
    └── file3

итоговый скрипт:
#!/bin/bash
base=$1
ren=$2
comm -1 -2 \
<(cd "$base"; find -mindepth 1 | tr '[:upper:]' '[:lower:]' | sort) \
<(cd "$ren"; find -mindepth 1 | tr '[:upper:]' '[:lower:]' | sort) | \
while read n; do
 c1=$(cd "$base"; find -iwholename "$n")
 c2=$(cd "$ren"; find -iwholename "$n")
 if [[ "$c1" != "$c2" ]]; then
  echo "переименовываем $ren/$c2 в $ren/$c1"
  mv "$ren/$c2" "$ren/$c1"
 fi
done

принимает два параметра — «базовый» и «переименовываемый» каталоги.


text:
Q: PHP not allowing ACCESS update on certain columns I am trying to update records in my legacy access system via php, but on certain columns it isn't working. For example the below works :
$query = "UPDATE Valuations SET SalesParticulars = '" . $salesparticulars . "',
 Company = '" . $company . "' WHERE Ref=" . $ref;

If I change "Company" to "Name" it doesn't work, even though name is just a column in the database exactly the same as Company.
Basically I can update "Company" but not "Name", even though they are both the same data types
I get this exception, how can I catch it?

Fatal error: Uncaught exception 'com_exception' with message 'Source: Microsoft Access Database EngineDescription: Syntax error in UPDATE statement.' in

This is my full code
// Create an instance of the ADO connection object
$conn = new COM ("ADODB.Connection") or die("Cannot start ADO");

// Define the connection string and specify the database driver
$connStr = "PROVIDER=Microsoft.Ace.OLEDB.12.0;Data Source=".realpath("HS_BE.accdb").";";

// Open the connection to the database
$conn->open($connStr);
$name= "gareth";
// Declare the SQL statement that will query the database
$query = "UPDATE Valuations SET SalesParticulars = '" . $salesparticulars . "',
 Name = '" . $name . "'
 WHERE Ref=" . $ref;

echo $query;

// Execute the SQL statement and return records
$rs = $conn->execute($query);

A: That's because Name is a reserved word in Access SQL.
You can wrap it in brackets like this:
$query = "UPDATE Valuations SET SalesParticulars = '" . $salesparticulars . "',
 [Name] = '" . $name . "' WHERE Ref=" . $ref;


text:
Q: Sails Query Returns Nothing After count() Query The following returns empty results when executed. It's fine without the Count query, but even still, the correct values are returned but the response is always empty. Am I having a race condition issue?
module.exports = {
getSites: function (req, res) {
    var sites = [];
    Site.find({ company: req.session.companyID }).populate('locations').exec(function afterFind(err, results) {

        for (index in results) {

            var siteObj = {};

            siteObj = results[index];

            sails.models['site_users__user_sites'].count({ user_sites: results[index].id }).exec(function found(err, counted) {
                if (err) {
                    sails.log.error(err);
                }
                sails.log.debug(counted); // Prints correct number
                siteObj['user_count'] = counted;
                sails.log.debug(siteObj['user_count']); // Shows value is present
                sites.push(siteObj);
            });
        }
    });

    sails.log.debug(sites); // Nothing
    return res.json(sites); // Nothing
},}

Update:
module.exports = {
getSites: function (req, res) {
    var sites = [];

    Site.find({ company: req.session.companyID }).populate('locations').exec(function afterFind(err, results) {
        var completedResults = 0;

        for (index in results) {
            sails.log.debug(results);
            var siteObj = {};

            siteObj = results[index];

            sails.models['site_users__user_sites'].count({ user_sites: results[index].id }).exec(function found(err, counted) {
                if (err) {
                    sails.log.error(err);
                }
                siteObj['user_count'] = counted;
                sites.push(siteObj);

                completedResults++;
                if(completedResults === results.length) {
                    sails.log.debug(sites);
                    res.json(sites);
                }
            });
        }
    });
},
}

After updating to the above, logging "results" produces all the correct records. However, when returning "sites", the two entries returned are duplicates.
Update 2
I have a feeling that the async query is not completing before the next item in the for loop is being accessed, thus assigning the values to the wrong object.
Update 3
Provided logs for help.
Here is the log for the "results"
[ { locations: [],
company: 1,
name: 'N',
id: 1,
createdAt: '2017-06-06T10:07:25.000Z',
updatedAt: '2017-06-06T10:07:26.000Z' },
{ locations: [],
company: 1,
name: 'W',
id: 2,
createdAt: '2017-06-06T11:08:08.000Z',
updatedAt: '2017-06-06T11:08:08.000Z' } ]

This is the log for "sites"
[ { locations: [],
company: 1,
name: 'W',
id: 2,
createdAt: '2017-06-06T11:08:08.000Z',
updatedAt: '2017-06-06T11:08:08.000Z',
user_count : 1 },
{ locations: [],
company: 1,
name: 'W',
id: 2,
createdAt: '2017-06-06T11:08:08.000Z',
updatedAt: '2017-06-06T11:08:08.000Z',
user_count : 1 } ]

A: It's because
sails.log.debug(sites); // Nothing
return res.json(sites); // Nothing

Executes before
sails.models['site_users__user_sites'].count({ user_sites: results[index].id }).exec(function found(err, counted) {
    if (err) {
        sails.log.error(err);
    }
    sails.log.debug(counted); // Prints correct number
    siteObj['user_count'] = counted;
    sails.log.debug(siteObj['user_count']); // Shows value is present
    sites.push(siteObj);
});

To fix it, you need to call sails.log.debug and res.json once the async exec function has completed for all results. Like this:
module.exports = {
    getSites: function (req, res) {
        const sites = [];
        Site.find({ company: req.session.companyID }).populate('locations').exec(function afterFind(err, results) {

            let completedResults = 0;

            for (index in results) {

                const siteObj = results[index];

                sails.models['site_users__user_sites'].count({ user_sites: results[index].id }).exec(function found(err, counted) {
                    if (err) {
                        sails.log.error(err);
                    }
                    sails.log.debug(counted); // Prints correct number
                    siteObj['user_count'] = counted;
                    sails.log.debug(siteObj['user_count']); // Shows value is present
                    sites.push(siteObj);

                    completedResults++;
                    if(completedResults === results.length) {
                        sails.log.debug(sites);
                        res.json(sites);
                    }
                });
            }
        });

    }
}

A: find,count  and .exec are asynchronous in nature
You  are returning  the sites variable  , which is initally  an empty array , even before your afterFind function is computed , Not to mention the second exec after count .


text:
Q: Is this the correct logic behind the rule of three? If we define our very own destructor, it means that there is some dynamically allocated variable. And therefore, we need to define the copy constructor and copy assignment operator as well because we definitely are dealing with a pointer somewhere.
Is this the main logic behind the rule?

A: Pretty much. In C++11 this becomes the rule of five, as move semantics is disabled by declaring a destructor or copy constructor/assignment operator. But it is better to follow the rule of zero, i.e. use RAII to perform automatic release of resources via smart pointers etc.
Note that you may not need to deal with a pointer directly to need a custom destructor, but with a resource that is not managed via RAII, e.g. a file open via fopen for which you have to call fclose, or some connection to a database etc. So the rule is to use RAII so that destructors take care of the resources that are acquired.


text:
Q: How to show FCM push notifications when app is killed or in background react native? I am using react-native-FCM and trying to show notifications from the rest client, its working fine when the app is in the foreground and trigger the screen where I want to show the notifications data but when the app is in the background or killed it does not trigger the notifications screen. So, I am wondering how to trigger app notifications screen when the app is killed or in the background.Thanks in advance.Any help would be appreciated.Here is my code:
homepage.js
    import React, { Component } from 'react';
    import {
      Platform,
      StyleSheet,
      Text,
      View
    } from 'react-native';

    import FCM,{FCMEvent,RemoteNotificationResult,WillPresentNotificationResult,NotificationType,NotificationActionType,NotificationActionOption,NotificationCategoryOption} from "react-native-fcm";

    let data=[];
    FCM.on(FCMEvent.Notification, async(notify)=>{
      if(notify.local_notification){
        //this is a local notification
      }
      if(notify.opened_from_tray){

            navigation.navigate('TargetScreenPage')

      }
      if(Platform.OS==='android'){
        switch(notify.NotificationType){
          case NotificationType.Remote:
          notify.finish(
            RemoteNotificationResult.NewData
          )
          break;
          case NotificationType.NotificationResponse:
          notify.finish();
          break;
          case NotificationType.WillPresent:
          notify.finish(WillPresentNotificationResult.All)
          break;
        }
      }
    });
    FCM.on(FCMEvent.RefreshToken,(token)=>{
      console.log(token);
    })

    export default class HomePage extends Component {

      constructor(props){
        super(props);
        this.state={
          totalTarget: null,
          targetAchieved:null,
          message:null,
          notificationsType:null,
          extraMessage:null,
          token:null
        }
      }

      componentDidMount () {
         const { navigate } = this.props.navigation;
        FCM.requestPermissions().then(()=>console.log('granted')).catch(()=>console.log('notification permission'))

        FCM.getFCMToken().then(token=>{
          console.log(token)
          this.setState({token:token})
        });

        this.notificationListener = FCM.on(FCMEvent.Notification, async(notify)=>{
          this.setState({
            totalTarget:notify.totalTarget,
            targetAchieved:notify.targetAchieved,
            message:notify.message,
            notificationsType:notify.notificationsType,
            extraMessage:notify.extraMessage
          })
      navigate("TargetScreenPage",{message:this.state.message,extraMessage:this.state.extraMessage})
        })

        FCM.getInitialNotification().then(notify=>{
          console.log("notification-----"+ JSON.stringify(notify))

        })
      }

      componentWillUnmount(){
        this.notificationListener.remove();
      }

      render() {
        return (
          <View style={styles.container}>
           {/* <Text style={styles.instructions}>
              {this.state.token}
            </Text> */}
             <Text style={styles.instructions}>
              {this.state.totalTarget}
            </Text>
            <Text style={styles.instructions}>
              {this.state.targetAchieved}
            </Text>

             <Text style={styles.instructions}>
              {this.state.message}
            </Text>
            <Text style={styles.instructions}>
              {this.state.notificationsType}
            </Text>
         <Text style={styles.instructions}>
              {this.state.extraMessage}
            </Text>

          </View>
        );
      }
    }
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
      },
      welcome: {
        fontSize: 40,
        textAlign: 'center',
        margin: 10,
      },
      instructions: {
        fontSize:40,
        textAlign: 'center',
        color: '#333333',
        marginBottom: 5,
        flexDirection:'row'
      },
    });

and TargetScreen.js
import React, { Component } from 'react';
import {ImageBackground,
  Platform,StyleSheet,BackHandler,Image,TouchableOpacity,Text,StatusBar,View} from 'react-native';
import { Header,Right} from 'native-base';

const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' +
    'Cmd+D or shake for dev menu',
  android: 'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

export default class TargetScreen extends Component {

    handleCrossButtonClick() {
        this.props.navigation.goBack(null);
        return true;
    }

  render() {
    const { params } = this.props.navigation.state;
    return (
    <View style={{flex:1,backgroundColor: '#fff'}}>
    <StatusBar hidden = {true} />
    <Header style={{ backgroundColor: "#fff" ,justifyContent:'center',alignItems:'center'}}>
        <Image style={{height:45,width:90,resizeMode: "stretch",marginLeft:95}} source={require('./images/salesLineLogo.jpg')} />
        <Right>
        <TouchableOpacity onPress={()=>this.handleCrossButtonClick()}>
        <Image style={{height:25,width:25,resizeMode: "stretch"}} source={require('./images/cross.png')}/>
        </TouchableOpacity></Right>
     </Header>
     <View style={{flex:0.5,justifyContent:'center',alignItems: 'center'}}>
    <ImageBackground source={require('./images/up-arrow.png')} style={{ resizeMode: "stretch",height: 95, width: 95,justifyContent:'center',alignItems:'center' }} >
    <Text style={{fontSize:20}}>8</Text></ImageBackground>
    <Text style={{fontSize:20,marginTop:25}}>{params.message}</Text>
    </View>
    <View style={{flex:0.5,justifyContent:'center',alignItems:'center'}}>
    <ImageBackground source={require('./images/up-arrow.png')} style={{ resizeMode: "stretch",height: 95, width: 95,justifyContent:'center',alignItems:'center'}} >
    <Text style={{fontSize:20}}>8</Text></ImageBackground>
    <Text style={{fontSize:20,marginTop:25}}>{params.extraMessage}</Text>
    </View></View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});


text:
Q: Correct Preposition: the risk-adjusted cost (the cost is adjusted by, in, for, with or according to risk?) I cannot correctly understand the Title of academic papers such as "the risk-adjusted cost".
Here, the cost is adjusted by, in, for, with or according to risk?
Which preposition is more correct or comes first to the mind of a native English speaker?
Thank you in advance.


text:
Q: Triggers and entry/exit actions for IsDefaulted and IsKeyboardFocused button storyboard What's the proper way to trigger a defaulted/focused button glow effect on a custom button template in WPF? This would be similar in behavior to Windows 7's button glow and Windows 8/10's thick outline for focused and defaulted buttons.
(Note: vanilla WPF projects in Windows 7 do not exhibit the focused/defaulted button glow that is present in the rest of the operating system. Oh, Microsoft...)
I tried this:
<MultiTrigger>
    <MultiTrigger.Conditions>
        <Condition Property="IsDefaulted" Value="False" />
        <Condition Property="IsKeyboardFocused" Value="False" />
    </MultiTrigger.Conditions>
    <MultiTrigger.EnterActions>
        <RemoveStoryboard BeginStoryboardName="IsDefaultedStoryboard" />
    </MultiTrigger.EnterActions>
    <MultiTrigger.ExitActions>
        <BeginStoryboard x:Name="IsDefaultedStoryboard" Storyboard="{StaticResource IsDefaultedStoryboard}" />
    </MultiTrigger.ExitActions>
</MultiTrigger>

The behavior seems to be as expected, but it produces a lot of warnings -- one warning per button as they're loaded on-screen.

System.Windows.Media.Animation Warning: 6 : Unable to perform action because the specified Storyboard was never applied to this object for interactive control.; Action='Remove'; Storyboard='System.Windows.Media.Animation.Storyboard'; Storyboard.HashCode='16952812'; Storyboard.Type='System.Windows.Media.Animation.Storyboard'; TargetElement='System.Windows.Controls.Button: Save'; TargetElement.HashCode='37829947'; TargetElement.Type='System.Windows.Controls.Button'

My slightly more verbose solution still produces warnings -- although only upon losing focus -- and does not work as expected: when tabbing from the default button to another button, the default button keeps glowing.
<Trigger Property="IsDefaulted" Value="True">
    <Trigger.EnterActions>
        <BeginStoryboard x:Name="IsDefaultedStoryboard" Storyboard="{StaticResource IsDefaultedStoryboard}" />
    </Trigger.EnterActions>
    <Trigger.ExitActions>
        <RemoveStoryboard BeginStoryboardName="IsDefaultedStoryboard" />
    </Trigger.ExitActions>
</Trigger>
<Trigger Property="IsKeyboardFocused" Value="True">
    <Trigger.EnterActions>
        <BeginStoryboard x:Name="IsFocusedStoryboard" Storyboard="{StaticResource IsDefaultedStoryboard}" />
    </Trigger.EnterActions>
    <Trigger.ExitActions>
        <RemoveStoryboard BeginStoryboardName="IsFocusedStoryboard" />
    </Trigger.ExitActions>
</Trigger>

Maybe it's acceptable to use solution #1 and just ignore the warning, but I'd rather not. What's the better way to do this?
The storyboard is nothing exciting:
<Storyboard x:Key="IsDefaultedStoryboard" RepeatBehavior="Forever">
    <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="IsDefaulted" Storyboard.TargetProperty="(UIElement.Opacity)">
        <EasingDoubleKeyFrame KeyTime="0" Value="0" />
        <EasingDoubleKeyFrame KeyTime="0:0:0.8" Value="0" />
        <EasingDoubleKeyFrame KeyTime="0:0:2.0" Value="1" />
        <EasingDoubleKeyFrame KeyTime="0:0:4.0" Value="0" />
    </DoubleAnimationUsingKeyFrames>
</Storyboard>

A: I ended up making an identical copy of the storyboard and applied it through two separate triggers, i.e.
<Trigger Property="IsDefaulted" Value="True">
    <Setter TargetName="buttonStroke" Property="Opacity" Value=".5" />
    <Trigger.EnterActions>
        <BeginStoryboard x:Name="IsDefaultedStoryboard" Storyboard="{StaticResource IsDefaultedStoryboard}" />
    </Trigger.EnterActions>
    <Trigger.ExitActions>
        <RemoveStoryboard BeginStoryboardName="IsDefaultedStoryboard" />
    </Trigger.ExitActions>
</Trigger>
<Trigger Property="IsKeyboardFocused" Value="True">
    <Setter TargetName="buttonStroke" Property="Opacity" Value=".5" />
    <Trigger.EnterActions>
        <BeginStoryboard x:Name="IsKeyboardFocusedStoryboard" Storyboard="{StaticResource IsKeyboardFocusedStoryboard}" />
    </Trigger.EnterActions>
    <Trigger.ExitActions>
        <RemoveStoryboard BeginStoryboardName="IsKeyboardFocusedStoryboard" />
    </Trigger.ExitActions>
</Trigger>

I don't like the duplication, but it produces no warnings and works as expected.


text:
Q: no sdk path for flutter flutter doesn't run the app and asked for put --stracktrac or --debug and also didn't work and when open project structure i found this and when choose src/flutter as flutter sdk path it tell me not valid
please what should i do
the error in project structure
the output when run
flutter sdk path

A: delete completely android studio + .config in C:\ and reinstall android studio and let that to download requirements .it probably should solve your problem.