text:
Q: Why won't my Lightning Component Attributes store entered value 2/15/2017 Update
Per comment from Doug in one of the answers this is an issue with Locker service. I verified that with Locker disabled is works as expected...
In Spring 17 as of today, with locker enabled it is still not working however
Update
So, since we get an internal error when passing classes/objects to apex controllers AND if values are not set in the controller when the component requests them then there is no way to pass those properties back (see below), I am left with this mess for every non string property
    @AuraEnabled public String endDate {
        get {
            return endDate == null ? '' : endDate;
        }
        set;
    }
    private date endDateValue {
        get {
            if (string.isBlank(endDate)) return null;

            return date.valueOf(endDate);
        }
        set {
            if (value == null) endDate = null; else endDate = string.valueOf(value);

        }
    }

Should not have to go through all that to use a simple class property in a component...Ugh
Original discussion
So I have been fighting with this for a while. Maybe my mindset is wrong and what I am doing is correct but it just seems like a lot of extra work.
Scenario

*

*Component with attribute set to a type of a custom class

*Input boud to a property in that class

Now is it too much to as that when the data is entered in the input that it is reflected in the component? The actual input keeps the value but the attribute is never set....
It makes it extremely difficult to pass data around. Right not I am manually setting the attribute properties based on the value input in the component.
So the examples:
The first input when data is input always logs as:

{}

The second input the data logs correctly when value are input into the field.

The weird part is that accessing the actual property outputs as expected:
console.log(component.get('v.myCustomClass.myTestString'));

outputs

a

as shown in the second debug line in the image

Custom Class
public class myProblemClass {
    @AuraEnabled public string myTestString {get;set;}

    public myProblemClass(){

    }

    public myProblemClass(String setDefault){
        mytestString = setDefault;
    }
}

Apex Controller
public class myProblemController {

    @AuraEnabled
    public static myProblemClass newProblemClass(){
        return New myProblemClass();
    }

    @AuraEnabled
    public static myProblemClass newProblemClassInitial(){
        return New myProblemClass('initial');
    }

}

Lightning Component
<aura:component description="myProblemComponent" controller="myProblemController">

    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>

    <aura:attribute name="myCustomClass" type="myProblemClass"/>
    <aura:attribute name="myCustomClassInitial" type="myProblemClass"/>

                    Input Label

                        <ui:inputText aura:id="firstInput" updateOn="keyup" keyup="{!c.logMe}" requiredIndicatorClass="slds-required"
                                      required="true" value="{!v.myCustomClass.myTestString}" placeholder="Enter Me"
                                      class="slds-input"/>

                    Input Label

                        <ui:inputText updateOn="keyup" keyup="{!c.logMe}" requiredIndicatorClass="slds-required"
                                      required="true" value="{!v.myCustomClassInitial.myTestString}" placeholder="Enter Me"
                                      class="slds-input"/>

</aura:component>

Component Controller
({
    doInit: function (component, event, helper) {

        var action = component.get("c.newProblemClass");
        var actionInitial = component.get("c.newProblemClassInitial");

        action.setCallback(this, function (response){
            component.set('v.myCustomClass',response.getReturnValue());
        })

        actionInitial.setCallback(this, function (response){
            component.set('v.myCustomClassInitial',response.getReturnValue());
        })

        $A.enqueueAction(action);
        $A.enqueueAction(actionInitial);

    },
    logMe: function(component,event,helper){
        console.log(JSON.stringify(component.get('v.myCustomClass')));
        console.log(component.get('v.myCustomClass.myTestString'));
        console.log(JSON.stringify(component.get('v.myCustomClassInitial')));
    }
})

Now, I get that in the first attribute that I am not setting the value of the class property thus the Java object does not contain anything. However, when I set a value in the first Input that is Bound to the class property I would expect it to set it.
The questions:

*

*Are my expectations incorrect

*If #1 is true then is setting the value of the attribute as follows the correct way. Keeping in mind my real class has 20-30 properties so that is a lot of extra code to write just to set the values
 component.get('v.myCustomClass').myTestString =
      component.find('firstInput').get('v'value');

So as Ashwani points out, the binding of the value on the input get set properly so you can access the property directly. So why does it still output as {} when logging the attribute.
Now if I do this:
    component.get('v.myCustomClass').myTestString = 'ABCDEF';
    console.log(JSON.stringify(component.get('v.myCustomClass')));

then JSON of the attribute outputs the correct JSON string (see 4th debug line). So I can set it in the JS but there is no way to set it in using the actual Input field?? But you can access the property directly when set by the input field v.myCustomClass.mytestString....Confusing.....

A: This issue is currently scheduled to be fixed in the Summer '17 release by leveraging Proxy as Doug mentioned in the comments to another answer. I've verified the fix with a very similar scenario on the Summer '17 codeline. Unfortunately, the fix is not scheduled to be patched in to Spring '17 as initially hoped for.

A: Code is working as expected.
In the above approach there is  basic problem. Lightning does not initialize any variable itself.
In controller testString is not defined so, it is not even getting set and result {}:-
public class myProblemClass {
    @AuraEnabled public string myTestString {get;set;}

    public myProblemClass(){
    }

    public myProblemClass(String setDefault){
        mytestString = setDefault;
    }
}

Define variable in no argument constructor and it will start working:-
public myProblemClass(){
   mytestString = '';
}

There is a framework logic. Only you know there is myCustomClass.myTestString but framework doesn't know.
Take the example: set the input as:
 <ui:inputText aura:id="firstInput" updateOn="keyup" keyup="{!c.logMe}" requiredIndicatorClass="slds-required"
                                      required="true" value="{!v.myCustomClass.myTestStringNOTEXIST}" placeholder="Enter Me"
                                      class="slds-input"/>

and access it as
console.log( ' 1.1 '+component.get('v.myCustomClass.myTestStringNOTEXIST'));

You will get the value but it is not the variable in controller.


text:
Q: Redux Toolkit middleware with react-redux connector fails I migrated redux to @reduxjs/toolkit but I'm having an issue.
Everything worked fine without the toolkit middlewares applied. When I started applying some, I got errors.
I have a component:
import React from 'react';
import type { PayloadAction } from '@reduxjs/toolkit';

import { type AppDispatch, appConnect } from '@/store/app';
import { authActions } from '@/store/reducers/auth';

import HeaderView from './Header.view';

interface IPropsFromDispatch {
    logout: () => PayloadAction;
}

interface IProps extends IPropsFromDispatch {}

const Header: React.FC<IProps> = (props: React.PropsWithChildren<IProps>) => {
    const onExitButton = () => {
        props.logout();
    };

    return <HeaderView onExitButton={onExitButton} />;
};

Header.displayName = 'Header';
Header.defaultProps = {};

const mapDispatchToProps = (dispatch: AppDispatch): IPropsFromDispatch => {
    return {
        logout: (): PayloadAction => dispatch(authActions.logout()),
    };
};

export default appConnect(null, mapDispatchToProps)(React.memo(Header));

And I have the following store:
import { configureStore } from '@reduxjs/toolkit';
import { type Connect, connect } from 'react-redux';

import authReducer from './reducers/auth';
import authListenMiddleware from './middlewares/auth';

const store = configureStore({
    reducer: {
        auth: authReducer,
    },
    middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(authListenMiddleware.middleware),
    devTools: process.env.REACT_APP_NODE_ENV === 'development',
});

export type AppState = ReturnType<typeof store.getState>;

export type AppDispatch = typeof store.dispatch;

export const appConnect = connect as Connect<AppState>;

export default store;

When I started to apply middlewares in the store, I got an error in the component file:
TS2769: No overload matches this call.
  The last overload gave the following error.
    Argument of type '(dispatch: AppDispatch) => IPropsFromDispatch' is not assignable to parameter of type 'MapDispatchToPropsParam<IPropsFromDispatch, {}>'.
      Type '(dispatch: AppDispatch) => IPropsFromDispatch' is not assignable to type 'MapDispatchToPropsFactory<IPropsFromDispatch, {}>'.
        Types of parameters 'dispatch' and 'dispatch' are incompatible.
          Type 'Dispatch<Action<unknown>>' is not assignable to type 'ThunkDispatch<{ auth: IAuthState; }, undefined, AnyAction> & ((action: Action<"listenerMiddleware/add">) => UnsubscribeListener) & Dispatch<...>'.
            Type 'Dispatch<Action<unknown>>' is not assignable to type '(action: Action<"listenerMiddleware/add">) => UnsubscribeListener'.
              Type 'Action<"listenerMiddleware/add">' is not assignable to type 'UnsubscribeListener'.
                Type 'Action<"listenerMiddleware/add">' provides no match for the signature '(unsubscribeOptions?: UnsubscribeListenerOptions | undefined): void'.

I've also tried to follow this thread:
https://github.com/reduxjs/redux-toolkit/issues/2285
But it didn't help

A: Copying the answer I provided in the issue thread:
The best fix is don't use connect any more - use the hooks API instead :)
The second-best option is to use the object form of mapDispatch, not the function form.
The third option is to pass mapDispatch as a function directly inline to connect.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting html listitem style value for comparison Hi i have a html list item thats hidden by default on the page that contains a date picker:

    Returning:
    <input type="text" id="returning" required/>
    Proper format "12/04/2014"

If the user selects that they want a return journey then the list item is made visible:

If the user click continue button then external .js file validates the form, but if they don't need a return ticket then browser displays message saying please fill in this information.
I was hoping to determine the state of the listitem style and if it was visible then show the warning else continue:
        else if (returning === "")
    {
         var item = document.getElementById("hiddenListItem");
         if(item.style.display === "list-item")
         {
            alert("Please enter a return date.");
         }
    }

I cant get the above statement to work, any help please.
HTML and JS is not my thing.

A: This should work:
if (item.style.display !== 'none') {
    alert("Please enter a return date.");
}


text:
Q: debugging post variables with webkit Webkit's Web Inspector is pretty nice, but there doesn't seem to be a good way to debug POST application/x-www-form-urlencoded variables in the requests. The "Query Parameters" palette shows up for GET requests, but nothing for POST. In fact, the only way I can see the request was indeed a POST is that the Request Headers have a Content-Type entry.
Is there a way, in Webkit, to show those variables? Such as a debugging plugin, a secret hidden preference, or simply being able to examine the content body being sent?
I'm aware that HTTP proxies such as Charles can be used here. I'd prefer to not use an additional tool if I can help it.


text:
Q: Two mobile apps use the same set of Web APIs and database, how to differentiate We are developing two mobile apps, one (A) for a group of people, another (B) for another group of people.
These two mobile apps use the same set of Web APIs, although some APIs may only be used one group and vice versa. In other words, we have just one Web API project.
Both apps' user need to register and (later) login with username and password. We save all users in the same AspNetUsers table.
Now I realize there is a problem. A user registered on app A can login on app B and a user registerd on app B can login on app A.
How do I solve this problem? Do we require the apps to send a code to our API so that our API know if its from A or B?
Thank you!

A: Asp.net membership has user roles, you can use it to authorize users to some parts of your api.

*

*Give "GroupA" or "GroupB" role to a user during registration.

*Properly set principals after authenticate.

*Use System.Web.Http.AuthorizeAttribute to authorize

  public class FooController : ApiController
  {
    [Authorize(Roles = "GroupA")]
    public void GetOnlyForGroupA(){}

    [Authorize(Roles = "GroupB")]
    public void GetOnlyForGroupB(){}

    public void GetForBoth(){}
  }


text:
Q: Vectorized (partial) inverse of an N*M*M tensor with numpy I'm almost exactly in a similar situation as the asker here over a year ago:
fast way to invert or dot kxnxn matrix
So I have a tensor with indices a[n,i,j] of dimensions (N,M,M) and I want to invert the M*M square matrix part for each n in N.
For example, suppose I have
In [1]:    a = np.arange(12)
           a.shape = (3,2,2)
           a

Out[1]: array([[[ 0,  1],
                  [ 2,  3]],

                  [[ 4,  5],
                  [ 6,  7]],

                  [[ 8,  9],
                  [10, 11]]])

Then a for loop inversion would go like this:
In [2]: inv_a = np.zeros([3,2,2])
        for m in xrange(0,3):
            inv_a[m] = np.linalg.inv(a[m])
        inv_a

Out[2]: array([[[-1.5,  0.5],
                  [ 1. ,  0. ]],

                  [[-3.5,  2.5],
                  [ 3. , -2. ]],

                  [[-5.5,  4.5],
                 [ 5. , -4. ]]])

This will apparently be implemented in NumPy 2.0, according to this issue on github...
I guess I need to install the dev version as seberg noted in the github issue thread, but is there another way to do this in vectorized manner right now?

A: Update:
In NumPy 1.8 and later, the functions in numpy.linalg are generalized universal functions.
Meaning that you can now do something like this:
import numpy as np
a = np.random.rand(12, 3, 3)
np.linalg.inv(a)

This will invert each 3x3 array and return the result as a 12x3x3 array.
See the numpy 1.8 release notes.

Original Answer:
Since N is relatively small, how about we compute the LU decomposition manually for all the matrices at once.
This ensures that the for loops involved are relatively short.
Here's how this can be done with normal NumPy syntax:
import numpy as np
from numpy.random import rand

def pylu3d(A):
    N = A.shape[1]
    for j in xrange(N-1):
        for i in xrange(j+1,N):
            #change to L
            A[:,i,j] /= A[:,j,j]
            #change to U
            A[:,i,j+1:] -= A[:,i,j:j+1] * A[:,j,j+1:]

def pylusolve(A, B):
    N = A.shape[1]
    for j in xrange(N-1):
        for i in xrange(j+1,N):
            B[:,i] -= A[:,i,j] * B[:,j]
    for j in xrange(N-1,-1,-1):
        B[:,j] /= A[:,j,j]
        for i in xrange(j):
            B[:,i] -= A[:,i,j] * B[:,j]

#usage
A = rand(1000000,3,3)
b = rand(3)
b = np.tile(b,(1000000,1))
pylu3d(A)
# A has been replaced with the LU decompositions
pylusolve(A, b)
# b has been replaced to the solutions of
# A[i] x = b[i] for each A[i] and b[i]

As I have written it, pylu3d modifies A in place to compute the LU decomposition.
After replacing each NxN matrix with its LU decomposition, pylusolve can be used to solve an MxN array b representing the right hand sides of your matrix systems.
It modifies b in place and does the proper back substitutions to solve the system.
As it is written, this implementation does not include pivoting, so it isn't numerically stable, but it should work well enough in most cases.
Depending on how your array is arranged in memory, it is probably still a good bit faster to use Cython.
Here are two Cython functions that do the same thing, but they iterate along M first.
It's not vectorized, but it is relatively fast.
from numpy cimport ndarray as ar
cimport cython

@cython.boundscheck(False)
@cython.wraparound(False)
def lu3d(ar[double,ndim=3] A):
    cdef int n, i, j, k, N=A.shape[0], h=A.shape[1], w=A.shape[2]
    for n in xrange(N):
        for j in xrange(h-1):
            for i in xrange(j+1,h):
                #change to L
                A[n,i,j] /= A[n,j,j]
                #change to U
                for k in xrange(j+1,w):
                    A[n,i,k] -= A[n,i,j] * A[n,j,k]

@cython.boundscheck(False)
@cython.wraparound(False)
def lusolve(ar[double,ndim=3] A, ar[double,ndim=2] b):
    cdef int n, i, j, N=A.shape[0], h=A.shape[1]
    for n in xrange(N):
        for j in xrange(h-1):
            for i in xrange(j+1,h):
                b[n,i] -= A[n,i,j] * b[n,j]
        for j in xrange(h-1,-1,-1):
            b[n,j] /= A[n,j,j]
            for i in xrange(j):
                b[n,i] -= A[n,i,j] * b[n,j]

You could also try using Numba, though I couldn't get it to run as fast as Cython in this case.


text:
Q: wait for button click on button click move button to a slot in tkinter I get the title wasn't the best but I don't quite know how to explain it. I tkinter I want to make square widgets with "slots on them. When the app is run I want buttons to show up at the top of the screen and a 4x4 grid of the square widgets. the app to wait for a user to click on a button. Then that button should move into the top left slot on the top left square. After this is done the user should repeat the process and the next button should go into the next slot on the top left square and so on until the square is full, the repeat the process with the next square. The should also be an fixed position button that allows me to pass on a slot without putting things in it? How should I accomplish this? I already have the for loop I need:
 for elem in zip(*l):
    for a in elem:
        print(a)

A: I'm not entirely sure if I understand your problem correctly, but it looks like at the core, you're basically trying to reposition tkinter widgets, correct?
You can do this with your geometry manager. If you use the grid method (which in your case I would recommend) then you can do:
def changeButtonPostion():
    button2.grid_remove() #gets rid of the widget in the top left corner
    button.grid(row=0, column=1) #the top left corner of your 4x4 grid

Otherwise, you can use the pack_forget method if you use the pack geometry manager.


text:
Q: Core Data Where clause between two tables? I have two tables that I would like to get data and from by seeing if they match a particular attribute.
I want to write a predicate or something like this but I do not seem to be able to come up with a solution: @"Data.item == Item.code".
The reason why I don't use relationships is because my database was imported from mysql. So all the data is coming from outside of the app its being synced from downloaded mysql tables.
---------------------------EDIT-------------------------
What I have tried so far lots of things here is the crappy way I am doing this now perhaps from this you can understand more of what I am trying to do .
 NSPredicate * Newpredicate = [NSPredicate predicateWithFormat:@"hid == 2"];
    NSArray *row2 = [db DLook:Newpredicate table:@"Data"];
    for (NSManagedObject *data in row2) {
        NSLog(@"\n\n\n\nid\n\n\n\n: %@", [data valueForKey:@"id"]);
        NSString *itemToCode = [data valueForKey:@"item"];
        NSPredicate *itemPredicate = [NSPredicate predicateWithFormat:@"code == %@",itemToCode];
        NSArray *itemRow = [db DLook:itemPredicate table:@"Item"];
        for (NSManagedObject *item in itemRow) {
            NSLog(@"\n\n\n\ncode : %@\n\n\n\n",[item valueForKey:@"code"]);
        }
       // NSLog(@"id: %@", [data valueForKey:@"id"]);
        //NSManagedObject * itemhid= [data valueForKey:@"testRel"];
        //NSLog(@"code: %@",[itemhid valueForKey:@"code"]);
    }
    NSLog(@"\n\n\n\n%d\n\n\n\n",[row2 count]);

The DLook is a convince method that just fetches the data using the predicate on the table that I pass.  Then take the returned area of NSmanaged objects looping through them.
I wish I could just make a magical relationship that would let me get a all the Item.data that match the Data.items!!!
I don't want to do it like this I want to make a relationship that would work like that.
Help
Thanks

A: Your equality in the predicate would only be true if the two objects are actually the same object. You could do this:
[NSPredicate predicateWithFormat:@"item = %@", code];

However, you should really try to get the relationships right when importing your model. Then you would not even have to do a fetch from the store but just use
dataObject.item;

So, when you import do something like this:
// get one data object from your source
// get the corresponding item object from your source
Data *dataObject = [NSEntityDescription insertNewObjectForEntityForName:@"Data"
     inManagedObjectContext:self.managedObjectContext];
Item *itemObject = [NSEntityDescription insertNewObjectForEntityForName:@"Item"
     inManagedObjectContext:self.managedObjectContext];
[dataObject addItemObject:itemObject];


text:
Q: Prevent element stacking with CSS When there are multiple of the following element they are shown right on top of each other, as if the z-index is different on each element.  I'd like for them to stack up against the right side of the screen, going up the side of the screen and then as they "fade away" via my javascript for them to slide down to the right corner... I hope that makes sense.  I'm not sure the best method to accomplish this...
.push-notification {
    background-color: #000;
    position: fixed;
    right: 20px;
    bottom: 20px;
    color: #fff;
    padding: 15px 15px 15px 30px;
    -webkit-border-top-right-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
    background-repeat: no-repeat;
        background-position: 7px center;
    opacity: 0.7;
    filter: alpha(opacity=70);
    vertical-align: middle;
    box-shadow: 4px 4px 4px #000;
    -webkit-box-shadow: 4px 4px 4px #000;
    -moz-box-shadow: 4px 4px 4px #000;
}

A: I think 'postion: fixed;' is your culprit.

A: I'm pretty sure you'd want something like this: http://jsfiddle.net/z8nJk/2/
We first create a container that acts like a "queue" for the notifications, then stick it to the top right corner of the user's screen. The HTML will look like this:

Your notification here

You should position #side to the top right corner with position: fixed.
#side {
    position: fixed;
    right: 10px;
    top: 10px;
}

Then modify the notification code slightly like this:
.push-notification {
    background-color: #000;
    color: #fff;
    padding: 10px 15px 13px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;

    opacity: 0.7;
    filter: alpha(opacity=70);

    -webkit-box-shadow: 4px 4px 4px rgba(0, 0, 0, 0.3);
    -moz-box-shadow: 4px 4px 4px rgba(0, 0, 0, 0.3);
    box-shadow: 4px 4px 4px rgba(0, 0, 0, 0.3);

    width: 200px;
    font-family: Arial;

    font-size: 12px;
    line-height: 1.4em;
    margin-bottom: 10px;
}

And finally some simple jQuery to add and fade away the old notifications.

A: position: fixed;
right: 20px;
bottom: 20px;

When you apply this class to multiple things, each of them are going to end up in the exact same location 20px from the right and 20px from the bottom of the page which is why they end up on top of one another.
You probably want to make a single container or column that takes up the entire right side of your page and then fill it with your items.


text:
Q: Very confused with ember redirect and/or renderTemplate I'm new to ember, and am really struggling with how to accomplish what should be a fairly simple task.
I'm trying to put my resume into an ember app.
As part of my resume, I have a few references.
When someone hits the 'references' link in the navigation, I'd like it to show the links to each reference, as well as the first reference, displayed as a child to the links.
Apparently, my options here are to either redirect to the 'references/1' url(not really ideal), or display the 'reference' template.
I'd build a JSFiddle for this, but jsfiddle seems to be broken as I can't load or view anything already up there.
I have this working with regular routes, where I load references, it shows the links, and if I click on a link, or load the page directly with the 'references/2' url, it shows the correct content.
If I redirect using

App.ReferencesRoute = Ember.Route.extend({
    model: function(){
        return App.References.find();
    },
    redirect: function(){
        this.transitionTo('reference',App.References.find(1));
    }

});

I get the url redirecting correctly, but I don't get the links to the references. I do get the  'reference' template loaded, but  the model isn't getting passed. I've tried using this.modelFor('references').get('firstObject') but that doesn't return anything either, which is why I'm using find(1).
If I try to do this with the render template and controller like this

App.ReferencesRoute = Ember.Route.extend({
    model: function(){
        return App.References.find();
    },
    renderTemplate: function(){
        this.render();
        this.render('reference',{into: 'references',controller:'reference'});

    }
});

App.ReferenceController = Ember.ObjectController.extend({
    letter: 'test letter'
});

I get the links and the 'test letter' message but I run into a few other problems.
1) I can't figure out how to pass the Reference controller the first model so that it actually returns the same as if the user was at the '/references/1' url
2) If I click the links, the selected letter is not displayed, meaning the links don't work if I use the controller.
3) I'd want the first link to be active, as that is the letter which is already showing, but that is a minor detail compared to the other issues.
Am I going about this completely wrong? Is there something big that I'm missing?

A: for passing the model via a redirect i use something like this:
App.ReferencesIndexRoute = Ember.Route.extend({
   model    : function(){
       return App.References.find();
   },
   redirect : function(){
      var model = this.controllerFor('references').get('model');
      this.transitionTo('reference', model);
   }
});


text:
Q: Where is AsyncStorage Data Physically Located on Android Devices? Maybe the title isn't very clear. Here is what I mean/need to know-
If I use SQLite for some data storing purpose on Android app, I can see the DB created in my phone. (/root/data or something I guess). I have viewed the DB and performed some manipulations, it helps in development.
Now, I am using AsyncStorage API of react native.
There is some problem in my code, I am not able to get the stored data from the store. Not sure what I am doing wrong.
So, to see what's wrong, is there a way to view the list of Objects that are being stored on the phone? If so where? And how do I view it?
PS: I am debugging my React Native app using Android Studio's logs. As my chrome on linux is a bad boy(Any Help would be appreciated)!

A: React Native on Android actually uses SQLite to back up the AsyncStorage API. The database file is /data/data/<your_app>/databases/RKStorage on your device/emulator. Keys and values are stored in a table named catalystLocalStorage.

A: Use sqlite3 /data/data/<your_app>/databases/RKStorage .dump to see entire content. And use cp /data/data/<your_app>/databases/RKStorage /mnt/sdcard/ and use adb pull/push to copy it to your local device.

A: You can follow below steps

*

*Run your apk in debug mode in your device and connect your device to your system

*Open command prompt.

*To get list of databases related to your application use below command

adb -d shell "run-as om.yourpackage_name ls
  /data/data/com.yourpackage_name/databases/

you can get package name from your AndroidManifest.xml file

*Now you have database name in above list then copy that database to sdcard in your phone using following command for react native it will be RKStorage

adb -d shell "run-as com.yourpackage cp /data/data/com.your_package/databases/RKStorage /sdcard/Rkstorage"

*Now use below command to pull above copied database from your device to your system. below command will copy database to directory where adb.exe exists.

adb pull /sdcard/Rkstorage

*Now Install Firefox SQLite Manager: https://addons.mozilla.org/en-US/firefox/addon/sqlite-manager/

*Open Firefox SQLite Manager from Tools->SQLite Manager

*In SQLite Manager go to Database->Connect Database and "open file" window will open there you select All files at bottom of your window and navigate where your database copied.
Thanks.

A: If you are working on react-native and using react-native-sqlite-storage, then you can find the DB file <aap-name>/android/app/src/main/assets/www/<db-named-file> for Android. And for iOS, DB file location is <app-name>/ios/<app-name>/www/<db-named-file>.


text:
Q: Is there a delay in the effect of the gravitational or electromagnetic force if a secondary body suddenly appears? If the sun were to suddenly vanish in our solar system, it would take about 8 minutes for the Earth to exit its orbit. This is because the gravitational field of the sun would vanish at a rate of $c$. I am basing this on a question where the sun suddenly disappeared.
However, suppose the sun was already present for, say, a million years. If I were to suddenly add a massive body, such as a planet, at a distance of 149.60 million kilometres (the current average radius of the Earth's orbit), then shouldn't the planet immediately be attracted to the sun? Would there be a delay? And, if so, why?
This question would also apply to charges and electromagnetic fields since they also travel at the speed of light.

A: Note: your example isn't quite right, because Einstein's field equation implies $\partial_\mu T^{\mu\nu} = 0$, i.e. conservation of energy. Attempting to consider a situation where a mass suddenly appears 'out of nowhere' is mathematically self-contradictory in GR. But, putting this issue aside...

Yes, the planet would immediately be attracted to the sun. But the sun wouldn't be immediately attracted to the planet, since the effect of the planet needs to propagate at light speed!
You might think this is paradoxical, since it violates Newton's third law. Indeed, situations like this come up all the time when a mediating field is involved. For example, there are cases where the forces between two moving charges are not equal and opposite (see here).
The resolution is to view the field as a physical intermediate object: the charges are not acting on each other, but separately acting on the field, and these two force pairs each satisfy Newton's third law. Since the field can act and be acted on by forces, it must carry momentum. Total momentum is conserved, as long as we account for this field momentum.
However, this resolution doesn't work in GR, because we cannot define the energy/momentum of the gravitational field (see here). This goes back to my initial point, which is that this situation is not physical. But it does illustrate an important physical principle.


text:
Q: How can I avoid error MSB3073 with code -1 from Exec with visual studio while still using sysnative virtual folder This is a followup of a question I asked before. In a nutshell I run a 64 bit version of cmd from visual studio (which is 32 bit application). I do this because I need to run a command oscdimg.exe which is only accessible from 64 bit version of cmd.
  <Target Name="AfterBuild">
    <Exec Command="%windir%\sysnative\cmd.exe /c "$(ProjectDir)test.bat UPLOAD"" WorkingDirectory="$(ProjectDir)" />
  </Target>

Now while this works fine, I receive following error.
error MSB3073: The command "%windir%\sysnative\cmd.exe /c "C:\XXXX\XXX\XXX\test.bat UPLOAD"" exited with code -1.
While this error is not disrupting my work, meaning the batch performs its tasks successfully, it still is nice to fix this error message, as others in my team questions this error message.
I am making an assumption that this error is triggered because although the visual studio is 32 bit application, the build or exec calls for windows operating system application which may be 64 bit application. And 64 bit application cannot see the sysnative virtual folder.
Is there any way to resolve this error?
EDIT: Added argument to the command to simulate the real use and to show the reason I add ".

A: One of the recent surprise for me is that robocopy returns 1 when it finishes the copy successfully, the author @Valamas shows in italic

Confusion will set in when no files are copied = no error in VS. Then when there are changes, files do get copied, VS errors but everything the developer wanted was done.

VS picks up and interprets this return value as an error when robocopy is the last command in the batch file.
In the case of robocopy, VS returns 1 and not -1 so it is slightly different from my current situation. However, since my batch file is functioning as intended, I felt safe enough to return 0 once the batch is completed without error.
exit 0

And I no longer see the MSB3073.
For this post's issue, since oscdimg is my last command in the batch file, I am assuming that oscdimg returns non-zero value after it succeeds.
I could not find supporting document regarding oscdimg.


text:
Q: Can WinUSB be used to communicate with any USB device? Is there a way to determine whether or not I can use WinUSB with any given device?
I am attempting to see if I can use libusb with USB3 Vision devices. This is the first time I have ever tried to communicate with a USB device so I am having some difficulties.
From libusb's site I know that it requires using WinUSB as the driver for the device. It also seems like WinUSB is a safe bet for a lot of devices, but I am having a hard time finding out whether WinUSB can be used with USB3 Vision devices.
Since I wasn't able to find a direct yes or no online, I tried using Zadig to install WinUSB, with no luck. I have also tried making a custom inf file and trying to install the WinUSB driver through the device manager. Obviously I haven't had much luck.
I know that USB3 Vision is relatively new, so I know there might not be many people out there who have tried doing anything similar. So I am wondering if it is worth it to continue trying to install WinUSB as a driver for the device. Is there some way of knowing for sure that it will or will not work with my device?

Update:
The device doesn't seem to have any compatible ID's in its Details section (Device Manager -> Right click on Device -> Properties -> Details).
Is it possible that the lack of a WinUSB Compatible ID means it isn't compatible for sure?


text:
Q: JavaScript array won't update and can't type anything in inputs When I click the 'create note' button on my expense manager website the edit page appears but keeps trying to reload and i'm not able to type anything in either of the inputs.
I'm receiving one error: 'Cannot read property 'title' of undefined' and a message: ' Throttling navigation to prevent the browser from hanging. Command line switch --disable-ipc-flooding-protection can be used to bypass the protection'
I expected to be able to create an expense and to see it updated when I returned to the home page however I can't even type anything and nothing will update anyway.
// JS code
// Read existing expenses from localStorage
const getSavedExpenses = function () {
    const expensesJSON = localStorage.getItem('expenses')

    if (expensesJSON !== null) {
        return JSON.parse(expensesJSON)
    } else {
        return []
    }
}
// Save expenses to localStorage
const saveExpenses = (expenses) => {
    localStorage.setItem('expenses', JSON.stringify(expenses))
}

const titleElement = document.querySelector('#expense-title')
const bodyElement = document.querySelector('#expense-body')
const removeElement = document.querySelector('#remove-note')
const expenseId = location.hash.substring(1)
const expenses = getSavedExpenses()
const expense = expenses.find(function (expense) {
    return expense.id === expenseId
})

// Get the DOM elements for an individual expense
const generateExpenseDOM = function (expense) {
    const expenseEl = document.createElement('div')
    const textEl = document.createElement('a')
    const removeButton = document.createElement('button')

// Setup the expense text
if (expense.title.length > 0) {
    textEl.textContent = expense.title
} else {
    textEl.textContent = 'Unnamed note'
}
textEl.setAttribute('href', `expense-edit.html#${expense.id}`)
expenseEl.appendChild(textEl)

// Remove expense by id
const removeExpense = function (id) {
const expenseIndex = expenses.findIndex(function (expense) {
return expense.id === id
})
if (expenseIndex > -1) {
    expenses.splice(expenseIndex, 1)
  }
}

// Setup the remove expense button
removeButton.textContent = 'x'
expenseEl.appendChild(removeButton)
removeButton.addEventListener('click', function () {
    removeExpense(expense.id)
    getSavedExpenses(expenses)
    renderExpenses(expenses, filters)
})
return expenseEl
}

if (expense === undefined) {
    location.assign('expense-edit.html')
}

titleElement.value = expense.title
bodyElement.value = expense.body

titleElement.addEventListener('input', function (e) {
    expense.title = e.target.value
    savedExpenses(expenses)
})
// add new expenses
document.querySelector('#new-expense').addEventListener('click', function (e) {
   const id = uuidv4()
      expenses.push({
         id: id,
         title: '',
         body: ''
      })
      getSavedExpenses()
     location.assign(`/expense-edit.html#${id}`)
   })

// HTML code
   <input id="title" placeholder="Expense title">
    <textarea id="body" placeholder="Expense body"></textarea>
    <button id="remove-expenses">Remove expense</button>

   <input id="search-text" type="text" placeholder="Filter todos">

    <button id="new-expense">Submit</button>

A: There are two places where you use location.assign(), which navigates to a new page.
My guess is this one keeps triggering:
if (expense === undefined) {
    location.assign('expense-edit.html')
}

expense is undefined, so the page reloads; expense is undefined, so the page reloads again...
Figure out why expense does not have a value. (You can also just comment these lines out to confirm that this is, in fact, the problem.)

update: Additionally, I think you are assuming variables (like the expenses array) persist across page loads. JS variables do not persist across page loads. After you call location.assign(), all JS variables reset.
So this part of the code doesn't really do anything:
expenses.push({
     id: id,
     title: '',
     body: ''
  })

I wasn't sure what happens in getSavedExpenses(), and thought maybe variables were persisted there via localstorage or something. (Otherwise that is probably also dead code, since its return value isn't even used.)
There are two ways to persist data across "page loads":

*

*Save the data to persistent storage, like a database or localstorage. Then reload the data the next time the page is loaded. If a database is used, usually data from a form is sent via an API request to a database server.

*Don't reload the page; modify the page DOM via JS (so it might look like the page "reloaded.")

update 2:

TypeError: Cannot set property 'value' of null

This error is caused by trying to access a property called value on a variable with the value null. In your code, that is happening in two places:
titleElement.value = expense.title
bodyElement.value = expense.body

After the error is encountered, JS stops executing. This is likely the reason localStorage.getItem('expenses') results in null.


text:
Q: Не могу сделать поиск alt+: windows, ssh putty, Midnight Commander Захожу на linux машину по ssh через putty с windows, на машине есть mc.
Вот только что надо поменять в настройках putty чтоб корректно mc реагировал на нажатия alt? Вроде по alt+? должен появится диалог поиска.
везде стоит xterm, и в putty и echo $TEMP

A: Один из вариантов - перейти на связку far2l + putty4far2l (мой форк putty). Все привычные горячие клавиши классического двухпанельника заработают. Если mc запускать в far2l в putty4far2l, тоже все хоткеи работать будут. В качестве бонуса получите работающий через ssh буфер обмена :)


text:
Q: Setting a javascript date to be static How can i make this code to give me a static date?Like if I post something on 10 december 2015 at 15:03 2015 to show that date,not the current date.
        var d = new Date();
var months = new Array ("Ianuarie","Februarie", "Martie","Aprilie","Mai","Iunie","Iulie","August","Septembrie","Octombrie","Noiembrie","Decembrie");
var day = d.getUTCDay();
var  month = months[d.getUTCMonth()];
var hour = d.getUTCHours();
var year = d.getUTCFullYear();
if(hour < 10) {
    hour = "0" + hour;
}
var minutes = d.getUTCMinutes();
if (minutes < 10) {
    minutes = "0" + minutes;
}
document.getElementById("date").innerHTML = ("Postat pe " + day + " " + month + " la ora " + hour + ":" +  minutes + " | " + year ).toString();

A: Try something like this(e.g if your date is "10/10/2004"):
var d = new Date("10/10/2004")


text:
Q: Wordpress import csv custom fields I'm working with Wordpress and I need to import a csv file but my project has too many custom fields and every WP plugin I've seen does not work with this feature (or it is buggy).
Any advice about a nice plugin? Thanks

A: Did you tried wp ultimate csv importer? It is very nice plugin to handle csv imports. What custom field plugin you are using? Free version support wordpress custom fields and CPT plugin fields. For types, cctm and ACF fields you need the pro version of this plugin.


text:
Q: wpf DockPanel issue I have DockPanel with ListView and StackPanel:
<DockPanel Margin="5" LastChildFill="True">
    <ListView Margin="5" ItemsSource="{Binding Source={StaticResource taxGroupSource}}" DockPanel.Dock="Top" VerticalContentAlignment="Stretch" HorizontalContentAlignment="Stretch" VerticalAlignment="Stretch">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding SerialNumber}" />
                <GridViewColumn Header="First Name" DisplayMemberBinding="{Binding Name}" />
            </GridView>
        </ListView.View>
    </ListView>
    <StackPanel DockPanel.Dock="Bottom" Style="{StaticResource buttonPanel}">
        <Button Content="Close" Click="CloseClick"/>
    </StackPanel>
</DockPanel>

When GridView have great rows count, ListView overlaps bottom StackPanel. Why?

A: I believe the issue is your LastChildFill on the DockPanel iteself. As explained by MSDN, LastChildFill makes it so that your StackPanel takes the remaining space in the DockPanel, even though you have set it to dock at the bottom. Try removing the attribute and seeing if that helps.
Edit: Removing the attribute alone does not do it. I got the expected behavior by swapping the ListView and StackPanel, but that changes the tab order (although here it is only between two items so setting the focus to the ListView makes it look right).
Alternately, can you use a grid with two rows--the ListView in the first row with a height of "*" and the StackPanel in the second with a height of "Auto"? Or is this a simplification of a more complex layout where that would not work?

A: As @DocMax said the last child fill would work ONLY if there is some space available in the dockpanel after all previous children are occupied. For ListView having  large number of rows, the space is already taken up by it so stackpanel is left with no space to occupy.
I suggst you supply some MinHeight to the stackpanel.

A: If you don't want to use Grid, then you can solve it by adding StackPanel first and then ListView, with using LastChildFill="True".


text:
Q: Calculating the correlation between various columns of a matrix in R I have the following matrix mat in R:
      x  y  z
rowA -1  1  2
rowB -1 -2 -1
rowC  2  1 -1

How do I calculate the correlation between various columns of the matrix (say, corr(x, y), corr(y, z), corr(x, z)), rather than separating the columns into vectors?

A: you can do:
#gives pairwise
COR = cor(M)
# to get 1 vs 2, 1 vs 3 and 2 vs 3
COR[upper.tri(COR)]

A: We can use combn to create combination of column names taking 2 at a time, subset the combination from the matrix and then calculate the correlation between them.
combn(colnames(mat), 2, function(x) cor(mat[, x[1]], mat[, x[2]]))
#[1]  0.5 -0.5  0.5

data
mat <- structure(c(-1L, -1L, 2L, 1L, -2L, 1L, 2L, -1L, -1L), .Dim = c(3L,
3L), .Dimnames = list(c("rowA", "rowB", "rowC"), c("x", "y", "z")))

A: Base R:
cor_df <- data.frame(vars = row.names(cor(mat)), cor(mat), row.names = NULL)


text:
Q: Error message when using aliases with cypressIO I get the following error message when using: "TypeError: Cannot read property 'text' of undefined"
I´ve done exactly as they do in the documentation: https://docs.cypress.io/guides/core-concepts/variables-and-aliases.html#Aliases
Can anyone see what i´m doing wrong?
beforeEach(() => {
    cy.visit('http://localhost:4200/');
    loginPage.login();
    timeFilter.button.click();
    cy.get('#title').invoke('text').as('text');
  });

  it('should show text', () => {
    console.log(this.text);
  });

A: Read the cypress documentation and the problem i did was using arrow functions and i did not access the alias in a closure using a .then(). As soon as i did this, it worked:
cy.get('#title').invoke('text').as('text');

it('should show text', () => {
    cy.get('#main').then(function () {
      console.log(this.text);
    });
  });

OR use function() instead of () => on the it() callback
cy.get('#title').invoke('text').as('text');

it('should show text', function() {
  console.log(this.text);
});

A: Text has always been a pain in cypress.  This could be one of a few things:
1) Sometimes this.alias doesn't work, try using:
cy.get('@text').then(text => console.log(text));
2) If the text is contained in an element below #title, you will have to get that specific element.  For example, #title might be a div, which contains an h1 element inside of it, so in that case you would need to use #title > h1 as your selector.  Post your HTML and I'll be able to tell if that's the case
3) invoke('text') almost never works, I'm not sure why.  I find this works much more often cy.get('#title').then($el => el.text())


text:
Q: Maximal and maximum (matchings)
*

*Maximal and maximum matchings seem to be with respect to different
partial orders, do they? In the set of all matchings in a graph,  a
maximal matching is with respect to a partial order defined by
growing a matching, while a maximum matching is with respect to a
partial order defined by its size.

*Wikipedia says:

While a partially ordered set can have at most one each maximum and minimum it may have multiple maximal and minimal elements.

But there can be several maximum matchings in a graph. What goes
wrong?
Thanks!

A: What you call "with respect to a partial order defined by growing a matching" is usually referred to as "(partially) ordered by inclusion".
A maximum matching isn't defined with respect to a partial order defined by size. This is because a partial order requires $(a\le b\land b\le a)\Rightarrow a=b$, whereas two matchings may have the same size yet be different. Thus, it's only the sizes that are partially (in fact totally) ordered, not the matchings. There is indeed only one maximum size, but several maximum matchings may have it.


text:
Q: Exact Target API: using Soap using Sample Java Code (Axis 1.4) from
https://help.exacttarget.com/en/technical_library/web_service_guide/technical_articles/creating_an_import_definition/
there is an error on the line:
Soap stub = init();
what is this object type "Soap", where should it be imported from?
Sample Java Code (Axis 1.4)
public class ImportDefTestCase extends BaseTestCase {

public void testCreateImportDef() throws RemoteException {

    Soap stub = init();
    ImportDefinition impDef = new ImportDefinition();
    impDef.setName("ImportDefinitionSeed_1");
    impDef.setCustomerKey("ImportDefinitionSeed_1");
    impDef.setDescription("This import definition was created through the API.");

    impDef.setAllowErrors(true);

    impDef.setDestinationObject(new List());
    impDef.getDestinationObject().setID(new Integer(2464));

    // Specify the notification type (optional)

    AsyncResponse asyncResponse = new AsyncResponse();
    asyncResponse.setResponseType(AsyncResponseType.email);
    asyncResponse.setResponseAddress("test@example.com");
    impDef.setNotification(asyncResponse);

    FileTransferLocation fileTransferLocation = new FileTransferLocation();
    fileTransferLocation.setCustomerKey("ExactTarget Enhanced FTP");
    impDef.setRetrieveFileTransferLocation(fileTransferLocation);

    impDef.setUpdateType(ImportDefinitionUpdateType.AddAndDoNotUpdate);
    // Map fields (required)
    impDef.setFieldMappingType(ImportDefinitionFieldMappingType.MapByOrdinal);

    FieldMap map1 = new FieldMap();
    map1.setDestinationName("Subscriber Key");
    map1.setSourceName("1");
    //map1.setSourceOrdinal(new Integer(1));
    FieldMap map2 = new FieldMap();
    map2.setDestinationName("Email Address");
    //map2.setSourceOrdinal(new Integer(2));
    map2.setSourceName("2");

    FieldMap[] maps = {map1, map2};
    impDef.setFieldMaps(maps);
    impDef.setFileSpec("12345.csv");

    // Specify the FileType
    impDef.setFileType(FileType.CSV);

    //Assign ImportDefinition to sub-account
    ClientID clientID = new ClientID();
    clientID.setPartnerClientKey("12345");// Partner Key
    impDef.setClient(clientID);

    CreateRequest createRequest = new CreateRequest();
    createRequest.setOptions(new CreateOptions());
    APIObject[] apiObjectList = {impDef};
    createRequest.setObjects(apiObjectList);
    CreateResponse createResponse = stub.create(createRequest);
    System.out.println("CreateResponse ::: " + createResponse.getOverallStatus());

}

public void testCreateImportDefToDataExtension() throws RemoteException {

    try {
        Soap stub = init();

        DataExtension dataExtension = getDataExtension(stub);
        ImportDefinition impDef = new ImportDefinition();
        impDef.setName("Import_Definition_UpdateButDoNotAdd");
        impDef.setCustomerKey("Import_UpdateButDoNotAdd_Key");
        impDef.setDescription("Import_Definition_UpdateButDoNotAdd_Desc");

        impDef.setAllowErrors(true);

        //dataExtension.setID(new Integer(12345));
        impDef.setDestinationObject(dataExtension);

        // Specify the notification type (optional)

        AsyncResponse asyncResponse = new AsyncResponse();
        asyncResponse.setResponseType(AsyncResponseType.email);
        asyncResponse.setResponseAddress("test@example.com");
        impDef.setNotification(asyncResponse);

        FileTransferLocation fileTransferLocation = new FileTransferLocation();
        fileTransferLocation.setCustomerKey("ExactTarget Enhanced FTP");
        impDef.setRetrieveFileTransferLocation(fileTransferLocation);

        impDef.setUpdateType(ImportDefinitionUpdateType.UpdateButDoNotAdd);
        // Map fields (required)
        //impDef.setFieldMappingType(ImportDefinitionFieldMappingType.MapByOrdinal);
        impDef.setFieldMappingType(ImportDefinitionFieldMappingType.InferFromColumnHeadings);
        //impDef.setSubscriberImportType(ImportDefinitionSubscriberImportType.Email);

        FieldMap map1 = new FieldMap();
        map1.setDestinationName("EmailId");
        map1.setSourceOrdinal(new Integer(1));
        FieldMap map2 = new FieldMap();
        map2.setDestinationName("StatusField");
        map2.setSourceOrdinal(new Integer(2));

        FieldMap[] maps = {map1, map2};
        impDef.setFieldMaps(maps);
        impDef.setFileSpec("Test2.csv");

        // Specify the FileType
        impDef.setFileType(FileType.CSV);

        //impDef.setClient(dataExtension.getClient());

        CreateRequest createRequest = new CreateRequest();
        createRequest.setOptions(new CreateOptions());
        APIObject[] apiObjectList = {impDef};
        createRequest.setObjects(apiObjectList);
        CreateResponse createResponse = stub.create(createRequest);
        System.out.println("CreateResponse ::: " + createResponse.getOverallStatus());
    } catch (RemoteException e) {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    } catch (IOException e) {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    }

}

This sample code creates an import definition and associates it with a specific data extension.
/**
 * Creating Import-Definition and associating it with a Data Extension
 *
 * @throws RemoteException
 */

   public void testCreateImportDefToDataExtensionMarket2Lead() throws RemoteException{
    try {
        Soap_PortType stub = init();
        ImportDefinition impDef = new ImportDefinition();
        impDef.setName("Import_To_DE");
        impDef.setCustomerKey("Import_To_DE_Key");
        impDef.setDescription("Import_To_DE");
        impDef.setAllowErrors(true);

        // Associate Data-Extenison to Import-Defintion
    DataExtension dataExtension = new DataExtension();
        dataExtension.setCustomerKey("UsingAPI_For_Key");
        impDef.setDestinationObject(dataExtension);

        // Specify the notification
        AsyncResponse asyncResponse = new AsyncResponse();
        asyncResponse.setResponseType(AsyncResponseType.email);
        asyncResponse.setResponseAddress("response@example.com");
        impDef.setNotification(asyncResponse);

    //Specify Location of File, In this case it is FTP
    FileTransferLocation fileTransferLocation = new FileTransferLocation();
        fileTransferLocation.setCustomerKey("ExactTarget Enhanced FTP");
        impDef.setRetrieveFileTransferLocation(fileTransferLocation);
        impDef.setUpdateType(ImportDefinitionUpdateType.AddAndDoNotUpdate);

        //Map fields by Column headings.
        impDef.setFieldMappingType(ImportDefinitionFieldMappingType.InferFromColumnHeadings);
        FieldMap map1 = new FieldMap();
        map1.setDestinationName("EmailAddress");

        //map1.setSourceOrdinal(new Integer(1));
        FieldMap map2 = new FieldMap();
        map2.setDestinationName("ChannelUser");

        //map2.setSourceOrdinal(new Integer(2));
        FieldMap map3 = new FieldMap();
        map3.setDestinationName("ChannelUser_EmailAddress");
        FieldMap map4 = new FieldMap();
        map4.setDestinationName("Demographic_Address");
        FieldMap[] maps = {map1, map2, map3, map4};
        impDef.setFieldMaps(maps);
        impDef.setFileSpec("Import2L.csv");

        // Specify the FileType
        impDef.setFileType(FileType.CSV);
        CreateRequest createRequest = new CreateRequest();
        createRequest.setOptions(new CreateOptions());
        APIObject[] apiObjectList = {impDef};
        createRequest.setObjects(apiObjectList);
        CreateResponse createResponse = stub.create(createRequest);

        //ImportResultsSummary importResultsSummary = (ImportResultsSummary) createResponse.getResults();
        System.out.println("CreateResponse ::: " + createResponse.getOverallStatus());

        }
        catch (RemoteException e)
        {
        e.printStackTrace();
        }
        catch (IOException e)
        {
        e.printStackTrace();
        }
    }

A: If you are doing a new implementation, I would recommend using Axis2.0.  Axis1.4 has known issues with handling double-byte characters.  An example of creating an import definition for Axis2.0 can be found at:
https://github.com/MichaelAllenClark/exacttarget-soap-java/blob/master/src/com/exacttarget/example/CreateImportDefinition.java
That GitHub Repo contains a complete project where that code example is used.


text:
Q: If two different symmetric positive definite matrices have equal determinants then $A-B$ is neither positive semidefinite nor negative definite Recently I've asked question about the set given as $\{x: x^T(A-B)x = 1\}$. In that question I wanted to prove that such set isn't bounded, and according to the answer I can do it if I can prove the fact from the title of this question i.e.:

If $A$ and $B$ are different, symmetric, positive definite $n \times n$ $(n > 1)$ matrices such that $\det A = \det B$ then the matrix $A - B$ is neither positive semidefinite nor negative definite

Could you please help me to start the proof? I have no idea how to do it (namely how to use the equality of determinants)

A: Audience request: we can begin with orthogonal $Q$ such that $Q^TB Q = D$ is diagonal with positive diagonal elements. We can then continue with a diagonal matrix $W$ with diagonal elements certain reciprocals of square roots, so that $W Q^T BQW = W^T Q^T B Q W = I,$ and name P = QW.$
there is a matrix $P$ with $\det P \neq 0$ so that $P^T B P = I.$ Then
$$ P^T ( A - B) P = C - I,   $$
where $$  C = P^T A P  $$
is symmetric,  positive definite and, since $\det B \cdot \det^2 P = 1,$ so $\det A \cdot \det^2 P = 1,$ we get  $$  \det C = 1.$$
Let's see, if all eigenvalues of $C$ are equal to $1$ then it is the identity matrix; that needs a little proof using symmetry and orthogonal matrices. In this case, $A = B$ and $x^T (A-B)x = 1$ is impossible.
Otherwise, $C$ has an eigenvalue larger than $1$ and another eigenvalue smaller than $1,$ which tells us that $C-I$ is indefinite.
You should look up Sylvester's Law of Inertia, which has to do with the "congruence" I am using.


text:
Q: How to pass a list of function names as a parameter? How to use a function name as a parameter in Python?
For example:
def do_something_with(func_name, arg):
    return func_name(arg)

where 'func_name' might be 'mean', 'std', 'sort', etc.
For example:
import numpy as np
func_list = ['mean', 'std']

for func in func_list:
    x = np.random.random(10)
    print do_something_with(func, x)

and of course the result should a successful application of 'mean' and 'std' on my array 'x'.

A: Tadhg McDonald-Jensen's solution is right because function is first-class citizen in Python. Also, I have another idea:
from operator import methodcaller

import numpy as np

func_list = ['mean', 'std']
for func in func_list:
    x = np.random.random(10)
    f = methodcaller(func, x)
    result = f(np)
    print(result)

You can use operator.methodcaller for some cases.

A: As suggestet in the comments, pass function objects in a list to your function and call them. This will not just work with numpy, but with all Python functions:
import numpy as np
func_list = [np.mean, np.std]

for func in func_list:
    x = np.random.random(10)
    print func(x)

Make sure the function calls work all the same way, i.e. x as first parameter.
The above is pretty similar to how function renaming works:
import time

another_sleep = time.sleep
another_sleep(1)  # Sleep for one second

You create a function object (time.sleep) and assign it to a variable (another_sleep). Now you can call it with the variable's name (another_sleep(1)).


text:
Q: Is Shakespeare proper English?
"Divides one thing entire to many objects; Like perspectives, which rightly gazed upon show nothing but confusion..." - William Shakespeare, The Tragedy of King Richard the Second

I read plenty of Shakespeare in high school, especially in drama. I have a lot of difficulty making sense of things he says, such as the above.
Is Shakespeare proper English?  Would this have been clear, easily understood material back in his day?  In other words, have all the changes in the English language over time made the material difficult to comprehend?  Is the material subjective poetry?

A: As a general rule of thumb, we consider Shakespeare to be the first well-known writer of "Modern English". That doesn't mean language hasn't changed in several hundred years since he his time. It means that (poetic imagery and cultural references aside) we can mostly understand him - unlike Chaucer, which most people can't understand without a lot of help.
On the specifics, Divides one thing entire to many objects simply means "Takes something which is meaningfully identifiable as a single entity, and divides it into constituent parts".
As an example, a motorcar can be divided into gearing cogs, carburettor needles, tyre valves, etc. Shakespeare obviously wasn't thinking of a motorcar, but it certainly illustrates what he goes on to say about perspectives.
Unless you're a mechanic, the pile of components that make up a motorcar may represent nothing but confusion, in the same way that you may end up with no useful understanding of a situation if you try to grasp it from multiple perspectives. Similar to the difficulties we face looking at an example of "multiple perspectives" in Picasso's Cubist paintings.

A: Shakespeare wrote highly inventive, poetic English of his time. Some of what he wrote uses words, grammatical forms and syntax that are no longer current, and can be difficult for modern readers or hearers to understand.
Some of what he wrote uses poetic phrases or syntax which might have been difficult even for contemporaries to understand fully.
There are plenty of editions of Shakespeare which explicate or translate his text, some better than others.
In order to answer whether it is "proper" English or not, you will have to give us a comprehensive characterisation of what you regard as "proper".
But I think I can safely say that the quotation above (which I assume is attached to a section on objects) is inserted for amusement or artistic delight, and has no connection with the text apart from the word "object" and the suggestion that a multiplicity of them can be confusing.


text:
Q: Does there exist a complex function which is differentiable at one point and nowhere else continuous? Let $f\colon\mathbb{C}\to\mathbb{C}$. We know that if $f^{\prime}(a)$ exists for some $a\in\mathbb{C}$ then $f$ is continuous at $a$. This is because, from the definition of the derivative, $$f(z)-f(a)=[f^{\prime}(a)+\varepsilon(z)](z-a)$$ for some $\varepsilon$ such that $\varepsilon(z)\to0$ as $z\to a$, and hence $f(z)\to f(a)$.
I think we can interpret this geometrically by saying that, for $z$ close to $a$, if we take the vector from $a$ to $z$, rotate it counterclockwise about its tail by $\mathrm{Arg}\,{(f^{\prime}(a))}$ and scale its length by $\lvert f^{\prime}(a)\rvert$, then we get approximately the vector from $f(a)$ to $f(z)$ (it's only approximate, because of the $\varepsilon$ error term, but for $z$ close to $a$ this $\varepsilon$ is small).
However, consider the following heuristic argument: let $z_{1}$ and $z_{2}$ both be "close to" $a$ (and therefore close to each other). The above interpretation then suggests that the vector from $f(a)$ to $f(z_{1})$ should be approximately the same as the vector from $f(a)$ to $f(z_{2})$, and therefore $f(z_{2})-f(z_{1})$ should be small in magnitude. This seems to suggest that $f$ should be continuous not just at $a$, but also in some small interval around $a$. This seems too good to be true.
Hence my question:

Does there exist a function $f\colon\mathbb{C}\to\mathbb{C}$ such that $f^{\prime}(a)$ exists at some point $a\in\mathbb{C}$ but $f$ is continuous nowhere else?

Update, added later: A quick thanks to those who responded. I have since thought through this with a friend and we've found a problem with the heuristic argument:

Properly interpreted, the heuristic argument is saying that if $z_{1}$ and $z_{2}$ are close to $a$, then $f(z_{1})$ is close to $f(z_{2})$. However, to have continuity at $z_{1}$, say, we need to be able to make $f(z_{2})$ arbitrarily close to $f(z_{1})$ by choosing $z_{2}$ to be sufficiently close to $z_{1}$ --- therein lies the problem. Suppose $\lvert z_{3}-z_{1} \rvert < \lvert z_{2}-z_{1} \rvert$, i.e., suppose $z_{3}$ is even closer to $z_{1}$ than $z_{2}$ is. Then, for $f$ to be continuous, we need to be able to ensure that $f(z_{3})$ is closer still to $f(z_{1})$ (than $f(z_{2})$ is); in general, we can't ensure this.

If I get round to it, I might try to work through the details in a specific case and see if there are any other problems. If I get anywhere, I'll post the results as an additional answer.

A: Let $g \colon \mathbb{C} \rightarrow \mathbb{C}$ be a function that is discontinuous everywhere and bounded. Consider $f(z) := z^2 g(z)$. Then $f$ is continuous only at $z = 0$, and $f$ is differentiable at $z = 0$ as
$$ \lim_{z \to 0} \frac{f(z) - f(0)}{z} = \lim_{z \to 0} z g(z) = 0.$$

A: Consider $f(z)=|z|^2\cdot \mathbf 1_{\Bbb Q[i]}(z)$


text:
Q: Why are Hilbert Numbers Called Hilbert Numbers? It is my understanding that a Hilbert number is any number of the form $4n + 1$.
According to
https://en.wikipedia.org/wiki/Hilbert_number#CITEREFFlanneryFlannery2000
it seems that these numbers were named in honor of Hilbert almost twenty years ago.
My question is: Does anyone know why; or what connection they may have had to David Hilbert who was not a number theorist; and so, I am imagining, did not study them.
Or did he?
Does anyone know for sure?

A: The context, I am told, is that Hilbert wanted to illustrate that the uniqueness of prime factorization is not a completely obvious claim that needs no proof.
To this end, we introduce Hilbert numbers (which indeed have a rather silly definition out of context) and Hilbert primes (which are Hilbert numbers $n$ whose only Hilbert number divisors are $1$ and $n$ itself). Hilbert primes are not Hilbert numbers which are prime in the ordinary sense: for example, $9$ is a Hilbert prime because its only nontrivial factor, $3$, is not a Hilbert number.
Every Hilbert number has a "prime factorization" into Hilbert primes. But that factorization is not unique; for example, $441$ has two prime factorizations $$441 = 21 \cdot 21 = 9 \cdot 49.$$
(I'm not positive that Hilbert himself used this as an example; I can't find a source for this.)


text:
Q: How do I obtain a valid token for updating layer definition in a feature service? I'm attempting to automate data updates of an ArcGIS Online feature service using the REST API.
So far, I've been able to successfully:

*

*Get a valid token from https://www.arcgis.com/sharing/rest/generateToken

*Upload a new GeoJSON file to https://www.arcgis.com/sharing/rest/content/users/{user}/items/{feature}/update, passing in the token from step #1

*The above does not seem to update the service, so I republish by passing my token and {overwrite:"true"} to https://www.arcgis.com/sharing/rest/content/users/{user}/publish
This is great, it meets the original goal of having an updated dataset in an automated fashion. However, any default styling I configure for the layer goes poof when I republish it. To fix this, I'm trying to use the functionality at https://services5.arcgis.com/{id}/ArcGIS/rest/admin/services/{service}/FeatureServer/0/updateDefinition to pass in the renderer and label information that I'd like to use. Whenever I pass in the same token for steps 3 & 4, it replies with:
{"error":{"code":498,"message":"Invalid token.","details":["Invalid token."]}}

When I check the info from that endpoint to make sure I don't have to go someplace else for my token, I see it is nearly the same URI that I used in step 1. Changing my token URI to the new value doesn't seem to make the token any more valid.
From http://services5.arcgis.com/{id}/ArcGIS/rest/info?f=pjson:
{
    "currentVersion" : 10.41,
    "fullVersion" : "10.4.1.210",
    "owningSystemUrl" : "http://www.arcgis.com",
    "owningTenant" : "{id}",
    "authInfo" :
    {
        "isTokenBasedSecurity" : true,
        "tokenServicesUrl" : "https://www.arcgis.com/sharing/generateToken"
    }
}

I can visit the endpoint above in my browser and it allows me to edit it without a problem (inspecting my browser traffic shows that it does not pass a token in the post, but instead a cookie with authentication inside)
I've tried requesting a separate token specifically for this one call, and I've tried passing in a { serverURL: 'http://services5.arcgis.com/{id}/arcgis/' } parameter with that token call. Neither of those seem to work.
I feel like I'm missing something simple, but I'm running out of ideas!

A: I've found requestip to be somewhat unreliable. A better practice is to request a token with a referer instead. So, in the token request, use it with the URL of your app (or a made up, unique one):
'referer': "www.something.com"


text:
Q: how to change font size and colour of a list in itext? I'm using itextpdf for generating my pdf file. I have a list which should be added in a cell of a table. The problem is I can't change the font size of the list present in the cell of the table?
Here my code is
PdfPTable table = new PdfPTable(1);
PdfPCell cell = new PdfPCell();
List fruitList = new List(List.UNORDERED);
//fruitList.setListSymbol(new Chunk("", FontFactory.getFont(FontFactory.HELVETICA, 6)));
fruitList.add("Mango");
fruitList.add("Apple");
fruitList.add("Orange");
cell.addElement(fruitList);
table.addCell(cell);

Here I have added setListSymbol for the created list. But the font or its size is not getting changed. But font is getting changed for cell's which doesn't have list in it. How to change the size and font of the list?

A: Are you sure this isn't what you want:
Font font = FontFactory.getFont(FontFactory.HELVETICA, 6)
PdfPTable table = new PdfPTable(1);
PdfPCell cell = new PdfPCell();
List fruitList = new List(List.UNORDERED);
fruitList.add(new ListItem("Mango", font));
fruitList.add(new ListItem("Apple", font));
fruitList.add(new ListItem("Orange", font));
cell.addElement(fruitList);
table.addCell(cell);


text: Q: PDFparsing and pattern recognition in python how to identify header and footer in pdf or classify the content of pdf file using python or is there any similar approach like image processing for PDF files?


text:
Q: Shortcut to hiding everything in the view except the Progressbar? I have several Views in my layout. During background loading, I wish to set the Visibility of my ProgressBar to View.VISIBLE and everything else to View.INVISIBLE. Needless to say, after loading I wish to do the reverse.
I wish to know if anyone has figured out a smart way to do this. I tried this
constraintLayout.setVisibility(View.INVISIBLE);
progressBar.setVisibility(View.VISIBLE);

But unfortunately, that did not work. Any ideas?

A: Progressbar Should be visibility "gone" by default, visible it once process started and set other view elements visibility "gone". And then do it vice versa when process completes.


text:
Q: D3 data do not rescale properly after pan or zoom I am working with D3 v4 and JS. I have a scatter plot with a predefined set of data loaded along with axes with the ability to pan and zoom. I need to be able to then dynamically add points and eventually output them in data space not pixel space. I am using the "rescaleX" and "rescaleY" methods of the zoom object. They work fine for rescaling the axes but, when I try to add new points, the location of the plotted point does correspond to the mouse location. Here is a simplified version of the code:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<script>

    var data = [{x:17,y:3},
        {x:20,y:16},
        {x:2,y:13},
        {x:19,y:10},
        {x:13,y:15},
        {x:2,y:2},
        {x:5,y:8},
        {x:11,y:19},
        {x:20,y:12},
        {x:10,y:20}];

    var width = 600;
    var height = 600;
    var padding = 50;
    var newXscale, newYscale;

    var dataScale = d3.scaleLinear()
        .domain([0,21])
        .range([0, width]);

    var svg = d3.select('body').append('svg')
        .attr('width', width+2*padding)
        .attr('height', height+2*padding)
        .on('click', clicked);

    var xAxis = d3.axisTop()
        .scale(dataScale);

    var gX = svg.append('g')
        .attr('transform','translate(50,50)')
        .call(xAxis);

    var yAxis = d3.axisLeft()
        .scale(dataScale);

    var gY = svg.append('g')
        .attr('transform','translate(50,50)')
        .call(yAxis);

    var canvas = svg.append('g')

    var points = canvas.append('g');
    points.selectAll('circle').data(data)
        .enter().append('circle')
        .attr('cx', function(d) {return dataScale(d.x)+padding})
        .attr('cy', function(d) {return dataScale(d.y)+padding})
        .attr('r', 5);

    var zoom
    var zoomOn = false;
    window.addEventListener('keydown', function (event) {
        if (event.key=='z') {
            if (zoomOn) {
                d3.select('#zoomBox').remove();
                zoomOn = false;
            } else {
                zoom = d3.zoom()
                    .scaleExtent([0.1, 10])
                    .on('zoom', zoomed);

                svg.append("rect")
                    .attr('cursor','move')
                    .attr("width", width+padding*2)
                    .attr("height", height+padding*2)
                    .attr('id','zoomBox')
                    .style("fill", "none")
                    .style("pointer-events", "all")
                    .call(zoom);
                zoomOn = true;
            }

        }
    });

    function zoomed() {
        canvas.attr("transform", d3.event.transform)
        newXscale = d3.event.transform.rescaleX(dataScale);
        newYscale = d3.event.transform.rescaleY(dataScale);
        gX.call(xAxis.scale(newXscale));
        gY.call(yAxis.scale(newYscale));
    }

    function clicked() {
        var coords = d3.mouse(this);
        points.append('circle')
            .attr('cx',coords[0])
            .attr('cy',coords[1])
            .attr('r',5);
        var x = newXscale.invert(coords[0]-padding);
        var y = newYscale.invert(coords[1]-padding);
        console.log(x+' '+y);
    }

</script>

</body>
</html>

A: Create a variable to store the zoom level:
newZscale = d3.event.transform.k;

And, in your clicked function, use the dateScale to plot the new circles, dividing the padding by the zoom level:
function clicked() {
    var coords = d3.mouse(this);
    if (newXscale && newYscale) {
        var x = newXscale.invert(coords[0] - padding);
        var y = newYscale.invert(coords[1] - padding);
    };
    console.log(newZscale);
    points.append('circle')
        .attr('cx', (!x) ? coords[0] : dataScale(x) + (padding / newZscale))
        .attr('cy', (!y) ? coords[1] : dataScale(y) + (padding / newZscale))
        .attr('r', 5);
    console.log(x + ' ' + y);
}

Here is the demo:

var data = [{
    x: 17,
    y: 3
}, {
    x: 20,
    y: 16
}, {
    x: 2,
    y: 13
}, {
    x: 19,
    y: 10
}, {
    x: 13,
    y: 15
}, {
    x: 2,
    y: 2
}, {
    x: 5,
    y: 8
}, {
    x: 11,
    y: 19
}, {
    x: 20,
    y: 12
}, {
    x: 10,
    y: 20
}];

var width = 600;
var height = 600;
var padding = 50;
var newXscale, newYscale, newZscale;

var dataScale = d3.scaleLinear()
    .domain([0, 21])
    .range([0, width]);

var svg = d3.select('body').append('svg')
    .attr('width', width + 2 * padding)
    .attr('height', height + 2 * padding)
    .on('click', clicked);

var xAxis = d3.axisTop()
    .scale(dataScale);

var gX = svg.append('g')
    .attr('transform', 'translate(50,50)')
    .call(xAxis);

var yAxis = d3.axisLeft()
    .scale(dataScale);

var gY = svg.append('g')
    .attr('transform', 'translate(50,50)')
    .call(yAxis);

var canvas = svg.append('g')

var points = canvas.append('g');
points.selectAll('circle').data(data)
    .enter().append('circle')
    .attr('cx', function(d) {
        return dataScale(d.x) + padding
    })
    .attr('cy', function(d) {
        return dataScale(d.y) + padding
    })
    .attr('r', 5);

var zoom
var zoomOn = false;
window.addEventListener('keydown', function(event) {
    if (event.key == 'z') {
        if (zoomOn) {
            d3.select('#zoomBox').remove();
            zoomOn = false;
        } else {
            zoom = d3.zoom()
                .scaleExtent([0.1, 10])
                .on('zoom', zoomed);

            svg.append("rect")
                .attr('cursor', 'move')
                .attr("width", width + padding * 2)
                .attr("height", height + padding * 2)
                .attr('id', 'zoomBox')
                .style("fill", "none")
                .style("pointer-events", "all")
                .call(zoom);
            zoomOn = true;
        }

    }
});

function zoomed() {
    canvas.attr("transform", d3.event.transform)
    newXscale = d3.event.transform.rescaleX(dataScale);
    newYscale = d3.event.transform.rescaleY(dataScale);
    newZscale = d3.event.transform.k;
    gX.call(xAxis.scale(newXscale));
    gY.call(yAxis.scale(newYscale));
}

function clicked() {
    var coords = d3.mouse(this);
    if (newXscale && newYscale) {
        var x = newXscale.invert(coords[0] - padding);
        var y = newYscale.invert(coords[1] - padding);
    };
    points.append('circle')
        .attr('cx', (!x) ? coords[0] : dataScale(x) + (padding / newZscale))
        .attr('cy', (!y) ? coords[1] : dataScale(y) + (padding / newZscale))
        .attr('r', 5);
}
<script src="https://d3js.org/d3.v4.min.js"></script>

A: I figured it out. The problem lied in the fact that I was removing the zoom box when toggling the zoom. I switched the event listener to just hide the box and unbind the pointer-events. Here is the final code:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<script>

    var data = [{x:17,y:3},
        {x:20,y:16},
        {x:2,y:13},
        {x:19,y:10},
        {x:13,y:15},
        {x:2,y:2},
        {x:5,y:8},
        {x:11,y:19},
        {x:20,y:12},
        {x:10,y:20}];

    var width = 600;
    var height = 600;
    var padding = 50;
    var newXscale, newYscale;
    var zoomOn = false;

    var xScale = d3.scaleLinear()
        .domain([0,21])
        .range([0, width]);

    var yScale = d3.scaleLinear()
        .domain([0,21])
        .range([0, width]);

    var svg = d3.select('body').append('svg')
        .attr('width', width+2*padding)
        .attr('height', height+2*padding)
        .on('click', clicked)
        .attr('cursor','crosshair');

    var xAxis = d3.axisTop()
        .scale(xScale);

    var gX = svg.append('g')
        .attr('transform','translate(50,50)')
        .call(xAxis);

    var yAxis = d3.axisLeft()
        .scale(yScale);

    var gY = svg.append('g')
        .attr('transform','translate(50,50)')
        .call(yAxis);

    var canvas = svg.append('g')

    var points = canvas.append('g');
    points.selectAll('circle').data(data)
        .enter().append('circle')
        .attr('cx', function(d) {return xScale(d.x)+padding})
        .attr('cy', function(d) {return yScale(d.y)+padding})
        .attr('r', 5);

    var zoom = d3.zoom()
        .scaleExtent([0.1, 10])
        .on('zoom', zoomed);

    var zoombox = svg.append("rect")
        .attr("width", width+padding*2)
        .attr("height", height+padding*2)
        .attr('id','zoomBox')
        .style("fill", "none")
        .style("pointer-events", "none")
        .style('visibility','off')
        .call(zoom);

    window.addEventListener('keydown', function (event) {
        if (event.key=='z') {
            if (zoomOn) {
                d3.select('#zoomBox')
                    .attr('cursor','auto')
                    .style('pointer-events','none')
                    .style('visibility','off');
                zoomOn = false;
            } else {
                d3.select('#zoomBox')
                    .attr('cursor','move')
                    .style('pointer-events','all')
                    .style('visibilty','on')
                zoomOn = true;
            }

        }
    });

    function zoomed() {
        canvas.attr("transform", d3.event.transform)
        newXscale = d3.event.transform.rescaleX(xScale);
        newYscale = d3.event.transform.rescaleY(yScale);
        gX.call(xAxis.scale(newXscale));
        gY.call(yAxis.scale(newYscale));
        newZscale = d3.event.transform.k;

    }

    function clicked() {
        var coords = d3.mouse(this);
        if (newXscale && newYscale) {
            var x = newXscale.invert(coords[0] - padding);
            var y = newYscale.invert(coords[1] - padding);
        };
        console.log(newZscale);
        points.append('circle')
            .attr('cx', (!x) ? coords[0] : xScale(x) + (padding / newZscale))
            .attr('cy', (!y) ? coords[1] : yScale(y) + (padding / newZscale))
            .attr('r', 5);
        console.log(x + ' ' + y);
    }

</script>

</body>
</html>


text:
Q: how to filter array using php? print_r($menus); gives the following output:
Array
    (
        [0] => Array
            (
                [name] => Politics
                [action] => politics
            )

        [sub_menu2] => Array
            (
                [0] => Array
                    (
                        [name] => submenu2
                        [action] => politics
                    )
                 [1] => Array
                    (
                        [name] => submenu3
                        [action] => sport
                    )

            )

    )

My expected filtered array is:
Array
    (
        [0] => Array
            (
                [name] => Politics
                [action] => politics
                [sub_menu2] => Array
               (
                 [0] => Array
                    (
                        [name] => submenu2
                        [action] => politics
                    )
                 [1] => Array
                    (
                        [name] => submenu3
                        [action] => sport
                    )

               )
            )
    )

My code is:
$filteredMenu = array();
$unique = array();
$index = 0;
$index2 = 0;
foreach ($menus as $key => $menu) {
    $pm = $menu['Menu']['name'];
    if (isset($unique[$pm])) {
        if (!empty($menu['sub_menus']['name'])) {
            $temp = array('name' => $menu['sub_menus']['name'], 'action' => $menu['sub_menus']['action']);
            $filteredMenu[$index]['sub_menu'][] = $temp;
        }
         if(!empty($menu['sub_sub_menus']['name'])){
                 $temp = array('name' => $menu['sub_sub_menus']['name'], 'action' => $menu['sub_menus']['action']);
            $filteredMenu[$index]['sub_menu']['sub_menu2'][] = $temp;
            }
    } else {
        if ($key != 0)
            $index++;
        $unique[$pm] = 'set';
        $temp = array('name' => $pm, 'action' => $menu['Menu']['action']);
        $filteredMenu[$index]['menu'] = $temp;
        if (!empty($menu['sub_menus']['name'])) {
            $temp = array('name' => $menu['sub_menus']['name'], 'action' => $menu['sub_menus']['action']);
            $filteredMenu[$index]['sub_menu'][] = $temp;
        }
         if(!empty($menu['sub_sub_menus']['name'])){
                 $temp = array('name' => $menu['sub_sub_menus']['name'], 'action' => $menu['sub_menus']['action']);
            $filteredMenu[$index]['sub_menu']['sub_menu2'][] = $temp;
            }
    }
}

I can filter to wrap all sum menus under menu. But I can't wrap all second level sub menu under sub menu. I spent lot of time to solve but failed.

A: Your php code is different from your array. From where you find
$pm = $menu['Menu']['name'];

this will display error Undefined index: Menu
I think you have to apply more condition.
I don't sure apply below code. I think this will solve your problem.
$filteredMenu = array();
$unique = array();
$index = 0;
$index2 = 0;
foreach ($menus as $key => $menu) {
  $pm = $menu['Menu']['name'];
$pm1 = $menu['sub_menus']['name'];
if (isset($unique[$pm])) {
    if (!empty($menu['sub_menus']['name'])) {
        $temp = array('name' => $menu['sub_menus']['name'], 'action' => $menu['sub_menus']['action']);
        $filteredMenu[$index]['menu']['sub_menu'][] = $temp;
    }
     if(!empty($menu['sub_sub_menus']['name'])){
             $temp = array('name' => $menu['sub_sub_menus']['name'], 'action' => $menu['sub_menus']['action']);
        $filteredMenu[$index]['menu']['sub_menu']['sub_menu2'][] = $temp;
        }
} else {
    if ($key != 0)
        $index++;
    $unique[$pm] = 'set';

    $temp = array('name' => $pm, 'action' => $menu['Menu']['action']);
    $filteredMenu[$index]['menu'] = $temp;

    if (!empty($menu['sub_menus']['name'])) {
        $temp = array('name' => $menu['sub_menus']['name'], 'action' => $menu['sub_menus']['action']);
        $filteredMenu[$index]['menu']['sub_menu'][] = $temp;
    }
     if(!empty($menu['sub_sub_menus']['name'])){
             $temp = array('name' => $menu['sub_sub_menus']['name'], 'action' => $menu['sub_menus']['action']);
        $filteredMenu[$index]['menu']['sub_menu']['sub_menu2'][] = $temp;
        }

}
}


text:
Q: New to array variables - can I do this without a loop? I'm using VBA to import data from an Excel spreadsheet into an Access data base.  I have an array variable (data) set up with 17 elements and have the following code to import the 17 values from a single line of the spreadsheet:
For i = 1 To 17
    data(i) = Cells(Line.Row, i).Value
Next i

Can I do this without a loop?
BTW - I'm processing each line of the spreadsheet inside a loop as well, because different rows get different treatment based on the data in column 1.

A: Yes you can simply assign the values of a Range to a variant variable, it will then hold the values in a 2-dimensional array.
You can use it like this:
On the debug.print line, the first dimension refers to the row and is always 1 here.
Sub test()
    Dim v
    Dim line As Range
    Dim i As Long

    Set line = Range("A2:Q2")
    v = line.Value

    ' accessing the values:
    For i = LBound(v, 2) To UBound(v, 2)
        Debug.Print v(1, i)
    Next

End Sub

As you say you are iterating over multiple lines as well, you can also assign the entire Range to v and iterate over both dimensions.

A: When passing range to any variable you could create an array. However, it would be 2 dimensional array. To make it one-dimensional we would need to transpose it (twice). So, the code could be as follow:
data = Application.Transpose(Application.Transpose(Range(Cells(Line.Row, 1), _
                                                        Cells(Line.Row, 17))))

One more important information- this data array will start with index 1 instead of default 0.


text:
Q: I have a few questions about Damage Formulas I have a damage formula that works at a basic level. Before evolving the equation I want to consider different situations:

*

*There are multiple formulas at use in a RPG. If you are using a physical attack, the formula may something like ATK - DEF = DMG vs using a magic attack which could be MAG - M.DEF = DMG. Are these stored as separate a formula with each attack calling a different formula or is it a modular equation where certain values are updated to reflect what is needed?

*Lets talk about probabilities. Imagine an attack that has a 30% chance to poison an enemy. I was going to do Random.Range (1, 100); if its a value from 1-30 then, true. Is this the .. professional way of going about it? Any recommendations?

*In RPG damage formulas; Level is often included in the equation. Why? What does it add? I am assuming it is some kind "penalty/bonus", like if your level is to low the boss will sweep you in a few hits, but if you are close to the same level or over you will be even or sweep the boss? Currently, my formula does not have a level value.


text:
Q: BaseClass unable to find its subclasses I have a bunch of feature classes spread over a few modules all inherit from a BaseFeature class. Somehow the BaseFeature is unable to know its sublcasses by calling the subclasses() method.
In another module e.g. (pipeline.py) I only import the BaseFeature class.
Then I call BaseFeature.subclasses() on the class object, not an actual object of the BaseFeature!
Somehow the call returns nothing. But when I additionally import feature_x.py into pipeline.py the BaseFeature knows its subclasses again.
I want avoid that because of dynamic module importing.
inside pipeline.py:
from base_feature import BaseFeature

class Pipeline:

    def init_features:
        feature_classes_list = BaseFeature.__subclasses__()
        print(feature_classes_list)

        # loop for init features in feature_classes_list

[] - empty list
But:
import feature_x
import feature_y

then repeat the feature initiation, the BaseFeature "knows" its sublcasses again.
[<class feature_x>, <class feature_y>]

I want to avoid a separate feature module import because they are a lot. And not all are needed every time.
So why is the BaseClass not knowing of its sublasses?


text:
Q: Closing form5 from form1 if download completed Here is the whole code from form1 :
using System;
using System.IO;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.IO.Compression;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Diagnostics.Tracing;

namespace BSCS_Launcher
{
    public partial class Form1 : Form
    {
        private WebClient webClient = null;
        const string basPath = @"cstrike";

        public Form1()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Form6 f6 = new Form6();
            f6.ShowDialog(); // Shows Form6 - Launchoptions
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string path = @"steamlop.lop";
            string cfgpath = @"cstrike/config.cfg";
            FileAttributes attributes = File.GetAttributes(cfgpath);

            if (File.Exists(path))
            {
                File.SetAttributes(cfgpath, File.GetAttributes(cfgpath) | FileAttributes.ReadOnly);
                var str = File.ReadAllText(path);
                System.Diagnostics.Process.Start("hl.exe", arguments: str);
            }
            else
            {
                string message = "Launch options not found. Please go into launch options and click double click Reset!!!";
                string title = "Launch options error";
                MessageBox.Show(message, title);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Form2 f2 = new Form2();
            f2.ShowDialog(); // Shows Form2 - Features
        }

        private void button4_Click(object sender, EventArgs e)
        {
            Form3 f3 = new Form3();
            f3.ShowDialog(); // Shows Form3 - Options
        }

        private void button5_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("https://fastxhoster.com/");
        }

        private void button7_Click(object sender, EventArgs e)
        {
            Form5 f5 = new Form5();
            f5.ShowDialog(); // Shows Form5 - Updatelauncher

            // Is file downloading yet?
            if (webClient != null)
            {
                return;
            }

            var dirdir = new DirectoryInfo($"{basPath}");
            if (!dirdir.Exists)
            {
                webClient = new WebClient();
                webClient.DownloadFileCompleted += FileDownloading;
                webClient.DownloadFileAsync(new Uri("https://sipi-portfolio.000webhostapp.com/verzija.php"), $"{basPath}/version.php");
            }
            else
            {
                webClient = new WebClient();
                webClient.DownloadFileCompleted += FileDownloading;
                webClient.DownloadFileAsync(new Uri("https://sipi-portfolio.000webhostapp.com/verzija.php"), $"{basPath}/version.php");
            }  //Ovaj kod treba da se izvrsi tek kada je igracu skinut novi update ukoliko ga je bilo
        }

        private void FileDownloading(object sender, AsyncCompletedEventArgs e)
        {
            webClient = null;

            string pathfile = $"{basPath}/verzija.php";
            string pathfile2 = $"{basPath}/version.php";
            var str = File.ReadAllText(pathfile);
            var str2 = File.ReadAllText(pathfile2);

            if (str != str2)
            {
                CloseProcessing();
                string message = "We found an avilable update for this launcher!";
                string title = "Update launcher";
                MessageBox.Show(message, title);
            }
            else
            {
                CloseProcessing();
                string message = "No new updates!";
                string title = "Update launcher";
                MessageBox.Show(message, title);
            }
        }

        public void CloseProcessing()
        {
            Form5 f5 = new Form5();
            f5.Close(); // Closes Form5 - Updatelauncher
        }
    }
}

Here you can see that I created code for download one file from one website, and it should check if those 2 files have the same context, if not it should do something and if yes it should do something again, in both situations, it should close form5, but it not closing... I tried many codes to resolve this but it not affects...
Thanks in advance...!

A: just Declare Form5 outside of methods (in the class) and for closing it don't rredefine it:
        private void button7_Click(object sender, EventArgs e)
        {
            Form5 f5 = new Form5();
            f5.ShowDialog(); // Shows Form5 - Updatelauncher

to
        Form5 f5 = new Form5();
        private void button7_Click(object sender, EventArgs e)
        {
            f5.ShowDialog(); // Shows Form5 - Updatelauncher

and
        public void CloseProcessing()
        {
            //remove this line: //Form5 f5 = new Form5();
            f5.Close(); // Closes Form5 - Updatelauncher
        }

when you call Form5 f5 = new Form5(); in CloseProcessing you create a new instance of form5 instead of closing existing one.


text:
Q: Loading Image sequence in HTML I have to load image sequence animation about 60 images array. I want this particular sequence loaded separately. means that images loading time does not affected to whole page load time. because it is taking too much time to load page with image sequence animation. Currently i have added all 60 images of sequence in HTML code and set "display:none" to load with page.
Is there any possibility to load this images separately or load after my whole html page loaded. or any other better solution.
Thanks in advance.

A: Load them dynamically using javascript/jquery
var imagePaths = ["img1.png", ....];
$(document).ready(function(){
   for(var i=0; i<imagePaths.length; i++) {
      var newImg = $('<img style="display:none;" />'); //Add any class or attribute you want or anything for images.
      newImg.bind("load", function(){
         $(this).show();
      });
      newImg.attr("src", imagePaths[i]);
      $(parentSelector).append(newImg);
   }
});

When you load dynamically from script, your HTML page would have loaded and be ready for use. And later all the images will come into view gradually.
Edit:
In addition if you want to keep your image hidden until it gets completely loaded, you could initially set display:none; inline and attach an onload listener, display:block there.
Hope this helps. Let me know if I missed anything.

A: Yes it is possible.
var images[60];
var names[60]={"img1.jpg","img2.jpg"...}

function loadImages() {
  for(var i=0;i<60;i++) {
    images[i] = new Image();
    images[i].src = "www.myWebPage.com/"+names[i];
  }
}

This function will now load images. Just make sure to call it after your page loads.
<body onLoad="loadImages()">
...
</body>


text:
Q: How to get a remainder in java The Student Union is organising a student trip and they are determining how many cars are required.
Prompt the user to enter the total number of students going on the trip.
Then determine how many cars are required (5 to a car) and how many students are left without transport.
import java.util.Scanner;

class P2Trip
{
public static void main(String []args)
{
    Scanner input = new Scanner(System.in);

    int students;
    int space = 5;
    int sum;

    System.out.println("How many students are going today?: ");
    students = input.nextInt();

    sum =(students / space);
    System.out.println("Ammount of cars needed: " + sum);

 }
}//code works fine, but im not sure how to get a remainder of students without a lift.

A: From your comment, it looks like you just need help with who will be left without a car. You need to use modular division (some people call it remainder) with the percent sign (%). Here is the line of code you  are missing:
System.out.println("Amount of people without a car: "+students%sum);

The full code for the program is:
import java.util.Scanner;
public class Solution {
    public static void main(String[] args) [
        Scanner s=new Scanner(System.in);
        int carCapacity=5;

        System.out.println("How many students?");
        int students=s.nextInt();
        int cars=students/carCapacity;
        int leftOver=students%carCapacity;

        System.out.println("Cars needed: "+cars);
        System.out.println("Students left over: "+leftOver);

    }
}

A: Have a look at the remainder/modulo operator here:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html

A: In my view, there are two corrections you can do in your program:
sum = (student/space);
int leftstudent;`
leftstudent=(students%space);
System.out.println("left students without transport are " +leftstudent);

A: You might want to check the modular division operator in Java.
Division / Divisor =  coefficient
Division % Divisor = remainder
To find the remainder of number students for example you will have to use "%".