text:
Q: Loading variable from php into javascript continuously I am currently trying to draw some dynamically loaded graphs using google's visualization tools.
I want to pull the data from an sql database. I have a php script (getnumber.php) that is capable of doing so.
I am trying to use this php script within my javascript that draws the graphs.
<html>
<head>
<!--Load the AJAX API-->
  <script type="text/javascript" src="https://www.google.com/jsapi"></script>
  <script type="text/javascript" src="jquery.js"></script>
  <script type="text/javascript">
  function drawChart(Z)
  {
    tmpdata = new google.visualization.DataTable();
    datalist.push(tmpdata);
    datalist[Z].addColumn('string', 'Complete');
    datalist[Z].addRows([['Finished', $.ajax({url:"getnumber.php"})], ['Incomplete', 10]]);
    .
    .
    .
  }
  window.setInterval("drawChart()", 1000);
</script>

I realise that this use of $.ajax is completely wrong but I'm stumped!

A: You should try using either $.post() or $.get() functions instead of using the basic ajax one. Anyways, you can manipulate the data in thsoe 3 functions this way
$.post('getnumber.php',function(data){
/* Do whatever you want with the data you grabbed from the php page. */
});

I'm not sure of what your question is exactly, but I hope this will help you.
Have a nice day!
EDIT: The functions themselves don't contain the data, it is contained into the function(data){} portion of the $.ajax() call.
Edit2: The $.ajax(); function has a parameter called success(data, textStatus, jqXHR)which can be used, compared to the two other functions.
http://api.jquery.com/jQuery.ajax/

A: I ended up using the following:
my_url="dosomething.php";
function getvar() {
  var json = null;
  $.ajax({
      'async': false,
      'global': false,
      'url': my_url,
      'dataType': "json",
      'success': function (data) {
          json = data;
      }
  });
  json = parseInt(json);
  return json;
};

With the php script ending with:
echo json_encode($id_max);
For some reason I could not get $.post to work. Thanks for the help anyway.


text:
Q: Does the force between two point charges change when inertial reference frame changes? The two point charges are as below:

Then the Coulomb force between them is:
$$F_1=\frac{q^2}{4\pi\epsilon_0 r^2}$$
When the inertial reference frame moves left at $v$(or the point charges move right at $v$), then there will be magnetic field according to Biot–Savart law.
The Lorenz force between the two point charge in the vertical direction will be nonzero. The magnitude of the Lorentz force is:
$$f_L=\frac{\mu_0 q^2v^2}{4\pi r^2}$$
In wiki on Lorentz force, it says that:

The electric and magnetic fields are dependent on the velocity of an observer, so the relativistic form of the Lorentz force law can best be exhibited starting from a coordinate-independent expression for the electromagnetic and magnetic fields,[27] \mathcal{F}, and an arbitrary time-direction

Considering $F_1$ and $f_L$ have opposite directions and optical velocity $1/c^2=\mu_0\epsilon_0$, the magnitude of the force $F_2$ between the two charges becomes:
$$F_2=F_1-f_L= \left(1-\frac{v^2}{c^2}\right)F_1$$
Am I right?

Per the calculation here, it is easy to obtain the time dilation factor $\displaystyle\sqrt{1-\frac{v^2}{c^2}}$ of an event that the two point charges separate to a distance of $r$.
The nonlinear ODE:

$$\dfrac{d^2r(t)}{dt^2}=\dfrac{\left(1-\dfrac{v^2}{c^2}\right)q^2}{2\pi m\epsilon_0\left(R+r(t)\right)^2}$$
with initial/boundary conditions
  $$r(t)=0,\quad r'(t)=0$$

Solution:
$$ \because\qquad\qquad\qquad\qquad\qquad\qquad\qquad $$
$$\int {\rm{Left }}\cdot dr=\int\frac{d^2r}{dt^2}\cdot {dr}=\int\frac{d\left(\dfrac{dr}{dt}\right)\cdot dr}{dt}=\dfrac{1}{2}\int d\left(\left(\dfrac{dr}{dt}\right)^2\right)=\dfrac{1}{2}\left(\dfrac{dr}{dt}\right)^2$$
$$\int{\rm Right}\cdot dr=\int\dfrac{\left(1-\dfrac{v^2}{c^2}\right)q^2 \cdot {dr}}{2\pi m\epsilon_0\left(R+r\right)^2}=\dfrac{\left(1-\dfrac{v^2}{c^2}\right)q^2 {r}}{2\pi m\epsilon_0\left(R+r\right)R}$$
$$\therefore \dfrac{dr}{dt}=\sqrt{\dfrac{\left(1-\dfrac{v^2}{c^2}\right)q^2 {r}}{\pi m\epsilon_0\left(R+r\right)R}}$$
$$\therefore{dt}=\sqrt{\dfrac{\pi m\epsilon_0\left(R+r\right)R}{\left(1-\dfrac{v^2}{c^2}\right)q^2 {r}}}dr$$
$$\therefore\int{dt}=\sqrt{\dfrac{\pi m\epsilon_0}{\left(1-\dfrac{v^2}{c^2}\right)q^2 }}\int\sqrt{\frac{\left(R+r\right)R}{r}}dr$$
$$\Delta t(r)=\frac{1}{\sqrt{1-\dfrac{v^2}{c^2}}}\sqrt{\dfrac{\pi m\epsilon_0}{q^2 }}\left(\sqrt{r R (r+R)}-\frac{1}{2} R^{3/2} \left(\log R-2 \log
   \left(\sqrt{r+R}+\sqrt{r}\right)\right)\right)$$
which indicates:
The time interval that the two point charges separate a further distance $r$ in the moving reference frame is $\displaystyle\frac{1}{\sqrt{1-\dfrac{v^2}{c^2}}}$ that in the static reference frame where $v=0$.
Does this means Lorentz transformation for time is natural for an event involving both electric and magnetic laws without the need of considering special relativity?
Can a full version of Lorentz transformation be derived in such an approach?
P.S.
I found this question with no accepted answer is similar, but I made some further calculation and extension here.

A:
Does this means Lorentz transformation for time is natural for an event involving both electric and magnetic laws without the need of considering special relativity?

It means that Lorentz transformations follow from electric and magnetic laws. It is how special relativity was discovered in the first place.
Your derivation looks correct. Maxwell's equations are not invariant under Newtonian transformations, only under Lorentz transformations.

A: I  would answer "yes". The Couloumb force $qE$ changes, and here's why:  In frame at rest B=0, while in the moving frame (')  B' is not zero. Since $E^2-B^2$ is Lorentz invariant: E' must be larger than E. (Which is the familiar relativistic squishing of fields--like in a transition-radiation-detector).

A: The answer is no, the Coulomb force between two point charges does not change, unless you change the distance between them.  If the charges move in parallel, then the Coulomb equation no longer applies.  You must use the Lorentz equation, instead.  In other words, if the reference frame is moving and the charges are stationary, then the Coulomb equation applies.  If the reference frame is stationary and the charges are moving, then the Lorentz equation applies. You can not apply both equations at the same time!

redpajama_set_name: RedPajamaStackExchange


text:
Q: sonar jdbc properties are not supported anymore in sonarqube 5.3 version I am using sonarqube 5.3 latest version and when I configure the sonar jdbc properties in my properties file using
property "sonar.jdbc.url", "jdbc:mysql://localhost:3306/sonar")
property "sonar.jdbc.username", "root")
property "sonar.jdbc.password", "root")

I get warning message
Property 'sonar.jdbc.url' is not supported any more. It will be ignored. There is no longer any DB connection to the SQ database.
Property 'sonar.jdbc.username' is not supported any more. It will be ignored. There is no longer any DB connection to the SQ database.
Property 'sonar.jdbc.password' is not supported any more. It will be ignored. There is no longer any DB connection to the SQ database.

How to configure external database and not use embedded database provided by sonarqube?

A: You only need to configure the sonar.host.url. All communication between scanner and server is done with web services, and the scanner no longer talks to the database at all.


text:
Q: Kerberos SSO with Java7 not working for some minutes after client reboot We have a Kerberos SSO enabled product that runs in a Tomcat container under Java7. It generally works, but when a client (some Windows box) has just rebooted, it takes a few minutes until SSO works again.
Why is that? Is there a way around this?


text:
Q: How did offset of an array come to mean the starting address of an array consider the assembly code - mov edi, offset newarray
As per what I have read this will put the address of newarray into the register edi
What I don't understand is this term offset how does the English meaning of this term
fits here.

A: x86 memory addresses are of the form segment:offset, where the offset part is in a normal (general purpose) register like EDI (or RDI in 64-bit code).
In modern systems where we use a flat memory model, the segment base is always 0, and the offset is the whole address, equal to the linear address.
x86-64 addressing for mov eax, [rdi + rax*4 + 1234]:

*

*RDI is the base register in the addressing mode.

*

*RAX is the index (because it has the scale factor, or the 2nd register in [rdi+rax])

*1234 is the displacement, encoded as a dword (disp32) sign-extended to 64-bit

*RDI + RAX*4 + 1234 is the effective address calculated by that addressing mode.  (Hence lea eax, fs:[rdi + rax*4 + 1234] gives you that, even if the FS segment base is non-zero.)  This is the offset part of the seg:off address.

*RDI as the base register implies the DS segment.  The seg:off -> linear address is DS_base + offset.  (Which equals the offset because the CS, DS, ES, and SS bases are fixed to 0 in 64-bit mode, and in 32-bit mode mainstream OSes set them to 0.)

*The linear address is a virtual address because 64-bit mode requires that paging is enabled.

*virt->phys translation happens by looking up the page-number part (the bits above the bottom 12) in the page tables, cached by the TLB.  (Why in x86-64 the virtual address are 4 bits shorter than physical (48 bits vs. 52 long)?).  The resulting physical address is used to access memory (via the cache), or MMIO over PCIe if the phys address is a device address.
So yes, to index an array, you want RDI = OFFSET my_array in MASM syntax.  (Of course in 64-bit mode you'd want a RIP-relative LEA like lea rdi, [my_array], but in 32-bit mode yes you'd do mov edi, OFFSET my_array.)

The OS takes care of making sure the segment base address is 0 for CS, DS, ES, and SS, so [ebx] and [ebp] access the same linear address when EBX = EBP.  (implicit DS vs. SS segments implied by using EBX or EBP as the base register for the addressing mode.)
And that call ebx would fetch code from the same memory address you could read or write with mov dword ptr [ebx], 0C3909090  (3x nop + ret).

Legacy 16-bit real-mode mode code often does need to make sure the DS segment base is set to match the start of the data section. Or a data section in a large program.**  (In real mode, mov ds, ax writing to a segment register sets the base = value<<4, instead of using the value as a selector indexing the GDT or LDT.)
For example, DOS .exe programs often started with
PROC main
   mov ax, @data       ; segment for the data section
   mov ds, ax
   mov es, ax

  mov  bx, OFFSET other_var
  mov  ax, [bx]         ; relies on DS being set properly

  mov  [some_var], ax   ; also relies on DS; uses the offset of some_var in the addressing mode.
  ...

You could mov bx, OFFSET some_var before setting DS, and dereference it after.  The segment and offset parts are independent.
Similarly, legacy BIOS MBR bootloaders need to set DS to match the org value they assume, otherwise they access the wrong place in memory.
Real-mode programs with more than 64k of data would need multiple segments, and have to switch DS or ES to use them.  This was generally inconvenient compared to having universal 32-bit pointers that any code could use efficiently, and x86-16 is pretty thoroughly obsolete, so it's rare for people to write new programs that actually use x86 segmentation for anything.
If you want lots of memory, it's much easier to write 32-bit or 64-bit code.


text:
Q: How to use grep function in R to find the correlation based on sample names I have two data frames that has information about genes. Both of these data frames has the same dimensions (20,000 rows x 50 columns). I have another file called info contains the matched subject names between those data frames. I want to grep the names from the file (info) to find the correlation coefficient between the matched subjects. here is example of those files:
df1
gene_name    loc1  loc2 .........  loc50
gene1        1        23              25
gene2        24       15              67

df2
gene_name    loc1  loc2 .........  loc50
gene1        21       31              55
gene2        2       65              89

info file
subject     loc_in_df1   loc_in_df2
1                loc1          loc2
2                loc3          loc46

A: try something like the following
first build up a df with your columns pulled from df1 and df2 according to the info file
df <- cbind(df1[, info$loc_in_df1],df2[, info$loc_in_df2])

and
cor = apply(df, MARGIN = 1, FUN = function(x) return(cor.test(x[1:50], x[51:100])$estimate))

the 1:50 and 51:100 is assuming that you have 50 pairings in your info file but it's all just guessing as you didn't provide a reproducible sample


text:
Q: How to mock a C++ function in Objective C testing I am trying to write test case for an objective-C function that uses a C++ function with return type bool. Inside the Objective-C function, I am simply calling the C++ function in a conditional statement as if(CppClass::CppFunction) and proceeding accordingly. For writing the test for the said objective-C function, I need to mock the CppFunction. I am not able to do that with OCMock. What is the correct way of mocking the C++ function?

A: This might be overkill if you're really just trying to mock one C++ function, but you can try using Mimicc
Run it on the header which declares the C++ code you want to mock and pass the same command line arguments that you would to the clang invocation you use to compile the code.


text:
Q: Sails.js expireAfterSeconds option in the model I am using sails to write a simple model which should expire after a few hours, so I need something like
    createdAt: {
        type: 'Date',
        expires : 60,
        index: true
    }

But the "expireAfterSeconds" seems not working when I check my database (MongoDB), therefore I have to use
db.collection.ensureIndex( { "createdAt": 1 }, { expireAfterSeconds: 3600 } )

I wonder if it is possible to set the "expire" option in the model?

A: Inspecting the sails-mongo source code that is responsible for handling the index attribute property[1], it seems that it does not take into account anything like an expires property. This makes sense though, because the sails.js waterline ORM does not support database-specific functionality like expiring index data in MongoDB.
However, waterline does provide access to the MongoDB native connection (which uses node-mongodb-native) through the Collection.native() method[2]
Chances are, you only really need to make changes to the model's index once during the lifecycle of the Sails application, so the best place to do that would be in the config/bootstrap.js file. At this point in the sails.js lifecycle, all of the models have been instantiated, so you could do something like this to perform the necessary logic on your keys:
// config/bootstrap.js
exports.bootstrap = function (done) {

    YourModelName.native(function (err, collection) {
        // define index properties
        collection.ensureIndex( { "createdAt": 1 }, { expireAfterSeconds: 3600 } );

        // be sure to call the bootstrap callback to indicate completion
        done();
    });
}

You could take this even further and write a utility that inspects the models that sails has loaded (they are available as keys in the global object sails.models) and, if they have an expires attribute, perform the necessary native functionality. This would also need to be done in the config/bootstrap.js.
If you have native functionality that needs to be done on a per-record basis, you can use the sails.js model lifecycle hooks[3] for that.
references:

*

*[1] https://github.com/balderdashy/sails-mongo/blob/ad7ec276af3a0e823ee5075074788ca915328db2/lib/adapter.js#L112

*[2] https://github.com/balderdashy/sails-mongo/issues/21#issuecomment-20765896

*[3] See the section titled "Lifecycle Callbacks" @ http://sailsjs.org/#!documentation/models

A: UPDATE:
I created a sails hook to give advanced indexing options for models that use the sails-mongo adapter.
Supports all mongo indexing options.
https://www.npmjs.com/package/sails-hook-mongoat

OLD:
I created the below to do this automatically if the model attribute has an expires property and is of type 'date'. Just paste into to your config/bootstrap.js
Hope it helps!

  _.forEach(Object.keys(sails.models), function(key) {
    var model = sails.models[key];
    _.forEach(Object.keys(model.attributes), function(attr) {
      if (model.attributes[attr].hasOwnProperty('expires')) {
        var seconds = model.attributes[attr].expires;
        // delete validators from global model, otherwise sails will error
        delete sails.models[key].attributes[attr].expires;
        delete sails.models[key]._validator.validations[attr].expires;
        if (model.attributes[attr].hasOwnProperty('type') && model.attributes[attr].type === 'date') {
          var obj = {};
          obj[attr] = 1;
          model.native(function(err, collection) {
            // define index properties
            collection.ensureIndex(obj, {
              expireAfterSeconds: seconds
            }, function(err) {
              if (err)
                sails.log.error(err);
              else
                sails.log.info(key + " model attribute '" + attr + "' has been set to expire the document after " + seconds + " seconds.");
            });
          });
        } else {
          sails.log.warn(key + " model attribute '" + attr + "' is set to expire but is not of type 'date'. Skipping...");
        }
      }
    });
  });


text:
Q: URL hack to prefill values not working on mobile. Alternate method possible? My main aim is to show different fields on child object, if the parent object has a particular piclist value.
To achieve this I have created 2 record types and 2 page layouts.
So I have created a custom button to add the child record with prefilled value of the parent by URL hacking.
/a0T/e?
CF00N0k000002irEW={!TRIM(Returns_Request__c.Name)}
&CF00N0k000002irEW_lkid={!Returns_Request__c.Id}
&retURL=%2F{!Returns_Request__c.Id}
&RecordType={!IF( INCLUDES( Returns_Request__c.Reason__c ,'Incorrect Pricing') ,'0120k0000008QsNAAU','')}
&ent=01I0k000000AsBx
This is the code I have used. It works perfectly on website but does not work on mobile.
Please suggest any improvement on this or maybe a completly different way to show different fields on child record creation based on parent record picklist.

A: You want to replace your url hack with actions.
Here is a talk on how to do it: https://www.salesforce.com/video/300736/


text:
Q: Is it safe to store the value of getContext When using the canvas element. Is it safe to call getContext("2d") only once after the page is loaded? Or should I call this function every time I want to draw a frame?

A: Yes, it is save. Calling getContext("2d") repeatedly on the same canvas would always get you the same context object.


text:
Q: charge a 15v Cap with 24v Can I charge a 15V Cap with a 24V supply, as long as I have the supply disconnect, once the cap reaches 15v ?
I have seen the analogy of comparing the voltage to the max psi of a tank, and if you go over, it will quite literally spill out.  So in this case, it would be like filling a 100 psi tank with a 150 psi source and simply shutting the fill valve when reaching 100 psi.  Should work no?
Thanks for you input in advance!

A: Yes, the concept could work to disconnect the 24V charging supply as long as you had arranged the charging time constant to give sufficient time to detect the voltage over 15V and get the supply disconnected.
What this means is that you would not want to be trying to charge the capacitor with it directly connected to the supply. In that case it would charge so fast that some detector comparator circuit, which might have a 1usec response time and a switch MOSFET which may also have a response time, may not have been able to register the 15V event before the cap was charged farther than 15V.
So use an series R to charge through so that you limit the charge rate giving time for the detect circuit.
You have another choice to make a voltage divider of two resistors that divide 24V down to 15V. Then connect your capacitor across the lower resistor of the divider and it will only charge to 15V.


text:
Q: Run JSF project on Apache Tomcat How can lunch JSP project on Tomcat? I copy WebContent folder to webapp folder of Apache but it can't find my jsp page, but if I change jsp to jsf (index.jsf) works fine. How can I solve this problem?
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Graph</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
  </servlet-mapping>
  <context-param>
    <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
    <param-value>resources.application</param-value>
  </context-param>
  <context-param>
    <description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
    <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
    <param-value>client</param-value>
  </context-param>
  <context-param>
    <description>
    This parameter tells MyFaces if javascript code should be allowed in
    the rendered HTML output.
    If javascript is allowed, command_link anchors will have javascript code
    that submits the corresponding form.
    If javascript is not allowed, the state saving info and nested parameters
    will be added as url parameters.
    Default is 'true'</description>
    <param-name>org.apache.myfaces.ALLOW_JAVASCRIPT</param-name>
    <param-value>true</param-value>
  </context-param>
  <context-param>
    <description>
    If true, rendered HTML code will be formatted, so that it is 'human-readable'
    i.e. additional line separators and whitespace will be written, that do not
    influence the HTML code.
    Default is 'true'</description>
    <param-name>org.apache.myfaces.PRETTY_HTML</param-name>
    <param-value>true</param-value>
  </context-param>
  <context-param>
    <param-name>org.apache.myfaces.DETECT_JAVASCRIPT</param-name>
    <param-value>false</param-value>
  </context-param>
  <context-param>
    <description>
    If true, a javascript function will be rendered that is able to restore the
    former vertical scroll on every request. Convenient feature if you have pages
    with long lists and you do not want the browser page to always jump to the top
    if you trigger a link or button action that stays on the same page.
    Default is 'false'
</description>
    <param-name>org.apache.myfaces.AUTO_SCROLL</param-name>
    <param-value>true</param-value>
  </context-param>
  <servlet>
    <servlet-name>faces</servlet-name>
    <servlet-class>org.apache.myfaces.webapp.MyFacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet>
    <servlet-name>UploadServlet</servlet-name>
    <servlet-class>controler.UploadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>faces</servlet-name>
    <url-pattern>*.jsf</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>faces</servlet-name>
    <url-pattern>*.faces</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>UploadServlet</servlet-name>
    <url-pattern>/Upload</url-pattern>
  </servlet-mapping>
  <listener>
    <listener-class>org.apache.myfaces.webapp.StartupServletContextListener</listener-class>
  </listener>
</web-app>

Error:
type Status report

message /Graph/index.jsp
description The requested resource
  (/Graph/index.jsp) is not available.

A: That's not a problem. That's expected behaviour. You're just misunderstanding how the basic Servlet API works. You have configured the JSF-standard FacesServlet to listen on URLs matching /faces/* and you have configured Apache MyFaces specific MyFacesServlet to listen on URls matching *.jsf and *.faces.
To get JSF to run, you have to open the page in browser by an URL which matches the mapping of the FacesServlet. Given the fact that you've an index.jsp file and that your context path is Graph and that you have configured two JSF servlets on three different URL patterns, you can open the JSP by the following URLs:

*

*http://localhost:8080/Graph/faces/index.jsp (invokes FacesServlet)

*http://localhost:8080/Graph/index.jsf (invokes MyFacesServlet)

*http://localhost:8080/Graph/index.faces (invokes MyFacesServlet)

Said that, your configuration is unnecessarily overcomplicated. Get rid of the MyFacesServlet entry and all of its associated URL mappings (with the servlet name of faces). Just stick to the standard FacesServlet and use its mapping instead, or alter it instead. I personally recommend using *.jsf.
<servlet>
    <servlet-name>facesServlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>facesServlet</servlet-name>
    <url-pattern>*.jsf</url-pattern>
</servlet-mapping>

Then you can just open the page by http://localhost:8080/Graph/index.jsf.

Unrelated to the concrete problem, your welcome-file won't work that way. Tomcat would give a HTTP 404 error on that (page/resource not found). You need to specify index.jsf as welcome-file and supply a concrete but empty index.jsf file in the same folder as your index.jsp. This way Tomcat will be fooled that the file exist and show the page by just calling http://localhost:8080/Graph.

If your concern is that it is possible to open JSF pages by their *.jsp extension which would result in a RuntimeException: FacesContext not found and you have actually no one JSP file which is to be served plain vanilla, then you can restrict direct access to JSP files by the following security constraint in web.xml:
<security-constraint>
    <display-name>Restrict direct access to JSP files</display-name>
    <web-resource-collection>
        <web-resource-name>JSP files</web-resource-name>
        <url-pattern>*.jsp</url-pattern>
    </web-resource-collection>
    <auth-constraint />
</security-constraint>

(in JSF 2.0 this is by the way not needed anymore, with the default view technology Facelets it's possible to map the FacesServlet on just *.xhtml, which is the same as the default extension of Facelets files)

A: you can deploy your application with the tomcat manager
http://tomcatIP:8080/manager/html
there you can upload your application and it should run out of the box
if you have no idea what username and password you should type in, you have to configure your tomcat-users.xml


text:
Q: How to get data sequentially? This is an interview question.
This is a actual table Employee:
id  |  name  | salary
1   |    A   | 7000
2   |    B   | 6000
3   |    C   | 5000
4   |    D   | 5500
5   |    E   | 4000
6   |    F   | 4800
7   |    G   | 3000
8   |    H   | 2000

And I want a result like this:
id  |  name  | salary
1   |    C   | 5000
2   |    D   | 5500
3   |    E   | 4000
4   |    F   | 4800
5   |    G   | 3000

I want to show records whose salary between 5000 to 3000 but 1st column should be sequential.
When I perform query it shows this result.
id  |  name  | salary
3   |    C   | 5000
4   |    D   | 5500
5   |    E   | 4000
6   |    F   | 4800
7   |    G   | 3000

[here] what can I write then it will give proper result?
 select name, salary, [HERE]
 from Employee
 where salary between 5000 and 3000;

A: This is standard ANSI SQL (supported by all modern DBMS)
select row_number() over () as id
       name,
       salary
where salary between 5000 and 3000

Note that the order of rows (and in this case the "generated") id is undefined if you do not specify an order by clause. To get a "stable sort order", you should use something like this:
select row_number() over (order by salary) as id
       name,
       salary
where salary between 5000 and 3000
order by salary

A: Try this::
For MYSQL ::
SELECT @rownum:=@rownum + 1 as row_number,
       t.*
FROM (
select name, salary from Employee
 where salary between 5000 and 3000) t,
(SELECT @rownum := 0) r

A: As already commented, for MS SQL server the solution can be found in this post: https://stackoverflow.com/a/1293399/2822268


text:
Q: RecyclerView.Adapter отключить обновление элементов Здравствуйте, у меня имеется RecyclerView с 10 эл. и когда листаешь до 10 и обратно он выгружает первые элементы и загружает обратно. (смена страниц производится кнопкой и мне не нужно их обновлять. 10 эл не так много, элементы берутся из List)
Как мне сделать так чтобы он загрузил все 10 эл. и не обновлял их?

A: Попробуйте так:
mRecyclerView.setDrawingCacheEnabled(true);
mRecyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
mRecyclerView.setItemViewCacheSize(10);


text:
Q: Sort on multiple columns in WPF datagrid How can I set up my WPF datagrid to sort on multiple columns similar to having two sortable columns, clicking on the header of the first column for a primary sort and then SHIFT clicking on the header of the second column for a secondary sort. I would like the multiple column sort to happen automatically when the user clicks on the header of the first column without having to SHIFT click on the second column header. Is there a way to do this entirely in the xaml? If not how can I do this in the code behind? Currently using VB.Net but a C# snippet is acceptable if you have one. Thanks!

A: You can do this by adding System.ComponentModel namespace like this:
xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"

then inside the CollectionViewSource  XAML add new SortDescriptions like this:
<CollectionViewSource … >
            <CollectionViewSource.SortDescriptions>
                <scm:SortDescription PropertyName="Column1"/>
                <scm:SortDescription PropertyName="Column2"/>
            </CollectionViewSource.SortDescriptions>
</CollectionViewSource>

this will sort datagrid on column1,column2.
Edit:
also doing this using C# code behind is pretty easy :
    private void btnSort_Click(object sender, RoutedEventArgs e)
    {
        System.Windows.Data.CollectionViewSource myViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("The_ViewSource_Name")));
        myViewSource.SortDescriptions.Add(new SortDescription("Column1", ListSortDirection.Ascending));
        myViewSource.SortDescriptions.Add(new SortDescription("Column2", ListSortDirection.Ascending));
    }

Edit2:
Workaround can be made to catch the column header left mouse click event and prevent the grid from sort on that column like this:

*

*Disable  grid property named
CanUserSortColumns

*

*Add this code to the grid
PreviewMouseLeftButtonUp event :
private void myDataGrid_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    DependencyObject dep = (DependencyObject)e.OriginalSource;
    while ((dep != null) &&
    !(dep is DataGridCell) &&
    !(dep is DataGridColumnHeader))
    {
        dep = VisualTreeHelper.GetParent(dep);
    }

    if (dep == null)
        return;

    if (dep is DataGridColumnHeader)
    {
        DataGridColumnHeader columnHeader = dep as DataGridColumnHeader;
        // check if this is the wanted column
        if (columnHeader.Column.Header.ToString() == "The_Wanted_Column_Title")
        {
            System.Windows.Data.CollectionViewSource myViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("myViewSource")));
            myViewSource.SortDescriptions.Clear();
            myViewSource.SortDescriptions.Add(new SortDescription("Column1", ListSortDirection.Ascending));
            myViewSource.SortDescriptions.Add(new SortDescription("Column2", ListSortDirection.Ascending));
        }
        else
        {
            //usort the grid on clicking on any other columns, or maybe do another sort combination
            System.Windows.Data.CollectionViewSource myViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("myViewSource")));
            myViewSource.SortDescriptions.Clear();
        }

    }
}

You can modify and expand this code to achieve your requirements.

A: I hope this will help others.  My solution keep the default sort functionality and allow sorting on multiple columns.
Put a sorting event on your datagrid
<DataGrid x:Name="dataGridName" Sorting="dataGridName_Sorting">

And now in your code behind
private void dataGridName_Sorting(object sender, DataGridSortingEventArgs e)
{
    var dgSender = (DataGrid) sender;
    var cView = CollectionViewSource.GetDefaultView(dgSender.ItemsSource);

    //Alternate between ascending/descending if the same column is clicked
    ListSortDirection direction = ListSortDirection.Ascending;
    if (cView.SortDescriptions.FirstOrDefault().PropertyName == e.Column.SortMemberPath)
        direction = cView.SortDescriptions.FirstOrDefault().Direction == ListSortDirection.Descending ? ListSortDirection.Ascending : ListSortDirection.Descending;

    cView.SortDescriptions.Clear();
    AddSortColumn((DataGrid)sender, e.Column.SortMemberPath, direction);
    //To this point the default sort functionality is implemented

    //Now check the wanted columns and add multiple sort
    if (e.Column.SortMemberPath == "WantedColumn")
    {
        AddSortColumn((DataGrid)sender, "SecondColumn", direction);
    }
    e.Handled = true;
}

private void AddSortColumn(DataGrid sender, string sortColumn, ListSortDirection direction)
{
    var cView = CollectionViewSource.GetDefaultView(sender.ItemsSource);
    cView.SortDescriptions.Add(new SortDescription(sortColumn, direction));
    //Add the sort arrow on the DataGridColumn
    foreach (var col in sender.Columns.Where(x => x.SortMemberPath == sortColumn))
    {
        col.SortDirection = direction;
    }
}

The sortDirection on the DataGridColumn allow showing the arrow on the grid.


text:
Q: Piecewise regular curves This is my first question on this site, so I hope I'm doing good.
Consider a continuous curve $\gamma\colon [a,b] \to \mathbb{R}^2$ and a point $c \in (a,b)$ such that $\gamma|_{[a,c]}$ and $\gamma|_{[c,b]}$ are regular curves.
It means that $\gamma'$ is defined and continuous in $[a,c) \cup (c,b]$.
However, in general it could be that $\gamma'$ is not defined in $c$, since in general $(\gamma|_{[a,c]})'(c) \neq (\gamma|_{[c,b]})'(c)$.
Obviously the same applies to its module $|\gamma'|\colon [a,c) \cup (c,b] \to [0,+\infty)$.
Now my question is: the function $|\gamma'|$ is Riemann integrable in $[a,b]$ even if it is not even defined (not only discontinuous) in point $c$?
P.S. sorry for my english, I'm not native language.


text:
Q: how to have Folder Structure with DefaultMutableTreeNode,JTree I am trying to show the same folder structure of folder/subfolder as parent/children
Suppose of this Structure:

however I am struggling on how to add children to the parent node, I have a parent folder named Computerscience, I get all its subfolders and add them as children, how ever some of these children can be parents when there are more subfolders inside them, it seems I need a recursive function but I am not able to do it, here is what I did:
import java.awt.BorderLayout;
import java.io.File;
import java.util.Arrays;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

public class TestTree extends JFrame {

    JTree tree;
    DefaultTreeModel treeModel;

    public TestTree() {
        super("Tree Test Example");
        setSize(400, 300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    protected String[] getListFiles(String Path) {
        File file = new File(Path);
        String[] names = file.list();
        return names;
    }

    public void init() {
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Computerscience");
        String[] names = this.getListFiles("C:\\Users\\neginn\\Google Drive\\NetBeansProjects\\computerscience");
        for (String name : names) {
            root.add(new DefaultMutableTreeNode(name));
            String[] names_level_2 = this.getListFiles("C:\\Users\\neginn\\Google Drive\\NetBeansProjects\\computerscience\\" + name);
            if (names_level_2 != null) {
                for (String name_level2 : names_level_2) {
                    int folder_index = Arrays.asList(names_level_2).indexOf(name_level2);
                    treeModel.insertNodeInto(root, (DefaultMutableTreeNode) root.getChildAt(folder_index), folder_index);
                }
            }
        }
        treeModel = new DefaultTreeModel(root);
        tree = new JTree(treeModel);

        getContentPane().add(tree, BorderLayout.CENTER);
    }

    public static void main(String args[]) {
        TestTree tt = new TestTree();
        tt.init();
        tt.setVisible(true);
    }
}

my problem is in the line treeModel.insertNodeInto

A: As you say, you need to write a recursive method. I tried to write one, please test code below:
public class TestTree extends JFrame {

    JTree tree;
    DefaultTreeModel treeModel;

    public TestTree() {
        super("Tree Test Example");
        setSize(400, 300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    protected File[] getListFiles(String Path) {
        File file = new File(Path);
        return file.listFiles();
    }

    private void addChilds(DefaultMutableTreeNode rootNode, String path) {
        File[] files = this.getListFiles(path);
        for(File file:files) {
            if(file.isDirectory()) {
                DefaultMutableTreeNode subDirectory = new DefaultMutableTreeNode(file.getName());
                addChilds(subDirectory, file.getAbsolutePath());
                rootNode.add(subDirectory);
            } else {
                rootNode.add(new DefaultMutableTreeNode(file.getName()));
            }
        }
    }

    public void init() {
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Computerscience");

        addChilds(root, "C:\\Users\\neginn\\Google Drive\\NetBeansProjects\\computerscience");

        treeModel = new DefaultTreeModel(root);
        tree = new JTree(treeModel);

        getContentPane().add(tree, BorderLayout.CENTER);
    }

    public static void main(String args[]) {
        TestTree tt = new TestTree();
        tt.init();
        tt.setVisible(true);
    }
}


text:
Q: SQL Server 2008 R2 pagination I need to implement pagination for my union query, but I get error "Msg 102, Level 15, State 1, Line 14
Incorrect syntax near ')'.". I followed example I found from this link.
select *
  from (select Id,
               row_number() OVER (order by Id asc) as RowNumber
          from (select Id
                  from (select Id
                          from Table1) as table1
                union all
                select Id
                  from (select Id
                          from Table2) as table2)) as t Derived
  WHERE RowNumber > 5
    and RowNumber <= 10

A: Use:
SELECT u.*
  FROM (SELECT t.id,
               ROW_NUMBER() OVER (ORDER BY t.id) as rownum
          FROM (SELECT t1.id
                  FROM TABLE1 t1
                UNION ALL
                SELECT t2.id
                  FROM TABLE2 t2) as t) AS u
 WHERE u.rownum > 5
   AND u.rownum <= 10

It looks to me that your query was missing a closing bracket for a derived table called "derived", but there wasn't the need for the subqueries in the UNION so I've removed them.

A: You just need to move one parenthesis:
from Table2) as table2)) as t Derived should read from Table2) as table2) as t) Derived
You could also remove some of the subqueries that make Table1 into table1 and Table2 in to table2 but I assume there's some other reaon for those in there (like this is based on another query that is more complicated)

A: select *
  from (select Id,
               row_number() OVER (order by Id asc) as RowNumber
          from (select Id
                  from Table1 as table1
                union all
                select Id
                  from Table2)p)t
  WHERE RowNumber > 5
    and RowNumber <= 10

A: If you select from subquery then  you have to give alias for it. You have 2 outer subqueries but only one with alias. Should be: from Table2) as tabl2) as t) as t


text:
Q: What is the accepted style for using a foreign term followed by its translation?
*

*How do you show a foreign term followed by its translation? Is the foreign term placed in quotation marks with its translation italicized or the other way around? Style guides favor but don't always require the foreign word to be in italics.

*What if the foreign word is a quotation? Would you need italics and quotation marks? If so, how would you punctuate the subsequent translation, with parentheses?

*Absent the obligation to follow a specific style guide, should a writer just decide on an approach that is logical, easily understood and stick with that?
Example

*

*"Cloaca Maxima" greatest sewer
or

*

*Cloaca Maxima "greatest sewer"

A: How do you show a foreign term followed by its translation? Is the foreign term placed in quotation marks with its translation italicized or the other way around?
It is fairly common to

*

*italicize foreign terms (as you note),

*put the translated term inside paired punctuation,1 and

*put the translated term into quotation marks, since it is being "mentioned".

For example:

According to that book, the Cloaca Maxima ("greatest sewer") was a marvel of ancient engineering.2

What if the foreign word is a quotation? Would you need italics and quotation marks?
If you've been italicizing foreign terms and are now quoting one that wasn't originally italicized, you can leave it in regular type. If you do italicize quoted text, then it is common to include a note saying something like "italics mine" or "italics not in original".3

If so, how would you punctuate the subsequent translation, with parentheses?
There would ideally be no difference from how you'd punctuate a non-quoted translation. Of course, you'd need to quote accurately, so if the translation wasn't in the original, then that would need to be clear to the reader. For example, if you were using brackets for editorial insertions:

According to that book, "the Cloaca Maxima ["greatest sewer"] was a marvel of ancient engineering."

Absent the obligation to follow a specific style guide, should a writer just decide on an approach that is logical, easily understood and stick with that?
You should always write with your goal in mind. If you're simply trying to communicate information to your audience, then write in a way that is clear, concise, consistent, etc. Style guides help you do that. If you aren't following one, then you'll have to manage those issues yourself. (I'm not providing a fuller answer to this because it's not specifically related to the rest of the question.)

1 It may be considered as a nonrestrictive appositive (or other structure, since terminology varies), which normally gets set off by paired punctuation.
2 Paired dashes and commas are also possible, though less common.
3 CMOS says, "When it is desirable to call attention to a certain word or words in material being quoted, such words may be set in italics (underlined in manuscript). The reader should be told when this has been done." (14th edition, section 10.67)

A: Before I show you some concrete recommendations from reputable bodies, I'd like to present one paragraph from the third chapter of Robert Bringhurst's The Elements of Typographic Style to better set the stage explaining how we got to where we are with our constant interplay between roman and italic in print.

Italic and roman lived quite separate lives until the middle of the sixteenth century. Before that date, books were set in either roman or italic, but not in both. In the late Renaissance, typographers began to use the two for different features in the same book. Typically, roman was used for the main test and italic for the preface, headnotes, sidenotes and for verse or block quotations. The custom of combining italic and roman in the same line, using italic to emphasize individual words and mark specific classes of information, developed in the sixteenth century and flowered in the seventeenth. Baroque typographers liked the extra proved so useful to editors and authors that no subsequent change of typographic has ever driven it entirely away. Modulation between roman and italic is now a basic and routine typographic technique, much the same as modulation in music between major and minor keys.

Here are some of those style recommendations for modulations in the case of foreign terms.

With pen and ink
In documents written with pen and ink, you can switch into a hand that's different from the one you're using for the main text, such as by using an unconnected hand ("printing" in the language of schoolchildren) combined with a cursive hand ("writing" in the language of schoolchildren) for the material on which you wish to place special emphasis.
Or vice versa, as it doesn't really matter which paired hands you choose provided they're distinct from each other.
At your typewriter
In typewriter copy, as in non-calligraphic handwritten copy, the custom is to underline anything you would set in italic if you could. When you get your typeset copy back from the printer, it will have been converted with that understanding in mind.
On the web
In his fine book on Practical Typography, Matthew Butterick writes this in his
section on italic:

Foreign words used in English are sometimes italicized, sometimes not,
depending on how common they are. For instance, you would italicize your
bête noire and your Weltanschauung, but neither your croissant nor your
résumé. When in doubt, consult a dictionary or usage guide. Don't
forget to type the ᴀᴄᴄᴇɴᴛᴇᴅ ᴄʜᴀʀᴀᴄᴛᴇʀꜱ correctly.

Chicago
The Chicago Manual of Style makes this recommendation:

[7.49] Italics are used for isolated words and phrases in a foreign language if they are likely to be unfamiliar to readers. If a foreign word becomes familiar through repeated use throughout a work, it need be italicized only on its first occurrence. If it appears only rarely, however, italics may be retained.

That's muddy enough, yet that is hardly all Chicago have to say about it. Their rules 6.93, 11.6, and 14.109 also touch on this matter. Their overall directions on this remain no better than fuzzy.
AP
As is par for the course, the Associated Press Stylebook gives ungraceful directions fit only for a manual typewriter. They would see nothing but quotation marks to enclose the foreign term followed by its definition in the body of the text with no further adornment.
I would not use the AP style guide for anything unless you paid me to.  A lot.
The OED
The OED always sets "mentions" in italic, such as you find in a word's etymology section. They then follow that with the translation set in roman if needed. Here's the one for your cloacae maximae:

Inflections:   Plural cloacæ, cloacas.
Origin: A borrowing from Latin. Etymon: Latin cloāca.
Etymology: < classical Latin cloāca (also clouāca, cluāca) underground drain, sewer, in post-classical Latin also privy (from 13th cent. in British sources), cavity in certain animals (1651 in the passage translated in quot. 1653 at sense 2a) < cluere to purify (< the same Indo-European base as lutter adj.) + -āca, suffix forming nouns.

The Economist
The Economist Style Guide says to put the translation in parens if need be:

foreign languages and translation
Occasionally, a foreign language may provide the mot juste. But try not
to use foreign words and phrases unless there is no English alternative,
which is unusual. So:

*

*a year or per year, not per annum

*a person or per person, not per caput or per capita

*beyond one's authority, not ultra vires
(See also italics.)
translating words and phrases
If you want to translate a foreign word or phrase, even if it is the
name of a group or newspaper or party, just put it in brackets without
inverted commas, so:

*

*Arbeit macht frei (work makes free)

*jihad (struggle)

*Médecins Sans Frontières (Doctors Without Borders)

*Pravda  (Truth)

*zapatero (shoemaker)

italics
foreign words and phrases
should be set in italics unless they are so familiar that
they have become anglicised and so should be in roman. For
example:

ad hoc
bourgeois

apartheid
café

a priori
coup d'état (but coup de

a propos
foudre, coup de grâce)

avant-garde
de facto, de jure

bona fi de
dirigisme

elite
parvenu

en masse, en route
pogrom

grand prix
post mortem

in absentia
putsch

in situ
raison d'être

machismo
realpolitik

matériel
status quo

nom de guerre
vice versa

nouveau riche
vis-à-vis

Set in italics:

cabinet (French type)
loya jirga

dalits
Mitbestimmung

de rigueur
pace

jihad
papabile

glasnost
perestroika

in camera
Schadenfreude

intifada
ujamaa

Remember to put appropriate accents and diacritical signs
on all foreign words in italics (and give initial capital letters
to German nouns when in italics, but not if not). Make sure
that the meaning of any foreign word you use is clear. See also
accents.
For the Latin names of animals, plants, etc, see spelling

Summary
Seeing that there are so many style standards, if it's up to you then you should just pick whatever style makes sense to you and stick with that.
If it's not up to you, you should just do whatever they force you to do.


text:
Q: Linq Performance with predicates I'm refactoring a project at the moment, which has a lot of very similar queries on a page
db.WF_Process.Where(x=>x.WorkflowProcessState ==
(int)WorkflowProcessStateEnum.SubtitleFileVersion &&
x.WorkflowProcessSubState == (int)SubtitleFileProcessEnum.SubtitleQCReferred).Count();

db.WF_Process.Where(x=>x.WorkflowProcessState ==
(int)WorkflowProcessStateEnum.SubtitleFileVersion &&
x.WorkflowProcessSubState == (int)SubtitleFileProcessEnum.QCUserFailed).Count();

This produces the following SQL which runs very quick
SELECT
[GroupBy1].[A1] AS [C1]
FROM ( SELECT
    COUNT(1) AS [A1]
    FROM [dbo].[WF_Process] AS [Extent1]
    WHERE (4 = [Extent1].[WorkflowProcessState]) AND (119 = [Extent1].[WorkflowProcessSubState])
)  AS [GroupBy1]

//Repeat the above queries with 100 different enum values
To clean up the code a bit i've refactored it into the below method
 private int GetSubtitleProcessCount(Func<WF_Process, bool> predicate)
        {
            return
                db.WF_Process.Where(x => x.WorkflowProcessState == (int)WorkflowProcessStateEnum.SubtitleFileVersion)
                    .Where(predicate)
                    .Count();
        }

Called like this
model.SubtitleQCReferred = GetSubtitleProcessCount(x=> x.WorkflowProcessSubState == (int)SubtitleFileProcessEnum.SubtitleQCReferred);

This however produces this SQL
SELECT
[Extent1].[ProcessID] AS [ProcessID],
[Extent1].[MaterialID] AS [MaterialID],
[Extent1].[VideoVersionID] AS [VideoVersionID],
[Extent1].[AudioVersionID] AS [AudioVersionID],
[Extent1].[TXVersionID] AS [TXVersionID],
[Extent1].[XMLVersionID] AS [XMLVersionID],
[Extent1].[SubtitleVersionID] AS [SubtitleVersionID],
[Extent1].[Progress] AS [Progress],
[Extent1].[ProcessStatusDescription] AS [ProcessStatusDescription],
[Extent1].[WorkflowProcessState] AS [WorkflowProcessState],
[Extent1].[WorkflowProcessSubState] AS [WorkflowProcessSubState],
[Extent1].[ProcessState] AS [ProcessState],
[Extent1].[ProcessStateDateLastModified] AS [ProcessStateDateLastModified],
[Extent1].[DateCreated] AS [DateCreated],
[Extent1].[DateLastChecked] AS [DateLastChecked],
[Extent1].[SleepUntil] AS [SleepUntil],
[Extent1].[LongRunningProcessID] AS [LongRunningProcessID]
FROM [dbo].[WF_Process] AS [Extent1]
WHERE 4 = [Extent1].[WorkflowProcessState]

Which retrieves the entire record set and then performs the count in code.
I'm assuming this is to do with the second where clause. Why is this?
Is there any way of keeping the pattern i'm using (with small) modification so it  produces decent SQL?

A: If you change the accepted type of the method to be Expression<Func<WF_Process, bool>> it should properly convert the Count logic to SQL.
i.e.:
GetSubtitleProcessCount(Expression<Func<WF_Process, bool>> predicate)

The documentation on PredicateBuilder has some more info about this.


text:
Q: In jest : "could not find react-redux context value; please ensure the component is wrapped in a " I get this error when trying to execute simple Jest test with a form React component :
  ● <LoginForm /> › clicking the validate button › should display page title

    could not find react-redux context value; please ensure the component is wrapped in a <Provider>

      14 |      const [inputPassword, setInputPassword] = useState("");
      15 |
    > 16 |      const dispatch = useDispatch();

Here is the component itself :
import React, { useState, useEffect } from "react";
import { useDispatch } from "react-redux";
import { useHistory } from "react-router-dom";
import jwt_decode from "jwt-decode";
import Cookies from "js-cookie";

import post from "../../../services/request/Post";
import { setCurrentUser } from "../../../redux/action";
import "./index.scss";

const LoginForm = () => {
    const [userData, setUserData] = useState(null);
    const [inputEmail, setInputEmail] = useState("");
    const [inputPassword, setInputPassword] = useState("");

    const dispatch = useDispatch();
    const history = useHistory();

    const handleEmailChange = (e) => {
        setInputEmail(e.target.value);
    };

    const handlePasswordChange = (e) => {
        setInputPassword(e.target.value);
    };

    const handleSubmit = (e) => {
        e.preventDefault();
        setUserData({
            ...userData,
            email: inputEmail,
            password: inputPassword
        });
    };

    const handleLogin = async (data) => {
        if (data) {
            let body = {
                user: { email: data.email, password: data.password }
            };
            const response = await post("/tokens", body);
            if (response != null) {
                Cookies.set("token", response.data.token, {
                    sameSite: "strict",
                    Secure: true
                });
                const payload = {
                    type: "user",
                    id: jwt_decode(response.data.token).user_id,
                    email: userData.email,
                    username: response.data.username
                };
                dispatch(setCurrentUser(payload));
                history.push("/");
            }
        }
    };

    useEffect(() => {
        handleLogin(userData);
    }, [userData]);

    return (

            <form action="" onSubmit={handleSubmit}>
                Adresse email
                <input
                    type="email"
                    id="email"
                    name="email"
                    value={inputEmail}
                    onChange={handleEmailChange}
                />

                Mot de passe
                <input
                    type="password"
                    id="password"
                    name="password"
                    value={inputPassword}
                    onChange={handlePasswordChange}
                />

                <button type="submit" id="submitButton">
                    Valider
                </button>
            </form>

    );
};

export default LoginForm;

Here is the main.jsx component (the entry point):
ReactDOM.render(
    <React.StrictMode>
        <Provider store={store}>
            <PersistGate loading={null} persistor={persistor}>
                <App />
            </PersistGate>
        </Provider>
    </React.StrictMode>,
    document.getElementById("root")
);

As one can see, I already wrapped the <App /> component in a <Provider>
Finally, here is the quite simple test I wrote:
import React from 'react';
import { render, screen } from "@testing-library/react";
// import userEvent from "@testing-library/user-event";

import LoginForm from '../components/forms/LoginForm';

describe('<LoginForm />', () => {
  describe('clicking the validate button', () => {
    beforeEach(
      render(<LoginForm />)
    );

    it("should display page title", () => {
      expect(screen.getByText("Page de connexion")).toBeInTheDocument();
      expect(screen.getByText("Adresse email")).toBeInTheDocument();
      expect(screen.getByText("Mot de passe")).toBeInTheDocument();
    })
  });
});

It is the first time I write test with React so I am kinda lost. Should I use a sort of mock store for testing environments ? If so, is it possible to do it globally, for every tested components ?

A: Yes, you should be wrapping the <LoginForm /> with a <Provider store={store}>.
You can set up a reusable function that will automatically do that for you:
https://redux.js.org/usage/writing-tests#components

A: In my case, to be able to mock store and provider, I implemented a custom render function named renderWithProviders according to the redux docs to my application that was built using Typescript, Webpack, React-Redux, and Jest.
Referance

*

*markerikson's answer

*Redux Documentation: Writing Tests

*serdarsen/getir_market (my application)


text:
Q: Proxy Server refuses connection after short period of time I have a freshly installed ubuntu version 14.04 running on my Lenovo G780 (only later I learned that this Laptop may not be the ideal choice for a Linux system). Please note that I have never really used a Linux system before; I might need some thorough explanation and I apologize in advance.
My situation: I am online using a LAN cable. I am staying in a universitary guesthouse that provides Internet access after successful login on an authentification page that opens first thing after connecting the cable. To do this, I had to connect via a proxy server.
Now the problem: After a couple of minutes in which I can access the Internet without problems, the connection breaks down and the "proxy server refuses connections", as Firefox told me. When I unplug the cable and put it back in, the cycle starts again: For a variable, but not very long time, I have Internet before the connection breaks down again. I have the feeling that it may depend in part on the amount of data that is processed; Trying to run a video stream or a skype call lets the connection crash almost immediately, while if I leave it alone, the connection sometimes stays open for almost an hour.
Does anybody have an idea? Thanks in advance!


text:
Q: Uploading Image as base64 image but the request sent with empty base64 image I made a Flask API which can take an image as input as Base64 string. Now I want to send request on that API from Android app using Ktor. I am using Jetpack Compose for UI here.
I succeeded to send request to that api but there is a problem, the Base64 string is going to the api as empty string. Now to convert the image to base64, I am using this code.
if (imageUri.value!=null){
            val file = File(imageUri.value.toString()).readBytes()
            imageStr = Base64.encodeToString(file, Base64.DEFAULT)
            println(imageStr)
        }

Is this code correct? I want to pick an image from gallery and convert that to base64 string. I am also giving the code of the MainActivity.kt and my Composable function file code.
MainActivity.kt

class MainActivity : ComponentActivity() {

    private var imageUri = mutableStateOf<Uri?>(null)
    private var imageStr: String = ""

    private var post: ImageResponse? = null

    private var cropActivityResultContracts = object : ActivityResultContract<Any?, Uri?>() {
        override fun createIntent(context: Context, input: Any?): Intent {
            return CropImage.activity()
                .getIntent(this@MainActivity)
        }

        override fun parseResult(resultCode: Int, intent: Intent?): Uri? {
            return CropImage.getActivityResult(intent)?.uri
        }

    }

    private val launcher = registerForActivityResult(cropActivityResultContracts) { uri ->
        imageUri.value = uri
    }

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (imageUri.value!=null){
            val file = File(imageUri.value.toString()).readBytes()
            imageStr = Base64.encodeToString(file, Base64.DEFAULT)
            println(imageStr)
        }

        setContent {
            val scope = rememberCoroutineScope()
            UploadImageTheme {
                ImagePickerDesign(
                    onSelect = {
                        launcher.launch("image/*")
                    },
                    imageUri = imageUri,
                    onUpload = {
                        scope.launch {
                            post = service.postImage(
                                ImageRequest(imageStr)
                            )
                        }
                    },
                    result = post.pred_percentage
                )
            }
        }
    }
}

And one more thing! How can I display the response from the server in the app? In the above code, result parameter will take take the response from the server and display it. But for some reason I can't update that value in the UI.
ImagePickerDesign.kt
package com.example.uploadimage

import android.net.Uri
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.unit.dp
import com.skydoves.landscapist.glide.GlideImage
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.sp

@Composable
fun ImagePickerDesign(
    imageUri: MutableState<Uri?>,
    onUpload: () -> Unit,
    onSelect: () -> Unit,
    result: String
) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        verticalArrangement = Arrangement.SpaceEvenly,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {

        if (imageUri.value != null) {
            GlideImage(
                imageModel = imageUri.value,
                modifier = Modifier
                    .size(350.dp)
                    .clickable(onClick = onSelect),
                contentScale = ContentScale.Fit
            )
        }else{
            Image(
                painter = painterResource(id = R.drawable.placeholder_image),
                contentDescription = "placeholder",
                modifier = Modifier
                    .size(350.dp)
                    .clickable(onClick = onSelect),
                colorFilter = ColorFilter.tint(Color.Black)
            )
        }

        Text(text = result, fontSize = 16.sp)

        Button(onClick = onUpload) {
            Text(text = "Upload Image")
        }
    }
}

You can also see my project here: https://github.com/srang992/Pancard-Tampering-app
This is the output while running the Android app:
Install successfully finished in 6 s 709 ms.
$ adb shell am start -n "com.example.uploadimage/com.example.uploadimage.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 32033 on device 'xiaomi-m2010j19si-6686ff050321'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/ple.uploadimag: Late-enabling -Xcheck:jni
E/ple.uploadimag: Unknown bits set in runtime_flags: 0x48000
I/Perf: Connecting to perf service.
I/FeatureParser: can't find lime.xml in assets/device_features/,it may be in /vendor/etc/device_features
E/libc: Access denied finding property "ro.vendor.df.effect.conflict"
E/libc: Access denied finding property "ro.vendor.knock.type"
W/ple.uploadimage: type=1400 audit(0.0:18925): avc: denied { read } for name="u:object_r:vendor_default_prop:s0" dev="tmpfs" ino=16328 scontext=u:r:untrusted_app:s0:c35,c257,c512,c768 tcontext=u:object_r:vendor_default_prop:s0 tclass=file permissive=0
    type=1400 audit(0.0:18926): avc: denied { read } for name="u:object_r:vendor_default_prop:s0" dev="tmpfs" ino=16328 scontext=u:r:untrusted_app:s0:c35,c257,c512,c768 tcontext=u:object_r:vendor_default_prop:s0 tclass=file permissive=0
W/Looper: PerfMonitor looperActivity : package=com.example.uploadimage/.MainActivity time=273ms latency=938ms running=224ms  procState=2 ClientTransaction{ callbacks=[android.app.servertransaction.LaunchActivityItem] lifecycleRequest=android.app.servertransaction.ResumeActivityItem } historyMsgCount=1 (msgIndex=1 wall=997ms seq=2 running=873ms runnable=46ms io=17ms late=2ms h=android.app.ActivityThread$H w=110)
W/Looper: PerfMonitor looperActivity : package=com.example.uploadimage/.MainActivity time=0ms latency=1216ms running=0ms  procState=2 ClientTransaction{ callbacks=[android.app.servertransaction.TopResumedActivityChangeItem] } historyMsgCount=2 (msgIndex=1 wall=997ms seq=2 running=873ms runnable=46ms io=17ms late=2ms h=android.app.ActivityThread$H w=110) (msgIndex=2 wall=273ms seq=3 running=224ms runnable=4ms io=20ms late=938ms h=android.app.ActivityThread$H w=159)
I/AdrenoGLES-0: QUALCOMM build                   : 243b6bc, I98aee2b40e
    Build Date                       : 12/08/20
    OpenGL ES Shader Compiler Version: EV031.29.00.16
    Local Branch                     :
    Remote Branch                    : refs/tags/AU_LINUX_ANDROID_LA.UM.8.15.R1.10.00.00.643.066
    Remote Branch                    : NONE
    Reconstruct Branch               : NOTHING
    Build Config                     : S P 8.0.16 AArch64
    Driver Path                      : /vendor/lib64/egl/libGLESv2_adreno.so
I/AdrenoGLES-0: PFP: 0x016ee188, ME: 0x00000000
I/OpenGLRenderer: Davey! duration=902ms; Flags=1, IntendedVsync=17962622634853, Vsync=17962905968175, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=17962922546739, AnimationStart=17962922639291, PerformTraversalsStart=17962922843354, DrawStart=17963416902364, SyncQueued=17963440580541, SyncStart=17963440964031, IssueDrawCommandsStart=17963441058406, SwapBuffers=17963524637156, FrameCompleted=17963525914447, DequeueBufferDuration=106000, QueueBufferDuration=392000,
W/Looper: PerfMonitor doFrame : time=605ms vsyncFrame=646397 latency=300ms procState=2 historyMsgCount=4 (msgIndex=1 wall=997ms seq=2 running=873ms runnable=46ms io=17ms late=2ms h=android.app.ActivityThread$H w=110) (msgIndex=2 wall=273ms seq=3 running=224ms runnable=4ms io=20ms late=938ms h=android.app.ActivityThread$H w=159)
I/Choreographer: Skipped 34 frames!  The application may be doing too much work on its main thread.
W/Looper: PerfMonitor doFrame : time=11ms vsyncFrame=646410 latency=576ms procState=2 historyMsgCount=5 (msgIndex=1 wall=605ms seq=6 running=461ms late=300ms h=android.view.Choreographer$FrameHandler c=android.view.Choreographer$FrameDisplayEventReceiver)
I/ple.uploadimag: ProcessProfilingInfo new_methods=5563 is saved saved_to_disk=1 resolve_classes_delay=8000
I/Timeline: Timeline: Activity_launch_request time:17970735
W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy@8f28626
W/ple.uploadimag: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
W/ple.uploadimag: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
I/Timeline: Timeline: Activity_launch_request time:17970975
W/Glide: Failed to find GeneratedAppGlideModule. You should include an annotationProcessor compile dependency on com.github.bumptech.glide:compiler in your application and a @GlideModule annotated AppGlideModule implementation or LibraryGlideModules will be silently ignored
I/System.out: 20:44:19.969 [main] INFO io.ktor.client.HttpClient - REQUEST: https://pancard-fraud.herokuapp.com/
    20:44:19.978 [main] INFO io.ktor.client.HttpClient - METHOD: HttpMethod(value=POST)
I/System.out: 20:44:19.978 [main] INFO io.ktor.client.HttpClient - COMMON HEADERS
I/System.out: 20:44:19.981 [main] INFO io.ktor.client.HttpClient - -> Accept: application/json
    20:44:19.982 [main] INFO io.ktor.client.HttpClient - -> Accept-Charset: UTF-8
I/System.out: 20:44:19.982 [main] INFO io.ktor.client.HttpClient - CONTENT HEADERS
    20:44:19.983 [main] INFO io.ktor.client.HttpClient - -> Content-Length: 18
    20:44:19.983 [main] INFO io.ktor.client.HttpClient - -> Content-Type: application/json
I/System.out: 20:44:19.984 [main] INFO io.ktor.client.HttpClient - BODY Content-Type: application/json
I/System.out: 20:44:20.024 [main] INFO io.ktor.client.HttpClient - BODY START
    20:44:20.025 [main] INFO io.ktor.client.HttpClient - {"imageString":""}
    20:44:20.025 [main] INFO io.ktor.client.HttpClient - BODY END
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
I/DpmTcmClient: RegisterTcmMonitor from: $Proxy0
I/System.out: 20:44:41.745 [main] INFO io.ktor.client.HttpClient - RESPONSE: 503 Service Unavailable
    20:44:41.746 [main] INFO io.ktor.client.HttpClient - METHOD: HttpMethod(value=POST)
I/System.out: 20:44:41.747 [main] INFO io.ktor.client.HttpClient - FROM: https://pancard-fraud.herokuapp.com/
I/System.out: 20:44:41.747 [main] INFO io.ktor.client.HttpClient - COMMON HEADERS
I/System.out: 20:44:41.748 [main] INFO io.ktor.client.HttpClient - -> cache-control: no-cache, no-store
I/System.out: 20:44:41.749 [main] INFO io.ktor.client.HttpClient - -> connection: keep-alive
I/System.out: 20:44:41.750 [main] INFO io.ktor.client.HttpClient - -> content-length: 506
I/System.out: 20:44:41.751 [main] INFO io.ktor.client.HttpClient - -> content-type: text/html; charset=utf-8
I/System.out: 20:44:41.752 [main] INFO io.ktor.client.HttpClient - -> date: Wed, 03 Nov 2021 15:14:40 GMT
I/System.out: 20:44:41.753 [main] INFO io.ktor.client.HttpClient - -> server: Cowboy
I/System.out: 20:44:41.754 [main] INFO io.ktor.client.HttpClient - -> x-android-received-millis: 1635952481690
I/System.out: 20:44:41.755 [main] INFO io.ktor.client.HttpClient - -> x-android-response-source: NETWORK 503
I/System.out: 20:44:41.756 [main] INFO io.ktor.client.HttpClient - -> x-android-selected-protocol: http/1.1
I/System.out: 20:44:41.757 [main] INFO io.ktor.client.HttpClient - -> x-android-sent-millis: 1635952461008
I/System.out: 20:44:41.769 [ktor-android-dispatcher-worker-3] INFO io.ktor.client.HttpClient - BODY Content-Type: text/html; charset=utf-8
I/System.out: 20:44:41.770 [ktor-android-dispatcher-worker-3] INFO io.ktor.client.HttpClient - BODY START
I/System.out: 20:44:41.771 [ktor-android-dispatcher-worker-3] INFO io.ktor.client.HttpClient - <!DOCTYPE html>
        <html>
          <head>
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <meta charset="utf-8">
            <title>Application Error</title>
            <style media="screen">
              html,body,iframe {
                margin: 0;
                padding: 0;
              }
              html,body {
                height: 100%;
                overflow: hidden;
              }
              iframe {
                width: 100%;
                height: 100%;
                border: 0;
              }
            </style>
          </head>
          <body>
            <iframe src="//www.herokucdn.com/error-pages/application-error.html"></iframe>
          </body>
        </html>
I/System.out: 20:44:41.772 [ktor-android-dispatcher-worker-3] INFO io.ktor.client.HttpClient - BODY END
I/System.out: Error: Service Unavailable


text:
Q: $\mathrm{SU}(2)$ axis and angle representation I have a question about the rotation matrix of $\mathrm{SU}(2)$,
$$\exp\left(-\mathrm{i}\vec\theta\cdot\vec\sigma/2\right)$$
in this form, it represents a rotation at the angle $\theta$ around the axis $\hat{n}=\vec{\theta}/\lvert{\vec{\theta}\rvert}$. How do you show that $\hat{n}$ and $\theta$ indeed mean geometrically the axis and the angle of the rotation?

A: Let us say that $\hat n$ points in the direction $(\theta,\phi)$, i.e.
$$\hat n_z=\cos\theta,\quad\hat n_x=\sin\theta\cos\phi,\quad \hat n_y=\sin\theta\sin\phi$$
Then one demands that the states $|\hat n,\pm\rangle$ are eigenvectors of $\hat n\cdot\vec S$. You can think of this dot product as the projection of the spin operator $\vec S$ along the axis of rotation $\hat n$. I think this clears up $\hat n$. One checks that $\theta$ has the correct interpretation by considering a rotation about, for instance, the $z$-axis. Then the rotation operator has the form $\exp(-\mathrm{i}\theta\sigma_z/2)$. Suppose we rotate the coordinate system so that the old $z$-axis is now $\hat n$. Then $\sigma_z\rightarrow \hat n\cdot\vec\sigma$ as explained earlier. The parameter $\theta$ is obviously unaffected. Thus the rotation operator is $\exp(-\mathrm{i}\vec\theta\cdot\vec\sigma/2)$.


text:
Q: How can I show one alert when ever a var == 0? I am currently trying to make one easy card comparison game but I am having some problems. When ever the var playerLife or computerLife == 0 I want to show a alert message and refresh the page for a new game. If you scroll down you can see that I am trying to do this using the if statment but it does not seem to work. I am quite new at this so all the help and tips are welcome. Also if this code that I have at the moment can be better I should love to hear it. Thanks for your time.
var cards = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10,
            1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8,8, 9, 9, 10, 10];
var shuffledCards = shuffle(cards);
var playerDeck = shuffledCards.slice(0,20);
var computerDeck = shuffledCards.slice(20);
var playerlife = 25;
var computerLife = 25;

function shuffle(array) {
    var m = array.length, t, i;

    // While there remain elements to shuffle…
    while (m) {

        // Pick a remaining element…
        i = Math.floor(Math.random() * m--);

        // And swap it with the current element.
        t = array[m];
        array[m] = array[i];
        array[i] = t;
    }

    return array;
}

function getTopCard(deck) {
    return deck[0];
}

function dealCards() {
    var playerTopCard = getTopCard(playerDeck);
    var computerTopCard = getTopCard(computerDeck);
    var cardImage = "";

    whoWon();
    console.log('--------------------');

    document.getElementById("card1").innerHTML = "
" + playerTopCard + '
' + cardImage;
    document.getElementById("card2").innerHTML = "
" + computerTopCard + '
' + cardImage;
    document.getElementById("scoreComputer").innerHTML = computerLife;
    document.getElementById("scorePlayer").innerHTML = playerlife;
}

function whoWon() {
    var playerTopCard = getTopCard(playerDeck);
    var computerTopCard = getTopCard(computerDeck);

    if (playerTopCard > computerTopCard) {
        console.log('Player Won! ' + playerTopCard + '/' + computerTopCard);
        computerLife = computerLife - (playerTopCard - computerTopCard);
        playerDeck.shift();
        computerDeck.shift();
        console.log('Player Life - ' + playerlife);
        console.log('Computer Life - ' + computerLife);
    } else if (playerTopCard < computerTopCard) {
        console.log('Computer Won! ' + playerTopCard + '/' + computerTopCard);
        playerlife = playerlife - (computerTopCard - playerTopCard);
        playerDeck.shift();
        computerDeck.shift();
        console.log('Player Life - ' + playerlife);
        console.log('Computer Life - ' + computerLife);
    } else {
        console.log('Tie! ' + playerTopCard + '/' + computerTopCard);
        playerDeck.shift();
        computerDeck.shift();
        console.log('Player Life - ' + playerlife);
        console.log('Computer Life - ' + computerLife);
    }
}

shuffle(cards);
console.log('playerDeck - ' + playerDeck);
console.log('computerDeck - ' + computerDeck);

document.getElementById("click").addEventListener("click", dealCards);

(function gameEnd () {
    if (playerlife <=0 || computerLife <=0) {
        alert('DONE');
    }
}());

A: You should considering changing your code like this:
// new function
function checkIsGameOver () {
    if (playerlife <=0 || computerLife <=0) {
        alert('DONE');
    }
}
function whoWon() {
    var playerTopCard = getTopCard(playerDeck);
    var computerTopCard = getTopCard(computerDeck);

    if (playerTopCard > computerTopCard) {
        console.log('Player Won! ' + playerTopCard + '/' + computerTopCard);
        computerLife = computerLife - (playerTopCard - computerTopCard);
        // added code here...
        checkIsGameOver();
        playerDeck.shift();
        computerDeck.shift();
        console.log('Player Life - ' + playerlife);
        console.log('Computer Life - ' + computerLife);
    } else if (playerTopCard < computerTopCard) {
        console.log('Computer Won! ' + playerTopCard + '/' + computerTopCard);
        playerlife = playerlife - (computerTopCard - playerTopCard);
        // added code here...
        checkIsGameOver();
        playerDeck.shift();
        computerDeck.shift();
        console.log('Player Life - ' + playerlife);
        console.log('Computer Life - ' + computerLife);
    } else {
       console.log('Tie! ' + playerTopCard + '/' + computerTopCard);
       playerDeck.shift();
       computerDeck.shift();
       console.log('Player Life - ' + playerlife);
       console.log('Computer Life - ' + computerLife);
    }
}


text:
Q: Calculating an index in an array help with algorithm I'm taking a sprite sheet and splitting it up into an array.  I then take that array and rotate the image by a certain granularity and push that onto the end of the array too to pre bake the rotations for faster drawing (no hardware acceleration).  The final result looks something like this:
array[0] = frame1 of the animation
array[1] = frame2 of the animation
array[2] = frame3 of the animation
array[3] = frame1 of the animation rotated at 45 degrees
array[4] = frame2 of the animation rotated at 45 degrees
array[5] = frame3 of the animation rotated at 45 degrees
array[6] = frame1 of the animation rotated at 90 degrees
... etc

So now I'm trying to come up with a function that'll return the right element for any angle at the right granularity.  For example, say my in-game object is currently rotated 30 degrees and is on frame1 of the animation, I would want array[3].  If I was on frame2 of the animation, I would want array[4].  If the object was rotated 80 degrees and was on frame1, I would want array[6], and so on.
These are the constants I have:
The # of animation frames (pre-rotation)
The # of animation frames (post-rotation)
The Granularity of the Rotations (from 1 to 360, ie granularity of 45 would be the above example).
This is the signature of the function to calculate the frame:
function calculateImageIndex(animationFrame : Number, currentAngle : Number) : Number
Any ideas on how to calculate this?  I'm stumped.

A: nf: total number of frames
gr: granularity of rotation
r: actual angle of rotation
f: actual frame number

i = round(r / gr) * nf + f - 1

A: n = Number of frames (Pre-rotation)
g = granularity of rotation
r = actual angle of rotation
f = actual frame
I think these are the constants you need and are given.
The first thing we will want to do it find the number of rotations it would take to get to the angle desired. In the above example getting to an angle of 45 would be 1 rotation. 90 degrees = 2 rotations and so on. Let R = number of rotations.
R = r / g  This should always be an integer as you should never need an angle that doesn't fit the gratuity you used.
Next we will calculate the starting index of that rotation "group". In your example above the first group with a rotation 0 would start at index 0. 45 degress or 1 rotation would start at index 3. And so on. To do this we need to multiply the number of rotations (R) by the number of frames pre-rotation (n). Let j = the starting index of that rotation group.
j = R * n
The last step would be to figure out how much you must add to the starting index (j) to reach the frame you want. I will assume the first frame will be numbered 1 as in your example above, but if the first frame is numbered 0 then remove the -1 in the algorithm. Let i = the final index.
i = j + (f - 1)
I will be the index you are looking for. To put this together in one algorithm it would look like this.
i = ((r / g) * n ) + (f - 1)
Hope this helps! Let me know if you need my to clarify anything.


text:
Q: unable to execute PHP files on my server While accessing PHP files in my server it prevents to execute PHP files. Image and text files etc can be browsed. When I try to browse PHP file it gives the following error:

The server encountered an unexpected condition which prevented it from fulfilling the request. The script had an error or it did not
  produce any output. If there was an error, you should be able to see
  it in the error log.

The .htaccess file is empty, I can access the cpanel but have no idea whats wrong.

A: change your php files permission to 775.


text:
Q: Share executable between docker images Maybe it is really lame question, but would it be possible to share some executables to all docker containers at once?
The reason is i.e. JDK part of the image is pretty big, why not put the binaries in some volume and then just execute java command from there?
Is it feasible at all or nonsense from the start?

A:
The reason is i.e. JDK part of the image is pretty big, why not put the binaries in some volume and then just execute java command from there?

Docker images should be portable, and you should be able to start your image anywhere where Docker is installed. If you don't package all the dependencies inside the image, the image
will not be portable on any machine.


text:
Q: SSIS Use DataFlow task with variables instead of a source database I have a task that I am working on that has me stumped. Hoping you can help me. I am using a data flow task which is basically inserting a row into a sqlite table. I was doing this using a "SQL Task" but unfortunately the only way to successfully insert a guid into the sqlite table is to convert it as a byte stream using the data flow task. I do not want to use a source database because my data is not flowing from one table to another. I really just want to take my populated variables and convert them to a byte stream which i can then insert successfully into a sqlite database. The issue is, i cannot use a dataflow task without a source database.
My work-around so far has been to declare a source database/table and only one column (but never use it in the data flow). This works fine and I am unable to insert the row into sqlite using my pre-set variables, but i am left with a somewhat annoying message in my Output log every time i do this:
Warning: 0x80047076 at , SSIS.Pipeline: The output column "" (117) on output "OLE DB Source Output" (11) and component "OLE DB Source" (1) is not subsequently used in the Data Flow task. Removing this unused output column can increase Data Flow task performance.
Anyone know of a good way to get this warning not to show up?

A: In your dataflow choose a Script Component.
When prompted to choose Source, Destination, or Transformation, choose Source.
Add your pre populated variables to the CustomProperties.ReadOnlyVariables section of the script tab.
Go to the Inputs and Outputs section.
Add a column to the default output for each of your variables.
In your script  (if using C#) put something similar to the following in the CreateNewOutputRows() section
    Output0Buffer.AddRow();
    Output0Buffer.ContainerName = Variables.ContainerName;
    Output0Buffer.TaskName = Variables.TaskName;
    Output0Buffer.TaskStartDate = Variables.ContainerStartTime;

Save your script.
Connect your script component to your destination object.

A: If this is causing your package execution to get failed, you got an option of ignoring these warnings/errors..
Just double click the Source block in Dataflow and navigate to the last tab("Error OUtput") in left side pane and you need to select the option to ignore the errors. (I dont know eactly what phrase in that option will do it )


text:
Q: More efficient way for: value_counts (in %) for many columns grouped by a variable I am working on a use case where I have many observations of many features per id and I need to count the frequency of values (~5 discrete values) for each id per column.
I have a solution for it which works for a fairly small dataset (e.g. < 1million rows) but fails on my whole dataset (which might get even larger in the future) since it fills my RAM. I could not find a clean groupby solution since I need to do it for many columns at once.
Sample data:
import pandas as pd
import numpy as np

n = 100     # Number of features
m = 100     # Number of classes
k = 10000   # number of occurrences per class

possible_values = [1, 2, 3, 4, 5]

df = []
for i in range(m):
    for j in range(k):
        df.append( np.append(i, np.random.choice(possible_values, n)) )

features = [f"feature{i}" for i in range(n)]
df = pd.DataFrame(df, columns=(["id"] + features))

It is easy enough without the groupby case:
df[features].apply(pd.value_counts).T / df.shape[0]

My approach
melted = df.melt(id_vars="id", var_name='feature', value_name='value')
feature_freq_id = pd.crosstab(index=[melted.id, melted.feature], columns=melted.value).reset_index()
feature_freq_id[possible_values] = feature_freq_id[possible_values].div(feature_freq_id[possible_values].sum(axis=1), axis=0)

The problem is that melted has n*m*k rows. My dataset has >250 features, >200 ids and ~5k observations per id which means that melted will have >250 mil rows. This results in my memory being eventually filled and python dies.
Expected result:
feature_freq_id.head(3)

id
feature
1
2
3
4
5

0
0
feature0
0.183
0.185
0.226
0.187
0.219

1
0
feature1
0.178
0.222
0.209
0.209
0.182

2
0
feature10
0.215
0.213
0.175
0.196
0.201

A: Just an idea: Use groupby over id in combination with your "easy" method:
def fractions(sdf):
    return sdf.apply(pd.value_counts, normalize=True).fillna(0.).T

result = df.groupby("id")[features].apply(fractions)
result.index.set_names("feature", level=1, inplace=True)

This should avoid the memory melt-down?


text:
Q: A simple regex, extract what is between "/d/" and "/" I need to extract the xxxx in the following string in a url:
{anything}/d/xxxx/{anything}

That is, get whatever is between "/d/" and the first "/" after that, and forget the rest.

A: You haven't noticed what language you are using.
.+\/d\/([^\/]+).+
will do it and have the searched part in $1 (in perl)

A: /d/(.*?)/

Will give you a capture group containing what you want.
Regular Expression Tutorial is a decent place to start, otherwise get a tool such as Expresso and have a play around!  It'll give you a plain text interpretation of the what your regular expression means.
Here's a tutorial to go along with Expresso: The 30 Minute Regex Tutorial.

A: As for the question - I'm not really sure, but I've got this site bookmarked. It's a pretty good Tutorial.
Hope this helps!


text:
Q: Using Geopandas and Scipy.interpolate, how can I only display the interpolated map and exclude the grid? I am using scipy.interpolate to interpolate a dataset to within a boundary. I need to know how to display only the interpolated data without grid overlay, just to clean up the display. In other words, even though I use a grid to interpolate across the entire field, I need to display it without the grid. How can I do that?
For reproducibility, the data can be found and downloaded from this Google drive directory. You will need both the .csv file and the .shp file. The .csv file is 7KB, whereas the shape files total up to 22KB.
Here is what I have tried:
# Import modules
import geopandas as gpd
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from shapely.geometry import box
from scipy.interpolate import griddata

# Read in data
df = pd.read_csv('python_question.csv')
bnd = gpd.read_file('bound.shp')

# Reproject shapefile boundary
bnd  = bnd.to_crs("epsg:4326")

# Convert DataFrame to GeoDataFrame
df = gpd.GeoDataFrame(df)
df.head()

# Define coordinate systems
epsg_wgs = 4326 # World Geodetic System 1984
epsg_utm = 32614 # UTM Zone 14

# Convert latitude and longitude to point data
df['geometry'] = gpd.points_from_xy(df['Longitude'],
                                     df['Latitude'],
                                    crs = epsg_wgs)

df.head()

# Check CRS for both datasets
print(bnd.crs)
print(df.crs)

# Plotting of map boundary and sampled points
fig, ax = plt.subplots(1,1, figsize=(8,8))
ax.ticklabel_format(useOffset=False)
bnd.plot(ax=ax, facecolor='w', edgecolor='k')
df.plot(ax=ax, marker='x', facecolor='k')
plt.show()

# Find and delete points outside of the field boundaries
print(df.shape)
for k,row in df.iterrows(): #Prints row without indexed rows
    point = row['geometry']
    if not point.within(bnd['geometry'].iloc[0]):
        df.drop(k, inplace=True) #Drops the Kth row

df.reset_index(inplace=True, drop=True)
print(df.shape)

# Plot again after deleting the points outside of the boundary
# Plotting of map boundary and sampled points
fig, ax = plt.subplots(1,1, figsize=(8,8))
ax.ticklabel_format(useOffset=False)
bnd.plot(ax=ax, facecolor='w', edgecolor='k')
df.plot(ax=ax, marker='x', facecolor='k')
plt.show()

# Create grid to interpolate over
xmin, ymin, xmax, ymax = bnd.to_crs(epsg=epsg_utm).total_bounds #Represents field in terms of meters

# Define cell size
xdelta = 1 # meters
ydelta = 1 # meters

# Create an empty array to save the grid
grid = np.array([])

for x in np.arange(xmin, xmax, xdelta): #min, max step
    for y in np.arange(ymin, ymax, ydelta): #min, max step
        cell = box(x,y, x+xdelta, y+ydelta)
        grid = np.append(grid, cell)

gdf_grid = gpd.GeoDataFrame(grid, columns=['geometry'], crs=epsg_utm)
gdf_grid['centroids'] = gdf_grid['geometry'].centroid
gdf_grid.head()

# Convert CRS back to Lat/Long
gdf_grid['geometry'] = gdf_grid['geometry'].to_crs(crs=epsg_wgs)
gdf_grid['centroids'] = gdf_grid['centroids'].to_crs(crs=epsg_wgs)

# Plot field boundaries, points, and grid
fig, ax = plt.subplots(1,1, figsize=(8,8))
ax.ticklabel_format(useOffset=False)
bnd.plot(ax=ax, facecolor='w', edgecolor='r')
df.plot(ax=ax, marker='x', facecolor='k')
gdf_grid.plot(ax=ax, facecolor = 'None', edgecolor='k')
plt.show()

# Clip cells to shapefile boundary
gdf_grid = gpd.clip(gdf_grid, bnd['geometry'].iloc[0])
gdf_grid.reset_index(inplace=True, drop=True)

#Plot
fig, ax = plt.subplots(1,1, figsize=(8,8))
ax.ticklabel_format(useOffset=False)
bnd.plot(ax=ax, facecolor='w', edgecolor='r')
df.plot(ax=ax, marker='x', facecolor='k')
gdf_grid.plot(ax=ax, facecolor = 'None', edgecolor='k')
plt.show()

# Interpolate the values of observed automobiles to each centroid
x = df['geometry'].x
y = df['geometry'].y
z = df['car_obs']

xq = gdf_grid['centroids'].x
yq = gdf_grid['centroids'].y

# Arrange variables in griddata input format
points = (x,y)
values = z
xi = (xq, yq)

car_nn = griddata(points,
                    values,
                    xi,
                    method='nearest')

#Save interpolated data values into the geodataframe
gdf_grid['car_obs'] = car_nn.round(1)

# Plot
fig, ax = plt.subplots(1,1, figsize=(8,8))
ax.ticklabel_format(useOffset=False)
bnd.plot(ax=ax, facecolor='w', edgecolor='r')
gdf_grid.plot(ax=ax, column='car_obs', edgecolor='k', cmap='OrRd')
plt.show()

The plot looks like the image below. I just need to plot the interpolations without the grid on top of it.

A: By specifying edgecolor='k' you are telling geopandas/matplotlib to draw the grid borders.
You can set edgecolor='none' to turn the borders off, but you still get some white lines as a result of antialiasing:

To get rid of those white lines, set edgecolor="face", linewidth=0.5 or edgecolor="none", antialiased=False.
Note in the example below, I also plot bnd after gdf_grid and set facecolor='none' so the boundary draws on top, otherwise the borders get masked a bit by the grid.
# Plot
fig, ax = plt.subplots(1,1, figsize=(8,8))
ax.ticklabel_format(useOffset=False)
gdf_grid.plot(ax=ax, column='car_obs', cmap='OrRd', edgecolor="none", antialiased=False)
# gdf_grid.plot(ax=ax, column='car_obs', cmap='OrRd', edgecolor="face", linewidth=0.5)
bnd.plot(ax=ax, facecolor='none', edgecolor='r')
plt.show()


text:
Q: What does rcu_note_context_switch mean when debugging context switches on a Java thread? I am trying to determine why thousands of context switches are happening to my isolated process as described here Why one non-voluntary context switch per second? so I am tracing the kernel with ftrace.
My Java thread is NOT doing any I/O or any blocking. It is on a busy spin incrementing a long variable, that's it.
Using the function tracer I see a bunch of this:

java-3372  [002] .N..  5366.541160: rcu_note_context_switch <-__schedule
java-3372  [002] d...  5366.541163: finish_task_switch <-__schedule
java-3372  [002] .N..  5366.553137: rcu_note_context_switch <-__schedule
java-3372  [002] d...  5366.553139: finish_task_switch <-__schedule
java-3372  [002] .N..  5366.565113: rcu_note_context_switch <-__schedule
java-3372  [002] d...  5366.565115: finish_task_switch <-__schedule

Does anyone know what rcu_note_context_switch means?
My kernel is 3.5.0-17-generic on Ubuntu.
I am also missing the tracer sched_switch so I used the function tracer. I did some research but I think I will have to recompile my kernel to get this sched_switch available to ftrace. Not sure what to do. Here is my ftrace available tracers. As you can see there is no sched_switch :\

# cat /sys/kernel/debug/tracing/available_tracers
blk function_graph mmiotrace wakeup_rt wakeup function nop


text:
Q: Obj-C: Swipe to delete locking app I'm having an issue with swipe to delete in UITableViews when using ECSlidingViewController.
I have a very simple example here: https://github.com/RichardSimko/ECSlidingViewControllerTest
The problem arises when you swipe to delete on the table cells, if you then try to open the menu using the menu button, which calls the method [self.slidingViewController anchorTopViewToRightAnimated:YES];, the app will lock up. However, if you use the swipe gesture to trigger the menu it won't.
As I'm not that familiar with animations and the likes I was wondering if anyone have any ideas as to what I can do to fix the issue in ECSlidingViewController. Or am I perhaps using it in the wrong way?

A: This turned out to be related to an issue with ECSlidingViewController. I fixed it in a PR, it was related to the recognizer setting isInteractive even when the view controller could not slide in the specified direction. More details in the issue on GitHub: https://github.com/ECSlidingViewController/ECSlidingViewController/issues/254


text:
Q: Error in execution of query in java class hi am not to execute the following query. it works fine in sql developer but doesnt work in my java class
    query = new StringBuilder().append("select SUBSTR(attrib,2) as DEF,DECODE(parent_id,null,null,'C'||parent_id) as xyz,'C'||attribute_id as lmn,decode(parent_id,null,'C'||(to_char(attribute_id)),'C'||parent_id||'/'||'C'||attribute_id) as abc from (select ATTRIBUTE_NAME,SYS_CONNECT_BY_PATH(ATTRIBUTE_NAME, '/') as attrib, TREESTRUCT_ATTRIBUTE_NAME,parent_id,attribute_id from MY_TABLE where TREESTRUCT_ATTRIBUTE_NAME = 'xyz' start with attribute_level =1 connect by prior attribute_id = parent_id);").toString();

Statement stmt=con.createStatement();
System.out.println("After connection");
ResultSet rs =  stmt.executeQuery(query);
System.out.println("After ececute");

query is not executed. goes to the exception block. what should i do to execute this query in my java class


text:
Q: OnClick listerner seems to stop OnLongClick? I have a listview in which previously every item was clickable, and it worked fine. But as soon as I added a feature to have all items long clicked, the onClick feature stopped working. I stripped down all my code for debugging purposes which I will submit here:
listview = (ListView) findViewById(R.id.workout_listview);
listview.setAdapter(new WorkoutListViewAdapter(this, new String[] {...}));

listview.setClickable(true);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view,  int position, long id) {
        System.out.print("CLICK");
    }
});

listview.setLongClickable(true);
listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        System.out.println("LONG CLICK");
        return true;
    }
});

This code causes nothing to happen when a list item is clicked and displays "LONG CLICK" when one is long clicked.
I found this question, which seems to have the same problem but the code is structured very differently, and my code is already following the answer's guidelines of implementing the listener on the ListView rather than the row.