text:
Q: Using a separate thread will increase the performance when you have to return value to the caller? I have a method and in that method, I'm looping a list of Strings with fixed 3 elements in it. Each element is a command that I need to send to a plugin and receive a reference number from the plugin. But between each call, I need to wait about 30 seconds to make sure that the plugin will execute the commands and send a response. I need to have all 3 reference numbers before I return a list of strings from this method. I want to make each plugin calls in a separate thread (CompletableFuture maybe?). But, since I will return all ref.nrs to the caller, does that make it useless to use a separate thread for this job?
Here is the method I call inside the loop from the first method:
private String sendToPluginAndGetReference(String command, InputStream in, PrintStream out) {
     CompletableFuture<String> future =
             CompletableFuture.completedFuture(command).thenApplyAsync(reference -> {
                 try {
                     TimeUnit.SECONDS.sleep(30);
                     reference = sendCommandToPlugin(in, out, command);
                     return reference;
                 } catch (InterruptedException e) {
                     LOGGER.error(e.getMessage(), e);
                     return null;
                 }});
     try {
         return future.get();
     } catch (InterruptedException | ExecutionException e) {
         LOGGER.error(e.getMessage(), e);
         return null;
     }
 }


text:
Q: Sync App-Backend user table with wordpress login I programmed a Backend for an app. In the Backend is of course the login/registration endpoint.
The problem is that my client had the new idea of synchronizing his Wordpress Blog with the app. And now he wants that when an user registers himself in the App, then he can log in the Wordpress and when an user registers himself in the Wordpress Blog, he can log in the App.
My problem is that I'm not specialized either in Wordpress nor in PHP. I was watching the wp-login.php file, but didn't find a good result.
I'm thinking of using the Backend Endpoint with Wordpress, I can guess that Wordpress could work as a client. Then I could use the same Login-Backend-Function with the App and with Wordpress and it should work.
I was reading this kind of post in Internet, but is not that way, I don't want to register an user in Wordpress from the app, but the other way, I would like to register an user in the App or in Wordpress and log him in the App or Wordpress, but using the Django Endpoints of the Backend.
I did't think that it would be so complicated.
Maybe someone already tried something like that and can say me how I should program it.

A: I continued searching in Internet and found this post.
Then, I easy changed the do_register_user function of the second page of the post the way I needed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to copy one column from one spreadsheet to another I am trying to copy the data from column A in spreadsheet called "Dividends" and paste in spreadsheet called "Draft" but there`s an error. My code looks like that:
Sub copy_2()
  Sheets("Dividends").Range("A").Copy
  Sheets("Draft").Activate
  Range("A1").Select
  ActiveSheet.Paste
  Application.CutCopyMode = False
End Sub

A: Sub copy_2()
  Sheets("Dividends").Range("A:A").Copy
  Sheets("Draft").Paste
  Application.CutCopyMode = False
End Sub

Removing references to Active as much as possible helps eliminate confusion.

A: You don't need to copy/paste either - you can just set the ranges equal.
Sub copy()
Dim lastRow As Integer
'This will let us know the last used row in column A
lastRow = Sheets("Dividends").Cells(1, 1).End(xlDown).row
Sheets("Draft").Range(Sheets("Draft").Cells(1, 1), Sheets("Draft").Cells(lastRow, 1)).Value = Sheets("Dividends").Range(Sheets("Dividends").Cells(1, 1), Sheets("Dividends").Cells(lastRow, 1)).Value
End Sub

Or you can copy/paste:
Sub copy()
Dim lastRow As Integer
'This will let us know the last used row in column A
lastRow = Sheets("Dividends").Cells(1, 1).End(xlDown).row
Sheets("Dividends").Range(Sheets("Dividends").Cells(1, 1), Sheets("Dividends").Cells(lastRow, 1)).copy _
    Destination:=Sheets("Draft").Range(Sheets("Draft").Cells(1, 1), Sheets("Draft").Cells(lastRow, 1))

Application.CutCopyMode = False

End Sub

Note: If you have a gap anywhere in Column A, the lastRow integer might be off.  If you want to copy all the way down to the last used row, replace the "lastRow = " with this:
lastRow = Sheets("Dividends").UsedRange.Rows.Count

A: This works,
 Sheets("Dividends").Range("A:A").Copy Sheets("Draft").Range("A1")


text:
Q: Need help on setting up matlab to access external c++ compiler I am currently following SIFTGPU matlab tutorial, and is stuck at this very early section:

SIFTGPU is coded in C++ and must be saved as a .mex (matlab external)
  file before it can be called from Matlab. In order to create the .mex
  file, you must make sure that Matlab is set up to access an external
  C++ compiler by entering
mex –setup
into the Matlab command window and following the on-screen
  instructions.

Because I didn't have Visual C++ express 2010 and Windows SDK, I followed the instruction at http://www.mathworks.com/support/compilers/R2011a/win64.html
The installation of both software are fine, however, when it comes to matlab:
>> mex -setup

Welcome to mex -setup.  This utility will help you set up
a default compiler.  For a list of supported compilers, see
http://www.mathworks.com/support/compilers/R2011a/win64.html

Please choose your compiler for building MEX-files:

Would you like mex to locate installed compilers [y]/n? y

Select a compiler:
[1] Microsoft Visual C++ 2010 Express in D:\VS2010

[0] None

Compiler: 1

Please verify your choices:

Compiler: Microsoft Visual C++ 2010 Express
Location: D:\VS2010

Are these correct [y]/n? y

*****************************************************************************
  Error: Microsoft Visual C++ 2010 Express requires the Microsoft Windows
         Software Development Kit (SDK), but the SDK cannot be found.
         For more information about the required SDK, see:
         http://www.mathworks.com/support/compilers/R2011a/win64.html
*****************************************************************************

??? Error using ==> mex at 208
Unable to complete successfully.

I am not sure where to go next. Could somebody tell me what do I need to do next after installing VC++ Express 2010 and Windows SDK?

A: Do not install Visual Studio Express. Install the Windows SDK - it comes with a compiler, and that setup works with MATLAB. Visual Studio did not work for me either because of some problems with batch files you need to run to setup the environment.
Edit This is the mex configuration screen after you install the SDK:

mex -setup
Welcome to mex -setup.  This utility will help you set up
  a default compiler.  For a list of supported compilers, see
http://www.mathworks.com/support/compilers/R2012a/win64.html
Please choose your compiler for building MEX-files:
Would you like mex to locate installed compilers [y]/n? y
Select a compiler:
[1] Microsoft Software Development Kit (SDK) 7.1 in C:\Program Files (x86)\Microsoft Visual Studio 10.0
[0] None
Compiler:


text:
Q: Moving avg 3 months Vs previous n months and not inclusive of the first 3? Some data
df <- data.frame(
  dates = seq(as.Date('2018-01-01'), as.Date('2018-12-01'), by = "month"),
  user_id = c("a","b","c","a","b","c","a","b","c","a","b","c"),
  somenum = 1:12
)

 df
        dates user_id somenum
1  2018-01-01       a       1
2  2018-02-01       b       2
3  2018-03-01       c       3
4  2018-04-01       a       4
5  2018-05-01       b       5
6  2018-06-01       c       6
7  2018-07-01       a       7
8  2018-08-01       b       8
9  2018-09-01       c       9
10 2018-10-01       a      10
11 2018-11-01       b      11
12 2018-12-01       c      12

Using the answers e.g. here, I am able to calculate a 3 months rolling average. The solutions arrange the data in order of user, then use rollapply().
This is fine for calculating the e.g. rolling 3 month average for a user_id. What if I wanted to calculate the rolling average from the previous 3 months to that, exclusive of the initial 3 months mean?
E.g. user_id 'c' has a 3 months average of 12 + 9 + 6 = 27/3 = 9. If wanted the previous 3 it would be just mean(3) = 3. If my data were longer there might have been 3 months going further back than the first inital 3.
The end goal is to analyse user behavior change... what is the ratio of somenum for a user in the most recent 3 months vs. the preceeding 3 months.
How could this be calculated?

A: One option is to use the rollmean argument align="left" to create a column and align="right" in another. if you want the function to be used even for groups with less than 3 observation, you have to usse the rollapply function with the argument partial=T.


text:
Q: Out-of-bag estimate biased by correlated features I have a data set with a small number of samples (322) and a large number of features (318.976). My data consists of images, and I want to train a binary classifier.
Since I have such a small amount of data available, I have employed the following strategy:

*

*Reduce dimensionality using a few hand-written rules (from 318.976 to 12.000 features)

*Train Sparse Filter to reduce dimensionality further (from 12.000 to 1000 features

*

*To train the sparse filter, I construct additional data by shifting my images horizontally which my problem is invariant under. This gives me 19.320 samples instead of 322.

*Now my data set has 19.320 samples and 1000 features

*In the training set, only around 2% of the samples are positives

*Now I train a random forest on the data set weighting the positive samples up so they in total achieves the same weight as the negative samples

Here my problem arises. I get a quite good OOB-estimate from my random forest, but it is overly confident. The problem is that when I shifted my data to obtain more samples and then trained the sparse filter, I get some some sets of features which are just shifted versions of each other. When I then train my random forest, these features have a very high correlation, and the OOB-estimate does not take into account that some of my features are very highly correlated, consequently over-estimating the predictive power.
Since I have so few samples originally, I have no good way to do cross-validation, especially since I have a highly imbalanced data set. Is there any way to get slightly more accurate error-estimates?


text:
Q: jQuery ajax - blank response returned I am trying to use jQuery ajax to get some values from the database and then return them in an array.
I have used the same code several times before but this time, no response is being returned. Although the post values are the correct values that I would expect. Here is the javascript code that I am using:
$.ajax({ url: '/BlogArchive.asmx/ChangePost'
                    , type: 'POST'
                    , contentType: 'application/json; charset=utf-8'
                    , data: '{FileName:"' + FileName + '"}'
                    , dataType: 'json'
                    , success: function (data)
                    {
                        var arrayList = data.d;

                        var BlogPostTitle = $(".BlogPostTitle")[0];
                        var BlogPostDate = $(".BlogPostDate")[0];
                        var BlogPostContent = $(".BlogPostContent")[0];

                        $(BlogPostTitle).html(arrayList[0]);
                        $(BlogPostDate).html(arrayList[1]);
                        $(BlogPostContent).html(arrayList[2]);

                    }
//                    , error: function (XMLHttpRequest, textStatus, errorThrown)
//                    {
//                        //There was an error
//                        alert('dfd');
//                    }
            });

The only javascript error that I am receiving is that data is null, which I would expect as the response is blank.
It seems that the name of the web method that I am calling from my javascript is not even being read, because if I changed 'ChangePost' to 'ChangePost1' for example, it still returns a blank response, although I would expect an error message saying that the web method can't be found.
It seems that it does recognise that the BlogArchive.asmx web service exists because if I put something that would create an error in the VB code, the error appears as the response.
I am sure this must be something simple that I am doing wrong. Any help would be appreciated.

A: , data: '{FileName:"' + FileName + '"}'

Seems odd. You probably meant:
, data: {FileName: FileName}

(or 'FileName=' + FileName)
Furthermore, did you inspect the request (and response) via FireBug or similar?

A: You should try using jQuery getJSON with the minimal arguments.
Another thing, when you are using JSON with jQuery, if the answer data are not wellformed
(like a space before / after the starting JSON string) could lead to a blank answer from
jQuery.
Be sure using traditionnal AJAX with jQuery that your answered data are correct.


text:
Q: Solving an equation for two primes This is from contest preparation:

Find all pairs of primes $(p, q)$ that satisfy
$$p^q - q^p = p q^2 - 19$$.

It looks simple, but I spent hours trying to solve it... and no luck so far.
NOTE: There are similar MSE Q&Ąs here and here. Perhaps someone could apply some ideas from there.

A: We have a diophantine equation involving prime numbers. Therefore it makes sense to try to solve the problem with the help of techniques and theorems from this particular field of mathematics. I refer to the answer posted by Hagen von Eitzen.
However, we can also see the problem as a fairly simple math puzzle, and solve it with common sense and elementary mathematical considerations.
The right hand side of the equation has a cubic term and a constant. The left hand side has two terms with (in general) much higher powers. So if we plug in some random values, e.g. $p=7$ and $q=11$, then the absolute value of the LHS will be many orders of magnitude larger than the RHS. Even when the difference between $p$ and $q$ is minimal, the LHS increases much more rapidly than the RHS. Thus there is a strict limit on the maximum value for the smallest of the pair $(p, q)$.
It turns out that $3$ is the critical value. However if we try $(p,q) = (3,5)$, then the LHS is already too large. This effect only increases for larger $q$. From this we conclude that there can be only be solutions if the smallest value equals $2$. [In fact there is also a solution $p=1$ and $q=4$, but these are not prime numbers.]
Case 1. $p=2$. This leads to the equation $f = 2^q - 3q^2 + 19 = 0$. We can easily verify that the function has (roughly) a parabolic shape, and thus there are at maximum two solutions. These are indeed found for $q=3$ and $q=7$.
Case 2. $q=2$. This leads to the equation $g = 2^p -p^2 + 4p -19 = 0$. This function appears to be monotonically increasing. So there is at most one solution. We can verify that $g$ has indeed a zero for a real value of $p$ larger than $4$, smaller than $5$. It follows that there are no solutions where $p$ is a natural number (prime).

A: Certainly $p\ne q$ (as we cannot have $pq^2-19=0$).
Consider the equation modulo $p$ and $q$, using Fermat's little theorem:
$$ -q\equiv -19\pmod p$$
$$ p\equiv -19\pmod q$$
Hence $$-19\equiv p-q\pmod{pq}.$$
Let $p-q=kpq-19$ with $k\in\mathbb Z$. With $p=2$ we arrive at $(2k+1)q=21$, so $q=3$ or $q=7$. This gives us two candidate solutions $(p,q)=\color{red}{(2,3)}$ and  $(p,q)=\color{red}{(2,7)}$. Assume from now on that $p\ge 3$. Especially, $(kp+1)q=p+19$ is a positive even number, hence $kp+1$ must be positive even, i.e., $k$ is positive odd.

*

*The case $k=1$ is only possible with
$$ p-2\ge p-q=pq-19\ge 2p-19,$$
i.e., $p\le 17$. For each of $p=3,5,7,11,13,17$, check if $q=\frac{p+19}{p+1} $ is prime. This leads to $(p,q)=\color{red}{(17,2)}$.

*The case  $k=3$ is only possible with
$$ p-2\ge p-q=3pq-19\ge 6p-19,$$
i.e., $5p\le 17$ and finally $p=3$. However, then $q=\frac{p+19}{3p+1}$ fails to be prime.

*If $k\ge 5$, we find
$$ p-2\ge p-q=kpq-19\ge 10p-19,$$
i.e., $9p\le 17$, which is impossible.

Check the original equation with the solution candidates found.


text:
Q: Im getting "com.ibm.db2.jcc.am.SqlIntegrityConstraintViolationException: DB2 SQL Error: SQLCODE=-803, SQLSTATE=23505 My code :

@Id
    @Column(name = "cust_admin_id" )
    @SequenceGenerator(name = "Cust_Admin_seq" , sequenceName = "cust_Admin_id",allocationSize=1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE , generator = "Cust_Admin_seq")
    private Integer custAdminId;

Please help as this is in production...

A: you violate a constraint.
f.e. you insert the same dataset twice (same primary key, maybe different values) or you insert a dataset, that has no foreign key dataset connected to another table.
We need a bit more information


text:
Q: asp.net mvc 2 and .net 4 parallelism How can MVC website benefit from the new parallelism features in .net 4? don't websites support parallelism by default since multiple users access them at the same time? Can someone clarify this?

A: Executing tasks in parallel is especially useful for long running tasks. What constitutes a long running task might differ, but it should be longer than the overhead of spinning up and synchronizing the threads.
So, there is no particular benefit for MVC, but there is a general benefit for each request which require more things to be run in parallel.
There's an article from 2007 in MSDN Magazine which outlines some performance aspects of the parallel library.
Example 1: a user hits a page which displays two different graphs. Each graph is calculated from a dataset. Executing the calculations in parallel will benefit the overall time to render the page. (Executing parallel individual tasks)
Example 2: You need to execute some function on a list of data, And use Parallel.For to enumerate over the data and execute some code on it in parallel.
You should analyze your application and figure out which parts can be run in parallel, and then test with the new language features if it helps your application or not.

A: Parallelism is by computer processor.  Parallelism doesn't mean multiple users access the application.  Parallelism is that for one request, the app can split tasks across multiple processors to do the work.  So multiple users accessing the app is a factor in how the server dishes out the work, but not the core idea of parallelism.

A: Every request is handled in its own thread, so you get some degree of parallelism by default with ASP.Net.
When considering implementing any kind of parallelism it is important to test your code with and without parallelism. You have to make sure that the overhead of wrapping, distributing and executing each task is not greater than running the tasks in serial. It often is for most of your day-to-day loops. Parallelism is best used in computationally intensive tasks.


text:
Q: Bulk insert to ElasticSearch with NEST I try to add 100k products to elasticsearch, but when i try i get: {"Validation Failed: 1: no requests added;"}
My code:
        var Node = new Uri("......");
        var ConnectionPool = new SniffingConnectionPool(new[] { Node });
        var Config = new ConnectionConfiguration(ConnectionPool)
                    .SniffOnConnectionFault(false)
                    .SniffOnStartup(false)
                    .SniffLifeSpan(TimeSpan.FromMinutes(10));
        var Client = new ElasticsearchClient(Config);

        var AllProducts = Product.GetProducts();
        var SPl = AllProducts.Split(100); // Split into 100 collections/requests

        var COll = new List<ElasticsearchResponse<DynamicDictionary>>();

        foreach (var I in SPl)
        {
            var Descriptor = new BulkDescriptor();

            foreach (var Product in I)
            {
                Descriptor.Index<Product>(op => op.Document(Product));
            }

            COll.Add(Client.Bulk(Descriptor));
        }

AllProducts contains a list of this object:
public class Product
{
 public int AffiliateNr { get; set; }
 public string AffiliateProductId { get; set; }
 public int BrandNr { get; set; }
 public string Currency { get; set; }
 public string IndexId { get; set; }
 public decimal Price { get; set; }
 public long ProductNr { get; set; }
 public string Title { get; set; }
}

So,

*

*Where can i set the name of the index?

*Why did i get, Validation Failed: 1: no requests added;?

*IndexId is my id for the product. How do i tell Elasticsearch to use this id? Or must i specify a id?

A: Refering to your previous problem, you can use IndexMany for indexing the data.
Now as per your question in comment, you can specify the id which elastic search will use. see the below example.
  ElasticType(IdProperty = "<fieldName>")]
    public class ClassName
    {

if you dont want to specify any Id to elastic search, create a dummy field dummyId(nullable) and put it in "IdProperty". Elastic search will auto assign the value to it if it null.
Edit :
From 2.3 onwards, Its
[ElasticsearchType(IdProperty = "<fieldName>")]


text:
Q: Python (Numpy) array sorting I've got this array, named v, of dtype('float64'):
array([[  9.33350000e+05,   8.75886500e+06,   3.45765000e+02],
       [  4.33350000e+05,   8.75886500e+06,   6.19200000e+00],
       [  1.33360000e+05,   8.75886500e+06,   6.76650000e+02]])

... which I've acquired from a file by using the np.loadtxt command. I would like to sort it after the values of the first column, without mixing up the structure that keeps the numbers listed on the same line together. Using v.sort(axis=0) gives me:
array([[  1.33360000e+05,   8.75886500e+06,   6.19200000e+00],
       [  4.33350000e+05,   8.75886500e+06,   3.45765000e+02],
       [  9.33350000e+05,   8.75886500e+06,   6.76650000e+02]])

... i.e. places the smallest number of the third column in the first line, etc. I would rather want something like this...
array([[  1.33360000e+05,   8.75886500e+06,   6.76650000e+02],
       [  4.33350000e+05,   8.75886500e+06,   6.19200000e+00],
       [  9.33350000e+05,   8.75886500e+06,   3.45765000e+02]])

... where the elements of each line hasn't been moved relatively to each other.

A: Alternatively
Try
import numpy as np

order = v[:, 0].argsort()
sorted = np.take(v, order, 0)

'order' has the order of the first row.
and then 'np.take' take the columns their corresponding order.
See the help of 'np.take' as
help(np.take)

take(a, indices, axis=None, out=None,
  mode='raise')
      Take elements from an array along an axis.
This function does the same thing as "fancy" indexing (indexing arrays
using arrays); however, it can be easier to use if you need elements
along a given axis.

Parameters
----------
a : array_like
    The source array.
indices : array_like
    The indices of the values to extract.
axis : int, optional
    The axis over which to select values. By default, the flattened
    input array is used.
out : ndarray, optional
    If provided, the result will be placed in this array. It should
    be of the appropriate shape and dtype.
mode : {'raise', 'wrap', 'clip'}, optional
    Specifies how out-of-bounds indices will behave.

    * 'raise' -- raise an error (default)
    * 'wrap' -- wrap around
    * 'clip' -- clip to the range

    'clip' mode means that all indices that are too large are

replaced
          by the index that addresses the last element along that axis. Note
          that this disables indexing with negative numbers.
Returns
-------
subarray : ndarray
    The returned array has the same type as `a`.

See Also
--------
ndarray.take : equivalent method

Examples
--------
>>> a = [4, 3, 5, 7, 6, 8]
>>> indices = [0, 1, 4]
>>> np.take(a, indices)
array([4, 3, 6])

In this example if `a` is an ndarray, "fancy" indexing can be used.

>>> a = np.array(a)
>>> a[indices]
array([4, 3, 6])

A: Try
v[v[:,0].argsort()]

(with v being the array).  v[:,0] is the first column, and .argsort() returns the indices that would sort the first column.  You then apply this ordering to the whole array using advanced indexing.  Note that you get a sorte copy of the array.
The only way I know of to sort the array in place is to use a record dtype:
v.dtype = [("x", float), ("y", float), ("z", float)]
v.shape = v.size
v.sort(order="x")

A: If you have instances where v[:,0] has some identical values and you want to secondarily sort on columns 1, 2, etc..,  then you'll want to use numpy.lexsort() or numpy.sort(v, order=('col1', 'col2', etc..) but for the order= case, v will need to be a structured array.

A: An example application of numpy.lexsort() to sort the rows of an array and deals with ties in the first column. Note that lexsort effectively sorts columns and starts with the last column, so you need to reverse the rows of a then take the transpose before the lexsort, and finally transpose the result (you'd have thought this should be easier, but hey!):
In [1]: import numpy as np

In [2]: a = np.array([[1,2,3,4],[1,0,4,1],[0,4,1,1]])

In [3]: a[np.lexsort(np.flip(a, axis=1).T).T]
Out[3]:
array([[0, 4, 1, 1],
       [1, 0, 4, 1],
       [1, 2, 3, 4]])

In [4]: a
Out[4]:
array([[1, 2, 3, 4],
       [1, 0, 4, 1],
       [0, 4, 1, 1]])

Thanks go to @Paul for the suggestion to use lexsort.


text:
Q: Simple android app always crashes Im newbie at developing Android apps but even the simpliest app always crashes when I try to add click listener I tried to google my problem but with no success. I also tried to change API to different versions at new project screen. Im able to run Hello World app but when I try to add listener to my app then Im no longer able to run it. Here is my error log.
03-02 21:13:49.153  19700-19700/com.example.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.app/com.example.app.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2205)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2240)
at android.app.ActivityThread.access$600(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1262)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:4977)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.app.MainActivity.onCreate(MainActivity.java:32)
at android.app.Activity.performCreate(Activity.java:4538)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1071)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2161)
 at android.app.ActivityThread.access$600(ActivityThread.java:139)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2240)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1262)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:4977)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
03-02 21:13:49.163    1598-1922/? E/EmbeddedLogger﹕ App crashed! Process: com.example.app
03-02 21:13:49.163    1598-1922/? E/EmbeddedLogger﹕ App crashed! Package: com.example.app v1 (1.0)
03-02 21:13:49.163    1598-1922/? E/EmbeddedLogger﹕ Application Label: My Application 7
03-02 21:13:51.566  19729-19729/? E/ActivityThread﹕ Failed to find provider info for com.google.android.gallery3d.GooglePhotoProvider
03-02 21:13:56.871  19959-19959/? E/ActivityThread﹕ Failed to find provider info for com.google.android.gallery3d.GooglePhotoProvider

And here only piece of code where I changed something (I added button in design)
public class MainActivity extends ActionBarActivity {

    Button btn = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }

        btn = (Button)findViewById(R.id.button);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                btn.setText("Hi");
            }
        });
    }

A: Look at the line 32 of the file MainActivity.java. Sounds like you're trying to call a method on a null object.
For example, are you sure your layout activity_main.xml contains a Button with an id R.id.button?

A: The problem is either that R.id.button doesn't exist in your activity_main.xml layout, or that there is something null in this code:
if (savedInstanceState == null) {
    getSupportFragmentManager().beginTransaction()
      .add(R.id.container, new PlaceholderFragment())
      .commit();
}

Try them both out separately and figure out which one isn't working. Go from there.
By the way, the NullPointerException occurs on line 32.

A: According to your comment on the last answer, you do not import any R file.
You need to import it this way:
import com.<package_name>.<app_name>.R;
That will import the ids generated file available into your Java code and the Button id button will be visible.


text:
Q: Django:What is best way to import my Custom-User in views.py? Actually i have created my own custom-user (MyUser) in models.py
from django.db import models
from django.contrib.auth.models import AbstractUser

class MyUser(AbstractUser):
    country=models.CharField(max_length=20)

settings.py
AUTH_USER_MODEL = 'new_user.MyUser'

I created a simple function in views.py to create new users.
from django.shortcuts import render,redirect
from django.http import HttpResponse
from django.contrib.auth import get_user_model
from django.conf import settings

def save_account(request):
    MyUser=get_user_model()
    if request.method == "POST":
        name=request.POST.get("name")
        email=request.POST.get("email")
        password1=request.POST.get("password1")
        password2=request.POST.get("confirm-password")
        country=request.POST.get("country")
        new_user=MyUser.objects.create_user(username=name,email=email,password=password1,country=country)
        new_user.save()
        return redirect('/')
    else:
        return HttpResponse("404 Not Found")

1. Here i use get_user_model() function to get my currently custom-user.
2. I have second option to get my custom user just by importing MyUser model from models.py and then use it.
from .models import MyUser

3. I have third option to get custom-user just by importing AUTH_USER_MODEL directly from settings.py and use it like in this way.
from django.conf import settings
MyUser=settings.AUTH_USER_MODEL

but third option returning a string instead of returning my custom-user.but why?
I just want to know that which option is best to import custom-user in views.py and why?

A: Your first two options are both ok. Using get_user_model makes it easier to reuse the app without changing the import. However many Django projects are not meant to be re-used, in which case the explicit import makes it clearer where the user model is imported from.
settings.AUTH_USER_MODEL is meant to be a string. You set it to a string when you did AUTH_USER_MODEL = 'new_user.MyUser', and Django doesn't automatically change it to the model instance when you access it. It's useful in foreign keys because it means you don't need to import the model. For example:
class MyModel(models.Model):
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )


text:
Q: How to test a never-ending stream with Jasmine Marbles? in my Angular service I have some code that performs polling to show a spinner until a certain condition is met:
@Inject({…})
export class SomeService {
  backendCall(): Observable<SomeStatusWrapper> {
    return this.http.get(…)
  }
  isDocumentReady(): Observable<boolean> {
    const hasFinished = new Subject<boolean>()
    return interval(1000).pipe(
      switchMap(idx => of(idx).pipe(delay(idx*250))), // Increment delay between retries
      switchMap(() => this.backendCall()),
      map(({status}) => status === 'Done'),
      tap(done => done?hasFinished.next(done) : undefined),
      distinctUntilChanged(),
      takeUntil(hasFinished),
      endWith(true)
    )
  }
}

Now, I'd like to add a unit test for this one and I am using Jasmine marbles, but I am not certain of how many frames there's going to be there and I can't get to get the unit test working.
How does one express an 'interval' with marble syntax? I know we can do something like cold('1000ms (a|)',{a:true}) where it waits 1000ms, emits "true" and completes at the same time.
I was assuming that this test would pass but it failed:
it('should emit false after 1000ms', () => {
  const service = TestBed.inject(service) // already mocked backendCall to return a status != 'Done'
  expect(service.isDocumentReady()).toBeObservable(cold('1000ms f', {f: false}))
})

Simpler version
How do I write jasmine marbles to make this test pass?
describe('', () => {
  it('should pass', () => {
    const stream$ = interval(1000).pipe(
      switchMap(val => of(val).pipe(delay(250*val))),
      mapTo(false)
    )
    expect(stream$).toBeObservable(cold(???, {f:false}))
  })
})


text:
Q: Why literal does not match format string exception in JPA while saving Date Field I have some Date fields in Oracle but i kept it as String in Entity Class. Except one field all other fields are saving correctly . For one field i am getting an error as
ORA-01861: literal does not match format string.

Just before calling the save function in JPA i see the values exactly matching with the values which are saving correctly . Not sure what else can debug or how i can fix it .
Below are the values just before calling save .
paymentDate=2013-03-04 16:30:07,
noteDate   =2013-03-04 16:30:07,

A: using To_Date TO_DATE(dateStr, formatStr) may solve your problem.
if your table column data type is String then you should typecast to a string before saving it to your database.


text:
Q: Non-standard activity lifecycle on Moto G? I am developing Android apps and use a Nexus 7 and a Moto G as testing targets. Using a very simple test app I noticed that on the Moto G the activity life cycle does not include the onRestart()-Method, in contrary to the Nexus (and the AVDs as well). Has anybody made a similar experience!

A: It is likely that due to lower memory availability, and more aggressive memory management on the Moto G, that your app is being terminated instead of just being stopped.
Instead of seeing an onRestart() are you seeing an onCreate()? If so, that would match the application life cycle diagrams.


text:
Q: Cannot upload back up photos Library to iCloud After I changed iPhones, my Photos library became corrupted: albums disappeared, the order of albums was all over the place, etc. Given this, I decided to start from scratch.
I deleted all photos and albums directly on the iCloud website and purged all deleted items. In short, the Photos library was wiped clean.
I took the Photos library from my Time Machine back up from a couple of days prior to this and made it the new system library and turned on iCloud.
The issue is that the Photos library in the cloud takes priority and it proceeds to erase all the photos on the new system library on my MacBook. It is basically trying to match what is in the cloud (basically nothing) by deleting everything on my computer's Photos library.
How can I force the system to make the new system library take priority and upload the photos from my Macbook to the cloud?


text:
Q: How to remove scrolling delay on website? On my blogger website I have been deciding on what template I want to use and I found the one I like, but for some reason with the particular template that I picked, there is a delay when scrolling on the website.
www.lifeof56.com
Is there a way to make scrolling automatic or instant? I appreciate the help!


text:
Q: C2995: template already defined I have read this question and its answer and still don't understand why I am encountering this issue.
This code compiles in VS2017:
#include <iostream>
#include <string>

template <class T>
struct A
{
    template<class U>
    friend std::enable_if_t<!std::is_void<U>::value, A<void>> operator&&(A<U> a1, A<void> a2)
#if 1
    ;
#else
    {
        return {};
    }
#endif

};

#if 1
template<class U>
std::enable_if_t<!std::is_void<U>::value, A<void>> operator&&(A<U> a1, A<void> a2)
{
    return {};
}
#endif

int main()
{
    std::string s;
    A<int> a1;
    A<void> a2, a3;

    a3 = a1 && a2;

    std::cout << "Press ENTER to exit.\n";
    std::getline(std::cin, s);
}

But if I change the #if 1s to #if 0s, I get C2995:  template function has already been defined.
Why does the compilation fail if I define the friend function inside struct A but succeed if I define it outside?

A: There is actually a rule in the standard that says this is an error, from [temp.inst.3]:

However, for the purpose of determining whether an instantiated redeclaration is valid according to [basic.def.odr] and [class.mem], a declaration that corresponds to a definition in the template is considered to be a definition.

Example from the standard:
template<typename T> struct Friendly {
  template<typename U> friend int f(U) { return sizeof(T); }
};
Friendly<char> fc;
Friendly<float> ff;  // error: produces second definition of f(U)

In your example, A<void> is instantiated when the friend function is instantiated in the instantiation of A<int>. That generates the second definition of the friend function.


text:
Q: Saving Visualforce page as a PDF including Temporary Controller Variables I have a page I am working on that grabs data using an account ID. It allows the user to edit the data and then highlight some parts of the data. The edited data is saved to their account and a PDF is returned showing the highlighting. The highlighting is not saved since it only matters on this one run.
The issue I have is that I am getting a network error when 'downloading' the PDF (in Chrome). I added a line in the page header for 'contentType="application/x-pdf#DocName.pdf"' and it now only saves as a 'Chrome HTML Document' but at least the network error is gone. When I go directly to the PDF (with the currently saved data, but no temporary instances of highlighting) and download, it works correctly and saves as a PDF. So for some reason, I just can't save a PDF version of the document with the temporary highlighting. I don't want to save the highlighting anywhere to Salesforce and I would prefer to show the PDF before letting the user choose whether or not to 'download'/save. Is there another way around this that I am just missing?
Here is the apex:page line in my PDF page and the new pagereference that I return after saving the permanent changes in the controller. Please let me know if any other lines would be helpful. Thanks in advance!
<apex:page sidebar="false" showHeader="false" controller="MyController" renderAs="PDF" applyBodyTag="false" applyHtmlTag="false" standardStylesheets="false" contentType="application/x-pdf#DocName.pdf">

return new PageReference('/apex/DocNamePDF?id=' + accountdId);

A: Not sure I've fully understood, but you could possibly use a dataUri for this, something like this:
Controller
public PDFController
{
    private Id accountId;
    public PDFController(ApexPages.StandardController controller)
    {
        accountId = controller.getId();
    }
    public String getContent()
    {
        PageReference ref = return new PageReference('/apex/DocNamePDF?id=' + accountdId);
        Blob contentData = ref.getContentAsPDF();
        return 'data:application/pdf;base64,' + EncodingUtil.base64Encode(contentData);
    }
}

Page
<apex:page standardController="Account" showHeader="true" sidebar="true" extensions="PDFController">

    <apex:iframe height="500px" width="1000px" src="{!content}">
    </apex:iframe>

</apex:page>

I've used a similar approach before for previewing PDFs, rendering the PDF in an iFrame should allow you to use the PDF plugin save button.


text:
Q: View is not sending right data to controller I have a very simple partial view and I am using ajaxform. In my partial view I have one sigle textArea and a Submit button.
The problem is whatever I write into the text area, It does not send the data to controller, rather it sends a text which is = "Comment".
If I dont write anything, the validation works perfect.
The Viewmodel:
public class NoteCommentViewModel
{
    public Int32 Id { get; set; }

    [Required(ErrorMessage="Hey, if you dont wanna write then why pressing the button !!")]
    public string Comment { get; set; }

    public DateTime CommentDate { get; set; }
    public long UserId { get; set; }
    public double Rating { get; set; }
    public Guid NoteId { get; set; }
}

Controller:
//
    //GET:/Notes/Comment/
    public ActionResult Comment(string id)
    {
        ViewBag.NoteId = id;
        var m = new NoteCommentViewModel()
        {
            NoteId = new Guid(id),
            UserId = Convert.ToInt64(Session["LoginUserId"].ToString()),
            //Comment=""

        };
        return PartialView(m);
    }
    //
    //POST:/Notes/Comment
    [HttpPost]
    public ActionResult Comment(NoteCommentViewModel nvm)
    {
        NoteRatingComments comment = new NoteRatingComments();
        comment.Comment = nvm.Comment; // Here I always have "Comment", regardless whatever I write in the page.
        comment.EntryDate = DateTime.Now;
        comment.NoteId = nvm.NoteId;
        comment.UserId = nvm.UserId;
        comment.Rating = 3.00;

        dc.NoteRatingComments.AddObject(comment);
        dc.SaveChanges();

        return Content(Boolean.TrueString);
    }

The view:

@using (Ajax.BeginForm("Comment", "Notes", null, new AjaxOptions
{
UpdateTargetId = "Comment-message",
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
OnSuccess = "commentSuccess"
}, new { id = "commentForm" }))
{

    @{
        long UserId = Convert.ToInt64(Session["LoginUserId"].ToString());
        string Fullname = Session["LoginUserFullName"].ToString();
    }

    @Html.HiddenFor(m => m.UserId)
    @Html.HiddenFor(m=>m.NoteId)
    @Html.TextAreaFor(m => m.Comment, new { style = "width:600px;height:120px;" })

    @Html.ValidationMessageFor(m => m.Comment)

        <input type="submit" value="Comment" name="comment" class="btn"/>

}

Here is the screen shot of the error...for better understanding. I am writing "data" in the view but in the controller I am getting "Comment"..Where is it coming from??

WOuld be great if someone can help me to identify the problem...!!

A: I am not sure what exactly your problem is. But the below code should work.
public class NoteCommentViewModel
{
    public Int32 Id { get; set; }

    [Required(ErrorMessage=" Your Error message")]
    [DataType(DataType.MultilineText)]
    public string Comment { get; set; }

    //other properties
}

And in your View, Use it like this
  @Html.EditorFor(m => m.Comment)

A: The problem is that your submit button's name attribute is the same as the Comment textarea name attribute.
To resolve this you need to change the submit button's name to something else than "comment" or remove the name attribute from your submit button, so change:
<input type="submit" value="Comment" name="comment" class="btn"/>

To
<input type="submit" value="Comment" class="btn"/>

Because the Ajax.BeginForm uses the the jQuery .serializeArray() method which - because your submit button has a name and this input triggers the submit - also sends the submit button's value "Comment" to the server.

A: actually your code is very confusing. in your view u didnt use Model and seems you use m as your model and as i know this is completely wrong.i dont know your view is rendering but wherever you use m=>m.sth the second m must be nothin.instead  you must define your @model NoteCommentViewModel at first of cshtml file and then use Model instead of second m


text:
Q: Xilinx SDK (Eclipse) project command line build I have an Xilinx SDK workspace with:
- hardware specification (hw);
- board support package (bsp);
- C-language application.
In other words, it is no need to create an workspace like described here http://www.xilinx.com/support/documentation/sw_manuals/xilinx14_3/SDK_Doc/reference/sdk_u_commandline.htm.
Provided Xilinx SDK is an Eclipse-based IDE, how can I make Eclipse to run project clean and release|debug|all configurations build from command line/batch file?

A: This link really helps
http://www.xilinx.com/support/documentation/sw_manuals/xilinx14_1/SDK_Doc/reference/sdk_u_commandline.htm
about headlessbuild syntax:
https://www.cct.lsu.edu/~rguidry/eclipse-doc36/org/eclipse/cdt/managedbuilder/internal/core/HeadlessBuilder.html
script contents
set XILINX_EDK=c:\Xilinx\14.3\ISE_DS\EDK\
set XILINX=c:\Xilinx\14.3\ISE_DS\ISE\
set ECLIPSE=%XILINX_EDK%eclipse\nt\eclipse\eclipsec.exe
set WSPACE=%CD%
set VM=%XILINX%java6\nt\jre\bin\
set BSP=%CD%\TEST_bsp\
set BSPNAME=TEST_bsp
set APP=%CD%\TEST\
set APPNAME=TEST

%ECLIPSE% -vm %VM% -nosplash -application org.eclipse.cdt.managedbuilder.core.headlessbuild -cleanBuild all -data %WSPACE%

A: If you have the workspace already, can you not just run make clean; make in the project directory?


text:
Q: Laravel's bcrypt changes passwords, but then I cannot log in I have a PHP/Laravel script that allows user to change his password:
$obj_user->password = bcrypt($post['password']);

But once the password is changed, user cannot log back in with the new password.
I am using Laravel 5.3, and I don't get any warnings when I use bcrypt, so I am not sure of what's going on.

A: Okay, first of all, look at my code:
$obj_user = User::find($user_data['id']);
$obj_user->password = $post['password'];//Hash::make($post['password']);
$obj_user->save();

Notice two things:  (1) I am using a Laravel model to get the user's data. (2) And Hash::make is grayed out. I am no longer using it yet I was able to encrypt the password anyhow.
This issue has affected Laravel users in the past. Inside the User model, I have this:
public function setPasswordAttribute($password)
{ $this->attributes['password'] = Hash::make($password); }

This is a Laravel mutator. When I use the save() method on the model the mutator activates and encrypts the password. Therefore, my problem was that I was encrypting my password twice. Laravel models with mutators may cause problems if the programmer is not aware of them.


text:
Q: How to find the minimal polynomial? Let
$$T : \mathbb{R}^{n \times n} \to \mathbb{R}^{n \times n}, \qquad T(A) = A^{t}$$
I want to find its minimal polynomial, but in order to do that I need to find the matrix basis $[T]_{\tilde{e}}$ lets say $\tilde{e}$ is the basis of a matrix. Which means that its consider by the vectors after we bring the matrix to its  row-echelon form.
I am quite confused could someone help me understand how to find $[T]_{\tilde{e}}$ and the minimal polynomial?

A: You don't need to pick any basis. Since $(A^t)^t$ is identically equal to $A$, $p(x)=x^2-1$ annihilates $T$. If you can prove that no linear polynomial annihilates $T$ (note: whether $n$ is greater than $1$ is essential here), then $p$ is the minimal polynomial of $T$.


text:
Q: How can we maintain session variables between our CMS and a standalone script on the same server? We have developed a stand-alone script on the same server as our Joomla 1.5 installation.  We want to see if the user is logged into to Joomla before giving them access to the script.  To do that, we want to cross reference the session_id from Joomla and then query the Joomla database to verify that the user is logged in.
At this point our standalone script looks like this, just to test whether we can access the session variables.
<?
session_start();
print_r($_SESSION);
?>

However, the session variable is empty and prints out an empty array.  Does anyone know why we are unable to pass the session variables to the standalone script?  Doing a print_r($_SESSION) from within the Joomla code works just fine.

A: SEE "Joomla login session" tutorial:
Especially this part:

"Once the frame work is initialised you can start using Joomla session"

SEE ALSO Custom Sessions with Joomla

A: Joomla is probably using a custom session handler.
See: http://www.php.net/manual/en/function.session-set-save-handler.php


text:
Q: Samsung Galaxy S4 rear camera slow in burst mode I created a camera Activity, which provides a burst" mode.
This means, the activity takes a new picture as soon as the last one has been taken.
The activity is based on the code example provided here: https://github.com/rdasxy/android-burst-camera .
I measure the duration between the two methods camera.takePicture and pictureCallback.onPictureTaken.
The app uses the rear camera, does discard the picture data and not save it, thus I measure the camera performance.
On the Samsung Galaxy S3 the rear camera is able to take about 4 pictures per second.
The new Samsung Galaxy S4 only takes 1 (one!) picture about every 800[ms] to 1200[ms].
The performance does not change when I set even the smallest picture size.
This slow performance is strange, since the built in camera app is able to take a bunch of pictures within a second even using the highest resolution.

*

*Does anyone have experience with the Galaxy S4 rear camera and know
about this performance drop?

*Are there any undocumented camera properties specific to the Galaxy S4?

*Can anyone give hints to get a higher burst-rate on the Galaxy S4?


text:
Q: How to reset metrics every X seconds? I am trying to measure application and jvm level metrics on my application using DropWizard Metrics library.
Below is my metrics class which I am using across my code to increment/decrement the metrics. I am calling increment and decrement method of below class to increment and decrement metrics.
public class TestMetrics {
  private final MetricRegistry metricRegistry = new MetricRegistry();

  private static class Holder {
    private static final TestMetrics INSTANCE = new TestMetrics();
  }

  public static TestMetrics getInstance() {
    return Holder.INSTANCE;
  }

  private TestMetrics() {}

  public void increment(final Names... metricsName) {
    for (Names metricName : metricsName)
      metricRegistry.counter(name(TestMetrics.class, metricName.value())).inc();
  }

  public void decrement(final Names... metricsName) {
    for (Names metricName : metricsName)
      metricRegistry.counter(name(TestMetrics.class, metricName.value())).dec();
  }

  public MetricRegistry getMetricRegistry() {
    return metricRegistry;
  }

  public enum Names {
    // some more fields here
    INVALID_ID("invalid-id"), MESSAGE_DROPPED("drop-message");

    private final String value;

    private Names(String value) {
      this.value = value;
    }

    public String value() {
      return value;
    }
  };
}

And here is how I am using above TestMetrics class to increment the metrics basis on the case where I need to. Below method is called by multiple threads.
  public void process(GenericRecord record) {
    // ... some other code here
    try {
      String clientId = String.valueOf(record.get("clientId"));
      String procId = String.valueOf(record.get("procId"));
      if (Strings.isNullOrEmpty(clientId) && Strings.isNullOrEmpty(procId)
          && !NumberUtils.isNumber(clientId)) {
        TestMetrics.getInstance().increment(Names.INVALID_ID,
            Names.MESSAGE_DROPPED);
        return;
      }
      // .. other code here

    } catch (Exception ex) {
      TestMetrics.getInstance().increment(Names.MESSAGE_DROPPED);
    }
  }

Now I have another class which runs every 30 seconds only (I am using Quartz framework for that) from where I want to  print out all the metrics and its count. In general, I will send these metrics every 30 seconds to some other system but for now I am printing it out here. Below is how I am doing it.
public class SendMetrics implements Job {

  @Override
  public void execute(final JobExecutionContext ctx) throws JobExecutionException {
    MetricRegistry metricsRegistry = TestMetrics.getInstance().getMetricRegistry();
    Map<String, Counter> counters = metricsRegistry.getCounters();
    for (Entry<String, Counter> counter : counters.entrySet()) {
      System.out.println(counter.getKey());
      System.out.println(counter.getValue().getCount());
    }
  }
}

Now my question is: I want to reset all my metrics count every 30 seconds. Meaning when my execute method prints out the metrics, it should print out the metrics for that 30 second only (for all the metrics) instead of printing for that whole duration from when the program is running.
Is there any way that all my metrics should have count for 30 seconds only. Count of whatever has happened in last 30 seconds.

A: As an answer because it is too long:
You want to reset the counters. There is no API for this. The reasons are discussed in the linked github issue. The article describes a possible workaround. You have your counters and use them as usual - incrementing and decrementing. But you can't reset them. So add new Gauge which value is following the counter you want to reset after it have reported to you. The getValue() method of the Gauge is called when you want to report the counter value. After storing the current value the method is decreasing the value of the counter with it. This effectively reset the counter to 0. So you have your report and also have the counter reset. This is described in Step 1.
Step 2 adds a filter that prohibits the actual counter to be reported because you are now reporting through the gauge.


text:
Q: Send array data from one class to another JAVA (I'm a beginner so this may sound obvious/lack information.) I have an ArrayList of attributes for different pets including attributes such as their given-name, common-name, the price of the animal, sex, date bought and date sold.   this information is generated from a separate class that adds an array of information to an array of arrays of the already existing list of animals. Essentially, I want to send the array to another class (called Pets) so it can then be added to the array of arrays. I understand this may sound confusing but this is the only way I can word it, I can clarify anything if needed. Any help would be great as I'm really stuck and can't work out how to send it. This is the code that generates my values in the array (using text-boxes to input the information).
public void actionPerformed(ActionEvent e) {
            ArrayList<String> NewanimalArr = new ArrayList<>();

            String givenName = txtGivenname.getText();
            String commonName = txtCommonName.getText();
            String priceOf = txtPrice_1.getText();
            String sexOf = txtSex.getText();
            String colourOf = txtMaincolour.getText();
            String dateOfA = txtArrivaldate.getText();
            String dateSold = txtSellingdate.getText();

            NewanimalArr.add(givenName);
            NewanimalArr.add(commonName);
            NewanimalArr.add(priceOf);
            NewanimalArr.add(sexOf);
            NewanimalArr.add(colourOf);
            NewanimalArr.add(dateOfA);
            NewanimalArr.add(dateSold);

            System.out.println(NewanimalArr);
        }
    });

this will then print information generated that is entered for example:
[alex, Dog, 40.50, Male, Brown, 14/04/2015, 14/12/2016]
how do I then send this data to another class

A: Option one Constructor Injection:
public class Foo {
  List<String> actionPerformed(ActionEvent e) {
    List<String> newanimalArr = new ArrayList<>();
    .....
    return newanimalArr
}
...
public class Pets {
  private final List<String> array;
  public Pets(final List<String> array) {
    this.array = array;
  }
  void bar() {
    System.out.println(this.array);
  }
}
....
public static void main(String[] args) {
  Foo foo = new Foo();
  Pets pets = new Pets(foo.actionPerformed( new ActionEvent() ) );
  pets.bar();
}

Option two Getter-Setter Injection:
public class Foo {
   private final List<String> newanimalArr;
   public Foo() {
     this.newanimalArr = new ArrayList<>();
   }
   public void actionPerformed(ActionEvent e) {
    .....
   }
   public List<String> getNewanimalArr() {
      return new ArrayList<String>(newanimalArr);
   }
}
...
public class Pets {
  private List<String> array;
  public Pets() {
    this.array = Collections.<String>emptyList();
  }
  public void setArray(final List<String> array) {
    this.array = array;
  }
  public void bar() {
    System.out.println(this.array);
  }
}
....
public static void main(String[] args) {
  Foo foo = new Foo();
  foo.actionPerformed( new ActionEvent() );
  Pets pets = new Pets();
  bar.setArray( foo.getNewanimalArr() );
  pets.bar();
}

See also Dependency Injection Patterns

A: Create a class definition of Pet, using instance variables for the fields. In Java it is custom to create a setXyz and a getXyz for each xyz field. You can also create a constructor in which you pass all the values and assign them to the fields, this minimizes the risk of fields not being filled in.
The initial ArrayList you are creating doesn't add that much use, it is easier to create the Pet instances directly:
List<Pet> newArrivals = new ArrayList<>();
// get data from view fields and if necessary transform them to other objects such as:
LocalDate arrivedOn = LocalDate.parse(txtArrivaldate.getText(), DateTimeFormatter.ofLocalizedDate(FormatStyle.FormatStyle);
// create and add a new Pet object to the list
newArrivals.add(new Pet(.....));

public class Pet {
public enum Gender {
    FEMALE, MALE
}

private String givenName;
private String commonName;
private double price;
private Gender gender;
private String color;
private LocalDate arrivedOn;
private LocalDate soldOn;

public Pet() {
}

public Pet(String givenName, String commonName, double price, Gender gender, String color, LocalDate arrivedOn,
        LocalDate soldOn) {
    super();
    this.givenName = givenName;
    this.commonName = commonName;
    this.price = price;
    this.gender = gender;
    this.color = color;
    this.arrivedOn = arrivedOn;
    this.soldOn = soldOn;
}

public String getGivenName() {
    return givenName;
}

public void setGivenName(String givenName) {
    this.givenName = givenName;
}

public String getCommonName() {
    return commonName;
}

public void setCommonName(String commonName) {
    this.commonName = commonName;
}

public double getPrice() {
    return price;
}

public void setPrice(double price) {
    this.price = price;
}

public Gender getGender() {
    return gender;
}

public void setGender(Gender gender) {
    this.gender = gender;
}

public String getColor() {
    return color;
}

public void setColor(String color) {
    this.color = color;
}

public LocalDate getArrivedOn() {
    return arrivedOn;
}

public void setArrivedOn(LocalDate arrivedOn) {
    this.arrivedOn = arrivedOn;
}

public LocalDate getSoldOn() {
    return soldOn;
}

public void setSoldOn(LocalDate soldOn) {
    this.soldOn = soldOn;
}

}


text:
Q: How to determin if a SystemTime value is in UTC Is there a way to determine the timezone of a DATE data type that has been converted to a SystemTime value?
Let say a C# file using the COM lib set the value below:
someComInterface.someDateAttribute = new DateTime(somedate).ToUniversalTime();

In the COM library I want to do something like this
if(VariantTimeToSystemTime(DATE, &systm )){
    if(st == UTC ){
          //do something
    }
    else{
          // do something with localtime
    }
}

A: According to MSDN: http://msdn.microsoft.com/en-us/library/system.datetime.kind.aspx
The DateTime kind property "gets a value that indicates whether the time represented by this instance is based on local time, Coordinated Universal Time (UTC), or neither."
If it's local, you'll want to check the TimeOffset property.
http://msdn.microsoft.com/en-us/library/system.datetimeoffset.aspx


text:
Q: Amazon RDS and connecting from MySQLWorkbench I am struggling with this - i've read loads about it but I still cannot see where I am going wrong.
I've installed MySQLWorkBench and connection tests to my RDS fail.  I've tested using telnet to my endpoints on port 3306 and they cannot connect either.
I've created the classic public/private subnets within the Amazon VPC, this includes a DBServerSG Security Group which is currently set to Allow ALL inbound traffic and allow ALL outbound traffic (for testing) and i've ensure my RDS instance is set with the right DB Subnet Group.
I don't have a firewall on my client PC either
I STILL can't connect to my RDS Instances, any thoughts?
Edit, I created a second instance to rule out password/user problems

A: step 1
create a new security rule (or edit an existing one) and add your IP address to gain access to the Amazon Web Service RDS instance.
setp 2
Go to RDS console > security group screen > select or create a new security group. And add your public IP address (don't forget to add the subnet mask for example /32 after the host).
step 3
Then figure out what is the instance address, to do so go to the instance menu and write down the endpoint, port number and principal username:
step 4
now connect to RDS from workbench using a new connection with these Hostname: the endpoint of your RDS instance
Port: the port of your RDS instance
Username: your MySQL username
For further clarification refer to this link for pictorial representation


text:
Q: Retrieve attachments from a Kaltura video Our system allows the possibility of playing videos from Kaltura. There is a chance these videos may contain attached files, which I would like to present to the user. Is there any API call to retrieve these files by just passing the entry_id of the video?
I found this, but looks it only allows to get the attachment by the attachment ID, and not the entry_id from the video containing the attachements.
Thank you so much

A: You can use the list action for the attachmentasset service (see here).
Note, that in the filter (KalturaAssetBaseFilter) you have field called entryIdEqual (string)


text:
Q: Jquery function to Increment one hours based on time input string I have string value in this format.
9:00 am

i want it to be like this.
9:00 am - 10:00 am

second hour must be 1 greater then first one. for example if time is
7:00 am then it should be 7:00 am - 8:00 am

how can i do that using jquery?
i tried this but its not working as it works now.
var time= "9:00 am"
var nexttime=time.setHours(time.getHours()+1)
 alert(nexttime);

getting error of
time.getHours is not a function

A: You can try this :
function increaseTimeByOne(timeStr) {
    var splitedTimeStr = timeStr.split(':');
    var hours = parseInt(splitedTimeStr[0]);
    var meridiem = splitedTimeStr[1].split(" ")[1];
    var minutes = splitedTimeStr[1].split(" ")[0];
    var nextHours = (hours + 1);
    var nextMeridiem;
    if (hours >= 11) {
        if (meridiem.toLowerCase() == "am") {
            nextMeridiem = "pm";
        } else if (meridiem.toLowerCase() == "pm") {
            nextMeridiem = "am";
        }
        if (nextHours > 12) {
            nextHours = nextHours - 12;
        }

    } else {
        nextMeridiem = meridiem;
    }
    return nextHours + ":" + minutes + " " + nextMeridiem;
}

and using above function as
var timestr="9:00 am";
var next_hour = increaseTimeByOne(timeStr);
alert(next_hour);

A: refer this
var time=new Date();
time.setHours(9, 00, 00);
var nexttime=(time.getHours()+1);
alert(nexttime);

// to get hrs mins and seconds
var nexttime=(time.getHours()+1) +":"+time.getMinutes()+":"+time.getSeconds();

A: YOu can make your time string like:

function increaseTimeByOne(t) {
  var s  = t.split(':');
  var n  = parseInt(s[0], 10);
  var nt = (n + 1) + ":00 ";
  var ampm = n >= 11 ? "pm" : "am";

  return t + " - " + nt + ampm;
}

console.log(increaseTimeByOne('9:00 am'));
console.log(increaseTimeByOne('11:00 am'));
console.log(increaseTimeByOne('12:00 pm'));


text:
Q: How init change redux state from componentDidMount? componentDidMount(){
    var self = this;

    //selt.props is undefined too from this point !!!! WHY
    //   this.props.addTodo();

    window.onscroll = function(){

         //self.setState({ type:'ADD_TODO' });
        // debugger
         self.props.addTodo('param')
    }

}

function mapStateToProps (state) {
    return {
        todos: state
    };
}

 function mapDispatchToProps (dispatch, ownProps) {

    return {

        addTodo: function(text){
            dispatch({type: 'ADD_TODO', text: text, id: ++_idSeq});
        }

    }

}

self.props.addTodo is not a function
self.setState({ type:'ADD_TODO' }); dont init reducer ! Why ?

reducer code :
function todoReducer (currentState, action) {
    currentState = currentState || {}; // Initial State
    // debugger
    console.log('reducer!');
    switch (action.type) {
        case 'ADD_TODO':
            debugger
            let newTodo = {id:1};
            return Object.assign({}, currentState, newTodo);

        default:
            return currentState; // TODO: Always return the state
    }
}

// Create Store
var todoStore = createStore(todoReducer);

let unsubscribe = todoStore.subscribe(() => console.log(todoStore.getState()))

window.store = todoStore;

var TodoListContainer = connect(mapStateToProps, mapDispatchToProps)(TodoList);

A: You need to dispatch and action from your componentand change your state in the reducer.
Simple example:
Component:
componentWillMount() {
    store.dispatch({ type: 'YOUR-ACTION', payload: 'yourValue' })
}

Reducer:
function app(state = initialState, action) {
  switch (action.type) {
    case 'YOUR-ACTION':
      // change your state here
    default:
      return state
  }
}

Notes:
Sending directly actions from your component IMO it is not really optimal for real world apps, because you couple your components. Consider instead to use containers and decoupling your app more. An interesting article.


text:
Q: Count word/pos from file I've almost solved an exercise from my python lectures. I've been asked to write a program that counts how often each word occurs in a file, and how often it has been tagged with which POS.
The counts should be written to a new file, which is also given on the command line.
For instance,
python3 wordcount-pos.py wsj00-pos.txt counts-wsj00-pos.txt

should produce a output like this:
   Mortimer 1   NNP 1

   foul 1   JJ  1

   ...

   reported 16  VBN 7   VBD 9

   ...

   before   26  RB  6   IN  20

   ...

   allow    4   VB  2   VBP 2

My code produces an output such as:
   Mortimer 1   {NNP:   1}

   foul 1   {JJ: 1}

   ...

   reported 2   {VBN:   7   VBD:    9}

   ...

   before   2   {RB:    6   IN: 20}

   ...

   allow    2   {VB:    2   VBP:    2}

It doesn't print the occurrences of "word" in my dictionary
Here it is my code:
import sys
from collections import defaultdict

def main():
    if len(sys.argv) != 3:
        print('Usage: python poscount.py <input file>', file=sys.stderr)
        sys.exit(1)

    input_filename = sys.argv[1]
    output_filename = sys.argv[2]
    # your code
    freq = defaultdict(list)
    with open(input_filename) as f:
        for line in f:
            # skip empty lines
            if line.strip() != '':
                #  split a word/pos pair into two separate strings
                word, pos = line.strip().rsplit("/", 1)
                # add word and list of pos as k, v into "freq" dictionary
                freq[word].append(pos)

    for k, v in freq.items():
        D = defaultdict(list)
        for i, item in enumerate(v):
            D[item].append(i)
        D = {k: len(v) for k, v in D.items()}
        # Output file
        with open(output_filename, "a") as f:
            print(k + "\t" + str(len(D.items())) + "\t" + str(D), file=f)

if __name__ == '__main__':
    main()

file from where extract the data: https://paste.elnota.space/nezemivaku.sql
Partial content of the file:
Pierre/NNP
Vinken/NNP
,/,
61/CD
years/NNS
old/JJ
,/,
will/MD
join/VB
the/DT
board/NN
as/IN
a/DT
nonexecutive/JJ
director/NN
Nov./NNP
29/CD
./.
Mr./NNP
 Vinken/NNP
is/VBZ
chairman/NN

A: I think this will solve your problem
print(k + "\t" + str(sum(D.values())) + "\t" + str(D), file=f)


text:
Q: Updating a string using regular expressions in Python I'm pretty sure that my question is very straightforward but I cannot find the answer to it. Let's say we have an input string like:
input = "This is an example"
Now, I want to simply replace every word --generally speaking, every substring using a regular expression, "word" here is just an example-- in the input with another string which includes the original string too. For instance, I want to add an @ to the left and right of every word in input. And, the output would be:
output = "@This@ @is@ @an@ @example@"

What is the solution? I know how to use re.sub or replace, but I do not know how I can use them in a way that I can update the original matched strings and not completely replace them with something else.

A: You can use capture groups for that.
import re

input = "This is an example"
output = re.sub("(\w+)", "@\\1@", input)

A capture group is something that you can later reference, for example in the substitution string. In this case, I'm matching a word, putting it into a capture group and then replacing it with the same word, but with @ added as a prefix and a suffix.
You can read about regexps in python more in the docs.

A: Here is an option using re.sub with lookarounds:
input = "This is an example"
output = re.sub(r'(?<!\w)(?=\w)|(?<=\w)(?!\w)', '@', input)

print(output)

@This@ @is@ @an@ @example@

A: This is without re library
a = "This is an example"
l=[]
for i in a.split(" "):
    l.append('@'+i+'@')

print(" ".join(l))

A: You can match only word boundaries with \b:
import re

input = "This is an example"
output = re.sub(r'\b', '@', input)
print(output)

@This@ @is@ @an@ @example@


text:
Q: Finding the distance between the centre of an arbitrarily rotated cylinder and a point on that cylinder this is a bit more complicated than the post title suggests because I was running out of words. I suppose the full title would be: "Finding the distance between the centre of an arbitrarily rotated cylinder and a point on that cylinder which is the intersection of a ray projected from the centre of the cylinder at angles a and b, which are relative to the absolute axes."
To break it down a little:
I have a circular cylinder, which is rotated to an arbitrary orientation in 3D. I have the radius of the cylinder and I have a vector which is the vector along the cylinder's length (essentially the cylinder's orientation). The cylinder's height is infinite.
I also know the coordinates of the centre of the cylinder, let's call that point p. From p I draw a line in 3D in a direction specified by two angles, alpha and beta, which are angles of rotation in the cardinal axes of x and y (i.e. the absolute axes, and not relative to the cylinder). I would like to work out the point at which this line intersects the cylinder and also the distance between the two points.
So to break it down further:
1) I need to rotate the cylinder back to the origin, and then rotate the line by the exact same same angles to get them relative to the cylinder while the cylinder is at the origin.
2) Using this new point of reference, I need to calculate the point of intersection between the now transformed cylinder and the line made from the two transformed angles I have.
I can get x and y of this point by using rCosAlpha,rSinAlpha and I can get z by using rtanBeta (I have the adjacent - r (the radius) - and need the opposite)
And then I simply use Pythagoras' theorem to get the distance.
The problem is working this all out using these two frames of reference: absolute orientations and relative orientations. Or solving problem (1) so I don't have
Does anybody have any ideas?

A: The distance should be easy to determine in closed-form from $r$ (cylinder radius), $\overline{C}$ (a vector along the cylinder's center) and $\overline{P}$ (a vector representing a ray from that centerline to the point $p$).
My first stab...
$$ d = r \tan\left(\arccos{\left(\! \frac{\overline{C}\cdot\overline{P}}{|\overline{C}| |\overline{P}|} \!\right)}\right) $$


text:
Q: buck or booster converter, difference between R RL load I understand the concept of buck or booster converter but I can't find source about what changes if the load is rl instead of just R. Could you help me to see what changes in the characteristics?
At buck converter if my understanding is right it's just the RL load is just L in series with the converter's L.

A: Whether you talk about a boost or a buck converter, it can be loaded by various types of load but let's assume a resistance \$R\$. In the literature, you often find \$L\$, \$C\$ and \$R\$ for the constitutive elements:

Then, if you consider energy-storing elements parasitics like their equivalent series resistance or ESR, writers use lowercase to designate these: \$r_C\$ and \$r_L\$ respectively for the capacitor and the inductor. The sketch for a boost converter thus updates to:

The load resistance can be labeled whatever you want but \$R\$, \$R_L\$ or \$R_{load}\$ will do just fine as long as you respect lower and uppercase notations for consistency.

A: In general, a DC-DC converter with feedback and good phase margin can handle a wide range of loads.
An inductive load is no exception.  Of course an inductor across a DC source will eventually become a near short circuit, and the load will look like whatever series resistance there is.
If the load is disconnected while the inductor is storing energy, and there's no path for the current then there's the potential for damage as the voltage increases, possibly causing arcing.
You wouldn't normally connect the winding of a BLDC directly to a DC-DC converter, it typically would serve no purpose to do so.  A BLDC motor is normally driven by a (e.g.) 3 phase FET bridge to provide the rotating field that turns the motor.
I'm not sure what you mean by "the RL load is just L in series with the converter's L".  The load is clearly NOT in series with the converter's inductor.  In the boost shown it's after the switch node and in parallel with the output capacitors.  In a buck, it's also in parallel with the output caps.


text:
Q: Retrieve filename startwith character using package.xml I know that we can retrieve all file name using this:
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <types>
        <members>*</members>
       <name>ApexClass</name>
 </types>
    <version>30.0</version>
</Package>

Is there any way we can retrieve file start or contain with character example 'MyClass__' using package.xml?

A: No, you cannot use wildcards to find partial file matches with package.xml.
Take a look at the Tquila package.xml builder, it might make the process of creating your project contents a little easier.


text:
Q: Trying to add a loop I have a for loop, and I am trying to get it to add 5000 to the annual sales and print the calculations up to 10 times with the commission added, but I'm falling short. (This is of course after the original calculation) Why is my code falling short?   Also after my first output, I cant get the rest of the code to run.
System.out.println("Enter your annual sales");
String annual = input.nextLine();

int salary = 7550281;
int commission = 38_28;
if (Integer.parseInt(annual) < 92416_02) {
  commission = 37_28 * 1_32 / 100;
}
int compensation = Integer.parseInt(annual) * commission / 100 + salary;
System.out.println("compensation is: "+compensation );

for(int sales = (Integer.parseInt(annual) ); sales < 10; sales +=5000);
int salary = 7550281;
int commission = 38_28;
if (Integer.parseInt(annual) < 92416_02) {
  commission = 37_28 * 1_32 / 100;
}
int compensation = Integer.parseInt(annual) * commission / 100 + salary;

System.out.println("Your Annual compensation in 5000 increments are ");

A: The correct for loop syntax is
for(int sales = (Integer.parseInt(annual) ); sales < 10; sales +=5000){
    //code
}

not
for(int sales = (Integer.parseInt(annual) ); sales < 10; sales +=5000);

though I think your logic needs some work. sales won't be less than 10 for more than one iteration of this loop, since you are adding 5000 to it each time.

A: Another shot in the dark, since you haven't given us your error message:
int commission = 38_28;

These _'s are ignored by the compiler. They're just there to make numbers easier to read. For example, you could say:
int phoneNumber = 1_800_555_5555;
int socialSecurityNumber = 123_12_1234;

Which is identical to this, but potentially easier to read:
int phoneNumber = 18005555555;
int socialSecurityNumber = 123121234;

In your case, they're meaningless, so I would remove that.
Probably what you want is floating point numbers:
float commission = 38.28;

Also, this loop is extremely suspicious, besides ending with a semicolon:
for(int sales = (Integer.parseInt(annual) ); sales < 10; sales +=5000);

The fact that if sales < 10, you add 5000 is extremely strange. If that's what this loop is actually supposed to do, I'd write it as an if statement to be less confusing:
int sales = Integer.parseInt(annual);
if (sales < 10) {
    sales += 5000;
}

Or maybe annual starts out extremely negative?


text:
Q: pgbouncer:is it OK putting on localhost or it's better on another server? I'm about to migrate my (tiny) server farm to Google Cloud Platform and so giving the architecture a small restyling.
One of the changes I'm about to commit is the introduction of pgBouncer, to manage pooling (ATM I'm having only one DB server with Debian Jessie).
But I cant' find anywhere (or I need improving my Googling skills :-) ) this kind of information:
If I install pgBouncer on the same machine where PostgreSQL runs, will it impact performance? (my primary concerns are about I/O, while CPU and memory can always be improved). Is it better to install it somewhere else?
Thanks in advance

A: Unless you're on the very extremes of performance requirements (or on woefully underpowered hardware), I wouldn't expect running pgbouncer on the DB server would be noticeable.  However, what you might like to consider is the network connection between the DB clients and the server.  Specifically, if you put pgbouncer on the client, then it will make the 'over-the-network' connections to the DB server and keep them alive avoiding repeated TCP handshakes, and the client will then be making a really quick local connection to pgbouncer.  If you put pgbouncer on the DB server, then there is no advantage network connection-wise (the client has to make a TCP connection to the remote DB server), and all pgbouncer is doing is being a connection pool.


text:
Q: Is there a Kubernetes pattern or concept equivalent to init containers that runs after the application has started? I have an application that starts, is configured, then the configuration is run, via the application's API calls (i.e. Cannot be configured until after the application is running).  The application also takes a bit of time to start up before it is ready to accept the configuration.  This container is being run inside a Kubernetes cluster.
I want to create a helper container inside the pod that:

*

*Uses a different language than what the application container has (add python, so it should be a separate container)

*Loops/waits/sleeps until the application is ready (check for a url to be available)

*Runs a script to configure the application, then start the configuration

*Runs to completion and isn't always running

*Is tied to the main application (automated, runs once if the main application is restarted, I can already do this if I just run it manually after a restart)

*(Bonus) Runs the script to completion or shows the main application as failed

Basically I am looking for a lot of the same characteristics of an init container, except that it runs post application startup instead of pre application startup.
Anyone have an example or pattern to research that does this?
Thanks!


text:
Q: Working with ui-router I'm completely new to Angularjs, I need some help in achieving the following requirement. Initially, i will be loading the following index.html file.
<!DOCTYPE html>

    <meta charset="utf-8">

And this is my app.js file;
'use strict';

var App = angular.module('myApp',['ui.router']);

App.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider){

    $urlRouterProvider.otherwise("/login")

    $stateProvider
        .state('login', {
        url: "/login",
        templateUrl: "views/login.html",
        controller: "NextPageController as nxtPgCtrl"
        })
        .state('nextpage', {
            url: "/nextpage",
        views: {
            "": {
                templateUrl: "views/nextpage.html"
            },
            "menu@nextpage": {
                templateUrl: "views/menu.html"
            },
            "footer@nextpage": {
                templateUrl: "views/footer.html"
            }
        }
        })
        .state('nextpage.addemployee', {
            url: "/add-employee",
            templateUrl: "/views/addemployee.html"
        })
        .state('nextpage.listemployee', {
            url: "/list-employee",
            templateUrl: "/views/listemployee.html"
        })
        .state('nextpage.dashboard', {
            url: "/dashboard",
            templateUrl: "views/dashboard.html"
        })
}]);

I'm loading the login.html file inside the div block of index.html where I have used ui-view.
login.html;

    <form ng-submit="nxtPgCtrl.nextPage()">
        <input type="text">

        <input type="password">

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

Once the submit button is pressed I'm redirecting the user to the next page using the following controller.
NextPageController.js;
App.controller('NextPageController', ['$location', function($location) {
    var self = this;
    self.nextPage = nextPage;
    function nextPage() {
        $location.path('/nextpage');
    }
}]);

And this is my nextpage.html;

This is main content...

This is the file that will be loaded inside the div where I have used ui-view="menu" in nextpage.html,
menu.html;

Dashboard

Add Employee

List Employee

And this file will be loaded inside the div where I have used ui-view="footer",
footer.html;

This is footer...

If I press the Dashboard, Add Employee & List Employee links the following respective files will be loaded inside the div block with id: main_content, since I have used ui-view.
dashboard.html;

This is main content...

addemployee.html;

Add employee form...

listemployee.html;

List of employees...

The above codes are working fine, but I need some help.
The first one is that, when I load nextpage.html, I want dashboard.html to be loaded inside the div block whose id is main_content. Now the code is like, I have hard coded the dashboard.html file content inside the div with id: main_content and if the user clicks the Dashboard link on the menu I'm loading the dashboard.html content. So, I have used the dashboard.html file content twice. Instead, I want the dashboard.html template to be loaded dynamically when I enter nextpage.html.
The next one is, whether this is the proper way of using ui-router to achieve what i'm trying in a web application or is there any standard way of doing this if any please guide me.


text:
Q: How to create advanced aggregation with lookup and filtering in Spring Data MongoDB? I need to create advanced aggregation using Spring Data MongoDB having model like that:
@Getter
@Setter
@Document
public class Library {

  @Id
  @JsonSerialize(using = ToStringSerializer.class)
  private ObjectId id;

  private Address address;

  private String workingHours;

  ...

}

@Getter
@Setter
@Document
public class Book {

  @Id
  @JsonSerialize(using = ToStringSerializer.class)
  private ObjectId id;

  private Boolean published;

  private Boolean hidden;

  private String title;

  @DBRef
  @NotNull
  private Library library;

  ...

}

pom.xml
<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-mongodb</artifactId>
        <version>2.2.0</version>
</dependency>

Libraries collection:
{
    "_id" : ObjectId("5f45440ee89590218e83a697"),
    "workingHours" : "8:00 PM - 8:00 AM",
    "address" : DBRef("addresses", ObjectId("5f4544198da452a5523e3d11"))
}

Books collection:
{
    "_id" : ObjectId("5f454423be823729015661ed"),
    "published": true,
    "hidden": false,
    "title": "The Hobbit, or There and Back Again"
    "library" : DBRef("libraries", ObjectId("5f45440ee89590218e83a697"))
},
{
    "_id" : ObjectId("5f45445b876d08649b88ed5a"),
    "published": true,
    "hidden": false,
    "title": "Harry Potter and the Philosopher's Stone"
    "library" : DBRef("libraries", ObjectId("5f45440ee89590218e83a697"))
},
{
    "_id" : ObjectId("5f45446c7e33ca70363f629a"),
    "published": true,
    "hidden": false,
    "title": "Harry Potter and the Cursed Child"
    "library" : DBRef("libraries", ObjectId("5f45440ee89590218e83a697"))
},
{
    "_id" : ObjectId("5f45447285f9b3e4cb8739ad"),
    "published": true,
    "hidden": false,
    "title": "Fantastic Beasts and Where to Find Them"
    "library" : DBRef("libraries", ObjectId("5f45440ee89590218e83a697"))
},
{
    "_id" : ObjectId("5f45449fc121a20afa4fbb96"),
    "published": false,
    "hidden": false,
    "title": "Universal Parks & Resorts"
    "library" : DBRef("libraries", ObjectId("5f45440ee89590218e83a697"))
},
{
    "_id" : ObjectId("5f4544a5f13839bbe89edb23"),
    "published": false,
    "hidden": true,
    "title": "Ministry of Dawn"
    "library" : DBRef("libraries", ObjectId("5f45440ee89590218e83a697"))
}

Features:

*

*User must be able to filter by each field. -> That's not the problem for me. Based on passed parameters I would create Criteria and use Aggregation.match().

*Depending on the context of the user, I have to return a different count of books that can be filtered based on startsWith() or like() principle. -> Here I have a problem.

Assuming that I have 4 published books, one more added by normal user and one more hidden.

*

*Administrator should know about all of them, so he will see booksCount as 6.

*The regular user sees only published or added by himself, so he will see booksCount as 5.

*Not logged users see only published, so he will see booksCount as 4.

*There can be some other conditions in the future.

Criteria criteria = Criteria.where("_id").ne(null).and("address.city").is("Chicago");

if (!isAdministrator()) {
    criteria = criteria.and("published").is(Boolean.TRUE);
}

MatchOperation matchOperation = Aggregation.match(criteria);

LookupOperation lookupOperation = LookupOperation.newLookup().from("books").localField("id").foreignField("library.$id").as("books");

UnwindOperation unwindOperation = Aggregation.unwind("books");
CountOperation countOperation = Aggregation.count().as("booksCount");

Aggregation aggregation = Aggregation.newAggregation(matchOperation, lookupOperation, unwindOperation, countOperation);

mongoTemplate.aggregate(aggregation, "libraries", Document.class).getRawResults().getInteger("booksCount");

At first I thought I would use LookupOperation, but it doesn't work properly (it fetches all books in the collection independently from ObjectId). Unfortunately, I ran into a problem that we can't use DBRef in the aggregation pipeline, except in the $match stage. Here is the description of the problem.
I read the explanation in the second post, but I don't know how to implement such advanced projection with map operation using Spring Data MongoDB. Additionally, I would like to be able to filter by this value as described in the second point.
My questions are:

*

*How can I achieve such behavior using Spring Data MongoDB (I'll probably be able to tweak the version a little bit)?

*If we implement this, will I be able to apply appropriate filters to booksCount as stated in description?

*Is there another way to accomplish such behavior using another library, framework or functionality? I was thinking only about custom DTO, querying all existing libraries, looping through them and based on passed parameters query booksCount. But that won't solve the filtering and pagination problem.

Thank you in advance.


text:
Q: extract just one element from list and write it into a csv as another name I have a list:
IDs = ["111111111111", "222222222222"]

and create a csv with this code:
for acc in IDs:
    with open("/tmp/test.csv", "a+") as f:
            test = csv.writer(f)
            test.writerow([IDs])

result is:
{'111111111111', '222222222222'}

what i want to do is like:
if IDs == "111111111111":
    IDs = "AccountA"
elif IDs == "222222222222":
    IDs = "AccountB"

expected result in csv:
Account A
    some information about account a i put later on it
Account B
    some information about account a i put later on it

How can I achieve the result?

A: You could use a dictionary. What you do is you create a dictonary with all data. At the left side you would have your input, and and the right side you have your data that your want to write. For this case, take a look at this dictionary:
data = {
  '111111111111':'AccountA',
  '222222222222':'AccountB'
}

Than, create a loop around your list and create a new list, with the new ids, configured with your data.
new_ids = []
for x in ids:
  new_ids.append(data[x])

Now, you can use the new_ids list to use in your write function.
Hope it helps.
Sincerly, Chris Fowl.


text:
Q: How to get logged user data in ASP.NET Core 5 MVC (.NET 5)? I'm currently working on an ASP.NET Core 5 MVC web project, I used default created Single User Account generated template for user management. I have applied the migration and it's working fine as expected. I need to get logged user, in .NET 5 Single User Account template AccountController was not visible. I tried following code outside the controller, it's giving null.
public class UserService
{
    private readonly IHttpContextAccessor _context;

    public UserService(IHttpContextAccessor context)
    {
        _context = context;
    }

    public string GetUser()
    {
       return _context.HttpContext.User?.Identity?.Name;
    }
}

A: You can see sample code at here https://stackoverflow.com/a/38751842/3728901 (maybe, ASP.NET Core 1, 2, or 3)
Focus at
public class MyController : Microsoft.AspNetCore.Mvc.Controller

var id = _userManager.GetUserId(User); // Get user id:

or other way
private UserManager<ApplicationUser> _userManager;

//class constructor
public MyController(UserManager<ApplicationUser> userManager)
{
    _userManager = userManager;
}

and
var user = await _userManager.GetUserAsync(User);
var email = user.Email;

Because this question related .NET 5 therefore I don't consider the question is duplicated. Let's me know or revise small details if has minor changes in .NET 5.


text:
Q: Between express server and react.js - fetch does not work? I am trying to get data in react by sending GET or POST request to express server.
But I can't receive response from server.
Below is my React component code.
    handleButton() {
        const sendData = {
            "say" : "Hello",
            "to" : "React App"
        };
        fetch("http://localhost:5000/", {
            mode : "no-cors",
            method : "POST",
            body : JSON.stringify(sendData)
        }).then(res => {
            console.log(res);
            alert(res);
        });
    }

handleButton() is called when I press the button.
I want to receive data from server when I click the button.
Then here is my express server code.
var express = require("express");
var bodyParser = require("body-parser");
var multer = require("multer");
var upload = multer();
var app = express();

app.get("/", function(req, res) {
  res.render("form");
});

app.set("view engine", "pug");
app.set("views", "./views");

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({extended : true}));

app.use(upload.array());
app.use(express.static("public"));

app.post("/", function(req, res) {
  console.log(req.body);
  res.send("received your request!");
});

app.listen(5000);

My server is very simple but it doesn't work.
When I press the button, server console outputs empty object.
This is my server console capture image.

And then this is my google chrome browser console capture image.

Please help me with getting right result. I want to notice that server received request by alert in react.


text:
Q: How to return multiple values from a SQL Case subquery without grouping I have the following SQL query where the CASE statement needs to return multiple values.
select TASK_NAME
from TASK
where TASK_TYPE in (
    case
        when (select USER_COUNTRY from USER) in (select COUNTRY_NAME from COUNTRY where CONTINENT = 'Europe') then ('Adhoc', 'Resell')
        when (select USER_COUNTRY from USER) in (select COUNTRY_NAME from COUNTRY where CONTINENT = 'Americas') then ('Classified', 'Bought', 'Handle')
        else ('None', 'Blank')
    end )

However, the number of WHEN clauses is not fixed as there may be more conditions. I don't think SQL return multiple values from CASE statement will work.
I should also add that grouping is not recognised by the application which this query is passed to.
I apologise for not providing the tables. I will do so in due course. Just wanted to get this out there.

A: You can move the comparison to the when clauses and have the case return a scalar value indicating a match:
where 1 = (case when (select USER_COUNTRY from USER) in (select COUNTRY_NAME from COUNTRY where CONTINENT = 'Europe') and Task_Type IN ('Adhoc', 'Resell')
                then 1
                when (select USER_COUNTRY from USER) in (select COUNTRY_NAME from COUNTRY where CONTINENT = 'Americas') and Task_Type IN ('Classified', 'Bought', 'Handle')
                then 1
                when Task_Type IN ('None', 'Blank')
                then 1
            end )

This is a rather strange set of conditions.  Are you sure you can't express the logic better using JOIN.


text:
Q: javascript inside php wordpress Sorry for the basic question, just a bit confused as to what is going on here.
I have some PHP running in Wordpress, I am able to run html, php and javascript all from within one file. For example:
<?php
//query WP for the tag

$wp_getTag = $wpdb->get_results(
    "
    SELECT name
    FROM $wpdb->mydb_wor1.ukj_terms
    INNER JOIN ukj_term_taxonomy
    ON (
        ukj_terms.term_id = ukj_term_taxonomy.term_id
        )
    WHERE ukj_term_taxonomy.taxonomy LIKE 'post_tag'
    "
);

$json = json_encode($wp_getTag);

?>

<script type="text/javascript">
// pass the value to js

var JsonTags = <?php echo $json ?>;

</script>

So all the above works.
I am grabbing some info from wp and then assigning it's value to a JS variable using echo.
But it is not clear what is going on here? is the Javascript running on the server instead of the client?

A: No, the JavaScript is running on the client.  The PHP is running on the server.  That is, this code runs on the server:
<?php echo $json ?>

The evaluation of that code results in a string being emitted to the client in that location of the output.  So, if the variable $json contains the string "{ 'value' : 'hello world' }" then this code would then run on the client:
var JsonTags = { 'value' : 'hello world' };

First all the server-side code runs, which ultimately results in a response to the client.  Once that response is received by the client, all the client-side code runs.

A: The server is outputting information into the client side, hence the function name 'echo' (it echo's from the server onto the client side).
You're able to mix server side code into client side code as a result as it's processed by the server first, this is why you can't (without the use of Ajax) effect server side code with Javascript.


text:
Q: How to query second 10 records order by date in varchar format in DB2 assuming below table;
column name | type
id          | int
date        | varchar

When I use
SELECT ROWNUMBER() OVER( ORDER BY TYPE_DATE ) as ROWID,
       TO_DATE( date, 'mm\dd\yyyy' ) as TYPE_DATE,
       *
FROM TABLE

I always get below error:
SQL0104N an expected token "*" was found following .... <select_sublist>

here are three questions:

*

*Why can't * be used here?

*Why can't this new column be used in OVER()

*How can I get the set of second 10 records, order by a formatted column

A: To answer your first question, it is because you have designated additional columns, and DB2 is unable expand this * to a column list.  You can fix this by adding a table identifier FROM TABLE T, and using the exposed identifier to expand the column list SELECT ..., T.*
As you can see on this chart from the Information Center, you can only have EITHER * OR expressions and exposed-name.*
>--+-*-----------------------------------------------+---------><
| .-,-------------------------------------------. |
| V                                             | |
'---+-expression--+-------------------------+-+-+-'
    |             | .-AS-.                  | |
    |             '-+----+--new-column-name-' |
    '-exposed-name.*--------------------------'

For two and three, the column can't access the value of a function in the same SELECT clause by referring to it by its alias.  You can push it lower into a sub-select, and then use the OVER() function.  You can then get the rows you want by adding a BETWEEN:
SELECT ROWNUMBER() OVER( ORDER BY TYPE_DATE ) as ROWID, T1.*
FROM (
    SELECT TO_DATE( date, 'mm\dd\yyyy' ) as TYPE_DATE, T.*
    FROM TABLE T
) T1
WHERE ROWNUMBER() OVER( ORDER BY TYPE_DATE ) BETWEEN 10 AND 20
ORDER BY TYPE_DATE


text:
Q: About Operating system States In a non-preemptive CPU scheduling scheme, can the scheduling take place when a process
or thread switches from the waiting state to the ready state? Why

A:
In a non-preemptive CPU scheduling scheme, can the scheduling take place when a process or thread switches from the waiting state to the ready state?

Yes, but only if a CPU is idle; otherwise (if all CPUs have a currently running task and none are idle) you'd have to preempt a currently running task (and it wouldn't be non-preemptive).