text:
Q: Best way to regenerate JWT in multipages app Let's say I authenticate users by JWT whose expiry time is in 25 minutes from creation. I create (and give the order to regenerate) the JWTs on LogIn.js file and, after login and JWT creation, the user is taken to file LandingPage.js. And later on the user might want to visit the page rendered by file Example1.js or Example2.js.
But what is the best way to keep regenerating the JWTs across the different pages/files? For instance, if I have a function on LogIn.js that keeps regenerating them even on LandingPage.js, it works until the user refreshes the page of LandingPage.js. And then the JWT is not regenerated anymore...
Thanks in advance! Any help would be much appreciated!
EDIT
The JWTs are generated on the server-side, not on the client-side. But before the JWT gets expired on the client, there is a function that calls the server to create a new JWT and store it on the client again. This function is the above mentioned one stored on LogIn.js


text:
Q: Pros/cons of running PulseAudio at 24 Bits to match hardware? Long-time lurker, first post - please be gentle.
I am trying to get my USB audio interface to reproduce bit-perfect audio. It is a Native Instruments Audio Kontrol 1, which is plug-and-play on my Ubuntu 14.04LTS system.
The sound card runs at 24-bit/192KHz natively, and while I can edit asound.conf to make it run at other sampling rates, only 24-bit depth is supported (not 16).
I understand that by default both ALSA and PulseAudio will downsample audio material to 16-bits/48KHz. I can edit the config files of each so that they run at 24-bit/48KHz instead. I understand that this will increase CPU overhead. Sounds good right?
I have two questions/reservations:
a.) It says here that ALSA automatically resamples all audio playback to 16-bit/48KHz . Does this override my card's settings in asound.conf ?
b.) If so, is running PulseAudio at 24 bits just a waste of overhead (Since PulseAudio uses ALSA as an intermediary layer to the soundcard)?
Thanks for any help you can provide!

A: a) In short: no. By default pulseaudio and alsa are configured for 44.1kHz 16-bit audio. However, if you configure pulseaudio to e.g. 48kHz and 24-bit audio, see below for details, that's the minimum your device will get assuming it's supported. E.g. I configured pulseaudio, and made no changes to alsa whatsoever, to feed my external USB DAC with a 96KHz and 24-bit audio stream. LED's on the DAC confirm it's getting the 96kHz (@24-bit) after the change.
b) Given the above, NA :).
On how to configure (pulseaudio): edit with sudo and your favorite editor /etc/pulse/daemon.conf and look for the following lines:
; default-sample-format = s16le
; default-sample-rate = 44100

uncomment by removing the ';' and change settings to your liking. E.g.:
default-sample-format = s24le
default-sample-rate = 192000

Then restart pulseaudio (with your user account, no sudo):
pulseaudio -k
pulseaudio --restart

You can confirm settings changed with:
pacmd list-sinks

and look for 'sample spec' for the 'sink' that corresponds to your Native Instruments device.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Do the electric and magnetic components of an electromagnetic wave really generate each other? Frequently when EM waves are taught, it is said that the change in electric field causes a change in the magnetic field, which then causes a change in the electric field, and so on and so forth.
But from my understanding of basic electromagnetics, it is not necessarily a changing electric field that creates a change in magnetic field, but instead an accelerating charge. and it is this charge that creates both the electric and magnetic field. Again, from my understanding, a changing magnetic field is not generated by a changing electric field, but instead just happens to always be present perpendicular to a changing electric field due to the laws of electromagnetism.
Am I wrong? Or is the "mutual generation" concept between the electric and magnetic components of an EM wave an actual thing?

A: Do the electric and magnetic components of an electromagnetic wave really generate each other?
No they don't. Like Andrea said, they're two "aspects" of the same thing. And like you said, it's an electromagnetic wave. See the wiki article for  electromagnetic radiation where you can read that "the curl operator on one side of these equations results in first-order spatial derivatives of the wave solution, while the time-derivative on the other side of the equations, which gives the other field, is first order in time". One's the spatial derivative, the other's the time derivative. If it was a water wave and you were in a canoe, the tilt of your canoe is E and the rate of change of tilt is B.
Frequently when EM waves are taught, it is said that the change in electric field causes a change in the magnetic field, which then causes a change in the electric field, and so on and so forth.
Yes, and the people who say this tend to say this is why electromagnetic waves don't need a medium. But they do need a medium. Space is the medium. It isn't a medium like water or the ground, but it isn't nothing. See LIGO and note that they're trying to detect a length-change in the arms of the interferometer. That's essentially space waving. Also see this where Robert B Laughlin talks about quantum vacuum and likens space to window glass rather than Newtonian emptiness.
and it is this charge that creates both the electric and magnetic field
IMHO you should avoid charge for now and stick to electromagnetic waves.
Is the "mutual generation" concept between the electric and magnetic components of an EM wave an actual thing?
No it isn't. Check out this Wikipedia article about Jefimenko's equations:
There is a widespread interpretation of Maxwell's equations indicating that spatially varying electric and magnetic fields can cause each other to change in time, thus giving rise to a propagating electromagnetic wave (electromagnetism). However, Jefimenko's equations show an alternative point of view. Jefimenko says, "...neither Maxwell's equations nor their solutions indicate an existence of causal links between electric and magnetic fields. Therefore, we must conclude that an electromagnetic field is a dual entity always having an electric and a magnetic component simultaneously created by their common sources: time-variable electric charges and currents".

A: This  plane polarized  wave from wikipedia may help

Electromagnetic waves can be imagined as a self-propagating transverse oscillating wave of electric and magnetic fields. This 3D animation shows a plane linearly polarized wave propagating from left to right. Note that the electric and magnetic fields in such a wave are in-phase with each other, reaching minima and maxima together.

It is plotting the mathematical functions, solutions of Maxwell's equations, that describe a propagating wave.
$$\text{electric field}: E = E_m\sin(kx - \omega t) \\\\\\\ \text{magnetic field}: B = B_m \sin(kx - \omega t) $$

To be consistent with Maxwell's equations, these solutions must be related by

$$\frac{E_m}{B_m} = c$$
$E$ and $B$ are perpendicular to each other and in synchrony growing and diminishing as the wave propagates. The statement

the change in electric field causes a change in the magnetic field, which then causes a change in the electric field, and so on and so forth

refers to this graphic, where electric and magnetic fields increase and decrease in synchrony.
The acceleration of charged particles generates electromagnetic waves and then the waves become independent of the source of the electric field that generated it and propagate according to the equations.
This is the classical framework.
In the quantum mechanical framework the wave is built up by an enormous number of photons generated by the accelerated  electrons in the antenna , but that is another story.

A:
"a changing magnetic field is not generated by a changing electric field, but instead just happens to always be present perpendicular to a changing electric field due to the laws of electromagnetism."

So ... it is due to but not caused by. What is the difference?
Short answer: it is not only "a thing" it is a correct thing.
This is much more clearly stated in the differential form of Maxwell's equations:
$$ \nabla \times \mathbf{E} = - \frac{\partial \mathbf{B}}{\partial t} $$
$$ \nabla \times \mathbf{B} = \mu_0 \left( \mathbf{j} + \epsilon_0 \frac{\partial \mathbf{E}}{\partial t}\right) \,.$$
And while magnetic fields can be cause by either current or changing electric fields, light will happily travel in charge-free regions of space, so there is no question at all about which term is at work in electromagnetic waves.

A: Maxwell's equations in vacuum are:
$$\nabla\cdot\mathbf{E} = 0$$
$$\nabla\cdot\mathbf{B} = 0$$
$$\nabla\times\mathbf{E} = -\frac{\partial\mathbf{B}}{\partial t}$$
$$\nabla\times\mathbf{B} = \frac{1}{c^2}\frac{\partial\mathbf{E}}{\partial t}$$
It's the last two of these that give rise to the interpretation that a changing magnetic field generates an electric field and vice versa. But you could always take the curl of both these equations, use the other two, and get simple, straightforward wave equations separately for $\mathbf{E}$ and $\mathbf{B}$:
$$\nabla^2\mathbf{E} - \frac{1}{c^2}\frac{\partial^2 \mathbf{E}}{\partial t^2} = 0$$
$$\nabla^2\mathbf{B} - \frac{1}{c^2}\frac{\partial^2 \mathbf{B}}{\partial t^2} = 0$$
While these wave equations mean that $\mathbf{E}$ and $\mathbf{B}$ propagate as ordinary waves, they are still constrained by the original relations; we haven't magically made that dependence disappear.
So, while it is correct to say that changing magnetic and electric fields generate each other (simultaneously), it is also correct to say that each propagates as a wave of its own right, but is everywhere related to the other by the original Maxwell equations.
Indeed, when a charge is accelerating, it does generate both a changing electric and magnetic field at its position. You can then say that they both propagate out as ordinary waves, but (repeat) are always constrained by Maxwell's equations to be interdependent.

A: As you say, a changing magnetic field is always associated with a changing electric field, and in fact in relativity they are finally revealed to be the same field. So at this level it cannot be said that the one field generates the other, as they are merely two aspects of the same object.
But maybe you still want to look at it from the perspective of "naive EM", and see what sense one could make of the statement that one field generates the other.
Now, if you look at the fields of a
 plane wave at a fixed point in space, you'll see that they oscillate in sync, and both reach maximum and $0$ intensity at the same time. In fact what you could say is that increasing $E$ field is trying to reduce the $B$ field and the increasing $B$ field is trying to reduce the $E$ field. You could follow the appropriate equations and you'll see this is analogous to the equations of a vibrating membrane.
But the point is, that in fact the fields try to mutually reduce each other rather than generate. In fact they do that so well, that there is an overshoot, and the cycle repeats.
This dynamics turns out to make the energy flow through that point in space, to the fields in the neighbouring space. In fact, at some moments there is no EM field at that point, which means there is no energy at that field.
I guess the best description would be that a moving charge generates a disturbance in the electromagnetic field, in the sense that there is an energy transfer from its kinetic energy to the EM energy. This disturbance than propagates through space and time.

A: Jefimenko believed that time varying electric and magnetic fields did not cause one another because Maxwell's equations only give the relationship between the fields at the same instant in time. He said the equation for the E field did not predict a future value for the B field - it just tells you what the B field is if you know the E field. This is unlike the calculation of E and B fields from earlier charge positions and movements using the retarded field equations which are patently a causal relationship.
However, taking Maxwell's equation:-
$$\nabla\times\mathsf{E_{present}} = -\frac{\partial\mathsf{B_{present}}}{\partial t}$$
Re-write the rate of change of B as:-
$$\frac{B_{future}-B_{past}}{dt}$$
Substite this expression and re-arrange the terms in Maxwell's equation to give:-
$$B_{future}= B_{past}-dt{(\nabla\times\mathsf{E_{present}}})$$
Similarly using Maxwell's equation for curl B gives:-
$$E_{future}= E_{past}+c^2dt{(\nabla\times\mathsf{B_{present}}})$$
Written in this way the two Maxwell's equations are now seen to be predictive and causal. This is not just a mathematical trick as there is a numerical computational technique, known as the finite-difference time-domain (FDTD) method, which by alternately using each equation in a time stepping sequence can calculate exactly how the fields will propagate. It does not require any information about the charges or  currents which produced the initial fields, just the starting distribution of the electric and magnetic fields. An FDTD computer program provides a good demonstration of how the electric field generates a  magnetic field and the magnetic field generates an electric field.


text:
Q: How to make a file writeable for its owner? Linux newbie here, working on Debian Jessie.
Why does chmod u+w not make a file writeable for its owner?
I have run:
sudo chmod u+w /var/log/myapp/gunicorn-error.log

But now if I list the permissions on the file, it still doesn't seem to be writeable:
ls -al /var/log/myapp/
total 52
drwxr-xr-x  2 opuser webapps  4096 Sep  1 11:08 .
drwxr-xr-x 10 root   root     4096 Sep  1 11:24 ..
-rw-r--r--  1 opuser webapps     0 Aug 23 07:11 gunicorn-access.log
-rw-r--r--  1 opuser webapps 38639 Sep  1 11:15 gunicorn-error.log

What am I doing wrong?

A: Your presented command and related output seem fine; not too sure what you believe is going wrong. You simply issued this chmod command via symbolic mode:
sudo chmod u+w /var/log/myapp/gunicorn-error.log

And then this is the result:
-rw-r--r--  1 opuser webapps 38639 Sep  1 11:15 gunicorn-error.log

From left to right

*

*The first rw- is for the user/owner of the file.

*The next r-- indicates group permissions.

*The final r-- is permissions for others.

So knowing that, your chmod u+w succeeded because the user/owner has rw- permissions.
That said, if somehow your concern is about the group and other permissions, changing the permissions for the user/owner via symbolic mode does not negate existing permissions for the group and other permissions.
If you somehow want to set read and write for a user/owner but negate permissions for the group and others, you need to run a chmod with an absolute (octal) mode setting like this:
sudo chmod 600 /var/log/myapp/gunicorn-error.log

Which would result in permissions like this:
-rw-------  1 opuser webapps 38639 Sep  1 11:15 gunicorn-error.log

While harder to remember for most casual users, the main benefit of the absolute (octal) mode method is you can set multiple aspects of permissions in one command.
In contrast, symbolic mode makes setting permissions easier to read and remember, but you might need to issue a few symbolic mode commands in a row to achieve the same final result the absolute (octal) mode can achieve in one command.


text:
Q: Round only specific columns of matrix i am getting some output in Matlab as given below
   4.4033       1.2575       3.1456       2.9319
   7.8755       1.9982        4.873       2.2627
   5.3249       2.1254       2.3472       3.3858
   7.0089       2.7482       4.5202         4.73

i want to get output having first and second column as integer. I tried round function but i got following result
4       1       3     3
8       2       5     2
5       2       2     3
7       3       5     5

how do i get output as following form
   4   1   3.1456    2.9319
   8   2   4.873     2.2627
   5   2   2.3472    3.3858
   7   3   4.5202    4.73

A: Use linear indexing to select the columns you want to round, as simple as that:
A(:,1:2) = round( A(:,1:2) )


text:
Q: Acceso directo a cmd de windows con una ruta determinada Buenas nunca he realizado esto y es algo que estoy intentando y no lo consigo.
Quisiera, crear un acceso directo que vaya a la consola, y este en una carpeta concreta por ejemplo D:\proyecto\xxxx .
Así al acceder a ese SHORTCUT me abrirá la terminal en ese PATH.

A: Eso puedes hacerlo con un archivo .bat, no tanto con un acceso directo, crea tu archivo con:
D:
cd "D:\proyecto\xxxx"
cmd

Basicamente se ejecutan métodos del intérprete de comandos para hacer que cambie de unidad, cambie de directorio y ejecute el cmd.


text:
Q: Works, but is VERY slow... calling an XML with JS and then adding a JS function to the text from the XML I'm calling text from an XML file with JS and then adding a JS function to that text.  However, the response is very, very slow.  Is there a way I can improve this?
I have two XML files... one that I created, and then another from a database that was created with a flash program.  I want certain features on this flash program to highlight.  I have done this one of three ways:

*

*I manually enter the text in and use a JS to highlight the flash features onmouseover (speed is great, but I have to manually enter all of the text in  on the html page and will have to do this for EVERY single flash file (I am doing over 50)  Plus, the data will change frequently, and it would be better to have a single database document rather than going in to each flash file individually.

*I make a tag in the XML file that contains the JS and when I call it from the page, the entire list populates at once, but it is extremely slow to the point of taking several seconds on each mouseover of each text)

*I call the XML text with JS and add another JS function for the mouseover.  This works as well, but is very slow (however not as slow as #2, but still very slow) and the JS is very long as I have to call each text individually rather than populating the entire list as I did in #2
Here are the examples for 2 and 3:
XML for #2
<VIRGINIAREP>
        <DISTRICTS>
            <STATE>Virginia</STATE>
            <DISTRICT>1</DISTRICT>
            <REPRESENTATIVE>Robert J. Wittman</REPRESENTATIVE>
            <REPWEB>http://wittman.house.gov' onMouseOver='highlight1()' onMouseOut='highlight_clear()'</REPWEB>
            <PARTY>R</PARTY>
        </DISTRICTS>
        <DISTRICTS>
            <STATE>Virginia</STATE>
            <DISTRICT>2</DISTRICT>
            <REPRESENTATIVE>Scott Rigell</REPRESENTATIVE>
            <REPWEB>http://rigell.house.gov' onMouseOver='highlight2()' onMouseOut='highlight_clear()'</REPWEB>
            <PARTY>R</PARTY>
        </DISTRICTS>
        <DISTRICTS>
            <STATE>Virginia</STATE>
            <DISTRICT>3</DISTRICT>
            <REPRESENTATIVE>Robert C. Scott</REPRESENTATIVE>
            <REPWEB>http://www.house.gov/scott/' onMouseOver='highlight3()' onMouseOut='highlight_clear()'</REPWEB>
            <PARTY>D</PARTY>
        </DISTRICTS>..... etc.

JS for #2

The HIGHLIGHT FEATURE
function highlight() {
            theMap.features('DISTRICT="1"').highlight(
                {visible: true, fillColor: "#FFFF00", fillAlpha: 1.0}
            );
        }

XML for #3
<VIRGINIAREP>
            <DISTRICTS>
                <STATE>Virginia</STATE>
                <DISTRICT>1</DISTRICT>
                <REPRESENTATIVE>Robert Wittman</REPRESENTATIVE>
                <REPWEB>http://wittman.house.gov</REPWEB>
                <PARTY>R</PARTY>
            </DISTRICTS> ...etc.

JS for #3
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.open("GET","113CongressC.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;

x=xmlDoc.getElementsByTagName("DISTRICTS");
i=0;

function displayREPS()
{
rep="" +(x[0].getElementsByTagName("REPRESENTATIVE")[0].childNodes[0].nodeValue) + "";
district=(x[0].getElementsByTagName("DISTRICT")[0].childNodes[0].nodeValue);
party=(x[0].getElementsByTagName("PARTY")[0].childNodes[0].nodeValue);

//2
rep1="" +(x[1].getElementsByTagName("REPRESENTATIVE")[0].childNodes[0].nodeValue) + "";
district1=(x[1].getElementsByTagName("DISTRICT")[0].childNodes[0].nodeValue);
party1=(x[1].getElementsByTagName("PARTY")[0].childNodes[0].nodeValue);
//3
rep2="" +(x[2].getElementsByTagName("REPRESENTATIVE")[0].childNodes[0].nodeValue) + "";
district2=(x[2].getElementsByTagName("DISTRICT")[0].childNodes[0].nodeValue);
party2=(x[2].getElementsByTagName("PARTY")[0].childNodes[0].nodeValue);

....etc.
//TXT

txt0=district + " -  " + rep + "  ("+ party + ")";
txt1=district1 + " -  " + rep1 + "  ("+ party1 + ")";
txt2=district2 + " -  " + rep2 + "  ("+ party2 + ")";
txt3=district3 + " -  " + rep3 + "  ("+ party3 + ")";
txt4=district4 + " -  " + rep4 + "  ("+ party4 + ")";
...etc

document.getElementById("showREPS").innerHTML=txt0 + "
" + txt1 +  "
" + txt2 + "
" + txt3 + "
" + txt4 + "
" + txt5 + "
" + txt6 + "
" + txt7 + "
" + txt8 + "
" + txt9 +  "
" + txt10 + "
";
}
</script>

I've also tried: <REPWEB><![CDATA[]]></REPWEB> for the XML
Any suggestion on how I can do this better and more efficiently with a fast speed?

A: I found the same problem with the XHR object in COM code.
When I use the responseXML method instead of the responseText, the xml document is very slow to find nodes with XPath queries.
I'm using MSXML6.

*

*use the responseText to get the entire text

*create a DOM document

*load the xml through the loadXML(string) method of the new DOM document

and voilà!Really faster! I don't why what kind of DOM document the XMLHTTPRequest creates on responseXML to get a so slowly DOM document but it is really faster to create a new one

A: I would consider using JSON format as opposed to XML. It is much faster to transmit (it is smaller in terms of bytes), also JSON is going to parse much quicker.


text:
Q: Which generic fast collection (set) provides getIndexFromValue or similar? I need a collection that is a set (no duplicate values) and provides quick insert times. I also need to be able to get the index of a value.
Pseudocode:
Set.Insert(value)
Set.GetIndex(value)

The position of the value relative to the other values doesn't matter, sorting isn't required.
Is there a C# generic collection that provides this functionality? Or is there a way to do it by combining different collection types?

A: You can use HashSet<T>  It doesn't allow duplicates and is fast.  http://msdn.microsoft.com/en-us/library/bb359438.aspx
If you want to get the index of a value, you could convert the HashSet into an array and use Array.IndexOf(value); however, the HashSet allows you to use the value itself as an index, so you may no longer have need of that.

A: I'm not sure why is that you'd need to do id = search[key] and if this is ideal but i'll just throw it here...
You could try OrderedDictionary.
It's not ideal (in terms of your search) - but internally it keeps the method IndexOfKey which does just what you need. Basically it's an implementation based on an ArrayList which keeps an array of items + you have Dictionary<> for fast access etc.
Source is easily found (but I won't link it here for obvious reasons) - and either you can use that - or adjust it.

A: You could make a wrapper around two Dictionarys
class MySet<T> {
    Dictionary<T,int> valToIndex;
    Dictionary<int,T> indexToVal;
    int curIndex;
    Add(T newItem) {
        curIndex++;
        valToIndex.Add(newItem, curIndex);
        indexToVal.Add(curIndex, newItem);
    }
    T this[int index] {
       get {
           return indexToVal[index];
       }
    }
    GetIndexOf(T value) {
        return valToIndex[value];
    }
}

Of course this isn't complete, but you get the idea. You will probably want to add more error checking.


text:
Q: Continue chaining on a many to many relationship using eloquent I have a many to many relationship between User and Subject. The following code fetches all subjects associated with that authenticated user.
$chosensubject = Auth::User()->usersubject;

What I would like to do is take only 4 subjects and no more. Is this possible without using the query builder? For example I would like my code to look something like this:
$chosensubject = Auth::User()->usersubject->take(4)->get();

I think this may be possible using Laravel 5 however I am using Laravel version 4.2

A: Change this:
$chosensubject = Auth::User()->usersubject->take(4)->get();

To this:
$chosensubject = Auth::User()->usersubject()->take(4)->get();

This is the same with Laravel 4 and 5.


text:
Q: How to pass file location in batch file I'm currently trying to create a batch file that has a file location pass to it within c++.
$(CURRENT_DIRECTORY)
^^ that variable currently holds the files location. So if you run
Command cmd(TEXT("$(CURRENT_DIRECTORY)")); it opens the file explorer to that files location.
Now I am creating a batch file, by doing
const char* batch_file_name = "filelocation.bat";{

std::ofstream batch_file(batch_file_name);
                batch_file <<
                    "set path_location=%1\n"
                    "%path_location%\n"
                    "cd %path_location%\n"
                    "pause\n";
            }

system("filelocation.bat " + TEXT("$(CURRENT_DIRECTORY)"));
That is how i'm trying to pass in the files location. Seems to throw an error though "expression must have integral or unscoped enum type". I've been trying to figure this out, but I'm am stuck. Any ideas to the solution?

A: "filelocation.bat " + TEXT("$(CURRENT_DIRECTORY)" is trying to concatenate two string literals (of potentially different types, depending on whether UNICODE is defined or not). That will not work.  Try this instead:
system((string("filelocation.bat ") + "$(CURRENT_DIRECTORY)").c_str());

Or:
system(("filelocation.bat " + string("$(CURRENT_DIRECTORY)")).c_str());

Or:
ostringstream oss;
oss << "filelocation.bat " << "$(CURRENT_DIRECTORY)";
system(oss.str().c_str());

Or, simply don't concatenate at all:
system("filelocation.bat $(CURRENT_DIRECTORY)");


text:
Q: How to keep 9 points of precision with double in C I've been reading about the issues with floating point precision in C. I need 9 points  of precision but as we can see this isn't working:
double d_lower = 0.123456789;
double d_upper = 123456789.0;
d_upper = d_upper + d_lower;
printf("d_upper: %.11f\n", d_upper);
// Outputs: d_upper: 123456789.12345679104
// Desired: 123456789.123456789

There are various posts about WHY this is happening on SO, such as these:
Why Are Floating Point Numbers Inaccurate?
Why can't decimal numbers be represented exactly in binary?
But I can't find any infomration on how to solve this problem? Is there a way to work around it? I need 9 points of accuracy, other people must have the same problem. Is it possible to make a union value that achieves this maybe?
My C skills are fairly basic so I can understand the problem but I can't see how to resolve it or work around it.


text:
Q: R/exams Problem deploying app to shinyapps.io I have developed a shiny app in which I use the function exams2blackboard from the R/exams package. I installed the package from http://R-Forge.R-project.org. When I go to publish it on shinyApps.io I receive the following error:

Error: Unhandled Exception: Child Task 980776811 failed: Error building image: Error fetching exams (2.4-0) source.  unable to satisfy package: exams (2.4-0)

Note: I used the R/exams version 2.4-0 from http://R-Forge.R-project.org following the recommendation at Blackboard not importing Blackboard.zip

A: Chapter 2.4 of the shinyapps.io user guide at https://docs.rstudio.com/shinyapps.io/getting-started.html#using-your-r-packages-in-the-cloud says:

Currently, the shinyapps.io service supports deploying packages installed
from CRAN, GitHub (both public and private repos), and BioConductor.
[...]
Support for R-Forge and other repos is on our backlog; please drop us a line
in the shinyapps.io Community
if the lack of support is a blocker for you.

Hence my interpretation is that you cannot install the R-Forge version easily. Possibly, you can install it from the R-Forge mirror on GitHub, though: https://github.com/r-forge/exams/tree/master/pkg/exams


text:
Q: Can I use NodeMailer in strongloop to send emails? I am trying to send email from strongloop. Am working in cloudnine platform online.
I tried using the simple code to send mail. But nothing is working.

A: Note that outgoing smtp is disabled on cloud9 (c9.io) for general usage. You can send to gmail addresses for testing or use the google, amazon, sendgrid, etc mailer APIs.

A: Here is a sample from a blog - http://strongloop.com/strongblog/robust-node-applications-error-handling/

Here is sample email alert template using nodemailer:

var nodemailer = require('nodemailer')
var transport = nodemailer.createTransport('SMTP', { // [1]
  service: "Gmail",
  auth: {
    user: "gmail.user@gmail.com",
    pass: "userpass"
  }
})

if (process.env.NODE_ENV === 'production') { // [2]
  process.on('uncaughtException', function (er) {
    console.error(er.stack) // [3]
    transport.sendMail({
      from: 'alerts@mycompany.com',
      to: 'alert@mycompany.com',
      subject: er.message,
      text: er.stack // [4]
    }, function (er) {
       if (er) console.error(er)
       process.exit(1) // [5]
    })
  })
}

Also which version of LoopBack are you using, see 2.0 release notes here - http://docs.strongloop.com/display/public/LB/LoopBack+2.0+release+notes
hth


text:
Q: Валидация данных в микросервисной архитектуре Я занимаюсь в данный момент проектированием микросервисной архитектуры. На данный момент у меня есть какое-то количество сервисов, которым нужны данные из другого сервиса
Допустим, сервис А, Б, С, Д. Всем им необходима информация из сервиса GEO, который содержит в себе информацию о странах, городах, таймзонах и яызках. Например, при создании данных в сервисе А мне необходимо проверить, что выбранная страна существует в системе (в сервисе GEO).
Придумал два решения:

*

*С помощью grpc / http / orleans делать запрос на GEO сервис и валидировать полученные айдишники стран

*При старте какого-либо сервиса получить данные из другого сервиса в локальную копию кэша (через те же http / grpc запросы), а в случае изменения этих данных реагировать на изменения с помощью azure service bus

В первом случае получаем сильную связанность сервисов, и рискуем получить каскадный отказ сразу кучи сервисов.
Во втором случае получаем намного менее сильную связанность за счёт того, что в случае выхода GEO сервиса из строя, у нас останется локальная копия в кэше.
От сюда возникает несколько вопросов

*

*Какой в данном случае выбрать подход

*Насколько хорошее второе решение с точки зрения архитектуры ?

*Есть вообще другие решения этой проблемы (может через саги), к-ые я не додумал ?

С orleans до этого не работал, поэтому вообще не уверен, правильно ли я решил его применять. Был бы благодарен, если бы мне объяснили, в каких кейсах его можно применять

A: На данный момент есть три базовых шаблона:

*

*Прямые вызовы другого микросервиса.

*Асинхронные вызовы с помощью брокера сообщений.

*Дублирование данных.

На мой взгляд, в вашем случае лучше всего подходит третий вариант. Допустим у вас есть объект Страна, который содержит свойства Название, Валюта, ЧислоЖителей. Когда новая страна заводится в вашу систему, то должно генерироваться событие вида ICountryCreated, содержащее искомый объект, и отправляться в брокер.
Допустим, сервису А нужны для работы название и валюта страны, тогда вы подписываете его на получение события создания новой страны и при потреблении делаете сохранение в своей локальной базе только нужных для него двух свойств. Таким образом, разные микросервисы будут обладать разными знаниями о стране и будет определённая избыточность данных, но, одновременно, единственным источником правды будет оставаться ваш гео-сервис. Это позволит вашим сервисам сохранить несвязаность и синхронно обрабатывать запросы, которые как-то завязаны на геоданные.


text:
Q: Problema de codificación con  estoy intentando pasar de un Java a otro los inputs de un form, tanto type="text", como type="file", el problema és que los inputs que són texto, al llegar al otro Java, las letras que llevan acento no las codifica bien entiendo, "Gijón" se convierte en "Gijón".
<form action="test.jsp" class="formular form form-horizontal well row" enctype="multipart/form-data" method="post" id="idFormUserReg" name="form1" novalidate>

                Short Name
                <input type="text" name="shortName"  id="idShortName" maxlength="30" class="input-large" value="<%=aShortCompanyName%>">

                Logo
                <input type="file" name="logoFile" id="idNameLogo">
                <input type="hidden" name="nameLogo" value="logo_<%=lIdClient%>.png">

</form

He intentado también poner enctype="multipart/form-data;charset=UTF-8", las inputs texto funcionan bién, pero el file no llega.
Hay alguna otra forma de hacer que lleguen todos bien? Gracias!


text:
Q: On an Android tab, how to show the text under the image? I have an Android application that uses tabs.
I already have the tabs, and the Activities correctly on the application.
My problem is that, when I add the text and image on the tab, the text appears over the image.(EXAMPLE)
What I want is the text to appear bellow the image. This happens either if I use the image or a selector.
I use this code to add the tab to the tabHost:
// Do the same for the other tabs
intent = new Intent().setClass(this, CategoryListActivity.class);
spec = tabHost.newTabSpec(getString(R.string.category_title)).setIndicator(getString(R.string.category_title), res.getDrawable(R.drawable.ic_category)).setContent(intent);
tabHost.addTab(spec);

Any ideas on how I can fix this?

A: I think the default behaviour is that (see some example here: http://mobileorchard.com/android-app-development-tabbed-activities/)
The recommended tab images are darkish to avoid that, using white and grey as font color.
To change that you will have to create custom tabs:
Custom tabs in android


text:
Q: How to correctly handle the case where iteration on a single element causes an error to be thrown? I have some code that decomposes a wave into it's component frequencies, and plots those components. Here is the plotting method:
    def plot_components(self):
        try:
            N = self.rate * self.time
            t_vec = np.arange(N) * self.period

            fig, axes = plt.subplots(len(self.components), 1)
            for i, wave in enumerate(self.components):
                axes[i].plot(t_vec, wave)
            plt.xlabel('Time')
            plt.ylabel('Amplitude')
            plt.show()
        except ValueError:
            print('plt_components: Encoder must be fit against composite wave before plotting')
            raise

This works fine if multiple wave components are returned. Sometimes, either the wave doesn't have any components except itself, or some times the algorithm can only identify a single component. In that case, a singleton wave makes up the list of components and I get this error:
TypeError: 'AxesSubplot' object is not subscriptable

I thought about handling this with another except statement:
except TypeError:
   axes.plot(t_vec, self.components[0])
   plt.show()

And this does work. However, I'm unsure if this is proper use of error handling? I'm a bit new to the idea of stopping/handling errors and want to know if what I did is okay in practice.
I guess my nervousness comes from wondering "What if another TypeError is thrown for a reason I didn't expect?"

A: You could add a small check after the plt.subplots line:
if len(self.components) == 1:
    axes = [axes]

In general, there is the EAFP coding guideline, programming for happy flow and catching exceptions is a valid coding style. You could wrap only the offending line in the try-except block if you are worried.


text:
Q: 30 days of code hackerrank day1 I was solving this hackerrank 30 days of code challenge. The code is below:
import java.util.*;

public class jabcexample1 {
    public static void main(String[] args) {
        int i = 4;
        double d = 4.0;
        String s = "HackerRank ";

        /* Declare second integer, double, and String variables. */
        try (Scanner scan = new Scanner(System.in)) {
            /* Declare second integer, double, and String variables. */
            int i2;
            double d2;
            String s2;

            /* Read and save an integer, double, and String to your variables.*/
            i2 = scan.nextInt();
            d2 = scan.nextDouble();

            scan.nextLine(); // This line
            s2 = scan.nextLine();

            /* Print the sum of both integer variables on a new line. */
            System.out.println(i + i2);

            /* Print the sum of the double variables on a new line. */
            System.out.println(d + d2);

            /* Concatenate and print the String variables on a new line;
            the 's' variable above should be printed first. */
            System.out.println(s.concat(s2));
        }
    }
}

In this code I added an extra line scan.nextLine(); because without it the compiler doesn't even notice the next line that is s2 = scan.nextLine();. Why compiler doesn't notice s2=scan.nextLine(); without writing scan.nextLine();?

A: This has nothing to do with the compiler and everything with how Scanner behaves.
If you read the Java docs you will see Sanner.nextLine() does

Advances this scanner past the current line and returns the input that
  was skipped. This method returns the rest of the current line,
  excluding any line separator at the end. The position is set to the
  beginning of the next line.

Now you may be wondering what is left after you called
i2 = scan.nextInt();
d2 = scan.nextDouble();

In this case it is the carriage return characters. Calling scan.nextLine() reads those character and sets the position to the beginning of the next line.


text:
Q: Sharing TCP socket between application in linux I want to share the existing TCP socket from the main application to the second one on the device and continue communication with the client. Applications work in the Linux system. I found in QAbstractSocket documentation that I should bind the socket with mode QAbstractSocket::ShareAddress, but I can't achieve a working example. I tried to share the socket using a socket descriptor or create a QTcpSocket object with the IP address and port.
The demo implementation server-side
[First application]
Reimplemented incomingConnection on the server:
void InternalTcpServer::incomingConnection(qintptr socketDescriptor)
{
    QTcpSocket *newSocket = new QTcpSocket();
    newSocket->bind(QHostAddress("0.0.0.0"), 0 , QAbstractSocket::ShareAddress);
    newSocket->setSocketDescriptor(socketDescriptor);

    this->addPendingConnection(newSocket);

    emit internalNewConnection();
}

The communication is correct and communication with client is possible.
[Second application]
Try opening the socket using socket descriptor in the second application on the device:
bool TransmitterServer::initSocket(qintptr socketDescriptor)
{
    m_tcpSocket = new QTcpSocket();
    m_tcpSocket->setSocketDescriptor(socketDescriptor);

    if(m_tcpSocket->state() == QAbstractSocket::ConnectedState){
        qDebug() << "Socket connected";
        return true;
    }

    qDebug() << "Socket doesn't connected.";

    return false;
}

Try opening the socket using the address and port in the second application on the device:
bool TransmitterServer::initSocket(QString peerAddress, QString peerPort)
{
    m_tcpSocket = new QTcpSocket();

    if(m_tcpSocket->bind(QHostAddress(peerAddress), peerPort.toInt(), QAbstractSocket::ShareAddress)){
        qDebug() << "Socket binded";
        return true;
    }else{
        qDebug() << "Can't bind socket " << m_tcpSocket->error();
    }
    return false;
}

Is it possible to achieve it on the server-side?


text:
Q: Basic jQuery bind I came to a point in my project where I am detecting arrow key presses and was using:
$(document).bind('keypress', function(event) {
    alert("Handler for .keypress() called.");
});

and was researching and found I could use this instead:
$(document).keypress(function() {
    alert("Handler for .keypress() called.");
});

I like the second one best, it looks cleaner. They appear to do the same thing. So...

*

*Why would I use .bind()?

*Don't these do the same thing?

A: The two examples you give do indeed do the same thing - both of which are pretty much deprecated as of jQuery 1.7
From http://api.jquery.com/bind/

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document.

These older methods of attaching an event handler required that the elements existed in the DOM when the event handler was attached. There are smarter (not to mention more efficient) ways of doing the same with more recent versions - and this is generally refered to as delegation. You should check out .on()

A: The .keypress() or any other similarly named function .click(), .hover() etc are just shorthands for the .on() function

A: The jQuery docs are your friend!

*

*.bind() is being deprecated, so as suggested here, you should not use it if you're using jQuery 1.7+.

*.on() is the preferred way of attaching event handlers in jQuery 1.7+.

*.keypress() is one of a number of "special", specific event attachers (most of which usually call .on() or .bind() anyway) and, according to the docs, may have different behavior across browsers, browser versions, and platforms.

Given the info on those three functions, your best bet should be to use .on().

A: It's mostly personal preference. You're right, they do both do the same thing... however, they've been deprecated in recent versions of jQuery
As Andrew mentioned in your comment, use on, not bind.
on gives you the additional benefit of being able to use the same function to bind delegate handlers for elements that may or may not exist at the time the bindings are initialized:
$('#someExistingElement').on('keypress', handler); //normal binding

$('#someExistingElement').on('keypress', '.some-child-element-that-doesnt-exist', handler); //delegate binding

Please excuse the horrendous class names and id's...demo purposes only :D


text:
Q: Tensorflow R-CNN very small object detection - optimal configuration for Scale and Aspect Ratio? Using Faster R-CNN with Resnet-101, I am trying to detect small objects in a fairly large image.
The size of the objects is typically 20x20 pixels, the image might be 2300x1700.
I'm currently using the following configuration for scale/aspect ratio:
first_stage_anchor_generator {
  grid_anchor_generator {
    scales: [0.25, 0.5, 1.0, 2.0]
    aspect_ratios: [0.25, 1.0, 2.0]
    height_stride: 8
    width_stride: 8
  }

What would be optimal values for scales and aspect_ratios in order to improve very small object detection?
Secondly, scale is also used in grid_anchor_generator. Could someone please explain which scale is used where (grid_anchor_generator or the .config file) and how the two are related?


text:
Q: Process.Threads does not contain the full list of threads spawned by a process My application starts a secondary Process (an exe file stored in the filesystem). This Process then spawns several Threads that perform long operations multicore.
I can see from ProcessExplorer the list of threads started by this Process:

In yellow, the Process that my application started, in red the "long" threads that this Process started by itself (note that their addresses starts from a DLL!).
In my C# code, I expect to see all of these threads using myprocess.Threads property (where myprocess is the Process started by my app). Instead, I see thread ID 18160 and others, but not the ones  highlighted in red. Why?
In general, as you see from the image the total count of threads is 43, while the size of myprocess.Threads is 30.

A: The implementation of Process.Threads returns all threads associated with this process, but they might be threads that are not necessarily owned by this process.
Process.Threads uses CreateToolHelp32Snapshot to collect the information on Win32.  The documentation of CreateToolHelp32Snapshot says:

To identify the threads that belong to a specific process, compare its
  process identifier to the th32OwnerProcessID member of the
  THREADENTRY32 structure when enumerating the threads.

The code that populates Process.Threads, however, doesn't check th32OwnerProcessID; it simply enumerates all threads.  You can see the code here:
if (NativeMethods.Thread32First(handleRef, thread))
{
    do
    {
       ThreadInfo threadInfo = new ThreadInfo();
       threadInfo.threadId = thread.th32ThreadID;
       threadInfo.processId = thread.th32OwnerProcessID;
       threadInfo.basePriority = thread.tpBasePri;
       threadInfo.currentPriority = thread.tpBasePri + thread.tpDeltaPri;
       threadInfos.Add(threadInfo);
    }
    while (NativeMethods.Thread32Next(handleRef, thread));
}

So, I assume you also see threads that are owned by other processes, but associated with your child process.


text:
Q: JSDoc adding real code in documentation Do you know if there is some sort of  tag in JSDoc? I need to add pieces of code in my documentation like this:
/**
 * This function does something see example below:
 *
 * var x = foo("test"); //it will show "test" message
 *
 * @param {string} str: string argument that will be shown in message
 */
function foo(str)
{
   alert(str);
}

I need the code in the comments to be displayed by JSDoc as code (if not syntax highlighted, at least like pre-formatted or something with grey background).

A: @example http://code.google.com/p/jsdoc-toolkit/wiki/TagExample
/**
 * This function does something see example below:
 * @example
 * var x = foo("test"); //it will show "test" message
 *
 * @param {string} str: string argument that will be shown in message
 */
function foo(str)
{
   alert(str);
}

A: You can put any HTML in JSDoc and it will be copied out. Heres an example of what I use:
/**
 * The ReplaceSlang method replaces the string "hi" with "hello".
 *
 *   <input type="button" value="Test" onclick="testFunc()" />
 * @param {String} str The text to transform
 * @return {String}
 */
exports.ReplaceSlang = function(str) {
  return str.replace("hi", "hello");
};

To make sure the button is not in the summary, add a sentence and a dot (.) before it.
You need to find some way to include your javascript file in the output of JSDoc so that they are loaded. (Your code otherwise does not exist as javascript in the output of JSDoc – you can modify the template for that : see JsPlate documentation)

A: Use

....

This is whats used in many official docs, and will for instance receive syntax hightlighting with some tools

A: For jsdoc3 ... seems to work just fine. It also keeps the code inline while adding in
 creates a paragraph (which is what it should do anyways). Browser support seems to be ok so I don't see any reason to not use it.

A: Jsdoc3 has a markdown plugin but it is turned off by default. Enable it the default config file ./node_modules/jsdoc/conf.json.EXAMPLE via ...
"plugins": [
    "plugins/markdown"
],

... and you have nice syntax support for docs, including for code.  Markdown uses three backticks (```) to demarcate code blocks. For to use the original example:
/**
* This function does something see example below:
* ```
* var x = foo("test"); //it will show "test" message
* ```
* @param {string} str: string argument that will be shown in message
*/

A: Using @example works for most cases, but HTML reserved characters need to be translated to literals: < > and so on, otherwise the HTML will be rendered and not displayed as code.


text:
Q: Regex and C++11, software or compiler wrong? i'm trying to create a complex software in C++ using Regular expressions... Now i'm doing some tests, but i've got runtime error. I tried gcc 4.7 on Ubuntu 12.04 64bit and latest CodeBlocks with compiler included (I think is MinGW porting of gcc 4.7). The Regular Expression is correct because i try that on this website http://gskinner.com/RegExr/ and work. They need to recognize and addition. This is the software:
#include <iostream>
#include <string>
#include <regex>
using namespace std;

string stringa;

int main()
{
        cin >> stringa;
        if (regex_match(stringa, regex("^[0-9]*\\+[0-9]*$", regex::ECMAScript))) //need to insert \\ to prevent escape sequence
        {
                cout << "Addition" << endl;
        }
        else
        {
                cout << "Not addition" << endl;
        }
        return 0;
}

When i run that, after insert input, i receive that error:
terminate called after throwing an instance of 'std::regex_error'
what(): regex_error     Annullato (core dump creato)

The problem is my code or compiler?


text:
Q: how to split one dataframe column string(letter and number) into 2 columns? to separate the letters and numbers I have a dataframe with this as index
Index(['LCOc1', 'LCOc2', 'LCOc3', 'LCOc4', 'LCOc5', 'LCOc6', 'LCOc7', 'LCOc8',
       'LCOc9', 'LCOc10', 'LCOc11', 'LCOc12', 'CLc1', 'CLc2', 'CLc3', 'CLc4',
       'CLc5', 'CLc6', 'CLc7', 'CLc8', 'CLc9', 'CLc10', 'CLc11', 'CLc12',
       'OQc1', 'OQc2', 'OQc3', 'OQc4', 'OQc5', 'OQc6', 'OQc7', 'OQc8', 'OQc9',
       'OQc10', 'OQc11', 'OQc12'],
      dtype='object', name='CLOSE')

I wish to create 2 column one with only letters and the other with only numbers, I tested with str.split and str.extract but haven't succeeded
Basically I want one new column with values like ['LCOc', 'LCOc', 'LCOc'] and another one  with values like [1,2,3.....11,12,1]
this is part of the dataframe with "CLOSE" as the index name
        2022-09-02
CLOSE
LCOc1        93.02
LCOc2        91.81
LCOc3        90.66
LCOc4        89.52
LCOc5        88.52
LCOc6        87.68
LCOc7        86.94
LCOc8        86.24
LCOc9        85.63
LCOc10       85.02
LCOc11       84.40
LCOc12       83.81
CLc1         86.87
CLc2         86.48
CLc3         85.90
CLc4         85.19
CLc5         84.41

A: You can use .str.extract with the index like this:
df[['letters', 'digits']] = df.index.str.extract('(\D+)(\d+)').to_numpy()

Output:
        2022-09-02 letters digits
CLOSE
LCOc1        93.02    LCOc      1
LCOc2        91.81    LCOc      2
LCOc3        90.66    LCOc      3
LCOc4        89.52    LCOc      4
LCOc5        88.52    LCOc      5
LCOc6        87.68    LCOc      6
LCOc7        86.94    LCOc      7
LCOc8        86.24    LCOc      8
LCOc9        85.63    LCOc      9
LCOc10       85.02    LCOc     10
LCOc11       84.40    LCOc     11
LCOc12       83.81    LCOc     12
CLc1         86.87     CLc      1
CLc2         86.48     CLc      2
CLc3         85.90     CLc      3
CLc4         85.19     CLc      4
CLc5         84.41     CLc      5

A: You can also use re package to extract and then assign them as your new indices (if that's what you wanted)
import re
df.index = [(re.search('[a-zA-Z]+', df.index[i])[0], re.search('[0-9]+', df.index[i])[0]) for i in range(len(df.index))]

or if you want to add them to your dataframe
df[['letters','digits']] = ([[re.search('[a-zA-Z]+', df.index[i])[0], re.search('[0-9]+', df.index[i])[0]] for i in range(len(df.index))])


text:
Q: A word for "technify"? Looking for a word to convey the meaning that you are going to develop a technology around something.
"Technify" is something I made up that embodies the concept quite well, but it's not a real word.
Can you think of any alternatives?

A: "Technify" is actually a real accepted word. In lexico.com:
technify
To make technical; to adopt or cause to adopt technology or technical methods.
A synonym can be "mechanize", although it doesn't clearly refer to the process of developing a technology.


text:
Q: Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience Quando eu incluo @Scripts.Render("~/bundles/jqueryval") na parte inferior em partialview recebo aviso no log:

Synchronous XMLHttpRequest on the main thread is deprecated because of
  its detrimental effects to the end user's experience.

Esse aviso aparece ao abrir modal bootstrap.
Preciso de @Scripts.Render("~/bundles/jqueryval") para validar os campos.
Aqui está o código simples em partialview:
@model Projeto.Models.ModeloModels
@using (Ajax.BeginForm("Ação", "Controller", new AjaxOptions{ OnSuccess = "OnSuccess"}))
    {
       @Html.AntiForgeryToken()
       @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        ...
    }
@Scripts.Render("~/bundles/jqueryval")

Ao remover linha: @Scripts.Render("~/bundles/jqueryval") o aviso desaparece. Alguém sabe o que pode ser esse problema ?

A: Resolvi o problema de outra maneira.
Removendo a linha :@Scripts.Render("~/bundles/jqueryval").
E adicionar esse código no javascript:
<script type="text/javascript">
    $("form").removeData("validator");
    $("form").removeData("unobtrusiveValidation");
    $.validator.unobtrusive.parse("form");
</script>


text:
Q: Oracle 'identifier myschema.mytable must be declared' Trying to run some sql in a pl/sql procedure.
Select field from schema.view;
I get a compile error
Error(22,18): PLS-00201: identifier 'schema.view' must be declared
From the error, it seems that my user does not have access to the table.  I can run the same statement in a query window.
Is there a permission I need to grant?
Thanks!

A: You need to grant the user running the procedure explicit permission on the table/view.  Granting it through a role will not work.
Regards
K

A: Yes.  Oracle doesn't consider permissions that you have from role membership when you are executing procedures, so it is likely that the user who owns the procedure was granted access to schema.view via a role.  You need to explicitly grant permissions for that object to the owner of the procedure.

A: The PLS-00201 exception seems a bit unusual to me, for the "privileges granted through a role not available in a stored procedure" problem.   As Steve Broberg and Khb have already pointed out, granting privileges directly to a user will resolve exception
ORA-00942: table or view does not exist.

(That's the exception I normally see when compiling a stored procedure, when the statement works outside the stored procedure, and i find that privileges are granted through roles.)
What's kind of peculiar is that the exception you are seeing is a PLS-00201 (That has me puzzled.)

Another workaround to the ORA-942 "no privileges through roles" issue is to define the procedure with invoker rights and use dynamic SQL:
create procedure foo authid current_user
is
  ln_cnt number;
begin
  execute immediate 'select cnt(1) from schema.view' into ln_cnt;
end;
/

I don't think this is the best approach (it has its own issues) but it is a workaround.
http://download.oracle.com/docs/cd/B28359_01/appdev.111/b28370/dynamic.htm


text:
Q: Ruby install aborted due to missing extensions: openssl, readline, zlib compilation error I'm using macOs Catalina. I'm trying to install older version of Ruby (1.9.3, 2.1.2) via rbenv.
However, I keep getting the errors below, when trying installing older version. *It was fine when installing 2.4 or newer.
I already try
brew install openssl
brew install readline
brew install zlib

as well as brew update.
I have everything installed and up-to-dated but still the errors below keeps coming up.
I also did tried to install with configure option
RUBY_CONFIGURE_OPTS="--with-readline-dir=`brew --prefix readline` --with-openssl-dir=`brew --prefix openssl`" rbenv install 2.1.2

Please let me know how I can fix this.

ruby-build: using readline from homebrew
BUILD FAILED (Mac OS X 10.15.7 using ruby-build 20201005)
Inspect or clean up the working tree at
/var/folders/80/ts3rxpm5199g71p1vm4xzydj03b4g3/T/ruby-build.20201113153529.74484.A9uFGC
Results logged to
/var/folders/80/ts3rxpm5199g71p1vm4xzydj03b4g3/T/ruby-build.20201113153529.74484.log
Last 10 log lines:
The Ruby openssl extension was not compiled.
The Ruby readline extension was not compiled.
The Ruby zlib extension was not compiled.
ERROR: Ruby install aborted due to missing extensions
Configure options used:
--prefix=/Users/username/.rbenv/versions/2.1.2
--with-openssl-dir=/usr/local/opt/openssl@1.0
--with-readline-dir=/usr/local/opt/readline
CC=clang
LDFLAGS=-L/Users/username/.rbenv/versions/2.1.2/lib
CPPFLAGS=-I/Users/username/.rbenv/versions/2.1.2/include

A: *

*ruby-build required clang 11 to install older version of ruby: GitHub comment link

*

*If clang is already updated to 12, you need to nuke it first: sudo rm -rf /Library/Developer/CommandLineTools (source GitHub comment)

*Then, install Command_Line_Tools_for_Xcode_11.5.dmg for clang 11 from official Apple Developers's website (required at least Free Apple Developer Account)

*Ensure openssl 1.0 is picked up while installing older version of ruby

*

*ruby-build installs appropriate openssl, eg. 2.1.2 build

*echo $RUBY_CONFIGURE_OPTS to ensure it's empty or set to use openssl@1.0

*If ruby-build still picks openssl 1.1, then you may explicitly brew install rbenv/tap/openssl@1.0 and RUBY_CONFIGURE_OPTS="--with-openssl-dir=$(brew --prefix openssl@1.0)" (source GitHub comment)

A: Hi I also kept running into this on 'Mac OS X 10.15.7 using ruby-build' I had to set both of the following variables at the same time before the rbenv install 3.0.1 command:
OPENSSL_CFLAGS=-Wno-error=implicit-function-declaration RUBY_CONFIGURE_OPTS=--with-readline-dir="$(brew --prefix readline)" rbenv install 3.0.1

The first one tells the compiler to ignore where functions are implicitly declared rather than erroring out when this happens. And the second tells ruby which readline to use (in this case the one installed trough homebrew).
p.s. I also had set the openssl to 1.1.1

A: I've had issues installing Ruby on both Intel and M1 Macs. What's worked 100% of the time is ruby-install:
# install ruby-install from source
wget -O ruby-install-0.8.5.tar.gz https://github.com/postmodern/ruby-install/archive/v0.8.5.tar.gz
tar -xzvf ruby-install-0.8.5.tar.gz
cd ruby-install-0.8.5/
sudo make install

# install via homebrew (macOS)
brew install ruby-install openssl@1.1 readline zlib

# install specific version
ruby-install ruby 3.1.2

# install specific version (macOS)
ruby-install ruby-2.7.2 -- --with-openssl-dir=$(brew --prefix openssl@1.1)

# list rubies
ruby-install

# update all rubies
ruby-install --update

Not sure how far it goes back, as the CDN/FTP has to exist, but for v2.7.* it appears to have a long tail. Did have a 404 with 2.1.2:
>>> Downloading https://cache.ruby-lang.org/pub/ruby/2.1/ruby-2.1.2.tar.xz into /Users/lance.stephens/src ...
--2023-01-05 14:40:04--  https://cache.ruby-lang.org/pub/ruby/2.1/ruby-2.1.2.tar.xz
Resolving cache.ruby-lang.org (cache.ruby-lang.org)... 151.101.1.178, 151.101.65.178, 151.101.129.178, ...
Connecting to cache.ruby-lang.org (cache.ruby-lang.org)|151.101.1.178|:443... connected.
HTTP request sent, awaiting response... 404 Not Found
2023-01-05 14:40:05 ERROR 404: Not Found.

!!! Download of https://cache.ruby-lang.org/pub/ruby/2.1/ruby-2.1.2.tar.xz failed!

Stable versions as of today:
λ ruby-install
Stable ruby versions:
  ruby:
    2.6.8
    2.7.4
    3.0.2
  jruby:
    9.3.4.0
  rbx:
    5.0
  truffleruby:
    22.1.0
  truffleruby-graalvm:
    22.1.0
  mruby:
    3.0.0


text:
Q: Binary Search Tree: How/if to handle unlucky insertion orders? I'm brushing up on fundamental algorithms and data structures.
A typical binary search tree insertion algorithm looks something like:
insert(newValue)
    if newValue is less than node.value:
        if lesser subtree exists:
            insert into lesser subtree
        otherwise:
            lesser subtree = new tree with newValue
    if newValue is greater than node.value
        if greater subtree exists:
            insert into greater subtree
        otherwise:
            greater subtree = new tree with newValue

With an unlucky insertion order, you can get a tree that is identical to a list:
insert(1)
insert(2)
insert(3)

Produces:
1
 \
  2
   \
    3

With a tree that is actually a list, searching will of course take linear time.
Is expected for a binary search tree implementation? Or would you expect the insertion function to do some sort of rebalancing?

A: You have two kind of binary search trees. First one that you have, in worst case it will take Linear time to insert and delete and this happends when you insert things in Increasing or decreasing order.
However this is simple binarysearch tree.
There  are also RedBlack Binary search trees or sometimes called 2-3 binary search tree because in every node you can have two values. This means that from every node you have red link or black link to other node.These are called balanced search tree because number of black edges are equal in each path(from source to depth). Here Binary search tree grows from downside but RedBlack search tree pops up a value when it's node is full(that's interesting).
Search and insert: This algorithm is a bit complex but it's complexity for insert and search is always ~logN.
Max height Max height of this tree is between log3N and logN:
Here is a trace how it works:


text:
Q: Chart JS Zoom Pan I am using the Chart JS Zoom/Pan Plugin (https://github.com/chartjs/chartjs-plugin-zoom) and was wondering if there is a way to disable it when there is no data present. The current basic options settings are
pan: {
    enabled: true,
    mode: 'x'
},
zoom: {
    enabled: true,
    mode: 'x'
}

A: Yes, you can change this by setting "enabled" to false and/or use chart.resetZoom() link

A: Try this:
// since myChart.update() is not working. You need to do this.

var myChartOptions = myChart.options; // need to store in variable.

// check data present
if (data.length > 0) {
    myChartOptions.pan.enabled = true;
    myChartOptions.zoom.enabled = true;
    myChart.options = myChartOptions; // update myChart.options.
}
else {
    myChartOptions.pan.enabled = false;
    myChartOptions.zoom.enabled = false;
    myChart.options = myChartOptions; // update myChart.options.
}


text:
Q: How to predicate for first occurrence on a fetchRequest I'm trying to find a way of predicating for the first occurrence of an event on a given day. So say an event occurs multiple times during the day (range 1-16), I only want it to return the first occurrence and then look for the next first occurrence on the following day.

A: You won't be able to do this with one fetchRequest; you'll need to do two.
For each day, just use a predicate to limit to occurrences after the beginning of that day, sort in ascending order of date, and fetch only one item:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
request.entity = [NSEntityDescription entityForName:@"YourObject" inManagedObjectContext:context];
request.predicate = [NSPredicate predicateWithFormat:@"date > %@", beginningOfDay];
request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES]];
request.fetchLimit = 1;

Of course, you'll want to check the item you get to make sure it's still on the same day. Then, repeat for the next day.


text:
Q: ibm rhapsody compilation i couldn't compile using ibm rhapsody; i have this error:
Building ------------  MainDefaultComponent.class   ------------
   Executing: "C:\Program Files (x86)\IBM\Rational\Rhapsody\8.0\Share\etc\jdkmake.bat" DefaultComponent.bat build

   Unable to compile

   Build Done

How can i fix it?

A: Have a look here:
Unable to run Rational Rhapsody due to "Unable to compile" error

A: hmm did you select proper JDK during installation of Rhapsody? it doesn't seem so.
Although some of tweaks mentioned above might work, I strongly suggest reinstalling your Rhapsody, because this tool makes many adjustments on internal scripts, based on the location of JDK you provide. good luck.


text:
Q: How to reduce memory use of fitted sklearn estimators I am fitting and persisting a bunch of scikit-learn models, which subsequently I need to deploy to production servers.
The joblib pickle object for some of the generated models (mostly for bagged estimators) takes a lot of space, in the order of 50MB (note that this is compressed data).
The memory consumption of these models is limiting how many different ones I can upload to a single production server.
For our workflow, fitting happens in our development machines (with plenty of cores and memory), but production runs in a tighter environment. Since once we deploy a model we are not interested in fitting anymore, just on predicting, I was wondering if I could prune the python object before persisting it, things like the features used for fitting (assuming they are not needed in the predict step).
So, the question is: is there an easy way of identifying elements of a fitted sklearn estimator that are not needed for calling the predict method and removing them from the class prior to persisting the object?
Additional clarifications
I am not concerned about disk space, just about system memory use; determining the amount of memory used by a single one is tricky so I used the pickled size as a proxy (in-memory size ranges around 3-7x the size of the pickle). The estimators that get uploaded to the production system can in principle be anything (we are building a Caruana-type ensemble out of them). The worst offenders are instances of MLPClassifier or RandomForestClassifier. Issue seems to be that for an estimator of a fixed "size" (say I fix the number of inputs and hidden layer neurons for a network) the size of the saved estimator seems to grow depending on the dataset I use to train it, which to me looks like some of the training data is being kept inside the instance object. Training data is not needed for a neural network or a random forest to make a prediction, so I would like to get rid of it if it is there.


text:
Q: How to load model with materials instead of textures OpenGl? I used the learnopengl model loading tutorial and their code to load their model. When I tried to load a different model it did not work. After reading online I learned that my model might not have textures and might have materials instead.
I read to use the following function in my Model class:
Material loadMaterial(aiMaterial *mat)
    {
        Material material;
        aiColor3D color(0.f, 0.f, 0.f);
        float shininess;

        mat->Get(AI_MATKEY_COLOR_DIFFUSE, color);
        material.Diffuse = glm::vec3(color.r, color.b, color.g);

        mat->Get(AI_MATKEY_COLOR_AMBIENT, color);
        material.Ambient = glm::vec3(color.r, color.b, color.g);

        mat->Get(AI_MATKEY_COLOR_SPECULAR, color);
        material.Specular = glm::vec3(color.r, color.b, color.g);

        mat->Get(AI_MATKEY_SHININESS, shininess);
        material.Shininess = shininess;

        return material;
    }

I am not sure where to call this and how to integrate this with the rest of my code.
Here is the rest of my code:
Model class:
#ifndef MODEL_H
#define MODEL_H

//#include <glad/glad.h>

#include <GL/glew.h>
#include <glm/glm.hpp>
#include <GLFW/glfw3.h>

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <stb_image.h>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>

#include "Mesh.h"
#include "Shader.h"

#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <map>
#include <vector>
using namespace std;

unsigned int TextureFromFile(const char *path, const string &directory, bool gamma = false);

class Model
{
public:
    /*  Model Data */
    vector<Texture> textures_loaded; // stores all the textures loaded so far, optimization to make sure textures aren't loaded more than once.
    vector<Mesh> meshes;
    string directory;
    bool gammaCorrection;

    /*  Functions   */
    // constructor, expects a filepath to a 3D model.
    Model(string const &path, bool gamma = false) : gammaCorrection(gamma)
    {
        loadModel(path);
    }

    // draws the model, and thus all its meshes
    void Draw(Shader shader)
    {
        for (unsigned int i = 0; i < meshes.size(); i++)
            meshes[i].Draw(shader);
    }

private:
    /*  Functions   */
    // loads a model with supported ASSIMP extensions from file and stores the resulting meshes in the meshes vector.
    void loadModel(string const &path)
    {
        // read file via ASSIMP
        Assimp::Importer importer;
        const aiScene *scene = importer.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs | aiProcess_CalcTangentSpace);
        // check for errors
        if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) // if is Not Zero
        {
            cout << "ERROR::ASSIMP:: " << importer.GetErrorString() << endl;
            return;
        }
        // retrieve the directory path of the filepath
        directory = path.substr(0, path.find_last_of('/'));

        // process ASSIMP's root node recursively
        processNode(scene->mRootNode, scene);
    }

    // processes a node in a recursive fashion. Processes each individual mesh located at the node and repeats this process on its children nodes (if any).
    void processNode(aiNode *node, const aiScene *scene)
    {
        // process each mesh located at the current node
        for (unsigned int i = 0; i < node->mNumMeshes; i++)
        {
            // the node object only contains indices to index the actual objects in the scene.
            // the scene contains all the data, node is just to keep stuff organized (like relations between nodes).
            aiMesh *mesh = scene->mMeshes[node->mMeshes[i]];
            meshes.push_back(processMesh(mesh, scene));
        }
        // after we've processed all of the meshes (if any) we then recursively process each of the children nodes
        for (unsigned int i = 0; i < node->mNumChildren; i++)
        {
            processNode(node->mChildren[i], scene);
        }
    }

    Mesh processMesh(aiMesh *mesh, const aiScene *scene)
    {
        // data to fill
        vector<Vertex> vertices;
        vector<unsigned int> indices;
        vector<Texture> textures;

        // Walk through each of the mesh's vertices
        for (unsigned int i = 0; i < mesh->mNumVertices; i++)
        {
            Vertex vertex;
            glm::vec3 vector; // we declare a placeholder vector since assimp uses its own vector class that doesn't directly convert to glm's vec3 class so we transfer the data to this placeholder glm::vec3 first.
            // positions
            vector.x = mesh->mVertices[i].x;
            vector.y = mesh->mVertices[i].y;
            vector.z = mesh->mVertices[i].z;
            vertex.Position = vector;
            // normals
            vector.x = mesh->mNormals[i].x;
            vector.y = mesh->mNormals[i].y;
            vector.z = mesh->mNormals[i].z;
            vertex.Normal = vector;
            // texture coordinates
            if (mesh->mTextureCoords[0]) // does the mesh contain texture coordinates?
            {
                glm::vec2 vec;
                // a vertex can contain up to 8 different texture coordinates. We thus make the assumption that we won't
                // use models where a vertex can have multiple texture coordinates so we always take the first set (0).
                vec.x = mesh->mTextureCoords[0][i].x;
                vec.y = mesh->mTextureCoords[0][i].y;
                vertex.TexCoords = vec;
            }
            else
                vertex.TexCoords = glm::vec2(0.0f, 0.0f);
            // tangent
            vector.x = mesh->mTangents[i].x;
            vector.y = mesh->mTangents[i].y;
            vector.z = mesh->mTangents[i].z;
            vertex.Tangent = vector;
            // bitangent
            vector.x = mesh->mBitangents[i].x;
            vector.y = mesh->mBitangents[i].y;
            vector.z = mesh->mBitangents[i].z;
            vertex.Bitangent = vector;
            vertices.push_back(vertex);
        }
        // now wak through each of the mesh's faces (a face is a mesh its triangle) and retrieve the corresponding vertex indices.
        for (unsigned int i = 0; i < mesh->mNumFaces; i++)
        {
            aiFace face = mesh->mFaces[i];
            // retrieve all indices of the face and store them in the indices vector
            for (unsigned int j = 0; j < face.mNumIndices; j++)
                indices.push_back(face.mIndices[j]);
        }
        // process materials
        aiMaterial *material = scene->mMaterials[mesh->mMaterialIndex];
        //std::cout <<"sizeee" << scene->mMaterials.size()<< std::endl;

        // we assume a convention for sampler names in the shaders. Each diffuse texture should be named
        // as 'texture_diffuseN' where N is a sequential number ranging from 1 to MAX_SAMPLER_NUMBER.
        // Same applies to other texture as the following list summarizes:
        // diffuse: texture_diffuseN
        // specular: texture_specularN
        // normal: texture_normalN

        // 1. diffuse maps
        vector<Texture> diffuseMaps = loadMaterialTextures(material, aiTextureType_DIFFUSE, "texture_diffuse");
        textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end());
        // 2. specular maps
        vector<Texture> specularMaps = loadMaterialTextures(material, aiTextureType_SPECULAR, "texture_specular");
        textures.insert(textures.end(), specularMaps.begin(), specularMaps.end());
        // 3. normal maps
        std::vector<Texture> normalMaps = loadMaterialTextures(material, aiTextureType_HEIGHT, "texture_normal");
        textures.insert(textures.end(), normalMaps.begin(), normalMaps.end());
        // 4. height maps
        std::vector<Texture> heightMaps = loadMaterialTextures(material, aiTextureType_AMBIENT, "texture_height");
        textures.insert(textures.end(), heightMaps.begin(), heightMaps.end());

        // return a mesh object created from the extracted mesh data

        return Mesh(vertices, indices, textures);
    }

    // checks all material textures of a given type and loads the textures if they're not loaded yet.
    // the required info is returned as a Texture struct.
    vector<Texture> loadMaterialTextures(aiMaterial *mat, aiTextureType type, string typeName)
    {
        vector<Texture> textures;
        for (unsigned int i = 0; i < mat->GetTextureCount(type); i++)
        {
            aiString str;
            mat->GetTexture(type, i, &str);
            // check if texture was loaded before and if so, continue to next iteration: skip loading a new texture
            bool skip = false;
            for (unsigned int j = 0; j < textures_loaded.size(); j++)
            {
                if (std::strcmp(textures_loaded[j].path.data(), str.C_Str()) == 0)
                {
                    textures.push_back(textures_loaded[j]);
                    skip = true; // a texture with the same filepath has already been loaded, continue to next one. (optimization)
                    break;
                }
            }
            if (!skip)
            { // if texture hasn't been loaded already, load it
                Texture texture;
                texture.id = TextureFromFile(str.C_Str(), this->directory);
                texture.type = typeName;
                texture.path = str.C_Str();
                textures.push_back(texture);
                textures_loaded.push_back(texture); // store it as texture loaded for entire model, to ensure we won't unnecesery load duplicate textures.
            }
        }
        return textures;
    }

};

unsigned int TextureFromFile(const char *path, const string &directory, bool gamma)
{
    string filename = string(path);
    filename = directory + '/' + filename;

    unsigned int textureID;
    glGenTextures(1, &textureID);

    int width, height, nrComponents;
    unsigned char *data = stbi_load(filename.c_str(), &width, &height, &nrComponents, 0);
    if (data)
    {
        GLenum format;
        if (nrComponents == 1)
            format = GL_RED;
        else if (nrComponents == 3)
            format = GL_RGB;
        else if (nrComponents == 4)
            format = GL_RGBA;

        glBindTexture(GL_TEXTURE_2D, textureID);
        glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
        glGenerateMipmap(GL_TEXTURE_2D);

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

        stbi_image_free(data);
    }
    else
    {
        std::cout << "Texture failed to load at path: " << path << std::endl;
        stbi_image_free(data);
    }

    return textureID;
}
#endif

Mesh class:
#ifndef MESH_H
#define MESH_H

//#include <glad/glad.h> // holds all OpenGL type declarations

#include <GL/glew.h>
#include <glm/glm.hpp>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>

#include "Shader.h"

#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <vector>
using namespace std;

struct Vertex {
    // position
    glm::vec3 Position;
    // normal
    glm::vec3 Normal;
    // texCoords
    glm::vec2 TexCoords;
    // tangent
    glm::vec3 Tangent;
    // bitangent
    glm::vec3 Bitangent;
};

struct Texture {
    unsigned int id;
    string type;
    string path;
};
struct Material {
glm::vec3 Diffuse;
glm::vec3 Specular;
glm::vec3 Ambient;
float Shininess;
};

class Mesh {
public:
    /*  Mesh Data  */
    vector<Vertex> vertices;
    vector<unsigned int> indices;
    vector<Texture> textures;
    unsigned int VAO;

    /*  Functions  */
    // constructor
    Mesh(vector<Vertex> vertices, vector<unsigned int> indices, vector<Texture> textures)
    {
        this->vertices = vertices;
        this->indices = indices;
        this->textures = textures;

        // now that we have all the required data, set the vertex buffers and its attribute pointers.
        setupMesh();
    }

    // render the mesh
    void Draw(Shader shader)
    {
        // bind appropriate textures
        unsigned int diffuseNr  = 1;
        unsigned int specularNr = 1;
        unsigned int normalNr   = 1;
        unsigned int heightNr   = 1;
        for(unsigned int i = 0; i < textures.size(); i++)
        {
            glActiveTexture(GL_TEXTURE0 + i); // active proper texture unit before binding
            // retrieve texture number (the N in diffuse_textureN)
            string number;
            string name = textures[i].type;
            if(name == "texture_diffuse")
                number = std::to_string(diffuseNr++);
            else if(name == "texture_specular")
                number = std::to_string(specularNr++); // transfer unsigned int to stream
            else if(name == "texture_normal")
                number = std::to_string(normalNr++); // transfer unsigned int to stream
             else if(name == "texture_height")
                number = std::to_string(heightNr++); // transfer unsigned int to stream

                // now set the sampler to the correct texture unit
            glUniform1i(glGetUniformLocation(shader.ID, (name + number).c_str()), i);
            // and finally bind the texture
            glBindTexture(GL_TEXTURE_2D, textures[i].id);
        }

        // draw mesh
        glBindVertexArray(VAO);
        glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0);
        glBindVertexArray(0);

        // always good practice to set everything back to defaults once configured.
        glActiveTexture(GL_TEXTURE0);
    }

private:
    /*  Render data  */
    unsigned int VBO, EBO;

    /*  Functions    */
    // initializes all the buffer objects/arrays
    void setupMesh()
    {
        // create buffers/arrays
        glGenVertexArrays(1, &VAO);
        glGenBuffers(1, &VBO);
        glGenBuffers(1, &EBO);

        glBindVertexArray(VAO);
        // load data into vertex buffers
        glBindBuffer(GL_ARRAY_BUFFER, VBO);
        // A great thing about structs is that their memory layout is sequential for all its items.
        // The effect is that we can simply pass a pointer to the struct and it translates perfectly to a glm::vec3/2 array which
        // again translates to 3/2 floats which translates to a byte array.
        glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), &vertices[0], GL_STATIC_DRAW);

        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW);

        // set the vertex attribute pointers
        // vertex Positions
        glEnableVertexAttribArray(0);
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0);
        // vertex normals
        glEnableVertexAttribArray(1);
        glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Normal));
        // vertex texture coords
        glEnableVertexAttribArray(2);
        glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, TexCoords));
        // vertex tangent
        glEnableVertexAttribArray(3);
        glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Tangent));
        // vertex bitangent
        glEnableVertexAttribArray(4);
        glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Bitangent));

        glBindVertexArray(0);
    }
};
#endif


text:
Q: Window's Service set to manual startup, but automatically starting I have a very strange thing happening on a Windows 10 machine.
I have a Windows service that is set startup manually. I wrote a script that starts the service when on the desktop. Basically a net start thing.
What happens is when I Log-off then log back on, the service automatically starts. I am using a "ForceAutoLogon" which bounces me off the logon screen right back in to windows, but it doesn't affect any of my other Windows 10 machines running the same service.
How is this possible? Has anyone seen anything like this before? Is there some setting in Windows or service that is preserving the state of the service?

A: This is a bug (or a hidden setting in windows). I have a service that I only start from the command line that is set to manual but Windows starts it if it was running when I shut down. It may be caused by that irritating fast boot thing that saves the PC state and does not do a proper reboot. I believe Microsoft forced this on users to discourage dual boot systems with Linux and Windows 10.

A: Event Viewer used to record information about the start of each service (https://stackoverflow.com/a/496675/704977), but apparently does not any longer.
Instead, you should be able to audit the security for a specific service using the Security Templates tool: http://windowsitpro.com/systems-management/access-denied-auditing-users-who-might-be-starting-and-stopping-services

*

*Open MMC and add a snap-in.

*Choose the Security Templates snap-in and add it to the Console.

*Create a new template and give it a name.

*Open the new template, double-click on System Services to view a list of the services on your computer.

*Double-click the troublesome Oculus service and click to enable Define this policy setting in the template.

*Click Edit Security.

*Click Advanced.

*Click Auditing.

*Click Add.

*Click Select a principal, make sure From this location is set to your computer, enter everyone, and click OK.

*Select Start, stop and pause under Basic Permissions.

*Click OK.

Now you'll right-click on the template and save it.
Next, add the Security Configuration and Analysis snap-in to the console, open (or create) a database, and import the template you just created into the database.
Now you'll be able to look in the Security Log for Event ID 560 indicating a success audit when the Object Name is the short name of the service you're tracing, and the logged accesses include the Start and Stop commands sent to that service.


text:
Q: Java: How to insert CLOB into oracle database I need to write an XML file content into oracle database where the column is of CLOB datatype.
How will I do that?

A: passing the xml content as string.
table1

ID   int
XML  CLOB

import oracle.jdbc.OraclePreparedStatement;
/*
Your Code
*/
 void insert(int id, String xml){
    try {
        String sql = "INSERT INTO table1(ID,XML) VALUES ("
                + id
                + "', ? )";
        PreparedStatement ps = conn.prepareStatement(sql);
        ((OraclePreparedStatement) ps).setStringForClob(1, xml);
        ps.execute();
        result = true;
        } catch (Exception e) {
        e.printStackTrace();
    }
  }

A: This code worked for me. I use ojdbc6-11.2.0.2.jar.
java.sql.Connection con;
javax.xml.bind.Marshaller marshaller;

Clob xmlClob = con.createClob();
try {
  try (Writer xmlClobWriter = xmlClob.setCharacterStream(1)) {
    m.marshal(jaxbObject, xmlClobWriter);
  } // xmlClobWriter.close();
  try (PreparedStatement stmt = con.prepareStatement("INSERT INTO table (xml) values(?)")) {
    stmt.setClob(1, xmlClob);
    stmt.executeUpdate();
  }
} finally {
  xmlClob.free();
}

A: Converting clob to string:
Clob clob=rs.getClob(2);
String str=(String)clob.getSubString(1,(int)clob.length());
System.out.println("Clob Data is : "+str);

A: The easiest way is to simply use the
stmt.setString(position, xml);

methods (for "small" strings which can be easily kept in Java memory), or
try {
  java.sql.Clob clob =
    oracle.sql.CLOB.createTemporary(
      connection, false, oracle.sql.CLOB.DURATION_SESSION);

  clob.setString(1, xml);
  stmt.setClob(position, clob);
  stmt.execute();
}

// Important!
finally {
  clob.free();
}

A: For this purpose you need to make the connection result set

ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE

Connection con=null;
//initialize connection variable to connect to your database...
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String query="Select MYCLOB from TABLE_NAME for update";
con.setAutoCommit(false);
ResultSet resultset=stmt.executeQuery(query);

if(resultset.next()){
oracle.sql.CLOB    clobnew = ((OracleResultSet) rss).getCLOB("MYCLOB");
PrintWriter pw = new PrintWriter(clobnew.getCharacterOutputStream() );
BufferedReader br = new BufferedReader( new FileReader( new File("filename.xml") ) );
String  lineIn = null;
while( ( lineIn = br.readLine() ) != null )
      pw.println( lineIn );
      pw.close();
      br.close();
}

con.setAutoCommit(true);
con.commit();
}

Note: its important that you add the phrase for update at the end of the query that is written to select the row...
Follow the above code to insert the XML file

A: You can very well do it with below code, i am giving you just the code to insert xml hope u are done with rest of other things..
import oracle.xdb.XMLType;

//now inside the class......
// this will be to convert xml into string

File file = new File(your file path);
FileReader fileR = new FileReader(file);
fileR.read(data);
String str = new String(data);

// now to enter it into db

conn = DriverManager.getConnection(serverName, userId, password);

XMLType objXml = XMLType.createXML(conn, str);

// inside the query statement put this code

objPreparedstatmnt.setObject(your value index, objXml);

I have done like this and it is working fine.

A: OUTDATED See Lukas Eder's answer below.

With about 100 lines of code ;-) Here is an example.
The main point: Unlike with other JDBC drivers, the one from Oracle doesn't support using Reader and InputStream as parameters of an INSERT. Instead, you must SELECT the CLOB column FOR UPDATE and then write into the ResultSet
I suggest that you move this code into a helper method/class. Otherwise, it will pollute the rest of your code.

A: I had similar issue. Changed one of my table column from varchar2 to CLOB.
I didn't needed to change any java code. I kept it as setString(..) only so no need to change set method as setClob() etch if you are using following versions ATLEAST of Oracle and jdbc driver.
I tried in In Oracle 11g and driver ojdbc6-11.2.0.4.jar

A: Try this , there is no need to set its a CLOB
  public static void main(String[] args)
        {
        try{

                    System.out.println("Opening db");

                    Class.forName("oracle.jdbc.driver.OracleDriver");
                    if(con==null)
                     con=DriverManager.getConnection("jdbc:oracle:thin:@192.9.200.103:1521: orcl","sas","sas");
                    if(stmt==null)
                    stmt=con.createStatement();

                    int res=9;

                    String usersSql = "{call Esme_Insertsmscdata(?,?,?,?,?)}";
                    CallableStatement stmt = con.prepareCall(usersSql);
            // THIS THE CLOB DATA
            stmt.setString(1,"SS¶5268771¶00058711¶04192018¶SS¶5268771¶00058712¶04192018¶SS¶5268772¶00058713¶04192018¶SS¶5268772¶00058714¶04192018¶SS¶5268773¶00058715¶04192018¶SS¶5268773¶00058716¶04192018¶SS¶5268774¶00058717¶04192018¶SS¶5268774¶00058718¶04192018¶SS¶5268775¶00058719¶04192018¶SS¶5268775¶00058720¶04192018¶");
                    stmt.setString(2, "bcvbcvb");
                    stmt.setString(3, String.valueOf("4522"));
                    stmt.setString(4, "42.25.632.25");
                    stmt.registerOutParameter(5,OracleTypes.NUMBER);
                    stmt.execute();
                    res=stmt.getInt(5);
                    stmt.close();

                    System.out.println(res);

                    }
                    catch(Exception e)
                    {

                         try
                         {
                            con.close();
                        } catch (SQLException e1) {

                        }
                    }
                }
    }

A: Take a look at the LobBasicSample for an example to use CLOB, BLOB, NLOB datatypes.


text:
Q: Vertical center each line in multi line edittext I have a multiline edittext with maxLines as 1. When the input exceeds more than one line, the previous lines entered shift by few pixels to top as shown in image 1 below.
How can i center vertical each line in edittext?

<EditText android:id="@+id/et"
    android:layout_width="match_parent"
    android:layout_height="30dp"
    android:layout_marginTop="50dp"
    android:paddingStart="10dp"
    android:paddingEnd="10dp"
    android:maxLines="1"
    android:inputType="textMultiLine|textNoSuggestions"/>

A: I figured it out:
You've set android:layout_height="30dp" and depending on the user phone's font size or your own app's it will show just part of it or have extra room like you had in your first picture:
change the EditText to:
<EditText
    android:id="@+id/et"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="50dp"
    android:paddingStart="10dp"
    android:paddingEnd="10dp"
    android:maxLines="1"
    android:inputType="textMultiLine|textNoSuggestions"
    />

I've tested it and worked fine, but let me know if it's not working for you.


text:
Q: Is there a way to allow default control painting, while adding my own painting? I was planning on creating a custom TrackBar class that implements from TrackBar.  I want it to look/feel EXACTLY the same, other than a display on the value just to the side of the track itself.
I've been seeing that you can either let the OS draw the control, or allow the user draw it, but then the user must draw EVERYTHING.  Is there a way for me to allow the OS draw the control, and then let me draw the value?
EDIT:
The key I want to emphasize is, I want to only add the drawing the value, rather than drawing the whole thing myself.


text:
Q: TLE in Word Search backtracking Here is a problem from Leetcode:
Given an m x n grid of characters board and a string word, return true if word exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
I did simple backtracking with dfs, here is my code:
class Solution {
public:
    bool exist(vector<vector<char>>& board, string word) {
        int index = 0;
        for(int i = 0; i < board.size(); i++) {
            for(int j = 0; j < board[0].size(); j++) {
                if(existsUtil(board, index, word, i, j))
                    return true;
            }
        }

        return false;
    }
    bool existsUtil(vector<vector<char>> board, int index, string word, int i, int j) {
        if(index >= word.length())
            return true;
        if(i < 0 || i >= board.size() || j < 0 || j >= board[0].size() || board[i][j] != word[index] || board[i][j] == '0')
            return false;

        char temp = board[i][j];
        board[i][j] = '0';
        index += 1;
        bool value = existsUtil(board, index, word, i + 1, j) || existsUtil(board, index, word, i, j - 1) || existsUtil(board, index, word, i - 1, j) || existsUtil(board, index, word, i, j + 1);
        board[i][j] = temp;

        return value;
    }
};

This code is giving TLE for larger inputs. But in the dfs function, if I pass the board parameter by referece, that is, if I pass vector<vector<char>> &board, it passes all test cases. Why is this happening?

A: *

*I guess, you can do one optimization on the code to start dfs only from position where (words[i][j] == word[0])

*Secondly answering your question when you pass by value every time a new copy of 2d array is created in recursive calls which gives the TLE.

*See My faster than 100% JAVA code, Hope this helps!
class Solution {
    boolean flag = false;
    public boolean exist(char[][] board, String word) {

        for(int i = 0;i < board.length;i++){
            for(int j = 0;j < board[0].length;j++){
                if(board[i][j] == word.charAt(0)){
                    backtrack(board,word,1,i,j);
                    if(flag) return true;
                }
            }
        }

        return false;
    }

    void backtrack(char[][] board, String word, int p, int row, int col){
        if(board[row][col] > 255)
            return;
        else if(p > word.length() - 1){
            //System.out.println(asf);
            flag  = true;
            return;
        }

        board[row][col] ^= 256;
        //up
        if(row > 0 && board[row-1][col] == word.charAt(p)) {
            backtrack(board, word, p + 1, row - 1, col);
        }
        //down
        if(row < board.length - 1 && board[row+1][col] == word.charAt(p))
            backtrack(board,word, p+1,row+1,col);
        //left
        if(col > 0 && board[row][col-1] == word.charAt(p))
            backtrack(board,word, p+1,row,col-1);
        //right
        if(col < board[0].length - 1 && board[row][col+1] == word.charAt(p))
            backtrack(board,word, p+1,row,col+1);

        board[row][col] ^= 256;

        return;
    }
}