text:
Q: ClearInterval doesn't work. What is the problem? How can I solve it? https://codepen.io/fodi91/pen/ExNqGpY
First I click the random background every 4 seconds button, then I click the random background onclick button, but the interval doesn't stop. Why? How can I solve this?
let onClick = document.getElementById('generate');
onClick.addEventListener('click', generator);

let onClick2 = document.getElementById('generate2');
onClick2.addEventListener('click', generator2);

function generator2() {
    let r = Math.floor(Math.random() * 256);
    let g = Math.floor(Math.random() * 256);
    let b = Math.floor(Math.random() * 256);

    let background = document.getElementById('random');
    background.style.backgroundColor = 'rgb(' + r + ', ' + g + ', ' + b + ')';
    myInterval = setInterval(generator2, 2000);
}

function generator() {

    let r = Math.floor(Math.random() * 256);
    let g = Math.floor(Math.random() * 256);
    let b = Math.floor(Math.random() * 256);

    let background = document.getElementById('random');
    background.style.backgroundColor = 'rgb(' + r + ', ' + g + ', ' + b + ')';
    clearInterval(myInterval);

}

A: you have two problems:

*

*You're using myInterval like it's a global variable, but it's not defined anywhere outside the functions

*You're calling generator2 recursively, generator2 sets the color, then sets an interval to call generator2, regardless if there's another interval, so with every interval passing you actually set another interval, you'll eventually hang the tab with this. not to mention, myInterval will have a different interval ID, meaning even if you stop it, you only stopped the last running interval. a possible solution is setting the color changing to a different function, and have it called in the interval instead of on click.

A: The problem here is the fact that you are defining multiple intervals by calling the generator2 function in the interval itself. So instead, you should use a setTimeout. This would cause every timeout defined to get cleared (almost) as soon as the timer runs out.
So, the generator functions would change to:
function generator2() {
    let r = Math.floor(Math.random() * 256);
    let g = Math.floor(Math.random() * 256);
    let b = Math.floor(Math.random() * 256);

    let background = document.getElementById('random');
    background.style.backgroundColor = 'rgb(' + r + ', ' + g + ', ' + b + ')';
    myTimeout = setTimeout(generator2, 2000);
}

function generator() {

    let r = Math.floor(Math.random() * 256);
    let g = Math.floor(Math.random() * 256);
    let b = Math.floor(Math.random() * 256);

    let background = document.getElementById('random');
    background.style.backgroundColor = 'rgb(' + r + ', ' + g + ', ' + b + ')';
    clearTimeout(myTimeout);
}

In addition, you would have to ensure the myTimeout is declared such that it is accessible by the generator function as well, since you wish to clear it on the button click.

A: There are a couple of issues with your code.
Firstly, you need to declare your myInterval variable outside of the generator2() function.
The second issue is that your interval function is calling itself creating a recursive loop. Separate your callback which sets the interval from the code you want to execute on each interval.
let myInterval;
let onClick = document.getElementById('generate');
. . .

onClick2.addEventListener('click', secondClickHandler);

function secondClickHandler() {
    myInterval = setInterval(generator2, 2000);
}

function generator2() {
    let r = Math.floor(Math.random() * 256);
    let g = Math.floor(Math.random() * 256);
    let b = Math.floor(Math.random() * 256);

    let background = document.getElementById('random');
    background.style.backgroundColor = 'rgb(' + r + ', ' + g + ', ' + b + ')';
}

With that in mind, here's how I'd approach it:
const generate1Button = document.getElementById('generate');
const generate2Button = document.getElementById('generate2');
const randomBackground = document.getElementById('random');

let backgroundInterval;

generate1Button.addEventListener('click', () => {
    clearInterval(backgroundInterval);
    setRandomBackgroundColor();
})

generate2Button.addEventListener('click', () => {
    setRandomBackgroundColor();
    backgroundInterval = setInterval(setRandomBackgroundColor, 2000);
})

function setRandomBackgroundColor() {
    const r = Math.floor(Math.random() * 256);
    const g = Math.floor(Math.random() * 256);
    const b = Math.floor(Math.random() * 256);

    randomBackground.style.backgroundColor = `rgb(${r}, ${g}, ${b})`;
}


text:
Q: null values in sql i have data like this
ID Nu     name
1  234    asd
2  566    asd
3  -      sdf
4  356    sd
5  NULL   sfsg

now how to get all data with - and null values

A: select * from table_name;

this will give you all the data with - and null value
if you want to fetch only the data where nu is null and - use this:
select *
from table_name
where nu is null or nu = '-';

I think this should help.

A: select * from table_name where Nu is null or Nu='-'

A: To get all the info from the table you can use the following query:
select * from table_name;

To filter by null and dash values, try the where clause:
select * from table_name where nu is null;
UNION ALL
select * from table_name where nu = '-';

redpajama_set_name: RedPajamaStackExchange


text:
Q: Oracle job that runs a batch file So I have in my DB a user, that I want to use to run a. bat file. The easiest way to do this, was to use an Oracle Job.
So I created my job, but when I try to run it, it gives me the following errors :
ORA-27370: job slave failed to launch a job of type EXECUTABLE
ORA-27300: OS system dependent operation:accessing job scheduler service failed with status: 2
ORA-27301: OS failure message: The system cannot find the file specified.
ORA-27302: failure occurred at: sjsec 6a
ORA-27303: additional information: The system cannot find the file specified.

Out of curiosity, I created the same job, with the exact settings with the SYS user in its schema(yes, i know that this is not recommanded...), and when I ran the job, it worked perfectly.
So I though that there are probably some permission involved so I gave my user, all the system priviledges and roles that the SYS user had, to see if this is the problem.
However, I got the same errors.. Any ideas why this works in sys schema, and not in my user's schema, although the user has all the priviledges set ?:|

A: You have not given any information on what exact command you're running. We'll have to guess.
From your description, I would say the behaviour is typical of "SYS is special". In the DBA guide, we can see that an external local job will behave differently if the account is SYS when no credential is provided.
So I'm guessing that you're running your job with DBMS_SCHEDULER without credential and that the default non-SYS OS account has not the same OS rights as the Oracle installer account.
Try to create a credential with DBMS_SCEDULER.CREATE_CREDENTIAL with a sufficiently-privileged OS account and assign this credential to your job.


text:
Q: Can i create lists of lists using Core Data i am using Core Data in an iOS app i am writing
i have an entity called Track and an entity called List
a List comprises a number of Tracks, but can also include other Lists.
to give an analogy, imagine a playlist comprising a combination of songs and other playlists, which themselves can have both songs and other playlists in them.
the xdatamodeld seems to accommodate having a list entity with a name attribute and to-many relationships to both tracks and lists, but i'm wondering if this is the right way to do this.  i thought i'd ask the experienced programmers here what if any problems i may have to look out for if i go this route...i assume there is a significant risk of circular references, and that a list should not contain any lists that contain it...but there may be other problems as well...
thanks in advance for any help

A: There's nothing wrong with your approach.  Just be careful when setting what happens to dependents in the event of record deletion to avoid circular deletion.  A cleaner way would be to create a listItem table that contains a boolean field to indicate whether the item is associated to list or track, then have has_one relationship with list and track.  List table will contain listItems and listItems will manage what it contains.  It's same as yours except it adds a design separation that makes it easy to deal with dependencies.


text:
Q: Show/ Hide components on the selection of checkbox of a Tree The onSelect event is present for the  component only and I want to show/hide my comboboxes for selected checkboxes only.
Here is my zul file for reference
![<?page title="MVVM Tree POC"?>
<zk>
    <borderlayout height="800px">
        <west size="25%"></west>

            <window apply="org.zkoss.bind.BindComposer"
                viewModel="@id('vm') @init('com.nagarro.viewmodel.TreeViewModel')"
                title="Dynamic Tree" border="normal">
                <tree checkmark="true" model="@bind(vm.treeModel)"
                    onSelect="@command('select')">
                    <treecols>
                        <treecol label="Name" align="center" />
                        <treecol label="Value" align="center" />
                        <treecol label="IP" align="center" />
                    </treecols>
                    <template name="model" var="node" status="s">
                        <treeitem checkable="@load(node.checkable)">
                            <treerow style="text-align:center;">
                                <treecell
                                    label="@bind(node.data.firstName)" style="text-align:left;">

                                </treecell>
                                <treecell style="text-align:center;">
                                    <combobox>
                                        <comboitem label="Fixed" />
                                        <comboitem label="System" />
                                        <comboitem label="Parameter" />
                                    </combobox>
                                </treecell>
                                <treecell style="text-align:center;">
                                    <combobox>
                                        <comboitem label="IP" />
                                    </combobox>
                                </treecell>
                            </treerow>

                        </treeitem>
                    </template>
                </tree>

            </window>

    </borderlayout>
</zk>]

snapshot of the issue
In the image I want to show the combo boxes only for the components which have checked checkboxes. There should not be any combobox shown for component without checkbox or unchecked checkbox. Thanks
Here is the mvvm file
public class TreeViewModel {

    private Request request;
    private AdvancedTreeModel treeModel;

    /**
     * @return the treeModel
     */
    public AdvancedTreeModel getTreeModel() {
        if(treeModel == null){
            TreeNode<Tree> treeNode = new TreeList(request).getRoot();
            treeModel = new AdvancedTreeModel(treeNode);
            treeModel.setMultiple(true);
        }
        return treeModel;
    }

    /**
     * @param treeModel the TreeModel to set
     */
    public void setTreeModel(AdvancedTreeModel treeModel) {
        this.treeModel = treeModel;
    }
    @Init
    public void init(){
        try {
            File file = new File("C:\\Users\\jatin1937\\Desktop\\XML files\\Request.xml");
            JAXBContext jaxbContext = JAXBContext.newInstance(Request.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            request = (Request) jaxbUnmarshaller.unmarshal(file);
        }catch (JAXBException e) {
            e.printStackTrace();
        }
    }

    /**
     * @return the request
     */
    public Request getRequest() {
        return request;
    }

    /**
     * @param request the request to set
     */
    public void setRequest(Request request) {
        this.request = request;
    }
    @Command
    public void select(){
        System.out.println("onSelect method entered");
    }
}

Tree data is prepared through some helper classes but thats not important to describe here.

A: I also tried it and found a way out. Now, instead of using onSelect event on tree component I am using onClick event on treeRow component.  I kept a field isChecked with my class which is referred by node.data in the zul file. According to the value of that boolean isChecked I show/hide the combobox.
Below is the zul file for reference
<?page title="MVVM Tree POC"?>
<zk>
    <borderlayout height="800px">
        <west size="25%"></west>

            <window apply="org.zkoss.bind.BindComposer"
                viewModel="@id('vm') @init('com.nagarro.viewmodel.TreeViewModel')"
                title="Dynamic Tree" border="normal">
                <tree checkmark="true" model="@bind(vm.treeModel)">
                    <template name="model" var="node" status="s">
                        <treeitem
                            checkable="@load(node.data.isCheckable)" open="true">
                            <treerow style="text-align:center;"
                                onClick="@command('select', treeNode = node.data)">
                                <treecell
                                    label="@bind(node.data.firstName)" style="text-align:left;">
                                </treecell>
                                <treecell style="text-align:center;"
                                    if="${node.data.isChecked == true}">
                                    <combobox>
                                        <comboitem label="Fixed" />
                                        <comboitem label="System" />
                                        <comboitem label="Parameter" />
                                    </combobox>
                                </treecell>
                                <treecell style="text-align:center;"
                                    if="${node.data.isChecked == true}">
                                    <combobox>
                                        <comboitem label="Fixed" />
                                        <comboitem label="System" />
                                        <comboitem label="Parameter" />
                                    </combobox>
                                </treecell>
                            </treerow>
                        </treeitem>
                    </template>
                </tree>

            </window>

    </borderlayout>
</zk>

Here is the select method in ViewModel for reference
@NotifyChange("treeModel")
@Command
public void select(@BindingParam("treeNode") final Tree tree){
    if(tree.getIsCheckable()){
        if(tree.getIsChecked() == true){
            tree.setIsChecked(false);
        }else{
            tree.setIsChecked(true);
        }
    }

}

Please note that Tree is a custom class through which I prepare tree
  data.  isCheckable is also a boolean field in the Tree class. If
  true then checkbox will appear in a treeRow else not.
  isChecked is another Boolean field in Tree class. If true then
  corresponding checkbox is checked else not

A: Just do it like this
<tree onSelect="@command('select', tree=self)" >

and in your vm
Set<Treeitem> oldSelection;
...

@Command
public void select(@BindingParam("tree")Tree tree){
   // delete
   Set<Treeitem> unselected = oldSelected.removeAll(tree.getSelectedItems());
   for(Treeitem x : unselected){
       x.getTreerow().getLastChild().setParent(null);
   }
   // add
   tree.getSelectedItem().getTreerow().appendChild(getCombobox());
   oldSelection = tree.getSelectedItems()
}


text:
Q: Getting Image DPI in PDF files using iText I 'm trying to get information about scanned images that are saved into PDF files through iText (using Java).
Using the answer and comments, I got width and height (either through Matrix, or through BufferedImage). The idea was to use the answer here to calculate the DPI, but I am a bit lost.
Are these values (width and height) in pixels or points? Is there any other way to achieve this? There are a lot of answers on how to scale and save an image to a PDF file, but I didn't find any on how to read the width/height/scale of an image and be confident about the result.

A: Let's split this problem into two separate problems. To calculate the DPI, you need two sets of values: a number of pixels and a distance in inch.

*

*Number of pixels: you obtain the image and the image consists of pixels. You can retrieve the width and height of the image in pixels from the image. Let's say these values are wPx and wPx.

*Distance in inch: you obtain the matrix which gives you values expressed in points. As 72 points equal 1 inch, you need to divide these values by 72. Let's say these values are wInch and hInch.

Now you can calculate the DPI in the x direction like this: wPx / wInch and the DPI in the y direction like this: hPx / hInch.

A: I think original answer (answered Aug 28, 2014) was for iText 5. A newer answer for iText 7 is here:

*

*https://kb.itextpdf.com/home/it7kb/faq/how-to-get-the-image-dpi-in-pdf
Info from above link is pasted below:

Now you don't need to calculate the DPI values yourself. There is an ImageData class in iText 7 with built-in methods to solve your problem:

ImageData image = ImageDataFactory.create(IMG);
int x = image.getDpiX();
int y = image.getDpiY();


text:
Q: Exclude the zero in the given data in Haskell I have a list of integers.
Also, I have a function which returns True when the element is non-zero, and returns False when the element is zero (let's call it FUNCTION1).
So, how to define another function (using FUNCTION1), which will give us a new list and only include the non-empty elements?
For example, we have [1,2,3,0,6,0], and we want [1,2,3,6]

A: What you're looking for is the filter function.
To filter out 0 from a list, you would say:
filter (\x -> not (x==0)) [1,2,3,0,6,0]
-- or better yet
filter (not . (==0)) [1,2,3,0,6,0]
-- or best of all
filter (/=0) [1,2,3,0,6,0]

If you want, you can substitute the anonymous function with your named function. It should work the same:
filter Function1 [1,2,3,0,6,0]


text:
Q: Very simple macOS XPC I want to use the XPC technology simply to launch an app. I do not need any interprocess communication, or any of the other feature of XPC.
The only documents that I can find on the internet show a complex structure, with code for the XPC service, separate code to launch the XPC service via a script, and app code to communicate with the service.
In other words, I only want something that does the equivalent of this:
NSWorkspace.shared.openApplication(at: path,
                                   configuration: configuration,
                                   completionHandler: nil)

but with XPC. So I would need something along the lines of:
let listener = NSXPCListener.service("/path/to/my_app.app")
listener.resume()
RunLoop.main.run()

Obviously, the service method does not take an argument that would be an executable path, so this does not work.
How can I do that ?
PS: to explain the motivation, launching an XPC service will preserve sandbox restriction form the launching app, whereas launching the app directly via NSWorkspace.shared.openApplication will not preserve sandbox restrictions (because the spawned app does not have "com.apple.security.inherit" as entitlement).

A: It does not seem possible to launch a sub process while altering it's sandbox (i.e. giving it more or less entitlements than it was originally blessed with).
I recommend stripping the sandboxing from the existing application, modifying the entitlements appropriately and then re-signing it. It's not a regular approach but would solve your specific issue.


text:
Q: How to identify an input field by an input method service? I am implementing a custom keyboard and therefore use an input method service. In the onStartInput() method I am able to identify the app, the keyboard is used in, by the packageName of the EditorInfo parameter.
I would like to identy the input field to allow the user to execute certain actions depending on which field he has selected. For example if he uses app XY and select the first field their should be different keys offered to the user than when he selected the second or third field. All fields are regular text fields. To be able to do so, it is necessary to get an ID of the input field.
Does anyone now a solution for this?

A: From your question I think you want to identify the InputType of the keyboard to know which type of keyboard to show to a user. You can also do it in the onStartInputView like this:

    @Override
    public void onStartInputView(EditorInfo info, boolean restarting) {

        super.onStartInputView(info, restarting);
        int inputType = info.inputType & InputType.TYPE_MASK_CLASS;
                //Some input types have variation
                //like passwords for InputType.TYPE_CLASS_TEXT
                //to handle that:
        int inputVariation = info.inputType & InputType.TYPE_MASK_VARIATION;

        switch (inputType){
            case InputType.TYPE_CLASS_TEXT:
                Log.i("InputType", "onStartInputView: Text");

                if(inputVariation == InputType.TYPE_TEXT_VARIATION_PASSWORD){
                    //letter input method for passwords
                }
                break;
            case InputType.TYPE_CLASS_NUMBER:
                Log.i("InputType", "onStartInputView: number");
                break;
            //Case ...:
            default:
                //Todo: what ever you prefer

        }
    }

For more information check out this link


text:
Q: Typed Racket: Natural Numbers I have to solve a problem with a unique definition of the natural numbers:
(define-type Nat (U 'Zero Succ))
(define-struct Succ ([prev : Nat]) #:transparent)

So basically, 0 = 'Zero, 1 = (Succ 'Zero), 2 = (Succ (Succ 'Zero)).... etc.
Using this form, without converting them into integers, I have write recursive functions to add, subtract, and multiply the natural numbers. For the add function I've tried this
(: nat+ : Nat Nat -> Nat)
(define (nat+ n m)
  (match '(n m)
    ['('Zero 'Zero) 'Zero]
    ['((Succ p) 'Zero)
     n]
    ['('Zero (Succ p))
     m]
    ['((Succ p) (Succ t))
     (nat+ p (Succ m))]))

but I get the error

p: unbound identifier in module in: p.

Does anyone have any advice for writing this type of recursive function.

A: The problem is your use of quoting. When you quote a list, say '(n m), it doesn't mean "a list containing whatever n is and whatever m is - it means a list containing the literal symbols n and m. Quoting things completely ignores whatever bindings they have and only gives you the literal interpretation of whatever you quote. So when you do match '(n m), you are not matching a list containing the values n and m are bound to, you are matching a list containing the symbols n and m. Similar problems exist with your usage of quote everywhere else - in the pattern matching clauses you have to use list instead of quote to get the behavior you expect:
(: nat+ : Nat Nat -> Nat)
(define (nat+ n m)
  (match (list n m)
    [(list 'Zero 'Zero) 'Zero]
    [(list (Succ p) 'Zero) n]
    [(list 'Zero (Succ p)) m]
    [(list (Succ p) (Succ t)) (nat+ p (Succ m))]))

Note that the use of quote remains in 'Zero - this is because Zero is not a binding with a value, you're using the literal symbol Zero so it's quoted.

Additionally, you can make this more succinct by using the define/match form:
(: nat+ : Nat Nat -> Nat)
(define/match (nat+ n m)
  [('Zero 'Zero) 'Zero]
  [((Succ p) 'Zero) n]
  [('Zero (Succ p)) m]
  [((Succ p) (Succ t)) (nat+ p (Succ m))])

This form lets you match against the arguments directly, instead of having to pack them together into a list first.


text:
Q: INSERT COMMAND :: ERROR: column "value" does not exist I'm using postgresql and I'm trying to insert data into a table users. When I do that using
INSERT INTO users (user_name, name, password,email)
    VALUES ("user2", "first last", "password1", "user2@gmail.com" );

I get the following error:
ERROR:  column "user2" does not exist

This is how the table looks like:
Table "public.users"
  Column   |       Type    |  Modifiers
 user_name | character varying(50)  |
 name      | character varying(50)  |
 password  | character varying(50)  |
 email     | character varying(100) |
 user_id   | integer                | not null default nextval('users_user_id_seq'::regclass)
Indexes:
    "users_pkey" PRIMARY KEY, btree (user_id)

I was able to insert a row, but it is not working now.

A: Character constants need single quotes.
Use: INSERT INTO users(user_name, name, password,email) VALUES ('user2','first last','password1', 'user2@gmail.com' );
See the manual: postgresql.org/docs/current/static/…
Note: After I encountered the same problem and almost missed the answer that exists in this page (at the comments section), thanks to @a-horse-with-no-name - I've posted this answer

A: You use double quotes for VALUES instead of single quotes. That's why you got the error:
INSERT INTO users (user_name, name, password,email)
    VALUES ("user2", "first last", "password1", "user2@gmail.com");
            ↑     ↑  ↑          ↑  ↑         ↑  ↑               ↑

So, use single quotes for VALUES instead as shown below, then you can solve the error:
INSERT INTO users (user_name, name, password,email)
    VALUES ('user2', 'first last', 'password1', 'user2@gmail.com');
            ↑     ↑  ↑          ↑  ↑         ↑  ↑               ↑


text:
Q: How to allow Self-Signed Certificates on Android with React Native I'm developing a React Native App makes http / https requests. I'm doing for both platforms Android and iOS. I am facing with a problem that don't let me fetch an url with self-signed certificate. I have tested that this is working with other url that aren't self-signed. There is a way to force React Native to trust in Self-Signed certificates?
The error that I get when I execute the fetch() function is this:
TypeError: Network request failed
Here I post my code:
const form = new FormData();
form.append('parameters[ticketPerson]', this.state.ticketPerson);
form.append('rawxmlresponse', 'false');

fetch(this.state.url, {
    method: 'POST', headers: { Connection: 'close' },
    body: form,
})
.then(response => response.json())
.then(async (responseJson) => {
  console.log('repsonse --->', responseJson);
})
.catch((error) => {
  console.log('ERROR ---> ', error);
});

It works on iOS, only fail on Android. And this code works on Android if the url is not a Self-signed certificate.
Avoid responses like "You shouldn't trust in" or "Just Sign it and will work".

A: I had to change the certificates by server side. Also I had similar problems due to TSL2 because Android < 5 won't connect with it


text:
Q: Prolog Successor Arithmetic I have a knowledge base with the following:
numeral(0).
numeral(s(X)) :- numeral(X).
numeral(X+Y) :- numeral(X), numeral(Y).

add(0,X,X).
add(s(X),Y,s(Z)) :- add(X,Y,Z).

add2(W+X,Y+Z,R) :- add(W,X,A),add(Y,Z,T),add2(A,T,R).
add2(X+Y,Z,R) :- add(X,Y,A),add2(A,Z,R).
add2(X,Y+Z,R) :- add(Y,Z,A),add2(X,A,R).
add2(X,Y,R) :-  add(X,Y,R).

which evaluates correctly queries such as:
?- add2(s(0)+s(s(0)), s(s(0)), Z).
Z = s(s(s(s(s(0)))))

?- add2(0, s(0)+s(s(0)), Z).
Z = s(s(s(0)))

?- add2(s(s(0)), s(0)+s(s(0)), Z).
Z = s(s(s(s(s(0)))))

However the following query is evaluated to:
?- add2(s(0)+s(0), s(0+s(s(0))), Z).
Z = s(s(s(0+s(s(0))))) .

But the required output is:
?- add2(s(0)+s(0), s(0+s(s(0))), Z).
Z = s(s(s(s(s(0)))))

I know the issue is with the line:
add2(W+X,Y+Z,R) :- add(W,X,A),add(Y,Z,T),add2(A,T,R).

But i just can't figure it out. Any help would be appreciated!

A: I think you make the problem more complex by handling the cases with an add2/3 predicate. You first need to resolve the structure of the first two arguments to something of the shape s(s(...s(0)...)).
In order to do this, we can make an resolve/2 function that looks for (+)/2 terms and recursively works with add/3:
resolve(0,0).
resolve(s(X),s(Y)) :-
    resolve(X,Y).
resolve(X+Y,Z) :-
    resolve(X,RX),
    resolve(Y,RY),
    add(RX,RY,Z).

So now for a grammar:
E -> 0
E -> s(E)
E -> E + E

resolve/2 will convert this to a grammar with:
E -> 0
E -> s(E)

For example:
?- resolve(s(0)+s(0),X).
X = s(s(0)).

?- resolve(s(0+s(s(0))),X).
X = s(s(s(0))).

And now our add2/3 predicate will first resolve/2 the operands, and then add these together:
add2(A,B,C) :-
    resolve(A,RA),
    resolve(B,RB),
    add(RA,RB,C).

The sample queries you then write resolve to:
?- add2(s(0)+s(s(0)), s(s(0)), Z).
Z = s(s(s(s(s(0))))).

?- add2(0, s(0)+s(s(0)), Z).
Z = s(s(s(0))).

?- add2(s(s(0)), s(0)+s(s(0)), Z).
Z = s(s(s(s(s(0))))).

?- add2(s(0)+s(0), s(0+s(s(0))), Z).
Z = s(s(s(s(s(0))))).


text:
Q: Closing, then reopening a pull request with some new commits I've had a PR open for a few days that's now a little stale.  I've been asked to close it, make some changes, then re-open.
I'm not sure how to do that however-- and the current pull request has about five commits to it.
Should I open a new branch, make my new modifications, then submit a PR from there?  If so, how can that PR have the other five commits in it?  If there are better ways to do this I'd be interested to know.

A: A pull request is, effectively, one person requesting that their branch make their way into another branch, so you're only dealing with branches at a Git level.
At a GitHub level, you can close a PR without deleting the branch, which is likely what you want to do here.
How you proceed depends on the history you want.  Note that I'm invoking these from a local Git standpoint, as the GitHub interaction we need is only really concerned with the PR.

*

*If you want to simply continue the work you need to and reopen the PR, then do the work on that branch directly.  It will still have the other commits from that branch so you don't run the risk of anything getting lost.
It also means one less branch to keep track of mentally, and one less branch to delete when all of the work is merged up.  Lastly, it keeps the commit history cleaner, as there are no unnecessary merge commits lingering around.

*If you want to branch off of the branch, then that's an option too - create a branch as you normally would, do your work, and then submit your PR.  This branch will also have the other commits on it, so you don't run the risk of anything getting lost.

A: This may tangentially help in this scenario too...  After closing a Github Pull Request, without deleting its original branch, that Pull Request can later be reopened in the web UI:  Just make a comment on it, and there will be a 'Reopen Pull Request' to submit that comment with.


text:
Q: Running a simple server, but the counter seems to go up by 3, why? I have this little server here. The intent is that if I visit localhost:8000/* it should increase counter by 1, and if I go to localhost:8000/count, it should show me the current number of counter.
A weird thing happening is that it seems like every time I visit localhost:8000, the counter goes up by 3. So I'd go to localhost:8000/count and the counter would be at 3, and then I visit localhost:8000, and then localhost:8000/count again, counter would now be at 6. Why does that happen? Is there something weird with net/http?
Also, why is it that when I refresh localhost:8000/count, the count goes up 1 by 1? The counter func doesn't increment count, yet count still goes up - why is that? Does handler get added to the localhost:8000/count route as well?
package main

import (
        "fmt"
        "log"
        "net/http"
        "sync"
)

var mu sync.Mutex
var count int

func main() {
        http.HandleFunc("/", handler)
        http.HandleFunc("/count", counter)
        log.Fatal(http.ListenAndServe("localhost:8000", nil))
}

// handler echoes the Path component of the requested URL.
func handler(w http.ResponseWriter, r *http.Request) {
        mu.Lock()
        count++
        mu.Unlock()
        fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path)
}

// counter echoes the number of calls so far.
func counter(w http.ResponseWriter, r *http.Request) {
        mu.Lock()
        fmt.Fprintf(w, "Count %d\n", count)
        mu.Unlock()
}

A: The extra requests are your browser trying to access /favicon.ico
You can see this, for example, if you print the http.Request to stdout in your handler funcs.

A: The issue is that your handler is serving extra static content like favicon and such. If you log the request, you'll see your browser is probably also requesting
/favicon.ico, which is being passed to that same handler.
To serve static content one way is to create your own ServeMux:
package main

import (
    "fmt"
    "net/http"
    "strings"
)

var chttp = http.NewServeMux()

func main() {

    chttp.Handle("/", http.FileServer(http.Dir("./")))

    http.HandleFunc("/", HomeHandler) // homepage
    http.ListenAndServe(":8080", nil)
}

func HomeHandler(w http.ResponseWriter, r *http.Request) {

    if (strings.Contains(r.URL.Path, ".")) {
        chttp.ServeHTTP(w, r)
    } else {
        fmt.Fprintf(w, "HomeHandler")
    }
}

Serve homepage and static content from root


text:
Q: Which multiplication and addition factor to use when doing adaptive learning rate in neural networks? I am new to neural networks and, to get grip on the matter, I have implemented a basic feed-forward MLP which I currently train through back-propagation. I am aware that there are more sophisticated and better ways to do that, but in Introduction to Machine Learning they suggest that with one or two tricks, basic gradient descent can be effective for learning from real world data. One of the tricks is adaptive learning rate.
The idea is to increase the learning rate by a constant value a when the error gets smaller, and decrease it by a fraction b of the learning rate when the error gets larger. So basically the learning rate change is determined by:
+(a)

if we're learning in the right direction, and
-(b * <learning rate>)

if we're ruining our learning. However, on the above book there's no advice on how to set these parameters. I wouldn't expect a precise suggestion since parameter tuning is a whole topic on its own, but just a hint at least on their order of magnitude. Any ideas?
Thank you,
Tunnuz

A: I haven't looked at neural networks for the longest time (10 years+) but after I saw your question I thought I would have a quick scout about.  I kept seeing the same figures all over the internet in relation to increase(a) and decrease(b) factor (1.2 & 0.5 respectively).
I have managed to track these values down to Martin Riedmiller and Heinrich Braun's RPROP algorithm (1992).  Riedmiller and Braun are quite specific about sensible parameters to choose.
See: RPROP: A Fast Adaptive Learning Algorithm
I hope this helps.


text:
Q: Convert Multiple Json Array to a Single Array Rather than Array Inside a Parent Array I have Following 2 Json in 2 rows.
  {
            "attributes": [{
                "name": "text-1580797977710",
                "value": "Nikesh Niroula"
            }, {
                "name": "email-1580797979166",
                "value": "nikesh@gmail.com"
            }]
          }

{
    "attributes": [{
            "name": "text-1580797977720",
            "value": "Denver"
        }, {
            "name": "text-1580797977723",
            "value": "colarado"
        },
        {
            "name": "text-1580797977727",
            "value": "USA"
        }
    ]
}

I need the above json to be aggregated into one single array by using postgresql, the expected result would be as below. I tried using json_agg but this will add a inner array inside the main array. There might be multiple json and not only 2.
  {
        "attributes": [{
                "name": "text-1580797977710",
                "value": "Nikesh Niroula"
            }, {
                "name": "email-1580797979166",
                "value": "nikesh@gmail.com"
            }, {
                "name": "text-1580797977720",
                "value": "Denver"
            }, {
                "name": "text-1580797977723",
                "value": "colarado"
            },
            {
                "name": "text-1580797977727",
                "value": "USA"
            }
        ]

     }

A: You can use
the concatenation operator (||) along with jsonb_array_elements jsonb_agg functions to solve your problem.
with t (id,
attr1,
attr2) as (
values (1,
'{
      "attributes": [
        {
          "name": "one-1",
          "value": "Nikesh Niroula"
        }]}'::jsonb,
'{"attributes": [
        {
          "name": "one-2",
          "value": "Nikesh Niroula"
        }]}'::jsonb) ,
(1,
'{
      "attributes": [
        {
          "name": "two-1",
          "value": "Nikesh Niroula"
        }]}'::jsonb,
'{"attributes": [
        {
          "name": "two-2",
          "value": "Nikesh Niroula"
        }]}'::jsonb) ,
(1,
'{
      "attributes": [
        {
          "name": "three-1",
          "value": "Nikesh Niroula"
        }]}'::jsonb,
'{"attributes": [
        {
          "name": "three-2",
          "value": "Nikesh Niroula"
        }]}'::jsonb) ,
(2,
'{
      "attributes": [
        {
          "name": "four-1",
          "value": "Nikesh Niroula"
        }]}'::jsonb,
'{"attributes": [
        {
          "name": "four-2",
          "value": "Nikesh Niroula"
        }]}'::jsonb) )
select
    id ,
    jsonb_agg(value)
from
    t,
    jsonb_array_elements(attr1->'attributes' ||(attr2->'attributes'))
group by
    1;

A: You need to unnest them before you feed them to the agg function.  If the table is "j" and the column is "x", then:
select jsonb_build_object('attributes',jsonb_agg(value))
   from j, jsonb_array_elements(x->'attributes');


text:
Q: Is a private static field guaranteed to be non null when accessed from a static method if initialized in the private constructor I have a class named UrlController The method is like:
public class UrlController {
    private static final String BASE_URL = "http://api.site.mil/";

    private static Retrofit retrofit;

    private UrlController() {
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    public static Retrofit getRetrofit() {
        return retrofit;
    }
}

Should I check if(retrofit==null) in the getRetrofit() method or it's that always not null?

A: Since the method getRetrofit is static, hence it can be called, even when the object of the class has not been created.
Hence, you must check for it.
But even if you don't check, the method will return null. So you must check for null where you call this method.

A: Are you trying to create a Singleton?
Because right now you have a private constructor which can only be called within the class. So your retrofit field will always be null. Furthermore you probably want to use something like this:
public final class UrlController {
private static final String BASE_URL = "http://api.site.mil/";
private static volatile Retrofit instance;

private UrlController() {
    instance = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
}

 public static Retrofit getInstance() {
        if (instance == null) {
            synchronized (UrlController.class) {
                if (instance == null) {
                    instance = new UrlController();
                }
            }
        }
        return instance;
    }

}

With that you can simple call UrlController.getInstance() and you will never get a null by that.

A: Nothing can construct UrlController (except UrlController because your constructor is private) so retrofit is guaranteed to be null. I think you wanted a static initializer. Something like,
static {
    retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
}


text:
Q: "Disk Not Ejected Properly" Alert after computer goes to sleep USB3 only Ok so this is a relatively new one for me, I recently upgraded my computer, both to Yosemite and installing a USB3 Card from Sonnet.  I have downloaded the drivers for the Sonnet card, and everything works great with it.  However when my computer goes to sleep and then wakes back up, I am left with the alert that a drive was not ejected properly. It will list any and all USB 3 drives only that were connected and mounted.  However when waking back up those drives will still be mounted on the computer.
So I am not sure what is causing the message, or if the drives are actually being disconnected, but something seems to be amiss.
Any help would be appreciated.
Computer system is 2012 Mac Pro 3.47 12 Core

A: The likely answer is that your external drives also have a hibernate feature on them, and when they hibernate, Yosemite sees it as the drive disconnecting without it being ejected.
This exception is likely picked up by OS X even though the system is asleep. When you wake the Mac again, you will still see the warning, but the drives are also woken up and reestablish their connection to the Mac, so you can access them and see them as mounted.
Check the documentation for the drives that you have to see if they have a hibernate feature and whether it can be turned off. If it can, then turn it off, let the computer go to sleep and see if the warning comes back.
You can also test by setting the Energy Saver>Computer Sleep in System Preferences to 1 minute let the computer go to sleep, then wait about 5 to 10 minutes and wake it again. Unless the external drives are taking their cue from the USB card and hibernating the drives, they likely should not have entered hibernation, which means when you wake the Mac, you shouldn't see the Disk Not Ejected Properly warning.
Though less likely check the documentation for the USB 3.0 card and see how it behaves when your computer goes to sleep. Maybe it enters into low power mode that causes it to loses its connections, sort of like how your phone won't charge from a USB on a shutdown computer.

UPDATE

I thought of another thing that you can check for. Take a look at *Energy Saver>Computer Sleep** in System Preferences and see if the "Put hard disks to sleep when possible" is checked. This really should only effect internal HDDs, but maybe that could have a knock on effect to your external HDDs as well.
Also, if you have not filled these drives up yet and have the room to back them up, I would recommend going into Disk Utility and formatting them as Mac OS Extended (Journaled), or even better as they are externals, Mac OS Extended (Journaled, Encrypted), if you have not already done so. While most manufactures say that they are Mac compatible, what it usually means that they are ExFat formatted. If you are using the drives exclusively with Mac, it is always best to freshly format them to the native OS X format. It also has the added benefits of wiping away all of the OEM "utilities" that generally do nothing but make performance worse.

A: in energy saver settings in system preferences disable or uncheck "put hard disks to sleep when possible"  That stops the HDs from ejecting when MAC goes to sleep.

A: Finally figured this out. My issue was my surge protecter. I had my drive plugged into a secondary slot that would power down when not in use (computer in master plug and when computer would sleep all other outlets power down).
I switched to and "unswitched" outlet on surge protector and now all is good.

A: Turn off Spotlight for your external drivers in System Preferences -> Spotlight -> Privacy, and they will not be ejected when the computer is sleeping. I found this solution here.

A: I have a 27" IMAC 14.2  late 2013 using Sierra 10.12.5 and in Energy Saver of system preferences have checked only the first box-prevent computer from sleeping automatically when display is off.  This seems to work and am not getting the disk not ejected properly so far.  Will see if this continues to work.

A: My Mac pro does the same thing. Any drive, SD card or USB jump drive will show the "not ejected properly" warning every-time my Mac pro 5,1 comes out of deep sleep. This only happens on my USB3 PCI card. I have 2 Datatale removable drive enclosures on eSata with no ejection problems. Recently bought a OWC USB3 Dual Drive dock, since I can't get the Datatale enclosures anymore. Was hoping they wouldn't act like my USB 3 desktop hub, but unfortunately, I get the warning now on the Seagate drives in it. I plugged the dock into the Mac pro USB 2 port in the rear and the warnings have completely gone away. While I've lost USB 3 speed in dock's hard drives, I'm only using them as a archive back-up system, so once I copied over the vast amount of info on USB3, USB2 is fine for incremental backups using smart update with SuperDuper. Others tell you to uncheck "put the drives or computer to sleep  when ever possible" in the OS System Energy saver preferences, but that defeats the deep sleep feature of shutting down the drives and computer when not in use. Perhaps someone makes a USB3 PCI that won't eject the disks, but for now, the USB2 solution works fine and no more annoying and possibly digit damaging eject drive warnings :-)

A: "Jettison for Mac" is a neat little GUI app that costs only a few dollars and solves all these problems.  Very customisable, so you can decide what to unmount, remount etc etc.
Super little app.
Mac *


text:
Q: JNI library name for 64 bit architecture on linux I develop a JNI dynamic library for java desktop. For now it works on MacOS and Windows, but on Linux I have a weird behaviour.
I Have the library compiled for 32 and 64 bits, but when I only put the 64 bits library and I call  System.loadLibrary (myLibrary); it is not able to find it, but in a 32 bits architecture when I only add the 32 bits it is able to find it (I name it libMyLibrary.so).
So my question is, for 32 bits I need to name it like libMyLibrary.so but how it should be named the 64 bits architecture? Shall I write some code that loads the proper library depending on the architecture?
Thanks!

A: The standard solution is to have 32 and 64 bit versions (and for other architectures) in separate directories, and make sure the java.library.path points to the right one.

A: What version of library your JVM should load depends on the JVM version the code run on, as well as the os architecture. 32 bits JVM should load 32 bits library, 64 bits should load library for 64 bits.
I have Ubuntu 64 bits OS with two JVM installed. One is 64 bits
$ java -version
java version "1.8.0_25"
Java(TM) SE Runtime Environment (build 1.8.0_25-b17)
Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode)

And another is 32 bits
$ /opt/jdk1.7.0_72/bin/java -version
java version "1.7.0_72"
Java(TM) SE Runtime Environment (build 1.7.0_72-b14)
Java HotSpot(TM) Server VM (build 24.72-b04, mixed mode)

I use the following code to load libraries for app running in different JVMs.
static {
    if (System.getProperty("os.name").equals("Linux")) {
        if (System.getProperty("os.arch").equals("i386")) {
            System.out.println("loading i386 library");
        } else if (System.getProperty("os.arch").equals("amd64")) {
            System.out.println("loading x86_64 library");
        }
    }
}


text:
Q: EditText not tinted in Accent color on lollipop devices I'm Software Engineering student that just started learning android development a couple months ago during my spare time.
at the moment im making my first app while learning in the process and i ran into a problem.
I'm using a DialogFragment and for some reason the Accent color i use in my theme is overridden only in pre-lollipop devices (both emulator and physical).
you can notice that only the floating hint is tinted in lollipop.

my DialogFragment layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/dialog_add_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<android.support.design.widget.TextInputLayout
    android:id="@+id/input_title_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <EditText
        android:id="@+id/input_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:hint="@string/dialog_add_title_hint"
        android:imeOptions="actionNext"
        android:inputType="text"
        android:singleLine="true" />

</android.support.design.widget.TextInputLayout>

<android.support.design.widget.TextInputLayout
    android:id="@+id/input_password_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <EditText
        android:id="@+id/input_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:hint="@string/dialog_add_password_hint"
        android:imeOptions="actionGo"
        android:inputType="text"
        android:singleLine="true" />

</android.support.design.widget.TextInputLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <Button
        android:id="@+id/input_cancel"
        style="?attr/buttonBarButtonStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:layout_weight="1"
        android:text="Cancel" />

    <Button
        android:id="@+id/input_confirm"
        style="?attr/buttonBarButtonStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:layout_weight="1"
        android:text="Add" />

</LinearLayout>

my values/styles.xml:
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="colorControlHighlight">@color/colorHighlight</item>

    <!-- Context Action Mode will Overlay Toolbar -->
    <item name="windowActionModeOverlay">true</item>

</style>

i already tried several solutions to no avail:

*

*overriding colorControlActivated and colorControlNormal - only changes floating hint tint

*changing the tint programmatically, but that only changes the underline while not focused:
Drawable background = InputTextLayout.getEditText().getBackground();
DrawableCompat.setTint(background, yourColor);
InputTextLayout.getEditText().setBackground(background);
using EditText alone, not wrapped in TextInputLayout, doesn't help either.
any ideas?
Thanks in Advance

A: after a thorough search through the internet i stumbled upon a question here in stackoverflow regarding animating a DialogFragment - here
the answer in that link referred to a post by a Google Engineer saying:

...DialogFragment is just a wrapper around a Dialog to help manage its lifecycle.  Dialogs are top-level windows so their animations are window animations, just like when you use Dialog in all other situations.  You thus control the animations of dialogs through the theme or explicit window animation style you have set in its WindowManager.LayoutParams.

so i decided to check how to theme the DialogFragment
& found this guide by CodePath - here
basically, in your App Theme, in order to override the Dialog Themes you have to add the following:
<style name="AppTheme" parent...>
    ....

    <!-- this will override DialogFragment theme -->
    <item name="android:dialogTheme">@style/MyDialogFragmentTheme</item>
    <!-- this will override AlertDialog theme -->
    <item name="android:alertDialogTheme">@style/MyAlertDialogTheme</item>
</style>

<style name="CustomAlertDialogTheme.Animation">
    ...
</style>

<style name="MyDialogFragmentTheme" parent="Theme.AppCompat.Light.Dialog">
    ...
</style>

in each of the theme you can override attributes like colorPrimary, colorAccent etc.
if using this method makes your DialogFragment appear without a title (it happend to me), then add the following to its style:
<item name="android:windowNoTitle">false</item>

Bonus - adding animations
in order to add animations to either the AlertDialog or DialogFragment, write the following in its style:
<style name="MyDialogFragmentTheme" parent="Theme.AppCompat.Light.Dialog">
        ...
        <item name="android:windowAnimationStyle">@style/MyDialogFragmentTheme.Animation</item>

</style>

then you need to create a style for the animation, for example:
<style name="MyDialogFragmentTheme.Animation">
        <item name="android:windowEnterAnimation">@anim/dialog_slide_in_up</item>
        <item name="android:windowExitAnimation">@anim/dialog_slide_out_down</item>
        <item name="android:interpolator">@android:interpolator/anticipate</item>
</style>

there's more info in the CodePath guide linked above.
note that this all takes place in values/styles.xml
hope this helps other people.


text:
Q: Connect remotely to an Android device via adb I'm just testing the adb and I'm wondering if this is possible.
I mean, let's say I have adb installed on a aws instance, whatever the Ip it may be.
Then from there, I want to connect to my Android device via adb I don't know if adb connect can do the trick having the external Ip of the device.
From what I've learned, seems like it is possible, but it's kind of confusing.
Also, I see it's possible to connect without having the device rooted.
But most tutorials or examples are based on wifi, I just want to know if there is a workaround or even a command which can make this possible remotely.
Any ideas?
Thanks in advance!

A: I would try looking into Vysor. The main purpose of this tool is to be able to control an Android device remotely, but it also provides an option to share the adb connection to the device without a root. Its a powerful tool, that as many applications.


text:
Q: Target and output in neural networks In ANN the output squeezed using sigmoid function so the result is always between 1 and  -1.
How am I supposed to calculate the error when the target value  might be  a big number?
For example I'm using ANN to predict a time series, so I get output like 0.98 but the target is 34.5.

A: You can either:

*

*have no activation function on your output layer (the "identity" activation function).

*scale your targets so that their range is spanned by the activation function of the output layer. For a typical sigmoid (logistic activation function), it would be between 0 and 1 (not -1 and 1 as you wrote).

Usually the second option is preferred because it is easier to initialize the weights.

A: The sigmoid activation is good for outputs bounded between 0 and 1 such as probabilities for classification.
In case you don't need specific bounds you can use other non-linearities like ReLU(x) = max(0,x). In case you do know some bounds for the output you can use the sigmoid and then do a linear transformation.
Warning: I saw that you are trying to train a Neural Network for a time series. Note that if you're starting with Neural Networks you may want to start with a simple FeedForward network applied to some simple problem (sequences are usually handled with Recurrent Neural Nets which are harder to train).


text:
Q: Does the absolute fragment of second-order logic satisfy a strong Lowenheim-Skolem property? Let $\mathsf{SOL_{abs}}$ be the "forcing-absolute" fragment of second-order logic - that is, the set of second-order formulas $\varphi$ such that for every (set) forcing $\mathbb{P}$ and every (set-sized) structure $\mathfrak{A}$ we have $$\mathfrak{A}\models\varphi\quad\iff\quad\Vdash_\mathbb{P}(\mathfrak{A}\models\varphi).$$ Note that this is in fact definable since the second-order theory of a structure in $V_\kappa$ is calculated, uniformly, in $V_{\kappa+1}$; by contrast, the set of forcing-absolute second-order properties of the universe is not so nice (to put it mildly).
Under a "mild" large cardinal assumption, $\mathsf{SOL_{abs}}$ has a weak downward Lowenheim-Skolem property for countable languages, namely every satisfiable countable $\mathsf{SOL_{abs}}$-theory $T$ has a countable model. This is just a consequence of the appropriate amount of large-cardinal-given absoluteness applied to the $\Sigma^1_{\omega+1}$ sentence "$T$ has a countable model," with $L(\mathbb{R})$-absoluteness being more than enough.
However, I don't see how to get the full downward Lowenheim-Skolem property for countable languages:

Does $\mathsf{ZFC}$ + [large cardinals] prove that every structure in a countable language has a countable $\mathsf{SOL_{abs}}$-elementary substructure?

(To clarify since there is a stronger notion of second-order elementary equivalence in use as well, I mean the "weak" version of elementarity here: $\mathfrak{A}\preccurlyeq_{\mathsf{SOL_{abs}}}\mathfrak{B}$ iff for every $\mathsf{SOL_{abs}}$-formula $\varphi(x_1,...,x_n)$ with only object variables we have $\varphi^\mathfrak{A}=\varphi^\mathfrak{B}\cap\mathfrak{A}^n$.)
The problem is that for a given structure $\mathfrak{A}$, the property "is a countable substructure of $\mathfrak{A}$" might be too wild for our large cardinal assumption to get useful purchase.

A: At MO, user Farmer S. showed that a proper class of Woodin cardinals suffices for a positive answer.
(I've made this CW to avoid reputation gain, and will delete this answer if Farmer adds one of his own; I just want to move this off the unanswered queue.)


text:
Q: Android Maps API requires openGL es 2 The Maps v2 documentation states:

Because version 2 of the Google Maps Android API requires OpenGL ES
  version 2, you must add a <uses-feature> element as a child of the
  manifest element in AndroidManifest.xml:
<uses-feature
   android:glEsVersion="0x00020000"
   android:required="true"/>`

This notifies external services of the
  requirement. In particular, it has the effect of preventing Google
  Play Store from displaying your app on devices that don't support
  OpenGL ES version 2.

In fact, it throws an exception if this is not in the manifest. I don't want to filter my app in the store, I plan to keep using the old maps for old devices, and only show the new maps if the required features are present, detected at runtime rather than before installation.
So how do I do that? Does it have to be something like multiple APKs with different manifests?

A: Final Update
As of 2013/12/20, the Android Dashboard shows that approximately 100% of devices now support OpenGL 2.0+ so this answer is no longer relevant. You may simply require OpenGL ES 2.0+ in your manifest.
Update
This is fixed as of rev 7 of the Google Play Services SDK add-on. It is safe to use <uses-feature android:glEsVersion="0x00020000" android:required="false"/> and to detect OpenGL ES 2.0 at runtime.
Original answer
It appears that the Google Maps Android API v2 requires an explicit <uses-feature android:glEsVersion="0x00020000" android:required="true/> declaration in AndroidManifest.xml so there is no way to deploy Google Maps Android API v2 services without excluding all OpenGL ES 1.x devices.  At the time of this writing, Google's Android Dashboard shows that, among 1.1 and 2.0 devices, 90.8% of devices support 2.0.
On a particular device (Motorola XOOM), this code results in supportsEs2 = true:
// Check if the system supports OpenGL ES 2.0.
final ActivityManager activityManager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
final boolean supportsEs2 = configurationInfo.reqGlEsVersion >= 0x20000;

However, when there is no <uses-feature> declaration in the manifest, MapFragment is throwing a RuntimeException:
    Caused by: java.lang.RuntimeException: Google Maps Android API only supports OpenGL ES 2.0 andabove. Please add <uses-feature android:glEsVersion="0x00020000" android:required="true" /> into AndroidManifest.xml
    at maps.y.ae.a(Unknown Source)
    at maps.y.bu.a(Unknown Source)
    at maps.y.p.onCreateView(Unknown Source)
    at com.google.android.gms.maps.internal.IMapFragmentDelegate$Stub.onTransact(IMapFragmentDelegate.java:107)
    at android.os.Binder.transact(Binder.java:297)
    at com.google.android.gms.maps.internal.IMapFragmentDelegate$a$a.onCreateView(Unknown Source)
    at com.google.android.gms.maps.SupportMapFragment$a.onCreateView(Unknown Source)
    at com.google.android.gms.internal.c$4.a(Unknown Source)
    at com.google.android.gms.internal.c.a(Unknown Source)
    at com.google.android.gms.internal.c.onCreateView(Unknown Source)
    at com.google.android.gms.maps.SupportMapFragment.onCreateView(Unknown Source)
    at android.support.v4.app.Fragment.performCreateView(Fragment.java:1460)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:884)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1066)
    at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1168)
    at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:280)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:669)
    ... 22 more

Here's to hoping that an update to the Maps library will remove this limitation so we can deploy a single APK and use runtime APIs to determine whether or not to load the new Google Maps v2 experience or fall back to another compatible solution.

A: This is fixed and will be release with next release of Maps Android API as mentioned in issue #4699

A: I had the same problem, looked around and most of the suggested workaround for the emulator didn't work for me. Then i found a post were the Genymotion emulator was suggested. This emulator supports OpenGL ES version 2. It is also much faster than the standard emulator.


text:
Q: DB Error: 26 "file is not a database" FMDB with SQLCipher Hello I am trying to open password protected database file. I ma using FMDB/SQLCipher. I am getting error file is not a database.
        rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0);
if (SQLITE_OK != rc) {
            if (_logsErrors) {
                NSLog(@"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
            }
}

DB Error: 26 "file is not a database.

I had added database at current place. My pod looks like
target 'FMDBDemo' do
  # Comment the next line if you don't want to use dynamic frameworks
  use_frameworks!
  pod 'FMDB/SQLCipher'   # FMDB with SQLCipher

  post_install do |installer|
      installer.pods_project.targets.each do |target|
          if target.name == "FMDB"
              config_path = target.build_configurations[0].base_configuration_reference.real_path
              File.open(config_path, "a") {|file| file.write("HEADER_SEARCH_PATHS = SQLCipher")}
          end
      end
  end

end


text:
Q: Mutate a list of object in FaunaDB I have my GraphQL schema imported in FaunaDB and want to create a new question
type Choices {
  key: String!
  value: String!
  question: Question
}

type Question {
  title: String!
  snippet: String
  choices: [Choices!]! @relation
  answer: String!
  explanation: String!
}

type Query {
  allQuestions: [Question!]!
}

To do so, I'm using axios and have my GraphQL mutation like that:
const CREATE_QUESTION = `
mutation($title: String!, $explanation: String!, $snippet: String, $answer: String!, $choices: [ChoicesInput]!) {
  createQuestion(data: {
    title: $title
    explanation: $explanation,
    snippet: $snippet,
        answer: $answer,
    choices: {
      create: $choices
    }
  }) {
    _id
    explanation
    answer
    title
    snippet
    choices {
      data {
        key
        value
      }
    }
  }
}
`

Everything work except for the choices, I want to send an array of object but got the error:
Variable '$choices' expected value of type '[ChoicesInput]!' but got: "[ { key: 'A', value: '`0 1 2` and `0 1 2`' }, { key: 'B', value: '`0 1 2` and `3 3 3`' }, { key: 'C', value: '`3 3 3` and `0 1 2`' } ]". Reason: '[0]' Expected 'ChoicesInput', found not an object. (line 2, column 86): mutation($title: String!, $explanation: String!, $snippet: String, $answer: String!, $choices: [ChoicesInput]!) { ^
What should I make differently to be able to send my array of objects?


text:
Q: How can I publish my Nuxt app in Bluehost I want to publish my site in Bluehost.
When I generate the production site with yarn build, and then accessing the .nuxt directory to copy all the contents to my bluehost html folder I get just plain text and not the Running site as you can see here.
tecnoeducacion.online
Please tell me if there are more configuration steps before yarn build

A: yarn generate is for SSG (target: 'static'), if you want to host some static files. It's basically JAMstack and hostable on Github pages/Netlify/Heroku etc.
More info here: https://nuxtjs.org/docs/concepts/static-site-generation
yarn build is for SSR (target: 'server'), it requires a Node.js server and will generate all the pages on demand on the server.
More info here: https://nuxtjs.org/docs/concepts/server-side-rendering

A: I had to Yarn Generate, instead of Yarn build, to make it work, but would be good if anybody could explain the difference of one to the other command


text:
Q: conditional expectation of exponentials of independent random variables For two independent identically distributed random variables $X$ and $Y$, we have $$E[e^{iX-iY}]=E[e^{iX}]E[e^{-iY}]=|E[e^{iX}]|^2.$$
I am wondering whether the above property still holds for conditional expectation, that is, if there is another random variable $Z$ which is independent of $X$ and $Y$, is the following true:
$$E[e^{iZX-iZY}|Z]=|E[e^{iZX}|Z]|^2.$$
If true, how to prove it? I know that $E[XZ|Z]=ZE[X|Z]=ZE[X]$, but how to compute $E[e^{iZX}|Z]$? Thanks for helping!

A: If $Z$ is independent of $X$ and $Y$ then $X$ and $Y$ will still be conditionally independent given $Z,$ and the same calculation you did before goes through.


text:
Q: Usable network speed increases when screen is locked, why? While diagnosing my slow network, I've noticed that my connection speeds up whenever I lock my screen.
The peaks in the linked image correspond exactly to when my screen is locked (using Win+L), and the network usage is caused by a Steam download.
The download runs at 2 MByte/s (displayed inside Steam) when I'm logged in, but at 3 MByte/s when I've locked the screen using Win+L. The Steam download graph shows the same peaks as the task manager.
I have no idea what could cause this. The only semi-reasonable explanation I could come up with is that I could have screen recording spyware or something that streams my screen somewhere else, and somehow hides its used bandwidth from the task manager's network graph, but stops whenever I lock my screen so the bandwidth is free to be used by other programs.
Do you have any other ideas what this could be, or in case you do believe it to be malware, any suggestions as to how to proceed?


text:
Q: Docker: cannot link containers in --net=host mode I have a Couchbase server container named db launched with --net=host option which exposes port 11210, and now I have to link another container to it.
If I use the --link option while running my new container, that is type:
docker run -d -P --name my_name --link db:db my_image

I get:

Error response from daemon: Conflicting options: host type networking can't be used with links. This would result in undefined behavior.

How can I solve this?

A: You can't.
"Linking" containers doesn't make any sense when using --net=host.  When you link containers, Docker creates entries in /etc/hosts so that the containers can connect to each other by name, but when using --net=host your containers do not have unique addresses.  They are sharing the host network environment.
You can just use localhost to access services running in either container, or any valid address on your host (assuming that your service is configured to listen on all available addresses).


text:
Q: How can enable http request in the https website? Because I have a backend api with http url, if I need to call api from frontend I need to send api request through http.  My frontend was deployed to AWS Amplify, it runs as https.  When I send api request it was blocked. console said: Mixed Content: The page at https//XXXX was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint http://XXXXX  This request has been blocked; the content must be served over HTTPS.
how can I use http request here?


text:
Q: Pass a typescript class method as a callback I'm trying to use Typescript on Firebase Functions, defining a class that has a method I want to pass as a callback to export the function code.
I've tried this:
class Foo {
  bar (data) { return data.bar; }
  handler(event) { return this.bar(event.data); }
}

On index.ts I've tried:
functions.pubsub.topic('subscriptions').onPublish(new Foo().handler);

but I get cannot access property 'bar' of undefined, which means this is undefined inside handler.
I then tried to use the call method as:
const fooInstance = new Foo()
functions.pubsub.topic('subscriptions').onPublish((event) => fooInstance.handler.call(fooInstance, event));

But I get the same error. I'm clueless right now. Any suggestions?

A: Here is a version that should work... although I don't know what your onPublish expects, so I have captured the result in a variable for now as I don't know what you want to do with it.
functions.pubsub.topic('subscriptions').onPublish((event) => {
    const result = new Foo().handler(event);
});


text:
Q: Multilinear maps in python using numpy In python I have a three dimensional array T with size (n,n,n), and a 2-D array, with size (n,k).
In linear algebra, the multilinear map defined by T and applied to W, in code would be:
X3 = np.zeros((k,k,k))
    for i in xrange(k):
       for j in xrange(k):
            for t in xrange(k):
               for l in xrange(n):
                 for m in xrange(n)
                    for h in xrange(n):
                        X3[i, j, t] += M3[l, m, h] * W[l, i] * W[m, j] * W[h, t]

See
https://en.wikipedia.org/wiki/Multilinear_map
For a reference.
This is very slow. I am wondering if there exist any alternative or any pre build function in numpy that can speed up the operations.

A: Einstein summation convention? Use np.einsum!
X3 = np.einsum('lmh,li,mj,ht->ijt', M3, W, W, W)

EDIT:
Out of curiosity, I just ran some benchmarks comparing np.einsum to Divakar's approach. The difference is hugely against np.einsum!
import numpy as np

def approach1(a, b):
    x = np.einsum('lmh,li,mj,ht->ijt', a, b, b, b)

def approach2(a, b):
    p1 = np.tensordot(b, a, axes=(0,0))
    p2 = np.tensordot(p1, b, axes=(1,0))
    x = np.tensordot(p2, b, axes=(1,0))

n = 100
k = 10
a = np.random.random((n, n, n))
b = np.random.random((n, k))
%timeit approach1(a, b)      # => 1 loop, best of 3: 26 s per loop
%timeit approach2(a, b)      # => 100 loops, best of 3: 4.23 ms per loop

There's some discussion about it in this question. It all seems to come down to the generality that np.einsum tries to achieve — at the cost of being able to offload computations to low-level linear algebra packages.

A: Here's an approach using a series of dot-products -
# Get partial products and thus reach to final output
p1 = np.tensordot(W,M3,axes=(0,0))
p2 = np.tensordot(p1,W,axes=(1,0))
X3out = np.tensordot(p2,W,axes=(1,0))


text:
Q: Implement script within included php file I am in the process of loading paragraphs from php files, which I then include on my site using the include_once method. The first paragraph loads as soon as the page loads. The problem is: when I try to implement js (jQuery) on certain elements within the php files (the first paragraph in particular), they do not seem to respond to the script. Is there any way of fixing this and what would be the best of going about this?
Thanks a lot.
I have chopped out the bits of relevant code:
JS:
$('button').click(function() {
$('.target').load('more.php');
});

$('.target').hide().fadeIn(2000); //this is the part not working (I wanted to fade in the loaded php)

*Just to clarify, the file loads fine, just the fadeIn and other similar effects do not take place.
Thanks in advance.

A: When we include php files in main php file . It becomes the part of main php file and makes a document object model. If you want to select the paragraph better way is to give some id to that paragraph and then select it using jquery using there id.


text:
Q: Snip & Sketch tool always flickers when using any annotation tools tl;dr: Drawing any annotation in Windows 10's Snip & Sketch tool causes a screen flicker. Is there any workaround to this?

Snip & Sketch is a gem in Windows 10 and it makes my life really easier. But the painless usage of it is only when I am using it in a simple matter of capturing some screen regions and pasting them to some program or saving them to disk.
The real pain starts when I am trying to use it with any of its annotation tools, i.e. Ballpoint pen, Pencil or Highlighter:

Any "real" annotation (i.e. left mouse click + move your mouse without releasing left mouse to draw some shape) always causes a very short, yet eyes blowing flicker of entire screen (a very fast image-to-black fade out + black-to-image fade in).
Only single clicks, without mouse moving or mouse moving after releasing mouse button does not cause this.
Is there anyone else who is experiencing the same problem? Is it a bug documented somewhere (I hope this is not a feature!)?
Is there any possible workaround to this, to not make your eyes blow after you have to do a lot of screenshot + annotation operations in a short period of time?


text:
Q: How to find the intersection of 2 lines? I have been trying to get grep to work to find the intersection between 2 lines:
grep -Fx -f line1.txt line2.txt

Input file contents:
line1.txt:
44.5   -125.0
44.0   -124.5
43.0   -124.3
42.0   -124.0

line2.txt:
43.0 -128.0
43.1 -127.0
43.2 -126.0
43.3 -125.0
43.4 -124.0
43.5 -123.0
43.6 -122.0
43.7 -121.0

The problem is the 2 lines do not have a row that is exactly the same.
Does anyone have a simple way to find the intersecting point?
The following image shows the 2 lines and approx intersection point:

I was hoping to have a command find the intersection point for me. grep probably cannot do this?
Also, tried GMT commands, but could not get that to work either.
Any advice?
I would settle for a command that would find and write the line2.txt points that are the closest to the intersection:

A: Grep is flat out the wrong tool for this! And sed is not much better as you need to do some math. Perl is be a candidate, but the bottom line is that you need to do line intersection testing. Here are a couple links to get you started. Good thing unix is a great platform for writing programs, because you need to write a program.
https://en.wikipedia.org/wiki/Line_segment_intersection
https://stackoverflow.com/questions/563198/whats-the-most-efficent-way-to-calculate-where-two-line-segments-intersect

A: I can guess that you thinking about something like this:
( cat line2.txt; cat line1.txt | sed 's/  */ xxxx /' ) | sort -n | awk '$2 == "xxxx" {f2=$3} $2 != "xxxx" {f1 = $2} {print $1" "f1" "f2}'

output would be:
42.0  -124.0
43.0 128.0 -124.0
43.0 128.0 -124.3
43.1 127.0 -124.3
43.2 126.0 -124.3
43.3 125.0 -124.3
43.4 124.0 -124.3
43.5 123.0 -124.3
43.6 122.0 -124.3
43.7 121.0 -124.3
44.0 121.0 -124.5
44.5 121.0 -125.0


text:
Q: MarkLogic search and retrieve specific fields I am faily new to MarkLogic (and noSQL) and currently trying to learn the Java API client. My question on searching, which returns back search result snippets / matches, is it possible for the search result to include specific fields in the document?
For example, given this document:
{"id":"1", "type":"classified", "description": "This is a classified type."}

And I search using this:
    QueryManager queryMgr = client.newQueryManager();
    StringQueryDefinition query = queryMgr.newStringDefinition();
    query.setCriteria("classified");
    queryMgr.search(query, resultsHandle);

How can I get the JSON document's 3 defined fields (id, type, description) as part of the search result - so I can display them in my UI table?
Do I need to hit the DB again by loading the document via URI (thus if I have 1000 records, that means hitting the DB again 1000 times)?

A: You have several options to retrieve specific fields with your search results.  You could use the Pojo Data Binding Interface.  You could read multiple documents matching a query which brings back the entirety of each document which you can then get as a pojo or String or any other handle.  Or you can use the same API you're using above but add search options to allow you to extract a portion of a matching document.
If you're bring back thousands of matches, you're probably not showing all those snippets to end users, so you should probably disable snippets using something like
<transform-results apply="empty-snippet" />

in your options.


text:
Q: What is difference between the return value of the method named "textFieldShouldReturn(textField:)"? I have doubts when i implement the delegate method textFieldShouldReturn of UITextField, I don't know what's difference between the return value.
I have tried return false and return true in it, but I didn't find the difference between them, and my custom delegate methods are all executed, the program seems to work fine.
Here is my code:
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        let legalInput = tagTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
        if !legalInput.isEmpty {
            if isUpdate {
                if tag!.tagName != legalInput {
                    delegate?.didUpdateTagName(tagName: legalInput)
                }
            } else {
                delegate?.didAddTag(tagName: legalInput, themeId: themeId)
            }
        }
        navigationController?.popViewController(animated: true)

        // return false
        return true
    }

A: YES if the text field should implement its default behavior for the return button; otherwise, NO.
The text field calls this method whenever the user taps the return button. You can use this method to implement any custom behavior when the button is tapped. For example, if you want to dismiss the keyboard when the user taps the return button, your implementation can call the resignFirstResponder method.
You can read it on docs.
If you want to hide the keyboard when the user clicks return button then
return true

otherwise default is false , the logic depends on your UX of whether you want the keyboard visible all time or not.


text:
Q: MacBook Pro - not booting - going around in loops? After a harrowing couple of days, I found this site and am hoping someone can help.
I have a 2011 MacBook Pro which has recently started having problems booting. During a game session (SIMMS), it suddenly shutdown and refused to reboot, and since then I've been unable to use it at all. The MBP has a new install of El Capitan on it but it's been working fine for the last couple of weeks since the install.
I tried Safemode, Recovery mode etc, but it wouldn't boot into any of these either. Eventually I set it to Target mode, and reloaded El Capitan from another "Companion" MacBook Pro. This process went without a hitch.
After loading it, I booted from the "companion" MacBook to make sure the OS was working OK, and it was!
I restarted the "Companion" MBP and ejected the faulty MBP, and tried to restart it normally. No go, still wouldn't boot even with the new OS.
I've tried a number of things to get it to boot, following this fresh install, but all that happening is that it'll get to the Apple Logo, try to boot, shutdown and then go around in circles.
Eventually it'll stop on the gray screen and the fans will startup and keep running.
I'm at the end of my knowledge, so any advice would be welcome!
Thanks

A: Have you had a luck with it yet?
Sound like it may be similar to mine. Logic board for Mac Book Pro's sold between late 2011, whole 2012 and start 2013 are under Apple's Extended Warranty Program. Your symptoms are the same as what I had before mine completely died. Going in tomorrow to have my logic board replaced for free. Thanks Apple.
Please see the link below.
https://www.apple.com/support/macbookpro-videoissues/
Hope this helps.


text:
Q: Hypermedia response in a microservice architecture I've started the journey of learning more about this architecture using Spring Cloud and the Netflix's projects.
From a general standpoint, I do understand the architecture but now that I'm actually coding an app, a horizon of doubts has appeared about some minimal stuff that could have a big impact in the big approach of this architecture.
First, my app is based on this tutorial which I assume as valid since it's from Spring itself: https://spring.io/blog/2015/07/14/microservices-with-spring
And now, the problem: (ALL THIS USES EUREKA) let's say I've a microservice "accounts" which consist only in Spring Data REST for the persistence/HATEOAS and on top of that I've a client service which consumes those endpoints using RestTemplate (because I'm using Ribbon's load balancer). From my view, this is how it works: user -> frontend -> client service -> Spring Data REST endpoints (the microservice) -> DB.
This is nice and all but when I get the endpoint response (from the RestTemplate), it contains hypermedia going directly to the microservice, and per se, you now can drive your way through the microservice while ignoring the load balancer, which, for me, kills the purpose of it. And if I've like 5 microservices scaling to each other, it means the user is now focusing into just one of a broad way of 5 microservice that are supposedly managed by load balancer.
Q1:
Is ok for an user to have that knowledge of the API (and then kinda killing part of the structure)?
Even if I add the links to the services detected by Eureka and delete the current endpoints to that microservice, those links aren't going to work and such means I'm chopping of the hypermedia links.
Q2:
Is there another approach to this? Through some kind of proxy, external load balancer, dns or something like that?
P.D: I don't know if I'm being clear enough. Please let me know if something is misty.
P.D.2: Summary question: what to do with those media links? Let them be or use something else (please tell) to actually get them "right"?
Edit: Based on the advices below, I added Zuul which seems to be the solution to my problem. Now, about Zuul, where should I use to filter?
My app is like this right now: account-microservice (Spring Data REST) and account-web-service (client with the RestTemplate Load balancer). Those are the Eureka registered names.
Where must go the @EnabledZuulProxy? Inside the microservice or inside the client?
My current config is this one (currently, the @EnabledZuulProxy is in the client):
My microservice:
@SpringBootApplication
@EnableEurekaClient
public class AccountServer {

    public static void main(String[] args) {
        System.setProperty("spring.config.name", "AccountServerClient");
        SpringApplication.run(AccountServer.class, args);
    }
 }

 //Config:
 spring.application.name=account-microservice
 spring.application.freemarker.enabled=false
 eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/
 eureka.client.instance.leaseRenewalIntervalInSeconds=5

My client:
@SpringBootApplication
@EnableEurekaClient
@EnableZuulProxy
@EnableCircuitBreaker
public class AccountMicroService {

    public static void main(String[] args) {
        // Tell server to look for registration.properties or registration.yml
        System.setProperty("spring.config.name", "AccountMicroServiceClient");
        SpringApplication.run(AccountMicroService.class, args);
    }
 }

 //Config
 # Spring properties
 spring.application.name=account-web-service
 spring.freemarker.enabled=false
 eureka.instance.leaseRenewalIntervalInSeconds: 5
 eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/
 zuul.routes.account-web-service.path=/accounts/**
 zuul.routes.account-web-service.serviceId=account-web-service
 zuul.routes.account-web-service.stripPrefix=false

Client code to consume SDR:
//@HystrixCommand(fallbackMethod="test")
public ResponseEntity<PagedResources<AccountResource>> findAll(Pageable pageable) throws RestClientException, URISyntaxException {

    return restTemplate.exchange(serviceUrl + "/accounts" + "?page={page}&size={size}&sort={sort}", HttpMethod.GET,
            null, new ParameterizedTypeReference<PagedResources<AccountResource>>() {
            }, pageable.getPageNumber(), pageable.getPageSize(), pageable.getSort());
}

Like this, it doesn't work at all. No filtering neither. If I change that and use it in the microservice, then it keeps sending everything directed to the microservice to the client, even the request from the client, which ends up with a loop and then an error (timeout, load balancer full, circuit broken...) which is generally this though: com.netflix.zuul.exception.ZuulException: Forwarding error.
Edit 2: I finally got Zuul to work and understood what it does. Now, when I access my new gateway app, it forwards the request to my microservice and the resulting hypermedia is now pointing to that gateway, which is what I wanted.
The problem was initially architectural and then turned into a coding problem, but now I think am clear about this technologies.
The cup of tea was understanding what Zuul does, when and how it does it. @Ryan Baxter guideline and this two articles: https://dzone.com/articles/microservice-architecture-with-spring-cloud-and-do and https://spring.io/guides/gs/routing-and-filtering/ where fundamentals to get this done. I'm gonna redact an answer for this with what I did and what I understood.

A: If you use Zuul from Spring Cloud Netflix as your load balancer it will automatically add the X-Forwarded-Host header which Spring HATEOAS will respect.  When that header is present HATEOAS will generate links using the host value in the header.  If you are not using Zuul than you will have to configure your load balancer to add that header.

A: Ok, what I did was simply to use Zuul (as @Ryan suggested). The thing is, initially, I kind of didn't get the approach for it. This was a petty architectural problem that, after interiorizing @Ryan's suggestion with the two articles I added to the bottom of my question, finally got them all right (hope so).
First: Now that my project is using Zuul (by creating the gateway app as both of my links suggested) and have both Hybrix and Ribbon in its classpath, Zuul must wire them all together and turn into a multifunctional proxy gateway with circuit breaker and load balancing characteristics.
Second: I got rid of that rest template load balancer because: a) the responses where getting the microservice hypermedia because I wasn't sending the port forward header, which pretty much nullify Zuul's proxying capabilities; and b) because since Zuul is acting as a gateway proxy load balancer, I do think is kinda boilerplate to use ribbon again with a rest template.
Now, my app is like this: user -> {[Zuul's gateway -> Spring Data REST microservice (forwarded by Zuul)] <- Eureka}.
I'm gonna take @Ryan's answer as the one since he pointed out exactly what was happening and what in the end I did to solve my problem. Still, I'm also answering since I think further explanation about what I ended up doing could help to another SO user.
If something is wrong about my solution, please comment.


text:
Q: Docker DNS with Multiple Projects Using the Same Network I have the following docker-compose.yml file:
version: '3'
services:
    frontend:
        image: alpine
        command: tail -f /dev/null
        networks:
            - shared
            - default
    backend:
        image: alpine
        command: tail -f /dev/null
        networks:
            - shared
            - default
networks:
    shared:
        external: true

Based on the file from above I create two projects which use the same network (shared) and the same service names (frontend and backend):
docker-compose -p foo up -d
docker-compose -p bar up -d

Does the DNS of docker make sure that docker-compose -p foo exec frontend ping backend only resolves to the backend container in project foo and vice versa for project bar?

A: According to https://github.com/docker/compose/issues/4645, the resolve order in this case in non deterministic. Since the network is being converted to unordered dict in golang, the order is not preserved. Which implies https://github.com/docker/libnetwork/blob/master/sandbox.go#L593 the order of endpoints being queried don't match the order of network.
The solution is to define https://docs.docker.com/compose/compose-file/compose-file-v2/#priority if using docker-compose version 2. Or fully qualified dns name as service.network such as backend.foo_default or backend.shared.

A: Based on your setup I have used nslookup to find out whether the DNS resolution is isolated or not.
$ docker-compose -p foo exec frontend nslookup backend

Name:      backend
Address 1: 172.19.0.2 foo_backend_1.shared
Address 2: 172.19.0.4 bar_backend_1.shared

As you can see from the output above, backend resolves to both of the containers.

A: If you use docker swarm you can qualify hostnames with the service name to disambiguate containers. But I don't believe docker-compose does this.


text:
Q: Java: Layout Button/Label Placement I'm trying to make a GUI pizza menu but I'm having trouble with the placements of the buttons/labels
public class PizzaGUI extends JFrame {

private JRadioButton rdoSmall;
private JRadioButton rdoMedium;
private JRadioButton rdoLarge;
private JRadioButton rdoExtraLarge;
private JLabel lblSize;
private ButtonGroup grpSize;
JPanel panelSize;

private JCheckBox chkPepperoni;
private JCheckBox chkMushrooms;
private JCheckBox chkOlives;
private JCheckBox chkPineapple;
private JLabel lblToppings;
JPanel panelToppings;

private JRadioButton rdoSoda;
private JRadioButton rdoTea;
private JRadioButton rdoBottledWater;
private JRadioButton rdoTapWater;
private JLabel lblDrinks;
private ButtonGroup grpDrinks;
JPanel panelDrinks;

JPanel container;
JButton calculateTotal;
JLabel order;

PizzaGUI()
{
    super("Pizza Menu");

    setSize(600,500);

    setDefaultCloseOperation(EXIT_ON_CLOSE);

    createPanel();

    add(container);

    setVisible(true);

}

public void createPanel()
{

    panelSize = new JPanel(new GridLayout(5, 1));
    panelToppings = new JPanel(new GridLayout(5, 1));
    panelDrinks = new JPanel(new GridLayout(5, 1));

    container = new JPanel();

    //Calculate Total
    calculateTotal = new JButton("Calculate");
    calculateTotal.setPreferredSize(new Dimension(95,45));

    order = new JLabel("Your Order:");

    //Pizza Sizes
    lblSize = new JLabel("Choose a size:");
    rdoSmall = new JRadioButton("Small ($7)");
    rdoMedium = new JRadioButton("Medium ($9)");
    rdoLarge = new JRadioButton("Large ($11)");
    rdoExtraLarge = new JRadioButton("Extra Large ($14)");

    //Toppings
    lblToppings = new JLabel("Choose toppings ($1 Each):");
    chkPepperoni = new JCheckBox("Pepperoni");
    chkMushrooms = new JCheckBox("Mushrooms");
    chkOlives = new JCheckBox("Olives");
    chkPineapple = new JCheckBox("Pineapple");

    //Drinks
    lblDrinks = new JLabel("Choose a drink:");
    rdoSoda = new JRadioButton("Soda ($2.00)");
    rdoTea = new JRadioButton("Tea ($1.50)");
    rdoBottledWater = new JRadioButton("Bottled Water ($1.25)");
    rdoTapWater = new JRadioButton("Tap Water (No charge)");

    //Add pizza sizes to button group
    grpSize = new ButtonGroup();
    grpSize.add(rdoSmall);
    grpSize.add(rdoMedium);
    grpSize.add(rdoLarge);
    grpSize.add(rdoExtraLarge);

    //Add drinks to button group
    grpDrinks = new ButtonGroup();
    grpDrinks.add(rdoSoda);
    grpDrinks.add(rdoTea);
    grpDrinks.add(rdoBottledWater);
    grpDrinks.add(rdoTapWater);

    //Add to panel
    panelSize.add(lblSize);
    panelSize.add(rdoSmall);
    panelSize.add(rdoMedium);
    panelSize.add(rdoLarge);
    panelSize.add(rdoExtraLarge);

    panelToppings.add(lblToppings);
    panelToppings.add(chkPepperoni);
    panelToppings.add(chkMushrooms);
    panelToppings.add(chkOlives);
    panelToppings.add(chkPineapple);

    panelDrinks.add(lblDrinks);
    panelDrinks.add(rdoSoda);
    panelDrinks.add(rdoTea);
    panelDrinks.add(rdoBottledWater);
    panelDrinks.add(rdoTapWater);

    container.add(panelSize);
    container.add(Box.createHorizontalStrut(40));
    container.add(panelToppings);
    container.add(Box.createHorizontalStrut(40));
    container.add(panelDrinks);
    container.add(calculateTotal);
    container.add(Box.createVerticalStrut(100));
    container.add(order);

}

}

This the output
Menu
I have three separate grid layout panels for each type of menu and then I add it into one main panel which gets added to the frame. I would like to get the "Your Order:" placed in the middle left like the red one shown in the image. I know I can set the layout to null which would allow me to enter coordinates and it would solve my issue, however I read that it is bad practice to do it like that and I'm trying to effectively learn how to use layouts correctly. I don't even know if I'm on the right track, any examples would help. Thanks

A: May be this can help you.
You can add a seperate panel and then create a empty border for that panel.
container.add(panelSize);
container.add(Box.createHorizontalStrut(40));
container.add(panelToppings);
container.add(Box.createHorizontalStrut(40));
container.add(panelDrinks);
container.add(calculateTotal);

JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(10, 200, 10, 700));
panel.add(order, BorderLayout.EAST);
container.add(panel);

A: Your modified code it do what you want :
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;

import javax.swing.Box;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;

public class PizzaGUI extends JFrame {

private JRadioButton rdoSmall;
private JRadioButton rdoMedium;
private JRadioButton rdoLarge;
private JRadioButton rdoExtraLarge;
private JLabel lblSize;
private ButtonGroup grpSize;
JPanel panelSize;

private JCheckBox chkPepperoni;
private JCheckBox chkMushrooms;
private JCheckBox chkOlives;
private JCheckBox chkPineapple;
private JLabel lblToppings;
JPanel panelToppings;

private JRadioButton rdoSoda;
private JRadioButton rdoTea;
private JRadioButton rdoBottledWater;
private JRadioButton rdoTapWater;
private JLabel lblDrinks;
private ButtonGroup grpDrinks;
JPanel panelDrinks;

JPanel container;
JButton calculateTotal;
JLabel order;

PizzaGUI()
{
    super("Pizza Menu");

    setSize(600,500);

    setDefaultCloseOperation(EXIT_ON_CLOSE);

    createPanel();

    add(container);

    setVisible(true);

}

public void createPanel()
{

    panelSize = new JPanel(new GridLayout(5, 1));
    panelToppings = new JPanel(new GridLayout(5, 1));
    panelDrinks = new JPanel(new GridLayout(5, 1));

    container = new JPanel(new GridLayout(2,1));
    JPanel container2 = new JPanel();
    JPanel placedOrderPanel =  new JPanel(new FlowLayout(FlowLayout.LEFT));

    //Calculate Total
    calculateTotal = new JButton("Calculate");
    calculateTotal.setPreferredSize(new Dimension(95,45));

    order = new JLabel("Your Order:");

    placedOrderPanel.add(new JLabel("Your Order placed"));

    //Pizza Sizes
    lblSize = new JLabel("Choose a size:");
    rdoSmall = new JRadioButton("Small ($7)");
    rdoMedium = new JRadioButton("Medium ($9)");
    rdoLarge = new JRadioButton("Large ($11)");
    rdoExtraLarge = new JRadioButton("Extra Large ($14)");

    //Toppings
    lblToppings = new JLabel("Choose toppings ($1 Each):");
    chkPepperoni = new JCheckBox("Pepperoni");
    chkMushrooms = new JCheckBox("Mushrooms");
    chkOlives = new JCheckBox("Olives");
    chkPineapple = new JCheckBox("Pineapple");

    //Drinks
    lblDrinks = new JLabel("Choose a drink:");
    rdoSoda = new JRadioButton("Soda ($2.00)");
    rdoTea = new JRadioButton("Tea ($1.50)");
    rdoBottledWater = new JRadioButton("Bottled Water ($1.25)");
    rdoTapWater = new JRadioButton("Tap Water (No charge)");

    //Add pizza sizes to button group
    grpSize = new ButtonGroup();
    grpSize.add(rdoSmall);
    grpSize.add(rdoMedium);
    grpSize.add(rdoLarge);
    grpSize.add(rdoExtraLarge);

    //Add drinks to button group
    grpDrinks = new ButtonGroup();
    grpDrinks.add(rdoSoda);
    grpDrinks.add(rdoTea);
    grpDrinks.add(rdoBottledWater);
    grpDrinks.add(rdoTapWater);

    //Add to panel
    panelSize.add(lblSize);
    panelSize.add(rdoSmall);
    panelSize.add(rdoMedium);
    panelSize.add(rdoLarge);
    panelSize.add(rdoExtraLarge);

    panelToppings.add(lblToppings);
    panelToppings.add(chkPepperoni);
    panelToppings.add(chkMushrooms);
    panelToppings.add(chkOlives);
    panelToppings.add(chkPineapple);

    panelDrinks.add(lblDrinks);
    panelDrinks.add(rdoSoda);
    panelDrinks.add(rdoTea);
    panelDrinks.add(rdoBottledWater);
    panelDrinks.add(rdoTapWater);

    container2.add(panelSize);
    container2.add(Box.createHorizontalStrut(40));
    container2.add(panelToppings);
    container2.add(Box.createHorizontalStrut(40));
    container2.add(panelDrinks);
    container2.add(calculateTotal);
    container2.add(Box.createVerticalStrut(100));
    container2.add(order);
    container.add(container2);
    container.add(placedOrderPanel);
}

public static void main(String args[]) {
  new PizzaGUI();
}

}