text:
Q: I get a number 2 when I reverse my string I wrote this code to reverse strings. It works well, but when I enter short strings like "american beauty," it actually prints "ytuaeb nacirema2." This is my code. I would like to know what is wrong with my code that prints a random 2 at the end of the string. Thanks
// This program prompts the user to enter a string and displays it backwards.

#include <iostream>
#include <cstdlib>
using namespace std;

void printBackwards(char *strPtr); // Function prototype

int main() {
    const int SIZE = 50;
    char userString[SIZE];
    char *strPtr;
    cout << "Please enter a string (up to 49 characters)";
    cin.getline(userString, SIZE);
    printBackwards(userString);

}

//**************************************************************
// Definition of printBackwards. This function receives a      *
// pointer to character and inverts the order of the characters*
// within it.                                                  *
//**************************************************************

void printBackwards(char *strPtr) {
    const int SIZE = 50;
    int length = 0;
    char stringInverted[SIZE];
    int count = 0;
    char *strPtr1 = 0;
    int stringSize;
    int i = 0;
    int sum = 0;

    while (*strPtr != '\0') {
        strPtr++; // Set the pointer at the end of the string.
        sum++; // Add to sum.
    }
    strPtr--;

    // Save the contents of strPtr on stringInverted on inverted order
    while (count < sum) {
        stringInverted[count] = *strPtr;
        strPtr--;
        count++;
    }
    // Add '\0' at the end of stringSize
    stringInverted[count] == '\0';

    cout << stringInverted << endl;
}

Thanks.

A: Your null termination is wrong.  You're using == instead of =.  You need to change:
stringInverted[count] == '\0';

into
stringInverted[count] = '\0';

A: // Add '\0' at the end of stringSize
stringInverted[count] == '\0';

Should use = here.

A: What is wrong with your code is that you do not even use strlen for counting the length of the string and you use fixed size strings (no malloc, or, gasp new[]), or the std::string (this is C++)! Even in plain C, not using strlen is always wrong because it is hand-optimized for the processor. What is worst, you have allocated the string to be returned (stringInverted) from the stack frame, which means when the function exits, the pointer is invalid and any time the code "works" is purely accidental.
To reverse a string on c++ you do this:
#include <iostream>
#include <string>

int main() {
    std::string s = "asdfasdf";
    std::string reversed (s.rbegin(), s.rend());
    std::cout << reversed << std::endl;
}

To reverse a string in C99 you do this:
char *reverse(const char *string) {
    int length = strlen(string);
    char *rv = (char*)malloc(length + 1);
    char *end = rv + length;
    *end-- = 0;
    for ( ; end >= rv; end --, string ++) {
        *end = *string;
    }
    return rv;
}

and remember to free the returned pointer after use. All other answers so far are blatantly wrong :)


text:
Q: Uploading XML data to a Dataset I am creating a generic XML to SQL Server data driver (In c#), that will take as input an XML file, and produce one or more data tables containing information.
So far I have an input XML file and an XSLT, the XSLT creates a new XML containing only the information needed from the xml.
My Problem lies in not knowing how to define a mapping from the XML elements to the columns in certain tables.
For example, say I have this extract of XML:
<Bug name = "MillenniumBug">
   <Severity value = "1" />
</Bug>

I would like to create two tables, a bugs table and a severity table, and I need the Bug name in the Bug table, and the severity value in the severity table.
A point in the right direction as to how I can specify this mapping would be really appreciated.
Thanks

A: You have already lined up your ruleset when you set up elements as tables and attributes as columnns in the table. Setting up the mapping, and even "table creation logic" is fairly easy using those rules. The harder part with your "driver" is going to be determination of types (is this number a byte, an int or a long?) and possibly creating an inferred schema to validate the input. Determining nullability of columns will also be an issue you have to examine.
Without better understanding the business driver for this project, I can't give you much more than that.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Combining functions with Javascript and JQuery I had a problem with combining som javascript functions through one function. I'm trying to build a little system to show at work. A kind a show how it could improve. Not for deployment.
The functions look like this.
// To choose an errand or with a zero start a new errand.
function buildErrandBox(number)
{
$.ajax({
    url: 'db/buildErrandBox.inc.php',
    type:'POST',
    dataType: 'json',
    data: { customerNumber: $("#customerNumber").val(), errandNumber: number },
    success: function(build){ $('#newErrandsBoxResult').empty(); $('#newErrandsBoxResult').append(build.buildForm); $('#newErrandsBoxTextResult').empty(); $('#newErrandsBoxTextResult').append(build.buildText); showMinorContent('#newErrands'); $('#errandArea').val(build.area); $('#errandGroup').val(build.group); $('#errandType').val(build.type); escalateOptions(); getEscalationGroups(); },
    error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(thrownError); }
});
}

// To save changes on a errand.
function saveErrand()
{
$.ajax({
    url: 'db/saveErrandsForCustomer.inc.php',
    type:'POST',
    dataType: 'json',
    data: { id: $("#errandID").val(),
            telephone: $("#errandTelephoneNumber").val(),
            email: $("#errandEmail").val(),
            area: $("#errandArea").val(),
            group: $("#errandGroup").val(),
            type: $("#errandType").val()
    },
    success: function(output_string){ showCustomerErrands(); },
    error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(thrownError); }
});
}

// To save a new note on an errand.
function saveTextForErrand()
{
$.ajax({
    url: 'db/saveErrandsText.inc.php',
    type:'POST',
    dataType: 'json',
    data: { id: $("#errandID").val(), text: $("#newTextForErrandTextArea").val() },
    success: function(output_string){ buildErrandBox($("#errandID").val()); },
    error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(thrownError); }
});
}

These are three seperate functions that work when a use the buttons on the webpage. First click to start a new errand. The change what type of errand it is. Put in some notes. And save the errand. All works fine.
In the background the build errand function build the whole box of inputs and selects to show the errand. But the next function to save the errand recognizes the errand number and saves the errand in the database.
But when i combine these like below
function preMadeErrand(area, group, type, text, servicetext)
{
buildErrandBox(0);
alert($("#errandID").val());
$('#errandArea').val(area);
changeErrandBoxes();
$("#errandGroup").val(group);
changeErrandBoxes();
$("#errandType").val(type);
$("#newTextForErrandTextArea").val(servicetext);
saveTextForErrand();
$("#newTextForErrandTextArea").val(text);
saveTextForErrand();
alert($("#errandID").val());

saveErrand();
}

The errandID becomes undefined. Any ideas?
Update!
When i had the alert in the beginning of the function it works. It seems as the function for building the box is not finished before it try to use the errandID. With two alerts the second gets the errandID.
Is there any way to make it finish execution one function like buildErrandBox(0) before it continues?

A: This is because ajax is asynchronous.. when alert is called. the ajax function is not yet executed..... one way you can fix it is by rearranging your functions and calling others, after the ajax success function of buildErrandBox(0).. this way we can make sure the other function is called only after buildErrandBox() is executed
function buildErrandBox(number)
{
  $.ajax({
    url: 'db/buildErrandBox.inc.php',
    type:'POST',
    dataType: 'json',
    data: { customerNumber: $("#customerNumber").val(), errandNumber: number },
    success: function(build){
                //your stuff..
                alert($("#errandID").val());
                $('#errandArea').val(area);
                changeErrandBoxes();
                ...
                saveTextForErrand();
                .........
                // function you want to execute here
             },
    error: function (xhr, ajaxOptions, thrownError) {
               //your stuff
             }
 });
}

A: You should have a look into using jQuery Deferred's when doing async requests like this.
http://api.jquery.com/jQuery.Deferred/
This will ensure that the requests are complete and returned before calling the next function.
Other deferred resources:
http://addyosmani.com/blog/digging-into-deferreds-1/
http://net.tutsplus.com/tutorials/javascript-ajax/wrangle-async-tasks-with-jquery-promises/

A: If you want the AJAX function to complete before proceeding, set the async option to false:
$.ajax({
    url: 'db/buildErrandBox.inc.php',
    type:'POST',
    dataType: 'json',
    async: false, // <-- add this line
    ...

This will block further execution of the next statement until the result has been returned (or timeout).
Documentation

A: You have to make sure that all your AJAX calls have finished and then you should try to further process the server respones.


text:
Q: Return result of .then() lambda expression as function result I'm relatively new to js so please forgive me if my wording isn't quite right. I've also created a jsfiddle to demonstrate the issue.
Overview
In the app I'm working on, I have a function with a jquery ajax call, like this:
function scenario1(ajaxCfg) {
    return $.ajax(ajaxCfg)
}

I want to change this function, but without in any way changing the inputs or outputs (as this function is called hundreds of times in my application).
The change is to make a different ajax call, THEN make the call specified. I currently have it written like this:
function callDependency() { //example dependency
    return $.ajax(depUri)
}

function scenario2(ajaxCfg) {
    return callDependency().then(() => $.ajax(ajaxCfg))
}

Desired Result
I want these two returned objects to be identical:
let result1 = scenario1(exampleCall)
let result2 = scenario2(exampleCall)

More specifically, I want result2 to return the same type of object as result1.
Actual Result
result1 is (obviously) the result of the ajax call, which is a jqXHR object that implements the promise interface and resolves to the same value as result2, which is a standard promise.
Since result2 is not a jqXHR object, result2.error() is undefined, while result1.error() is defined.
I did attempt to mock up these methods (simply adding a .error function to the return result, for example), but unfortunately even when doing this, result1.done().error is defined while result2.done().error is undefined.
Wrapping (or unwrapping) it up
In a nutshell, I want to return the jqXHR result of the .then() lambda function in scenario2 as the result of the scenario2 function. In pseudocode, I want:
function scenario2(ajaxCfg) {
    return callDependency().then(() => $.ajax(ajaxCfg)).unwrapThen()
} //return jqXHR

A: What about something like this? The approach is a little different, but in the end you can chain .done() etc. to the scenario2() function:

const exampleCall = { url: 'https://code.jquery.com/jquery-1.12.4.min.js'};
const depUri = { url: 'https://code.jquery.com/jquery-1.12.4.min.js'};

function callDependency() { //example dependency
    return $.ajax(depUri).done(() => console.log('returned callDependancy'))
}

let obj = { //creating an object with the scenario2 as a method so that I can bind it with defer.promise()
    scenario2: function(ajaxCfg) {
        return $.ajax(ajaxCfg).done(() => console.log('returned senario2')) // Purposely NOT calling the exampleCall() function yet
    }
}

defer = $.Deferred(); // Using some JQuery magic to be able to return a jqXHR
defer.promise(obj); // Set the object as a promise
defer.resolve(callDependency()); // Invoking the callDependency() by default on promise resolve

obj.done(() => {
    obj.scenario2() // Resolving so the callDependency() function can be called
}).scenario2(exampleCall).done(() => { // Here you can invoke scenario2 and FINALLY chain whatever you want after everything has been called
    console.log('Here I can chain whatever I want with .done\(\) or .fail\(\) etc.')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

What I think is cool about this way of doing it is that you can just keep adding methods to the object that you created, and then all your secondary functions that are built on top of callDependency() can be in one place. Not only that, but you can reuse those same methods on top of other AJAX calls.
Read more about this here.
I hope this helps!

A: I feel like your life would be made a lot easier if you used async/await syntax. Just remember though that async functions return a promise. So you could instead write:
async function scenario2(ajaxCfg) {
    let jqXhrResult;
    try {
        await callDependency();
        jqXhrResult = {
            jqXhr: $.ajax(ajaxCfg)
        };
    } catch() {
        // Error handling goes here
    }

    return jqXhrResult;
}

A: I actually thought of a way easier way to do this.
You can do it by adding a method to the function constructor's prototype object. That way any created function can inherit that method and you can still use the .done() syntax. It's referred to as prototypal inheritance:

const exampleCall = { url: 'https://code.jquery.com/jquery-1.12.4.min.js'};
const depUri = { url: 'https://code.jquery.com/jquery-1.12.4.min.js'};

function callDependency() {
    return $.ajax(depUri).done(() => console.log('returned callDependancy'))
}

Function.prototype.scenario2 = function(ajaxCfg, ...args) {
    return this(...args).then(() => $.ajax(ajaxCfg))
}

callDependency.scenario2(exampleCall).done(data => {
    console.log(data)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


text:
Q: Can the Hamiltonian be upscaled to speed up quantum gates? In quantum computing, gates are performed unitarily, i.e. $|\psi\rangle \mapsto U|\psi\rangle$, driven by some Hamiltonian, i.e. $U = \exp(-iHt)$. Consider $H$ as time independent, if it is proportionally scaled up, i.e. $H \mapsto \gamma H$, then the time for applying $U$ would become shorter, i.e., $t \mapsto \frac{t}{\gamma}$, does this speed up computation? (similar to how a classical computer can be overclocked)

A: Yes, in the simplified model of time-independent Hamiltonian $H$ effecting a quantum gate $U=\exp(-iHt)$ multiplying $H$ by a constant factor $\gamma > 1$ does shorten the gate's duration.
In practice, physics constants, material properties, control electronics etc constrain what Hamiltonians can be engineered on any given hardware platform. For example, in architectures based superconducting qubits where engineers have a high degree of control over a large number of parameters that go into the Hamiltonian, the energy scale is generally constrained to the microwave spectrum.

Also note that while fast gates are preferable to slow gates with the same decoherence because faster gates allow us to run longer algorithms, very high gate speed becomes a mixed blessing when implementing quantum error correction because that entails the need for a classical computer running alongside the quantum device for decoding syndrome measurements. Very fast quantum gates make it more challenging to implement the classical computer to perform quantum error correction.


text:
Q: Any need to verify disks after hard reboot? About every few days I need to reboot my 2012 MacBook Pro Retina.
I noticed these messages in the logs regarding "Journal is read-only and journal is dirty. Can not mount volume".
Any need to "Verify Disk" in Disk Utilities?

A: OS X doesn't normally seem to repair drives or volumes after hard resets or kernel panics, or at least the verbose startup output looks the same, and you don't probably need to do that manually either.
In this case you could try verifying the drives or volumes (logical partitions) as troubleshooting steps though. Note that the Verify Disk button performs completely different operations depending on whether a drive or a volume is selected. HFS+ volumes that support live verification can be verified even when they are mounted as the root filesystem, but you have to start up from the recovery partition to repair them.
According to Apple KB article TS1417, running fsck is not usually necessary.


text:
Q: What are login and non-login shells? It is said that settings for non login shell to go into .bashrc file and login shell settings to go into .profile file.
What is really meant by login and non-login shells?
Please explain without using technical jargon as far as possible.

A: Simply put:

*

*If you open a shell or terminal (or switch to one), and it asks you to log in (Username? Password?) before it gives you a prompt, it's a login shell.

*If it doesn't (like gnome-terminal), and lets you use it straight away, it's a non-login shell.

If you are a normal user of Ubuntu Desktop, the only login shell is...your desktop (you type a password to get in, right ;)? Well, technically it's a login shell that starts a GUI, but that's getting in to jargon. And yes, it will read the settings in .profile
The only time you (a normal user) will probably see a login shell that looks like a login shell is if you are having some problem with your desktop and you switch to a virtual terminal with the Ctrl+Alt+F1 shortcut.

The other general cases for having a login shell include:

*

*accessing your computer remotely via ssh (or connecting locally with ssh localhost)

*simulating an initial login shell with bash -l (or sh -l)

*simulating an initial root login shell with sudo -i

*

*or sudo -u username -i for another non-root user

*authenticating as another non-root user with su - username (and their password)

*using the sudo login command to switch user

A: I do not think that correct answer can be given without "technical jargon". Since this question is the first one popping up in Google for the query "what is a login shell" I am providing a more correct answer below:
Login shell is simply a shell that was told to be a login shell. It does not mean shell that pops up after you login, though usually application that logs you in is telling shell it launches to be a login shell. There exists the following ways to tell shell it should be a login one:

*

*Running shell with -l or --login argument assuming it knows it (I do not know any shells which do not know -l, but --login is only supported by a few shells).

*Running shell with argv[0] set to -{some_string} (i.e. with HYPHEN-MINUS prepended to usual argv[0] or to some other string). This is what ssh and su do: su just runs executable with -su as argv[0] (hello to everybody thinking argv[0] has something to do with currently running executable name), ssh runs zsh with -zsh when user has set /bin/zsh as his shell.

Loginess of the shell has absolutely nothing to do with anybody asking you a password or performing some other authenication procedure. Some programs like ssh or login (or some terminal emulators like urxvt) run shells as a login ones using argv[0] that starts with a HYPHEN-MINUS. Some like su or sudo (or zsh: see - precommand modifier described in section PRECOMMAND MODIFIERS in man zshmisc) do not do this by default, but can be told so. Some have the only option of telling shell to be the login one using its argument (i.e. bash -l): ssh with a command argument (that explicitly tells ssh what to run on the remote end).
Generally it is better to first consult the documentation of the program used to invoke the shell to determine whether shell will be the login one and second perform some tests to determine whether app will launch a login shell (e.g. by adding echo to .profile).


text:
Q: Why does my input not get validated when I'm not utilizing razor Html helpers? Say I have a simple web form that does not utilize razor html helpers/a model.
<form id="survey-form" action="@Url.Action("Submit", "Questionnaire")" method="post">
   <textarea name="1" form="survey-form">
</form>

The above form gets submitted using
$("#survey-form").submit();

Which posts to the following test method on a controller
[HttpPost]
[ValidateAntiForgeryToken]
[ValidateInput(true)]
public ActionResult Submit()
{
    NameValueCollection nvc = Request.Form;
    return View();
}

<script>alert("xss!")</script> into my text input does not get validated by the controller. Where I would normally expect the "A potentially dangerous Request.Form was detected from the client ..." exception to be thrown.
The Method does not return any exceptions or messages and is allowed to run.
The MSDN documentation says

The HttpRequest class uses input validation flags to track whether to perform validation on the request collections accessed through the Cookies, Form, and QueryString properties.

Since I am posting and processing a posted form with potentially dangerous values I would expect my input to be validated.
Is it possible for me to still utilize a simple MVC helper like the ValidateInput attribute, to validate user input without using the ASP.NET MVC conventions? (eg. creating a form using razor html helpers and a model etc.)
Edit:
As there seems to be some confusion of the values actually reaching my Action on the Controller, here is a screenshot showcasing that the values do reach the function.

A: I think you should include FormCollection as an argument for the Submit ActionResult.


text:
Q: AWS Glue - avro to parquet - Glue job getting an empty frame from catalog I'm using an AWS Glue Crawler to crawl a rough 170 GB of avro data to create a Data Catalog table.
There are a couple different schema versions in the avro data but the crawler still manages to combine the data into a single table (I have enabled the "Group by data compatibility and schema similarity - mode").
Here is when things get problematic.
I can only use Athena to run a SELECT COUNT(*) FROM <DB>.<TABLE> query on the data - any other query raises the following error:
GENERIC_INTERNAL_ERROR: Unknown object inspector category: UNION

A brief Google check leads me to believe that this has something to do with the schema in the avro files.
Normally, this is where I would focus my efforts BUT: I have been able to do this exact same procedure(AVRO -> crawler -> Glue job -> PARQUET) before, with a smaller avro data set (50GB) having the same issue(only being able to run a count query). Moving on.
The the conversion job previously took about an hour. Now, when running the same job on the 170 GB data, the job finishes in a minute because glueContext.create_dynamic_frame.from_catalog now returns an empty frame - no errors, no nothing. The confusion is real as I am able to run a COUNT query in Athena on the same table that the job is using, returning a count of 520M objects.
Does anyone have an idea what the problem might be?
A couple of things that might be relevant:

*

*The COUNT query returns 520M but the recordCount in table properties says 170M records.

*The data is stored in 300k .avro files with size 2MB-30MB

*Yes, the crawler is pointed to the folder with all the files, not to a file (common crawler gotcha).

*The previous attempt with a smaller data set(50 GB) was 100% successful - I could crawl the parquet data and query it with Athena (tested many different queries, all working)

A: We had the same issue and could solve it as follows.
In our avro schema there was a record with mixed field types, i.e., some were of the form "type" : [ "string" ], others of the form "type" : [ "null", "string" ].
Changing this manually to [ "null", "string" ] everywhere, we were able to use the table in Athena without any issues.


text:
Q: Structural Induction: Prove that all ternary trees with $n$ vertices have a height of at least $\lfloor\log_{3}{n}\rfloor$ Prove that all ternary trees (each vertex has up to three children) with $n$ vertices have a height of at least $\lfloor\log_{3}{n}\rfloor$.
I know we can show that a perfect ternary tree of height $h$ has $3^0+3^1+3^2+\dots+3^h=\frac{3^{h+1}-1}{2}$ vertices, $$n=\frac{3^{h+1}-1}{2}$$ so a perfect ternary tree with n vertices must have a height of $$h=\log_{3}{(2n+1)}-1$$
So, imperfect ternary trees have a height of at most $h=\log_{3}{(2n+1)-1}$, and $\lfloor\log_{3}{n}\rfloor\leq \log_{3}{(2n+1)}$, but I need to give a lower bound of $\lfloor\log_{3}{n}\rfloor$.
How should I continue? Or is there a better way to prove this?


text:
Q: Error: unable to open database on sqlite3 I'm working on Android and using Eclipse to develop and the emulator to test my application, I'm trying to insert the content from an ArrayList into a database, but when I try to access to the database's information through the console I get the following message:
Error: unable to open database /data/data/my.package/databases/ars.db : unable to open database file
So far I know the database is being created correctly since every time I insert a row the SQLiteDatabase's insert method returns the id of the row created and so far I have run my application 6 times and the last id I got was 18.
I'm trying to access to the database the following way:
#sqlite3 /data/data/my.package/databases/ars.db
and then when I try :
sqlite>.tables
I get the error message. What am I doing wrong? Why can't I get permission to access to the database data? Is it because I'm using the emulator instead of an Android device? Thanks for any piece of advice you can give.


text:
Q: MediaWiki Server does not display correctly I have a mediawiki server and when I open it, it looks like this

This is a brand new mediawiki server and I just finished setting it up.
My LocalSettings.php is at https://voidtm.tk/LocalSettings.php
How can I fix this?

A: You should configure a skin. I suggest using the most common skin known as vector. That page also has installation instructions.


text:
Q: Which windows event is triggered on secondary display device detection This question is specific to Windows 8.1.
I want to schedule a windows task to run when a secondary output device (e.g., VGA monitor or HDMI A/V receiver is turned on or off) but I'm not sure which event should be used for this. I found something related to network cable plug/unplug here https://superuser.com/questions/262799/how-to-launch-a-command-on-network-connection-disconnection , but nothing for external audio/video devices. Any such event or events exist? If not, any other way to do this?
Thanks

A: Your computer has no way of knowing if the "secondary output device" is turned on/off. Your machine only knows if a display is plugged in or not to the video port on the computer.


text:
Q: Bidirectional LSTM in seq2seq model I am trying to build a Encoder decoder bidirectional lstm model for my text summarization task. I am facing problems with input shape. Error: An initial_state was passed that is not compatible with cell.state_size. Received state_spec=ListWrapper([InputSpec(shape=(None, 128), ndim=2), InputSpec(shape=(None, 128), ndim=2), InputSpec(shape=(None, 128), ndim=2), InputSpec(shape=(None, 128), ndim=2)]); however cell.state_size is [128, 128].
Could anyone help with this please?
Here is the model:
latent_dim = 128
embedding_size=512
# Encoder
encoder_inputs = Input(shape=(max_len_text,))
enc_emb = Embedding(x_voc_size, embedding_size,trainable=True)(encoder_inputs)
#Preparing BiLSTM layer 1
encoder_lstm1 = Bidirectional(LSTM(latent_dim, return_state=True) )
encoder_output1, forward_h, forward_c, backward_h, backward_c = encoder_lstm1(enc_emb)
# Decoder layer
decoder_inputs = Input(shape=(max_len_text,))
print(y_voc_size,latent_dim)
dec_emb_layer = Embedding(y_voc_size, latent_dim,trainable=True)
dec_emb = dec_emb_layer(decoder_inputs)
decoder_lstm = LSTM(latent_dim, return_sequences=True, return_state=True)
decoder_outputs,decoder_fwd_state, decoder_back_state = decoder_lstm(dec_emb,initial_state=[forward_h, forward_c, backward_h, backward_c])
#Adding the dense layer
decoder_dense = TimeDistributed(Dense(y_voc_size, activation='softmax'))
decoder_outputs = decoder_dense(decoder_outputs)

# Prepare the model
model = Model([encoder_inputs, decoder_inputs], decoder_outputs)
model.summary()

A: normalizing your dataset will reduce the noise
 fig, ax = plt.subplots(figsize=(16,8))
 grouped=df.groupby('valid')
 temperatures=grouped[['tmpf','relh']].mean()
 temperatures.plot(ax =ax)
 plt.xticks(rotation=90)
 plt.ylabel('Temperature')
 plt.xlabel('Date')
 plt.title('Idaho')

 look_back = 3

 # LSTM configuration 1
 model = Sequential()
 model.add(LSTM(100, input_shape=(1, look_back)))
 model.add(Dense(1))
 model.compile(loss='mean_squared_error', optimizer='adam')

 dataset=temperatures
 scaler = MinMaxScaler(feature_range=(0, 1))
 dataset = scaler.fit_transform(np.array(dataset).reshape(-1,1))

 # convert an array of values into a dataset matrix
 def create_dataset(dataset, look_back=3):
     dataX, dataY = [], []
     for i in range(len(dataset)-look_back-1):
         a = dataset[i:(i+look_back)]
         dataX.append(a)
         dataY.append(dataset[i + look_back])
     return np.array(dataX), np.array(dataY)

 # normalize the dataset

 # split into train and test sets
 train_size = int(len(dataset) * 0.80)
 test_size = len(dataset) - train_size
 train, test = dataset[0:train_size], dataset[train_size:len(dataset)]
 print(len(train), len(test))

 trainX, trainY = create_dataset(train, look_back)
 testX, testY = create_dataset(test, look_back)

 # reshape input to be [samples, time steps, features]
 trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
 testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))

 model.fit(trainX, trainY, epochs=10, batch_size=1, verbose=2)


text:
Q: Can't link against libquadmath with g++ This is similar to Link libquadmath with c++ on linux but the extern "C" answer appears outdated based on comments. I did try the answer, but it didn't work.
Code
#include <iostream>
#include <quadmath.h>

int main()
{
    char buffer[1024];
    quadmath_snprintf(buffer, 1023, "%Qe", 5.099q);
    std::cout << buffer << std::endl;
    return 0;
}

Invocation
$ g++ -lquadmath -o float_formatting float_formatting.cpp
/tmp/cc1juozE.o: In function `main':
float_formatting.cpp:(.text+0x3e): undefined reference to `quadmath_snprintf'
collect2: error: ld returned 1 exit status

Based on the output, it's finding libquadmath.so fine, but it's missing the symbol.
g++ Verbose
$ g++ --verbose -lquadmath -o float_formatting float_formatting.cpp
Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/7/lto-wrapper
OFFLOAD_TARGET_NAMES=nvptx-none
OFFLOAD_TARGET_DEFAULT=1
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu 7.4.0-1ubuntu1~18.04.1' --with-bugurl=file:///usr/share/doc/gcc-7/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++ --prefix=/usr --with-gcc-major-version-only --program-suffix=-7 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-libmpx --enable-plugin --enable-default-pie --with-system-zlib --with-target-system-zlib --enable-objc-gc=auto --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 7.4.0 (Ubuntu 7.4.0-1ubuntu1~18.04.1)
COLLECT_GCC_OPTIONS='-v' '-o' 'float_formatting' '-shared-libgcc' '-mtune=generic' '-march=x86-64'
 /usr/lib/gcc/x86_64-linux-gnu/7/cc1plus -quiet -v -imultiarch x86_64-linux-gnu -D_GNU_SOURCE float_formatting.cpp -quiet -dumpbase float_formatting.cpp -mtune=generic -march=x86-64 -auxbase float_formatting -version -fstack-protector-strong -Wformat -Wformat-security -o /tmp/ccAU2pi6.s
GNU C++14 (Ubuntu 7.4.0-1ubuntu1~18.04.1) version 7.4.0 (x86_64-linux-gnu)
        compiled by GNU C version 7.4.0, GMP version 6.1.2, MPFR version 4.0.1, MPC version 1.1.0, isl version isl-0.19-GMP

GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
ignoring duplicate directory "/usr/include/x86_64-linux-gnu/c++/7"
ignoring nonexistent directory "/usr/local/include/x86_64-linux-gnu"
ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/7/../../../../x86_64-linux-gnu/include"
#include "..." search starts here:
#include <...> search starts here:
 /usr/include/c++/7
 /usr/include/x86_64-linux-gnu/c++/7
 /usr/include/c++/7/backward
 /usr/lib/gcc/x86_64-linux-gnu/7/include
 /usr/local/include
 /usr/lib/gcc/x86_64-linux-gnu/7/include-fixed
 /usr/include/x86_64-linux-gnu
 /usr/include
End of search list.
GNU C++14 (Ubuntu 7.4.0-1ubuntu1~18.04.1) version 7.4.0 (x86_64-linux-gnu)
        compiled by GNU C version 7.4.0, GMP version 6.1.2, MPFR version 4.0.1, MPC version 1.1.0, isl version isl-0.19-GMP

GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
Compiler executable checksum: 38816e3807cdcb3c59571e251bd6c090
COLLECT_GCC_OPTIONS='-v' '-o' 'float_formatting' '-shared-libgcc' '-mtune=generic' '-march=x86-64'
 as -v --64 -o /tmp/ccFFf6xp.o /tmp/ccAU2pi6.s
GNU assembler version 2.30 (x86_64-linux-gnu) using BFD version (GNU Binutils for Ubuntu) 2.30
COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/
LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/7/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/7/../../../:/lib/:/usr/lib/
COLLECT_GCC_OPTIONS='-v' '-o' 'float_formatting' '-shared-libgcc' '-mtune=generic' '-march=x86-64'
 /usr/lib/gcc/x86_64-linux-gnu/7/collect2 -plugin /usr/lib/gcc/x86_64-linux-gnu/7/liblto_plugin.so -plugin-opt=/usr/lib/gcc/x86_64-linux-gnu/7/lto-wrapper -plugin-opt=-fresolution=/tmp/cco3ADOI.res -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lc -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lgcc --sysroot=/ --build-id --eh-frame-hdr -m elf_x86_64 --hash-style=gnu --as-needed -dynamic-linker /lib64/ld-linux-x86-64.so.2 -pie -z now -z relro -o float_formatting /usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/Scrt1.o /usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/crti.o /usr/lib/gcc/x86_64-linux-gnu/7/crtbeginS.o -L/usr/lib/gcc/x86_64-linux-gnu/7 -L/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu -L/usr/lib/gcc/x86_64-linux-gnu/7/../../../../lib -L/lib/x86_64-linux-gnu -L/lib/../lib -L/usr/lib/x86_64-linux-gnu -L/usr/lib/../lib -L/usr/lib/gcc/x86_64-linux-gnu/7/../../.. -lquadmath /tmp/ccFFf6xp.o -lstdc++ -lm -lgcc_s -lgcc -lc -lgcc_s -lgcc /usr/lib/gcc/x86_64-linux-gnu/7/crtendS.o /usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/crtn.o
/tmp/ccFFf6xp.o: In function `main':
float_formatting.cpp:(.text+0x3e): undefined reference to `quadmath_snprintf'
collect2: error: ld returned 1 exit status

ld Verbose
I copy/pasted the LIBRARY_PATH variable and -L arguments from the g++ verbose output to check which file is picked up for -lquadmath
$ LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/7/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/7/../../../:/lib/:/usr/lib/ ld --verbose -L/usr/lib/gcc/x86_64-linux-gnu/7 -L/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu -L/usr/lib/gcc/x86_64-linux-gnu/7/../../../../lib -L/lib/x86_64-linux-gnu -L/lib/../lib -L/usr/lib/x86_64-linux-gnu -L/usr/lib/../lib -L/usr/lib/gcc/x86_64-linux-gnu/7/../../.. -lquadmath | grep libquadmath
ld: warning: cannot find entry symbol _start; not setting start address
attempt to open /usr/lib/gcc/x86_64-linux-gnu/7/libquadmath.so succeeded

Symbol
Checking that file for the symbol, it seems to be there.
$ nm -gD /usr/lib/gcc/x86_64-linux-gnu/7/libquadmath.so | grep quadmath_snprintf
0000000000020f20 T quadmath_snprintf

Alas, it's not found during link time. What am I doing wrong? How do I link in libquadmath using g++?

A: Your problem is that this link line is incorrect:
g++ -lquadmath -o float_formatting float_formatting.cpp

It should be:
g++ -o float_formatting float_formatting.cpp -lquadmath

To understand why the order matters, read this post.


text:
Q: Reload the Map when we navigate to MapTabBar I have a tabBarView controller and a TableViewController. When I click on a row I wan to go to another Tab which is UIViewController with Map:
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if(storeName)
       [self setMap];
}

- (void) setMap {

    NSLog(@"Name:%@\n", storeName);
    NSLog(@"Adress:%@\n", storeAddress);

        self.indexMapView.delegate = self;

        self.indexMapView.showsUserLocation = NO;

        self.locationManager = [[CLLocationManager alloc] init];
        [locationManager setDelegate:self];

        [locationManager setDistanceFilter:kCLDistanceFilterNone];
        [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];

        [self.indexMapView setShowsUserLocation:YES];

        CLLocationCoordinate2D location = [self getLocationFromAddressString:self.storeAddress];

        NSLog(@"%g", location.latitude);

        MapViewAnnotation *mapAnnotation = [[MapViewAnnotation alloc] initWithTitle:@"Store location" coordinate:location];
        [self.indexMapView addAnnotation:mapAnnotation];

}

-(CLLocationCoordinate2D) getLocationFromAddressString:(NSString*) addressStr {

    NSLog(@"FFF");

    NSString *urlStr = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&output=csv",
                        [addressStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

    NSError *error = nil;

    NSString *locationStr = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlStr] encoding:NSUTF8StringEncoding error:&error];

    NSArray *items = [locationStr componentsSeparatedByString:@","];

    double lat = 0.0;
    double lon = 0.0;

    if([items count] >= 4 && [[items objectAtIndex:0] isEqualToString:@"200"]) {
        lat = [[items objectAtIndex:2] doubleValue];
        lon = [[items objectAtIndex:3] doubleValue];
    }
    else {
        NSLog(@"Address, %@ not found: Error %@",addressStr, [items objectAtIndex:0]);
    }

    CLLocationCoordinate2D location;
    location.latitude = lat;
    location.longitude = lon;

    return location;
}

This is how I go to the MapViewController:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MapViewController *mapViewController = [[MapViewController alloc]init];

    [mapViewController setStoreAddress:store.address];
    [mapViewController setStoreName:store.name];
    [mapViewController viewDidLoad];

    [self.tabBarController setSelectedIndex:4];
}

The problem is Map does not get update when I go to the page again. When I tried it with PushSegue, it works. but how can I make it work with TabBar?

A: Well, it looks like you commented out your call to -setMap, which means that when the view loads, nothing of interest is going to happen. Was that intentional?

A: I figured out how can I pass the data over tab bars. You can find more descriptions in these links:
iPhone: How to Pass Data Between Several Viewcontrollers in a Tabbar App
Passing a managedObjectContext through to a UITabBarController's views
Also this tutorial is useful.


text:
Q: How to set DateTime format in IValueConverter and return string value? I want a specific format in IValueConverter and return a string. Like "MMMyyyy" How can I get this?
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    var item = (DateTime)value;
    if (item != null)
    {
        return item.ToString();
    }
    return null;
}

A: Please try below
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
     var item = (DateTime)value;
     if (item != null)
     {
         return item.ToString("MMMyyyy");
     }
     return null;
}

A: Do you really need an IValueConverter here?
If you want this for a binding to display the databound DateTime with a specific format in WPF, you can use the StringFormat property of the Binding
Article about StringFormat

A: You just simply need to add the format ToString as parameter
 return item.ToString("MMyyyy");

A: You can use DateTimes overload for ToString() - ToString( string format ). Thus - you can write:
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    var item = (DateTime)value;
    if (item != null)
    {
        return item.ToString("MMMyyyy");
    }
    return null;
}

For more information have a look at this link:
http://msdn.microsoft.com/en-us/library/az4se3k1.aspx


text:
Q: Error: No viable overloaded = I have a class which looks like this:
class MemberListEntry {
public:
    int id;
    short port;
    long heartbeat;
    long timestamp;
    MemberListEntry(int id, short port, long heartbeat, long timestamp);
    MemberListEntry(int id, short port);
    MemberListEntry(): id(0), port(0), heartbeat(0), timestamp(0) {}
    MemberListEntry(const MemberListEntry &anotherMLE);
    MemberListEntry& operator =(const MemberListEntry &anotherMLE);
    int getid();
    short getport();
    long getheartbeat();
    long gettimestamp();
    void setid(int id);
    void setport(short port);
    void setheartbeat(long hearbeat);
    void settimestamp(long timestamp);
};

The I have some code which instantiates it like this:
   int id = stoi(address.substr(0, pos));
   short port = (short)stoi(address.substr(pos + 1, address.size()-pos-1));
   memcpy(&addr[0], &id, sizeof(int));
   memcpy(&addr[4], &port, sizeof(short));

  MemberListEntry mEntry;
  mEntry = new MemberListEntry(id, port);

I am getting this error:
 error: no viable overloaded '='
 mEntry = new MemberListEntry(id, port);

Any idea what could be the cause of the issue?

A: Your code should be
MemberListEntry * mEntry;
mEntry = new MemberListEntry(id, port);

You are allocating an object on heap using new operator which returns pointer to the object created and you are trying to assign a pointer to an object.
Better alternative here would be allocate object on stack which you are doing it already.
MemberListEntry mEntry(id, port);
This creates and initializes the object and it will be destructed automatically when your function goes out of scope.
Fun fact: This not java, it's C++. :)
Hope this helps.


text:
Q: Incremental build for Android project using Ant My server needs to keep building a large amount of Android projects. All of them are almost identical except for minor change on manifest.xml or any resource file (if it's better for the task) for each build. To reduce cost and improve efficiency, I try to implement incremental build. My planned procedures are:

*

*after the first successful build, skip all the previous
procedures (aapt to generate R.java, adle to make java, etc.)

*directly call aapt to make resource files, e.g., *.ap_

*call apkbuilder to make classes.dex and usigned.apk

*make signed.apk

So my question is whether the above solution is possible? And any clue about how to implement it?

A: This isn't necessarily a solution for your particular requirements but perhaps it will provide you with some useful pointers.
I have an Antlib that I use for building Android projects.  You probably won't want to use it yourself as it has some drawbacks, but it should serve as an example of how to perform the various steps to build an Android app using Ant.  In particular, it shows how to call the various Android SDK tools from Ant and how to use the Ant uptodate task and Ant's if and unless attributes to avoid processing files that haven't changed.
The source for the Android Ant macros is here (the Antlib documentation might help you to make sense of what it's doing).


text:
Q: prev / nex post links does not work if polylang custom post traslations is on As I wrote in the title, custom posts previous, and next_post_links are working fine, but if I activate polylang-s custom post traslations, they do not work anymore
This is the code:

<?php if ( have_posts() ) : ?>
    <?php while ( have_posts() ) : the_post(); ?>

<?php the_title(); ?>

        <?php the_content(); ?>
    <?php endwhile; ?>
<?php endif; ?>
<?php if ( is_single() ) { ?>

<?php previous_post_link(); ?>

<?php next_post_link(); ?>

<?php } ?>

A: I have fond the problem, the post were not assigned to any language.


text:
Q: React Router path wrongly matches I'm using React v4.2 for my app, and it seems not to be matching the correct path for the routes:
  <Provider store={store}>
      <BrowserRouter>

          <Switch>
            <Route path="/login" render={(props) => {
                if (isAuthenticated()) {
                  return <Redirect to='/' />;
                } else {
                  return <LoginForm {...props}/>
                }
              }
            } />
            <EnsureLoggedInContainer>
              <Route exact path="/group" render={(props) => {
                debugger;
                return <GroupList {...props}/>
              }
              }/>
              <Route exact path="/group/new" render={(props) => {
                debugger;
                return <GroupList {...props} modal={rr}/>;
              }
              } />
            </EnsureLoggedInContainer>
          </Switch>

      </BrowserRouter>
  </Provider>

I have some links in the app, on which I click and I redirect the client to new URL:
  _onSubmit(values) {
    const { history } = this.props;
    this.props.createGroup(values, ({status}) => history.push('/group'));
  }

I inspect the values of props.history.location.pathname and props.match.path and they don't match. Why is this happening? Why is the correct route not matched?
Update 1
The code for EnsureLoggedInContainer:
class EnsureLoggedInContainer extends Component {
  componentDidMount() {
    if (!isAuthenticated()) {
      dispatch(setRedirectUrl(currentURL))
      this.props.history.replace("/login")
    }
  }

  render() {
    if (isAuthenticated()) {
      return(

          <AppNavBar />
          <ComponentsNavBar />
          {this.props.children}

      );
    } else {
      return ;
    }
  }
}

export default EnsureLoggedInContainer;

Update 2
I changed the router configuration code to the following:
ReactDOM.render(
  <Provider store={store}>
      <BrowserRouter>

          <Switch>
            <Route exact path="/login" render={(props) => {
                if (isAuthenticated()) {
                  return <Redirect to='/' />;
                } else {
                  return <LoginForm {...props}/>
                }
              }
            } />
            <Route exact path="/register" render={(props) => {
                if (isAuthenticated()) {
                  return <Redirect to='/' />;
                } else {
                  return <RegisterForm {...props}/>
                }
              }
            } />
            <EnsureLoggedInContainer>
              <Route exact path="/group" component={GroupList} modal={newGroupModal}/>
              <Route exact path="/group/new" component={GroupList}/>
              <Route component={Home} />
            </EnsureLoggedInContainer>
          </Switch>

      </BrowserRouter>
  </Provider>
  , document.querySelector('.container'));

And changed the last line of EnsureLoggedInContainer to :
export default withRouter(EnsureLoggedInContainer);

But still, I get Home always being rendered, and random URLs being matched to unrelated routes (e.g. /group/new)

A: As per the documentation:

A match object contains information about how a  matched
  the URL. match objects contain the following properties:
params - (object) Key/value pairs parsed from the URL corresponding to the dynamic segments of the path

isExact - (boolean) true if the entire URL was matched (no trailing characters)

path - (string) The path pattern used to match. Useful for building nested <Route>s

url - (string) The matched portion of the URL. Useful for building nested <Link>s

while

Locations represent where the app is now, where you want it to go, or
  even where it was.

so if you are on say /group/new, location.pathname will give you /group/new whereas match.path will give your the Route path defined for the component in which you log it if it is matched

A: I finally managed to resolve the issue by using the private route pattern.


text:
Q: Crash in reloadRowsAtIndexPaths: Attempt to delete row containing first responder that refused to resign I'm stuck on this error. First the code is in swift, not objective C. I am using a UITableView where the the cells can be expanded with additional subviews when selected. When I select a cell, it expands. When I select another cell, the first cell contracts and the new selected cell expands. This is all fine. The code uses this command:
super.viewTable!.reloadRowsAtIndexPaths(cellsToUpdate, withRowAnimation: UITableViewRowAnimation.Fade)

The problem is that one of the subviews in the expanded cell can pop up a UIAlertController when pressed. If I pop up this UIAlertController and cancel it so it goes away, then when I press any other cell in my table, the app crashes with this error:
Assertion failure in -[UITableView _updateWithItems:updateSupport:],
/SourceCache/UIKit_Sim/UIKit-3347.44.2/UITableView.m:2924
2015-10-05 15:59:32.276 MyAppName[46504:1975727] *** Terminating app due
to uncaught exception 'NSInternalInconsistencyException', reason: 'Attempt
to delete row containing first responder that refused to resign'

In other words, everything works fine unless I pop up an alert in the expanded cell. Unfortunately I HAVE TO pop up the alert in the expanded cell to make the program useful. So I need to fix this issue and have no idea how. How can I force whatever is holding on to first responder status in the expanded cell give it up? How can I even see what that first responder is? I have tried to call endEditing(true) and similar sorts of things. I do not have a UITextView as a subview anywhere, so that isn't the problem. Any ideas how to fix this?
I'm open to ideas how toI tried calling reloadData() before the call to reloadRowsAtIndexPaths. Nothing works so far.
UPDATE: Well guess what. There may be a bug in UIAlertController, because when I replace all my UIAlertController code with UIAlertView, everything now works fine, no crashes. Somehow UIAlertController screws up some first responder somewhere so that it now refuses to release first responder status. UIAlertView is a bit more annoying to set up, with UIALertViewDelegate and such, but at least it works without crashing.
But this still begs the question, what could be going wrong in UIAlertController?


text:
Q: How do I update Angular styling using ElementRef? I am new to Angular I am working on a bottom that updates the styling when pressed. Here is a copy of the HTML page.

  <button #toggleNavigation aria-expanded="false">
    <mat-icon>menu</mat-icon>
  </button>

      <side-menu-item *ngFor="let item of navItems" [hidden]="item.isHidden"
                      [finished]="item.finished" [name]="item.displayName"
                      [routeURL]="item.routeURL"
                      [ngClass]="{'mt-auto': item.name === 'Summary'}">
      </side-menu-item>

When the button is pressed, this is what I would like it to update to.

  <button #toggleNavigation aria-expanded="true">
    <mat-icon>menu</mat-icon>
  </button>

      <side-menu-item *ngFor="let item of navItems" [hidden]="item.isHidden" [finished]="item.finished" [name]="item.displayName" [routeURL]="item.routeURL"  [ngClass]="{'mt-auto': item.name === 'Summary'}"></side-menu-item>

Clicking the button will display a navigation list. As you see in the code the styling is updated from class="sidebar-sticky collapse navbar-collapse" to class="sidebar-sticky collapse navbar-collapse show". Originally, I using a bootstrap.js file to handle this but it interfered with styling associated with another program. In my .ts file this is what I have
import { Component, ElementRef, Renderer2, ViewChild } from '@angular/core';

@Component({
  selector: 'app-side-menu',
  templateUrl: './side-menu.component.html',
  styleUrls: ['./side-menu.component.scss']
})

export class NavMenuComponent {

  @ViewChild('toggleNavigation', {static: false}) toggleNavigation: ElementRef;
  constructor() {

  onToggleNavigation() {

  }
}

Any help would be greatly appreciated.

A: I would do this with [ngClass].
Try:

  <button #toggleNavigation aria-expanded="true" (click)="onToggleNavigation()">
    <mat-icon>menu</mat-icon>
  </button>

      <side-menu-item
          *ngFor="let item of navItems"
           [hidden]="item.isHidden"
           [finished]="item.finished" [name]="item.displayName"
           [routeURL]="item.routeURL"
           [ngClass]="{'mt-auto': item.name === 'Summary'}"
           (click)="collapseNavigation()"
>
</side-menu-item>

collapseSideNav: boolean = true; // can default it to whatever you like

onToggleNavigation() {
  this.collapseSideNav = !this.collapseSideNav;
}

collapseNavigation() {
  if (!this.collapseSideNav) {
    this.collapseSideNav = true;
  }
}

A: Use [ngClass] for this:

  <button  [attr.aria-expanded]="collapsed" (click)="collapsed = !collapsed">
    click
  </button>

      content

https://stackblitz.com/edit/angular-3rn8no?file=src%2Fapp%2Fapp.component.ts


text:
Q: How can I inject a String value defined in a xml file into a component class member? For instance, in the xml file, I have defined some String values:
<bean id="name" class="java.lang.String" >
    <constructor-arg type="java.lang.String" value="SMITH" />
</bean>

While in the component class, how can I inject this into its class member?
@Component
public class Person {
    private String name; // @Autowired doesn't work here
}

How can I inject the String 'name' defined in the xml file into Person? @Autowired doesn't work. Is there any workaround here?

A: Try to annotate with @Resource
@Resource(name="name")
private String name;


text:
Q: React Native NativeBase ListView with separators I currently use React Native's ListView to display a list with section headers (renderSectionHeader):
<ListView
  dataSource={this.state.dataSource}
  renderRow={(rowData) => <JobListDetail firstOccurrence={rowData} />}
  renderSectionHeader={(sectionData, sectionId) => <ListSectionHeader sectionId={sectionId} />}
/>

The dataSource contains an Array of objects with the section header in the key and and an array of list items as the value like so
{
  Section 1: [{firstName: 'A', lastName: 'B'}, {firstName: 'C', lastName: 'D'}],
  Section 2: [{firstName: 'E', lastName: 'F'}, {firstName: 'G', lastName: 'H'}]
}

I was wondering whether I could achieve the same (and with a nicer looking layout) using NativeBase's List component. However, I couldn't find any info on how to pass in section headers:
<List dataArray={items} renderRow={(data) =>
    <ListItem>
        <Text>{data}</Text>
    </ListItem>
} />

Is that possible and if yes, are there are downsides to using it instead of React Native's ListView?

A: In theory NativeBase's List should accept the props that React Native's ListView supports.
The section header could be rendered with the itemHeader prop:
<ListItem itemHeader>
  <Text>ACTION</Text>
</ListItem>


text:
Q: How to read latest commit hash programmatically? I want to print the latest commit hash in my Node.js application.
I found a similar discussion here, but it's not what I have in mind. I want to read this information from within Node.js, without running git commands in a terminal.
So if possible, I want to read the .git folder with fs, find the latest commit hash and write it to a variable. This file looks relevant: .git/logs/refs/heads/master.
Can I simply read the last non-empty line of this file and parse the commit hash from there? Any pitfalls I should look for? Any better ways? It's safe to assume I have only one branch (master)
Thanks for any help!

A: To get the hash for the current (pointed to by the HEAD) commit:
git rev-parse HEAD

To get the hash for the last commit on master branch (in case you moved HEAD to a different commit using git checkout or git switch):
git rev-parse master


text:
Q: when using Microsoft.Devices.Radio class in my windows phone application will the radio play in background? i am using the radio class in my application
FMRadio myRadio = FMRadio.Instance;

            // Turn the radio on.
            myRadio.PowerMode = RadioPowerMode.On;
            myRadio.CurrentRegion = RadioRegion.Europe;

            // Set the frequency.
            myRadio.Frequency = 92.7;

will the application exit and the radio of my phone will appear or will it play in background??

A: Yes, it will play on the background when you exit your app.


text:
Q: NativeScript angular Bottom navigation bar hide and show in specific pages both ios and android I am trying to hide and show bottom navigation bar for nativescript angular app in both ios and android for specific pages of app. Using basic one that gets created by nativescript angular.
Bottom navigation used https://docs.nativescript.org/angular/ui/ng-components/bottom-navigation
steps:
tns create my-app
select angular
then select tabs view app for sample app.
Then run the app.
Replicate issue:
Basic tabs view app created by tns create command has home page with list of item. when you tap on a item navigates to item detail page.
On Item detail page I want to hide bottom navigation bar. Once user uses back navigation action to go back to home page the navigation bar should shown as normal.
Thanks in advance for help....


text:
Q: Ancient-Humanity true purpose in the Human-Forerunner war I just watched the Halo 4 terminals and one of them call my attention, I think the name is "Charum Hakkor" where the Lord of Admirals attacks a Forerunner planet because there was a flood infestation, the terminal description is Humanity true purpose, or something like that. Later in another terminal video there is the Librarian talking about discovering that actually the humans where attacking and fighting the Flood. Why did the humans never communicate with the Forerunners regarding the Flood menace?

A: Well, I suggest you that you need to check the "human-forerunner war" in Halopedia. To be short, the name you mention above is the capital planet of the human empire, which was captured after a 53-year long battle between the warrior-servant led by the Didact and the human forces. The reason why they didn't communicate was clear, in my opinion. Because from the very beginning, when the floods invaded, they expanded for survival and thus resulting in the total conflict between human and forerunner. If they were looking for help, they would have to accept the forerunner as their savior and ally, and eventually lose control with the power, which could lead to their overall destruction.

A: The forerunner saga books explained that while the humans were at war with the forerunners we were both also fighting the flood on second fronts. We were losing the war to the forerunners but we're beating the flood, while the forerunners were beating us but losing to the flood. Pretty sure that's why we were given the Mantle which pissed off the Didact because he saw us as being inferior and not worthy of it. So ya not much communicating of any kind going on at that point.


text:
Q: Especificar versão do Oracle Entity Framework Hoje estamos trabalhando com duas versão do banco oracle 12c e 11g.
O desenvolvimento é realizado na versão 12c.
Ao utilizar o Entity Framework para realizar um Count, o mesmo está aplicando uma função que não existe na versão 11g OUTER APPLY.
Existe alguma maneira de configurar o entity para que ele entenda qual versão do oracle o banco está? Ou mesmo que seja setar para que sempre utilize a versão 11g?
Desde já obrigado.


text:
Q: How can I make a bridge ethernet-wlan on Ubuntu server 18.04 (on raspberry Pi)? I would like to make a bridge between eth and wlan on my raspberry pi, which has Ubuntu server O.S.
I made this on Raspbian, so I guess it is possible. The idea is to get the information from some devices (sensors, mainly) through ethernet, and use the raspberry as an access point to get the sensors data from another PC via wi-fi. So the schema would be:
|Sensor Devices|  ---- eth ---->  |Raspberry Pi (Ubuntu)|  ---- wlan ---->  |PC|
How could I do this?
Thank you


text:
Q: Friends_interests/likes/etc return as blank from Facebook Graph API I've been messing around with the graph API and have been able to access my own information just fine. However, when I attempt something like:
https://graph.facebook.com/999999/likes?access_token=xxx (where 999999 is a friend's ID)
I get a blank graph like so:
{
   "data": [
]
}
Keep in mind I'm doing this all manually for the time being. This is the URL I used to request permission from my profile:
https://www.facebook.com/dialog/oauth?client_id=xxx&redirect_uri=http://www.google.com&scope=email,read_stream,offline_access,user_likes,friends_likes
It all works hunky-dory and I get my access code, yet I still receive the blank graph. Suggestions?
Thanks.

A: Have you tried multiple friends? Your friends can configure what information third party applications can have access to, of theirs. For example I could limit applications that you use to not see anything about me, if we were friends.
Also you could check in account --> privacy --> settings --> applications and see if your application in fact has the permissions you think you granted it as a user.
-Kevin

A: I agree with kevin.  You need to request permissions first to get at the info and you also need to be prepared that you will get a blank list.
I suggest that you use an already built api as it will save you a lot of time.  I've recently released one here that should get you going in no time at all.
The code looks like this:
Dim FB As New SessionInfo("[access_token]")
Dim Req = New Functions.Requests(FB)
Dim U = Req.GetUserInfo("[userid for friend]")
Response.Write(U.name)

Also you can get a list of friends by calling this
Dim FL = Req.GetFriends()
For Each F In FL
    Response.Write(F.name)
Next

A: I have come to notice that even though an application can request (and be granted) certain permissions, e.g. to access Likes, it doesn't necessarily mean that an application will be able to access this information.
I'm not a 100% certain of this but there might be two instances where e.g. requesting a users Likes results in an empty data set even though the right permissions where requested and granted by the user:

*

*The user has set custom permissions in his/her privacy settings
not make public the information (e.g. Likes). Basically, customized
permission settings overrule the granted permissions that an
application requested.

*The user is under 18. https://www.facebook.com/help/?page=214189648617074


text:
Q: xmpp openfire is not authenticating the php script I am using later for strophe attach I am trying to get SASL authetication for xmpp openfire server. after i run php script in curl. I do get the success packet from server as soon as passing the hash value.
but as i move forward bind the auth server gives me unauthorized error
i took some hint from https://groups.google.com/forum/#!topic/strophe/Y2n2dQ5oSoU
see output logs below:

<stream:features><mechanisms xmlns="urn:ietf:params:xml:ns:xmpp-sasl"><mechanism>DIGEST-MD5</mechanism><mechanism>JIVE-SHAREDSECRET</mechanism><mechanism>PLAIN</mechanism><mechanism>CRAM-MD5</mechanism></mechanisms><compression xmlns="http://jabber.org/features/compress"><method>zlib</method></compression><bind xmlns="urn:ietf:params:xml:ns:xmpp-bind"/><session xmlns="urn:ietf:params:xml:ns:xmpp-session"/></stream:features>

<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'>dGVzdDJAbGV0c3RhbGsudGVzdAB0ZXN0MgB0ZXN0Mg== </auth>

<success xmlns="urn:ietf:params:xml:ns:xmpp-sasl"/>

and here is when i move next for bind i get error 401 not authorized
<iq type='set' id='_bind_auth_2' xmlns='jabber:client'><bind xmlns='urn:ietf:params:xml:ns:xmpp- bind'/></iq>

<iq xmlns="jabber:client" type="error" id="_bind_auth_2" to="letstalk.test/102b0b8b"><bind xmlns="urn:ietf:params:xml:ns:xmpp-  bind"/><error code="401" type="auth"><not-authorized xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"/></error></iq>

<iq  type='set'id='_session_auth_2' xmlns='jabber:client'><sessionxmlns='urn:ietf:params:xml:ns:xmpp-session'/></iq><iq xmlns="jabber:client" type="error" id="_session_auth_2" to="letstalk.test/102b0b8b"><session xmlns="urn:ietf:params:xml:ns:xmpp-session"/><error code="401" type="auth"><not-authorized xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"/></error></iq>

A: From XMPP over BOSH specification:

Upon receiving the <success/> element, the client MUST then ask the
  connection manager to restart the stream by sending a "restart
  request"

so your next packet should look like this:


text:
Q: Tidyverse: using pivot_wide when data are dependent on multiple columns I searched similar questions but couldn't find an answer to what I am trying to achieve. I have a dataset that is set up like so:
ID    Trial   Treatment   Frequency  Value
A       1      Control    8000       65.1
A       1      Top        8000       62.8
A       1      Bottom     8000       60.3
A       1      Control    9000       63.1
A       1      Top        9000       66.2
A       1      Bottom     9000       69.8
A       2      Control    8000       67.6
A       2      Top        8000       63.4
A       2      Bottom     8000       71.9
A       2      Control    9000       59.7
A       2      Top        9000       63.3
A       2      Bottom     9000       57.2

Each ID (altogether there are 27) is subjected to three Treatment of playbacks of sounds at either 8000 or 9000 Hz (Frequency). The process is repeated twice, meaning there are multiple Trial.
I want to use pivot_wider on the Treatment column to end up with a table that looks like:
ID   Trial   Frequency   Control   Top   Bottom
A    1       8000        65.1      62.8  60.3
A    2       8000        67.6      63.4  71.9
A    1       9000        63.1      66.2  69.8
A    2       9000        59.7      63.3  57.2

Reproducible data:
df <- read.table(text="ID  Trial  Treatment   Frequency  Value
A       1      Control    8000  65.1
A       1      Top    8000  62.8
A       1      Bottom   8000  60.3
A       1      Control    9000  63.1
A       1      Top    9000  66.2
A       1      Bottom  9000  69.8
A       2      Control  8000  67.6
A       2      Top      8000  63.4
A       2      Bottom   8000   71.9
A       2      Control    9000  59.7
A       2      Top      9000  63.3
A       2      Bottom     9000  57.2", strin=F,h=T)

A: We could create an index column with rowid (if there duplicate elements for ID, Treatment) and then do the reshaping to wide format with pivot_wider
library(dplyr)
library(tidyr)
library(data.table)
df %>%
    mutate(rid = rowid(ID, Treatment))  %>%
    pivot_wider(names_from = Treatment, values_from = c(Value))
# A tibble: 4 x 6
#  ID    Trial Frequency Control   Top Bottom
#  <chr> <int>     <int>   <dbl> <dbl>  <dbl>
#1 A         1      8000    65.1  62.8   60.3
#2 A         1      9000    63.1  66.2   69.8
#3 A         2      8000    67.6  63.4   71.9
#4 A         2      9000    59.7  63.3   57.2

Or another option is to apply a function i.e. mean for the 'Value' column so that we get the average value for any duplicates
df %>%
    pivot_wider(names_from = Treatment, values_from = c(Value), values_fn = mean)


text:
Q: Help with Regular expression (PHP, preg_replace) I need to do a preg_replace on all of the PHP tags in a string, as well as any characters sitting between the PHP tags.
Eg, if the file contents was:
Hey there!
<?php some_stuff() ?>
Woohoo!

All that should be left is:
Hey there!
Woohoo!

Here's my code:
$file_contents = file_get_contents('somefilename.php');
$regex = '#([<?php](.*)[\?>])#e';
$file_contents = preg_replace($regex, '<<GENERATED CONTENT>>', $file_contents);

FAIL.
My regular expression skills are poor, can someone please fix my regex. Thank you.

A: Try this regex:
#<\?.*?\?>#

Should work on short tags (without 'php') too.
I think the main issue with your attempt was that you need to escape the question marks with backslashes, and that you were using square brackets where you shouldn't have been.  Square brackets means "pick any one of these characters".

A: $regex="/<?php (.*?)?\>/"

you can also try this this will work for you

A: You can try:
$regex = '#<\?php.*?\?>#i';

The regex used: <\?php.*?\?>

*

*< : a literal <

*\? : ? is a metachar to match a
literal ? you need to escape it.

*.*? : non-greedy to match anything.

A: Use the right tool for the job. The PHP tokenizer contains all the functionality you need to strip PHP code away from the surrounding content:
source.php

Some  HTML

<?php echo("hello world"); ?>

More HTML

<?php
/*
 Strip this out please
 */
?>

Ok Then

tokenize.php
<?php
$source = file_get_contents('source.php');
$tokens= token_get_all($source);
foreach ($tokens as $token) {
 if ($token[2] == 3 || $token[2] == 1 || $token[2] == 9) {
    echo($token[1]);
 }
}

Output:

Some  HTML

More HTML

Ok Then

This is a simple example. The docs list all the parser tokens you can check for.


text:
Q: Expected value of power of random variable less than infinity implies $X_n = o(n^{1/p})$ I have a fair background in probability but am very inexperienced when it comes to limiting behavior of random variables. This being the case, I request some guidance for this problem:
If $\{X_n\}^\infty_{n=1}$ are i.i.d., then prove that for all fixed $p > 0$,
E$\{|X_1|^p\} \leq \infty$ if and only if
$X_n = o(n^{1/p})$ a.s.
Based off what I read on wikipedia, it seems the last line is saying that as $n$ increases, $X_n$ is essentially increasing at log speed (and it seems like $p$ doesn't matter much here). I suspect the last line is a typo since each $X_n$ is i.i.d. Perhaps it instead should be $\sum_{i=1}^n X_n$ on the left hand side? Please let me know if my understanding is correct here, as well as if there is a typo.
With that out of the way, I am not sure how to proceed. Based on related examples in the book, I am led to believe that there is some well known inequality which can be applied here. From there, I don't know how to end up with the expression $o(n^{1/p})$. Is there a general course of action that may be taken with problems such as these?

A: $E|X_1|^{p} <\infty$ if and only if $\sum P(|X_1|^{p} > n) <\infty$. Applying this to $\frac {X_1} {\epsilon^{1/p}}$ we see that $E|X_1|^{p} <\infty$ if and only if $\sum P(|X_1|^{p} > \epsilon n) <\infty$. This is equivalent to the condition $\sum P(|X_n|^{p} > \epsilon n) <\infty$. By Borel-Cantelli Lemma this is true if and only if the probability that $|X_n|^{p} > \epsilon n$ for infinitely many $n$ is $0$. This is true for any $\epsilon >0$. Thus $E|X_1|^{p} <\infty$ if and only if $n^{-1/p}X_n \to 0$ almost surely.


text:
Q: The operator % is undefined for the argument type(s) int[], int I have a code but it shows the error The operator % is undefined for the argument type(s) int[],   int
public class Test {
public static void main(String [] args) {
    int[] n = {2,3,5,7};
    System.out.println(arePrimeFactors(n));
    }
    public static boolean arePrimeFactors(int[] n){
            boolean a = arePrimeFactors(n);
                        if (n%2==0) {
                            return false;
               for(int i=3;i*i<=n;i+=2) {
                        if(n%i==0)
                            return false;
        }
               return true;
            }}}

can you guys pls check I'm new to java
thanks

A: Because n is an array, you need to specify which element you are using your modulus operator on:
if (n[index] % 2 == 0) {
    //So stuff...
}

An array can contain multiple values at multiple indices, for example: n can range anywhere from {1, 6, 4, 2, 8} to {10245, 23451, 35312, 1}. You need to pass an index number into the brackets to specify which element you are using
Consider this:  If you had an array int[] i = {1, 2, 3, 4};and you wanted to reference the 2, than you would type i[1]. This is because in Java indexing starts at zero rather then one, so for the second element you would pass a 1 rather than a 2. This picture gives you an idea of what I mean:


text:
Q: JQuery Mobile list elements overly sensitive to taps I've noticed that when I have long list elements in JQuery Mobile and I try to scroll them, I accidentally select an element.  Overall the act of scrolling tends to get confused with tapping.
I did some comparison to a native iOS list and here is the difference:
In JQueryMobile, as long as you do a MouseDown and MouseUp on an element, it is considered a click.  It doesn't matter if you've scrolled inbetween the events.
In iOS, if you do a MouseDown on an element and then scroll at all, the MouseDown is effectively canceled.  This allows you to tap on something, scroll the page up and release without it being considered a click.
Has anyone noticed this and/or developed a patch for it?  If not, any suggestions on a fix?


text:
Q: Cargo build not generating the pkg directory on wasm project As mentioned in the title the cargo build fails to generate the pkg directory. I am following a tutorial where I run the command cargo build --target wasm-unknown-unknown which runs fine and I get no errors there. Then in my index.js file I would need to import the wasm file with the following statement: import './pkg/rust_3d_demo'. But there is no pkg directory generated after running the cargo build command. The tutorial is only 3 days old on youtube by Mr Doug Milford so there are no version issues here and my rustc and rustup and cargo are all up to date. Any thoughts on the matter? Much appreciated.
Here is my Cargo.toml file:
[package]
name = "rust-3d-demo"
version = "0.1.0"
authors = ["Steel"]
edition = "2018"

[lib]
crate-type = ["cdylib"]

[dependencies]
console_error_panic_hook = "=0.1.5"
js-sys = "0.3.19"
lazy_static = "1.3.0"
nalgebra = "0.18.0"
wasm-bindgen = "0.2.44"

[dependencies.web-sys]
version = "0.3.4"

features = [
'Document',
'Element',
'EventTarget',
'HtmlCanvasElement',
'MouseEvent',
'WebGlBuffer',
'WebGlProgram',
'WebGlRenderingContext',
'WebGlShader',
'WebGlUniformLocation',
'Window'
]

and the devDependencies section in my package.json file here:
"devDependencies": {
"@wasm-tool/wasm-pack-plugin": "^1.1.0",
"html-webpack-plugin": "^3.2.0",
"text-encoding": "^0.7.0",
"webpack": "^4.41.5",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.10.1"
}

Other info that might help:
rustc --version => rust 1.40.0 (73528e339 2019-12-16)
rustup --version => rust 1.21.1
cargo --version => cargo 1.40.0

A: You use wasm-build via webpack.config.js this way:

*

*import the wasm-pack-plugin into the config file
const WasmPackPlugin = require("@wasm-tool/wasm-pack-plugin");

*add a new instance in the plugins section:
new WasmPackPlugin({ crateDirectory: path.resolve(__dirname, ".") })
After this the pkg directory is generated :)


text:
Q: Dictionary containing objects to be used in lock operations In cases where I have a non-thread-safe object (such as a NetworkStream) that needs to be accessed from multiple threads, is it safe to hold an object to be used for locking, to protect the non-thread-safe object, in the value of a ConcurrentDictionary (or regular Dictionary)?
i.e. that way, I could have multiple threads each attempting to write data to the client's NetworkStream, but only one allowed in at each time?
I'm assuming this is safe since object is reference type, but was hoping someone would be able to confirm.
Example using ConcurrentDictionary.  The Send() method would be called by the multiple threads.  The goal is to allow multiple callers to have write access to the NetworkStream and my curiosity is whether or not the object found in the value of the ConcurrentDictionary can be used reliably in this case for locking.
// Assume this is prepopulated
private ConcurrentDictionary<string, object> locks = ...

public void Send(string identifier, byte[] data)
{
  object clientLock = null;
  if (locks.TryGetValue(identifier, out clientLock))
  {
    lock (clientLock)
    {
      // assume we have the TcpClient here
      NetworkStream ns = client.GetStream();
      ns.Write(data, 0, data.Length);
    }
  }
}

A: In this case the Dictionary and the mutex in general might be unessesary. Normally you use a private object mutex, to avoid deadlocks. That way no other code can try to aquire on lock on this. But in this case both the mutex object and the stuff it is for are de-facto public.
If every thread is capable of running lock/unlock on both the ClientStreams and the mutex object, they do not fullfill their purpose. You could just lock on the "ClientStream" instance whatever that is.
Alternatively, make a class, struct or tupel with the types object and ClientStream. That way you have both the Mutex and hte ClientStream together at least.

A: Just tested and it works as expected.  Thanks everyone for the lively conversation.  When running the sample code below, Worker2 is delayed.
    static ConcurrentDictionary<string, object> locks = new ConcurrentDictionary<string, object>();

    static void Main(string[] args)
    {
        locks.TryAdd("foo", new object());
        Task.Run(() => Worker1());
        Task.Run(() => Worker2());
        Console.ReadKey();
    }

    static void Worker1()
    {
        object lockObj = null;
        locks.TryGetValue("foo", out lockObj);
        lock (lockObj)
        {
            Console.WriteLine("Worker1");
            Thread.Sleep(10000);
        }
    }

    static void Worker2()
    {
        object lockObj = null;
        locks.TryGetValue("foo", out lockObj);
        lock (lockObj)
        {
            Console.WriteLine("Worker2");
        }
    }


text:
Q: Does Stargate REST API support Cassandra batch query? Does Stargate rest api support batch query in Cassandra (DSE 6.8)? If any, can you provide me an example?

A: Batch queries are not supported at this time but we do have the following issue for adding the functionality
https://github.com/stargate/stargate/issues/821


text:
Q: When creating database model edmx files, Visual Studio 2k10 doesn't list all stored procedures I'm having a really hard time with Visual Studio 2010.  I have a SQL database I am programming against with Entity Framework.  Most of the SQL code is simply executing stored procedures, which Entity Framework excels at.
However, I'm having a problem.  When I click Update Model From Database, the Update Wizard intermittently fails to list all the stored procedures in the database.  I've created a stored procedure called sp_foo.  Sometimes, the Update Wizard will display and allow me to select it.  Sometimes, it behaves as if sp_foo does not exists.  I have absolutely no idea what is causing this.  I can always execute sq_foo in SQL Server Management Studio.
What could be going wrong?

A: Check your permissions on the database to see EF can see all stored procs.
I had a similar problem that I fixed that way.
You might have to run something like this.
If Exists (SELECT name FROM sys.database_principals WHERE name = 'UserName' ) GRANT EXECUTE ON [dbo].storedProcName TO [YourUserName]


text:
Q: Windows 10 & Internet Explorer 11 Wordpress passwords IE Saves passwords for all my Wordpress sites with one exception. Deleted the original settings in Credential Manager, username is saved but not the password.  Is this a Windows or Wordpress problem?

A: "Website passwords are maintained at Internet options > Content > Autocomplete settings not in credential manager – pun Dec 15 '15 at 6:09 "


text:
Q: How to convert array of events into HH:mm format I have an array with start and end called blockedTime. How can I convert these elements into HH:mm format? I have also seen how people use momentjs library, but whenever I tried to use it I didn't get the answer I wanted
   const BlockedTime = [
    {
        start: "2021-04-19T09:30:00.0",
        end: "2021-04-19T10:00:00.0"
    },
    {
        start: "2021-04-19T14:00:00.0",
        end: "2021-04-19T14:30:00.0"
    },
    {
        start: "2021-04-19T16:00:00.0",
        end: "2021-04-19T16:30:00.0"
    }

]

A: You can loop through each item of the array and you can use format function from the moment and pass HH:mm. The rough code will look something like below.
import moment from "moment";
let time_data =  [ { start: "2021-04-19T09:30:00.0", end: "2021-04-19T10:00:00.0" },
{ start: "2021-04-19T14:00:00.0", end: "2021-04-19T14:30:00.0" },
{ start: "2021-04-19T16:00:00.0", end: "2021-04-19T16:30:00.0" }];

time_data = time_data.map(item=>({start_time : moment(item.start).format("HH:mm"),end_time : moment(item.end).format("HH:mm")}));
console.log(time_data)


text:
Q: Paypal Rounding Algorithm Does anyone know what algorithm Paypal uses to round? I'm doing some testing with discount promo codes on my site, and I'm coming up with different totals than what Paypal comes up with when I pass the same discount amount using the "discount_rate_cart" variable.
For example, a couple of items on my site total $309.95.  Applying a 10% discount ( 309.95 * .9 = 278.955) should yield a total of $278.96, as .955 should round up to .96. However, when I pass the total $309.95 and the 10% discount to PayPal, they come up with a total of $278.95. They rounded down when they should have rounded up.
Does anybody know why this is happening? Please note, I'm not doing anything fancy like currency conversion here, just simple algebra for giving discounts on the total cost of the shopping cart.

A: So the algorithm is banking rounding but on a transaction by transaction basis. This means the discount is a transaction of its ow e.g.
10% of $309.95 is $30.995 and bank rounding is to the nearest even number being $31.00.
Therefore:
 $309.95
-$ 31.00
========
 $278.95

So theoretically if you had a discount of $30.987 this will round to $30.98 not $30.99.


text: Q: How does ForeFront UAG implement single sign-on? One feature of Forefront is the ability to pre-authenticate external users before their requests are sent to a published web application.  In addition, it is supposed to be able to forward the accepted credentials to the web application (according to technet).  How specifically are these credentials passed?  Are they in a header?  Are they sent with every request, or just the first?


text:
Q: Can't find Hibernate's SessionFactory in my Glassfish app server I'm just playing around with implementing Hibernate as persistence provider in Glassfish application server. I already configured JNDI datasource, connection pool etc. My Hibernate config is as follows:
        <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
    <hibernate-configuration>
      <session-factory>
        <property name="hibernate.connection.datasource">jdbc/myDatasource</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.connection.factory_class">net.sf.hibernate.transaction.JTATransactionFactory</property>
        <property name="hibernate.session_factory_name">hibernateSessionFactory</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.hbm2ddl.auto">validate</property>
        <property name="hibernate.current_session_context_class">thread</property>

        <mapping class="org.me.jsf.entities.Node" />
      </session-factory>
</hibernate-configuration>

When I try to use Session Factory this way:
    try {
        sessionFactory = (SessionFactory) new InitialContext()
                .lookup("hibernateSessionFactory");
    } catch (Throwable ex) {
        throw new ExceptionInInitializerError(ex);
    }

I get an exception "ExceptionInInitializerError", caused by, according to the logs,  "Lookup failed for 'hibernateSessionFactory'". But when I use this code:
    try {
         AnnotationConfiguration cfg = new AnnotationConfiguration();
         cfg.configure();
         sessionFactory = cfg.buildSessionFactory();
    } catch (Throwable ex) {
         throw new ExceptionInInitializerError(ex);
    }

...everything goes fine.
What I got wrong here? I even tried to make an entry for managed bean hibernateSessionFactory for relevant class in faces-config.xml, but still no luck...

A: Presence of hibernate.session_factory_name means that session factory will be bound to JNDI when created, but you still to execute a code that creates it during startup. From Hibernate documentation:

Hibernate will automatically place the SessionFactory in JNDI after you call cfg.buildSessionFactory(). This means you will have this call in some startup code, or utility class in your application, unless you use JMX deployment with the HibernateService (this is discussed later in greater detail).


text:
Q: PHP Mapper Pattern, many to many relationships When using the mapper pattern, what is the best practice for defining classes for many to many relationships.
For example, let's say we have tables for Products and Categories and Product_Categories
Here are some basic skeletons for Products and Categories.  Each has an object class and each has a Mapper.
Product Object & Product Mapper:
class Product
{
    public $product_id;
    public $name;

    public function __construct($product_id = false, $name = false)
    {
        $this->product_id = $product_id;
        $this->name = $name;
    }
}

class Product_Mapper
{
    private $_db;

    public function __construct($_db) {}

    public function getProducts() {}
    public function getProductById($product_id) {}
    public function insert(Product $product) {}
    public function save(Product $product) {}
    public function update(Product $product) {}
    public function delete(Product $product) {}
}

Category Object and Category Mapper
class Category
{
    public $category_id;
    public $name;

    public function __construct($category_id = false, $name = false)
    {
        $this->category_id = $category_id;
        $this->name = $name;
    }
}

class Category_Mapper
{
    private $_db;

    public function __construct($_db) {}

    public function getCategories() {}
    public function getCategoryById($product_id) {}
    public function insert(Category $category) {}
    public function save(Category $category) {}
    public function update(Category $category) {}
    public function delete(Category $category) {}
}

What's missing here is the ability to add products to categories and update/delete/select products from categories, etc.
Would it be going against this pattern, to create a methods within Product_Mapper called addCategory, deleteCategory, getProductsByCategoryId or would you create a new object with mapper called Product_Categories that would handle those functions?
Really appreciate any feedback. I could see either way being suitable, but without creating a new class, I could also see the product class becoming bloated as new relationships are built.

A: Regarding this particular point:

Would it be going against this pattern, to create a methods within Product_Mapper called "addCategory", "deleteCategory",

Yes, and no. It really has nothing to do with DataMapper.
Those should be considered Product methods; eg:
$oProduct->addCategory( $oCategory );

Then, when you save the product with the datamapper, the datamapper will add the relationship between that product and that category you added to it.
$oProductMapper->save( $oProduct );

A: I believe the idea of the DataMapper pattern is to convert the schema of DB to your inner schema. So you can forget about the third database table that connects products and categories. Thereby you should create methods like Category_Mapper::getCategoriesByProductId and Product_Mapper::getProductByCategoryId.
So, user uses Category and Product classes, they use Mappers, and Mapper can use some common class if you want.
I can't be sure about all this but it seems to be reasonable.


text:
Q: How can I search the entire SQL database for a specific column name, and then search only those columns for a specific value? At work, we use an absolutely massive database with multiple different programs writing to the main bucket. Unfortunately, there's not always a good way to know from those individual programs where specific data points might be written to the database. I have a query that can search everything for a specific value or string, but because of the size of the database, it usually takes about 7 hours to complete.
I thought that if I could narrow the search a bit, I might be able to speed that up. A lot of the values I often have to look up would be under similarly named columns (i.e. "UserName", "UserID", etc.) Is there a good way to do a search that looks through all of my tables for a specific column name, and then searches only those columns for the value that I'm trying to locate?
I found a similar question asked a few years back
Search sql database for a column name, then search for a value within the retuned columns
but when I run the answer, all it returns is "Command(s) completed successfully."
I'm still a little green at this, so I'm not discounting the fact that it could be a PICNIC issue on my end.


text:
Q: Question about computer engineering circuits (noob question) I'm currently self learning computer engineering stuff right now and I was wondering how RAM would work in terms of input and output and I stumbled upon this image

I think it's somewhat wrong from what I know so far. The data bus is used for reading and writing. Wouldn't that cause a short circuit? It means that there are logic gates facing outwards from the RAM towards the databus and if the CPU were to send a certain byte, the current would flow towards the output of the logic gate?
I'm not so sure if I'm right, but I did use digital which is a logic circuit simulator, and whenever I connect a button to an output such as this one

It would cause a short circuit apparently. I researched a bit about that and I learned that short circuits occur whenever there's a mix of  a hot wire and a neutral wire, which I believe in computing corresponds to two output circuits with 1 and 0 on the same wire.

A:
The data bus is used for reading and writing.

Correct.

Wouldn't that cause a short circuit?

No. The circuits are are arranged so that only one device is asserting a signal onto the data lines at any instant. The others are all just "watching" the data lines and can read the logic level.

... the electricity would move towards the output of the logic gate?

We would say, "current will flow from the logic high device to the logic low device".

... it would cause a short circuit apparently, ...

Short-circuit usually means that the current is taking a short-cut around the intended circuit. What you are describing is just a high current flow due to a conflict between two output devices - one trying to connect the line to V+ and the other to ground.

I researched a bit about that and i learned that short circuit occurs whenever there's a mix of a hot wire and a neutral wire ...

Live and neutral are terms used in mains AC wiring. Use "logic high" and "logic low" for digital circuits.

A: Memory chips (and many other parts that are used to drive a bus) have an "Output Enable" input.  Their output driver circuits are only active when that input is in its Active state-  otherwise, the data bus pins are inputs.
Normally, only one part connected to the data bus will have its Output Enable active.

A: The data pins on a RAM chip need to be "tristate".  A tristate pin can be output high, output low, or high impedance (input only).
Each RAM chip will need a number of state pins telling it what to do.  This will vary between memories, but there will some kind of "chip select" to tell the RAM chip when you are talking to it, rather than anything else, and a "read/write" pin to tell it whether you want to set the memory or read it.
When the chip is not selected, or if it's being written to, then all the data pins will be high impedance.  When the chip is being read, the pins will be high or low as required.


text:
Q: Explanation needed for this limit inferior Let $F$ be a non-negative continuous function. Is there someone who explain why from mentioned condition we have a sequence with those conditions?

From the condition $$\liminf_{\xi\to0}\frac{f(\xi)}{\xi^p}=0$$ there is a sequence $\{\theta_n\}\subseteq ]0,+\infty[$ such that $\lim_{n\to\infty} \theta_n=0$ and $$\lim_{n\to\infty} \frac{\sup_{|\xi|<\gamma_n} F(\xi)}{\theta_n^p}=0.$$ Indeed, one has $$\lim_{n\to\infty} \frac{\sup_{|\xi|<\theta_n} F(\xi)}{\theta_n^p}=\lim_{n\to\infty} \frac{F(\xi_n)}{\xi_{\theta_n}^p} \cdot \frac{\xi_{\theta_n}^p}{\theta_n^p} = 0,$$ where $F(\xi_n)=\sup_{|\xi|<\theta_n}F(\xi)$.

I know that $\lim\inf_{x\to 0^+}f(x)=\lim_{x\to 0^+}(\inf_{0<y<x}f(y))$.

A: Let $F(x)=x\sin^2{1\over x}.$ Then $$\liminf_{x\to 0}{F(x)\over |x|}=0,\qquad \sup_{|t|\le x}{F(t)\over |t|}=1$$


text:
Q: Unity XR - Controller based on VR Hands, Spins in random directions, should rotate the game object slowly in the direction of VR hands rotation I'm running into an issue with my Space Ship controller system, I'm using Unity XR to control the space ship based on the rotation of the XR Hands, however, when attached the Joystick in game goes crazy, as well as the Space Ship. I'm looking for a controller which gradually shifts the direction of the space ship, and then Joystick to mimic the input of the XR controller.
Example Video of What Goes Wrong:
Youtube - Issue with Game
Below is the script I have attached to the joystick collider:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using Unity.XR.CoreUtils;
using UnityEngine.XR;
using UnityEngine.XR.Interaction.Toolkit;

public class joystickControl : MonoBehaviour
{
    public Transform stick;
    public GameObject joyStick;
    [SerializeField]
    private Transform spaceShip;
    [SerializeField]
    private float forwardTilt = 0;
    [SerializeField]
    private float sideTilt = 0;
    [SerializeField]
    private float damper = 1000;
    private float roll = 0;
    private float pitch = 0;
    private float yaw = 0;
    public float rollCorrected;
    public float pitchCorrected;
    public float yawCorrected;
    private InputDevice hand;
    public XRNode inputSource;
    public GameObject handVector;
    private bool controlling;
    private bool triggerValue;

    void Start(){
    }

    void Update(){

        //This needs to have a deadzone and a limit, otherwise it gives too much control, and makes the ship uncontrolable.

        if(controlling){
            Debug.Log("Controlling");
            //hand.TryGetFeatureValue(CommonUsages.deviceAngularVelocity, out Vector3 handRot);
            Vector3 handRot = handVector.transform.eulerAngles;
            Debug.Log(handRot);

            pitch = handRot.x;
            if(pitch < 355 && pitch > 290){
                pitchCorrected =  Math.Abs(pitch - 360)/damper;
            }
            else if (pitch > 5 && pitch < 74){
                pitchCorrected =  pitch/damper;
            }
            roll = handRot.y;
            if(roll < 355 && roll > 290){
                rollCorrected =  Math.Abs(roll - 360)/damper;
            }
            else if (roll > 5 && roll > 290){
                rollCorrected  =  roll/damper;
            }
            yaw = handRot.z;
            if (yaw < 355 && yaw > 290){
                yawCorrected =  Math.Abs(yaw-360)/damper;
            }
            else if (yaw > 5 && yaw > 290){
                yawCorrected = yaw/damper;
            }
            Debug.Log(rollCorrected + " " + pitchCorrected + " " + yawCorrected);
            joyStick.transform.Rotate(pitchCorrected * damper, rollCorrected * damper, yawCorrected * damper);
            spaceShip.Rotate(0f, 0f, rollCorrected);
            spaceShip.Rotate(pitchCorrected, 0f, 0f);
            spaceShip.Rotate(0f, yawCorrected, 0f);
        }
    }
    void OnTriggerEnter(Collider other){
        if (other.CompareTag("PlayerHand")){
            InputDevice hand = InputDevices.GetDeviceAtXRNode(inputSource);
        hand.TryGetFeatureValue(CommonUsages.gripButton, out bool triggerValue);
            Debug.Log("JoyStickControl - Player Hand Collision");
            Debug.Log("JoyStickControl - triggerValue - " + triggerValue);
            if(triggerValue){
                controlling = true;
                Debug.Log("JoyStickControl - True");
            }
            else{
                Debug.Log("JoyStickControl - False");
            }
        }
    }
}

Thanks in advance for your help!