text:
Q: converting unix time to string time with date command I have read the man pages for date command, but there is no option for converting unix time to string time. I found some websites telling this:
date -d @1343715322

there is no option like @ in the man and info pages. Can someone explain it?

A: You usually won't find details like this in the man pages.
Check the info date, you will find this in the "Date input formats" section.

A: It's in the GNU date manual: http://www.gnu.org/software/coreutils/manual/coreutils.html#Seconds-since-the-Epoch. The same explanation is in the coreutils info pages.

If you precede a number with '@', it represents an internal time stamp
  as a count of seconds. The number can contain an internal decimal
  point (either '.' or ','); any excess precision not supported by the
  internal representation is truncated toward minus infinity. Such a
  number cannot be combined with any other date item, as it specifies a
  complete time stamp.
Internally, computer times are represented as a count of seconds since
  an epoch—a well-defined point of time. On GNU and POSIX systems, the
  epoch is 1970-01-01 00:00:00 utc, so '@0' represents this time, '@1'
  represents 1970-01-01 00:00:01 utc, and so forth. GNU and most other
  POSIX-compliant systems support such times as an extension to POSIX,
  using negative counts, so that '@-1' represents 1969-12-31 23:59:59
  utc.
Traditional Unix systems count seconds with 32-bit two's-complement
  integers and can represent times from 1901-12-13 20:45:52 through
  2038-01-19 03:14:07 utc. More modern systems use 64-bit counts of
  seconds with nanosecond subcounts, and can represent all the times in
  the known lifetime of the universe to a resolution of 1 nanosecond.
On most hosts, these counts ignore the presence of leap seconds. For
  example, on most hosts '@915148799' represents 1998-12-31 23:59:59
  utc, '@915148800' represents 1999-01-01 00:00:00 utc, and there is no
  way to represent the intervening leap second 1998-12-31 23:59:60 utc.


text:
Q: Repeating a block matrix many times in diagonal part of a block matrix, with the off-diagonal blocks all zero matrices? I would like to create a block diagonal matrix with the diagonal blocks being repeated a certain number of times, with the off-diagonal blocks being all zero matrices. For example, suppose we start with a matrix with the following:
> diag.matrix

       [,1] [,2] [,3] [,4] [,5]
  [1,]  1.0  0.5  0.5  0.5  0.5
  [2,]  0.5  1.0  0.5  0.5  0.5
  [3,]  0.5  0.5  1.0  0.5  0.5
  [4,]  0.5  0.5  0.5  1.0  0.5
  [5,]  0.5  0.5  0.5  0.5  1.0

I would like this matrix to be the diagonal block matrix so that in the end I have something like:
       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]  1.0  0.5  0.5  0.5  0.5  0.0  0.0  0.0  0.0   0.0
 [2,]  0.5  1.0  0.5  0.5  0.5  0.0  0.0  0.0  0.0   0.0
 [3,]  0.5  0.5  1.0  0.5  0.5  0.0  0.0  0.0  0.0   0.0
 [4,]  0.5  0.5  0.5  1.0  0.5  0.0  0.0  0.0  0.0   0.0
 [5,]  0.5  0.5  0.5  0.5  1.0  0.0  0.0  0.0  0.0   0.0
 [6,]  0.0  0.0  0.0  0.0  0.0  1.0  0.5  0.5  0.5   0.5
 [7,]  0.0  0.0  0.0  0.0  0.0  0.5  1.0  0.5  0.5   0.5
 [8,]  0.0  0.0  0.0  0.0  0.0  0.5  0.5  1.0  0.5   0.5
 [9,]  0.0  0.0  0.0  0.0  0.0  0.5  0.5  0.5  1.0   0.5
[10,]  0.0  0.0  0.0  0.0  0.0  0.5  0.5  0.5  0.5   1.0

Here, we have the same block matrix above repeated twice in the block diagonals. If I wanted to do this efficiently an arbitrary number of times, is there a way to do it? thanks!

A: 1) kronecker If M is your matrix and k is the number of times you want it repeated then:
kronecker(diag(k), M)

For example,
M <- matrix(0.5, 5, 5) + diag(0.5, 5)
k <- 2
kronecker(diag(k), M)

giving:
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]  1.0  0.5  0.5  0.5  0.5  0.0  0.0  0.0  0.0   0.0
 [2,]  0.5  1.0  0.5  0.5  0.5  0.0  0.0  0.0  0.0   0.0
 [3,]  0.5  0.5  1.0  0.5  0.5  0.0  0.0  0.0  0.0   0.0
 [4,]  0.5  0.5  0.5  1.0  0.5  0.0  0.0  0.0  0.0   0.0
 [5,]  0.5  0.5  0.5  0.5  1.0  0.0  0.0  0.0  0.0   0.0
 [6,]  0.0  0.0  0.0  0.0  0.0  1.0  0.5  0.5  0.5   0.5
 [7,]  0.0  0.0  0.0  0.0  0.0  0.5  1.0  0.5  0.5   0.5
 [8,]  0.0  0.0  0.0  0.0  0.0  0.5  0.5  1.0  0.5   0.5
 [9,]  0.0  0.0  0.0  0.0  0.0  0.5  0.5  0.5  1.0   0.5
[10,]  0.0  0.0  0.0  0.0  0.0  0.5  0.5  0.5  0.5   1.0

1a) %x% The last line of code can alternately be written as:
diag(k) %x% M

2) Matrix::bdiag Another possibility if you want to save space is to create a sparse matrix of class "dgMCatrix".  It does not store the zero values.  See ?bdiag :
library(Matrix)

bdiag(replicate(k, M, simplify = FALSE))

giving:
10 x 10 sparse Matrix of class "dgCMatrix"

 [1,] 1.0 0.5 0.5 0.5 0.5 .   .   .   .   .
 [2,] 0.5 1.0 0.5 0.5 0.5 .   .   .   .   .
 [3,] 0.5 0.5 1.0 0.5 0.5 .   .   .   .   .
 [4,] 0.5 0.5 0.5 1.0 0.5 .   .   .   .   .
 [5,] 0.5 0.5 0.5 0.5 1.0 .   .   .   .   .
 [6,] .   .   .   .   .   1.0 0.5 0.5 0.5 0.5
 [7,] .   .   .   .   .   0.5 1.0 0.5 0.5 0.5
 [8,] .   .   .   .   .   0.5 0.5 1.0 0.5 0.5
 [9,] .   .   .   .   .   0.5 0.5 0.5 1.0 0.5
[10,] .   .   .   .   .   0.5 0.5 0.5 0.5 1.0

2b) Diagonal or to create a sparse matrix of class "dgTMatrix" :
Diagonal(k) %x% M

redpajama_set_name: RedPajamaStackExchange


text:
Q: Schröder–Bernstein for representations of operator algebras This is claimed in a Wikipedia Article:

If two representations (of a $C^*$-algebra $A$) $\rho$ and $\sigma$, on Hilbert spaces $H$ and $G$ respectively, are each unitarily equivalent to a subrepresentation of the other, then they are unitarily equivalent.

I don't really follow the proof given.  Indeed, what bothers me is the following: if we let $I,J$ be sets and $f:I\rightarrow J, g:J\rightarrow I$ be injections inducing isometries $\ell^2(I)\rightarrow\ell^2(J)$ and $\ell^2(J)\rightarrow\ell^2(I)$ and we just let $A$ be the complex numbers, then the claim is that there is a unitary $U:\ell^2(I)\rightarrow\ell^2(J)$.  But furthermore, the proof indicates that $U$ is constructed from the original isometries, so $U$ maps basis vectors to basis vectors and hence immediately induces a bijection $I\rightarrow J$.  That is, we seem to have reproved Schröder–Bernstein using nothing but induction...
Indeed, I am fairly sure I can prove this result using Schröder–Bernstein for projections, working with $\lambda=\pi\oplus\rho$ and using comparison of projections in $\lambda(A)'$.  Notice that in the projection case, using the notation of the Wikipedia article, you need to consider $R$.

Am I correct to be a little worried?

Furthermore, Schröder–Bernstein for projections is very standard, and in lots of books.  Perhaps I have just not looked hard enough, but I cannot find a textbook proof of the result for the representations.

Is there a reference to this result in a textbook or paper?

Edit: Let me re-write the Wikipedia proof, in the special setting I outlined about.  It boils down to observing that we can partition $I = I' \sqcup g(J)$ and $J = J' \sqcup f(I)$ and then repeatedly applying $f$ and $g$, so
$$ J = J' \sqcup f(I) = J' \sqcup f(I') \sqcup fg(J)
= J' \sqcup f(I') \sqcup fg(J') \sqcup fgf(I) = \cdots $$
and
$$ f(I) = f(I') \sqcup fg(J) = f(I') \sqcup fg(J') \sqcup fgf(I) = \cdots $$
But now we come to Ruy's objection: you cannot conclude that e.g.
$$ J = \bigsqcup_{n\geq0} (fg)^n(J') \sqcup \bigsqcup_{n\geq 0} (fg)^nf(I') $$
The argument (for example) completely missing the possibility of "cycles", in Andreas's language.
So, I think I've answer my first question.  I know how to prove the result.  I am still interested in an actual reference in e.g. a textbook.


text:
Q: Python: an up-to-date GUI debugger for Python2.7 and Python3.x, without IDE I am looking for a Python debugger with the following features:

*

*Up-to-date - I searched in the web and found debuggers that were last updated in 2009-2010. This is too old and implies that is not supported anymore...

*Has GUI

*Is standalone - I don't want to load a whole IDE for debugging some released application

*Supports Python2.7 and Python 3.x
Can you recommend me on such a debugger?
EDIT:
From research and from the answers, it seems that there is no debugger that satisfies all the requirements:

*

*winpdb was last updated in 2009/2010

*pudb GUI is console based (Like vi editor) - not very convenient and modern

*Other standalone debuggers have no GUI at all

*Other debuggers are not standalone, but are a part of IDEs - not convenient for debugging released applications
If there's an update - I'll write it here...

A:
https://pypi.python.org/pypi/pudb

or

http://winpdb.org/about/

I guess. Haven't used either though.

A: Maybe you will approach this http://pybee.org/bugjar/. This debugger has not all features, but it works.


text:
Q: Is there a way to override OnNavigatedTo in WPF on a page? I know it exists on Silverlight but how about WPF?

A: Read this part of the MSDN
Page navigation in WPF is different from Silverlight/Phone because you can opt -in for KeepAlive.
In short: use Loaded and Unloaded. KeepAlive will only influence whether or not a new instance is created.
EDIT
An alternative is to subscribe to the this.NavigationService.Navigated event but that does not get raised just for your page as far as I know.


text:
Q: giving a type signature to `_` in haskell I want to associate _ with coerce yet I can't give a type signature to it.
Is there any trickery to get around that ?
import Data.Coerce

ok :: ()
ok =
  let a = _ "hi"
   in let a :: String = __ "Hi"
       in ()
  where
    _ = undefined
    __ :: Coercible a b => a -> b
    __ = coerce

ko =
  let a = _ "hi"
   in let a :: String = __ "Hi"
       in ()
  where
    __ = undefined
    _ :: Coercible a b => a -> b. -- Invalid type signature: _ :: ... Should be of form <variable> :: <type>parser
    _ = coerce

A: _ is a reserved name which can not be redefined. It can be used in patterns as a wildcard, e.g.
let (_,x) = ....           -- takes the second component
    (_,_,_,x,_) = ....     -- takes the fourth component
    _ = ....               -- does not bind any variable
in ....

Unlike other variable names, it can appear more than once in a pattern.
It can also be used as a hole: e.g.,
let a = _ "hi"

triggers the special error
• Found hole: _ :: [Char] -> t
  Where: 't' is a rigid type variable bound by
           the inferred type of a :: t

Essentially, _ "hi" asks the compiler to provide which type a term t should have to make the whole expression type-check when hole _ is replaced by t.
Therefore, your ok esample is not really OK, but triggers the above special error.


text:
Q: object name for checkbox and sql command to populate more than one table I have an database with 3 tables, I want to add data to it in my java aplication...
String command1 = "INSERT INTO Drivers (IDNumber, FirstName, LastName) VALUES" + drivID + FName + LName;

Can I use this command to enter data in all 3 tables or do I have to create 3 commands like this to use in the following prepared statement
PreparedStatement p = conn.getStatement(command1);

Allso in my tables I have checkboxes and strings
I made String variables as follow
String drivID = txtid.getText();

Can someone tell me what the object name for a checkbox is

A: String command1 = String.format("INSERT INTO %s (IDNumber, FirstName, LastName) VALUES (%s, %s, %s)", tableName, ID, fName, lName);
PreparedStatement p = conn.getStatement(command1);

Although, for your example, I see no reason why you cannot use a java.sql.Statement instead of a PreparedStatement.


text:
Q: How to make fields of pivot table updatable? In laravel 9 I have table pivot table defined :
    Schema::create('article_vote', function (Blueprint $table) {
        $table->id();
        $table->foreignId('article_id')->references('id')->on('articles')->onUpdate('RESTRICT')->onDelete('CASCADE');
        $table->foreignId('vote_id')->references('id')->on('votes')->onUpdate('RESTRICT')->onDelete('CASCADE');
        ...
    });

and having in both models methods with  belongsToMany
I can refer articles of a vote as :
$voteArticles = $vote->articles;

But when I try to update some data in article_vote table:
        $voteArticles = $vote->articles;
        \Log::info(varDump($voteArticles, ' -197 $voteArticles::'));

        $voteArticleUpdatedCount = 0;
        DB::beginTransaction();
        foreach ($voteArticles as $voteArticle) {
            try {
                $voteArticle->update($updateData); // I check these values in $updateData are diffrerent from data in  $voteArticle
                DB::Commit();
            } catch
            (\Exception $e) {
                DB::rollback();

                return sendErrorResponse($e->getMessage(), HTTP_RESPONSE_INTERNAL_SERVER_ERROR);
            }
        }

In database trace I see
   BEGIN;

   COMMIT;

statements but not any update statements. Looks like $voteArticle var can not be updated...
How to make it updatable ?
Thanks!


text:
Q: How to stop a user from updating the post date I have a custom role, called "dealer". Once they have posted a new post, they cannot delete it. It's important they cannot update the date either, and I'm a little stuck on how to do this. It looks like the old D/M/Y is preserved in the $_POST global, so I thought I'd over write any updated information for the date with this. Check out my code;
function rd_dealer_save_post($post_id)
{
$post_author_id = $_POST['post_author'];
//print_r($_POST);
//test if this author is a dealer based on the caps
if(!current_user_can('delete_published_posts'. $post_author_id))
{
    $_POST['mm'] = $_POST['hidden_mm'];
    $_POST['jj'] = $_POST['hidden_jj'];
    $_POST['aa'] = $_POST['hidden_aa'];
    $_POST['hh'] = $_POST['hidden_hh'];
    $_POST['mn'] = $_POST['hidden_mn'];
}
print_r($_POST);
//die();
}
add_action('save_post', 'rd_dealer_save_post');

Is my action correct? Any thoughts as this doesn't seem to work...
Thanks, Dan.

A: As @t-f pointed out in his comment to question, you have an error on checking current user capability: 'delete_published_posts'. $post_author_id simply doesn't exist.
After that, for your scope probably is a better hookin the filter wp_insert_post_data instead of the action save_post: because this one run when the post was already saved / updated, so if something is wrong you have to change and update again.
Hooking wp_insert_post_data filter, you can change the data that are being updated before update is ran, so this will improve performance.
add_filter('wp_insert_post_data', 'prevent_post_change', 20, 2);

function prevent_post_change( $data, $postarr ) {
  if ( ! isset($postarr['ID']) || ! $postarr['ID'] || current_user_can('delete_published_posts') )
    return $data;
  $old = get_post($postarr['ID']); // old post
  // prevent changing date
  $data['post_date'] =  $old->post_date
  $data['post_date_gmt'] =  $old->post_date_gmt
  // prevent sent to trash
  if ( $data['post_status'] == 'trash' ) $data['post_status'] = $old->post_status;
  return $data;
}


text:
Q: Quick blox chat message sending response is success but messages are not delivered to server Just working with Quick blox Chat API though its interesting and fun but stuck horribly when coming to sending messages successfully to group.
I first created a ChatDialog(not public group) and its created with out any problems.Now i want to send messages to the ChatDialog.
This is the code at Client side in Swift :
    let user = QBUUser()
    user.ID = (QBSession.currentSession().currentUser?.ID)!
    user.password = "*********"
    QBChat.instance().connectWithUser(user) { (error: NSError?) -> Void in
        if error == nil{
            print("Success in connection")
            self.chatGroup = QBChatDialog(dialogID:self.selectedChatGroup.chatGroupId, type: QBChatDialogType.Group)
            self.chatGroup.occupantIDs = self.selectedChatGroup.opponents
            self.chatGroup.joinWithCompletionBlock { (err) in
                if err == nil{
                    print("Joined Succesfully")
                    let message: QBChatMessage = QBChatMessage()
                    message.text = "PRAISE THE LORD"
                    message.deliveredIDs = [(QBSession.currentSession().currentUser?.ID)!]
                    message.readIDs = [(QBSession.currentSession().currentUser?.ID)!]
                    message.markable = true

                    self.chatGroup.sendMessage(message, completionBlock: { (error: NSError?) -> Void in

                        if err == nil{
                            print(message.text)
                            print("Message sent Succesfully")

                            let resPage = QBResponsePage(limit:20, skip: 0)

                            QBRequest.messagesWithDialogID(self.selectedChatGroup.chatGroupId, extendedRequest: nil, forPage: resPage, successBlock: {(response: QBResponse, messages: [QBChatMessage]?, responcePage: QBResponsePage?) in

                                print("Messages count is \(messages?.count)")

                                }, errorBlock: {(response: QBResponse!) in

                            })

                        }else{
                            print(err?.localizedDescription)
                        }

                    });
                }
                else{
                    print(err?.localizedDescription)
                }
            }

        }
    }

This is the Response that i am getting back.i am pretty sure that logging to chat, connecting to group are successful. Even from the response given back from the API is also affirming that sending message is successful.But i am not able to see any messages in the Admin Panel at Quick blox. And also tried getting all the messages from the Chat dialog but its giving 0 messages.So my messages are not getting delivered.

A: Yah, got the solution from Quickblox API.This is what i missed in my code.
    var params = NSMutableDictionary()
    params["save_to_history"] = true
    message.customParameters = params

Worked like a charm!


text:
Q: Laravel: How to show form after submission? I am new to Laravel and currently working on a project where the guests enter form data for booking a room in a hotel and after submitting it, they will be redirected to a page showing their booking they have just done. I know this can be done by allowing guests to create login account but my project requires login only for the backend(admin). (Q2.)Also the guests can view booking by entering the booking ID and their last name.
My controller:
public function store(Request $request)
   {
      $book = new book();
      $book->title = $request->input('title');
      $book->fname = $request->input('firstname');
      $book->lname = $request->input('lastname');
      $book->country = $request->input('country');
      $book->phone = $request->input('phone');
      $book->email = $request->input('email');
       $book->no_rooms = $request->input('no_rooms');
       $book->room_type_id = $request->input('type_room');
       $book->no_adults = $request->input('adults');
       $book->no_children = $request->input('children');
       $book->meal_id = $request->input('meal');
       $book->check_in = $request->input('check_in');
       $book->check_out = $request->input('check_out');
       $book->save();
   }
   public function show(book $book)
{

   return view('book.show', compact('book'));
}

The way I want it to display after it has been submitted:

 Name:
 {{$book->title}}   {{$book->firstname}}   {{$book->lastname}}

 Phone
 {{$book->phone}}

 Email
 {{$book->email}}

 Phone
 {{$book->phone}}

 Passport Issued:
 {{$book->country}}

 Number of rooms:
 {{$book->no_rooms}}

 Room Type
 {{$book->type_room}}

 No of adults:
 {{$book->adults}}

 No of children:
 {{$book->children}}

 Meal plan:
 {{$book->meals_id}}

 Check-in:
 {{$book->check_in}}

 Check-out:
 {{$book->check_out}}

A: You can redirect to the show method from the bottom of your store method:
// Replace MyController with the name of your controller
return redirect()->action(
    'MyController@show', ['book' => $book]
);

For more information check out the documentation: https://laravel.com/docs/master/redirects#redirecting-controller-actions

A: If I understand correctly your situation, you wish to show the same data introduced by the user after form submission.
I can think that redirecting to a page that show your div without anything else, is not enough. You'll still need to access to data entered in the form.
Laravel store form data in a session variable called old, according to documentation, that variable should be available during next request after submission, so you could try to get data using

             Name:
             {{ old('title') }}   {{ old('firstname') }}   {{ old('lastname') }}

             Phone
             {{ old('phone') }}

             Email
             {{ old('email') }}

             Phone
             {{ old('phone') }}

             Passport Issued:
             {{ old('country') }}

             Number of rooms:
             {{ old('no_rooms') }}

             Room Type
             {{ old('type_room') }}

             No of adults:
             {{ old('adults') }}

             No of children:
             {{ old('children') }}

             Meal plan:
             {{ old('meals_id') }}

             Check-in:
             {{ old('check_in') }}

             Check-out:
             {{ old('check_out') }}

Just in case that you don't have old data available in your session because a successive redirect, you should inject that data in your session using flash.
You can find more detailed information here, in laravel documentation

A: You can just use the laravel helper redirect()
return redirect()->route('route name here');

or
return redirect('your-form-path');

read more here: laravel http redirects


text:
Q: Creating a co-occurrence table from a log in a dataframe I have a usage log in a pandas data frame:
event_time   session_id      object
10:00:03      1             A
10:00:03      1             B
10:00:03      1             C
10:00:03      1             E
10:00:03      2             J
10:00:03      2             O
10:00:03      2             A
10:00:03      2             A

I have grouped the objects by session_id. I now want to build a co-occurrence matrix of objects against objects with each cell for any given pair of objects containing the number of times those objects co-occur in a group (i.e. against the same session_id): Something along the following lines:
   A    B      C   ...
A  20   1     12
B  1   100     9
C  12   9     30
...

Is there a way to have the above in dict form so all non-zero occurrences are not represented for any given object 'key'?
Clearly the matrix will be triangular. Is there a way to pivot the matrix into a molten data table of the form:
Object 1   Object 2    # of co-occurences
  A           A                20
  A           B                1
 ...         ...              ...

Thanks in advance for any help.
UPDATE: I am running the algos for prototyping on 12MB of data, but will run 'for real' on AMAZON on c. 2-3 GB of data from a multi-TB data set. I dont think GB is quite Pig territory - the more efficient the suggested the answer the better
I want to to be able to look up objects in the dictionary and then see all of the objects that co-occur with them and the counts (may end up indexing this structure in Solr in the future)

A: Your input
In [80]: df
Out[80]:
  event_time  session_id object
0   10:00:03           1      A
1   10:00:03           1      B
2   10:00:03           1      C
3   10:00:03           1      E
4   10:00:03           2      J
5   10:00:03           2      O
6   10:00:03           2      A
7   10:00:03           2      A

[8 rows x 3 columns]

This is the session_id counts matrix. Get's you most of the way there. (You can of course fill then nas if you want)
In [81]: df.groupby('session_id').apply(lambda x: x['object'].value_counts()).unstack()
Out[81]:
            A   B   C   E   J   O
session_id
1           1   1   1   1 NaN NaN
2           2 NaN NaN NaN   1   1

[2 rows x 6 columns]

A: You can use pivot_table:
In [11]: df.pivot_table('event_time', 'session_id', 'object',
                         aggfunc=len, fill_value=0)
Out[11]:
object      A  B  C  E  J  O
session_id
1           1  1  1  1  0  0
2           2  0  0  0  1  1


text:
Q: Router_Route with optional parameters I have the following route:
        $gridRoute = new Zend_Controller_Router_Route(
        ':module/:controller/list/:order/:dir/:page',
        array (
            'module' => 'default',
            'controller' => 'index',
            'order' => '',
            'dir' => 'asc',
            'page' => 1,
            'action' => 'list'
        ),
        array (
            'page' => '\d+'
        )
    );
    $router->addRoute('grid', $mainRoute->chain($gridRoute));

I would like to be able to add an optional parameter 'filter' to this route. So I could use the following url:
http://example.org/default/list/filter/all/lname/asc/1
or
http://example.org/default/list/lname/asc/
or
http://example.org/default/list/filter/all
Either one should work. I tried to place an optional parameter in the Route but that did not work. Any ideas?

A: Typically, in Zend's Router, like in PHP, an optional parameter is a parameter that has a default value. Add one for the filter parameter:
$gridRoute = new Zend_Controller_Router_Route(
    ':module/:controller/list/:order/:dir/:page/:filter',
    array (
        'module' => 'default',
        'controller' => 'index',
        'order' => '',
        'dir' => 'asc',
        'page' => 1,
        'action' => 'list',
        'filter' => null, // define default for filter here
    ),
    array (
        'page' => '\d+'
    )
);


text:
Q: Flex - Request for crossdomain.xml is attempting to use https on an http port and timing out My Flex application is being hosted at http://<ip>:8080/MyApp/Login.html, when I go there there is a request for http://<ip>:8080/crossdomain.xml is created, as well as a request for https://<ip>:8080/crossdomain.xml. This happens when I attempt to use a Remote Java Object call to the same server, and grab assets from it. I am not hosting https on port 8080, therefore this https call will fail.
The problem is that the https call will sometimes take a long time to fail (it fails by the connectionTimeout length in the tomcat connector). Other times it fails quickly. However, in the times that it does take a long time to fail, the page doesn't complete loading because I'm waiting on those assets and the remote object calls for data.
I've tried setting up a forceful retrieval of a crossdomain.xml with the following inside it:
<?xml version="1.0"?>
<cross-domain-policy>
    <allow-access-from domain="*" to-ports="*"/>
</cross-domain-policy>

With the AS3 code:
Security.loadPolicyFile(browserUrl+"/assets/crossdomain.xml");

Which is being called in the application's initialize event. The above, forceful, crossdomain.xml file is being called and retrieved correctly according to chrome and wireshark, but the default locations at the root of the server are still being attempted, and the https attempt is still timing out. And the app is not completing its loading until that attempt times out.

A: So I think I determined what this issue was. I had a secure channel being used first in the list of channels, and since it was different domain (http instead of the https that the channel was on) it would do the crossdomain.xml lookup.
I reordered the channels to have the regular http channel first, and my application no longer does any crossdomain lookups except the forceful one (which I've since removed).
Since the first channel was over https, Flex was waiting on that lookup before falling back to the insecure channel.
I also think this should continue to work if actually using https, since I believe that a plaintext request to a secure connector will be rejected instantly instead of timing out.


text:
Q: FFmpeg slideshow with images of different dimensions I have .jpg files like (img001.jpg), each of them with different dimensions. I also have an audio file .ogg. I wanna create slideshow with audio but I have a scaling problem, because the image dimensions are different.
ffmpeg -r 1/2 -i img%03d.jpg -i example.ogg -s 1920x1080 AL_SlideShow.mkv

(2 second image change interval, x265 1920*1080)
And sound only plays last 30 second I think.

A: You have to scale the images to a common size. Add a scale video filter:
ffmpeg -r 1/2 -i img%03d.jpg -i example.ogg \
-vf "scale=1920:1080,format=yuv420p" \
AL_SlideShow.mkv

If you want to use libx265, you need to specify -c:v libx265 as well.
You may want to add -shortest before the output filename to stop the encoding when all images have been read. That way, the audio stream will be cut.


text:
Q: Parsing a string to decimal works on Windows 8 but not on windows 7 I have a method that takes a string value and parses it into decimal.  That works perfectly on windows 8.1 but when i test the application on windows 7 it fails.
Windows 7 does have Dot net Framework 4.5 installed.
What could be the problem?
Here's the method:
void Save_Details()
{
     //The customer enters dots instead of commas to specify a decimal place
     string Ammount_Now = textbox1.Text.Replace('.', ',');//value text entered is 123.34
     //The value of Ammount_Now is now 123,34
     decimal value = 0;
     bool Ammount_Good = decimal.TryParse(Ammount_Now, out value);

     if(Ammount_Good)
     {
           //continue with method
           // windows 8 returns true in the decimal.TryParse()
           // windows 7 returns false in the decimal.TryParse()
           // They both use .net framework 4.5
     }
     else
     {
            //failed parsing
     }

}

A: There's nothing wrong with the OS versions, you tested the code in machines with different locales.
There's also no need to replace decimal marks to "fix" them as long as you use the proper CultureInfo when parsing. If the input text is always expected to use . as the decimal mark, you should use the Decimal.TryParse Method (String, NumberStyles, IFormatProvider, Decimal) overload:
decimal.TryParse(Amount_Now,NumberStyles.Number,CultureInfo.InvariantCulture,out value)


text:
Q: Android Studio - Illegal character 8204 error For some reason, after rebuilding my project I get an illegal character error but nothing within my code gets underlined in red. Can someone please tell me what is wrong and how to resolve it?
Error
illegal character: \8204

WCBankActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;

public class WCBankActivity extends ActionBarActivity {

    public final static String EXTRA_MESSAGE = "Station_key";

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

        if (savedInstanceState == null) {
            Intent intent = getIntent();
            String station = intent.getStringExtra(WCBankActivity.EXTRA_MESSAGE);

            FragmentWCBank newFragment = new FragmentWCBank();
            FragmentTransaction transaction = this.getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.detail_container, newFragment);
            transaction.commit();
        }
    }
}

A: Try changing your encoding, see the image:

A: That's a problem related to BOM (Byte Order Mark) character. Eclipse doesn't allow this character.
Just copy paste the same content to a Notepad++ editor,
it shows the "LS" with black background. Have deleted the "LS" content and
have copy the same content from notepad++ to java file, it works fine.


text:
Q: In DB2 for z/OS, can I rebuild multiple indexspaces with one command? On DB2 for z/OS version 10, an errant utility left MANY indexspaces in a status of "RW,RBDP" within a specific database. I can successfully use the REBUILD INDEXSPACE command to fix them one-by-one, but there are A LOT of them. So, I was hoping for some kind of wild-card or *ALL option, but that doesn't yet work for me.
Is there a way to do the equivalent of the following?
REBUILD INDEXSPACE (MYDB.*)
Thanks in advance!

A: You can't do an entire database at a time, but you could do some queries along with a LISTDEF to get a similar result.
First, find the indexes in question:
SELECT '  INCLUDE INDEX ' || RTRIM(CREATOR) || '.' || RTRIM(NAME)
FROM SYSIBM.SYSINDEXES
WHERE DBNAME = 'MYDB'

That will give you the list of indexes related to that database. Then, you can take the results as part of a larger LISTDEF. Here's some example JCL (honestly, I'm not sure how much of this is specific to my shop, so there may be some changes required):
//*****************************************************
//*  RUN REBUILD INDEX UTILITY
//*****************************************************
//IXRBREST EXEC PGM=IEFBR14 DUMMY STEP FOR RESTART
//IXRBUTIL EXEC DB2UPROC,SYSTEM=DB2T,COND=(4,LT)
//STEPLIB DD DSN=DB2.PROD.SDSNLOAD,DISP=SHR
//DB2UPROC.SYSIN DD *
LISTDEF INDEXES
  <insert generated list here>

REBUILD INDEX LIST INDEXES
      SORTKEYS SORTDEVT SYSDA SHRLEVEL CHANGE
      STATISTICS REPORT YES UPDATE ALL
      MAXRO 240 LONGLOG CONTINUE DELAY 900 TIMEOUT TERM
      DRAIN_WAIT 50 RETRY 6 RETRY_DELAY 30

That should get you the indexes that need to rebuild. If there are some that need to be rebuilt, and some that are fine, you could add SCOPE PENDING to the REBUILD INDEX utility, and it will only rebuild those in a pending state.

A: The alternative to REBUILD is to do a DROP/CREATE. This is necessary when the datasets are missing or damaged. Unless you specify DEFER on index create, you get a REBUILD for free. DB2 extracts the index from the tablespace VSAM Linear in all cases.


text:
Q: Extending my Java API to C++ through JNI: How to wrap a method returning a String? I am using JNI to extend my API in Java, in order to make it accessible through C++ (I am creating wrapper classes). I am experienced in Java but new to C++.
Now, I am creating a wrapper in C++ for a Java function getString() which returns a String. I am using GetStringUTFChars to get the C string from the Java String but I don't know where to use ReleaseStringUTFChars which releases the C string. Here is my code (aClass and aClassInstance are private date members inside the wrapper class):
const char* getString() {
jmethodID methodID = env->GetMethodID(aClass,
        "methodName",
        "()Ljava/lang/String;");
if (methodID == NULL) {
    cout << "--methodID = NULL";
    exit(0);
}
jstring jstringResult = (jstring) env->CallObjectMethod(aClassInstance, methodID);
const char* result = env->GetStringUTFChars(jstringResult, NULL);
// env->ReleaseStringUTFChars(jstringResult, result);
return result;
}

If I remove the // and use ReleaseStringUTFChars, result will be released and I will no longer be able to return it, right? Should I copy result to another char array before releasing it?
Thanks, any help is welcome!
K

A: Mahesh is right
std::string getString()
{
    jmethodID methodID = env->GetMethodID(aClass,
        "methodName",
        "()Ljava/lang/String;");
    if (methodID == NULL)
    {
        cout << "--methodID = NULL";
        exit(0);
    }
    jstring jstringResult = (jstring) env->CallObjectMethod(aClassInstance, methodID);
    const char* result = env->GetStringUTFChars(jstringResult, NULL);
    std::string result2(result);
    env->ReleaseStringUTFChars(jstringResult, result);
    return result2;
}

std::string takes copies your characters for you and will automatically free when needed. Using raw pointers in C++ is generally frowned upon. Coming from Java you probably have little idea of the problems they can cause.

A: The most obvious place to call ReleaseStringUTFChars is in your wrapper class' destructor. Use a vector or some other container to record each jstring as it's accessed, and then in your wrapper class' destructor, call ReleaseStringUTFChars on every element in the container. Your clients will need to make copies of the character data if they live longer than the wrapper class object.


text:
Q: Magento on admin order create and frontend checkout returns 500 error after update to 1.9.4.2 Hi guys I have just updated my site to 1.9.4.2. But when I attempt to create an order in admin I get a 500 error. Same happens on frontend onepage checkout.
Tried turning errors on nothing shows.
For enabling error reporting, I did the following:
In Index page change the following:
error_reporting(E_ALL | E_STRICT);

to
error_reporting(E_ALL);

Set $_SERVER['MAGE_IS_DEVELOPER_MODE'] = true

and uncomment this line
#ini_set('display_errors', 1);

In Errors folder rename local.xml.sample to local.xml.
In the .htaccess file I added
SetEnv MAGE_IS_DEVELOPER_MODE=true
php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
php_flag  log_errors on
php_value error_log  /var/www/html/mag19/mag19errorphp.log

The update works well on my local site and no errors. But, on the prod site which is nearly like for like as local site, it throws the 500 redirect error. Refreshing the page on frontend checkout, before the http 500 error is shown, whilst refreshing, I can shortly see
the red cross for error on chrome dev tools. This however disappears before you get to see the error as the http 500 error kicks in.
**

*

*UPDATE 05/07/19:
  Been awhile and and I am none the wiser as to why this happened. I have
  reverted back down to 1.9.4.1 and all is working well.
Backtracing, by carrying out each new change individually. I believe I have stumbled across the root cause. It has to be one of the changes in the Authorizenet module in core. As soon as I carry out those the afore stated error occurs.
Why this module causes issues is beyond me. We do not even use it!!
**
Files changed in Authorizenet module:

**

*

*Update 08-07-19:
        The validate function in the Directpost.php model file looks to be the
        issue cause;
public function validateResponse()
{
    $response = $this->getResponse();
    $hashConfigKey = !empty($response->getData('x_SHA2_Hash')) ? 'signature_key' : 'trans_md5';

    //hash check
    if (!$this->getConfigData($hashConfigKey)
        || !$response->isValidHash($this->getConfigData($hashConfigKey), $this->getConfigData('login'))
    ) {
        Mage::throwException(
            Mage::helper('authorizenet')->__('Response hash validation failed. Transaction declined.')
        );
    }
    return true;
}

**
**

*

*UPDATE 10/07/19:
I have looked into this further and I believe the issue is because production server runs 5.4.x whereas local server is on 5.6.x. Whereby, as per the php official documentation:

Note: Prior to PHP 5.5, empty() only supports variables; anything else will result in a parse error. In other words, the following will not work: empty(trim($name)). Instead, use trim($name) == false.

Thus, when PHP is going to parse this, it will result in a parse error.
Now, as per Magentos' official documentation they "are" supporting:

Whereby, 5.4 support is listed as supported but evidently it does not support this clearlly.
**

A: The problem is solved! namely this was occurring due to incompatibility between PHP 5.4.16-46.el7 and Magento 1.9.4.2.
Yes! their official document states this PHP version is supported. But certain segments of code in their Authorizenet core module are written in a coding structure that is not supported until PHP version 5.5 and above.
Section 1 below will illustrate said segments and how I overcame this.

So why were the errors not showing? (1)
The reason no errors were being displayed or logged in the magento logs was simple.
When the file(s) containing the incompatible segments of code is/are parsed, it will attempt to compile the code. But, when it reaches the incompatible segment it won't understand it and how to process this. Thus, causing a fatal error to be thrown, and in return caused the 500 internal server error.
As stated by interServer:

"The 500 Internal Server Error is the general catch all error when the
  server throws an exception. ... Simply, the 500 Internal Server Error
  is a general http status code that means something has gone wrong on
  the website's server, but the server could not be more specific on
  what that exact problem is."

This then prevented anything to be logged in magento.
As stated by media temple here:

...With any error message, particularly one as broad as the 500
  Internal Server Error, you will first want to check any Apache and PHP
  error logs for your server. These logs can provide valuable context
  related to any code failures or other potential causes of a site
  failure.

How did I overcome this? (2)
As we are all aware, the 1.9.4.2 is a minor update from 1.9.4.1. Where there are some small bug fixes and enhancements. I.e. Escaping HTML and introducing a new mailiciousFilter(). No drastic changes, so this made me ask myself What possibly could have changed that caused this?
From here I formulated a simple plan of action:

*

*Using the fantastic tool DiffMerge, I compared two fresh untouched versions of Magento 1.9.4.2 and 1.9.4.1;

*Then I traversed the list of changes, seeing what was exactly changed in the update. And, sequentially applying and testing each change. Whereby, I Backtracked until the culprit change was identified and scope for possible causes was made smaller;

Please Note: No changes were made on Production site at this point, and as per industry standard done in a like for like staging site.

From here, I was left with a very small scope for the cause. Namely, one perpetrating module: the AuthoriseNet Module, which as stated above, I do not use. But, it would still be parsed/compiled in magento when checking-out.
Analysing the changes in the module I was able to pinpoint that the following files:

*

*../app/code/core/Mage/Authorizenet/Model/Directpost.php

*../app/code/core/Mage/Authorizenet/Model/Directpost/Request.php

*../app/code/core/Mage/Authorizenet/Model/Directpost/Response.php

All have one commonality, where they are passing the return of a function into the empty() function. For example,
`$hashConfigKey = !empty($response->getData('x_SHA2_Hash')) ? 'signature_key' : 'trans_md5';`

This duly causing a parse error, since as stated above in the question update and on the php official documentation:

Prior to PHP 5.5, empty() only supports variables; anything else will
  result in a parse error.

This left two options:

*

*Update the server to PHP 5.5 or above;

*And, amend the incompatible code.

Unfortunately, At this present moment in time Centos officially only supports 5.4. Thus, ruling out option 1. Yes! I am fully aware I could use another repository like the EPEL. But, unfortunately a decision has been made above myself to wait until Centos officially supports a newer version.
Luckily, magento is highly customisable and lends itself to overrides without even needing to create our own module.

Please Note! Never make changes to the core code. Instead make a local override and make changes there. Deepak Mishra (2014) has written a fantastic guide here, where he explains the simplest method to override core files in magento.

Following suite, I made a local override for the three afore bulleted files. And, amended them as guided by Magentary(2019):
--- app/code/core/Mage/Authorizenet/Model/Directpost.php
+++ app/code/local/Mage/Authorizenet/Model/Directpost.php
@@ -389,7 +389,8 @@
     public function validateResponse()
     {
         $response = $this->getResponse();
-        $hashConfigKey = !empty($response->getData('x_SHA2_Hash')) ? 'signature_key' : 'trans_md5';
+       $response_getData_hash = $response->getData('x_SHA2_Hash');
+        $hashConfigKey = !empty($response_getData_hash) ? 'signature_key' : 'trans_md5';

         //hash check
         if (!$this->getConfigData($hashConfigKey)
--- app/code/core/Mage/Authorizenet/Model/Directpost/Request.php
+++ app/code/local/Mage/Authorizenet/Model/Directpost/Request.php
@@ -187,7 +187,8 @@
     {
         $fpTimestamp = time();

-        if (!empty($this->_getSignatureKey())) {
+       $this_getSignatureKey = $this->_getSignatureKey();
+        if (!empty($this_getSignatureKey)) {
             $hash = $this->_generateSha2RequestSign(
                 $this->getXLogin(),
                 $this->_getSignatureKey(),
--- app/code/core/Mage/Authorizenet/Model/Directpost/Response.php
+++ app/code/local/Mage/Authorizenet/Model/Directpost/Response.php
@@ -56,14 +56,17 @@
      */
     public function isValidHash($storedHash, $merchantApiLogin)
     {
-        if (empty($this->getData('x_amount'))) {
+       $this_getData_x_amount = $this->getData('x_amount');
+        if (empty($this_getData_x_amount)) {
             $this->setData('x_amount', '0.00');
         }

-        if (!empty($this->getData('x_SHA2_Hash'))) {
+       $this_getData_x_SHA2_Hash = $this->getData('x_SHA2_Hash');
+       $this_getData_x_MD5_Hash = $this->getData('x_MD5_Hash');
+        if (!empty($this_getData_x_SHA2_Hash)) {
             $hash = $this->generateSha2Hash($storedHash);
             return $hash == $this->getData('x_SHA2_Hash');
-        } elseif (!empty($this->getData('x_MD5_Hash'))) {
+        } elseif (!empty($this_getData_x_MD5_Hash)) {
             $hash = $this->generateHash($storedHash, $merchantApiLogin, $this->getXAmount(), $this->getXTransId());
             return $hash == $this->getData('x_MD5_Hash');

Now, upon clearing cache and other prerequisites of changes, the checkout is working again with no errors whatsoever. This is because magento instead of reading the core files with the incompatible segments, it will read from our local override where we have corrected the segments to be compatible with PHP 5.4.


text:
Q: Enable redux-form and set focus to field I've got disabled form field by default and when user clicks on button Edit, it will enable the field. I also want to set focus on the field, but I don't know how. I've created ref to the field and tried some focus() function on it, but it hasn't worked. You can try it here on sandbox.

A: *

*You must assign the ref to the input element instead of the Field component

*Add an callback to set in your parent component the reference of subcomponent input

*Use the reference to focus the input when pressing the edit button:

https://codesandbox.io/s/rlx390xn6m

A: just HTML's autofocus is much better:
https://davidwalsh.name/autofocus

*

*in react use with camelcase: autoFocus


text:
Q: How is RSA encryption/decryption done in Pycryptodome I am reading the docs for pycryptodome and got confused at over how the is the data encrypted and transmitted to the receiver and then decrypted over there
What I understood is
over at the sender side, the public key of the sender is used to encrypt a piece of data which is then write to a .bin file
from Crypto.PublicKey import RSA
from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES, PKCS1_OAEP

data = "I met aliens in UFO. Here is the map.".encode("utf-8")
file_out = open("encrypted_data.bin", "wb")

recipient_key = RSA.import_key(open("receiver.pem").read())
session_key = get_random_bytes(16)

# Encrypt the session key with the public RSA key
cipher_rsa = PKCS1_OAEP.new(recipient_key)
enc_session_key = cipher_rsa.encrypt(session_key)

# Encrypt the data with the AES session key
cipher_aes = AES.new(session_key, AES.MODE_EAX)
ciphertext, tag = cipher_aes.encrypt_and_digest(data)
[ file_out.write(x) for x in (enc_session_key, cipher_aes.nonce, tag, ciphertext) ]
file_out.close()

over at the receiver (the destination supposed to receive the data) the .bin file is loaded and decrypted using the private key of the receiver
from Crypto.PublicKey import RSA
from Crypto.Cipher import AES, PKCS1_OAEP

file_in = open("encrypted_data.bin", "rb")

private_key = RSA.import_key(open("private.pem").read())

enc_session_key, nonce, tag, ciphertext = \
   [ file_in.read(x) for x in (private_key.size_in_bytes(), 16, 16, -1) ]

# Decrypt the session key with the private RSA key
cipher_rsa = PKCS1_OAEP.new(private_key)
session_key = cipher_rsa.decrypt(enc_session_key)

# Decrypt the data with the AES session key
cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce)
data = cipher_aes.decrypt_and_verify(ciphertext, tag)
print(data.decode("utf-8"))

Now as I understand each one of the sender and the receiver have two .pem files one is public key and the other is private
what I don't understand is: Why do we have a session_key and how is the data decrypted with the private key of the receiver?


text:
Q: Metrics Filters Resolution What resolution (basic monitoring with 5 min period, detailed with 1 min, or high-resolution with 1 sec) do Metric Filters use? And how can I change it or at least see it?

A: Metric filters will only publish the data at 1min resolution.
As the data ages out, these will be rolled up into 5min (for data between 15d and 63d) then into 1h (for the remaining 15 months).
This follows the normal metric retention policy as described in the question "What is the retention period of all metrics?" in the CloudWatch FAQ.
AFAIK subminute resolution is not supported at the moment for metric filters.


text:
Q: Activities behavior I have four activities A,B,C,D. I am passing an text from activity A to Activity B using bundle and Activity B is displaying it nicely. Then i move from Activity B to Activity C and then Activity D. After that i called Activity B from the Activity D with the help of intent and i seeing no text are there in Activity B.
Please suggest me the way to keep the text there, with some code example.

A: You would need to use either FLAG_ACTIVITY_CLEAR_TOP or FLAG_ACTIVITY_REORDER_TO_FRONT.
Without one of these you are creating a new instance of your activity instead of revealing the old one. You can set activity flags on the intent you start from activity D:
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

before you call startActivity.


text:
Q: Prove if sup $S \in S \Rightarrow$ sup $S =$ max $S$ This is might be too easy, but just to make sure I am on the right track.

Prove that if sup $S \in S \Rightarrow$ sup $S =$  max $S$

By definition, the maximum $max$ of a set $S$ is the number that is greater or equal to all the elements of $S$. The supremum $sup$, if in the set, must be greater or equal to all numbers in the set, therefore $sup S = max S$.
Is this correct? Am I missing something?

A: I think you need to prove it rigorously.
$x\leq $ sup $S$ for all $x\in S$. Also $x\leq$ max $S$ for all $x\in S$.
Since sup $S\in S, $ sup $S\leq$ max $S$. Since always max $S\in S,$ max $S\leq $ sup $S$.
So, max $S=$sup $S$

A: It's certainly correct, technically. Stylistically, it feels to me like it's been in the reverse of the logical order. That is to say, the logic seems to flow better as:

The supremum is defined to be greater than or equal to every element in $S$. Given that $s=\sup S$ is a member of $S$, it is thus an element of $S$ greater than or equal to any given element of $S$. This is the definition of the maximum, hence $s$ is the maximum of $S$ as well.

We're trying to conclude something about the maximum given something about the supremum, so it makes sense to start by talking about the supremum.

A: We can prove the reverse as well, that is, if sup S = max S ⇒ sup S ∈ S.
Assume the opposite, that is, sup S ∉ S.
Hence, x < sup S for all x ∈ S.
Also, x ≤ max S for all x ∈ S.
As max S ∈ S always,
Hence, max S < sup S.
This contradicts our assumption that sup S = max S.
Hence, our assumption was wrong.
Hence, sup  S ∈ S.
Hence,  sup S = max S ⇒ sup S ∈ S.
So finally,
sup S ∈ S ⇔ sup S = max S.


text:
Q: Multi-level Inheritance I am having following classes
public class InheritTest{
    Parent p = new Child();
    Child c = (Child)p;
    void someMethod(){
        System.out.println(p.getX()+" "+c.getX());
    }
    public static void main (String [] args){
        InheritTest it = new InheritTest();
        it.someMethod();
    }

    class Child extends Parent{
         int x = 1;
        int getX(){
            return this.x;
        }
    }

}

And
public class Parent{
    int x = 0;
    int getX(){
        return x;
    }
}

When I call, p.getX() and c.getX(), it prints 1 & 1
but when I call p.x and c.x, it prints 0 & 1
how this multi-level inheritance works ?  Please help me understand this.

A: *

*In the line Parent p = new Child(); you create p as a reference to an object of type Child

*Then you create c as a second reference to the same object

The object is the object. It is what it is. It is a Child.
A reference has a type, and an object has a type. They are not the same thing. They do have to be compatible.

*

*The type of p is Parent

*The type of c is Child

*The type of the object is Child, regardless of which reference (p or c) you are using

With regard to the different in behaviour overriding between a method and a field, see:

*

*If you overwrite a field in a subclass of a class, the subclass has two fields with the same name(and different type)?


text:
Q: MoPub: Handle volatile device orientation and interstitials? MoPub requires you to pick the orientation associated with an interstitial ad unit. How does that work with an app that allows rotation? The user may rotate the device in between fetching an interstitial and displaying it.
Other networks I've used in the past will just load a generic interstitial, and then display it at whatever orientation the device happens to be in when the time comes.
Is there a better way to handle this in MoPub, other than the obvious "Load two interstitials"? I'd rather not have the potential of loading two at a time for networks that don't require you to pick an orientation.

A: Because MoPub has an orientation associated with and interstitial ad unit, I would set the orientation of the view immediately after the ad loads and then allow the orientation of the view to rotate on the close of the interstitial.
In Android, the method the MoPub SDK calls when an ad loads is:

@Override
public void onInterstitialLoaded(MoPubInterstitial interstitial) {
    if (interstitial.isReady()) {
        mInterstitial.show();
    } else {
        // Other code
    }
}

Before the ad is shown here, you can set the orientation of the device.

When the interstitial is closed, you can allow the orientation of the view to rotate.

@Override
public void onInterstitialDismissed(MoPubInterstitial interstitial) {}

This way, you are loading only one interstitial and the interstitial will not be interrupted on rotation.


text:
Q: how to get checked rows QtableWidget I have this code. I want to delete any row whose tick was active when clicked the delete button
from main import Ui_MainWindow
from PyQt5 import QtWidgets
from  PyQt5.QtCore import Qt

def set_cell_elements(rows, l):
    ui.tableWidget.setRowCount(len(rows))
    ui.tableWidget.setVerticalHeaderLabels(rows)
    ui.tableWidget.verticalHeader().setDefaultAlignment(Qt.AlignVCenter)
    ui.tableWidget.horizontalHeader().setDefaultAlignment(Qt.AlignCenter)

    for r in range(0, len(l)):
        for i in range (0, len(l[r])) :
            text = l[r][i]
            ui.tableWidget.setItem(r, i, QtWidgets.QTableWidgetItem(str(text)))
            ui.tableWidget.item(r, i).setTextAlignment(Qt.AlignCenter)
            item = ui.tableWidget.item(r, 0)
            item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
            item.setCheckState(Qt.Unchecked)
            item.checkState()
            table_ = ui.tableWidget.horizontalHeader()
            table_.setSectionResizeMode(i, QtWidgets.QHeaderView.ResizeToContents)

def delete_button():
    pass

import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
#=====================
rows = ['a', 'b', 'c', 'd', 'e', 'f']
l = [['Wade', 'Wade', 'Seth', 'Ivan', 'Riley'],
        ['Gilbert', 'Jorge', 'Dan', 'Brian', 'Roberto'],
        ['Ramon', 'Liam', 'Miles', 'Nathaniel', 'Lewis'],
        ['Ethan', 'Milton', 'Joshua', 'Claude', 'Glen'],
        ['Harvey', 'Blake', 'Antonio', 'Connor', 'Julian'],
        ['Aidan', 'Harold', 'Conner', 'Peter', 'Hunter']]

set_cell_elements(rows, l)
ui.delete_button.clicked.connect(delete_button)
MainWindow.show()
sys.exit(app.exec_())

I do not have a solution to get rows whose tick is active, can you help me !? Please

A: Welcome to StackOverflow! There are some missing information in your question to be able to help you with your problem. I can only guess the missing part of your code.
I guess that you have used Qt Designer to create graphically your UI. I will suppose that you UI looks like that:

When compiled it gives:
main.py
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'Ui_MainWindow.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
        self.verticalLayoutWidget.setGeometry(QtCore.QRect(19, 16, 761, 521))
        self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
        self.verticalLayout.setSizeConstraint(QtWidgets.QLayout.SetMaximumSize)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setObjectName("verticalLayout")
        self.delete_button = QtWidgets.QPushButton(self.verticalLayoutWidget)
        self.delete_button.setObjectName("delete_button")
        self.verticalLayout.addWidget(self.delete_button)
        self.verticalLayout_2 = QtWidgets.QVBoxLayout()
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.tableWidget = QtWidgets.QTableWidget(self.verticalLayoutWidget)
        self.tableWidget.setBaseSize(QtCore.QSize(0, 0))
        self.tableWidget.setRowCount(6)
        self.tableWidget.setColumnCount(5)
        self.tableWidget.setObjectName("tableWidget")
        self.verticalLayout_2.addWidget(self.tableWidget)
        self.verticalLayout.addLayout(self.verticalLayout_2)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 24))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.delete_button.setText(_translate("MainWindow", "Delete selected rows"))

The minimal changes solution would be:
Solution 1.py
from main import Ui_MainWindow
from PyQt5 import QtWidgets
from  PyQt5.QtCore import Qt

def set_cell_elements(rows, l):
    ui.tableWidget.setRowCount(len(rows))
    ui.tableWidget.setVerticalHeaderLabels(rows)
    ui.tableWidget.verticalHeader().setDefaultAlignment(Qt.AlignVCenter)
    ui.tableWidget.horizontalHeader().setDefaultAlignment(Qt.AlignCenter)

    for r in range(0, len(l)):
        for i in range (0, len(l[r])) :
            text = l[r][i]
            ui.tableWidget.setItem(r, i, QtWidgets.QTableWidgetItem(str(text)))
            ui.tableWidget.item(r, i).setTextAlignment(Qt.AlignCenter)
            item = ui.tableWidget.item(r, 0)
            item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
            item.setCheckState(Qt.Unchecked)
            item.checkState()
            table_ = ui.tableWidget.horizontalHeader()
            table_.setSectionResizeMode(i, QtWidgets.QHeaderView.ResizeToContents)

def delete_button():
    for r in range(ui.tableWidget.rowCount(), 0, -1):
        item = ui.tableWidget.item(r - 1, 0)
        if item.checkState() == Qt.Checked:
            ui.tableWidget.removeRow(r - 1)

import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
#=====================
rows = ['a', 'b', 'c', 'd', 'e', 'f']
l = [['Wade', 'Wade', 'Seth', 'Ivan', 'Riley'],
        ['Gilbert', 'Jorge', 'Dan', 'Brian', 'Roberto'],
        ['Ramon', 'Liam', 'Miles', 'Nathaniel', 'Lewis'],
        ['Ethan', 'Milton', 'Joshua', 'Claude', 'Glen'],
        ['Harvey', 'Blake', 'Antonio', 'Connor', 'Julian'],
        ['Aidan', 'Harold', 'Conner', 'Peter', 'Hunter']]

set_cell_elements(rows, l)
ui.delete_button.clicked.connect(delete_button)
MainWindow.show()
sys.exit(app.exec_())

But there can be some more cleanup and simplification to your code:
Solution 2.py
from main import Ui_MainWindow
from PyQt5 import QtWidgets

from PyQt5.QtCore import Qt

def set_cell_elements(row_headers, data_body):
    ui.tableWidget.setRowCount(len(row_headers))
    ui.tableWidget.setVerticalHeaderLabels(row_headers)
    ui.tableWidget.verticalHeader().setDefaultAlignment(Qt.AlignVCenter)
    ui.tableWidget.horizontalHeader().setDefaultAlignment(Qt.AlignCenter)

    for (row_number, current_row) in enumerate(data_body):
        for (column_number, current_text) in enumerate(current_row):
            ui.tableWidget.setItem(
                row_number, column_number,
                QtWidgets.QTableWidgetItem(str(current_text))
            )
            ui.tableWidget.item(row_number, column_number).setTextAlignment(Qt.AlignCenter)
            row_header = ui.tableWidget.horizontalHeader()
            row_header.setSectionResizeMode(column_number, QtWidgets.QHeaderView.ResizeToContents)
        item = ui.tableWidget.item(row_number, 0)
        item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
        item.setCheckState(Qt.Unchecked)

def delete_button_action():
    for current_row in range(ui.tableWidget.rowCount() - 1, -1, -1):
        first_item = ui.tableWidget.item(current_row, 0)
        state_current_row = first_item.checkState()
        if state_current_row == Qt.Checked:
            ui.tableWidget.removeRow(current_row)

import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)

row_headers = ('a', 'b', 'c', 'd', 'e', 'f')
data_body = (
    ('Wade', 'Wade', 'Seth', 'Ivan', 'Riley'),
    ('Gilbert', 'Jorge', 'Dan', 'Brian', 'Roberto'),
    ('Ethan', 'Milton', 'Joshua', 'Claude', 'Glen'),
    ('Ramon', 'Liam', 'Miles', 'Nathaniel', 'Lewis'),
    ('Harvey', 'Blake', 'Antonio', 'Connor', 'Julian'),
    ('Aidan', 'Harold', 'Conner', 'Peter', 'Hunter')
)

set_cell_elements(row_headers, data_body)
ui.delete_button.clicked.connect(delete_button_action)
MainWindow.show()
sys.exit(app.exec_())

But you could code this in a more object-oriented way. That way, as long as you provide the containing widget and its initial data, you can plug it anywhere in your UI and it will take of itself:
Solution 3.py
import sys
from main import Ui_MainWindow
from PyQt5 import QtWidgets

from PyQt5.QtCore import Qt

class Simple_table_editor(Ui_MainWindow):

    def __init__(self, parent, row_headers, initial_data):
        super().__init__()
        self.setupUi(parent)
        self.tableWidget.setRowCount(len(row_headers))
        self.tableWidget.setVerticalHeaderLabels(row_headers)
        self.tableWidget.verticalHeader().setDefaultAlignment(Qt.AlignVCenter)
        self.tableWidget.horizontalHeader().setDefaultAlignment(Qt.AlignCenter)

        for (row_number, current_row) in enumerate(initial_data):
            for (column_number, current_text) in enumerate(current_row):
                self.tableWidget.setItem(
                    row_number, column_number,
                    QtWidgets.QTableWidgetItem(str(current_text))
                )
                self.tableWidget.item(row_number, column_number).setTextAlignment(Qt.AlignCenter)
                row_header = self.tableWidget.horizontalHeader()
                row_header.setSectionResizeMode(column_number, QtWidgets.QHeaderView.ResizeToContents)
            item = self.tableWidget.item(row_number, 0)
            item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
            item.setCheckState(Qt.Unchecked)

        self.delete_button.clicked.connect(self.delete_button_action)

    def delete_button_action(self):
        for current_row in range(self.tableWidget.rowCount() - 1, -1, -1):
            first_item = self.tableWidget.item(current_row, 0)
            state_current_row = first_item.checkState()
            if state_current_row == Qt.Checked:
                self.tableWidget.removeRow(current_row)

row_headers = ('a', 'b', 'c', 'd', 'e', 'f')
data_body = (
    ('Wade', 'Wade', 'Seth', 'Ivan', 'Riley'),
    ('Gilbert', 'Jorge', 'Dan', 'Brian', 'Roberto'),
    ('Ethan', 'Milton', 'Joshua', 'Claude', 'Glen'),
    ('Ramon', 'Liam', 'Miles', 'Nathaniel', 'Lewis'),
    ('Harvey', 'Blake', 'Antonio', 'Connor', 'Julian'),
    ('Aidan', 'Harold', 'Conner', 'Peter', 'Hunter')
)

app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
table_editor = Simple_table_editor(MainWindow, row_headers, data_body)
MainWindow.show()
sys.exit(app.exec_())

If my guesses are wrong and you meant to do something else, please give us more detail.


text:
Q: Get all key/value pairs from data attr that have the same prefix I am working on a platform and would like to unify and standardize some behaviour throughout the platform...the data- attribute in the html elements will play a huge part...
So lets say I have a button:
...

now, my Javascripts handles the behaviour of this button.
What I would like is to get set a template_data array, that would give me all key/value pairs from the data- attribute that have the same prefix (data-template_data_)...
so in my example I would get:
{
    id: "14",
    action : "reset"
}

What is the best way to do that?

A: try this
var array = [];
$( ".btn" ).each( function(){
    var obj = {};
    $.each(this.attributes, function()
    {
        if(this.name.indexOf( "data-templade_data_" ) == 0 )
        {
            var key = this.name.replace( "data-templade_data_", "" );
            obj[ key ] = this.value;
        }
    });
    array.push( obj );
} );

A: this works for me
jQuery.fn.extend({
hyphened: function(prefix) { // prefix = data or myplugin
    var attributes = {};
    $.each(this.get(0).attributes, function(index, attrib) {
        if(attrib.name.indexOf(prefix+"-")==0) {
            var key = attrib.name.replace(prefix+"-","");
            attributes[key] = attrib.value;
        }
    });

    return attributes;
}

});


text:
Q: openapi generator typescript-angular adds numbers to the end of methods names Description
I have an exposed file from spring boot server
and I am using this script to generate a typescript angular client
openapi-generator-cli generate -g typescript-angular -i ./src/app/data/open-api.json -o ./src/app/data/build/openapi
there are duplicated api names among the system
simple structure
Controller1 : [get,list,delete,... ....]
Controller2 : [get,list,delete,... ....]
.....
the generated classes looks like
Controller1Service{
public get1 ....
public list1 .....
}
Controller2Service{
public get2 ....
public list2 .....
}

but the functions are unique in the same controller and the generator still adding numbers to them
openapi-generator version
4.3.1 using npm cli
OpenAPI declaration file content or url
Command line used for generation
openapi-generator-cli generate -g typescript-angular -i ./src/app/data/open-api.json -o ./src/app/data/build/openapi

So any way to make these numbers disappear ?
when updating the backend the numbers may be changed inside and it will lead to a manual code refactor

A: From the template, the numbers come from the 'nickname' attribute.
In the internals of OpenAPI this is produced from the operationId when generating the open-api.json file.
The solution for Spring Boot (and others alike, to adapt...) is to tweak the operationId generation (original answer).
To have generated code still match a common interface (as when using generic Spring controllers), the operationId must match a reference (default: handling method name).
Here is what I used (ChangeController.class being generic and making about 80% of the API).
@Bean
public OperationCustomizer operationIdCustomizer() {
    return (operation, handlerMethod) -> {
        Class<?> superClazz = handlerMethod.getBeanType().getSuperclass();
        if (Objects.nonNull(superClazz) && superClazz.isAssignableFrom(ChangeController.class)) {
            operation.setOperationId(String.format("%s", handlerMethod.getMethod().getName()));
        }
        return operation;
    };
}

IMPORTANT NOTE : this will generate error on the spec validation when generating the Angular client, disable validation explicitly (skipValidateSpec).
Also, for generation working with Angular 10+, openapi-generator 5.0.0 is required (for generic ModuleWithProviders).
<plugin>
    <groupId>org.openapitools</groupId>
    <artifactId>openapi-generator-maven-plugin</artifactId>
    <version>5.0.0</version>
    <executions>
        <execution>
            <goals>
                <goal>generate</goal>
            </goals>
            <configuration>
                <inputSpec>${project.basedir}/../sic-frontend/src/app/api/openapi.json</inputSpec>
                <generatorName>typescript-angular</generatorName>
                <output>${project.basedir}/../sic-frontend/src/app/api</output>
                <skipValidateSpec>true</skipValidateSpec>
                <configOptions>
                    <ngVersion>10.0.0</ngVersion>
                </configOptions>

            </configuration>
        </execution>
    </executions>
</plugin>


text:
Q: Subqueries for results Hello I`m trying to get few columns from two tables.
I need to read the information from table 1
SELECT `id`, `title`, `body`, `userid`, `cdate`, `tags` FROM `asks` WHERE `id`= ? AND `title`= ?

and I need to get information about the user who published this. his id as the userid in the previous query. and to get information about the user I need more query:
SELECT `username`, `fullname`, `asked`, `answered` FROM `accounts` WHERE `id`=

I must to echo all these information to one page. Thank so much.

A: You can join the two tables together like this:
SELECT `id`, `title`, `body`, `userid`, `cdate`, `tags`, `username`, `fullname`, `asked`, `answered` FROM `asks` inner join `accounts` on accounts.id=tags.id WHERE `id`= ? AND `title`= ?

And that will only select when a record is present in both tables otherwise you can use a different type of join Visual Explanation Of SQL Joins


text:
Q: lombok 0.10.1. error in Eclipse 3.7 when I try to use the @Data annotation with lombok 0.10.1. in Eclipse: 3.7.0.v20110504-0800-7b7qFVpFEx2XnmYtj_9RfO7
I got this error, can anyone advise?
Lombok annotation handler class lombok.eclipse.handlers.HandleData failed

java.lang.NoSuchMethodError: java/util/Arrays.copyOf([Ljava/lang/Object;I)[Ljava/lang/Object;
    at lombok.eclipse.handlers.EclipseHandlerUtil.createSuppressWarningsAll(EclipseHandlerUtil.java:514)
    at lombok.eclipse.handlers.EclipseHandlerUtil.injectMethod(EclipseHandlerUtil.java:451)
    at lombok.eclipse.handlers.HandleEqualsAndHashCode.generateMethods(HandleEqualsAndHashCode.java:227)
    at lombok.eclipse.handlers.HandleEqualsAndHashCode.generateEqualsAndHashCodeForType(HandleEqualsAndHashCode.java:116)
    at lombok.eclipse.handlers.HandleData.handle(HandleData.java:63)
    at lombok.eclipse.HandlerLibrary$AnnotationHandlerContainer.handle(HandlerLibrary.java:73)
    at lombok.eclipse.HandlerLibrary.handleAnnotation(HandlerLibrary.java:191)
    at lombok.eclipse.TransformEclipseAST$AnnotationVisitor.visitAnnotationOnType(TransformEclipseAST.java:204)
    at lombok.eclipse.EclipseNode.traverse(EclipseNode.java:96)
    at lombok.eclipse.EclipseAST.traverseChildren(EclipseAST.java:94)
    at lombok.eclipse.EclipseNode.traverse(EclipseNode.java:63)
    at lombok.eclipse.EclipseAST.traverseChildren(EclipseAST.java:94)
    at lombok.eclipse.EclipseNode.traverse(EclipseNode.java:58)
    at lombok.eclipse.EclipseAST.traverse(EclipseAST.java:89)
    at lombok.eclipse.TransformEclipseAST.go(TransformEclipseAST.java:166)
    at lombok.eclipse.TransformEclipseAST.transform(TransformEclipseAST.java:132)
    at lombok.eclipse.TransformEclipseAST.transform_swapped(TransformEclipseAST.java:85)
    at org.eclipse.jdt.internal.compiler.parser.Parser.endParse(Parser.java:8506)
    at org.eclipse.jdt.internal.core.util.CommentRecorderParser.endParse(CommentRecorderParser.java:116)
    at org.eclipse.jdt.internal.compiler.SourceElementParser.endParse(SourceElementParser.java:727)
    at org.eclipse.jdt.internal.compiler.parser.Parser.parse(Parser.java:9515)
    at org.eclipse.jdt.internal.compiler.parser.Parser.parse(Parser.java:9731)
    at org.eclipse.jdt.internal.compiler.parser.Parser.parse(Parser.java:9688)
    at org.eclipse.jdt.internal.compiler.SourceElementParser.parseCompilationUnit(SourceElementParser.java:921)
    at org.eclipse.jdt.internal.core.search.indexing.SourceIndexer.indexDocument(SourceIndexer.java:68)
    at org.eclipse.jdt.internal.core.search.JavaSearchParticipant.indexDocument(JavaSearchParticipant.java:72)
    at org.eclipse.jdt.internal.core.search.indexing.IndexManager.indexDocument(IndexManager.java:453)
    at org.eclipse.jdt.internal.core.search.indexing.IndexManager$1.execute(IndexManager.java:853)
    at org.eclipse.jdt.internal.core.search.processing.JobManager.run(JobManager.java:405)
    at java.lang.Thread.run(Thread.java:799)

A: The cause of this problem is that that version of lombok used java6 API, and I suppose you're using java5 to run eclipse. This has been fixed in the 0.10.4 release. The current version is 0.10.6.
Disclosure: I'm one of the core contributors.


text:
Q: Sum data in multi-dimensional arrays with variable number of grouping keys I have data coming back from MySQL and the goal is to pull data from multiple servers.
The data can be grouped by one or more fields, and I want to pull data from X number of MySQL servers and sum the data that should be summed, using the other data as a key or index.
Example:
Result from Mysql[$x]:
[{"date":"2017-10-10","account":"1","trees":"1","people":"0","pets":"4"}
,{"date":"2017-10-10","account":"2","trees":"2","people":"5","pets":"1"}
,{"date":"2017-10-11","account":"1","trees":"3","people":"3","pets":"4"}
,{"date":"2017-10-11","account":"2","trees":"4","people":"1","pets":"4"}]

Result from Mysql[$x+1]:
[{"date":"2017-10-10","account":"1","trees":"5","people":"1","pets":"1"}
,{"date":"2017-10-10","account":"2","trees":"5","people":"2","pets":"1"}
,{"date":"2017-10-11","account":"1","trees":"5","people":"0","pets":"2"}
,{"date":"2017-10-11","account":"2","trees":"5","people":"1","pets":"2"}]

Desired end result:
[{"date":"2017-10-10","account":"1","trees":"6","people":"1","pets":"5"}
,{"date":"2017-10-10","account":"2","trees":"7","people":"7","pets":"2"}
,{"date":"2017-10-11","account":"1","trees":"8","people":"3","pets":"6"}
,{"date":"2017-10-11","account":"2","trees":"9","people":"2","pets":"6"}]

in this case, there are 2 keys, date and account, but in reality there can be between 1 and 4.
The grouping keys are known, so the code knows that in this case, date and account are the keys.
I'm trying to find a better way than iterating through each row of mysql[$x] and then iterating through each row of mysql[$x+1] ... mysql[$x+n] and checking each value of the known keys to see if they match the current row's key values and then summing the data.
Also note that in reality, there may not be a row for each set of keys, hence the number and order of rows from each server can be variable.
I need an efficient way to do this because there are potentially tens of thousands of rows with a dozen+ columns.
I'm experimenting with code like this:
$res = array();

$keys = array('date','account');
array_walk($t,'rehash',$res);

function rehash($data,$key,&$result) {
    global $keys;
    global $res;
    $keydata = array_slice($data,0,count($keys));
    $vals = array_slice($data,count($keys));

    //this is how the data would ideally be structured, my model
    //$res[$keydata[$keys[0]]][$keydata[$keys[1]]] = $vals;
    //this code below successfully creates rows in the right format
    for($x = count($keys) - 1; $x>= 0; $x--) {
        if($x == count($keys)-1) {
            $tmp = array($keydata[$keys[$x]] => $vals);
        //} else if($x ==0) {
        //  maybe reconcile here?
        } else {
            $tmp = array($keydata[$keys[$x]] => $tmp);
        }
    }
}

But how do i reconcile this? I can't simply do $res[key1] = $tmp[key1] because with multiple keys it would remove all the other rows.
Also with nested arrays, how would I iterate through each nested array if the number of levels is variable?
Lastly if I do this, I would need to convert it back into the original format for the frontend, so... joy. :D (this part would be easy, just is worth taking into consideration from an efficiency standpoint)

A: You don't need to use array_walk, since your data isn't hierarchical. Just use an ordinary foreach loop.
$res = array();
foreach ($t as $row) {
    $cur = &$res;
    // Drill down into result array using the key fields, creating nested arrays
    // as necessary
    foreach ($keys as $keycol) {
        $key = $row[$keycol];
        if (!isset($cur[$key])) {
            $cur[$key] = array();
        }
        $cur = &$cur[$key];
    }
    // Now go through the data columns in the row, adding them to the totals
    foreach ($row as $key => $val) {
        if (in_array($key, $keys)) {
            // Put the key fields in the result row
            $cur[$key] = $val;
        } else {
            // Accumulate other values in the result row
            if (!isset($cur[$key])) {
                $cur[$key] = 0;
            }
            $cur[$key] += $row[$key];
        }
    }
    unset($cur); // Break the reference link
}

A: Here is a possible solution based on the structure of the sample data given in the question.
$jsn1 = '[{"date":"2017-10-10","account":"1","trees":"1","people":"0","pets":"4"}
    ,{"date":"2017-10-10","account":"2","trees":"2","people":"5","pets":"1"}
    ,{"date":"2017-10-11","account":"1","trees":"3","people":"3","pets":"4"}
    ,{"date":"2017-10-11","account":"2","trees":"4","people":"1","pets":"4"}]';

    $jsn2 = '[{"date":"2017-10-10","account":"1","trees":"5","people":"1","pets":"1"}
    ,{"date":"2017-10-10","account":"2","trees":"5","people":"2","pets":"1"}
    ,{"date":"2017-10-11","account":"1","trees":"5","people":"0","pets":"2"}
    ,{"date":"2017-10-11","account":"2","trees":"5","people":"1","pets":"2"}]';

    /* Decode the json strings into associative arrays: */
    $arr1 = json_decode($jsn1, true);
    $arr2 = json_decode($jsn2, true);

    /* Put in an array the keys whose values are to be added: */
    /* Do not include date and account keys if they are not to be added */
    $arr_keys = ['trees', 'people', 'pets'];

    /* Loop through both $arr1 and $arr2 while storing new arrays in arr: */
    /* Be adding up the values for the keys that are in $arr_keys */
    $arr = [];
    foreach($arr1 as $k => $v){
    $arr[$k]['date'] = $arr1[$k]['date']; $arr[$k]['account'] = $arr1[$k]['account'];
    foreach($arr_keys as $y){
if($arr1[$k][$y] !== null && $arr2[$k][$y] !== null){
    $arr[$k][$y] = $arr1[$k][$y] + $arr2[$k][$y];
    }}}

    /* encode the array to the required json string: */
    $json = json_encode($arr);

    echo $json;
    /* Output:
    [{"date":"2017-10-10","account":"1","trees":"6","people":"1","pets":"5"}
    ,{"date":"2017-10-10","account":"2","trees":"7","people":"7","pets":"2"}
    ,{"date":"2017-10-11","account":"1","trees":"8","people":"3","pets":"6"}
    ,{"date":"2017-10-11","account":"2","trees":"9","people":"2","pets":"6"}]
    */


text:
Q: Is there a way to get text as soon as possible without waiting for a newline? I'm using C. I wrote a very simpe program which prints back the input, using getchar() and putchar() or printf(). Is there any way to make it so as soon as the user types one key, the program registers it, without waiting for an Enter? Let me show:
Currently, if the user types "abc" and then presses Enter, the program prints "abc" and a newline and keeps waiting for more input. I want to make it so as soon as the user types "a", the program prints "a" and waits for more input. I'm not sure whether this has to be done inside the source code or if something has to be changed in the Windows command line.
Just in case, here's the source code:
#include <stdio.h>

int main()
{
    int c;

    while ((c = getchar()) != EOF) {
        putchar(c);
    }
    return 0;
}

A: if you are using Visual Studio, there is a library called conio (#include <conio.h>) which defines a kbhit() function and getch().
otherwise, on Windows, there is still the possibility of using functions from the Windows SDK (ReadConsoleInput() and the like), but that would require a little bit more code (although, once done and if done properly, it can be reused any time you want)

A: If you're using Visual Studio, you can use getch().

A: In this simple case, the other answers should suit you fine.
The general solution is to disable line buffering. This depends on the particular console; the following example is Windows-only (untested):
#include <windows.h>

int main() {
    HANDLE hConsole = GetStdHandle(STD_INPUT_HANDLE);
    DWORD mode;
    GetConsoleMode(hConsole, &mode);
    SetConsoleMode(hConsole, mode & ~ENABLE_LINE_INPUT);
    // ...
}

I assume that the standard C library functions are implemented in terms of ReadConsole and friends; if not, this might not even work. (I'm currently on Linux, so I cannot test this.)

A: On Linux you can take over the terminal:
#include <stdio.h>
#include <ctype.h>
#include <termios.h>

system("stty raw"); /* raw output to terminal, direct feedback */
system("clear"); /* clear screen */

printf("Press a key");
answer = getchar();

system("stty cooked"); /* revert back*/


text:
Q: Why does System.in.read() wait till the user presses enter?
System.in.read() is used to read a single character.

Then why does it allow the user to enter as many characters as he can until he presses enter?
Why doesn't it stop as soon as he presses a key and returns the character?
char ch = (char)System.in.read();

If the user enter "example" and then press enter, It takes the ch as e. and discards the other characters.
If there are multiple read(), it messes the whole thing.
So, why doesn't it take only the single character and then return?

A: System.in is of type BufferedInputStream. This type of stream caches input data until newline character is recognized. The following snippet shows you the type in the output.
System.out.println(System.in.getClass());

A:
If there are multiple read(), it messes the whole thing.
  So, why doesn't it take only the single character and then return?

To solve this issue you can wrap the standard input and read it with a Scanner instead.
For the given input:

abcd
  1234

the following Scanner code will pick just the chars a and 1.
// Local vars init
char ch1 = 0, ch2 = 0;

// Wrap the stdin with scanner
Scanner s = new Scanner(System.in);

if(s.hasNextLine()) ch1 = s.nextLine().charAt(0); // reads "abcd", picks just 'a'
if(s.hasNextLine()) ch2 = s.nextLine().charAt(0); // reads "1234", picks just '1'

System.out.println(ch1 + "," + ch2); // prints a,1

// Close after use
s.close();


text:
Q: Read key value pairings XML file via ant? I want to read an XML file like below
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
  <classpathentry kind="con" path="org.eclipse.jst.server.core.container/com.ibm.ws.st.core.runtimeClasspathProvider/com.ibm.worklight"/>
  <classpathentry kind="con" path="com.worklight.studio.plugin.classpath.SERVER_CONTAINER"/>
  <classpathentry kind="src" path="server/java"/>
  <classpathentry kind="src" path="common"/>
  <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
  <classpathentry kind="src" output="adapters/adp1/bin" path="adapters/agent/src"/>
  <classpathentry kind="src" output="adapters/adp2/bin" path="adapters/alerts/src"/>
  <classpathentry kind="src" output="adapters/adp3/bin" path="adapters/billing/src"/>
  <classpathentry kind="src" output="adapters/adp4/bin" path="adapters/client/src"/>
  <classpathentry kind="src" output="adapters/adp5/bin" path="adapters/category/src"/>
</classpath>

I want to read the value of path where kind is "src". I able to get all the path value but not able to imply condition over it. I am using the following code.
<target name="xml">
  <echo>Test For Each</echo>
  <for list="${classpath.classpathentry.path}" param="letter" delimiter=",">
    <sequential>
      <echo message="path :::  @{letter}"/>
    </sequential>
  </for>
</target>

It is working fine with all the path values but what I should do to get the value of path where kind is "src" ?

A: As I stated in the comment, the following XSLT will parse all classpath entries of kind=src and generate a single line path statement.
getclasspath.xslt
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:template match="/classpath">
        <xsl:text>path=</xsl:text>
        <xsl:for-each select="classpathentry[@kind='src']">
            <xsl:value-of select="@path"/>
            <xsl:text>;</xsl:text>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

Then the following ant task:
<xslt style='getclasspath.xslt' in='classpath.xml' out='classpath.properties' />


text:
Q: Parallel processing using TPL in windows service I have a windows service which is consuming a messaging system to fetch messages. I have also created a callback mechanism with the help of Timer class which helps me to check the message after some fixed time to fetch and process. Previously, the service is processing the message one by one. But I want after the message arrives the processing mechanism to execute in parallel. So if the first message arrived it should go for processing on one task and even if the processing is not finished for the first message still after the interval time configured using the callback method (callback is working now) next message should be picked and processed on a different task.
Below is my code:
Task.Factory.StartNew(() =>
{
    Subsriber<Message> subsriber = new Subsriber<Message>()
    {
       Interval = 1000
    };

    subsriber.Callback(Process, m => m != null);
});

public static void Process(Message message)
{
  if (message != null)
  {
     // Processing logic
  }
 else
 {

 }
}

But using the Task Factory I am not able to control the number of tasks in parallel so in my case I want to configure the number of tasks on which messages will run on the availability of the tasks?

Update:
Updated my above code to add multiple tasks
Below is the code:
         private static void Main()
        {
            try
            {
                int taskCount = 5;
                Task.Factory.StartNewAsync(() =>
                {
                   Subscriber<Message> consumer = new
                   Subcriber<Message>()
                   {
                       Interval = 1000
                    };

                   consumer.CallBack(Process, msg => msg!=
                   null);
                 }, taskCount);
                Console.ReadLine();
              }
             catch (Exception e)
            {
                 Console.WriteLine(e.Message);
            }

            public static void StartNewAsync(this TaskFactory
            target, Action action, int taskCount)
           {
                 var tasks = new Task[taskCount];
                 for (int i = 0; i < taskCount; i++)
                 {
                      tasks[i] = target.StartNew(action);
                 }
             }

             public static void Process(Message message)
            {
                 if (message != null)
                {

                 }
                else
                { }
             }
        }

A: I think what your looking for will result in quite a large sample. I'm trying just to demonstrate how you would do this with ActionBlock<T>. There's still a lot of unknowns so I left the sample as skeleton you can build off. In the sample the ActionBlock will handle and process in parallel all your messages as they're received from your messaging system
public class Processor
{
    private readonly IMessagingSystem _messagingSystem;
    private readonly ActionBlock<Message> _handler;
    private bool _pollForMessages;

    public Processor(IMessagingSystem messagingSystem)
    {
        _messagingSystem = messagingSystem;
        _handler = new ActionBlock<Message>(msg => Process(msg), new ExecutionDataflowBlockOptions()
        {
            MaxDegreeOfParallelism = 5 //or any configured value
        });
    }

    public async Task Start()
    {
        _pollForMessages = true;
        while (_pollForMessages)
        {
            var msg = await _messagingSystem.ReceiveMessageAsync();
            await _handler.SendAsync(msg);
        }

    }

    public void Stop()
    {
        _pollForMessages = false;
    }

    private void Process(Message message)
    {
        //handle message
    }
}

More Examples
And Ideas

A: Ok, sorry I'm short on time but here's the general idea/skeleton of what I was thinking as an alternative.
If I'm honest though I think the ActionBlock<T> is the better option as there's just so much done for you, with the only limit being that you can't dynamically scale the amount of work it will do it once, although I think the limit can be quite high. If you get into doing it this way you could have more control or just have a kind of dynamic amount of tasks running but you'll have to do a lot of things manually, e.g if you want to limit the amount of tasks running at a time, you'd have to implement a queueing system (something ActionBlock handles for you) and then maintain it. I guess it depends on how many messages you're receiving and how fast your process handles them.
You'll have to check it out and think of how it could apply to your direct use case as I think some of the details area a little sketchily implemented on my side around the concurrentbag idea.
So the idea behind what I've thrown together here is that you can start any number of tasks, or add to the tasks running or cancel tasks individually by using the collection.
The main thing I think is just making the method that the Callback runs fire off a thread that does the work, instead of subscribing within a separate thread.
I used Task.Factory.StartNew as you did, but stored the returned Task object in an object (TaskInfo) which also had it's CancellationTokenSource, it's Id (assigned externally) as properties, and then added that to a collection of TaskInfo which is a property on the class this is all a part of:
Updated - to avoid this being too confusing i've just updated the code that was here previously.
You'll have to update bits of it and fill in the blanks in places like with whatever you have for my HeartbeatController, and the few events that get called because they're beyond the scope of the question but the idea would be the same.
    public class TaskContainer
{
    private ConcurrentBag<TaskInfo> Tasks;
    public TaskContainer(){
        Tasks = new ConcurrentBag<TaskInfo>();
    }

//entry point
//UPDATED
public void StartAndMonitor(int processorCount)
{

        for (int i = 0; i <= processorCount; i++)
        {
            Processor task = new Processor(ProcessorId = i);
            CreateProcessorTask(task);
        }
        this.IsRunning = true;
        MonitorTasks();
}

private void CreateProcessorTask(Processor processor)
{
    CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

    Task taskInstance = Task.Factory.StartNew(
        () => processor.Start(cancellationTokenSource.Token)
    );
    //bind status update event
    processor.ProcessorStatusUpdated += ReportProcessorProcess;

    Tasks.Add(new ProcessorInfo()
    {
        ProcessorId = processor.ProcessorId,
        Task = taskInstance,
        CancellationTokenSource = cancellationTokenSource
    });

}

//this method gets called once but the HeartbeatController gets an action as a param that it then
//executes on a timer. I haven't included that but you get the idea

//This method also checks for tasks that have stopped and restarts them if the manifest call says they should be running.
//Will also start any new tasks included in the manifest and stop any that aren't included in the manifest.
internal void MonitorTasks()
    {
        HeartbeatController.Beat(() =>
        {
            HeartBeatHappened?.Invoke(this, null);
            List<int> tasksToStart = new List<int>();

            //this is an api call or whatever drives your config that says what tasks must be running.
            var newManifest = this.GetManifest(Properties.Settings.Default.ResourceId);

            //task Removed Check - If a Processor is removed from the task pool, cancel it if running and remove it from the Tasks List.
            List<int> instanceIds = new List<int>();
            newManifest.Processors.ForEach(x => instanceIds.Add(x.ProcessorId));
            var removed = Tasks.Select(x => x.ProcessorId).ToList().Except(instanceIds).ToList();

            if (removed.Count() > 0)
            {
                foreach (var extaskId in removed)
                {
                    var task = Tasks.FirstOrDefault(x => x.ProcessorId == extaskId);
                    task.CancellationTokenSource?.Cancel();
                }
            }

            foreach (var newtask in newManifest.Processors)
            {
                var oldtask = Tasks.FirstOrDefault(x => x.ProcessorId == newtask.ProcessorId);
                //Existing task check
                if (oldtask != null && oldtask.Task != null)
                {
                    if (!oldtask.Task.IsCanceled && (oldtask.Task.IsCompleted || oldtask.Task.IsFaulted))
                    {
                        var ex = oldtask.Task.Exception;

                        tasksToStart.Add(oldtask.ProcessorId);
                        continue;
                    }
                }
                else //New task Check
                    tasksToStart.Add(newtask.ProcessorId);

            }

            foreach (var item in tasksToStart)
            {
                var taskToRemove = Tasks.FirstOrDefault(x => x.ProcessorId == item);
                if (taskToRemove != null)
                    Tasks.Remove(taskToRemove);

                var task = newManifest.Processors.FirstOrDefault(x => x.ProcessorId == item);
                if (task != null)
                {
                    CreateProcessorTask(task);
                }
            }
        });
    }

}

//UPDATED
public class Processor{

private int ProcessorId;
private Subsriber<Message> subsriber;

public Processor(int processorId) => ProcessorId = processorId;

public void Start(CancellationToken token)
{
    Subsriber<Message> subsriber = new Subsriber<Message>()
    {
        Interval = 1000
    };

    subsriber.Callback(Process, m => m != null);
}

private void Process()
{
    //do work
}
}

Hope this gives you an idea of how else you can approach your problem and that I didn't miss the point :).

Update
To use events to update progress or which tasks are processing, I'd extract them into their own class, which then has subscribe methods on it, and when creating a new instance of that class, assign the event to a handler in the parent class which can then update your UI or whatever you want it to do with that info.
So the content of Process() would look more like this:
Processor processor = new Processor();
    Task task = Task.Factory.StartNew(() => processor.ProcessMessage(cancellationTokenSource.CancellationToken));

    processor.StatusUpdated += ReportProcess;


text:
Q: How can I select specific cell in a dataframe? How can I select a specific cell in this dataframe?, the index in this data frame is the Fishes column.
My expected output is: e.g > 35045.12  or anything in the production column. Thanks a lot!
Fishes                 | Month | Year | production
BF - Milkfish          |   3   | 2019 | 35045.12
BF - Tilapia           |   6   | 2019 | 68666.64
BF - Tiger prawn       |   9   | 2019 | 77064.91
BF - Mudcrab           |   12  | 2019 | 58163.4
BF - Endeavor prawn    |   3   | 2020 | 38108.49
BF - White shrimp      |   6   | 2020 | 67663.83
BF - Grouper           |   9   | 2020 | 71316.94

A: print(df.loc['BF - Milkfish', 'production'])
# or
print(df['production'].iloc[0])

35045.12

A: There are several ways to get the answer you are looking for, this is simply another way if you wanted to add to your bag of tricks
df['production'].loc[df['Fishes'] == 'BF - Milkfish'].squeeze()