text:
Q: AJAX request cancelled sometimes when api called several times In an application a url is being invoked 4 times via ajax. For some reason when the request is made the 4th time on a particular page the ajax request is cancelled.
The 4th request has "Provisional headers are shown" in its request headers and for some reason a 5th request(similar to 4th request) is made(not by the application).

I was able to do some digging in using chrome://net-internals.
Below i have reproduced the 3rd and 4th request completely and the main differences are in HTTP_TRANSACTION_READ_HEADERS portion of the network log.
The following is the entire data in the 4th request(for some reason it gets a 302 back unlike the other 3 requests -
t=61558 [st=  0] +REQUEST_ALIVE  [dt=274]
                  --> priority = "MEDIUM"
                  --> url = "https://example.com/api/v1/track/login?time=1556662845627"
t=61559 [st=  1]    NETWORK_DELEGATE_BEFORE_URL_REQUEST  [dt=0]
t=61559 [st=  1]   +URL_REQUEST_START_JOB  [dt=273]
                    --> load_flags = 0 (NORMAL)
                    --> method = "POST"
                    --> privacy_mode = 0
                    --> upload_id = "0"
                    --> url = "https://example.com/api/v1/track/login?time=1556662845627"
t=61559 [st=  1]      NETWORK_DELEGATE_BEFORE_START_TRANSACTION  [dt=0]
t=61559 [st=  1]      HTTP_CACHE_GET_BACKEND  [dt=0]
t=61559 [st=  1]     +HTTP_STREAM_REQUEST  [dt=0]
t=61559 [st=  1]        HTTP_STREAM_JOB_CONTROLLER_BOUND
                        --> source_dependency = 1619753 (HTTP_STREAM_JOB_CONTROLLER)
t=61559 [st=  1]        HTTP_STREAM_REQUEST_BOUND_TO_JOB
                        --> source_dependency = 1619754 (HTTP_STREAM_JOB)
t=61559 [st=  1]     -HTTP_STREAM_REQUEST
t=61559 [st=  1]      UPLOAD_DATA_STREAM_INIT  [dt=0]
                      --> is_chunked = false
                      --> net_error = 0 (?)
                      --> total_size = 112
t=61559 [st=  1]     +HTTP_TRANSACTION_SEND_REQUEST  [dt=1]
t=61559 [st=  1]        HTTP_TRANSACTION_HTTP2_SEND_REQUEST_HEADERS
                        --> :method: POST
                            :authority: example.com
                            :scheme: https
                            :path: /api/v1/track/login?time=1556662845627
                            content-length: 112
                            accept: application/json, text/javascript, */*; q=0.01
                            origin: https://example.com
                            x-requested-with: XMLHttpRequest
                            user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36
                            content-type: application/x-www-form-urlencoded; charset=UTF-8
                            referer: https://example.com/index.php
                            accept-encoding: gzip, deflate, br
                            accept-language: en-US,en;q=0.9
                            cookie: [1570 bytes were stripped]
t=61560 [st=  2]        UPLOAD_DATA_STREAM_READ  [dt=0]
                        --> current_position = 0
t=61560 [st=  2]        HTTP2_STREAM_UPDATE_SEND_WINDOW
                        --> delta = -112
                        --> stream_id = 117
                        --> window_size = 65424
t=61560 [st=  2]     -HTTP_TRANSACTION_SEND_REQUEST
t=61560 [st=  2]     +HTTP_TRANSACTION_READ_HEADERS  [dt=270]
t=61830 [st=272]        HTTP_TRANSACTION_READ_RESPONSE_HEADERS
                        --> HTTP/1.1 302
                            status: 302
                            date: Tue, 30 Apr 2019 22:20:45 GMT
                            content-type: text/html; charset=UTF-8
                            content-length: 0
                            location: http://example.com/api/v1/track/login?time=1556662845627
                            server: Apache/2.4.25 (Debian)
                            x-powered-by: PHP/5.6.39
                            expires: Thu, 19 Nov 1981 08:52:00 GMT
                            cache-control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
                            pragma: no-cache
                            set-cookie: [74 bytes were stripped]
                            set-cookie: [77 bytes were stripped]
                            access-control-allow-origin: *
                            access-control-allow-headers: origin, x-requested-with, content-type
                            access-control-allow-methods: PUT, GET, POST, DELETE, OPTIONS
t=61830 [st=272]     -HTTP_TRANSACTION_READ_HEADERS
t=61830 [st=272]      NETWORK_DELEGATE_HEADERS_RECEIVED  [dt=0]
t=61830 [st=272]      URL_REQUEST_DELEGATE_RECEIVED_REDIRECT  [dt=2]
t=61832 [st=274]      CANCELLED
t=61832 [st=274] -REQUEST_ALIVE

The following is the entire data in the 3rd request -
t=61346 [st= 0] +REQUEST_ALIVE  [dt=97]
                 --> priority = "MEDIUM"
                 --> url = "https://test.undostres.com.mx/api/v1/track/login?time=1556662845405"
t=61346 [st= 0]    NETWORK_DELEGATE_BEFORE_URL_REQUEST  [dt=0]
t=61346 [st= 0]   +URL_REQUEST_START_JOB  [dt=97]
                   --> load_flags = 0 (NORMAL)
                   --> method = "POST"
                   --> privacy_mode = 0
                   --> upload_id = "0"
                   --> url = "https://test.undostres.com.mx/api/v1/track/login?time=1556662845405"
t=61346 [st= 0]      NETWORK_DELEGATE_BEFORE_START_TRANSACTION  [dt=0]
t=61346 [st= 0]      HTTP_CACHE_GET_BACKEND  [dt=0]
t=61346 [st= 0]     +HTTP_STREAM_REQUEST  [dt=1]
t=61346 [st= 0]        HTTP_STREAM_JOB_CONTROLLER_BOUND
                       --> source_dependency = 1619732 (HTTP_STREAM_JOB_CONTROLLER)
t=61347 [st= 1]        HTTP_STREAM_REQUEST_BOUND_TO_JOB
                       --> source_dependency = 1619733 (HTTP_STREAM_JOB)
t=61347 [st= 1]     -HTTP_STREAM_REQUEST
t=61347 [st= 1]      UPLOAD_DATA_STREAM_INIT  [dt=0]
                     --> is_chunked = false
                     --> net_error = 0 (?)
                     --> total_size = 105
t=61347 [st= 1]     +HTTP_TRANSACTION_SEND_REQUEST  [dt=1]
t=61347 [st= 1]        HTTP_TRANSACTION_HTTP2_SEND_REQUEST_HEADERS
                       --> :method: POST
                           :authority: test.undostres.com.mx
                           :scheme: https
                           :path: /api/v1/track/login?time=1556662845405
                           content-length: 105
                           accept: application/json, text/javascript, */*; q=0.01
                           origin: https://test.undostres.com.mx
                           x-requested-with: XMLHttpRequest
                           user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36
                           content-type: application/x-www-form-urlencoded; charset=UTF-8
                           referer: https://test.undostres.com.mx/index.php
                           accept-encoding: gzip, deflate, br
                           accept-language: en-US,en;q=0.9
                           cookie: [1345 bytes were stripped]
t=61348 [st= 2]        UPLOAD_DATA_STREAM_READ  [dt=0]
                       --> current_position = 0
t=61348 [st= 2]        HTTP2_STREAM_UPDATE_SEND_WINDOW
                       --> delta = -105
                       --> stream_id = 113
                       --> window_size = 65431
t=61348 [st= 2]     -HTTP_TRANSACTION_SEND_REQUEST
t=61348 [st= 2]     +HTTP_TRANSACTION_READ_HEADERS  [dt=95]
t=61443 [st=97]        HTTP_TRANSACTION_READ_RESPONSE_HEADERS
                       --> HTTP/1.1 200
                           status: 200
                           date: Tue, 30 Apr 2019 22:20:45 GMT
                           content-type: text/html; charset=UTF-8
                           content-length: 41
                           server: Apache/2.4.25 (Debian)
                           x-powered-by: PHP/5.6.39
                           expires: Thu, 19 Nov 1981 08:52:00 GMT
                           cache-control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
                           pragma: no-cache
                           access-control-allow-origin: *
                           access-control-allow-headers: origin, x-requested-with, content-type
                           access-control-allow-methods: PUT, GET, POST, DELETE, OPTIONS
t=61443 [st=97]     -HTTP_TRANSACTION_READ_HEADERS
t=61443 [st=97]      NETWORK_DELEGATE_HEADERS_RECEIVED  [dt=0]
t=61443 [st=97]   -URL_REQUEST_START_JOB
t=61443 [st=97]    URL_REQUEST_DELEGATE_RESPONSE_STARTED  [dt=0]
t=61443 [st=97]   +HTTP_TRANSACTION_READ_BODY  [dt=0]
t=61443 [st=97]      HTTP2_STREAM_UPDATE_RECV_WINDOW
                     --> delta = -41
                     --> stream_id = 113
                     --> window_size = 6291415
t=61443 [st=97]   -HTTP_TRANSACTION_READ_BODY
t=61443 [st=97]    URL_REQUEST_JOB_FILTERED_BYTES_READ
                   --> byte_count = 41
t=61443 [st=97]    HTTP_TRANSACTION_READ_BODY  [dt=0]
t=61443 [st=97] -REQUEST_ALIVE

While trying to fix this issue we were able to get it working with following code -
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">

However it makes no sense.
PS - Here are some server logs. As you will notice, same api becomes 302 after some attempts. Also this seems related but didnt work.
 189.213.84.17 - - [30/Apr/2019:22:19:31 -0500] "POST /api/v1/track/login?time=1556680771692 HTTP/1.1" 200 1316 "https://example.com/index.php" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36"
189.213.84.17 - - [30/Apr/2019:22:19:32 -0500] "POST /api/v1/track/login?time=1556680772165 HTTP/1.1" 200 1316 "https://example.com/index.php" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36"
189.213.84.17 - - [30/Apr/2019:22:19:32 -0500] "POST /api/v1/track/login?time=1556680772167 HTTP/1.1" 200 1316 "https://example.com/index.php" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36"
189.213.84.17 - - [30/Apr/2019:22:19:32 -0500] "POST /api/v1/track/login?time=1556680772393 HTTP/1.1" 302 1534 "https://example.com/index.php" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36"

A: It looks like your web server is returning a redirect to a non secure URL
HTTP_TRANSACTION_READ_RESPONSE_HEADERS
                    --> HTTP/1.1 302
                        status: 302
                        date: Tue, 30 Apr 2019 22:20:45 GMT
                        content-type: text/html; charset=UTF-8
                        content-length: 0
                        location: http://example.com/api/v1/track/login?time=1556662845627

Chrome is refusing to redirect to that URL because it's already on HTTPS.  I guess with the meta tag in place, Chrome is transforming that HTTP into HTTPS automatically and everything works.
So first place to look would be why the server is sending a redirect to a HTTP URL when it is already receiving a HTTPS request.

A: The issue was an application level redirect(location:...) sent as a response to the ajax request.


text:
Q: Is semiconductor theory really based on quantum mechanics? Often semiconductors are cited as the big application of quantum mechanics (QM), but when looking back at my device physics book basically no quantum mechanics is used. The concept of a quantum well is presented and some derivations are done, but then the next chapter mostly ignores this and goes back to statistical physics along with referencing experimentally verified constants to explain things like carrier diffusion, etc.
Do we really need quantum mechanics to get to semiconductor physics? Outside of providing some qualitative motivation to inspire I don't really see a clear connection between the fields. Can you actually derive transistor behaviour from QM directly?

A: Many conference talks in the last 20 years began with this point and the Moore's law diagram, claiming that we are at the point where we do need to incorporate quantum mechanics in electronics design.
Band structure and mean free path
To expand a bit more about it: band structure is the basis of semiconductor electronics, so techncially quantum mechanics is necessary, since without it we would not have band structure. However, most transport phenomena  used by modern semiconductor technology can be understood in semi-classical terms: the kinetic energy is taken in the effective mass approximation and the variation in the band structure is represented as potential (potential steps, wells, etc.) This is largely due to the fast relaxation processes in semiconductors and the mean free path being smaller than the characteristic structure size. On experimental level we are beyond this limitations since a few decades, as manifested by massive research on semiconductor nanostructures: quantum wells, quantum dots, superlattices, etc. But the industry is getting there very slowly.
"Classical" is simplified quantum
Another important aspect is that many of the "classical" methods actually require rather involved quantum justifications - e.g., simple Drude model actually requires Landau Fermi liquid theory to prove its correctness (see this question).
Beyond currents
Finally, I have noted in passing that the semiclassical description works well for transport phenomena - it is not necessarily so good when we are dealing with opical phenomena, spin phenomena or even such seemingly simple things as heat capacity.

A:
Do we really need quantum mechanics to get to semiconductor physics?

It depends what level of understanding you're interested in. For example, are you simply willing to take as gospel that somehow electrons in solids have different masses than electrons in a vacuum? And that they can have different effective masses along different direction of travel? That they follow a Fermi-Dirac distribution? That band gaps exist? Etc.
If you're willing to accept all these things (and more) as true and not worry about why they're true, then quantum mechanics isn't really needed. You can get very far in life modeling devices with semi-classical techniques.
However, if you want to understand why all that weird stuff happens in solids, then yes, you need to know quantum mechanics.

Can you actually derive transistor behavior from QM directly?

It depends on the type of transistor. If you're talking about a TFET (or other tunneling devices, like RTDs and Zener diodes), then I challenge you to derive its behavior without quantum mechanics! However, if you're talking about most common transistors (BJTs, JFETs, MOSFETs, etc.), then deriving their behavior from quantum mechanics is a lot of work because the systems are messy and electrons don't "act" very quantum because of their short coherence time in a messy environment. However, the semi-classical physics used for most semiconductor devices does absolutely have a quantum underpinning. But there's a good reason it's typically not taught from first principles.
Anecdote: One time, I was sitting next to my advisor at a conference, and there was a presentation that basically boiled down to modeling a MOSFET using non-equilibrium greens functions (which is a fairly advanced method from quantum mechanics). During the presentation, my advisor whispered to me something along the lines of: "Why the heck are they using NEGF to model a fricking MOSFET?!?" In other words, just because you can use quantum mechanics to model transistors, doesn't mean you should. There are much simpler methods that are just as accurate (if not more accurate).

A: To understand how solid state physics works one needs two basic ingredients:

*

*What are (approximate) solutions of the Schrödinger equations for a single atom of a given kind.

*How are those solutions modified if said atom is part of a regular lattice of identical atoms (what are the mutual interactions of the nearest neighbors in the cristalline lattice on the outer electron shells of the atoms of said lattice).
The purely geometric relationship between these atoms, how they are piled up accounts for some properties of a cristalline lattice: diamond vs coal vs graphite, etc… but some other properties (e.g. the conductivity of a metal) can only be explained by how the behavior of the outer electron shells is modified by the cristalline structure.
So yes, the behavior of cristalline solids (conductivity, diffraction, reflection, etc.) requires the formalism of quantum mechanics and, a fortiori, so does the part of solid state physics dealing with semiconductors.

A: In short, semiconductor devices, particularly FET, are based on the principal of quantum tunneling.  Classical behaviour would say an electron could not travel through a perfect insulator/ infinite potential barrier but it is possible in QM.  Yes, you can derive behaviour from QM.  The electron wave equation will give the probability of where the electron will be (at least in one interpretation of QM).  From this you can find the probability of crossing the barrier and hence electrical properties.  More generally electron behaviour in crystals comes from solid state physics which is itself largely dervied from QM principals.

A: The question in the title is quite different from the question in the text.
But, here I will refer to the Preface in Shockley's book Electrons and Holes in Semiconductors, published in 1950 by van Nostrand.

In Part I, only the simplest theoretical concepts are introduced and the main emphasis is laid upon interpretation in terms of experimental results. This material is intended to be accessible to electrical engineers or undergraduate physicists with no knowledge of quantum theory or wave mechanics.

Part III, at the other extreme, is intended to show how fundamental quantum theory leads to the abstractions of holes and electrons ... Part III also contains an introduction to statistical mechanics and other topics applicable to the theory of electronic conduction in crystals.

Clearly Shockley thought quantum mechanics was pretty important to understanding electrons and holes, the heart of understanding a junction diode.
However, silicon 'cat whisker' diodes were invented before quantum mechanics (they were patented in 1906 per Wikipedia), but were not fully understood until solid state physics (based on quantum mechanics) was developed. Final understanding of them was the basis for the operation of the original point-contact transistor.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Product Lookup By Postal/Zip Code | Haversine Algorithm | Performance I have an application that searches for items based on a postal code.
When searching for the postal code, I return all products that are from that City/Neighborhood (done by parsing the postal/zip codes).
I now need to sort these products based on distance from the original postal/zip code.
I have the Lat/Long stored on the DB and plan to use the Haversine formula to calculate an apprx distance from the original query.
My question is, where should this be calculated.
Should I do this in a stored procedure, before returning my data set?
Or should I return my data set, with my Lat/Long, and calculate it server side before returning to user.
The calculation may need to be performed for up to 1000 results.

A: Typically, DB servers are IO-bound rather than CPU-bound. YMMV, but if your case is typical it would be desirable to perform the Haversine calculation on the DB server.
I would recommend using a customized lookup table for your arcsine calculations, as you can probably provide approximate distances on a logarithmic scale such as:

*

*100m,

*300m,

*1km,

*3km,

*10km,

*30km,

*> 30km
and then use linear interpolation as a refinement.
For the typical distances encountered with a single metropolitan area, you might consider using just 2 or 3 terms of the Taylor expansion for sin and cos rather than more exact calculations:

*

*sin(x) =~ x  -  x^3 / 6  +  x^5 / 120

*cos(x) =~ 1  -  x^2 / 2  +  x^4 / 24

Recall also that for a converging Taylor Series, the error after the n'th term is strictly less than the magnitude of the (n+1)'st term. This allows you to efficiently terminate a calculation once a desired accuracy has been achieved, which in general for the Haversine formula is only 0.5% due to the Earth not being a uniform sphere.

A: Are you using a version of SQL Server 2008 or above? If so, I recommend using the build-in geography data type rather than doing the Haversine calculation directly. You could have a table of zip codes that has the zip code (e.g. 90210) and either the central point of the zip code or the entire area covered by the zip code in another column (or both if that makes sense for your application). Then, you can use the STDistance() function to calculate the distance. Also, with spatial indexing, you can get a list ranked by distance without too much effort.


text:
Q: GLKIT and GLM Nate Robins First of all I want to thank you for looking at my problem.
Now to Describe.
My problem is that whenever I use nate robins GLM library I am unable to load my textures. However, seeing as I was unable to load textures I chose to next create arrays with no texture. None the less, I am still getting  this error. I have ran GlgetError to learn that I am receiving 1282 after glgenTexture() within the EdenSurfaces class of GLM.
EdenSurfacesTextureLoad(): GL error while generating texture name.
EdenSurfacesTextureLoad() couldn't read texture file "/var/mobile/Applications/4CD4F74F-AEF0-4D28-93D3-F5DE31938720/ObjLoaderv2.app/model/Data/101.jpg".
glmReadMTL(): Error loading texture.

Here is my code:
@implementation ViewController{

    GLMmodel *glmModel;
    NSArray *paths[2];
    NSString *myArrayString;

 }

//@synthesize glContext = _glContext;

- (void) viewDidLoad
{

    [super viewDidLoad];

    self.glContext = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];

    if (!self.glContext) {
        NSLog(@"Failed to create ES context");
    }

    GLKView *view = (GLKView *)self.view;
    view.context = self.glContext;
    view.drawableMultisample = GLKViewDrawableMultisample4X;

}

- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect
{

    paths[0] = [[NSBundle mainBundle] pathsForResourcesOfType:@".obj" inDirectory:@"model"];
    myArrayString = [paths[0] componentsJoinedByString:@" "];

    const char *stringAsChar = [myArrayString cStringUsingEncoding:[NSString defaultCStringEncoding]];

    GLfloat dimensions[3];
    glmModel =  glmReadOBJ(stringAsChar,0);

    glmCreateArrays(glmModel, GLM_NONE);

    glmDimensions(glmModel, dimensions);
    glmDrawArrays(glmModel, 0);

}

- (void) ReadInOBJ:(NSString *)file{
 glmModel =  glmReadOBJ([file UTF8String] ,0);

    if (!glmModel) {
        NSLog(@"Error: Unable to load model %@.\n", file);
    }
}
@end

Update: I solved my error my added glGenerateMipMapOES within the GLM library. However, I am still getting any of my model to load within in glkit. Nothing comes and I see now error message. What could I be doing wrong in integrating glkit and Nate Robins GLM?


text:
Q: Unable to wrap text in Kendo UI Angular grid I'm using a AngularJS Kendo UI data grid and there is a column which could have long string values. I want this column to wrap it's text.
Below is the column definition from my gridOptions in my controller:
{
    field: "ErrorMsg",
    title: "Error Msg",
    type: 'string',
    headerAttributes: 'style="overflow: visible; white-space:normal; text-align:center"',
    attritbutes: { style: "overflow: visible; white-space:normal; text-align:left; word-wrap:break-word;" }
}

I've explored some solutions provided on other forums but nothing worked so far.
Update: Attaching screenshot of the view.


text:
Q: How to stop bash being too smart restricting completion options? I often come across bash getting in my way when I'm doing something like this:
cmake -DCMAKE_INSTALL_PREFIX=/usr/<TAB><TAB>

Apparently, bash doesn't see that cmake can accept paths and I don't get anything suggested for completion. This happens for instance on Ubuntu 14.04 with bash 4.3.42. It doesn't happen on Ubuntu 12.04 with bash 4.2.25 and on BLFS with manually-compiled bash 4.3.39.
As a workaround I have to insert ls at the beginning of the line, add a space between = and the path, and only then does bash show me the completion options. After I've written the whole path I now have not to forget to remove the added workaround.
How can I setup bash to behave without this smartness — i.e. to always suggest paths if it doesn't have any other suggestions?

A: Bash does complete file names on the command line of cmake. It's looking for a directory called -DCMAKE_INSTALL_PREFIX= containing a subdirectory called usr, but not finding anything. A quick fix to get filename completion in this scenario is to add a space after the equal sign, and remove it afterwards.
You can always complete filenames regardless of context by calling the readline function complete-filename, bound to Alt+/ by default.
I don't think bash has a generic completion fallback feature, you'd have to add that to each individual completion function. (Or switch to zsh.)


text:
Q: How can I hide the documentation of helper functions? I'm maintaining a package that has a number of helper functions documented with .rd files. As they are not exported, they are not easily accessible by users - this is good. However, they still show up in the index of package help files.
Is there a way to have documentation removed from the index so that it does not clutter it, but still accessible via help?

A: There's a field in the Rd file you can add called keywords. Most keywords don't do anything except help you search for functions with one notable exception: internal. Marking a function with the internal keyword removes it from the index. According to the roxygen2 vignette:

@keywords keyword1 keyword2 ... to add standardised keywords. Keywords are optional, but if present, must be taken from the predefined list replicated in the keywords vignette. Keywords are not very useful, except for @keywords internal. Using the internal keyword removes all functions in the associated .Rd file from the documentation index and disables some of their automated tests. A common use case is to both export a function (using @export) and marking it as internal. That way, advanced users can access a function that new users would be confused about if they were to see it in the index.

Adding @keywords internal to the roxygen comments will give the desired result.

A: A little bump for people experiencing @keywords internal not working;
I made the mistake of mixing up ??PACKAGENAME and help(package="PACKAGENAME"). Because of this I was left confused why I still saw the documentation of the internals. ?? loads ALL documentation of your package and is not neccesarily the user help index.
Very basic mistake, but there ya go.


text:
Q: How to determine whether a variable is a nngraph.Node in Lua(Torch7) Suppose there is a variable named a,
the output of print(a) is nngraph.Node  (this is from torch7 package)
and
the output of print(type(a)) is table
How can I use an if to determine whether a variable is an nngraph.Node
The statement
if a== nngraph.Node then

or
if a== "nngraph.Node" then

are both NOT correct!


text:
Q: jquery "Filtering" a ul/li "tree" of data to show all children when a filter is met Given a tree of information, I have a need to "filter" the data in such a way that if someone queries for "Beta", they see Category 1 > Beta > ShowThisasWell
A crucial point is that these

 are created by some other component from json data. For the time being, I'm only concerned about the case where the nodes are created in dom. I'll figure out how to invoke the code to filter the actual data.

Category 1

Beta

ShowThisasWell

A: function filter(query) {
    $('li').hide();
    $('li li > div').each(function(){
        if($(this).text() == query) {
            $(this).parents('li').show();
            $(this).next().find('li').show();
        }
    });
}

This is specific to the code you provided, and will probably need to be tweaked (I'd add an id / class on your parent div to identify it within the document).
JSFiddle http://jsfiddle.net/va7yh/


text: Q: Unity 5.3 on Android M Why does unity ask at app start up for storage permission even if I need the storage permission later in my game? (using Unity 5.3) is there any way to disable this and let me ask for it when I need it?


text:
Q: How to use IF EXISTS in SQL (ifexists update, else insert in SQL) string searched = TextBox1.Text; // for example, text is 4477

...

sorgu.CommandText = "IF EXISTS(SELECT * FROM [Pins] WHERE Pin =' " + searched.ToString() + " ') BEGIN UPDATE [Pins] SET SAY= SAY+1, Pin = ' " + searched.ToString() + " ' END ELSE BEGIN INSERT INTO Pins(SAY,Pin) VALUES (+1,' " + searched.ToString() + " ') END";

...

I am using SAY for counting the number of searches.
This code is changing all records on column (Pins) to searched text.
Where/What is my fault?

A: You need to have a where to not update all records. This would fix it.... but is a horrible query.
IF EXISTS(SELECT * FROM [Pins] WHERE Pin = 'searched.ToString()')
BEGIN
    UPDATE [Pins] SET SAY = SAY + 1
    WHERE [Pin] = 'searched.ToString() '
END
ELSE
BEGIN
    INSERT INTO Pins(SAY, Pin) VALUES (1, 'searched.ToString()')
END

A: In pseudo code, you're saying
IF EXISTS(SELECT Statement) UPDATE ALL ROWS

The correct way to do this with EXISTS is
UPDATE TABLE
WHERE EXISTS(Correlated SELECT Statement)

A: You missed the WHERE clause.
I would also prefer using Parameters instead of string concatenated query (which makes your code open to SQL injection attacks)
string searched = TextBox1.Text; // for example, text is 4477

sorgu.CommandText = "IF EXISTS(SELECT * FROM [Pins] WHERE Pin = @searched) BEGIN UPDATE [Pins] SET SAY=SAY+1 WHERE Pin = @searched END ELSE BEGIN INSERT INTO Pins(SAY,Pin) VALUES (1, @searched) END";
sorgu.Parameters.AddWithValue("@searched", TextBox1.Text);


text:
Q: How to make PyCharm profiler show percentage of last call, not percentage from total? I saw this tutorial on how to use Pycharm's profiler.
Applying this to my large code base gives a rather unusable graph, as I only need to optimize some sub-sub tree of the computation, but that sub-tree is less than 10% of the total computation.
I would like to see each percentage in the graph relative to its direct parent, not relative to the root.
Can this be configured somehow?


text:
Q: Difference in JAXB Java 7 versus Java 8 I've found another difference between handling Jaxb on Java 7 versus Java 8. I've reduced the issue to a simplified example, and the code should run as a single class. (changed the categories so it's non-work-related etc) When the setter for a List is called by the Unmarshaller:
My Question is really a variation of

*

*Is the recommended practice for coding List accessors to omit the
Setter altogether when coding JaxB ? ( since it seems to do handle the
List via the Getter )

*Are there recommended alternative approaches?

When run in Java 7 the setter will be called with data in the List.
When run in Java 8 the setter will be called only with an empty List object which apparently gets populated later in the unmarshalling process.
The difference I experience is that I must not have the setter do any processing on the List, but rather have a process that is invoked only after the overall object is unmarshalled. Or to sum it up, "don't do any processing in the setter".
Example is below: (Three classes) - Under Java 7 the result returned is the first "album" title on the list as found in the setter. Under Java 8 a null is returned.
The code should run as a single class with no dependencies.
If run in Java 7 "First Album" title displayed is "Abbey Road".
If run in Java 8 "First Album" title is null
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

public class MainJaxbCase {
    public static void main( String[] args ) {
        new MainJaxbCase().testIt();
    }
    private void testIt() {
        try {
        AlbumLib   myLib = (AlbumLib) loadJaxbDocFromString( inXmlStr, AlbumLib.class );
        System.out.println("category:"+ myLib.getCateg());
        List<AlbumItm> albumList = myLib.getAlbumList();
        System.out.println("AlbumList size is " + albumList.size());
        System.out.println("The first album is titled:"
                + myLib.getFirstAlbumTitle()
                + "- shows \"null\" if using Java 8,  \"Abbey Road\" if using Java 7"
             );
        } catch ( Exception e ) {
            System.out.println( e.getClass().getSimpleName() + ", msg:" + e.getMessage() );
            e.printStackTrace();
        }
    }
    private final String inXmlStr =
            "<my_lib categ='albums'>"
            + "  <album title='Abbey Road'/> "
            + "  <album title='Revolver'/>"
            + "  <album title='Sgt.Pepper'/>"
            + "</my_lib>";

    private Object loadJaxbDocFromString ( String inStr, Class<?> clazz ) throws Exception {
        Object result = null;
        try {
            InputStream is = new ByteArrayInputStream( inStr.getBytes() );
            result = unmarshal( is, clazz  );
        } catch ( Exception e ) {
            String msg = this.getClass().getSimpleName() + ".loadJaxbDocFromResource() caught " + e.getClass().getSimpleName() + " msg:" + e.getMessage();
            throw new Exception(msg);
        }
        return result;
    }
    private Object unmarshal( InputStream prmIs, Class<?> clazz ) throws Exception{
        Object obj = null;
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance( clazz );
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            obj = jaxbUnmarshaller.unmarshal( prmIs );
        } catch ( Exception e ) {
            String msg = this.getClass().getSimpleName() + " caught " +
                    e.getClass().getSimpleName() + ", msg:" + e.getMessage();
            msg += " Trying to Unmarshall class " + clazz.getName();
            System.err.println(msg);
            e.printStackTrace();
            throw new Exception(msg);
        }
        return obj;
    }
}

@XmlRootElement ( name= "my_lib")
class AlbumLib {
    private String      categ;
    private List<AlbumItm> albumList;
    private String firstAlbumTitle;

    @XmlAttribute ( name="categ")
    public String getCateg() {
        return this.categ;
    }
    public void setCateg( String val ) {
        this.categ=val;
    }

    @XmlElement ( name="album")
    public List<AlbumItm> getAlbumList() {
        return this.albumList;
    }
    public void setAlbumList( List<AlbumItm> newList ) {
        if ( newList != null && newList.size() > 0 ) {
            firstAlbumTitle = newList.get(0).getTitle();
        }
        this.albumList = newList;
    }
    public String getFirstAlbumTitle() {
        return this.firstAlbumTitle;
    }
}

@XmlType(name = "album")
class AlbumItm {
    private String title;
    @XmlAttribute ( name="title" )
    public String getTitle() {
        return this.title;
    }
    public void setTitle(String val ) {
        this.title = val;
    }
}

This question arose because we had code that started behaving with subtle (but important) differences when it was switched to Java 8, but without any obvious exceptions.

A: We met the same problem with you, as this blog post stated.

*

*Is the recommended practice for coding List accessors to omit the Setter altogether when coding JaxB ? ( since it seems to do handle the List via the Getter )

*Are there recommended alternative approaches?

The point is not to 'omit the Setter' but not to add more functionality to setter. Setter is just setter, nothing more. Adding more logic violate the 'single responsibility rule' for setter and the name of this function diff from what it actually done, where more bugs may arise.
When it comes the recommended ways, there is no standard answer that covers all cases. Considering there exist no constructor init (which is somewhat hard for JAXB to do) and we need more logic after setter, we have two directions which you can take:

*

*Use XmlAdapter to customize the construction to add logic: adapter examples;

*Not adding any logic in this class, creating another class to process the data from xml -- (this is preferred, as this class is just some DTO which should not have logic)


text:
Q: Error installing a python package from github in canopy terminal I am trying to install orbital.py from github using the canopy command line and pip install.
The terminal is not letting me copy and paste the error message so I will include a picture.
The main issue seems to be raise SSLError(e, request=request) SSLError: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590)

A: Seems like this package is on PyPy, so you can just install it like this
pip install orbitalpy

If you want to install the latest version from github, you can install it like this
pip install -e git+https://github.com/RazerM/orbital.git#egg=orbital

A: From the SSL error, I suspect that you're running an old version of Canopy. What version are you running?
The current version is 2.1.9. To update Canopy, and for a link to release notes, please see "Installing a new Canopy version".


text:
Q: Finding radius of convergence $\sum _{n=0}^{}(2+(-1)^n)^nz^n$ 1) $\sum _{n=0}^{}(2+(-1)^n)^nz^n$
2) $\sum _{n=0}^{}n!z^n$
3) $\sum _{n=1}^{}\frac{1}{n^2}(\sqrt{ n^2+n}-\sqrt{n^2+1})^nz^n$
Hello, I struggle to show the radius of convergence for the above functions. I began with the second one and came to the conclusion that the radius of convergence is $0$ but I'm not sure if that's correct. I would appreciate it if you could help me with the other ones!

A: (2) and (3) left to you. first one is a little bit tricky. $\frac{1}{ROC}=
\limsup_{n\to \infty}|a_n|^{\frac{1}{n}}$. $$\limsup_{n\to \infty}|a_n|^{\frac{1}{n}}=3.$$


text:
Q: Why are menu items aligned so strangely on the ActionMenuView inside the toolbar? Why are menu items aligned so strangely on the toolbar?

It behaves even more strangely with smaller toolbar:

I use the following code:
MainActivity.java:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    //getMenuInflater().inflate(R.menu.menu_main_right, menu);

    Toolbar toolbar = findViewById(R.id.toolbar);
    ActionMenuView toolbarLeft = toolbar.findViewById(R.id.toolbarLeft);
    getMenuInflater().inflate(R.menu.menu_main_left, toolbarLeft.getMenu());

    return true;
}

activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:theme="@style/ActionBar"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <android.support.v7.widget.ActionMenuView
            android:id="@+id/toolbarLeft"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:gravity="center_vertical|start"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    </android.support.v7.widget.Toolbar>

</android.support.constraint.ConstraintLayout>

styles.xml:
<resources>

    <style name="ActionBar">
        <item name="android:background">@drawable/toolbar</item>
        <item name="actionMenuTextColor">@color/colorToolbarText</item>
    </style>

</resources>

menu_main_left.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">

    <item
        android:id="@+id/actionAdd"
        android:title="Add"
        app:showAsAction="always"/>

    <item
        android:id="@+id/actionDetails"
        android:title="Details"
        app:showAsAction="always"/>

    <item
        android:id="@+id/actionLegend"
        android:title="Legend"
        app:showAsAction="always"/>

    <item
        android:id="@+id/actionSettings"
        android:title="Settings"
        app:showAsAction="always"/>

</menu>


text:
Q: Cannot Push values of one array into another in Angular pipes I am unable to store the values of items[] array in the ResultSet[]. I have tried many ways to store the values but i am not able to it. Below is my code for Pipe.
    import { Pipe, PipeTransform } from '@angular/core';
    import { Bus } from '/home/pavan/Desktop/Pavan/apstrtcAngular/src/app/Bus';
    import { Item } from './Item';
    @Pipe({
      name: 'boardingFilter'
    })
    export class BoardingFilterPipe implements PipeTransform {
      transform(items: Bus[], customfilter1: Item[]): Bus[] {
    let ResultSet: Bus[];
        if (!items || !customfilter1) {
          return items;
        }
        else if (customfilter1.length == 0) {
          return items;
        }
        else{
        for (let i = 0; i < items.length; i++) {
          for (let j = 0; j < customfilter1.length; j++) {
            if (customfilter1[j].item_text === items[i].boardingpoint) {
              ResultSet.push(items[i]);
              console.log("Result Set =" + ResultSet);
            }
          }
        }
        return ResultSet;
      }
    }
}

Below is the Bus class and the Item class
    export class Bus {
    serviceno: String;
    board: String;
    destination: String;
    duration: string;
    type: string;
    price: string;
    bustype: string;
    boardingpoint: string;
    droppingpoint:string
  }

The Item Class is
export class Item {
    item_id: string;
    item_text:string;
  }

A: The Angular team and many experienced Angular developers strongly recommend moving filtering and sorting logic into the component itself. The component can expose a filteredHeroes or sortedHeroes property and take control over when and how often to execute the supporting logic. Any capabilities that you would have put in a pipe and shared across the app can be written in a filtering/sorting service and injected into the component.
https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe


text:
Q: ORACLE Constraint to allow Null Value, IF I'm working with oracle for the first time, and I have a table called ExpenseReport which stores details about expenses.
I want Nulls to be allowed for ApprUserNo IF ERStatus = 'PENDING'
Any help would be greatly appreciated, I've been trying to sort this all morning
CREATE TABLE ExpenseReport
(
  ERNo           NUMBER(10) NOT NULL,
  ERDesc         VARCHAR2(255) NOT NULL,
  ERSubmitDate   DATE NOT NULL,
  ERStatusDate   DATE NOT NULL,
  ERStatus       VARCHAR2(8) DEFAULT 'PENDING' NOT NULL,
  SubmitUserNo   NUMBER(10) NOT NULL,
  ApprUserNo     NUMBER(10) NOT NULL CONSTRAINT BEN_Check CHECK (ERStatus LIKE('PENDING')),
  UsersUserNo    NUMBER(10) NOT NULL,
  AssetAssetNo   NUMBER(10) NOT NULL,
  PRIMARY KEY (ERNo),
  CONSTRAINT Check_ER_Date CHECK (ERStatusDate >= ERSubmitDate),
  CONSTRAINT ERStatus_Null_Exception CHECK (IF ERStatus = 'PENDING',AppUserNo = NULLABLE),
  CONSTRAINT ERStatus_Option CHECK (ERStatus = 'PENDING','APPROBED','DENIED')
)

A: You need to re-form your constraints.
First, if you ever want a field to hold nulls, regardless of any other rules, it must be a nullable field.
ApprUserNo     NUMBER(10)   NULL,   -- No Check Constrain

Second, create a constraint that says ApprUserNo can not be NULL, unless ErStatus = 'PENDING'
CONSTRAINT ERStatus_Null_Exception CHECK (AppUserNo IS NOT NULL OR ERStatus = 'PENDING'),

A: This should do it:
CONSTRAINT ERStatus_Null_Exception
     CHECK (ERStatus <> 'PENDING' AND AppUserNo IS NOT NULL)

You should also change:
CONSTRAINT BEN_Check CHECK (ERStatus LIKE('PENDING'))
to
CONSTRAINT BEN_Check CHECK (ERStatus = 'PENDING')
because a) LIKE is not a function and b) LIKE without wildcards does not make sense.

Then you have another error here:
CONSTRAINT ERStatus_Option CHECK (ERStatus = 'PENDING','APPROBED','DENIED')
that should be
CONSTRAINT ERStatus_Option CHECK (ERStatus IN ('PENDING','APPROBED','DENIED'))
Please re-read the chapter in the Oracle manual that documents the syntax for CREATE TABLE and SQL conditions.


text:
Q: Cant log in to my wrbsite and cant find a mistake in elseif What can be wrong? cant seem find the mistake getting login=error but cant see what i wrote wrong in my last code part with elseif or maybe its not eelseif but if i not getting username or passwords or empty error it must be the last part or iam wrong ? but i dont know hot to solve it please help me.
<?php
session_start();
if (isset($_POST['submit'])) {
    include 'dbh.inc.php';
    $uid = mysqli_real_escape_string($conn, $_POST['uid']);
    $pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
    if (empty($uid) || empty($pwd)) {
        header("Location: ../index.php?login=empty");
        exit();
    } else {
        $sql = "SELECT * FROM users WHERE user_uid='$uid'";
        $result = mysqli_query($conn, $sql);
        $resultCheck = mysqli_num_rows($result);
        if ($resultCheck < 1) {
            header("Location: ../index.php?login=username error");
            exit();
        } else {
            if ($row = mysqli_fetch_assoc($result)) {
                $hashedPwdCheck = password_verify($pwd, $row['user_pwd']);
                if($hashedPwdCheck == false) {
                    header("Location: ../index.php?login=password error");
                    exit();
                } elseif ($hashedPwdCheck == true) {
                  //Log in the user here
                  $_SESSION['u_id'] = $row['user_id'];
                  $_SESSION['u_first'] = $row['user_first'];
                  $_SESSION['u_last'] = $row['user_last'];
                  $_SESSION['u_email'] = $row['user_email'];
                  $_SESSION['u_uid'] = $row['user_uid'];
                  header("Location: ../index.php?login=success");
                  exit();
                }
            }
        }
    }
} else {
    header("Location: ../index.php?login=error");
    exit();
}

A: It means "submit" is not set.
What is your submit button's name?
Change it to this:
<input type="submit" value="Submit" name="submit" />

the name="submit" is important


text:
Q: Loading Error in VSU WPF Designer I'm using Visual Studio Ultimate 2010 (32-bit). I am building a project in Visual Basic 2010 and WPF 4.
I had the WPF designer working just fine until yesterday, when I tried installing the Silverlight 4 Tools for Visual Studio 2010 from Microsoft. However, as soon as I installed it, I started getting the following error in the designer every time I tried loading any WPF window. I uninstalled the tools and reinstalled Visual Studio Ultimate, to no avail.

Problem Loading The document contains
  errors that must be fixed before the
  designer can be loaded. Reload the
  designer after you have fixed the
  errors.

However, the project compiles and runs without incident, and there are no errors being shown in the XAML text. Here is the first part of the XAML for each window, in case this helps.
<Window x:Class="FRM_TEACHER"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="FRM_TEACHER" Height="Auto" Width="Auto" WindowStyle="None" WindowState="Maximized" WindowStartupLocation="CenterScreen" Background="Black">
<Grid Width="640" Height="480">

Help?

A: After uninstalling and reinstalling the Silverlight 4 tools, it worked.


text:
Q: How to create columns for a CSV file with shell I'm trying to make a program that will monitor my CPU cores over time, using a little shell as I'm trying to learn it.

*

*I want to determine the # of cores

*I then want to create a column for each core, so that I can add the data to each core when I collect it.

The csv file would create the columns like: Core1, Core2, Core3, Core4, Core5, Core6, Core7, Core8
#!/bin/sh

cores=grep -c ^processor /proc/cpuinfo #Shows I have 8 cores

touch core_monitor.csv #make csv file

echo core{1..cores}, >> core_monitor.csv
#This echo doesn't work. it prints the string literal `core{1..cores},`


text:
Q: How to get Index numbers while using diff-match-patch in java? I am using google's diff-match-patch in java for finding differences in two strings.
String s1 = "Comment, Version, Message Type, Action, USI prefix, USI Value, Primary Asset";
String s2 = "Comment, Version, Message Type, Action, USI prefix, JPY Value, Primary Asset, Secondary Asset";

DiffMatchPatch dmp = new DiffMatchPatch();
LinkedList<DiffMatchPatch.Diff> diff = dmp.diffMain(s1, s2, false);

System.out.print(diff);

The code is giving correct output:
[Diff(EQUAL, "Comment, Version, Message Type, Action, USI prefix,"),
 Diff(DELETE, "USI"),
 Diff(INSERT, "JPY"),
 Diff(EQUAL, "Value, Primary Asset"),
 Diff(INSERT, ", Secondary Asset")]

How to know that at which index the change has occured? E.g. there are two "USI" in the string, how to know that which "USI" is modified? I need the index numbers at which the change occured.


text:
Q: Error itms 90086 while submitting app to itunes connect? I tried changing architectures to standard architectures and set build active architectures to "No", added armv7,arm64,armv7s to valid architectures for both project and target.but still get the error 90086.
 any help is appreciated.

A: They should be set to as following :

A: Here is an answer that resolve that. You should set target and project to standard architecture. LINK


text:
Q: How to use page-break and avoid white space to split my div over multiple pages when printed? On my page I have some content loaded from my database. All this content is placed inside a DIV, nicely styled with images, font styles and background image. I want the visitor to be able to print this content without losing the styles.
I get everything to work nicely, except for the pagebreak. Somehow whatever I try, there's always a small space placed beneath every div that makes my DIV result in a position slicely lower that it's previous. In other words: the more page's the content needs, the more of the DIV is cut into half and shown on the next page. See below for an illustration of my problem.
The CSS
@media all {
.page-break {
    display: none;
}

.wrapper_programmaker:after {
  padding-top: 70.71%;
  display: block ;
  content: '';
}
}

@media print {
.page-break {
    display:inline-block; page-break-after: always;
}

.wrapper_programmaker:after {
  padding-top: 70.71%;
  margin-bottom: -0.9%;
  display:block;
  content: '';
}
}

.main_programmaker {
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  color: #282828;
  font-family: 'Frutiger', sans-serif;
}

The PHP

  <? mysqli_fetch_array { ?>

        //way more divs and content that are irrelevant for this question

  <? } ?>

And the JS
function printDiv(printableArea) {
    var printContents = document.getElementById('printableArea').innerHTML;
    var originalContents = document.body.innerHTML;
    document.body.innerHTML = printContents;
    window.print();
    document.body.innerHTML = originalContents;
}

Image example of my problem:


text:
Q: Errno 36 :File name too long: "testLogisticRegression" I have a function that does classification. I am encountering a problem when exporting data. Here is the stack trace:
[Errno 36] File name too long: "testLogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,\n                   intercept_scaling=1, l1_ratio=None, max_iter=100,\n                   multi_class='warn', n_jobs=None, penalty='l2',\n                   random_state=None, solver='warn', tol=0.0001, verbose=0,\n                   warm_start=False).xlsx"

My code :
def classifieur(X, y):
    X = matrix(X)
    model_l = LinearSVC()
    model_m = MultinomialNB()
    model_lr = LogisticRegression()
    model_r = RandomForestClassifier()
    model_k = KNeighborsClassifier()
    models = [model_l, model_m, model_lr, model_r, model_k]
    cv_splitter = KFold(n_splits=10, shuffle=False, random_state=None)
    for model in models:
        y_pred = cross_val_predict(model, X, y, cv=cv_splitter)
        print("Model: {}".format(model))
        print("Accuracy: {}".format(accuracy_score(y, y_pred)))

        # export
        res = pd.DataFrame()
        res['Expected Output'] = y
        res['Predicted Output'] = y_pred
        print(output.head())
        res.to_excel("test{}.xlsx".format(model))

classifieur(X, y)

The function works. It is just the name of the file that poses a problem. I am working in a linux environment.

A: Create a dict with model name and model value and use the model name as file name:
def classifieur(X, y):
    X = matrix(X)
    model_l = LinearSVC()
    model_m = MultinomialNB()
    model_lr = LogisticRegression()
    model_r = RandomForestClassifier()
    model_k = KNeighborsClassifier()
    models = {'model_l': model_l, 'model_m': model_m, 'model_lr': model_lr, 'model_r': model_r, 'model_k': model_k}
    cv_splitter = KFold(n_splits=10, shuffle=False, random_state=None)
    for model_name, model in models.items():
        y_pred = cross_val_predict(model, X, y, cv=cv_splitter)
        print("Model: {}".format(model))
        print("Accuracy: {}".format(accuracy_score(y, y_pred)))

        # export
        res = pd.DataFrame()
        res['Expected Output'] = y
        res['Predicted Output'] = y_pred
        print(output.head())
        res.to_excel("test{}.xlsx".format(model_name))


text:
Q: Paypal Config All Greyed out/Disabled in magento backend
For some reason all my paypal configure buttons became disabled and greyed out. I filled in all my store info and thats correct so that cant be the case. I am on magento 1.9.1

A: From store scope select website or Store instead of store view.


text:
Q: "getOutputStream() has already been called for this response" Exception when downloading a file with spring mvc I am downloading a file from a jsp and a function in the controller is only a path to arrive to the jsp. However, I receive the "getOutputStream() has already been called for this response" exception. I have tryed a lot of solutions in other questions but nothing worked for me.
My controller:
   @RequestMapping(value="/openfile", params ={"path"})
public String openFile(@RequestParam(value="path", required=false) String path, ModelMap model) throws IOException {
    model.addAttribute("path", path);
    return "openfile";
}

My JSP:
String url = request.getParameter("path");
ServletOutputStream stream = null;
BufferedInputStream buf = null;
try {
    File file = new File(url);
    stream = response.getOutputStream();
    response.setContentType("application/download");
    response.addHeader("Content-Disposition", "attachment; filename=" + file.getName());
    response.setContentLength((int) file.length());
    FileInputStream input = new FileInputStream(file);
    buf = new BufferedInputStream(input);

    int readBytes = 0;
    while ((readBytes = buf.read()) != -1) {
        stream.write(readBytes);
    }
} catch (IOException ioe) {
    throw new ServletException(ioe.getMessage());
} catch(Exception ex){
    System.out.println("[openfile] Error: " + ex.getMessage());
} finally {
    if (stream != null) {
        stream.close();
    }
    if (buf != null) {
        buf.close();
    }
}

Exception:
 java.lang.IllegalStateException: getOutputStream() has already been called for this response
at org.apache.catalina.connector.Response.getWriter(Response.java:578)
at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:212)
at org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:115)
at org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:108)
at org.apache.jasper.runtime.PageContextImpl.release(PageContextImpl.java:183)
at org.apache.jasper.runtime.JspFactoryImpl.internalReleasePageContext(JspFactoryImpl.java:120)
at org.apache.jasper.runtime.JspFactoryImpl.releasePageContext(JspFactoryImpl.java:75)
at org.apache.jsp.WEB_002dINF.views.openfile_jsp._jspService(openfile_jsp.java:154)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:721)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:466)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:391)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:318)
at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:209)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:267)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1221)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1005)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:952)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1527)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1484)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)

The file is downloaded correctly but I receive this annoying message.
Thanks!

A: Ditch the JSP, that code belongs in the controller and move the response.getOutputStream to a point where you need it.
@RequestMapping(value="/openfile", params ={"path"})
public void openFile(@RequestParam(value="path", required=false) String path, ModelMap model, HttpServletResponse response) throws ServletException {

    try {
        File file = new File(path);
        response.setContentType("application/download");
        response.addHeader("Content-Disposition", "attachment; filename=" + file.getName());
        response.setContentLength((int) file.length());
        FileInputStream input = new FileInputStream(file);
        BufferedInputStream buf = new BufferedInputStream(input);
        FileCopyUtils.copy(buf, response.getOutputStream());
    } catch (IOException ioe) {
        throw new ServletException(ioe.getMessage());
    } catch (Exception ex) {
        System.out.println("[openfile] Error: " + ex.getMessage());
    }
}


text:
Q: Filtering an instance with multiple binds doesn't seem to work The idea is to take a model instance and partition it according to a score.
      <bind nodeset="instance('mDetails')/review" readonly="true()" id="liked" relevant="algorithmScore > 0"/>
  <bind nodeset="instance('mDetails')/review" readonly="true()" id="neutral" relevant="algorithmScore = 0"/>
  <bind nodeset="instance('mDetails')/review" readonly="true()" id="disliked" relevant="algorithmScore < 0"/>

Where above we have an instance containing all the reviews and I want to create different bindings based on the algorithm score (positive, neutral or negative).
Then in my UI
            <repeat bind="liked">
          <input ref="@critic">
            <label>Critic</label>
          </input>

is supposed to retrieve the subset that liked it (algorithmScore is positive) etc
However when I run this code I get the dislikes showing up when I request the  likes and the model prunes away the non-relevant rows (which I believe is supposed to happen).
Am I right that XForms is not designed to do this sort of thing in this way?

A: Only the last bind element is considered because all bindings are defined for the very same node set.

A: I have implemented what I want by simply applying a predicate to the nodeset in the UI.


text:
Q: Distinguish between server-side errors and connection problems As described in the Codename One blog post "Terse Table, Radar Chart and Networking Enhancements":

Better Error Code Handling
Up until recently if we got an error response code it wasn't sent
  through the global error handler and was handled via the local error
  handling chain first. This is no longer the case and these errors are
  now handled correctly.
However, if you relied on that misbehavior of older versions we have
  setHandleErrorCodesInGlobalErrorHandler(boolean). This defaults to
  true, you can set it to false to change the default behavior.

So, the global error handler is invoked both by server-side errors and connection problems. It's a very good thing to be able to manage networks errors in the most generic way, however I need to distinguish between server-side errors and connection problems.
After some testing, I wrote the following code, tested on Simulator, Android and iOS:
addNetworkErrorListener(err -> {
            // prevents the event from propagating
            err.consume();

            if (err.getError() != null) {
                // this is the case of a network error,
                // like: java.io.IOException: Unreachable
                Log.p("Error connectiong to: " + err.getConnectionRequest().getUrl());
                // maybe there are connectivity issues, let's try again
                ToastBar.showInfoMessage("Trying to reconnect...");
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        err.getConnectionRequest().retry();
                    }
                }, 2000);
            } else {
                // this is the case of a server error
                // logs the error
                Log.p("REST ERROR\nURL:" + err.getConnectionRequest().getUrl()
                        + "\nMethod: " + err.getConnectionRequest().getHttpMethod()
                        + "\nRequest body: " + err.getConnectionRequest().getRequestBody()
                        + "\nResponse code: " + err.getConnectionRequest().getResponseCode()
                        + "\nResponse message: " + StringUtilities.toString(err.getConnectionRequest().getResponseData()),
                        Log.ERROR);

                Log.sendLogAsync();
                ToastBar.showErrorMessage("Server Error", 10000);
            }
        });

In the tested platforms, server-side errors are reported, but no further action follows; connectivity errors are both reported and managed by retrying the connection every two seconds.
So, that code works.
Anyway, what I don't like is the assumption that err.getError() != null is true for connectivity errors, false for server-side errors. I came to this assumption after several tests, but I didn't find it documented anywhere.
So my question is whether:

*

*my assumption is always correct;

*there is a better way to distinguish server-side errors from connectivity errors.

Thank you


text:
Q: How to return http status 403 on http connection, not on https using Spring I am using spring mvc and spring security to lock down a webservice. I have restricted all connections to use https using this ...
<http auto-config='true'>
    <intercept-url pattern="/**" access="ROLE_USER" requires-channel="https"/>
    <http-basic/>
</http>

But when I connect over http I don't get http status code 403 Forbidden.

A: I guess you need to intercept creation of SecureChannelProcessor (for example, using BeanPostProcessor) and supply it with the custom ChannelEntryPoint that would send "403 Forbidden".


text:
Q: Error in lua script while using redis stack ReplyError: ERR Error running script (call to f_bda0b62c7548ec7a0d42a3aff20a05872c65d17e): @user_script:1: user_script:1: Attempt to modify a readonly table
    at parseError (/Users/pratham/Documents/cyndia/blog.cyndia.in/frontend/node_modules/.pnpm/redis-parser@3.0.0/node_modules/redis-parser/lib/parser.js:179:12)
    at parseType (/Users/pratham/Documents/cyndia/blog.cyndia.in/frontend/node_modules/.pnpm/redis-parser@3.0.0/node_modules/redis-parser/lib/parser.js:302:14) {
  command: {
    name: 'eval',
    args: [
      'tokens_key = KEYS[1]\n' +
        'local timestamp_key = KEYS[2]\n' +
        '\n' +
        'local rate = tonumber(ARGV[1])\n' +
        'local capacity = tonumber(ARGV[2])\n' +
        'local now = tonumber(ARGV[3])\n' +
        'local requested = tonumber(ARGV[4])\n' +
        '\n' +
        'local fill_time = capacity/rate\n' +
        'local ttl = math.floor(fill_time*2)\n' +
        '\n' +
        'local last_tokens = tonumber(redis.pcall("get", tokens_key))\n' +
        'if last_tokens == nil then\n' +
        '  last_tokens = capacity\n' +
        'end\n' +
        '\n' +
        'local last_refreshed = tonumber(redis.pcall("get", timestamp_key))\n' +
        'if last_refreshed == nil then\n' +
        '  last_refreshed = 0\n' +
        'end\n' +
        '\n' +
        'local delta = math.max(0, now-last_refreshed)\n' +
        'local filled_tokens = math.min(capacity, last_tokens+(delta*rate))\n' +
        'local allowed = filled_tokens >= requested\n' +
        'local new_tokens = filled_tokens\n' +
        'if allowed then\n' +
        '  new_tokens = filled_tokens - requested\n' +
        'end\n' +
        '\n' +
        'redis.pcall("setex", tokens_key, ttl, new_tokens)\n' +
        'redis.pcall("setex", timestamp_key, ttl, now)\n' +
        '\n' +
        'return { allowed, new_tokens }',
      '2',
      '::ffff:127.0.0.1.tokens',
      '::ffff:127.0.0.1.timestamp',
      '100',
      '500',
      '1677125916',
      '1'
    ]
  }
}

A: I found a fix that i am not using local in first variable tokens_key
so i just need to add local in first variable and it's fix the problem


text:
Q: How do I sum a column, and join it to another table based on a condition in SQL? I have two tables in SQL, one that contains product_id, products_name, department_name, and product_sales and one that has department_id, department_name, and over_head_costs.
I want to be able to find the sum of all sales (grouped by department_name in table 1) and subtract the over_head_costs from table 2 so that I know how profitable a department is. Then I want to output the information like:
department_id, department_name, over_head_costs, product/department sales, total_profit.
I've been searching for like 2-3 hours. I've messed around with joins (which I'm pretty sure is how to solve this) and found the SUM function, which achieves summing (but not by department) and honestly, even if I'd seen the solution I wouldn't know it. I'm just really struggling to understand SQL.
SELECT SUM(products.product_sales), department_id, departments.department_name, over_head_costs
FROM products, departments
WHERE products.department_name = departments.department_name;

This is my most recent query and the closest I've gotten, except it only returns one department (I currently have 3).
This is roughly what I'd like it to look like:
Table 1 (products):
ID    ITEM         DEPARTMENT                SALES

1      Hammer       Tools                     40

2.     Nails        Tools                     40

3.     Keyboard     Computer                  80

Table 2 (departments):
ID    DEPARTMENT    COST

1      Tools        20

2.     Computer     30

Output:
ID    DEPARTMENT    COST     SALES      PROFIT

1       Tools       20         80               60

2.      Computer    30         80               50

I'm not really sure what else to try. I think I'm just not understanding how joins and such work. Any help would be greatly appreciated.

A: You can try to use SUM wiht group by in a subquery. then do join.
Query 1:
SELECT d.*,
       t1.SALES,
      (t1.SALES - d.COST)PROFIT
FROM (
    SELECT DEPARTMENT,SUM(SALES) SALES
    FROM products
    GROUP BY DEPARTMENT
) t1 JOIN  departments d on d.DEPARTMENT = t1.DEPARTMENT

Results:
| DEPARTMENT | COST | SALES | PROFIT |
|------------|------|-------|--------|
|      Tools |   20 |    80 |     60 |
|   Computer |   30 |    80 |     50 |


text:
Q: Problema desarrollo web responsive Buenas una vez más a tod@s,
Estoy intentando elaborar una web responsive, pero no tengo ni idea de cómo implementar correctamente las propiedades CSS para que esto ocurra. Como se ve en el código, he intentado hacer flexboxes, pero no tengo claro que sea la mejor opción, ya que al redimensionar, las cajas de contenido también lo hacen, mientras que el texto no. Lo mismo ocurre con el logo, que al redimensionarse, va cambiando su tamaño, mientras que el h1 no lo hace.
En definitiva, que estoy bastante perdido con este asunto y me gustaría que alguien pudiera darme una orientación de dónde podría estar el fallo y qué podría hacer para que, de forma manual, el contenido fuera responsive.
Muchas gracias por adelantado.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>e-Administración -- Trámites</title>

e-Administración
 Trámites

        Informe de vida laboral

        Certificado de delitos sexuales

        Certificado de no pensionista

        <a href="https://sede.seg-social.gob.es/wps/portal/sede/sede/Ciudadanos/CiudadanoDetalle/!ut/p/z1/rVRdk5owFP0r-8Ij5iaAhr6h3WG1utZ1WYUXJyZB0_K1kMXaX19gO91-qZ2xvAQuh3Nyz8kFRWiNoozVase0yjOWNM9h1N9YuG9jF_DUh_EteMHsQ-BaC8sfY7TqAHDi8gBF579_QhGKeKYLvUdhJYXc8DzTMlMirwxoCwZw9SKYYFlbUVmcl6msbo43XJZaxYqzDoopxtjdqKyqWsqCK4FCRxDuyq0wB7HDTRsLMBkDyxQOUCmAECfm31s4sUdwL7awavUuMHSAcy6dFSF9NEHRLsm3r5F42daiOxSVMpalLHsvZVPea128M8CAw-HQK_JSs6RXdY7pkmVSV9XHrmhA8WNV2oBR57cUedlgDRhniqu8tb6s27tqw2XLkMjqb9L7vNJo_YskWjbQsDF18NYQgN_0GQxh-QQEg2-hVa3kAQVZk2bT1PItM1diETv21nSY5Zg2obZJJScm4RKIiKnjOAzdwe8KPl44rcKcjh8WGOjgSoVXemdOAU-ATKE_o-C5i2UwvccWDOwr6SeXAm-8JuVsNGu8Lpjem-3BR-sTxx-tAZ98hUL16fk58po5a6P-0uR1zaCdVvojkaENHp4_9sndLYb5Gcv-aU7PJuIDvpJ-cmnO_7eRP_-xijRIqXU0Pz_Qo5XU-126eT-8N8NJ_XV6l9TpaEsPj3G6-gal3zA1/dz/d5/L2dBISEvZ0FBIS9nQSEh/" target="_blank" class="nav_elem_flex">Certificado de prestaciones

        Renovar demanda de empleo

        Obtener declaración de la renta

Nombre de la empresa

Teléfono de contacto

e-mail

A: Buen día,
Para cambiar el tamaño del texto, en font-size : puedes utilizar la unidad vw (Viewport width) y eso hará que el tamaño de letra cambie al cambiar el tamaño de la página
Para continuar con tu aprendizaje te recomiendo la página w3schools (Aquí esta el ejemplo del tamaño de texto pero hay muchos ejemplos más)
Aquí te dejo un ejemplo con el font-size aplicado únicamente a tu h1

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>e-Administración -- Trámites</title>

e-Administración
 Trámites

        Informe de vida laboral

        Certificado de delitos sexuales

        Certificado de no pensionista

        <a href="https://sede.seg-social.gob.es/wps/portal/sede/sede/Ciudadanos/CiudadanoDetalle/!ut/p/z1/rVRdk5owFP0r-8Ij5iaAhr6h3WG1utZ1WYUXJyZB0_K1kMXaX19gO91-qZ2xvAQuh3Nyz8kFRWiNoozVase0yjOWNM9h1N9YuG9jF_DUh_EteMHsQ-BaC8sfY7TqAHDi8gBF579_QhGKeKYLvUdhJYXc8DzTMlMirwxoCwZw9SKYYFlbUVmcl6msbo43XJZaxYqzDoopxtjdqKyqWsqCK4FCRxDuyq0wB7HDTRsLMBkDyxQOUCmAECfm31s4sUdwL7awavUuMHSAcy6dFSF9NEHRLsm3r5F42daiOxSVMpalLHsvZVPea128M8CAw-HQK_JSs6RXdY7pkmVSV9XHrmhA8WNV2oBR57cUedlgDRhniqu8tb6s27tqw2XLkMjqb9L7vNJo_YskWjbQsDF18NYQgN_0GQxh-QQEg2-hVa3kAQVZk2bT1PItM1diETv21nSY5Zg2obZJJScm4RKIiKnjOAzdwe8KPl44rcKcjh8WGOjgSoVXemdOAU-ATKE_o-C5i2UwvccWDOwr6SeXAm-8JuVsNGu8Lpjem-3BR-sTxx-tAZ98hUL16fk58po5a6P-0uR1zaCdVvojkaENHp4_9sndLYb5Gcv-aU7PJuIDvpJ-cmnO_7eRP_-xijRIqXU0Pz_Qo5XU-126eT-8N8NJ_XV6l9TpaEsPj3G6-gal3zA1/dz/d5/L2dBISEvZ0FBIS9nQSEh/" target="_blank" class="nav_elem_flex">Certificado de prestaciones

        Renovar demanda de empleo

        Obtener declaración de la renta

Nombre de la empresa

Teléfono de contacto

e-mail


text:
Q: Why are most vector fields "found in nature" conservative? So I got the mathematical aspects down of what it means for a vector field to not be conservative, but I'm trying to make sense of the physical intuition. Why are so many vector fields found in nature conservative? What can be said about vector fields found in nature that are not conservative, for example, an induced electric field (Conservative nature of electric field). This is a pretty open ended question. Thanks!

A: A vector fields is conservative if it is the gradient of a scalar field. In static cases we can use the the scalar Coulomb and the Newton potentials. The force fields are then conservative. In the more general case they are not. The Coulomb and 'magnetic' vector potential form a Lorentz vector. For gravity you have to use General Relativity, which I guess does not lead to a conservative force either.

A: Your description gives the impression that most of the fields in nature are conservative which is not true and quite the opposite in classical applications and open systems. Force fields and systems where for example friction or drag is found are not overall conservative. Many confuse the law of conservation of energy with these two definitions which is irrelevant.
In general a force field in a system that does not produce any work that consumes energy which is expelled out of the system (i.e. energy transformed from one form to the other for example electric power to heat leaving the system) is considered a conservative acting field. Other characteristics of conservative fields are that the overall work done in a closed loop path is path independent which is another way to say that the overall energy consumption, work done in the system by the field is zero. For example a gravitational field without air all the potential energy is transformed to kinetic and back, independent of the path trajectory chosen going from point A to point B and back to point A again inside the field. Therefore, no work is done that consumes energy thus no energy leaves the system and therefore a gravitational field is a conservative field. However, the situation in the system totally changes when you add air drag and friction where work done consumes energy in the form of heat expelled out of the system.
Another helpful characteristic-criterion of a conservative field is that the field force in most cases acts along to the motion vector whereas in an non-conservative field the force is in many cases perpendicular to the motion vector. But these are not general rules and there are exceptions like for example, friction which is not perpendicular to the motion of an object but still is a non-conservative force.
So in the case of an electric charge moving linearly inside a magneto-static field the electromagnetic Lorentz force is always perpendicular to the linear charge motion and therefore we say that the interacting magnetic field does zero work on the linear direction of the charge's motion however the charge will now move on a spiral trajectory changing therefore its linear velocity therefore the magnetic field in this case is non-conservative since it reduces the energy of the moving electric charge.
An electrostatic field on the other hand when acting on an stationary electric charge moved on a closed loop trajectory as  in the case of a gravitational field, will in overall not  change the energy of the moving charge, overall there is no energy consumed by the electrostatic field on the electric charge, therefore a conservative field.
An electric field generated by a changing magnetic field caused by a moving magnet, in  this case the electrostatic field projected is irrotational (i.e. has a vanishing curl, vortex structure) which is another characteristic of conservative fields. See below the electrostatic field projected by moving magnet:

However when this conservative electrostatic field generated by the moving magnet is projected on a conductive loop or a solenoid or circuit only the field vectors which coincide with the loop wire will be induced inside the wire therefore creating a rotational field instead and thus a non-conservative electric field.
The list can go forever and the concept of conservative and non-conservative fields is one of the most complex subjects.
As a general conclusion a field is characterized as conservative or non-conservative always in relation with the system applied to.


text:
Q: netscape.javascript.JSException: ReferenceError: Can't find variable : Test_Vote I'm using JavaFx for loading htmp & javascript pages that uses jquery-1.9.1.min.js and pure_min.js.
Sometimes, when I launch application
I encounter an exception like :
    netscape.javascript.JSException: ReferenceError: Can't find variable: Test_Vote
    at com.sun.webkit.dom.JSObject.fwkMakeException(JSObject.java:128)
    at com.sun.webkit.WebPage.twkExecuteScript(Native Method)
    at com.sun.webkit.WebPage.executeScript(WebPage.java:1427)
    at javafx.scene.web.WebEngine.executeScript(WebEngine.java:948)

this error is randomly.
could you help me how to solve this issue, please ?
Environment used : Windows 7 64bit, JDK 1.8.0.51


text:
Q: htaccess rewrite for wildcard subdomains few hours later, i need help. I trie to rewrite the url for using wildcard subdomains.
My domains will be *.domain.com - for example mytest.domain.com
For every subdomain is a subfolder unter www.domain.com/sdom/content/mytest
I've setup the apache/nginx server. For testing i upload a index.html inside the "content" folder.
If i type mytest.comain.com this index.html will display. So now i upload the .htaccess file inside this folder to route from here to the destinations (in this example to the "mytest" folder).
I trie a lot of thiks, at least this
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.domain\.com$
RewriteCond %{HTTP_HOST} ^(.*)\.domain\.com$
RewriteRule (.*) /httpdocs/domain/sdom/content/$1/index.html

i call mytest.domain.com but it wont go to the subfolder, it go to the maindomain.
If i delete the htaccess file, the index.html of the "content" folder will display.
After rewriting the url in the adressfield of the browser shoul display mytest.domain.com - not the new path to the subfolder etc.
What i have to do, that is works ?
UPDATE
subdomains route to -> mainfolder
subdomains should route by htaccess to folder that has the same name of the subdomain
So i trie htacess
RewriteCond %{HTTP_HOST} ^(.*)\.domain\.tld$
RewriteRule ^$ /subdomainfolder/index.html

A: With .htaccess files you can't. Here mytest.domain.com and www.domain.com are different hostnames. So inevitably an external redirect will happen.
If you want different domains run by one physical server you should use virtual hosts:
<VirtualHost *:80> # Change this to *:443 if you use SSL/TLS
    ServerName mytest.domain.com # Your domain name
    DocumentRoot $SRV_ROOT/httpdocs/domain/sdom/content/mytest/ # assuming $SRV_ROOT is set to root of your server
    <Directory "$SRV_ROOT/httpdocs/domain/sdom/content/mytest/">
        Require all granted # on Apache 2.4
        # Below are instructions for Apache 2.2
        Order Allow,Deny
        Allow from all
    </Directory>
</VirtualHost>

You'll need to restart your server each time you add a subdomain, as well as having a DNS record or local record in /etc/hosts file if you test locally.


text:
Q: Logging in a page with java that first displays an error and no HTML I'm trying to login in an html web page using java's Jsoup. Problem here is that the web seem to try to log-in first (return's an un-authorized error (pic 1)) and ask credentials later using an alert box (if i'm not mistaken), and for some reason there is nothing in the html file (pic 2):

I tried something like this:
 Element loginform = doc.getElementById("alert");
    Elements inputElements = loginform.getElementsByTag("input");
    List<String> paramList = new ArrayList<String>();
    for (Element inputElement : inputElements) {
        String key = inputElement.attr("type");
        String value = inputElement.attr("value");

        if (key.equals("text"))
            value = username;
        else if (key.equals("password"))
            value = password;
        paramList.add(key + "=" + URLEncoder.encode(value, "UTF-8"));
    }

I'm not much of an expert in this field so I don't really know what could be wrong. I can't even find any ID for the alertbox anywhere since it's an empty file, CTRL+U returns blank as well...

A: It's called Basic Authentication.
Server expects you to send a request with "Authorization" header. The value of this header should start with string "Basic " followed by username and password joined with a colon : and base64 encoded.
Example:
//import java.util.Base64;

String username = "username";
String password = "password";
String joinedCredentials = username + ":" + password;
String base64EncodedCredentials = Base64.getEncoder().encodeToString(joinedCredentials.getBytes());
String authorizationHeaderValue = "Basic " + base64EncodedCredentials;

Document document = Jsoup.connect(URL)
     .header("Authorization", authorizationHeaderValue)
     .get();


text:
Q: How can I optimize this code snippet to execute faster and with a smaller footprint? We have a small script that uses memcache to track concurrent sessions, with the client making a new request every 10-seconds to "renew" its session and also get the latest count of users online.
$session    = $_GET['session'];
$streamid   = $_GET['streamid'];

if(!is_null($session) && !is_null($streamid)) {
    $memcache = new Memcache;
    $memcache->connect('localhost', 11211);

    $data   = $memcache->get($streamid);

    if($data === false) {
        $data   = array($session => time()+10);

        $memcache->add($streamid,$data,0,10);
    } else {
        $now            = time();
        $streamCount    = count($data);

        for($i=0;$i<$streamCount;$i++) {
            if($data[$i] > $now) {
                    unset($data[$i]);
            }
        }

        $data[$session] = time()+10;
    }

    echo count($data);
} else {
    echo 'no session or stream specified';
}

A: Have you tried running this yet? Do you need to optimize it? Maybe it works like how you want it right now. It seems like a better solution would be to decouple it and write it as clean as possible. Put timers around calls and if you see something being slow then try to fix that code. Don't optimize if you don't need to.


text:
Q: Cheking if an object has an attribute, without relying on '__getattr__' Is there a way to check if an object has an attribute, that doesn't rely on __getattr__ or object implementation specifics?
Consider the code below. I want Proxy to delegate to Wrapped what it can't handle. The code works, but I'd like to avoid the test attr in self.__dict__ (I'd prefer a stable interface to do this, without using implementation quirks). The function hasattr doesn't help here, because it gets routed to the wrapped object via __getattr__.
class Wrapped:
    def __init__(self):
        self.a = 0
        self.b = 1

class Proxy:
    def __init__(self, wrapped):
        object.__setattr__(self, 'wrapped', wrapped)
        object.__setattr__(self, 'a', 2)
    def __getattr__(self, attr):
        return getattr(self.wrapped, attr)
    def __setattr__(self, attr, value):
        if attr in self.__dict__:  # <-- Don't like this, hasattr doesn't work
            object.__setattr__(self, attr, value)
        elif hasattr(self.wrapped, attr):
            setattr(self.wrapped, attr, value)
        else: object.__setattr__(self, attr, value)

Testdrive:
>>> w = Wrapped()
>>> p = Proxy(w)
>>> p.a
2
>>> p.b
1
>>> p.a = 3
>>> p.a
3
>>> w.a
0
>>> p.b = 4
>>> p.b
4
>>> w.b
4
>>> p.c = 5
>>> p.c
5
>>> w.c
AttributeError: 'Wrapped' object has no attribute 'c'

A: The built-in hasattr() function

is implemented by calling getattr(object, name) and seeing whether it raises an AttributeError or not.

The inspect module has the getattr_static() method, which can be used to

Retrieve attributes without triggering dynamic lookup via the descriptor protocol, __getattr__() or __getattribute__()".

Using this method, you could define a hasattr_static() method similarly to hasattr(), but calling inspect.getattr_static(object, name) instead of getattr(object, name):
import inspect

def hasattr_static(object, name):
    try:
        inspect.getattr_static(object, name)
        return True
    except AttributeError:
        return False

And then use this in the __setattr__() method of your Proxy class as a check:
def __setattr__(self, attr, value):
    if hasattr_static(self, attr):
        object.__setattr__(self, attr, value)
    elif hasattr(self.wrapped, attr):
        setattr(self.wrapped, attr, value)
    else:
        object.__setattr__(self, attr, value)

Alternatively, you coud use the dir() function instead of __dict__ to retrieve a list of attributes of your object, or use inspect.getmembers().


text:
Q: Volatile and Lock not working - C# 4.0 I have a class that reads data from a serial, with a high threshold (1 byte).
I have a variable that stores all the data coming from serial port: _dataReceived.
private volatile string _dataReceived;

I am using the DataReceived event to store this data, and then I start an action to process it.
    private void _port_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        string newData = _port.ReadExisting();
        _dataReceived += newData;

        new Action(() =>
        {
            Debug("Data received: {0}", newData);
            ParseAnswers();
        }).BeginInvoke(null, null);
    }

Processing it, consists on removing it from variable and treat the answer.
The method ParseAnswers starts as follows:
    private void ParseAnswers()
    {
        string cmd = null;
        int idx = -1;

        lock (_dataReceived)
        {
            idx = _dataReceived.IndexOf(Environment.NewLine);
            if (idx != -1)
            {
                cmd = _dataReceived.Substring(0, idx);
                _dataReceived = _dataReceived.Substring(idx + 2);
            }
            else
                return;
        }
        ...
    }

This works 99.9% of the time.
But sometimes I get an ArgumentOutOfRangeException on this line:
                cmd = _dataReceived.Substring(0, idx);

Now, my question is:
My variable is volatile what means I am always accessing the real value and not a cache.
I am pretty sure I get this DataReceived event raising all the time (fast), but I am using the lock statement to prevent any other Thread changing this value.
There is no way to get this piece of code (substring) running without having the NewLine inside the string.
And there is no way that this IndexOf is returning a index out of the string.
So... what's damn going on here?
It's very difficult to test anything, because it just happens once a month, but we appreciate any theory about what is actually happening.
Thanks for any suggestions from you!

A: The volatile keyword is never a solution to synchronization problems.  The bug is clearly visible, you made a hard assumption that the DataReceived event handler is not going to execute again before ParseAnswers() consumed the string and finished running.  That's wishful thinking, your code crashes when the event handler fires again and replaces the string while ParseAnswers() is parsing it.  Using volatile actually made it more likely for your code to crash :)  You should also have noticed loss of data, that happens when ParseAnswers() runs too late.
The solution is a very simple one, give ParseAnswers() an argument.  Pass the string.
Using Invoke() instead of BeginInvoke() would be a solution too, SerialPort ensures that DataReceived can't be fired when it is still executing.  But it is pretty dangerous, apt to deadlock your program when you try to call Close().

A: This is why we recommend to use lock on a private readonly field.
Your dataReceived could be changed by another thread in _port_DataReceived method(since access is not synchronized) while it is executing ParseAnswers for previous event.
So what happens, now two threads race to the lock(_dataReceived), they both are permitted because both use different references of the lock object.
Remember lock statement works on references, _dataReceived += newData; changes the reference, so another thread is freely allowed to enter the critical region(as it uses different instance of string now).
Simple fix would be:
private string _dataReceived;
private readonly object padLock = new object();

private void _port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    string newData = _port.ReadExisting();

    lock (padLock)
    {
        _dataReceived += newData;
    }

    new Action(() =>
    {
        Debug("Data received: {0}", newData);
        ParseAnswers();
    }).BeginInvoke(null, null);
}

private void ParseAnswers()
{
    ...
    lock (padLock)
    {
        idx = _dataReceived.IndexOf(Environment.NewLine);
        if (idx != -1)
        {
            cmd = _dataReceived.Substring(0, idx);
            _dataReceived = _dataReceived.Substring(idx + 2);
        }
    }
    ...
}

Do note that I've removed the volatile modifier(which is redundant) and also I've synchronized the access to _dataReceived in _port_DataReceived method also(very very important)


text:
Q: I need help with my minecraft skin I have been trying to use my Minecraft custom made skin i have used it in singleplayer and multiplayer working and lately I have been playing singleplayer no problem but when i play multiplayer i don't see my skin but other people do and yes i have bought minecraft
this is my skin just in case there is a problem with it:

A: You need to be on the exact same version as the server.. Example: servers version is 1.7.9 you need to be on 1.7.9 it's a problem with bukkit

A: If you're using your skin as part of a custom resource pack (i.e. creating a folder named mobs, then placing your skin inside and naming it char.png), it won't sync with the Minecraft website. Go to https://minecraft.net/profile and upload your skin to sync it with the website, which will allow you to see your skin on servers.
Hope this helps. (Otherwise, it could be a server-side error, like Taco said in the other answer)


text:
Q: Saddle Point Integral I want to calculate ,
$$I = \int_0^\infty dx \,x^{2n}e^{-ax^2 -\frac{b}{2}x^4} $$
for real positive a, b and positive integer n. n is the large parameter. Using Saddle Point Integration
I find saddle points  by setting the derivative  P'(x) = 0 where
$$ P(x) = n\log(x^2) -ax^2 -\frac{b}{2}x^4$$
In order to do this I never know which saddle point to use !  I see there are two imaginary ones and two real ones. I think I want the one that is positive and real but I have no idea  why. (My professor hinted at this one).
By the way the reason there are two real solutions and two imaginary ones is actually not completely obvious to me but I believe that is the case by inspecting the function you get
$$ 0 =  n -ax^2 -bx^4$$
this function has two real roots so the other two must be imaginary.
My professor said: "Just plot the integrand at positive
psi and you will see what saddle point to use"
I looked at the plot using coefficient n=a=b= 1 but i didn't get how that tells me which saddle point to use.
Any help would be appreciated !thanks!

A: $$
\int_0^\infty x^{2n}e^{-ax^2-bx^4/2}\,\mathrm{d}x
$$
Let $x=x^2$ and $m=n-1/2$, and we get
$$
\frac12\int_0^\infty u^me^{-au-bu^2/2}\,\mathrm{d}u
=\frac12\int_0^\infty e^{-P(u)}\,\mathrm{d}u
$$
where
$$
\begin{align}
P(u)&=bu^2/2+au-m\log(u)\\
P'(u)&=bu+a-m/u\\
P''(u)&=b+m/u^2
\end{align}
$$
We get $P'(u_0)=0$ for
$$
u_0=\frac{-a+\sqrt{a^2+4bm}}{2b}
$$
and
$$
P''(u_0)=\frac{a^2+4bm+a\sqrt{a^2+4bm}}{2m}
$$
The Saddle Point method gives the asymptotic approximation
$$
\sqrt{\frac{\pi\vphantom{A}}{2P''(u_0)}}\,e^{-P(u_0)}
$$

A: $\int_0^\infty x^{2n}e^{-ax^2-\frac{b}{2}x^4}~dx$
$=\int_0^\infty x^{2n}e^{-x^2\left(a+\frac{b}{2}x^2\right)}~dx$
$=\int_0^\infty\left(\dfrac{\sqrt{2a}\sinh x}{\sqrt{b}}\right)^{2n}e^{-\left(\frac{\sqrt{2a}\sinh x}{\sqrt{b}}\right)^2\left(a+\frac{b}{2}\left(\frac{\sqrt{2a}\sinh x}{\sqrt{b}}\right)^2\right)}~d\left(\dfrac{\sqrt{2a}\sinh x}{\sqrt{b}}\right)$
$=\dfrac{2^{n+\frac{1}{2}}a^{n+\frac{1}{2}}}{b^{n+\frac{1}{2}}}\int_0^\infty e^{-\frac{2a\sinh^2x(a+a\sinh^2x)}{b}}\sinh^{2n}x\cosh x~dx$
$=\dfrac{2^{n+\frac{1}{2}}a^{n+\frac{1}{2}}}{b^{n+\frac{1}{2}}}\int_0^\infty e^{-\frac{2a^2\sinh^2x\cosh^2x}{b}}\left(\dfrac{e^x-e^{-x}}{2}\right)^{2n}\dfrac{e^x+e^{-x}}{2}dx$
$=\dfrac{2^{n+\frac{1}{2}}a^{n+\frac{1}{2}}}{b^{n+\frac{1}{2}}}\int_0^\infty e^{-\frac{a^2\sinh^22x}{2b}}\dfrac{e^x+e^{-x}}{2}\left(\dfrac{(-1)^nC_n^{2n}}{4^n}+\sum\limits_{k=1}^n\dfrac{(-1)^{n+k}C_{n-k}^{2n}(e^{2kx}+e^{-2kx})}{4^n}\right)dx$
$=\dfrac{\sqrt2a^{n+\frac{1}{2}}}{2^nb^{n+\frac{1}{2}}}\int_0^\infty e^{-\frac{a^2}{2b}\frac{\cosh4x-1}{2}}\left(\dfrac{(-1)^n(2n)!(e^x+e^{-x})}{2(n!)^2}+\sum\limits_{k=1}^n\dfrac{(-1)^{n+k}(2n)!(e^{2kx}+e^{-2kx})(e^x+e^{-x})}{2(n+k)!(n-k)!}\right)dx$
$=\dfrac{\sqrt2a^{n+\frac{1}{2}}e^\frac{a^2}{4b}}{2^nb^{n+\frac{1}{2}}}\int_0^\infty e^{-\frac{a^2\cosh4x}{4b}}\left(\dfrac{(-1)^n(2n)!(e^x+e^{-x})}{2(n!)^2}+\sum\limits_{k=1}^n\dfrac{(-1)^{n+k}(2n)!(e^{(2k+1)x}+e^{-(2k-1)x}+e^{(2k-1)x}+e^{-(2k+1)x})}{2(n+k)!(n-k)!}\right)dx$
$=\dfrac{a^{n+\frac{1}{2}}e^\frac{a^2}{4b}}{2^{n+\frac{3}{2}}b^{n+\frac{1}{2}}}\int_0^\infty e^{-\frac{a^2\cosh4x}{4b}}\left(\dfrac{(-1)^n(2n)!\cosh x}{(n!)^2}+\sum\limits_{k=1}^n\dfrac{(-1)^{n+k}(2n)!(\cosh((2k+1)x)+\cosh((2k-1)x))}{(n+k)!(n-k)!}\right)d(4x)$
$=\dfrac{a^{n+\frac{1}{2}}e^\frac{a^2}{4b}}{2^{n+\frac{3}{2}}b^{n+\frac{1}{2}}}\int_0^\infty e^{-\frac{a^2\cosh x}{4b}}\left(\dfrac{(-1)^n(2n)!\cosh\dfrac{x}{4}}{(n!)^2}+\sum\limits_{k=1}^n\dfrac{(-1)^{n+k}(2n)!\left(\cosh\dfrac{(2k+1)x}{4}+\cosh\dfrac{(2k-1)x}{4}\right)}{(n+k)!(n-k)!}\right)dx$
$=\dfrac{a^{n+\frac{1}{2}}e^\frac{a^2}{4b}}{2^{n+\frac{3}{2}}b^{n+\frac{1}{2}}}\left(\dfrac{(-1)^n(2n)!K_\frac{1}{4}\left(\dfrac{a^2}{4b}\right)}{(n!)^2}+\sum\limits_{k=1}^n\dfrac{(-1)^{n+k}(2n)!\left(K_\frac{2k+1}{4}\left(\dfrac{a^2}{4b}\right)+K_\frac{2k-1}{4}\left(\dfrac{a^2}{4b}\right)\right)}{(n+k)!(n-k)!}\right)$

A: The required mathematical background can be seen in N. G de Bruijn, Asymptotic methods in analysis, North-Holland Publ. Co - Amsterdam, P. Noordhoff LTD - Groningen (1958), Ch. 6, 6.8 A modified Gamma function. The asymptotics of the integral to which the integral under consideration can be easily reduced  (together with the proofs) is contained in M. Fedoryuk, Saddle method, Nauka, Moscow (1977) (in Russian).


text:
Q: Magmi question assign products to different root category I am uploading products through magmi, works fine but somehow he always adds my produts to my default root category, but he should add it to my second root category.
I just have the column categories with below value
rootcat2/category1/category2;;rootcat2/category2/category3

A: I'm going to take a wild guess and say that you meant to use the "On-the-Fly Category Importer" plugin of Magmi, but you didn't actually check the box to use it.
Magmi, without the category importer plugin, normally takes category IDs (at least for an older version I used a while back). If you want to use rootcat2/category1/category2;;rootcat2/category2/category3, you must use the On-the-Fly Category Importer.
Check out the wiki: http://wiki.magmi.org/index.php?title=On_the_fly_category_creator/importer