text:
Q: Javascript взаимодействие с элементом
Как сделать в javascript, чтобы при нажатии на голубой менялся цвет на желтый, а тот голубой, который был до этого, стал жёлтым, а при нажатии на жёлтый он менялся на красным, ну и красный с черным, а черный в свою очередь с голубым.
    div = document.querySelector("div")

    div.onclick = function (sobitie) {
        if (sobitie.target.classList.contains("div")) {

            blue.style.background = yellow.style.background

Но меняется только один цвет

A: Я не уверен что правильно понял вопрос. Вы имеете ввиду что надо менять цвет соседних блоков?

const colors = ['green', 'lightsalmon', 'navy', 'deepskyblue', 'slateblue'];

function wrap(level, string = '') {
  const id = level === 1 ? 'id="inner"' : '';
  return level ? `<div ${id} style="background-color: ${colors[level - 1]};">${wrap(--level, string)}</div>` : string;
}

document.addEventListener("DOMContentLoaded", function() {
  document.body.insertAdjacentHTML('beforeend', wrap(colors.length));

  document.body.addEventListener('click', (event) => {
    const next = event.target.parentElement === document.body ? inner : event.target.parentElement;
    [next.style.backgroundColor, event.target.style.backgroundColor] = [event.target.style.backgroundColor, next.style.backgroundColor];
  });
});
div {
  padding: 2rem;
}


text:
Q: What is the best way to save iphone app settings? I'd like to allow user to change the setting of app. But I am not sure where shall I save the configuration.
Is there any local space allocated for app?

A: You should use the NSUserDefaults class for storing settings. It's all documented.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Intent of Command pattern? In Elements of Reusable Object Oriented software by Erich Gamma, the intent for Command design pattern says:

Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.

What does the author mean by undoable operations? Hard to make out what he actually wants to refer here. I would appreciate a clarification.

A:
What does the author mean by undoable operations? Hard to make out what he actually wants to refer here.  I would appreciate a clarification.

He means the the operations which may be undone (reversed in a Ctrl-Z sense of a word).
At the minimum an abstract command interface defines the Execute() method.  If we go beyond the minimum, the command interface may also define an Undo() method.  If an Execute() arithmetically adds a number to its receiver, then the Undo() would subtract the same number from the total, for example.
The invoker may keep a list of the past executed commands, instead of discarding each command as soon as it has executed.  The invoker can call Undo() on past commands.
Good discussion here.
The examples in the GoF book don't have the Undo() methods.

A: I think its difficult to understand the pattern without looking at code. How about commanding a Human to Walk around a Walking Track?
Here is an implementation of a Command Pattern:
class Walk
{
    Walk(WalkingTrack track);

    Location walk(Human human);
}

This is simply a Lambda Function for languages without lambda functions.
Here is another implementation of the command patttern:
class Walk
{
    Walk(WalkingTrack track);

    Walking walk(Human human);
}
class Walking
{
    Location location();
    bool completed();
    void cancel();
}

This is a cancel-able command. It is by nature asynchronous, and the caller (or whomever has access to the returned Walking object) can request the process to be stopped, or otherwise monitor its status and perhaps its progress.
An undoable version of the above command would require that calling cancel() also undoes any side-effects introduced by the Walking processing the command. Essentially making the Walking class a form of Transaction.
Here is another Cancelable Command:
class Walk
{
    Walk(WalkingTrack track);

    Location location();

    bool walk(Human human);
    bool walking();
    bool completed();
    void cancel();
}

Try to avoid this layout though. It mixes several layers of concern which clouds its purpose. It also makes it easier for usage mistakes to be accepted by the compiler.

A:

What does the author mean by undoable operations? Hard to make out what he actually wants to refer here. I would appreciate a clarification.

He means just rolling back changes. I'm assuming you understand undos/redos and how they work to users just by virtue of using software in general (ex: ctrl-Z to undo a mistake you made). I might be wrong but I interpreted the question as more about how the command pattern facilitates undoing.
With the command pattern you have this object and abstraction between the invoker who wants to "do something" and the receiver who directly does it. As a basic example you might have an image software where the user wants to blur an image.
With the command pattern you'd have this sort of "Blur Image" command object with an abstract interface that all commands have in common, and so you have this command object to execute between the code that wants to blur an image and the code that actually does it. And that provides breathing room in the middle of these two to centralize functionality like logging all commands that are executed.
And likewise if the abstract command interface provides methods like undo/redo, then specific command subtypes can implement/override those functions to undo and redo whatever changes they make in their execution. Then instead of discarding the command object, the system can push it to the history ("undo stack") and start invoking those undo/redo methods as the user moves around in the history, e.g.
With that aside, you don't actually have to have undo/redo functions in the command interface to get undo/redo functionality in ways that still benefit from the command pattern (I wanted to pitch in primarily to mention this point). Again you have this central command execution area between invoker and receiver, so alternatively you can capture your application state before execution of any command (which would alter that state) and push that data (program state) to the undo stack (perhaps in a compacted form) prior to executing any command, and that likewise facilitates undoing/redoing even though the commands themselves don't provide undo/redo functionality.
You have this sort "sandwich". If the invoker and receiver are like two pieces of bread, the command pattern gives you room to put all kinds of stuff in the middle of requesting to perform some operation, like centralized logging, later you might want to uniformly execute commands in a deferred async fashion, you might want to capture program state prior to execution of any command for undoing, you might want to execute the command in a separate process so that if it crashes, the host application doesn't crash, etc. etc. etc. Whereas if the invoker directly invoked functions in the receiver (ex: blurring images directly with no command in the middle), you don't have that centralized breathing room in the middle to uniformly add and do whatever you want.
And specifically by virtue of commands being abstract objects which encapsulate their execution parameters, you can keep them around and execute them at a later time, re-execute them, etc, long after the receiver made the original request. You can also serialize them cheaply. If your program state is uniformly altered by commands, then that state might span gigabytes but the entire user's command history might be capable of being stored in kilobytes, and you can reevaluate those commands and get back to exactly the same state the user was in by just executing those same commands again with the same parameters and order the user originally invoked them.


text:
Q: Apache Thrift: Open and close transport automatically in C++ Background: I have many small c++ programs that all use the same static library. I'm now implementing thrift as a middle layer so that I can run the small c++ programs on a different computer from the static library. I can't change the c++ programs, so I am making a "fake" static library that looks like the original, but is actually a thrift client that calls the real static library.
Issue: How can I make the static library so that the c++ programs will automatically open the socket when it opens the library, and closes the socket when the program exits??
Usually thrift clients use a main method that opens the socket in the beginning and closes it in the end. I can have the library check if the socket is open before every method call, but I don't know how to close the socket. Is there any problem with leaving it open?

A: One approach might be to create a C++ class in your library with a single local static instance. Since the instance will be constructed on first call and destroyed on unload, you can connect and disconnect using the constructor/destructor, something like this:
#include <boost/shared_ptr.hpp>
#include <thrift/transport/TSocket.h>
#include <thrift/protocol/TBinaryProtocol.h>
#include "gen-cpp/mySvc.h"

using namespace apache::thrift::transport;
using namespace apache::thrift::protocol;

class ThriftProxy {
public:
    ThriftProxy() :
        trans(new TSocket("myhost", 8585)),
        proto(new TBinaryProtocol(trans)),
        client_(proto)
    {
        trans->open();
    }

    ~ThriftProxy()
    {
        trans->close();
    }

    static mySvcClient & client()
    {
        static ThriftProxy proxy;
        return proxy.client_;
    }

private:
    boost::shared_ptr<TSocket> trans;
    boost::shared_ptr<TProtocol> proto;
    mySvcClient client_;
};

the functions in your lib can then call through to the Apache Thrift server using the ThriftProxy::client() method:
int exportedFunc(int i) {
    return ThriftProxy::client().myRPCFunc(i);
}

Note: In most cases adding a TBufferedTransport or TFramedTransport to the I/O stack is a good idea to reduce small writes to the network. Left out here to keep the example simple.


text:
Q: How to save tensor with numpy? I need to save tensor by transform the x[-1] to numpy matrix, and then save it as a pkl file.
def forward(self, x):

   x=self.forward_features(x)

What does x[-1] means ? How can I transform x to numpy ..
Y=[]
Y=x.transform()
With open('result.pkl','w') as file
     Pickle.dump(Y,file)

A: x[-1] gets you the last item on the list.
If x is a list, do np.array(x) to convert the list to a numpy array.
To save x to a pickle file, do
import pickle
import numpy as np

x = np.array([1, 2, 3])

with open('res.pkl', 'wb') as df_file:
    pickle.dump(obj={'x':x}, file = df_file)


text:
Q: bootstrap-datetimepicker not executing correctly The docs at bootstrap-datetimepicker don't really explain what version of jquery and moment are required to use the widget (if specific versions are needed). I don't have any jquery errors according to dev tools, and I tested the calendar icon button by adding some quick jquery which worked fine.
($("#datetimepicker10 span").click(function(){
    alert('working!');
    };
));

Otherwise, I have everything required in the docs loaded in the correct order (I think). However; the icon link doesn't work and thus I cannot select a date nor time. I assume it is something with how files are being loaded or the version of jquery/moment I am using because I tried dropping in this jsfiddle, and it wouldn't work either.
Any ideas would be appreciated. Any hints on how to debug this sort of js error as well would be nice for the future.
Current Code:

    <link href="/static/css/bootstrap.min.css" rel="stylesheet" media="screen">
    <link href="/static/css/bootstrap-datetimepicker.min.css" rel="stylesheet" type="text/css">

End of body..

$( document ).ready(function() {
    $('#startDate').datetimepicker();
});

Lastly, the html:

Start

A: Please have a look at this fiddle:
BS Datetimepicker
$('.datepicker').datetimepicker({
format: 'DD-MM-YYYY HH:mm:ss'
});

A: For custom format, just use data-date-format in your input. For example:

    <input type='text' class="form-control" data-date-format="DD/MM/YYYY"/>

That is format in Latin-America, Day/Month/Year


text:
Q: c# asp.net object reference lost hello i m doing a very simple Asp.net application project
 namespace WebApplication1
 {
 public partial class WebUserControl1 : System.Web.UI.UserControl
 {
    market m = new market();

    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void button_clickSell(object sender, EventArgs e)
    {

        float price = float.Parse(this.BoxIdPrezzo.Text);

        m.insertProd("xxx", 10, "yyy");
        m.addOfferForProd("ooo", 5, "gggg");
        m.insertProd(this.BoxIdDescrizione.Text,price,this.BoxIdUtente.Text);
        String s;
        m.outMarket(out s);
        this.Output.Text = s;  //the output here work good
        this.Output.Visible = true;

    }
    protected void button_clickView(object sender, EventArgs e)
    {
        String s;
        m.outMarket(out s);
        this.Output.Text = s;  // here seem to have lost the reference to product why?
        this.Output.Visible = true;
    }
}
}

the problem is that when i click on button1 which call button_clickSell everything works good but when i click on button2 which call button_clickView products seem to not be anymore in the Market object, but this is pretty strange because in market object i have a list of product  and  m.outMarket in the first time work propely.

A: That is because of how pages work. Every time you make a request or a post-back to the page the values will be lost in that variable.
You will need to hold that in a session or something similar.
Here is a very basic example of using a session.
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["Collection"] == null)
        {
            Session["Collection"] = new List<int>();
        }//if
    }
    protected void button_clickSell(object sender, EventArgs e)
    {
        List<int> collection = (List<int>)Session["Collection"];
        collection.Add(7);
        collection.Add(9);
    }
    protected void button_clickView(object sender, EventArgs e)
    {
        List<int> collection = (List<int>)Session["Collection"];
        collection.Add(10);
    }

A: you can view this post on MSDN: ASP.NET Session State Overview

A:
Session should be used when information is required across the
  pages. Now the matter for the two buttons lying on the same page. So
  ViewState is Best option.

protected void Page_Load(object sender, EventArgs e)
{
     if (ViewState["Collection"] == null)
     {
            ViewState["Collection"] = new List<int>();
     }//if
}
protected void button_clickSell(object sender, EventArgs e)
{
     List<int> collection = (List<int>)ViewState["Collection"];
     collection.Add(7);
     collection.Add(9);
}
protected void button_clickView(object sender, EventArgs e)
{
     List<int> collection = (List<int>)ViewState["Collection"];
     collection.Add(10);
}


text:
Q: Left join on two tables with different conditions on part of table data I want to join two tables using left join. I want to put one condition one part  of the data and another condition on rest of the data. It's confusing , let me explain with an example:
Table  - a
 Date        ID    name
2015-04-30  Y235J   P54
2015-04-30  Y237F   P54
2015-04-30  Y234A   P54
2015-04-30  Y235    P54
2015-04-30  Y239    P54
2015-04-30  Y297    P54
2015-04-30  L234    P54
2015-04-30  L236    P54
2015-04-30  M234    P54
2015-04-30  M237    P54
2015-04-30  M239    P54
2015-04-30  M238    P54
2015-05-31
2015-06-30
2015-07-31
2015-08-31
2015-09-30
2015-10-31

Table -b

Date1        ID1
2015-04-30  Y235
2015-04-30  Y239
2015-04-30  L234
2015-04-30  M237
2015-04-30  M239
2015-05-31  B435
2015-05-31  B486
2015-06-30  B435
2015-06-30  B486
2015-06-30  B477
2015-07-31  G456
2015-07-31  G345
2015-07-31  B486
2015-07-31  B477

I want to do left join table a with table b. I want to put conditions that table a left joins with table b based on Date and ID if Date1 <= '2015-04-30' and based on just Date if Date1 > '2015-04-30'
Can you please tell how to deal with this situation
    Select * from a left joins b (If b.Date1 <= '2015-04-30' then on
a.Date = b.Date1 and a.ID = b.ID else on a.Date = b.Date1)

I am not able to get answer for it.
Thanks,

A: You can express this condition as:
Select *
from a left join
     b
     on a.Date = b.Date1 and
        (b.Date1 > '2015-04-30' or  and a.ID = b.ID)

A: select *
from a
left join b
on a.ID = b.ID
and a.Date = b.Date1
where b.Date1 > '2015-04-30';


text:
Q: How to remove the last N rows on a dataset based on ID in R? How do I go from a dataframe like this:

ID
X
Y

1
4
6

1
6
5

1
8
4

1
9
6

2
6
4

2
7
5

2
3
9

to this:

ID
X
Y

1
4
6

1
6
5

2
6
4

In this example, I wanted to remove the last 2 rows for every ID.

A: You can use the following solution:
library(dplyr)

df %>%
  group_by(ID) %>%
  filter(between(row_number(), 1, n()-2))

# A tibble: 3 x 3
# Groups:   ID [2]
     ID     X     Y
  <int> <int> <int>
1     1     4     6
2     1     6     5
3     2     6     4

Or this one:
df %>%
  group_by(ID) %>%
  slice(1:(n()-2))

# A tibble: 3 x 3
# Groups:   ID [2]
     ID     X     Y
  <int> <int> <int>
1     1     4     6
2     1     6     5
3     2     6     4

A: An option with head used within slice
library(dplyr)
df %>%
   group_by(ID) %>%
   slice(head(row_number(), -2)) %>%
   ungroup

-output
# A tibble: 3 x 3
     ID     X     Y
  <int> <int> <int>
1     1     4     6
2     1     6     5
3     2     6     4

data
df <- structure(list(ID = c(1L, 1L, 1L, 1L, 2L, 2L, 2L), X = c(4L,
6L, 8L, 9L, 6L, 7L, 3L), Y = c(6L, 5L, 4L, 6L, 4L, 5L, 9L)),
  class = "data.frame", row.names = c(NA,
-7L))

A: You can use:
library(dplyr)
 df %>%
  group_by(ID) %>%
  filter(row_number() <= n()-2)

Output:
     ID     X     Y
  <int> <int> <int>
1     1     4     6
2     1     6     5
3     2     6     4


text:
Q: Spring Boot - Make inherited fields in the JSON response as last The following response object results in the very same order in JSON format:
public SpecificResponse {

    private int id;
    private int processId;
}

{ "id": 1, "processId": 1 }

When this object inherits from ProcessResponse having an extra field List<Message> messages, this field suddenly comes as first in the JSON response:
{
    "messages": [{
        "code": "CODE1",
        "Message": "Bla..."
    }, {
        "code": "CODE2",
        "Message": "Ble..."
    }],
    "id": 1,
    "processId": 1
}

I want to have messages field (and others) as last. There is a way to push messages to the end of the JSON using:
@JsonPropertyOrder({ "id", "processId", "messages"})

This solution becomes hell in case there are a lot of instance fields inherited. Is there another way explicitly specifying that the inherited fields come last for selected objects?


text:
Q: how to find overridable methods in eclipse public class test2 extends ListActivity {
}
eg:i want to find what are the methods in ListActivity that can be overridden ..what is the short key find this in eclipse.. how the method can be brought through eclipse intellisense that is suppose method  onListItemClick with certain parameters that can be overriden in listactivity ..how can it be brought through intellisense..or how can it be automatically generated through eclipse
eg:
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);

}

A: Source > Override/Implement methods
Accessible via right click, menu bar (alt+s), alt+shift+s
ykaganovich points out another way, which is faster for overriding a single members. Override/Implement allows multiple members to be overridden through a single action.

A: If you put the cursor between methods (where the new method declaration will go) and hit ctrl-space, you get a list of all the methods that you can override.


text:
Q: Arraylist prints the addres of the elements this code prints the address like this --> project.Cateogry@d038117
Cate=c.listCat();
Arrays.toString(Cate.toArray());

what is wrong ?!!!! i want to print the elements from the arraylist "Cate"

A: Let's check the javadoc of toArray,

Returns an array containing all of the elements in this list in proper
  sequence (from first to last element).
The returned array will be "safe" in that no references to it are
  maintained by this list. (In other words, this method must allocate a
  new array even if this list is backed by an array). The caller is thus
  free to modify the returned array.

As you can see, the return value of it is a java array, if you want to print the content inside the array, there are multiple ways in the thread mentioned in the comment.
Btw, if you're interested about why path@hashcode is printed, please refer to this thread How do I print my Java object without getting "SomeType@2f92e0f4"?


text:
Q: Can't trigger javascript function on checkbox click I have the following code, that dynamically creates checkboxes based on unique values in an array. The trigger function does not work and I have no idea why. I need to trigger another function based on which checkbox was selected.

function onlyUnique(value, index, self) {
  return self.indexOf(value) === index;
}

function filter_based_on_selection(selected_box_id) {
  console.log("Selected option : ");
  console.log(selected_box_id);
}

array2 = ['Z1', 'Z1', 'Z2', 'Z3', 'Z3', 'Z4', 'Z4', 'Z4', 'Z5', 'Z5', 'Z5', 'Z6', 'Z7', 'Z7'];

var unique_account_groups = array2.filter(onlyUnique);

console.log("Unique Account Groups found : ");

console.log(unique_account_groups);

for (var prop in unique_account_groups)
{
    jQuery("#filters").append('
<input class="list-group2-item" id= ' + unique_account_groups[prop] + 'onclick="filter_based_on_selection(this.id)" type="checkbox" value="">' + unique_account_groups[prop] + '
');
}

A: The main issue with your code is because you're missing a closing quote around the id attribute, which is resulting in it being merged with the onclick attribute and messing up your logic. To fix this you simply need to add the " in the correct place.
That being said, you should really not be using on* event attributes at all any more. They are outdated and not good for separation of concerns.
Instead, attach your event handlers unobtrusively. As you've already included jQuery in the page, you can do that like this:

var array2 = ['Z1', 'Z1', 'Z2', 'Z3', 'Z3', 'Z4', 'Z4', 'Z4', 'Z5', 'Z5', 'Z5', 'Z6', 'Z7', 'Z7'];

var html = array2.filter(function(v, i, a) {
  return a.indexOf(v) === i;
}).map(function(item) {
  return `<div class="checkbox"><label><input class="list-group2-item" id="${item}" type="checkbox" value="">${item}</label></div>`;
});

$('#filters').append(html).on('change', '.list-group2-item', function() {
  console.log('Selected option :', this.id);
});

There's a couple of things to note here. Firstly I am building the HTML string to be appended once. This increases performance as it only requires 1 DOM access instead of once per each element of the array. Also it uses a delegated event handler, so it doesn't matter when you add the new checkboxes, the same event will be applied to them. Lastly, it uses the change event instead of the click event, which is better for UX and has better support for your visitors who navigate the web using the keyboard.

A: You have a wrong concatenation here:
'onclick="filter_based_o
^

Just adding a space and everthing works.

function onlyUnique(value, index, self) {
  return self.indexOf(value) === index;
}

function filter_based_on_selection(selected_box_id) {
  console.log("Selected option : ");
  console.log(selected_box_id);
}

array2 = ['Z1', 'Z1', 'Z2', 'Z3', 'Z3', 'Z4', 'Z4', 'Z4', 'Z5', 'Z5', 'Z5', 'Z6', 'Z7', 'Z7'];

var unique_account_groups = array2.filter(onlyUnique);

console.log("Unique Account Groups found : ");

console.log(unique_account_groups);

for (var prop in unique_account_groups)
{
    jQuery("#filters").append('
<input class="list-group2-item" id= ' + unique_account_groups[prop] + ' onclick="filter_based_on_selection(this.id)" type="checkbox" value="">' + unique_account_groups[prop] + '
');
}

A: You just missed quotes around id, and one space before onclick.
Working example:

function onlyUnique(value, index, self) {
  return self.indexOf(value) === index;
}

function filter_based_on_selection(selected_box_id) {
  console.log("Selected option : ");
  console.log(selected_box_id);
}

array2 = ['Z1', 'Z1', 'Z2', 'Z3', 'Z3', 'Z4', 'Z4', 'Z4', 'Z5', 'Z5', 'Z5', 'Z6', 'Z7', 'Z7'];

var unique_account_groups = array2.filter(onlyUnique);

console.log("Unique Account Groups found : ");

console.log(unique_account_groups);

for (var prop in unique_account_groups)
{
    jQuery("#filters").append('
<input class="list-group2-item" id=" ' + unique_account_groups[prop] + '" onclick="filter_based_on_selection(this.id)" type="checkbox" value="">' + unique_account_groups[prop] + '
');
}

A: There was a mistake in a concatenation and a forgotten space,
I managed to make it work as below by changing a minimum of things :

function onlyUnique(value, index, self) {
  return self.indexOf(value) === index;
}

function filter_based_on_selection(selected_box_id) {
  console.log("Selected option :", selected_box_id);
}

array2 = ['Z1', 'Z1', 'Z2', 'Z3', 'Z3', 'Z4', 'Z4', 'Z4', 'Z5', 'Z5', 'Z5', 'Z6', 'Z7', 'Z7'];

var unique_account_groups = array2.filter(onlyUnique);
//console.log("Unique Account Groups found : ", unique_account_groups);

for (var prop in unique_account_groups){
    jQuery("#filters").append('
<input class="list-group2-item" id="' + unique_account_groups[prop] + '" onchange="filter_based_on_selection(this.id);" type="checkbox" value="">' + unique_account_groups[prop] + '
');
}


text:
Q: Creating CfnCertificate using typescript for AWS IoT core, ERROR : "Invalid request provided" Error :
Failed resources:
IotCoreStack | 1:46:26 a.m. | CREATE_FAILED        | AWS::IoT::Certificate | MyCfnCertificate1 Resource handler returned message: "Invalid request provided: For certificate mode Default, one of the following combinations must be specified exactly: [CertificatePem and CACertificatePem] OR [CertificateSigningRequest]" (RequestToken: dc01e655-f0ba-5593-8983-f16973de7236, HandlerErrorCode: InvalidRequest)

 ❌  IotCoreStack failed: Error: The stack named IotCoreStack failed to deploy: UPDATE_ROLLBACK_COMPLETE: Resource handler returned message: "Invalid request provided: For certificate mode Default, one of the following combinations must be specified exactly: [CertificatePem and CACertificatePem] OR [CertificateSigningRequest]" (RequestToken: dc01e655-f0ba-5593-8983-f16973de7236, HandlerErrorCode: InvalidRequest)
    at prepareAndExecuteChangeSet (C:\Users\makad\AppData\Roaming\npm\node_modules\aws-cdk\lib\api\deploy-stack.ts:386:13)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at CdkToolkit.deploy (C:\Users\makad\AppData\Roaming\npm\node_modules\aws-cdk\lib\cdk-toolkit.ts:219:24)
    at initCommandLine (C:\Users\makad\AppData\Roaming\npm\node_modules\aws-cdk\lib\cli.ts:347:12)

The stack named IotCoreStack failed to deploy: UPDATE_ROLLBACK_COMPLETE: Resource handler returned message: "Invalid request provided: For certificate mode Default, one of the following combinations must be specified exactly: [CertificatePem and CACertificatePem] OR [CertificateSigningRequest]" (RequestToken: dc01e655-f0ba-5593-8983-f16973de7236, HandlerErrorCode: InvalidRequest)

Code :

export class IotCoreStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const cfnCertificate = new iot.CfnCertificate(this, 'MyCfnCertificate1', {
      status: 'ACTIVE',
    });

  }
}

IotCoreStack | 1/5 | 1:46:26 a.m. | CREATE_FAILED        | AWS::IoT::Certificate | MyCfnCertificate1 Resource handler returned message: "Invalid request provided: For certificate mode Default, one of the following combinations must be specified exactly: [CertificatePem and CACertificatePem] OR [CertificateSigningRequest]" (RequestToken: dc01e655-f0ba-5593-8983-f16973de7236, HandlerErrorCode: InvalidRequest)
// the properties below are optional
  caCertificatePem: 'caCertificatePem',
  certificateMode: 'certificateMode',
  certificatePem: 'certificatePem',
  certificateSigningRequest: 'certificateSigningRequest',

What type of value we can put here for sample certificate creation in AWS IoT core?

A: As your error says, you need to specify your certificate in one of chosen way, it could not be created out of nowhere. In fact, it's missing in CDK docs, but there are described ways how to specify such certificate:
Certificate resources
You can specify certificates in one of the following ways:

A certificate signing request (CSR).

A certificate ID of an existing device certificate. (Only certificate IDs can be used with a fleet provisioning template.)

A device certificate created with a CA certificate registered with AWS IoT. If you have more than one CA certificate registered with the same subject field, you must also pass in the CA certificate used to sign the device certificate.

source: https://docs.aws.amazon.com/iot/latest/developerguide/provision-template.html


text:
Q: Attaching Entity Capabilities to Packet in Smack I can't for the life of me see how to attach an Entity Capabilities extension to a Smack Packet.  In my case, I have the data ready to go, I just need to place it in the Packet class.
Am I missing something from the API?  Can I add the <c/> element to a smack Packet?

A: There is an patch that adds Entity Capabilities support. The integration in Smack is tracked as SMACK-361 and the patch can be found in the forum post.
The patch is included in my smack fork (which get's used by aSmack). The <c/> element gets added in ServiceDiscoveryManager.java:258, with help of the CapsExtension. I am still working on the Entity Caps support in Smack in the caps branch and hope to get it committed some time in the future. You can view the current patch with git by using git diff upstream caps, after you have cloned the repository. If you have any suggestions, feel free to contact me.

A: Smack appears not to support this feature out of the box. You'll have to implement it yourself. Define a class that implements PacketExtension, create a new instance of this at the time of sending your presence and attach it using addExtension.


text:
Q: Organize objects using un-instantiated classes as namespaces? I've built a module to hold all of the common selenium expected_conditions which are then referenced throughout various tests. (The selenium portion of this example is not important, just the fact that I have a 'catalog' of a few thousand items.)
# ec module
class EcHR(object):
    class sidemenu(object):
        hrfile: Clickable      = Clickable((By.ID, "sidemenu_HRFile"),       f"HR File")
        hrvistainfo: Clickable = Clickable((By.ID, "sidemenu_HRVistA Info"), f"HR VistA Info")
    class hrfile(__hr_search__):
        class actionmenu(__hr_search__.actionmenu):
            add: Clickable       = Clickable((By.ID, "NewHireLink"), f"Add {BUTTON}")
            personnel: Clickable = Clickable((By.ID, 'setEmpType'), f"Personnel Filter {DROPDOWN}")
            status: Clickable    = Clickable((By.ID, 'setStatus'), f"Status {DROPDOWN}")
            configure: Clickable = Clickable((By.ID, "configureLinkGen"), f"Configure {BUTTON}")
            reports: Clickable   = Clickable((By.ID, 'Reports'), f"Reports {BUTTON}")
            class addmenu(object):
                employee: Clickable = Clickable((By.ID, f'Employee'), f"Add->Employee {BUTTON}")

Sample reference to a given item in the ec module.
import ec

    # navigation helper method for a given page
    def do_hrfile_nav(self):
        self.clickbutton(ec.EcHR.sidemenu.hrfile)

This works great; I can trace the usage of each object while still providing readability context for what the object is.
self.clickbutton(ec.EcHR.sidemenu.hrfile) tells the reader we are clicking on the sidemenu item hrfile on the HR page.  This is important to distinguish from the ec.EcHR.hrfile which is a different set of objects.
My question: Is there a better/cleaner way to organize these objects?  I'm using classes that never get instantiated. (which somehow feels awkward for reasons I can't articulate) These classes act solely as a means to reference them in an organized way.  Perhaps some sort of lightweight data object that has class-like structure?  (am I over thinking things?)

A: I've got some ideas.
It may be useful.
How about using functions as namespaces?
@namespace
def EcHR():
    @namespace
    def sidemenu():
        hrfile: Clickable = Clickable((By.ID, "sidemenu_HRFile"), f"HR File")
        return locals()

    @namespace
    def hrfile():
        @namespace
        def actionmenu():
            add: Clickable = Clickable((By.ID, "NewHireLink"), "Add {BUTTON}")

            @namespace
            def addmenu():
                employee: Clickable = Clickable(
                    (By.ID, f"Employee"), "Add->Employee {BUTTON}"
                )
                return locals()

            return locals()

        return locals()

    return locals()

I've changed every class to a function. And every function must be decorated with namespace decorator and must return locals() or any dict with custom key, val mapping.
Here's NameSpace class and namespace decorator.
from functools import reduce

class NameSpace:
    def __init__(self, name):
        self.__name__ = name

    def __str__(self):
        return "{}".format(self.__name__)

    def __repr__(self):
        return "NameSpace({})".format(self.__name__)

    def __call__(self):
        pass

def namespace(func):
    return reduce(
        lambda ns, kv: setattr(ns, kv[0], kv[1]) or ns,
        func().items(),
        NameSpace(func.__name__),
    )

The namespace decorator runs the decorated function and transforms the returned dict into a NameSpace instance.
How to access objects?
print(EcHR.sidemenu.hrfile)
print(EcHR.hrfile.actionmenu.addmenu.employee)


text:
Q: Closing connection to browser early and returning respond status I am implementing a custom IHttpModule in a project, which filter file uploading and provide upload status.
I want the custom module to close the connection early (don't want to receive all the data the other side send, which is allowed to be big, save the incoming bandwidth).
Is it a possibility using HTTP protocol?
I tried sending "ContentLength: 0" and "Connection: close" header, flush the response, close the connection (HttpWorkerRequest.CloseConnection).
workerRequest.SendStatus(400, "Bad request");
workerRequest.SendKnownResponseHeader(HttpWorkerRequest.HeaderContentLength, "0");
workerRequest.SendKnownResponseHeader(HttpWorkerRequest.HeaderConnection, "close");
workerRequest.FlushResponse(false);
workerRequest.CloseConnection();
((HttpApplication)sender).CompleteRequest();

The browser/firefox response is displaying the "Connection reset" error message.
Without any sign of receiving any data/header/status from the server.
Thanks in advance.

A: An http client expects response only after it has completed sending the data. You should modify the client to make multiple requests of small sizes so a response can be sent to it instead of having server close the connection (which will not work and isn't working as you've tested already).
Check the http handler implemented in http://slfileupload.codeplex.com/ for a sample of how it is typically done.


text:
Q: Converting OOP PHP to Angular: Class Inheritance As I continue to learn how to build my sites in Angular, one issue I'm having a lot of trouble with is how to get a view to behave a certain way based on the controller.
I have a site for playing pen-and-paper RPGs via play-by-post. In PHP, I have a "character" class, which has some top level functions for display. I have other classes that extend from that class, based on the type of game, and sometimes classes extending from those.
One example is that the vast majority of RPGs have stats. In a D20 based game, they tend to be a common set of six. In Savage World games they're different. On my display, with PHP, I have a function called "displayStats", and what it actually does/shows is different based on what child class calls it. In Angular, I can only think of doing this by having a bunch of different directives with different names, like <stats-d20> or <stats-savage-worlds>, but its messy.
So, like a class, can I have a directive <stats> that'll call something different based on different settings, other than putting in a bunch of if statements in the link function? A friend mentioned that you can assign a controller to a directive, but I haven't quite figured out how that'd help?
In general, I'm not seeing how to setup Angular code in a situation like this. I'm not seeing how to use the techniques/methods I learned through OOP here (and I'm guessing they're not directly useful), and its kinda annoying. Here I have this really great working OOP code to display stuff, and I'm struggling to think of how to do it without creating <really-complex-directive-names>. Or is that what I have to do? Use non-pretty names, harkening back to the days of multi-part variable names to categorize?


text:
Q: Find probability that the sum of two different numbers on dice will be 8 Two dice are rolled and someone indicates that the two numbers that come up are different. Find the probability that the sum of the two numbers is $8$.
$(2,6)$, $(3,5)$, $(5,3)$, $(6,2)$.
Above are the sums that give $8$. I did not include $(4,4)$ since the question indicated that the number on die must be different from each other. I assume the probability would be $\frac{4}{36}$ since each probability is $\frac{1}{36}$. But my online exercise does not accept this answer. What am I missing?

A: If you know that both numbers are different, then you have less cases than 36. Actually, you have to eliminate the possibilities $(1,1), (2,2), ..., (6,6)$. So the answer will be $\frac4{30}=\frac2{15}$.


text:
Q: PSQL PG_DUMP with su - postgres I'm trying to write a bash script that would allow me to:
1) Login into ssh root account
2) If logged then log in as postgres
3) If logged as postgres then pg_dumb of my db to my local db
My code looks:
ssh root@myhost

user = `root`

if [ "$user" == "root" ]; then
  su - postgres
fi

user = `postgres`

if [ "$user" == "postgres" ]; then
  pg_dump my_user_name my_db | psql my_db2
fi

Before running my script I've created locally a new user my_db with --owner my_db2, so there shouldn't be problems with copying the dump to my local db.
But the problem is that when I run this script all I get is just login to ssh root and nothing more happens. Just getting /root
No next procedure.
Anyone would help with this ? Thanks...

A: You can directly fire command as a postgres user from root prompt. See below:
su - postgres -c 'pg_dump source-db | psql target-db'

A: Try this:
user="root"

if [ "$user" == "root" ]; then
su - postgres
fi


text:
Q: how to force symfony to create service instance eagerly instead of creating when it is access first time (lazily)? Below is my service definition
    <service id="st_mongo.mongo_config" class="St\Common\MongoBundle\Mongo\StMongoConfig"
             factory-class="St\Common\MongoBundle\Mongo\StMongoConfig"
             factory-method="factory" public="false">
        <argument>%mongo_dsn%</argument>
        <argument>%mongo_db_collection_map%</argument>
    </service>

Symfony creates instance of this service (it calls factory-method "factory") when the service is accessed first time by using
$continer->get("st_mongo.mongo_config");

I want, service instance should be created when symfony is bootstraped. I shouldnt need to call above service manually.
Is there any way to forcefully tell symfony to create service instance eagerly at the time of boostraping instead of creating lazily when called first time ?
May be I can use kernel events but there are no events common to http and console.
Update:
I could make it work using http://symfony.com/doc/current/components/dependency_injection/compilation.html#execute-code-during-compilation -- but not sure how reliable is it. -- This didn't work as it won't be called once cache is created.


text:
Q: Convert a  project/module into a  project/module For a project created by Intellij IDEA, how to convert a type of project/module to another type ?
for example :
java to maven
java to groovy
maven to java
......
tank you

A: There is no automated way to convert Java to Groovy and IntelliJ IDEA native project to Maven or Gradle build system project.
Related requests:

*

*IDEABKL-6990 Export IDEA project configuration to external build system (Maven, Gradle)

*IDEA-50321 Convert Java to Groovy code


text:
Q: How to change the order of how $DISPLAY is allocated? Setup:  I have two X screens (i.e. DISPLAY=:0.0 and DISPLAY=:0.1 on the separate screens), running from different Nvidia graphics cards in a Ubuntu 10.04.
Q: I'd like to know how $DISPLAY is set for each of these screens.
Reason (perhaps there's a better way to achieve the same result): One of the monitors often turned off, this is DISPLAY=:0.0.  Popups (Authentication, info, volume control, etc.) from gnome always appear on this screen and I would like them to appear on the other one (DISPLAY=:0.1).  I figure if I can change the order that DISPLAY is set for each then gnome will put the popups on my favoured screen....or perhaps there is a gnome level solution?
Happy to provide more info, or to clarify my question.


text:
Q: Javascript match two url variables I have a code that generates text depending on variables in the url. What I want to know is if there a method to get two variables that are located separately from each other in the same string of the url at the same time to show my text.
Say this is my string ?q1=iphone3gs&q2=Other&q3=fixme. The url must contain iphone and other in order for the text to show.
iphone and other must be selected to show text http://jsfiddle.net/2tXvh/6/show/?q1=iphone3gs&q2=Other&q3=fixme (this is only calling on q2=Other)
I was think along the lines of using (/iphone&Other/) shown below but that will not work.
if (keys[1].match(/iphone&Other/)) {
    $("#linkdiv1").append(nextLink1);
}

A: That's not how regex works. If you want to match 2 things together, you're going to have to either use 2 regexes (if you want to make sure it's in seperate order), or specify what is allowed to be in between the 2 matched strings. In this case, you'll probably need 2 seperate matches:
if (keys[1].match('iphone') && keys[1].match('Other')) {
    $("#linkdiv1").append(nextLink1);
}

Or, since you're simply searching for the occurrence of a string, you don't need to use a regex, or .match() for that matter:
if (keys[1].indexOf('iphone') !== -1 && keys[1].indexOf('Other') !== -1) {
    $("#linkdiv1").append(nextLink1);
}


text:
Q: Logical error BST ... wrong results HI i did this code with help of Marc Gravell in
Why can't I find _left and _right in BinarySearchTree?
&
How do I correct an implicit conversion error in BST C# Code?
, its Binary search tree , but now I'm having logical error the results coming are wrong the output of my code is the following:
2
3
5
6
10
17
------------------------------------------------
17
2
------------------------------------------------
3
6
Press any key to continue . . .

the last two number must give the total of inserted elements 6 but its showing 9
and but the way How can i get the height of the tree ?!

using System;
using System.Collections.Generic;
using System.Text;

namespace errors
{
    class Program
    {
        static void Main(string[] args)
        {
            BinarySearchTree t = new BinarySearchTree();

            t.insert(ref t.root, 10);
            t.insert(ref t.root, 5);
            t.insert(ref t.root, 6);
            t.insert(ref t.root, 17);
            t.insert(ref t.root, 2);
            t.insert(ref t.root, 3);

            BinarySearchTree.print(t.root);

            Console.WriteLine("------------------------------------------------");
            Console.WriteLine(t.FindMax());
            Console.WriteLine(t.FindMin());
            Console.WriteLine("------------------------------------------------");

            Console.WriteLine(t.CountLeaves(t.root));
            Console.WriteLine(t.CountNodes(t.root));

        }

        public class TreeNode
        {
            public int n;
            public TreeNode _left;
            public TreeNode _right;

            public TreeNode(int n, TreeNode _left, TreeNode _right)
            {
                this.n = n;
                this._left = _left;
                this._right = _right;
            }

            public void DisplayNode()
            {
                Console.Write(n);
            }

        }

        public class BinarySearchTree
        {
            public TreeNode root;

            public BinarySearchTree()
            {
                root = null;
            }

            public void insert(ref TreeNode root, int x)
            {
                if (root == null)
                {
                    root = new TreeNode(x, null, null);
                }
                else
                    if (x < root.n)
                        insert(ref root._left, x);
                    else
                        insert(ref root._right, x);
            }

            public int FindMin()
            {
                TreeNode current = root;

                while (current._left != null)
                    current = current._left;

                return current.n;
            }

            public int FindMax()
            {
                TreeNode current = root;

                while (current._right != null)
                    current = current._right;

                return current.n;
            }

            public TreeNode Find(int key)
            {
                TreeNode current = root;

                while (current.n != key)
                {
                    if (key < current.n)
                        current = current._left;
                    else
                        current = current._right;
                    if (current == null)
                        return null;
                }
                return current;
            }

            public void InOrder(ref TreeNode root)
            {
                if (root != null)
                {
                    InOrder(ref root._left);
                    root.DisplayNode();
                    InOrder(ref root._right);
                }
            }

            public int CountNodes(TreeNode root)
            {
                int count=1;
                if (root._left != null)
                    count += CountNodes(root._left);
                if (root._right != null)
                    count += CountNodes(root._right);
                return count;
            }

            public int CountLeaves(TreeNode root)
            {
                int count = (root._left == null && root._right == null) ? 1 : 0;
                if (root._left != null)
                    count += CountLeaves(root._left);
                if (root._right != null)
                    count += CountLeaves(root._right);
                return count;
            }

            public static void print(TreeNode root)
            {
                if (root != null)
                {
                    print(root._left);
                    Console.WriteLine(root.n.ToString());
                    print(root._right);
                }

            }

        }

    }
}

Thanx in advance and special thanx to Marc Gravell .

A: If what you mean in CountNodes is to count all non-leaf nodes you must change this line:
int count=1;

to read this:
int count = (root._left == null && root._right == null) ? 0 : 1;

(the opposite of what is in CountLeaves).
And this will get you the height of the tree:
public int Height(TreeNode root)
{
    int height = 1;
    if (root._left != null)
        height = Math.Max(height, Height(root._left));
    if (root._right != null)
        height = Math.Max(height, Height(root._right));
    return height;
}

A: Regarding getting the tree height, use the following recursive pseudo-code, calling nodeHeight(root):
nodeHeight(node)
    left=0
    right=0

    if (node == null) return 0

    left = 1 + nodeHeight(getLeft(node))
    right = 1 + nodeHeight(getRight(node))

    return max(left,right)

A: It doesn't appear that you balance your tree, so you just get a simple linked list, that may account for your incorrect values.  A properly balanced tree will have a maximum height of log2(n).


text:
Q: Pandoc - source code with internal references I use Pandoc to create pdf and docx documents that have to include grammar for certain language. Since grammar frequently changes I created short shell script that preprocesses grammar file and includes it in md file. This works fine, but what I can't figure out is how to have it both be a source code (so that it starts and ends with tildes) and contain internal links. For example given:
machines_list ::= machines_list declmachine
declmachine   ::= structure_definition

I want source code linked in such a way that clicking at declmachine in machines_list definition will bring me to declmachine definition. Of course placing proper markers is outside of this question, I just can't figure out what these markers should be. I tried using internal links, but it seems that they only work with html, latex and context (whatever it is) and I was unable to make it work - maybe it is sever case of PEBKAC.
If it matters (and I suppose it does) I generate pdfs and docx using:
@pandoc -f markdown -t latex -F pandoc-fignos -F pandoc-eqnos --listings -o $@ $< --citeproc --toc
@pandoc -f markdown -t docx -F pandoc-fignos -F pandoc-eqnos --citeproc --listings -o $@ $< --toc

If it is possible, I'd like to do it using as few extensions as possible (ideally none at all). For various reasons I am currently forced to do it using the following:
$ pandoc --version
pandoc 2.11.3.2
Compiled with pandoc-types 1.22, texmath 0.12.1, skylighting 0.10.2,
citeproc 0.3.0.3, ipynb 0.1.0.1


text:
Q: Unable to start test using mocha following is the error i am facing while running mocha tests...
upquire@0.0.0 test D:\tecsol\mtv
mocha test/bootstrap.test.js test/unit/**/*.test.js

1) "before all" hook
  0 passing (3m)
  1 failing

1)  "before all" hook:
  Error: timeout of 50000ms exceeded. Ensure the done() callback is being called in this test.
  at null.<anonymous> (D:\tecsol\mtv\node_modules\mocha\lib\runnable.js:189:19)

The following is my bootstrap.test.js file:
var Sails = require('sails');
var sails;

before(function(done) {
  this.timeout(5000);
  Sails.lift({
    // configuration for testing purposes
  }, function(err, server) {
    sails = server;
    if (err) return done(err);
    // here you can load fixtures, etc.
    done(err, sails);
  });
});

after(function(done) {
  // here you can clear fixtures, etc.
  Sails.lower(done);
});


text:
Q: Access Kerberos protected REST service with CORS aproach I try to call cross domen REST service from Ajax.
To accomplish CORS i tried to put Access-Control-Allow-Origin header in service Aapache config.

  Header add Access-Control-Allow-Origin "*"
  Header add Access-Control-Allow-Methods "GET"
When i switch of Kerberos protection from resource all is fine
And response header from server allows CORS
Access-Control-Allow-Cred...    true
Access-Control-Allow-Meth...    GET
Access-Control-Allow-Orig...    my_host
Access-Control-Max-Age  1728000
Problem starts when tunring on Kerberos protection on resource. Browser thinks that cross domen access is not allowed.
Response header:
ConnectionKeep-Alive
Content-Encodinggzip
Content-Length343
Content-Typetext/html; charset=iso-8859-1DateMon, 15 Oct 2012 14:05:43 GMT
Keep-Alivetimeout=5, max=100ServerApache/2.2.14 (Ubuntu)VaryAccept-Encoding
WWW-AuthenticateNegotiate
Basic realm="Kerberos Login"
Does any way exist we could use CORS for cross domen request on Kerberos protected resources?


text:
Q: Override theme text color My problem
I set my custom theme and it works fine.
But I get black text color on orange( accent) button, but I want to have white color.
My solution
In @material/theme/_variables.scss we have code like this :
$mdc-theme-primary: #3f51b5 !default; /* Indigo 500 */
$mdc-theme-accent: #ff4081 !default; /* Pink A200 */
$mdc-theme-background: #fff !default; /* White */

/* Which set of text colors to use for each main theme color (light or dark) */
$mdc-theme-primary-tone: mdc-theme-light-or-dark($mdc-theme-primary);
$mdc-theme-accent-tone: mdc-theme-light-or-dark($mdc-theme-accent);
$mdc-theme-background-tone: mdc-theme-light-or-dark($mdc-theme-background);

From the above code, we can see first three params have !default which means use this as default , if they are already declared dont override.
For that reason we can specify the custom colors.
But for properties like $mdc-theme-accent-tone we are forced to use the calculated values.
If I change the above code (source code of MDC ) to
$mdc-theme-accent-tone: mdc-theme-light-or-dark($mdc-theme-accent) !default;

and in my styles
$mdc-theme-accent-tone : "light"

It works fine. But obviously I can not change the source code. How to achieve this.

A: I realized this is according to the material design spec. So, expecting a provision to override is wrong.
But for all practical reasons, to override them do this :
@import "@material/theme/mdc-theme";

:root {
    --mdc-theme-text-primary-on-accent: white;
}

Remember the override style should be written after importing mdc-theme


text:
Q: Need guidance in making efficient swipe views New to android and recently learned swipe views a bit. In my app, it has 17 chapters and in each chapter, there will be 30 pages containing some text data, a user can swipe through. I need to use FragmentStatePagerAdapter to save memory but I need to know that do I need to make 510 Fragment objects, means 510 XML layout? I just need to change the text in each page, and I've seen many using switch statement like this
@Override
public Fragment getItem(int position) {
    switch (position) {
        case 0:
            return  new FragmentOne();
        case 1:
            return  new FragmentTwo();
        default:
            break;
    }
    return null;
}

Do I/Should I write 30 cases in each chapter? or is there a better way to do this? I've Googled and seen lots of Youtube videos but couldn't find the solution. I request everyone that if you're answering or commenting, do explain your codes cause I believe in learning, not in copy pasting.

A: Using FragmentStatePagerAdapter is right approach here. It will manage the fragment states based on the viepager offscreenLimit() you set.
In your case, you can have just one fragment and an arrayList of your text and given different text based on position.
Something like this..
List<String> yourList = new ArrayList<>();

@Override
public Fragment getItem(int position) {
    return new YourFragment(yourList.get(position));
}

A: It's easy peasy man!
You need only one Fragment object, here's the code
public class FragmentChild extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

    // INFLATE THE LAYOUT THAT EACH FRAGMENT OBJECT WILL HAVE, PUT IT IN A VIEW
     View root = inflater.inflate(R.layout.couplets, container, false);

    // RECEIVE THE BUNDLE DATA SENT (ARGUMENTS)
    Bundle args = getArguments();

    // CREATE AN ARRAY LIST OF STRINGS THAT WILL HOLD TEXT
    ArrayList<String> someText = new ArrayList<>();
someText.add("one");
someText.add("two");
someText.add("three");
TextView txt = (TextView) root.findViewById(R.id.text_view);
    txt.setText(someText.get(args.getInt("position")));
return root;
}

custom pager adapter
class MyFragmentAdapter extends FragmentStatePagerAdapter {

 MyFragmentAdapter(FragmentManager fm) {super(fm);}

@Override
public Fragment getItem(int position) {
    Bundle args = new Bundle();
    args.putInt("position", position);

    Fragment fragment = new FragmentChild();
    fragment.setArguments(args);
    return fragment;
}

@Override
public int getCount() {
    return 3;
}
}

And finally host activity
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chapter_one);

    // FIND THE VIEWPAGER AND SET THE CUSTOM ADAPTER TO IT TO PROVIDE CHILD PAGES
        ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
        MyFragmentAdapter adapter = new MyFragmentAdapter(getSupportFragmentManager());
        viewPager.setAdapter(adapter);
    }
}


text:
Q: Как работать с циклами в node.js? (синхронно/асинхронно) Есть обработчик POST запросов на авторизацию, если ему поступает запрос, то он берет пришедший username ищет в базе данных mongoose, если находит, сверяет password и теперь вопрос:
Нужно из полученного из базы значения объекта user, в котором много полей (username, userid, password, email итд) получить только определенные, допустим username и userid можно ли это сделать через обычный цикл for in это же синхронное действие (с расчетом на большую нагруженность)
User.findOne({username: username}, function(err, user) {
    if (user) {
        if (user.checkPassword(password)) {
            // Ok auth
        }
    }
}

A: метод findOne вторым параметром позволяет задать поля, которые нужно вернуть:
User.findOne(
  {username: username},
  {"username": true, "userid": true},
  function(err, user) {
    if (user) {
      if (user.checkPassword(password)) {
          // Ok auth
      }
    }
  }
)

A:

let obj = {
 name: 'qwa',
 foo(_f) {
  _f.call(this)
 }
}
let ass = () => Promise.resolve('qwa')
obj.foo(async function () {
 // console.log(this);
 console.log(
  await ass()
 );//qwa
})
obj.foo(function () {
 // console.log(this);
 console.log(
  ass()
 );//Promise {<resolved>: "qwa"}
})


text:
Q: Can you call a function that has not been previously declared? Would this work?
class Example:
    def fun2(self):
        fun1()

    def fun1()
        print "fun1 has been called"

Notice that fun2—which is declared above fun1—is calling fun1. I'm interested in seeing what happens when functions are called in this order inside a class.
Are there any situations in which a function would not be aware of another function, even if the call to the function would be properly addressed?

A: At first the function call fun2 in the original code didn't work. It would throw the error message: NameError: global name fun1' is not defined. Is it because functions have to be declared before they are called?
No.It turns out that the exception was thrown because fun1 is outside the scope of fun2. Understanding how namespaces work will illuminate the exception as well as answer the posted question.
The namespace of any function is first its own function namespace and then the global namespace. It doesn't, by default, include the 'class' namespace. But, it does (and should) have access to the class namespace. To let a function know that a it is calling a function that lives in the same class, one must use the self keyword before the calling function.
This, then, works:
class Example:
   def fun2(self):
      self.fun1() # Notice the `self` keyword tells the interprter that
                  # we're looking for a function, `fun1`, that is relative to
                  # the same object (once a variable is declared as an Example
                  # object) where `fun2` lives.

   def fun1(self):
      print "fun1 has been called"

# fun1 has been called

Now fun1 is reference-able by fun2, because fun2 will now look at the class namespace. I tested that this is true by running:
class Example:
   def fun2(self):
      fun1()

   def fun1(self):
      print "fun1 was called"

def fun1():
    print "fun1 outside the class was called"

Without the self keyword the output is:
fun1 outside the class was called

So, to answer the question here, when python interprets a script it pre-compiles all the relevant namespaces. Therefore all functions are aware of all other functions that are appropriately addressed, rendering the original declaration order irrelevant.


text:
Q: Responsive Hamburger Menu via jQuery I am new to coding and am struggling to get the template for my nav menu ready. First of all, I want the hamburger to hide whenever I click on it and then the menu opens. However, I'm still at the beginning, and can't even get the hamburger to hide. I want to toggle the class ".hamburger-hide" using jQuery, which includes the display:none property.
this is the html:
    <!DOCTYPE html>

    <meta charset="utf-8">
    <link rel="stylesheet" href="css/styles.css">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@100&display=swap" rel="stylesheet">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@800&display=swap" rel="stylesheet">
    <title>Navbar</title>

Logo

Home

About

Contact Us

Links

    <button>Hello World</button>

this is my CSS:
*{                              /*Setting all to 0*/
  padding:0;
  margin:0;
  box-sizing: border-box;      /*If you set box-sizing: border-box; on an element, padding and border are included in the width and height*/
}

header {
  display: flex;              /* Das ist der Flex container (header) in ihm müssen items positioniert werden*/
  justify-content: space-between;    /*justify-content + align-itmes = center ==> perfect center*/
  align-items: center;
  background-color: #707070;
  padding: 30px 10%;
}

.logo {
  font-family: "Montserrat", sans-serif;
  font-weight: 800;
  cursor: pointer;
}

button {
  cursor: pointer;
  padding: 9px 25px;
  background-color: rgba(0, 136, 169, 1);    /* letzter ist alpha --> opacity, 1 = 100%*/
  border: none;
  border-radius: 50px;
  transition: all 0.3s ease 0s;
}

button:hover {
  background-color: rgba(0, 136, 169, 0.7);  /* alpha ändert sich beim hovern --> opacity nimmt ab, 0,7 = 70%*/
  text-decoration: none;
}

.btn a {
  text-decoration: none;
}

.nav-item {
  list-style: none;
}

.nav-item {
  display: inline-block;                    /* ul ist in reihe nicht untereinander. kann auch direkt an li gemacht werden*/
  padding: 0px 30px;
}

.navbar li a {
  transition: all 0.3s ease 0s;      /*letzter wert= delay, ease-in-out= vorwärts und rückwärts*/
}

.navbar li a:hover {
  color: #0088a9;
}

.nav-item a, button{
  text-decoration: none;
  color: #edf0f1;
  font-family: "Montserrat", sans-serif;
  font-size: 16px;
  font-weight: normal;
}

.hamburger {
  height:40px;
  cursor: pointer;
  position:relative;
}

.hamburger:hover {
  padding:2px;
  border: 2px solid;
  border-radius: 5px;
}

.hamburger-hide {
  display:none;
}

@media (max-width: 768px){
  .nav-list{
    display: none;
  }
  .cta {
    display: none;
  }

}

@media (min-width:769px){
  .hamburger{
    display:none;
  }
}

and this is the jQuery I tried, so that it hides on click.
        $(".hamburger").click(function(){
  $(".hamburger").toggleClass(".hamburger-hide");
})

A: Solution with jQuery for build up Hamburger navbar responsive
For my example:

(function($) { // Begin jQuery
  $(function() { // DOM ready
    // If a link has a dropdown, add sub menu toggle.
    $('nav ul li a:not(:only-child)').click(function(e) {
      $(this).siblings('.nav-dropdown').toggle();
      // Close one dropdown when selecting another
      $('.nav-dropdown').not($(this).siblings()).hide();
      e.stopPropagation();
    });
    // Clicking away from dropdown will remove the dropdown class
    $('html').click(function() {
      $('.nav-dropdown').hide();
    });
    // Toggle open and close nav styles on click
    $('#nav-toggle').click(function() {
      $('nav ul').slideToggle();
    });
    // Hamburger to X toggle
    $('#nav-toggle').on('click', function() {
      this.classList.toggle('active');
    });
  }); // end DOM ready
})(jQuery);
@charset "UTF-8";
body{
 margin:0;
}
.navigation {
  height: 70px;
  background: #6d7993;
  font-family: montserrat, sans-serif;
  font-weight: 400;
  font-style: normal;
  opacity: 0.88;
}

.brand {
  position: absolute;
  padding-left: 20px;
  float: left;
  line-height: 70px;
  text-transform: uppercase;
  font-size: 1.4em;
}
.brand a,
.brand a:visited {
  color: #ffffff;
  text-decoration: none;
}

.nav-container {
  max-width: 1000px;
  margin: 0 auto;
}

nav {
  float: right;
}
nav ul {
  list-style: none;
  margin: 0;
  padding: 0;
}
nav ul li {
  float: left;
  position: relative;
}
nav ul li a,
nav ul li a:visited {
  display: block;
  padding: 0 20px;
  line-height: 70px;
  background: #6d7993;
  color: #ffffff;
  text-decoration: none;
}
nav ul li a:hover,
nav ul li a:visited:hover {
  background: #4b5569;
  color: #ffffff;
}
nav ul li a:not(:only-child):after,
nav ul li a:visited:not(:only-child):after {
  padding-left: 4px;
  content: " ▾";
}
nav ul li ul li {
  min-width: 190px;
}
nav ul li ul li a {
  padding: 15px;
  line-height: 20px;
}

.nav-dropdown {
  position: absolute;
  display: none;
  z-index: 1;
  box-shadow: 0 3px 12px rgba(0, 0, 0, 0.15);
}

/* Mobile navigation */
.nav-mobile {
  display: none;
  position: absolute;
  top: 0;
  right: 0;
  background: #6d7993;
  height: 70px;
  width: 70px;
}

@media only screen and (max-width: 798px) {
  .nav-mobile {
    display: block;
  }

  nav {
    width: 100%;
    padding: 70px 0 15px;
  }
  nav ul {
    display: none;
  }
  nav ul li {
    float: none;
  }
  nav ul li a {
    padding: 15px;
    line-height: 20px;
  }
  nav ul li ul li a {
    padding-left: 30px;
  }

  .nav-dropdown {
    position: static;
  }
}
@media screen and (min-width: 799px) {
  .nav-list {
    display: block !important;
  }
}
#nav-toggle {
  position: absolute;
  left: 18px;
  top: 22px;
  cursor: pointer;
  padding: 10px 35px 16px 0px;
}
#nav-toggle span,
#nav-toggle span:before,
#nav-toggle span:after {
  cursor: pointer;
  border-radius: 1px;
  height: 5px;
  width: 35px;
  background: #ffffff;
  position: absolute;
  display: block;
  content: "";
  transition: all 300ms ease-in-out;
}
#nav-toggle span:before {
  top: -10px;
}
#nav-toggle span:after {
  bottom: -10px;
}
#nav-toggle.active span {
  background-color: transparent;
}
#nav-toggle.active span:before, #nav-toggle.active span:after {
  top: 0;
}
#nav-toggle.active span:before {
  transform: rotate(45deg);
}
#nav-toggle.active span:after {
  transform: rotate(-45deg);
}

article {
  max-width: 1000px;
  margin: 0 auto;
  padding: 10px;
}

      Logo

          Home

          Contact Us

          Link

Updated

Solution 2, Using Pure CSS

body {
  margin: 0;
  font-family: Helvetica, sans-serif;
  background-color: #f4f4f4;
}

a {
  color: #000;
}

/* header */

.header {
  background-color: #fff;
  box-shadow: 1px 1px 4px 0 rgba(0,0,0,.1);
  position: fixed;
  width: 100%;
  z-index: 3;
}

.header ul {
  margin: 0;
  padding: 0;
  list-style: none;
  overflow: hidden;
  background-color: #fff;
}

.header li a {
  display: block;
  padding: 20px 20px;
  border-right: 1px solid #f4f4f4;
  text-decoration: none;
}

.header li a:hover,
.header .menu-btn:hover {
  background-color: #f4f4f4;
}

.header .logo {
  display: block;
  float: left;
  font-size: 2em;
  padding: 10px 20px;
  text-decoration: none;
}

/* menu */

.header .menu {
  clear: both;
  max-height: 0;
  transition: max-height .2s ease-out;
}

/* menu icon */

.header .menu-icon {
  cursor: pointer;
  display: inline-block;
  float: right;
  padding: 28px 20px;
  position: relative;
  user-select: none;
}

.header .menu-icon .navicon {
  background: #333;
  display: block;
  height: 2px;
  position: relative;
  transition: background .2s ease-out;
  width: 18px;
}

.header .menu-icon .navicon:before,
.header .menu-icon .navicon:after {
  background: #333;
  content: '';
  display: block;
  height: 100%;
  position: absolute;
  transition: all .2s ease-out;
  width: 100%;
}

.header .menu-icon .navicon:before {
  top: 5px;
}

.header .menu-icon .navicon:after {
  top: -5px;
}

/* menu btn */

.header .menu-btn {
  display: none;
}

.header .menu-btn:checked ~ .menu {
  max-height: 240px;
}

.header .menu-btn:checked ~ .menu-icon .navicon {
  background: transparent;
}

.header .menu-btn:checked ~ .menu-icon .navicon:before {
  transform: rotate(-45deg);
}

.header .menu-btn:checked ~ .menu-icon .navicon:after {
  transform: rotate(45deg);
}

.header .menu-btn:checked ~ .menu-icon:not(.steps) .navicon:before,
.header .menu-btn:checked ~ .menu-icon:not(.steps) .navicon:after {
  top: 0;
}

/* 48em = 768px */

@media (min-width: 48em) {
  .header li {
    float: left;
  }
  .header li a {
    padding: 20px 30px;
  }
  .header .menu {
    clear: none;
    float: right;
    max-height: none;
  }
  .header .menu-icon {
    display: none;
  }
}

  Your Logo
  <input class="menu-btn" type="checkbox" id="menu-btn" />

Home

About

Blog

Contact Me

A: Here you go:
https://jsfiddle.net/ap2rzb5x/1/
$("#hamburger").click(function(){
  $("#hamburger").toggleClass("hamburger-hide");
  $("#hamburger").toggleClass("hamburger");
})

Summary you toggled just that one class, didn't want you maybe switch them (toggle the original hamburger class away?). Just in case I matched on the ID instead of the class so I could toggle away the original hamburger and still be able to match it with the same code.
Another problem is that you toggled '.hamburger-hide' that's not the class name, it's called 'hamburger-hide' the dot is only used by jQuery as the dollar search. Same with #hamburger, it will find ID of hamburger not #hamburger-hide.
https://api.jquery.com/category/selectors/
Probably it's not exactly doing what you want, but I think it should unstuck you and you should be able to continue making what you intend to do.


text:
Q: How to rename a Content Type associated to a List in SharePoint Online I know you can change a content type name for an existing list using PowerShell for SharePoint On-premises versions, but I don't see any documentation for SharePoint Online. Does anyone have a link to the documentation if it exists? If the documentation does not exist, is it possible to do it so via PowerShell or any other method for that matter?

A: I tend to use CSOM as I can run it torwards both on prem and online.
It's not PowerShell, but I think it can be easily converted.
Not sure why you would want to rename just the list content type; ideally I would rename it at the site collection level.
public void RenameListContentType(ClientContext context, string listTitle)
{
    List list = context.Web.Lists.GetByTitle(listTitle);
    ContentType ct = list.ContentTypes.GetById("0x010100F92FB91056B24E40ACCE93A804002EFF001822ADB6403249B6AC60D10F8970E85E0001D97A142CFB4CD1BB0876B3669E30D3007022460F2F2E6C4BB4682EE84C366DF3");
    context.Load(list);
    context.Load(ct);
    context.ExecuteQuery();

    ct.Name = "New ct name";
    ct.Update(false);

    context.ExecuteQuery();
}


text:
Q: Split tmux.conf into multiple files? I have a file of common tmux settings I share between computers (tmux.conf.common). I'd like to be able to source this file in my tmux.conf. A way to accomplish this in bash is to have the each computer's .bashrc source the common file. Is there a way to do something analogous in tmux?

A: The .tmux.conf format has the source-file directive which can be used the same way. Using source also works.
source-file /path/to/tmux.conf.common

A: A bit late but this is how I use it across my workstations and deployed servers in order to be able to share my general preferences and easily override them.
First I just moved my .tmux.conf to a tmux.common then sourced it in the now empty tmux.conf
then I distributed this basic tmux.conf tmux.common to all nodes.
Since the last line in the tmux.common is run '~/.tmux/plugins/tpm/tpm'
Any additional plugins need to be mentioned before the sourced file.
If needed this could easily be expanded to include more common files, for instance for making devel/test / acceptance/production systems have different colors or whatnot.
generic .tmux.conf
#
# Include commons settings, shared between systems, anything but plugin
# related stuff can come after, like overriding common bindings or settings.
# Plugin stuff needs to be specified before this!
#
source-file ~/nocloud/conf/tmux.common

workstation .tmux.conf
On my workstations I use a layout plugin, this helps to make me aware if the tmux session is local or remote, and if remote, I have to look closer at the hostname, to ensure I am doing whatever it is to the right one.
set -g @plugin "arcticicestudio/nord-tmux"

#
# Include commons settings, shared between systems, anything but plugin
# related stuff can come after, like overriding common bindings or settings.
# Plugin stuff needs to be specified before this!
#
source-file ~/Dropbox/SharedConfigs/multi-os-apps/tmux.common


text:
Q: Binding Magnific Popup plugin to a button (besides the gallery element itself) I successfully implemented my Magnific Popup plugin, binding it to the gallery element (a div containing a set of img elements wrapped up in a elements). But I also want the lightbox to appear when clicking on a separate "see gallery" button.
I can't see anywhere how to achieve that in the documentation. Is it even possible?

A: You can just trigger click event via JS, e.g.:
$('.popup-gallery').find('a').eq(0).trigger('click');

A: Basically, when the "see gallery" button is clicked you want to trigger the click event on the element that normally opens the popup, so that the popup will open. See this question for some good ways of doing this.


text:
Q: Setting up a load balancer using Apache 2.4 I'm trying to setup a load balancer with Apache 2.4 but I can't make it work.
Here's what I wrote in my http.conf file:
<Proxy balancer://pop>
    BalancerMember http://pop1.local/ loadfactor=1
    BalancerMember http://pop2.local/ loadfactor=1
    ProxySet lbmethod=byrequests
</Proxy>

And this is the list of loaded Apache modules:

core mod_so http_core event mod_authn_file mod_authn_core
  mod_authz_host mod_authz_groupfile mod_authz_user mod_authz_core
  mod_access_compat mod_auth_basic mod_watchdog mod_reqtimeout
  mod_filter mod_mime mod_log_config mod_env mod_headers mod_setenvif
  mod_version mod_proxy mod_proxy_connect mod_proxy_ftp mod_proxy_http
  mod_proxy_fcgi mod_proxy_scgi mod_proxy_wstunnel mod_proxy_ajp
  mod_proxy_balancer mod_proxy_express mod_slotmem_shm
  mod_lbmethod_byrequests mod_lbmethod_bytraffic mod_lbmethod_bybusyness
  mod_lbmethod_heartbeat mod_unixd mod_heartmonitor mod_status
  mod_autoindex mod_dir mod_alias mod_rewrite mod_php5

To test, I've setup three VMs, one for load balancer and two for back-end webservers. Using hosts file I introduced three domains in all of the machines:
192.168.0.100   pop.local
192.168.0.101   pop1.local
192.168.0.102   pop2.local

pop.local is my load balancer and other two are the back-ends. Having a info.php file created on each of the back-ends, I can load them entering http://pop1.local/info.php and http://pop2.local. But when I type http://pop.local, a 404 File not found error returns.
The Apache on pop.local loads normally as if there's no Proxy balancer is set. It can even serve its own local files without a problem.
What's the problem? Am I missing something?
[UPDATE]
Here's the contents of my log file:
error_log:
[Wed Oct 02 02:40:55.530051 2013] [lbmethod_heartbeat:notice] [pid 2179:tid 140142625933120] AH02282: No slotmem from mod_heartmonitor
[Wed Oct 02 02:40:55.541737 2013] [mpm_event:notice] [pid 2179:tid 140142625933120] AH00489: Apache/2.4.6 (Unix) PHP/5.5.1 configured -- resuming normal operations
[Wed Oct 02 02:40:55.541768 2013] [core:notice] [pid 2179:tid 140142625933120] AH00094: Command line: '/usr/local/apache2/bin/httpd'
[Wed Oct 02 02:42:04.170782 2013] [:error] [pid 2615:tid 140142199158528] [client 192.168.0.81:55732] script '/usr/local/apache2/htdocs/info.php' not found or unable to stat

A: Here's a complete balancer config that should work:
<Proxy balancer://pop>
    BalancerMember http://pop1.local/ loadfactor=1
    BalancerMember http://pop2.local/ loadfactor=1
    ProxySet lbmethod=byrequests
</Proxy>
ProxyPass / balancer://pop/

As stated in documentation, if the first part of ProxyPass ends with a / the second part also needs to end with the /:

If the first argument ends with a trailing /, the second argument
  should also end with a trailing / and vice versa. Otherwise the
  resulting requests to the backend may miss some needed slashes and do
  not deliver the expected results.

You also need to make sure that ProxyRequests is set to off.


text:
Q: Data from HTML Form to PHP i have my HTML file:
<form action="input_db.php" method="post">
Name: <input type="text" name="name">

E-mail: <input type="text" name="email">

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

and PHP file in the same directory:
Welcome <?php echo $_GET["name"]; ?>

Your email address is: <?php echo $_GET["email"]; ?>

Both running on a "UniServer Zero XIII" on my local windwos maschine
the problem is that the echo just not work
https://www.w3schools.com/php/php_forms.asp
its this example from w3schools

A: You sending the data in form with the "POST" method and you trying to get it with $_GET variable;
you can edit the form method to "get" :
<form action="input_db.php" method="get">

Or try to get the data with the $_POST["name"] variable

A: You set the method to POST in the form.
So you need to use POST["name"] instead of GET["name"] in your PHP


text:
Q: Swipe between fragments with help of BottomNavigationBar I have trouble finding a good example on how to swipe between fragments with help of bottom navigatiom bar. Since FragmentStatePagerAdapter is deprecated and a new ViewPager2 is now recommended instead of the old ViewPager I want to use ViewPager2 and FragmentStateAdapter in my code instead. I have found an example of how to combine BottomNavigationBar and ViewPager here and I want to do something similar. My code have many similarities to the one in the example with the only difference that I have my code in a fragment instead of an activity. Here is a picture of how my FrontendFragment display look like. I can switch between the views using the bottomnavigationbar but I also want to be able to swipe between the views. Can someone help me or at least direct me on the right way? Here is my code:
FragmentPagerAdapter Class:
public class FragmentPagerAdapter extends FragmentStateAdapter {

    private static final int mFragmentCount = 5;

    public FragmentPagerAdapter(@NonNull Fragment fragment) {
        super(fragment);
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        switch (position){

            case 0:
                return new HomeFragment();
            case 1:
                return new SearchFragment();
            case 2:
                return new AddFragment();
            case 3:
                return new MessageFragment();
            case 4:
                return new ProfileFragment();
        }
        return null;
    }

    @Override
    public int getItemCount() {
        return mFragmentCount;
    }
}

FrontendFragment Class:
public class FrontendFragment extends Fragment implements BottomNavigationView.OnNavigationItemSelectedListener{

    private BottomNavigationView mBottomNavigationView;
    private ViewPager2 mViewPager2;
    private FragmentPagerAdapter mFragmentPagerAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v =  inflater.inflate(R.layout.fragment_frontend, container, false);

        loadFragment(new HomeFragment());

        mBottomNavigationView = v.findViewById(R.id.bottomNavigationBar);
        mBottomNavigationView.setOnNavigationItemSelectedListener(this);

        return v;
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {

        Fragment selectedFragment = null;

        switch (item.getItemId()) {
            case R.id.home_icon:
                selectedFragment = new HomeFragment();
                break;
            case R.id.search_icon:
                selectedFragment = new SearchFragment();
                break;
            case R.id.add_icon:
                selectedFragment = new AddFragment();
                break;

            case R.id.message_icon:
                selectedFragment = new MessageFragment();
                break;

            case R.id.profile_icon:
                selectedFragment = new ProfileFragment();
                break;
        }

        return loadFragment(selectedFragment);
    }

    private boolean loadFragment(Fragment selectedFragment) {

        if(selectedFragment != null){

            MainActivity.sFm.beginTransaction().replace(R.id.relLayoutMiddle, selectedFragment).commit();
            return true;
        }
        return false;
    }
}

Thanks in advance!

A: If you want to swipe between views, a simple solution would be to store all views in your parent view, but set all layouts for views except the initial view to android:visibility="gone". Make sure to set the initial view layout to android:visibility="visible" though. Now on you button clicks, you will have to implement onClick such that they turn on/ off view visibilities accordingly. For example, store views in order and control them via array index. But the whole thing you're trying to do is generally not a good design pattern in my opinion.
Why don't you load another Activity onClick instead of crowding your single activity? This will cause load time issues. Even if the views are non-visible, it's just an overall hassle to maintain all that in one place.

A: As I'm already using BottomNav with ViewPager2 in one of my app, I can help.
Your code is partially correct which means your FragmentPagerAdapter  is fine, but not your FrontEndFragment.
See, the FragmentPagerAdapter has to be set to a ViewPager2 as
//this here is the FrontEndFragment
mViewPager2.setAdapter(new FragmentPagerAdapter(this));

Then, You don't have to do the FragmentTransaction at all, you just have to change the ViewPager2's current item position through the BottomNavigationBar as
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {

    switch (item.getItemId()) {
        case R.id.home_icon:
            mViewPager2.setCurrentItem(0);
            break;
        case R.id.search_icon:
            mViewPager2.setCurrentItem(1);
            break;
        case R.id.add_icon:
            mViewPager2.setCurrentItem(2);
            break;

        case R.id.message_icon:
            mViewPager2.setCurrentItem(3);
            break;

        case R.id.profile_icon:
            mViewPager2.setCurrentItem(4);
            break;
    }

    return false;
}

This is all, you don't have to deal with Fragments at all apart from the FragmentPagerAdapter. Also, don't forget to remove the loadFragment(new HomeFragment()); which is not required, nor the function loadFragment() is required.
(Optional), Furthermore, if you want to disable the Swipe Action of the ViewPager2 and want the Fragments to be selected based on the Selected BottomNav item only, then you can set setUserInputEnabled() property of ViewPager2 as false.

Next, to set the BottomNavigationBar's item as selected based on the swipe of the ViewPager2, what you've to do is,
Create a global var
MenuItem previousMenuItem;

Then, set a default item (first) to be selected of BottomNav on activity start as
mBottomNavigationView.getMenu().getItem(0).setChecked(true);

Finally, set an OnPageSelected() callback on ViewPager2 to update the selected Menu Item as:
mViewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        super.onPageScrolled(position, positionOffset, positionOffsetPixels);
    }

    @Override
    public void onPageSelected(int position) {
        super.onPageSelected(position);
        if (previousMenuItem != null) {
            previousMenuItem.setChecked(false);
        }
        else {
            mBottomNavigationView.getMenu().getItem(0).setChecked(false);
        }
        mBottomNavigationView.getMenu().getItem(position).setChecked(true);
        previousMenuItem = mBottomNavigationView.getMenu().getItem(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        super.onPageScrollStateChanged(state);
    }
});

What you're doing here is that you're setting default item to previousMenuItem and then on swiping to a different page, deselecting the previousMenuItem and selecting the new one, which means updating the BottomNav based on ViewPager's current item. This is the complete code you require to acheive your objective.


text:
Q: Write your answers in rational form. Write down a polynomial $f(x)$ which has a root $\sqrt{5}$ I rewrite $\sqrt{5}$ in form of $\sqrt{4+1}$ which also can be $\sqrt{2^2+1}$. then I used formula $f(x)=f(a) +f'(a)(x-a)$ . I got $9/4 $.
 I think that not this is what exactly they asked as in the second part of the question, they tell that by using Newton's method, with $x_0=2$ to find  an approximation $x_1$ to $\sqrt{5}$.

A: Hint:
$$x=\sqrt{5}\implies x^2=5\implies x^2-5=0$$


text:
Q: jquery append and remove :removing order is not correct I am trying to implement a functionality that user can add and remove two text fields (ie heading, and description) using jquery, add more functionality is works fine but the removing order is not correct.
Hers is the  fiddle that shows the problem
Jquery
var append = '

 Day 1<input type="text" value="" name="subHeading" class="form-control">
';
append += '
 Description <textarea class="form-control" name="description"></textarea>';
append += '
<button type="button" class="btn btn-danger remove" id="btnAddMore">Remove</button>
';

$('#btnAddMore').click(function() {
  $('#appendContent:last').before(append);
});

$('body').on('click', '.remove', function() {
  //alert('ok');
  $(this).parent().remove();
});

Also i need one more thing when a user is click add more button I am showing a label thay shows day 1 if adding another item the it will show day 2 and so on.

A: *

*Update text of the label after append/remove

*Give some class to identify parent element of container.

$('.days').text(function(index) {
  return 'Day ' + (index + 1)
});

Updated Fiddle

A: You can do,
$('#btnAddMore').click(function() {
  var clone = $(append).clone()
  $('#appendContent').append(clone);
  clone.find(".form-group > label").text("Day " + $("#appendContent").children().length);
});
$('body').on('click', '.remove', function() {
  //alert('ok');
  $(this).parent().remove();
});

Fiddle

*

*Make a copy of the newly created div using clone().

*Then change the label inside the clone() using .find(".form-group > label").text()

*Get the number of the current div by counting the children of "appendContentDiv"

A: give class to main div
var append='

in jquery
$(this).closest('.minus').remove();

A: Have a look attached snippet :

       /* Latest compiled and minified JavaScript included as External Resource */
var append='

 <input type="text" value="" name="subHeading" class="form-control">
';
       append+='
 Description <textarea class="form-control" name="description"></textarea>';
       append+='
<button type="button" class="btn btn-danger remove" id="btnAddMore">Remove</button>
';
       $('#btnAddMore').click(function(){
           $('#appendContent:last').before(append);
                var i=1;
                        $('input[type="text"]').each(function(){
                            $(this).prev().html('Day '+i);
                            $(this).attr('name', 'subHeading' + i);
                                $(this).attr('id', 'subHeading' + i);
                                    i++;
                        });
       });
       $('body').on('click','.remove',function(){
           //alert('ok');
           $(this).parent().remove();
           var i=1;
                        $('input[type="text"]').each(function(){
              $(this).prev().html('Day '+i);
                            $(this).attr('name', 'subHeading' + i);
                                $(this).attr('id', 'subHeading' + i);
                                    i++;
                        });
       });
/* Latest compiled and minified CSS included as External Resource*/

/* Optional theme */
@import url('//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css');

body {
    margin: 10px;
}
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>

      <button type="button" class="btn btn-primary"id="btnAddMore">Addmore</button>

As well as please have a look attached fiddle.
Demo fiddle

A: var appendContentSize = $('#appendContent .appended-element').size();
       $('#btnAddMore').click(function(){
            var append='

 Day '+appendContentSize+'<input type="text" value="" name="subHeading" class="form-control">
';

       append+='
 Description <textarea class="form-control" name="description"></textarea>';
       append+='
<button type="button" class="btn btn-danger remove" id="btnAddMore">Remove</button>
';
           $('#appendContent').append(append);
           appendContentSize++
       });
       $('body').on('click','.remove',function(){
           //alert('ok');
           if(appendContentSize > 0){
                $(this).parent().remove();
            appendContentSize--
           }
       });

https://jsfiddle.net/giantomakin/wsm755vv/8/


text:
Q: Access to 32bit memory address c# I'm trying to access a 32bit address, but when i create the IntPtr it throws an OverflowException. Here's the code:
uint memAddr = 0xF5920824;
IntPtr bufPtr = new IntPtr(memAddr);
byte[] data = new byte[4];
Marshal.Copy(bufPtr, data, 0, 4);

How can i access that address?

A: For such a large number > 2^31-1 you need to compile as 64 bit.
Go to Configuration Manager... and change platform from x86 to Any CPU or x64.

A: By passing a uint to IntPtr, you are converting it to a long, as IntPtr doesn't support unsigned integers. Then, if you are running in a 32-bit process, your uint overflows an int.
You need to use 64-bit to read that address.

A: Your program CANNOT access a memory address of another program (regardless that the address you're going to read can't fit an Int32, see this post to understand what it is) simply using an IntPtrbecause they run within their private address space.
It must be shared somehow by the first program (shared memory or something else). Moreover an address XYZ in one program may be something completely different even in another instance of the same program (because the address is VIRTUAL).
If you're sure about the memory address (how? it could be even necessary to scan process memory) you have to P/Invoke ReadProcessMemory(), it's a function designed for debugging purposes and if your executable has enough privileges you can read the memory of another process.
See this post here on SO for an example.


text:
Q: Appium + selenium grid: Appium successfully registers to grid but doesn't make status calls My Appium + selenium grid has been workin fine up until a few days ago.
Now when i start my appium node it'll register onto the local grid:
"Appium successfully registered with the the grid on http://localhost:4444"

However it no longer sends get status calls like before and the grid will mark it as down
and clean it up as a stale session after some time or if you try to use the node.
java -jar /Users/pa23053/git/mobile-tools/selenium-server-standalone-3.141.59.jar -role hub
    08:59:44.265 INFO [GridLauncherV3.parse] - Selenium server version: 3.141.59, revision: e82be7d358
    08:59:44.354 INFO [GridLauncherV3.lambda$buildLaunchers$5] - Launching Selenium Grid hub on port 4444
    2022-08-26 08:59:44.846:INFO::main: Logging initialized @942ms to org.seleniumhq.jetty9.util.log.StdErrLog
    08:59:44.997 INFO [Hub.start] - Selenium Grid hub is up and running
    08:59:44.998 INFO [Hub.start] - Nodes should register to http://172.20.101.225:4444/grid/register/
    08:59:44.998 INFO [Hub.start] - Clients should connect to http://172.20.101.225:4444/wd/hub
    08:59:58.410 INFO [DefaultGridRegistry.add] - Registered a node http://0.0.0.0:49915
    09:02:39.295 INFO [DefaultRemoteProxy.onEvent] - Marking the node http://0.0.0.0:49915 as down: cannot reach the node for 2 tries
    09:04:00.616 INFO [DefaultRemoteProxy.onEvent] - Unregistering the node http://0.0.0.0:49915 because it's been down for 81321 milliseconds

After registering appium should regularly send these calls:
[HTTP] --> GET /wd/hub/status
[debug] [GENERIC] Calling AppiumDriver.getStatus() with args: []
[debug] [GENERIC] Responding to client with driver.getStatus() result: {"build":{"version":"2.0.0-beta.43"}}
[HTTP] <-- GET /wd/hub/status 200
[HTTP] --> GET /wd/hub/status
......

Instead now it just registers and then does nothing. So far the attempts at fixing have been:
Uninstalling + reinstalling appium.
upgrading and downgrading appium.
Switching selenium server versions.
The capabilities of the simulators that are being used should be fine as they haven't changed in a while and others use them without issue.
Any suggestions of things i should check or try would be greatly appreciated.

A: Was able to solve this myself. There was a weird issue were my laptop was setting my home networks Subnet mask to 255.255.252.0. This should've been 255.255.255.0. This caused an issue with either appium or selenium's ability to send/receive requests.
This explains why everything would work fine when i tried at office & while on mobile hotspot.