text:
Q: Identify ram module linked to ECC error di DMESG one of my server is logging the following ECC errors:
    [lun set 14 00:14:16 2020] {33}[Hardware Error]: Hardware error from APEI Generic Hardware Error
Source: 1
    [lun set 14 00:14:16 2020] {33}[Hardware Error]: It has been corrected by h/w and requires no further action
    [lun set 14 00:14:16 2020] {33}[Hardware Error]: event severity: corrected
    [lun set 14 00:14:16 2020] {33}[Hardware Error]:  Error 0, type: corrected
    [lun set 14 00:14:16 2020] {33}[Hardware Error]:  fru_text: CorrectedErr
    [lun set 14 00:14:16 2020] {33}[Hardware Error]:   section_type: memory error
    [lun set 14 00:14:16 2020] {33}[Hardware Error]:   node: 0 device: 1
    [lun set 14 00:14:16 2020] {33}[Hardware Error]:   error_type: 2, single-bit ECC
    [lun set 14 00:14:16 2020] ghes_edac: Internal error: Can't find EDAC structure

The server has the following RAN configuration:
Handle 0x0029, DMI type 16, 23 bytes
Physical Memory Array
        Location: System Board Or Motherboard
        Use: System Memory
        Error Correction Type: Single-bit ECC
        Maximum Capacity: 64 GB
        Error Information Handle: Not Provided
        Number Of Devices: 4

Handle 0x002A, DMI type 17, 40 bytes
Memory Device
        Array Handle: 0x0029
        Error Information Handle: Not Provided
        Total Width: 72 bits
        Data Width: 64 bits
        Size: 16384 MB
        Form Factor: DIMM
        Set: None
        Locator: DIMM CHA3
        Bank Locator: BANK 0
        Type: DDR4
        Type Detail: Synchronous
        Speed: 2133 MHz
        Manufacturer: SK Hynix
        Serial Number: 71929DA0
        Asset Tag: 1651
        Part Number: HMA82GU7MFR8N-TF
        Rank: 2
        Configured Clock Speed: 2133 MHz
        Minimum Voltage: Unknown
        Maximum Voltage: Unknown
        Configured Voltage: 1.2 V

Handle 0x002B, DMI type 17, 40 bytes
Memory Device
        Array Handle: 0x0029
        Error Information Handle: Not Provided
        Total Width: 72 bits
        Data Width: 64 bits
        Size: 16384 MB
        Form Factor: DIMM
        Set: None
        Locator: DIMM CHA1
        Bank Locator: BANK 1
        Type: DDR4
        Type Detail: Synchronous
        Speed: 2133 MHz
        Manufacturer: SK Hynix
        Serial Number: 71929CFF
        Asset Tag: 1651
        Part Number: HMA82GU7MFR8N-TF
        Rank: 2
        Configured Clock Speed: 2133 MHz
        Minimum Voltage: Unknown
        Maximum Voltage: Unknown
        Configured Voltage: 1.2 V

Handle 0x002C, DMI type 17, 40 bytes
Memory Device
        Array Handle: 0x0029
        Error Information Handle: Not Provided
        Total Width: 72 bits
        Data Width: 64 bits
        Size: 16384 MB
        Form Factor: DIMM
        Set: None
        Locator: DIMM CHB4
        Bank Locator: BANK 2
        Type: DDR4
        Type Detail: Synchronous
        Speed: 2133 MHz
        Manufacturer: SK Hynix
        Serial Number: 71929BB8
        Asset Tag: 1651
        Part Number: HMA82GU7MFR8N-TF
        Rank: 2
        Configured Clock Speed: 2133 MHz
        Minimum Voltage: Unknown
        Maximum Voltage: Unknown
        Configured Voltage: 1.2 V

Handle 0x002D, DMI type 17, 40 bytes
Memory Device
        Array Handle: 0x0029
        Error Information Handle: Not Provided
        Total Width: 72 bits
        Data Width: 64 bits
        Size: 16384 MB
        Form Factor: DIMM
        Set: None
        Locator: DIMM CHB2
        Bank Locator: BANK 3
        Type: DDR4
        Type Detail: Synchronous
        Speed: 2133 MHz
        Manufacturer: Samsung
        Serial Number: 33BB5E37
        Asset Tag: 1641
        Part Number: M391A2K43BB1-CPB
        Rank: 2
        Configured Clock Speed: 2133 MHz
        Minimum Voltage: Unknown
        Maximum Voltage: Unknown
        Configured Voltage: 1.2 V

How can I identify the faulty module to replace it? I think that the following log's row has the information I need but I miss the way to decrypt it.
[lun set 14 00:14:16 2020] {33}[Hardware Error]:   node: 0 device: 1


text:
Q: Nginx ssl proxy for Apache I am running the following setup:
[public ip]-nginx_proxy-[lan]-apache_server
SSL is configured and set up on the nginx proxy level (and this is working).
However, when I visit a site over ssl, I get .css and .js files returned over http (which are blocked by the browser). It seems like Apache is unaware that the client is requesting content over ssl.
This is my current config:
nginx:
server {
    listen              443;
    server_name         maiev.domain.com, ~.;

    ssl             on;
    ssl_certificate         /etc/nginx/ssl/domain.pem;
    ssl_certificate_key     /etc/nginx/ssl/domain.pem;

    access_log          off;
    error_log           off;

    location ~ /\.ht {
        deny all;
    }

    location ~ /\.git {
                deny all;
        }

    location / {
        proxy_pass      http://maiev.local:80;
            proxy_set_header        Host            $host;
            proxy_set_header        X-Real-IP       $remote_addr;
            proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header        X-Forwarded-Proto $scheme;
            add_header              Front-End-Https on;
            proxy_redirect          off;
    }
}

This is my Apache config:
<VirtualHost *:80>
    ServerAdmin help@domain.com
    ServerName dev.domain.com

    <IfModule rpaf_module>
        RPAFenable On
        RPAFsethostname On
        RPAFproxy_ips 172.16.1.130
        RPAFheader X-Forwarded-For
    </IfModule>

    DocumentRoot /home/sites/www/dev-domain/public

    <Directory />
        Options FollowSymLinks
        AllowOverride None
    </Directory>

    <Directory /home/sites/www/dev-domain/public/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride None
        Order allow,deny
        allow from all
    </Directory>

    ErrorLog /home/sites/logs/dev-domain/error.log
    LogLevel warn
    CustomLog /home/sites/logs/dev-domain/access.log combined
    php_value log_errors on
    php_value error_log /home/sites/logs/dev-domain/php.log
</VirtualHost>

If I change the $scheme to https in the nginx config, nothing changes.
What am I missing?

A: If you set your url to 'http://...' in your html file, it will be used as http, not converted to https magically because referrer is using https. So your probably need to fix your application and not you web server.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Spark:How we access in memory table in other sessions. I am new in Spark, So i want to know how we access in memory table in other spark scala shell session.
Thanks in advance!

A: So that's not currently supported. If you want to share RDD's between jobs you should take a look at either IBM's Spark Kernel project or the Ooyola Spark Job Server which allows for sharing a Spark Context between multiple applications.


text:
Q: iterate over large tsv.gs from network url I would like to iterate over some network files (tsv.gz), parse them (load each row), and only write portions (i.e. columns) to files, i.e. https://datasets.imdbws.com/ (ideally with flate2), but I can't seem to find any idioms for iterating over files from URIs. Should I use an external package like hyper and try to iterate over Body? If so, how can I convert a Body into something that implements Read? Here is some base code:
use flate2::read::GzDecoder;
use hyper::Client;
use std::io::BufReader;

#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
    let client = Client::new();
    let uri = "http://datasets.imdbws.com/title.basics.tsv.gz".parse()?;
    let body = client.get(uri).await?.into_body();
    let d = GzDecoder::new(body); // hyper::Body doesn't implement Read
    for line in BufReader::new(d).lines() {
        // do something with lines
    }
    Ok(())
}


text:
Q: How Do you Build A GUI shell for DOS? I would like to build a GUI shell for DOS so I can make a shell operating system like windows. I know this may sound stupid, but I'm just a beginner looking for a challenge. I was thinking something along the lines of Dream16OS but a little better looking. Also is it possible to make this in Visual Basic for DOS or Visual Basic 1 or any recent visual Basic? You can download Download from Geek Basic . webs . com
Also, I have started a project similar to this and could really use some guidance, so please check it out and post in the forum. Thanks Link Below
http://boss-basicoperatingsystemsimulation.yolasite.com/

A: You are asking for alot of pain. DOS doesn't give you any facilities for drawing windows, handling events and your memory is extremely limited.
Those of us old enough to remember near and far pointers will tell you it is a huge pain in the rear.
You can do what old dos games did and use a dos extender. This will give you a nice flat address space at least.
You might be able to find some old windowing toolkits
that will let you draw windows in all the glory of 640x480.
You can probably use the DOS version of visual basic, but you will end up with windows that look like your bios (remember dosshell.exe?)


text:
Q: Why is it that @MatrixParam values seem to only come from the final segment? I am exploring the use of MatrixURIs in a JAX-RS application. In the process I've noticed that the @MatrixParam annotated parameters seem to only get the matrix parameters from the final segment (which makes trying to use sub-resource locators a bit painful). I would like to know if this is a bug, or is part of the spec (and why?), or is simply an undefined crack.
I know that I likely could devise a way to use the @Context injected UriInfo object (which does change depending upon where in the locator chain one finds oneself), but this feels ugly.
Thumbing quickly through the JAX-RS 1.1 spec... the closest I could find to this not being supported was around: §3.2

Because injection occurs at object creation time, use of these annotations (with the exception of @Context) on resource class fields and bean properties is only supported for the default per-request resource class lifecycle.

But that's talking about Constructor/Field injection, not method parameters like in §3.3.2:

When a resource method is invoked, parameters annotated with @FormParam or one of the annotations listed in section 3.2 are mapped from the request according to the semantics of the annotation.

But of course the semantics of the annotation are seemingly vague.
Runtime Environment Details:

*

*Jersey 1.13, 1.15

*Tomcat 7.0.29

*Java 1.6.0_31 (Apple)

*MacOS X 10.7.5

Example resources:
public class Zero {

    public static final String[] IDS = { "1", "2", "3" };

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Map<String, Object> getMe(@Context final UriInfo info) {
        final UriBuilder builder = info.getAbsolutePathBuilder().path("one");
        final UriBuilder two = builder.clone().matrixParam("id", "{one}", "{two}");

        final List<String> links = new ArrayList<String>();
        for (int i = 0; i < IDS.length; i++) {
            final String first = IDS[i];
            for (int j = i + 1; j < IDS.length; j++) {
                final String second = IDS[j];
                links.add(two.build(first, second).toASCIIString());
            }
        }

        final Map<String, Object> toReturn = new HashMap<String, Object>();
        toReturn.put("class", getClass().getSimpleName());
        toReturn.put("next", builder.build().toASCIIString());
        toReturn.put("skip", links);

        return toReturn;
    }

    /*************************/
    /**** <PROBLEM CHILD> ****/
    /*************************/
    @Path("one")
    public Object getNext(@MatrixParam("id") final Set<String> ids) {
        if (ids.isEmpty()) {
            return new One();
        }
        return new Two(ids.toArray(new String[ids.size()]));
    }
    /*************************/
    /**** </PROBLEM CHILD> ***/
    /*************************/

    public static class One {
        @GET
        @Produces(MediaType.APPLICATION_JSON)
        public Map<String, Object> getMe(@Context final UriInfo info) {
            final UriBuilder builder = info.getAbsolutePathBuilder().path("{id}");
            final List<String> links = new ArrayList<String>();
            for (final String id : IDS) {
                links.add(builder.build(id).toASCIIString());
            }
            final Map<String, Object> toReturn = new HashMap<String, Object>();
            toReturn.put("class", getClass().getSimpleName());
            toReturn.put("next", links);
            toReturn.put("last", getLastURI(info));
            return toReturn;
        }

        @Path("{id}")
        public Two getNext(@PathParam("id") final String id) {
            return new Two(id);
        }
    }

    public static class Two {

        private final String[] myids;
        private final Three three;

        public Two(final String... ids) {
            three = new Three(ids);
            myids = ids;
        }

        @GET
        @Produces(MediaType.APPLICATION_JSON)
        public Map<String, Object> getMe(@Context final UriInfo info) {
            final UriBuilder builder = info.getAbsolutePathBuilder().path("three");
            final Map<String, Object> toReturn = new HashMap<String, Object>();
            toReturn.put("class", getClass().getSimpleName());
            toReturn.put("ids", myids);
            toReturn.put("next", builder.build().toASCIIString());
            toReturn.put("last", getLastURI(info));
            return toReturn;
        }

        @Path("three")
        public Three getNext() {
            return three;
        }
    }

    public static class Three {
        private final String[] myids;

        public Three(final String... ids) {
            myids = ids;
        }

        @GET
        @Produces(MediaType.APPLICATION_JSON)
        public Map<String, Object> getMe(@Context final UriInfo info) {
            final Map<String, Object> toReturn = new HashMap<String, Object>();
            toReturn.put("class", getClass().getSimpleName());
            toReturn.put("ids", myids);
            toReturn.put("last", getLastURI(info));
            return toReturn;
        }
    }

    /**
     * Helper method since info.getMatchedURIs doesn't play nice with Matrix Params
     * @param info info object
     * @return parent URI
     */
    public static final String getLastURI(final UriInfo info) {
        final List<PathSegment> segments = info.getPathSegments(false);
        final UriBuilder builder = info.getBaseUriBuilder();
        for (int i = 0; i < segments.size() - 1; i++) {
            final PathSegment segment = segments.get(i);
            builder.path(segment.getPath());
            final MultivaluedMap<String, String> matrixParams = segment.getMatrixParameters();
            if (!matrixParams.isEmpty()) {
                for (final Map.Entry<String, List<String>> param : matrixParams.entrySet()) {
                    final String name = param.getKey();
                    final String[] values = param.getValue().toArray(new String[param.getValue().size()]);
                    builder.matrixParam(name, values);
                }
            }
        }
        return builder.build().toASCIIString();
    }
}

Example Outputs from above:
http://localhost:8080/context/zero/one/2
{
"last":"http://localhost:8080/context/zero/one",
"ids":["2"],
"next":"http://localhost:8080/context/zero/one/2/three",
"class":"Two"
}

http://localhost:8080/context/zero/one/2/three
{
"last":"http://localhost:8080/context/zero/one/2",
"ids":["2"],
"class":"Three"
}

http://localhost:8080/context/zero/one;id=1;id=2
{
"last":"http://localhost:8080/context/zero",
"ids":["2","1"],
"next":"http://localhost:8080/context/zero/one;id=1;id=2/three",
"class":"Two"
}

http://localhost:8080/context/zero/one;id=1;id=2/three
{
"last": "http://localhost:8080/context/zero/one;id=1;id=2",
"ids": ["three"],
"next": "http://localhost:8080/context/zero/one;id=1;id=2/three/three",
"class": "Two"
}

A: I can't say for certain, but I suspect this is by design.  Suppose you have a two level URI like this:
/foo/bar

On both levels one could have a matrix parm named filter.  You could end up with a URL like so:
/foo;filter=13/bar;filter=April

In the Jersey resource for that path you'll have one paramter annotated with @MatrixParam("filter").  Which filter parameter should Jersey fill in?  What if one or the other is not supplied?
Having just implemented some matrix parameters, I can see the value in the current implementation.  Specifying @MatrixParam pulls only the last level.  If you want matrix parameters earlier in the URI, specify @PathParameter and have the parameter type be a PathSegment.  From the path segment you can pull out the matrix parameters.
Often times, the resource class will have a global @Path, and each method will have it's own @Path adding to the class level setting.  In this case it seems to make more sense that @MatrixParameter would apply only to the last path segment.
So, putting this all together (for our example above) yields the following
@Path("{fooPath: foo}")
public class FooResource {

@GET
@Path("bar")
public String getFooBar(@PathParam("fooPath") PathSegment fooPath,
    @MatrixParam("filter") String filter) {
    MultivaluedMap<String, String> mParms = fooPath.getMatrixParameters();
    List<String> parms = mParms.get("filter");
    String fooFilter = parms.get(0);
    // ... the rest of your code
    }
}


text:
Q: Open GL Create 4 Views Like 3ds max or maya How can I Create a 4 views (LEFT/TOP/PERSPECTIVE/FRONT) in Open GL ??
I Have Used this :
int main(int c,char ** argv)
{
    glutInit(&c,argv);
    glutInitDisplayMode(GLUT_DOUBLE |GLUT_DEPTH |GLUT_RGB );
    glutInitWindowSize(w,h);
    MainWin =glutCreateWindow("Teapot Window");
    glutDisplayFunc(display);

    LeftWin = glutCreateSubWindow(MainWin,0,0,s_window_w,s_window_h);
    glutDisplayFunc(displayLeft);
    glutReshapeFunc(reshapeLeft);

    TopWin = glutCreateSubWindow(MainWin,s_window_w+3,0,s_window_w,s_window_h);
    glutDisplayFunc(displayTop);
    glutReshapeFunc(reshapeTop);

    PerspectiveWin = glutCreateSubWindow(MainWin,0,s_window_h+3,s_window_w,s_window_h);
    glutDisplayFunc(displayPerspective);
    glutReshapeFunc(reshapePerspective);

    FrontWin = glutCreateSubWindow(MainWin,s_window_w+3,s_window_h+3,s_window_w,s_window_h);
    glutDisplayFunc(displayFront);
    glutReshapeFunc(reshapeFront);

    glutMainLoop();
    return 0;
}

Then I have make the projection for top and left and like this :
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-0.5f,0.5f,-0.35f,0.35f,1,500);

When I use the top lines for the front also , the output is something like this  :

Where is my fault ?
thanks in advance
Why the Front view is empty and the perspective and left view are same ??
For perspective projection i had used glFrustum ....
So Am I going wrong ?
Please help on creating multiple views like 3ds  max or maya ...
below is the code for display functions:
void displayLeft()
{
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt(0,0,-1,0,0,0,0,1,0);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glLightfv(GL_LIGHT0,GL_POSITION,light_pos);

    glShadeModel(GL_SMOOTH);
    glClearColor(0.2f,0.3f,0.4f,1);
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    glPushMatrix();
    glEnable(GL_COLOR_MATERIAL);
    glTranslatef(teapot_x,teapot_y,teapot_z);
    glRotatef(teapot_angle,0,1,0);
    glColor3f(0,1,0);
    glutSolidTeapot(0.2f);

    glPopMatrix();
    glFlush();
    glutSwapBuffers();
}
void displayTop()
{
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt(0,-1,0,0,0,0,0,0,-1);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glLightfv(GL_LIGHT0,GL_POSITION,light_pos);

    glShadeModel(GL_SMOOTH);
    glClearColor(0.2f,0.3f,0.4f,1);
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    glPushMatrix();
    glEnable(GL_COLOR_MATERIAL);
    glTranslatef(teapot_x,teapot_y,teapot_z);
    glRotatef(teapot_angle,0,1,0);
    glColor3f(0,1,0);
    glutSolidTeapot(0.2f);

    glPopMatrix();
    glFlush();
    glutSwapBuffers();
}
void displayFront()
{
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt(0,0,0,0,0,0,1,0,0);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glLightfv(GL_LIGHT0,GL_POSITION,light_pos);

    glShadeModel(GL_SMOOTH);
    glClearColor(0.2f,0.3f,0.4f,1);
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    glPushMatrix();
    glEnable(GL_COLOR_MATERIAL);
    glTranslatef(teapot_x,teapot_y,teapot_z);
    glRotatef(teapot_angle,0,1,0);
    glColor3f(0,1,0);
    glutSolidTeapot(0.2f);

    glPopMatrix();
    glFlush();
    glutSwapBuffers();
}
void displayPerspective()
{

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt(0,0,-1,0,0,0,0,1,0);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glLightfv(GL_LIGHT0,GL_POSITION,light_pos);

    glShadeModel(GL_SMOOTH);
    glClearColor(0.2f,0.3f,0.4f,1);
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    glPushMatrix();
    glEnable(GL_COLOR_MATERIAL);
    glTranslatef(teapot_x,teapot_y,teapot_z);
    glRotatef(0,0,1,0);
    glColor3f(0,1,0);
    glutSolidTeapot(0.2f);

    glPopMatrix();
    glFlush();
    glutSwapBuffers();
}

A: Use glViewport and glScissor to cut out panes of the window. Then for each pane perform the rendering as usual. Setting the projection matrix is actually a drawing state operation, so it belongs into the display function, not reshape.
Your display function should become something like
void ViewportScissor(int x, int y, int width, int height)
{
    glViewport(x, y, width, height);
    glScissor(x, y, width, height);
}

void display(void)
{

    int const win_width  = glutGet(GLUT_WINDOW_WIDTH);
    int const win_height = glutGet(GLUT_WINDOW_HEIGHT);

    glDisable(GL_SCISSOR);
    glClear(…);

    glEnable(GL_SCISSOR);

    ViewportScissor(0, 0, win_width/2, win_height/2);
    glMatrixMode(GL_PROJECTION);
    setup_frontview_projection();
    glMatrixMode(GL_MODELVIEW);
    setup_frontview();
    draw_scene();

    ViewportScissor(win_width/2, 0, win_width/2, win_height/2);
    glMatrixMode(GL_PROJECTION);
    setup_rightview_projection();
    glMatrixMode(GL_MODELVIEW);
    setup_rightview();
    draw_scene();

    ViewportScissor(0, win_height/2, win_width/2, win_height/2);
    glMatrixMode(GL_PROJECTION);
    setup_topview_projection();
    glMatrixMode(GL_MODELVIEW);
    setup_topview();
    draw_scene();

    ViewportScissor(win_width/2, win_height/2, win_width/2, win_height/2);
    glMatrixMode(GL_PROJECTION);
    setup_freecamview_projection();
    glMatrixMode(GL_MODELVIEW);
    setup_freecamview();
    draw_scene();

    glutSwapBuffers();

}

Adding splitter lines/frames is left as an exercise for the reader.


text:
Q: What compilers currently support Haswell transactional memory? Which compilers (as of May 2014) are able to generate code that uses the transactional memory capabilities (Restricted Transactional Memory, not simply lock elision)?

A: GCC, as of version 4.8 supports Intel RTM:

Support for the Intel RTM and HLE intrinsics, built-in functions and code generation is available via -mrtm and -mhle.

It's probably safe to assume that similar intrinsics are available for a recent version of Intel's ICC, however I can't find a particular version that specifies support (this paper did experimentation with RTM) .
In addition, support likely exists for various smaller languages and JITs, with more transparent support arriving sometime in the future.


text:
Q: setTimeout not always working in Greasemonkey I've found a lot of similar problems but none equal and no right solution. This is a very strange issue.
I have a simple Greasemonkey script to test the issue:
// ==UserScript==
// @name        testdiddio
// @namespace   http://userscripts.org/users/useridnumber
// @include     https://www.google.it/
// @version     1
// ==/UserScript==

function wait(){
    console.info("wait");
    setTimeout(wait,1000);
}

console.info("start");
wait();

This is the output from firebug:
start
wait
wait
wait
wait

The wait() function is called 4 times then stops. If I set the Timeout to 100ms the call seems works for at least 10/15 seconds then stops.
I'm using:
Firefox 12.0
Greasemonkey 0.9.19

A: This is a bug in Greasemonkey 0.9.19.
A feature was added to allow setTimeout() to work even when a page's JS was disabled and it introduced some complications (Issues 1549, 1552, and 1553, etc.).
It should be resolved shortly in release 0.9.20, or revert to version 0.9.18.


text:
Q: What determinants do I have in my entity? Trying to understand BCNF My teacher told me that if an entity is in BCNF all determinants should be a super key, but i'm struggling to understand this. I have an entity for a cinema database with following attributes: Showtime_id (PK), Date, Showtime, Hall.
I understand that Showtime_id is a determinant for Date, Showtime, Hall.
And that Date, Showtime and Hall is a determinant for Showtime_id, right?
But are these the only determinants in my entity?
Or is
Showtime_id, Date -> Showtime, Hall
Showtime_id, Showtime -> Hall, Date
and so on also determinants?
Thank you :)

A:
My teacher told me that if an entity is in BCNF all determinants should be a super key

That is wrong. BCNF is satisfied when/iff all determinants of non-trivial FDs (functional dependencies) are superkeys. Details matter.

I have an entity for a cinema database

What matters to BCNF is that you have a table with certain attributes & you know what FDs hold & what FDs don't hold.
If you mean that the only FDs that hold are the ones that follow from {Showtime_id} being a PK (primary key), then you need to say so. If you don't know what those are, ask a question about that. (When some FDs hold, all the other ones generated from them by Armstrong's axioms hold. But then we still need to know whether any other ones hold or not.)
You must tell us what FDs hold. If you don't know how to determine that from what your table rows mean & the business rules, ask another question where you quote your definition of FD & ask about being stuck. (And say why you think {Showtime_id} is PK.) (But PKs don't matter, CKs (candidate keys) do.)


text:
Q: ng-pattern not working for dynamically added input tag in angular I have a input tag in a variable with ng-pattern when I inserted it into a div its ng-pattern is not working
style:
.from_fields {
    transition: all linear 0.5s;
    background: transparent;
}
.from_fields.ng-invalid {
    color: white;
    background: red;
}

Script
$scope.input='<input type="text" ng-pattern="/^[0-9]{1,7}$/" class="from_fields">';
angular.element(document.getElementById('test')).html($scope.input);

can someone help??

A: The string you are trying to enter needs to be compiled for angular to have it in its watch list and have any ng attributes evaluated.
Right now ng-pattern is a regular custom data attribute with no meaning to angular
If you dont want to bind in an angular controller just remove the ng-
leaving
'<input type="text" pattern="^[0-9]{1,7}$" class="from_fields">';

note that the pattern attribute does not need slashes
otherwise you will have to import in your controller the $compile service
and compile the string given a $scope variable
var input = '<input type="text" ng-pattern="^[0-9]{1,7}$" class="from_fields">';
var compiled_input = $compile(input)($scope)

and the append it to the document
angular.element(<selector>).append(input);


text:
Q: Need help on Socket Programming in Python (beginner) I am learning socket programming and python. I need to create a client that sends a command to a server (list or get ).  The server then validates the command.  My client program can display "list" or "get" , but it doesn't show the error message when I enter other things.
Also, it only works one time; when I enter a different command after receiving a reply from the server, it gives me the following error:
Traceback (most recent call last):
  File "fclient.py", line 49, in
    client_socket.send(command)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 170, in _dummy
    raise error(EBADF, 'Bad file descriptor')
I'm totally lost. What is the best way to get a command line input in the client program and send it to the server and ask the server to validate the command line parameter?  Can someone take a look and point me to the right direction? Your help is greatly appreciated.
Client.py
import socket   #for sockets
import sys      #for exit

command = ' '
socksize = 1024

#return a socket descriptor which can be used in other socket related functions
#properties: address family: AF_INET (IP v4)
#properties: type: SOCK_STREAM (connection oriented TCP protocol)

try:
    #create an AF_INET, STREAM socket (TCP)
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:               #error handling
    print 'Failed to create socket. Error code: ' + str(msg[0]) + ', Error message: ' + msg[1]
    sys.exit();

print 'Socket Created'

#Get the IP address of the remote host/url
#connect to IP on a certain 'port' using the connect
#host = 'flip3.engr.oregonstate.edu'
#port = 30021
#host = 'www.google.com'
#port = 80
host = ''       #symbolic name meaning the local host
port = 8888     #arbitrary non-privileged port

try:
    remote_ip = socket.gethostbyname(host)
except socket.gaierror:
    #could not resolve
    print 'Hostname could not be resolved. Existing'
    sys.exit()
print 'IP address of ' + host + ' is ' + remote_ip

#Connect to remote server
client_socket.connect((remote_ip, port))
print 'Socket Connected to ' + host + ' on ip ' + remote_ip

#Send some data to remote server
while True:
    print 'Enter a command: list or get <filename>'
    command = raw_input()
    if command.strip() == 'quit':
        break
    client_socket.send(command)

    data = client_socket.recv(socksize)
    print data

#Close the socket
client_socket.close()

Server.py
import socket
import sys
from thread import *

#HOST = 'flip3.engr.oregonstate.edu' #symbolic name meaning all available interfaces
#PORT = 30021
HOST = ''
PORT = 8888

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

try:
    server_socket.bind((HOST, PORT))    #bind to a address(and port)
except socket.error, msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()

print 'Socket bind complete'

#put the socket in listening mode
server_socket.listen(10)     #maximum 10 connections
print 'TCP Server Waiting for client on port 30021'

#wait to accept a connection - blocking call
client, addr = server_socket.accept()
#display client information
print 'Connected with ' + addr[0] + ':' + str(addr[1])

#keep talking with the client
while 1:
    #Receiving from client
    data = client.recv(1024)

    if (data == 'list' or data == 'get'):
        reply = 'receive: ' + data
        client.send(reply)
        break;
    else:
        reply = 'wrong command'
        client.send(reply)

client.close()

A: The first problem is that you close your client socket inside your loop, closing it after receiving the reply to the first command. Move closing the socket out of the loop instead and introduce an exit condition to exit the loop:
#Connect to remote server
client_socket.connect((remote_ip, port))

print 'Socket Connected to ' + host + ' on ip ' + remote_ip

#Send some data to remote server
while True:
    print 'Enter a command: list or get <filename>'
    command = raw_input()
    if command.strip() == 'quit':
        break
    client_socket.send(command)

    data = client_socket.recv(socksize)
    print data

# Close the socket
client_socket.close()

You're doing something similar on the server side: You try to reopen the listening socket every iteration. Move this part out of the loop as well:
#wait to accept a connection - blocking call
client, addr = server_socket.accept()

#display client information
print 'Connected with ' + addr[0] + ':' + str(addr[1])

The reason your command parsing doesn't work is because of this statement:
if (data == 'list' or 'get'):

What you meant to write here is
if (data == 'list' or data == 'get'):

The first expression will evaluate like this:

*

*Is data == 'list'?

*If yes, that sub-expression evaluates to True and is therefore what a or b will return.

*If not, the second operand to or is chosen, which is the string 'get'.

*The result of that or expression will now be implicitely cast to boolean by the if statement:

*Case 1: True is already True

*Case 2: A non-empty string cast to boolean evaluates to True as well

So your if statement will always evaluate to True, that's why your command parsing didn't work.
To write
if (data == 'list' or data == 'get'):

in a nicer form, I would suggest to use
if (data.strip() in ('list'  'get')):

Lastly, you should wrap your socket code in a try..finally to make sure the sockets are always closed even if exceptions like a KeyboardInterrupt happen:
try:
    #keep talking with the client
    while 1:
        #Receiving from client
        data = client.recv(1024)

        if (data.strip() in ('list'  'get')):
            reply = 'receive: ' + data
            client.send(reply)
        else:
            reply = 'wrong command'
            client.send(reply)
except KeyboardInterrupt:
    print "Exiting gracefully."
finally:
    server_socket.close()

(The finally clause gets executed under all circumstances - whether handled or undhandled exceptions happened, or not)

A: One problem is that you close client_socket in your while loop. After that, client_socket.send() will not work anymore.  There are at least two ways to fix this:

*

*Move client_socket.connect() into your while loop also.

*Get rid of client_socket.close(), and move server_socket.accept() above the while loop in Server.py.

There are more sophisticated options involving select() or other methods, but one of the two items above should get you by for now.


text:
Q: SyntaxError: Unexpected end of JSON input - why is that? This is the code I have written using express and node.js
    const express = require("express");
    const https = require("https");
    const app = express();

    app.get("/", function(req, res) {

        // Url to my api key
         const url = "https://api.spoonacular.com/recipes/random?apiKey=...&number=1";

         https.get(url, function(response) {

              response.on("data", function (data) {
                   console.log(JSON.parse(data));
                   // const theRecipe = JSON.parse(data);
                   console.log(data);
              });

         });

         res.send("The server is up and running");
    });

    app.listen(3000, function () {
         console.log("Server started at port 3000");
    });

When I refresh my webpage on localhost, on console I get the following error:

quote
SyntaxError: Unexpected end of JSON input
at JSON.parse ()
at IncomingMessage. (C:\Users\ArunBohra\Desktop\FoodRecipes\app.js:12:33)
quote

Can anyone find what is the problem with my code.

A: The data event fires when a chunk of data from the response has arrived. You are trying to parse the first chunk as if it were the complete JSON text.
You need to collect the pieces from each data event but wait until the end event fires before joining them together into the complete string of JSON that you can parse.
There is an example of fetching and parsing JSON in the documentation.
You might want to look at modules like axios and node-fetch which take care of that (and the JSON parsing) for you while providing modern Promise based APIs.
If you have a new enough version of Node, you can use the native Fetch API.

A: If you use a package like node-fetch you can get the whole thing in one go instead of what you have now which is chunking the data
const fetch = require('node-fetch');
const url = "https://api.spoonacular.com/recipes/random?apiKey=...&number=1";
fetch(url)
  .then(response => response.json())
  .then(data => console.log(data));

A: In addition to other answers, you can do it without another package.
https.get(url, function (response) {
    let result = "";
    response.on("data", function (data) {
        result += chunk;
    });
    res.on('end', () => {
        // now you have the combined result
        console.log(result);
    });
});


text:
Q: Is there an opposite of :g in vim? I know how to do something to every line that matches a pattern, using :g.  Is there a way to do something to every line that does not match the pattern?
For example, suppose I want to delete every line that does not match /foo/.  I might do something like:
:G/foo/d

(:G is not the opposite of :g, but that is what I am looking for)
Any ideas?

A: I think there is a inversion within VIM as,
:g!/foo/d

or, like the grep command (below),
:v/foo/d

If you are ready to go to the shell prompt,
grep -v foo filename.txt > new.txt

will do this


text:
Q: Why is my website when using www inaccessible? asp.net If I access : https://example.com, it works. The website can be accessed
But if I access : https://www.example.com, it can't be accessed like this :

Do I need settings in web.config?

A: add domainwww.example.com to Azure. See the details below.
https://learn.microsoft.com/en-us/azure/active-directory/fundamentals/add-custom-domain


text:
Q: In case second highest value is missing then use the highest value of salary from employee table I have an employee table as below. As you can see that second highest salary is 200
Incase the second highest salary is missing then there will be only one row as shown at last . In this case the query should fetch only 100
I have written query as but it is not working. Please help! Thanks
select salary   "SecondHighestSalary" from(
(select id,salary,rank() over(order by salary desc) rnk
from employee2)
)a
where (rnk) in coalesce(2,1)
I have also tried the following but it is fetching 2 rows but i need only 1

A: It sounds like you'd want something like
with ranked_emp as (
  select e.*,
         rank() over (order by e.sal desc) rnk,
         count(*) over () cnt
    from employee2 e
)
select salary "SecondHighestSalary"
  from ranked_emp
 where (rnk = 2 and cnt > 1)
    or (rnk = 1 and cnt = 1)

Note that I'm still using rank since you're using that in your approach and you don't specify how you want to handle ties.  If there are two employees with the same top salary, rank will assign both a rnk of 1 and no employee would have a rnk of 2 so the query wouldn't return any data.  dense_rank would ensure that there was at least one employee with a rnk of 2 if there were employees with at least 2 different salaries.  If there are two employees with the same top salary, row_number would arbitrarily assign one the rnk of 2.  The query I posted isn't trying to handle those duplicate situations because you haven't outlined exactly how you'd want it to behave in each instance.

A: If you are in Oracle 12.2 or higher, you can try:
select distinct id,
 nvl
(
 nth_value(salary, 2) from first
 over(partition by id
      order by salary desc
      range between unbounded preceding and unbounded
      following),
 salary
) second_max_salary
 from employee2


text:
Q: How to access the Items of a User Control I have a C# Form that prints multiple instances of a User Control.  Let's say that the form prints 5 instances of the User Control (Please see the link attached). How can I store/save the data inputted in all User Controls? Thanks
Here is the screenshot of the C# Form:

A: You'll have to store the User Controls when you instantiate them in a List or something.
You could have a class like this:
class SomeUC : UserControl
{
    public SomeUC()
    {
    }

    // A public method.
    public string GetData()
    {
        return textBox1.Text;
    }
}

Where textBox1 is the Name of a TextBox in your SomeUC
And then inside your main or something.
// Instantiate a List that will hold your UserControls, this has to be outside all methods
List<SomeUC> list = new List<SomeUC>();

// And now when you want to build your UCs
// Instantiate your UserControl
SomeUC uc1 = new SomeUC();
// Store your UserControl in a List or something (Can't help you with that)
list.Add(uc1);

Add as much as you want.
A List is not the only way you can do that, but since you don't know how many UserControls you're going to build beforehand, it makes since to use a List.
And then you can access them from the list by their index.
SomeUC uc1 = list[0];
string data = uc1.GetData();

This is an example of accessing one control (the TextBox) in your SomeUC. For other classes (such as the ComboBox) the interaction is different. Meaning you won't have a Text property in the ComboBox. You'll have to figure out things like that on youself. A little research is what it takes. You can always come back if you couldn't find a solution for something.

A: You can create a property like this for each item in user control.
public string DG
{
    get
    {
        return txtDG.Text;
    }
    set
    {
        txtDG.Text = value;
    }
}

Then you can access the control value by using following line in your form.
supposed you have created a usercontrol MyControl and you have placed some object of this control in FlowLayoutPenal (pnlFLP).
To get value from control
string DG = ((MyControl)pnlFLP.Controls[0]).DG;

To set value in control
((MyControl)pnlFLP.Controls[0]).DG = "1";

A: Try this code for accessing user control in the page
Dim txtName As TextBox = TryCast(UserControlName.FindControl("txtName"), TextBox)


text:
Q: Delete 0's from cell upon entry I want a macro so that when you enter a 0 into a particular cell/range of cells that it clears the cell.
I wrote a simple macro like this
Sub RemoveZeros()
'to remove 0 values that may be a result of a formula or direct entry.

    For Each cell In Range("A1:D20")
        If cell.Value = "0" Then cell.Clear
    Next

End Sub

However, I have to run this after I have entered my values for it to clear. I would like the cell to clear if a 0 is entered. How do I do this?

A: I found a solution
Private Sub Worksheet_Change(ByVal Target As Range)
    Application.EnableEvents = False
      If Target.Value = 0 Then Target.ClearContents
    Application.EnableEvents = True
End Sub

Thanks


text:
Q: Android canvas does not draw LinearGradient I am trying to draw path with some LinearGradient shader, but it is drawn as transparent, this is my simplified example:
    private val _shader = LinearGradient(
        50f,0f,
        50f,100f,
        0xff0000,0x00ff00,
        Shader.TileMode.MIRROR
    )
    private val _paint by lazy {
        Paint().apply {
            shader = _shader
        }
    }

    override fun draw(canvas: Canvas) {
        canvas.drawRect(0f,0f,100f,100f ,_paint)
    }

I tried changing layerType and hardwareAccelerated but it doesn't help.


text:
Q: Don't send Axios request when user selects a result I'm using v-autocomplete  from vuetify.js to retrieve a list of values from API Server.
It works fine and my list of values is not empty.
But my problem is when I select the correct value from this list. My script sends another request to server to retrieve another autocomplete list.
Do you have any idea to avoid to send request when a result is selected by the user ? Or to send request only when a key is down ?
My component :
   <template>

    <v-autocomplete
      v-model="selectValeur"
      :loading="loading"
      :search-input.sync="search"
      :items="resultatsAutocomplete"
      class="mb-4"
      hide-no-data
      hide-details
      :label="recherche.label"
    ></v-autocomplete>

</template>

Thanks,

A: selectValeur would no longer be null if the user has selected a value, so you could update search() to return if selectValeur is truthy:
export default {
  watch: {
    search(val) {
      if (this.selectValeur) {
        // value already selected
        return
      }

      //...
    }
  }
}

Or you could use vm.$watch on the search property to be able to stop the watcher when selectValeur is set:
export default {
  mounted() {
    this._unwatchSearch = this.$watch('search', val => {
      val && val !== this.selectValeur && this.fetchEntriesDebounced(val)
      if (!val) {
        this.resultatsAutocomplete = []
      }
    })
  },
  watch: {
    selectValeur(val) {
      if (val && this._unwatchSearch) {
        this._unwatchSearch()
      }
    }
  }
}

A: I found a solution to my problem.
I used the @keyup event to send the axios request and I deleted the watcher on search.
So, the API request are only sent when I press a key.
<template>

    <v-autocomplete
      v-model="selectValeur"
      :loading="loading"
      :items="resultatsAutocomplete"
      :search-input.sync="search"
      class="mb-4"
      hide-no-data
      hide-details
      :label="recherche.label"
      @keyup="keyupSearch"
    ></v-autocomplete>

</template>


text:
Q: component to theme a StringGrid like the ThemedDBGrid Exist  any similar component to theme a stringrid like the ThemedDBGrid  component compatible with delphi 5.

A: TMSSoftware's Advanced String Grid is pretty popular:
http://www.tmssoftware.com/site/advgrid.asp

A: You could also look at skinning components that skin the built in grid, such as:
http://www.almdev.com/

A: Surely you could take the source from ThemedDBGrid and re-work it for a stringgrid? Or you could use a DBGrid and wrap your strings up so that they can be accessed through a dataset.


text:
Q: Moving window implementation So, I have to implement an algorithm of Constant False Alarm Rate(CFAR). It kind of works like this:

I am using the notion that, in case that the target window contains more than one pixels, this operator (CFAR) uses the following detection criterion

where μt is the mean value of pixels in the target window. In this case, t should be replaced by t√n (where n is the number of pixels in the target window) in the PFA calculation, and where μb is the background mean, σb is the background standard deviation and t is a detector design parameter which is computed from PFA by the following equation:

Now, (enough with the equations already! XD), I know that I have to implement some loops over an image (which is a 2d matrix). I know the pixel to distance ratio for my image (which is 10.054m per pixel in both directions approximately). I can translate the distance entered by user into pixel sizes, suppose the background window is 800m (roughly 80 pixel), the guard window is 400m (roughly 40 pixel), while the target window is given to be 20m (roughly 2 pixel). My question is:
How to loop over the image?
The problem is not as easy as it seems, atleast not to me. You see, I can't figure out, for mxn pixels, how to implement the moving window. At first I thought that the target size would be fixed, and I could hardcode my pixel coordinates, but that is not the point. Any help is appreciated :)
EDIT:
The Target window moves inside the guard window. After this has finished, the guard window will move inside the background window, where the above will again take place, then finally the background window will move across the whole image!

A: Assuming that the windows progress from left to right and then top to bottom, the pseudo code may be as follow:
consider four attributes of each window, namely, bg_top, bg_left, bg_width, bg_hight, grd_top... etc.
also considering a inner window will never go outside crossing the outer window,
set all windows left and top to image's left and top, that may be (0,0).
now the loop
while(bg_top+bg_hight <= image_top+image_hight)
{
    while(bg_laft+bg_width <= image_left+image_width)
    {
        while(grd_top+gdr_hight <= bg_top+bg_hight)
        {
            while(grd_left+gdr_width <= bg_left+bg_width)
            //some pixels may be left out if the inner and outer window sizes are not divisible, it will not change the window size to fit in the last case.
            {
                 while(target_top+target_hight <= grd_top+grd_hight)
                 {
                      while(target_left+target_width <= grd_left+grd_width)
                      // the condition will move till end but never goes outside nor changes the inner window size to fit
                      {
                          //DO THE PROCESSING
                          //target_left+=target_width; //if they do not overlap
                          target_left+=1; //if they overlap
                      }
                      target_top+=target_hight// don't overlap. use 1 for overlaping
                      // use 1 if it goes down 1 pixel
                 }
                 grd_left+=grd_width; //or 1
            }
            grd_top+=grd_hight; //or 1
         }
         bg_left+=bg_width; //or 1
     }
     bg_top+=bg_hight; //or 1
}


text:
Q: How to link a button to other xml in Android? How to link a button in Android ?
for example in the Home page there are 2 buttons : 'Item1 & item2'
and i need to put in the code so i can click the 'Item' button and the Item1 data will be displayed ...
this is my current code on Activity.java :
    package com.example.myshops;

    import java.text.SimpleDateFormat;
    import java.util.Calendar;

    import android.app.Activity;
    import android.app.AlertDialog;
    import android.app.FragmentManager;
    import android.app.FragmentTransaction;
    import android.app.ActionBar;
    import android.app.Fragment;
    import android.os.Bundle;
    import android.view.Gravity;
    import android.view.LayoutInflater;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.view.Display;
    import android.view.WindowManager;
    import android.view.ViewGroup;
    import android.widget.Button;
    import android.widget.TextView;
    import android.widget.Toast;
    import android.os.Build;

    public class MainActivity extends Activity implements OnClickListener  {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            FragmentManager fragmentManager=getFragmentManager();
            FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
            Home_fragment hf=new Home_fragment();
            fragmentTransaction.replace(android.R.id.content, hf);
            fragmentTransaction.commit();

            setContentView(R.layout.activity_main);

            Button item1Click = (Button)findViewById(R.id.Item1Button);
            itemClick1.setOnClickListener(this);

            Button item2Click = (Button)findViewById(R.id.Item2Button);
            itemClick2.setOnClickListener(this);

            Button item3Click = (Button)findViewById(R.id.Item3Button);
            itemClick3.setOnClickListener(this);

            Calendar c = Calendar.getInstance();
            System.out.println("Current time => "+c.getTime());

            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formattedDate = df.format(c.getTime());
            // formattedDate have current date/time
            Toast.makeText(this, formattedDate, Toast.LENGTH_SHORT).show();

          // Now we display formattedDate value in TextView
            TextView txtView = new TextView(this);
            txtView.setText("Current Date and Time : "+formattedDate);
            txtView.setGravity(Gravity.CENTER);
            txtView.setTextSize(20);
            setContentView(txtView);

        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {

            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();
            if (id == R.id.action_settings) {
                return true;
            }
            return super.onOptionsItemSelected(item);
        }

        /**
         * A placeholder fragment containing a simple view.
         */

        public static class PlaceholderFragment extends Fragment {

            public PlaceholderFragment() {
            }

            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                    Bundle savedInstanceState) {
                View rootView = inflater.inflate(R.layout.fragment_main, container, false);
                return rootView;
            }

            public void item1Click(View view) {
                FragmentManager fragmentManager=getFragmentManager();
                FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
                Item1_fragment hf=new Item1_fragment();
                fragmentTransaction.replace(android.R.id.content, hf);
                fragmentTransaction.commit();
            }

        }

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

 switch(v.getId())
      {
       case R.id.Item1Button:

         break;
       case R.id.Item2Button:

         break;
       case R.id.Item3Button:

         break;
       }

        }

        }

my home.xml (for example) :
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.myshops.MainActivity"
        tools:ignore="MergeRootFrame" >

        <Button
            android:id="@+id/Item2Button"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/Item2Button"
            android:onClick="item2Click"
            android:text="@string/Item2" />

        <Button
            android:id="@+id/Item3Button"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/Item2Button"
            android:onClick="item3Click"
            android:text="@string/Item3" />

        <Button
            android:id="@+id/Item1Button"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:onClick="item1Click"
            android:text="@string/Item1" />

        <Button
            android:id="@+id/PrevButton"
            android:layout_width="110dp"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:text="@string/Previous" />

        <Button
            android:id="@+id/HomeButton"
            android:layout_width="110dp"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:text="@string/Home" />

        <Button
            android:id="@+id/NextButton"
            android:layout_width="85dp"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:text="@string/Next" />

    </RelativeLayout>

error in my logcats :
04-11 15:56:54.915: D/dalvikvm(547): Not late-enabling CheckJNI (already on)
04-11 15:56:56.145: D/AndroidRuntime(547): Shutting down VM
04-11 15:56:56.155: W/dalvikvm(547): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
04-11 15:56:56.165: E/AndroidRuntime(547): FATAL EXCEPTION: main
04-11 15:56:56.165: E/AndroidRuntime(547): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.s0237600_diary/com.example.myshops.MainActivity}: java.lang.NullPointerException
04-11 15:56:56.165: E/AndroidRuntime(547):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
04-11 15:56:56.165: E/AndroidRuntime(547):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
04-11 15:56:56.165: E/AndroidRuntime(547):  at android.app.ActivityThread.access$600(ActivityThread.java:122)
04-11 15:56:56.165: E/AndroidRuntime(547):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
04-11 15:56:56.165: E/AndroidRuntime(547):  at android.os.Handler.dispatchMessage(Handler.java:99)
04-11 15:56:56.165: E/AndroidRuntime(547):  at android.os.Looper.loop(Looper.java:137)
04-11 15:56:56.165: E/AndroidRuntime(547):  at android.app.ActivityThread.main(ActivityThread.java:4340)
04-11 15:56:56.165: E/AndroidRuntime(547):  at java.lang.reflect.Method.invokeNative(Native Method)
04-11 15:56:56.165: E/AndroidRuntime(547):  at java.lang.reflect.Method.invoke(Method.java:511)
04-11 15:56:56.165: E/AndroidRuntime(547):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
04-11 15:56:56.165: E/AndroidRuntime(547):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
04-11 15:56:56.165: E/AndroidRuntime(547):  at dalvik.system.NativeStart.main(Native Method)
04-11 15:56:56.165: E/AndroidRuntime(547): Caused by: java.lang.NullPointerException
04-11 15:56:56.165: E/AndroidRuntime(547):  at com.example.myshops.MainActivity.onCreate(MainActivity.java:44)
04-11 15:56:56.165: E/AndroidRuntime(547):  at android.app.Activity.performCreate(Activity.java:4465)
04-11 15:56:56.165: E/AndroidRuntime(547):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
04-11 15:56:56.165: E/AndroidRuntime(547):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)
04-11 15:56:56.165: E/AndroidRuntime(547):  ... 11 more
04-11 15:56:58.955: I/Process(547): Sending signal. PID: 547 SIG: 9
04-11 15:57:02.035: D/AndroidRuntime(565): Shutting down VM
04-11 15:57:02.035: W/dalvikvm(565): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
04-11 15:57:02.055: E/AndroidRuntime(565): FATAL EXCEPTION: main
04-11 15:57:02.055: E/AndroidRuntime(565): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myshops/com.example.myshops.MainActivity}: java.lang.NullPointerException
04-11 15:57:02.055: E/AndroidRuntime(565):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
04-11 15:57:02.055: E/AndroidRuntime(565):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
04-11 15:57:02.055: E/AndroidRuntime(565):  at android.app.ActivityThread.access$600(ActivityThread.java:122)
04-11 15:57:02.055: E/AndroidRuntime(565):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
04-11 15:57:02.055: E/AndroidRuntime(565):  at android.os.Handler.dispatchMessage(Handler.java:99)
04-11 15:57:02.055: E/AndroidRuntime(565):  at android.os.Looper.loop(Looper.java:137)
04-11 15:57:02.055: E/AndroidRuntime(565):  at android.app.ActivityThread.main(ActivityThread.java:4340)
04-11 15:57:02.055: E/AndroidRuntime(565):  at java.lang.reflect.Method.invokeNative(Native Method)

A: You should either define the click listener in code or in the xml not both. Remove one of them and the other should work.

A: Use
Onclicklistener like
 Button item1Click = (Button)findViewById(R.id.Item1Button);

 item1Click.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

        }
    };

and same for other button

A: Do this
    @Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    //check here that to which view does v match for example
    if(v==item1Click)
        {
            //then do something
        }
}

or else you can remove that implements thing and create separate listeners for each button as stated by raj

A: Access your all the Button click listener using single click listener and use the id of your buttons and implement each click events as below:
 @Override
public void onClick(View v) {
    // TODO Auto-generated method stub

  switch(v.getId())
  {
   case R.id.Item1Button:
     //write your logic
     break;
   case R.id.Item2Button:
     //write your logic
     break;
   case R.id.Item3Button:
     //write your logic
     break;
   }
}

A: i am telling one way to the solve the issue, there are other ways too to solve the issue
<Button
        android:id="@+id/Item3Button"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/Item2Button"
        android:onClick="item3Click"
        android:text="@string/Item3" />

here you have written  android:onClick="item3Click", for all button,
so in the jave code you can write like
 public void item3Click(View view){

    //what ever you want to do in the button 3 click
    }
 public void item2Click(View view){

    //what ever you want to do in the button 2 click
    }
 public void item1Click(View view){

    //what ever you want to do in the button 1 click
    }

repeat the same for the all button,


text:
Q: Help with linear function, I think In Argentine, the cost of kW/h is $4,5$ cents and in Latin America, $16$ ctvs (average).
a) In how many months would you update the cost to reach $16$ cents kW/h, applying a linear $20\%$ increment each month? And with $40\%$?
RE: I came to the conclusion that it will cost $12,77$ months with $20\%$ and $6,39$ months for $40\%$. And that with an increment of $255\%$ in $1$ month I would reach it.
Now, the next point is the one I am having trouble with:
b) Elaborate a graphic representation that allows to visualize and analyze how the quantity of months needed varies according to the monthly increment percentage.
I think this is a linear equation, right? Well I am having trouble to reach the $y = m  x + b$ equation. What should I use?
c) And the minimun amount of months is $1$, so should I limit the function domain, like saying $y > 1$ ?
Thanks!!!

A: For part a)
Let us use numbers and call $P_0$ the price before any increase. After a month, the price is increased by $x$, so at the start of next month, the price will be $$P_1=(1+x)P_0$$. Similarly, at the start of next month, the price will be $$P_2=(1+x)P_1=(1+x)^2 P_0$$ and so on. I suppose you see how this works and then, at the start of month $n$, the price will be $$P_n=(1+x)^nP_0$$ So, if $P_0=4.5$ and you want to use $x=0.20$ to reach $P_n=16$, you then need to solve for $n$ $$16=(1+0.2)^n \times 4.5$$ Taking the logarithms of both sides, you then end with $n=6.96$ that is to say $7$ months.
If we repeat the same calculation with $x=0.4$, you need to solve similarly $$16=(1+0.4)^n \times 4.5$$ whih leads to $n=3.77$ that is to say $4$ months.
For part b)
In part a), you saw that basically the equation can write $$\frac{16}{4.5}=(1+x)^n$$ so, taking again logarithms, we have $$n \log(1+x)=\log(\frac{16}{4.5})$$ and since tou want $n$ as a function of $x$, you have $$n=\frac{\log(\frac{16}{4.5})}{\log(1+x)}$$ If you want to do all of that in a single month, use $n=1$ in the previous formula and, using exponentials, solve for $x$ and you will find $x=2.55556$ that is to say a $255.56$% increase which corresponds exactly to the ratio of $\frac{16-4.5}{4.5}$
I hope that you percieve why we do not face linear relations.


text:
Q: CUDA populate small array with contents of larger array I'm fairly new to CUDA programming, so please forgive me if this is a silly question.
In CUDA, I'm trying to populate a small device array B (~20000 int elements) with the contents of a large device array A (~20 million int elements). A contains mostly zeros, but has about ~20000 non-zero elements, located at random and unknown positions in the array. I'd like to fill B with the non-zero contents of A using CUDA. The order of the elements within B is not important.
I've looked at the SDK and I found a number of "reduce" strategies for, e.g., parallel summing of an array, but each of these approaches reduce the array to a scalar, whereas I'm trying to "reduce" an array to a smaller array. Searching online hasn't yielded anything either. I'm not looking for full code, but just some ideas/links of how to implement this. I'm using C, and if possible, I'd like to do this without using any C++ classes or structures.
Thank you in advance for your assistance.

A: what you're describing sometimes goes by the name stream compaction
Thrust (e.g. copy_if) and
cub (e.g. DeviceSelect) offer options that should have relatively good performance.
If you did want to implement it yourself, stream compaction may use a sequence of lower-level parallel operations, a key one being a prefix sum.  You can get an idea of the build-up of a simple parallel prefix sum (and stream compaction) in GPU Gems.  I'm just adding this for informational purposes; I'm not suggesting you implement either stream compaction or a prefix sum yourself.
A complete stream compaction example using the GPU Gems prefix sum method is here.  However, I strongly encourage anyone to use thrust or cub, instead.


text:
Q: Removing duplicate strings from an array? How can I remove duplicate strings from a string array without using a HashSet?
I try to use loops, but the words not delete.
StringBuffer outString = new StringBuffer("Our, aim, and, isn't, easy, you, you're, actual, and, are, aren't, and, improve, achieving, and, Obviously, and, illumination, are");

wordList = outString.toString().split(", ");
for (i = 0; i < wordList.length; i++) {
  for (j = 0; j < wordList.length; j++) {
    if((wordList[i]!=wordList[j])&&(j>i)){
      t=true;
    }
  }
  if(t==true){
    k++;
  }
}
String[] wordList1 = new String[k];
wordList = outString.toString().split(", ");
for (i = 0; i < wordList.length; i++) {
  (j = 0; j < wordList.length; j++) {
    if((wordList[i]!=wordList[j])&&(j>i)){
      t=true;
    }
  }
  if(t==true){
    wordList1[i]=wordList[i];
  }
}

A: 1)
I think you need to use the equals operator. Try
if (!wordList[i].equals(wordList[j])){

instead of !=.
2) Also Kevin is right. You need to set t back to false.
3) Side note as pointed out by others already: To be more efficient you should start the inner loop with
for (j = i+1; j < wordList.length; j++) {

4) Another side note: Your result array is still too long. If you don't want to use a List<String> and it is ok to loose the original array you could go with a solution as suggested by Zim-Zam O'Pootertoot and set the original duplicates to null, add a counter
to count how many null values you assigned, initialize the new array with the correct size and loop a final time over the first array and copy only the non-null values into your new array.

A: If you are allowed to use Lists, you can define a generic method that does this fairly easily:
public <T> T[] removeDuplicates(final T[] array) {
    List<T> noDuplicates = new ArrayList<T>();
    for (T arrayElem : array) {
        if (!noDuplicates.contains(arrayElem)) {
            noDuplicates.add(arrayElem);
        }
    }
    return (T[]) noDuplicates.toArray();
}

A: Try this code to remove dup words:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < wordList.length; i++) {
    boolean found = false;
    for (int j = i+1; j < wordList.length; j++) {
        if (wordList[j].equals(wordList[i])) {
            found = true;
            break;
        }
    }
    // System.out.printf("Checking: [%s]%n", wordList[i]);
    if (!found) {
        if (sb.length() > 0)
            sb.append(' ');
        sb.append(wordList[i]);
    }
}
System.out.printf("Unique: [%s]%n", sb);

A: You probably want to set t back to false after pulling the value you want:
if(t)
{
     wordList1[i]=wordList[i];
     t = false;
}

Also this:
if((wordList[i]!=wordList[j])&&(j>i))

Will always return true since strings are immutable (unless you compared a string to an exact reference of itself which you disallow with j>i).  You need to change it to say this:
if (!(wordList[i].equals(wordList[j]))&&(j>i))

Using .equals will compared that they contain the same string, not that they point to the exact reference of a string.
Not sure if that's the only problems or not, a bit unclear from what's given.

A: In your inner loop, initialize j = i + 1
if(wordlist[i] != null && wordlist[i].equals(worldlist[j])) { wordlist[j] = null; }

...and then compact the array when you're finished to remove all null values

A: How about using a List:
wordList = outString.toString().split(", ");
List<String> finalList = new ArrayList<String>();
for(String val : wordList) {
  if(!finalList.contains(val)) {
    finalList.add(val);
  }
}

A Set would be more efficient, however.  If you can't use a List or a Set, and you are forced to remove the duplicates, then you will have to loop through the array each time, which will perform horribly.

A: Iterate through the array, and store in an auxiliary int[] or List<Integer> the indexes of duplicates that you find with your two for's.
Create a new Array, with size equal to the original one minus the size of the repeated Strings.
Iterate through your original array, if the index isn't on your auxiliary list, set it to your new Array.

A: The best and most effective method is to suppose arr is the array that contains strings and can have duplicate values:
Arrays.sort(arr);
int l = 0;
for (int a = 0; a < arr.length; a++) {
    if (a == arr.length - 1)
        l++;// its a unique value
    else if (!(a[a + 1].equals(arr[a])))
        l++;// its also a unique
}
String newArray[] = new String[l];
l = 0;
for (int a = 0; a < arr.length; a++) {
    if (a == arr.length - 1)
        newArray[l] = arr[a];
    else if (!(a[a + 1].equals(arr[a]))) {
        newArray[l] = arr[a];
        l++;
    }
}

A: Try this...
public class RemoveDupsStringArray {

public static void main(String[] args) {
    String[] withDuplicates = new String[] {"one","one","two","three","one","three","three"};
    String[] withoutDuplicates = new String[] {"one","two","three"};

    removeDuplicates(withDuplicates);
    removeDuplicates(withoutDuplicates);
}

private static void removeDuplicates(String[] array) {
    int[] occurence = new int[array.length];
    for (int i = 0; i < array.length; i++) {
        for(int j=i+1;j<array.length;j++){
            if(array[i]==array[j]){
                occurence[j]=j;
            }
        }
    }
    int resultLength=0;
    for(int i=0;i<occurence.length;i++){
        if(occurence[i]==0){
            resultLength++;
        }
    }
    String[] result=new String[resultLength];
    int index=0;int j=0;
    for(int i=0;i<occurence.length;i++){
        index = occurence[i];
        if(index==0){
            result[j]= array[i];
            j++;
        }
    }

    for(String eachString : result){
        System.out.println(eachString);
    }
}
}


text:
Q: PHP SQLServer Stored Procedure não executa corretamente Olá, estou desenvolvendo uma aplicação utilizando Laravel Framework Handler do meu Backend e encontrei o seguinte erro.
Meu Banco de Dados SqlServer Express 2008 R2 possui uma stored procedure que realiza uma série de rotinas e insere os dados já formatados em uma tabela. A stored procedure recebe uma Chave (Varchar) e o ano (int) do relatório que quero gerar.
Quando eu executo a stored procedure pelo script do Banco de Dados a inserção ocorre corretamente e tenho todos os dados.
exec indicador.usp_indicador_101_1 'asdfgh', 2015

Após a execução da procedure eu executo um método que realiza o seguinte select:
select * from indicador.T101_Indicador where A101_chave = 'asdfgh'

No cenário ideal eu tenho todos os resultados retornados corretamente:

Porém quando eu executo pelo PHP o mesmo código:
<?php
$server = "###.###.###.#";
$options = array(  "UID" => "usuario",  "PWD" => "senha",  "Database" => "meubanco");
$conn = sqlsrv_connect($server, $options);

// Then execute the procedure
$proc = "exec indicador.usp_indicador_101_1 '147896311212', 2015";
$proc_result = sqlsrv_query($conn, $proc );
// Etc...
//mssql_free_statement($proc);
sqlsrv_close($conn);
?>

Eu tenho apenas o retorno de uma linha:

A Stored procedure faz as inserções por si só, o select dos dados é feito em outro momento. As fotos apresentadas são de selects feitos no script do banco de dados.
Eu tentei de várias formas a execução da stored procedure, minha ultima tentativa foi esta com o PHP puro e o retorno é sempre o mesmo, apenas uma linha.
A seleção na aplicação é feita por um método utilizando os recursos do Laravel:
public static function T101_indicador($chave){

$dados = T101_indicador::where('A101_Chave', '=', $chave)
->orderBy('A101_Nomord')
->get();

//dd($dados);

return $dados;
}

A: Resolvi meu problema, segue o novo código:
$chave = (string) $chave;

$server = "enderecobanco";
$options = array(  "UID" => "usuario",  "PWD" => "senha",  "Database" => "bancodedados");
$conn = sqlsrv_connect($server, $options);

// Then execute the procedure
$proc = "{call $procedure(?,?)}";
  $params = array(&$chave, &$argumento);
  $statement = sqlsrv_prepare( $conn, $proc, $params);

sqlsrv_execute($statement);//Precisa executar Duas vezes para gerar todos os dados.
sqlsrv_execute($statement);

sqlsrv_close($conn);//fecha conexão

foi preciso adicionar "&" antes do array de parâmetros, segundo este site e utilizar o método sqlsrv_execute() duas vezes, ao invés de sqlsrv_query(). Não entendo o por que de ser necessário a execução dupla. Sem esta execução dupla o código não tem o resultado correto.


text:
Q: Find the largest score a rugby team cannot get exactly using just 3-point field goals and 7-point tries. Want to try prove the above using induction. I have worked out the largest impossible score is 11, thus meaning any score 12 or larger should be possible.
Where I'm struggling is to actually come up with some sort of expression to prove. It is my instinct to say that any score above 12 should be divisible by a linear combination of 7x + 3y for some x and y that are natural numbers.
Can anyone help point me in the right direction to begining my induction proof?

A: This is the Frobenius number problem, and for two values $x$ and $y$ with $\gcd(x,y)=1$ the desired number is $x y -x-y$, which is $11$ when $x=3$ and $y=7$.

A: We wish to prove that every integer greater than $11$ can be expressed in the form $7x + 3y$, where $x$ and $y$ are positive integers.  Let's look at the first few cases.
\begin{align*}
12 & = 3 + 3 + 3 + 3\\
13 & = 7 + 3 + 3\\
14 & = 7 + 7\\
15 & = 3 + 3 + 3 + 3 + 3
\end{align*}
Notice that if $n \geq 12$ has at least two summands equal to $3$, we can obtain $n + 1$ by replacing two $3$'s with a $7$.  If the expression for $n \geq 12$ contains fewer than two $3$'s, then we must have at least two $7$'s, so we can obtain $n + 1$ by replacing two $7$'s with five $3$'s.
Alternatively, observe that one we establish that $12, 13, 14$ can be expressed in the form $7x + 3y$ for positive integers $x$ and $y$, we can establish that $n \geq 15$ can be expressed in that form by observing that if $n - 3 = 7x + 3y$, then $n = 7x + 3(y + 1)$.


text:
Q: Why using database (redis, SQL) would help when loading big data and RAM is running out of memory? I need to take 100 000 images from a directory, put them all in one big dictionary where the keys are the ids of the pictures and the values are the numpy arrays of the pixels of the images. Creating this dict takes 19 GB of my RAM and I have 24GB in total. Then I need to order the dictionary with respect to the key and at the end take only the values of this ordered dictionary and save it as one big numpy array. I need this big numpy array because I want to sent it to train_test_split sklearn function and split the whole data to train and test sets with respect to their label. I found this question where they have the same problem with running out of RAM in the step where after creating the dictionary of 19GB I try to sort the dict: How to sort a LARGE dictionary and people suggest using database.
def save_all_images_as_one_numpy_array():
    data_dict = {}
    for img in os.listdir('images'):
        id_img = img.split('_')[1]
        loadimg = load_img(os.path.join('images', img))
        x = image.img_to_array(loadimg)
        data_dict[id_img] = x

data_dict = np.stack([ v for k, v in sorted(data_dict.items(), key = lambda x: int(x[0]))])
mmamfile = open_memmap('trythismmapfile.npy', dtype=np.float32, mode='w+',shape=data_dict.shape)
mmamfile[:] = data_dict[:]

def load_numpy_array_with_images():
    a = open_memmap('trythismmapfile.npy', dtype=np.float32, mode='r')

When using np.stack I am stacking each numpy array in new array and this is where I run out of RAM. I can't afford to buy more RAM. I thought I can use redis in docker container but I don't understand why and how using a database will solve my problem?

A: The reason using a DB helps is because the DB library stores data on the hard-disk rather than in memory. If you look at the documentation for the library the linked answer suggests then you'll see that the first argument is filename, demonstrating that the hard-disk is used.
https://docs.python.org/2/library/bsddb.html#bsddb.hashopen
However, the linked question is talking about sorting by value, not key. Sorting by key will be much less memory intensive although you'll likely still have memory issues when training your model. I'd suggest trying something along the lines of
# Get the list of file names
imgs = os.listdir('images')

# Create a mapping of ID to file name
# This will allow us to sort the IDs then load the files in order
img_ids = {int(img.split('_')[1]): img for img in imgs}

# Get the list of file names sorted by ID
sorted_imgs = [v for k, v in sorted(img_ids.items(), key=lambda x: x[0])]

# Define a function for loading a named img
def load_img(img):
    loadimg = load_img(os.path.join('images', img))
    return image.img_to_array(loadimg)

# Iterate through the sorted file names and stack the results
data_dict = np.stack([load_img(img) for img in sorted_imgs])


text:
Q: Problems with using MemoryCache in Web API for large data caching for 24 hours I have a requirement of caching data (JSON) for each unique searches to avoid the call for same searches from a paid third party service within 24 hours.
When I looked for the solution, I found that MemoryCache will solve the requirement. The articles which made me to come to this conclusion are below
1) https://code.msdn.microsoft.com/Caching-In-Web-API-cb40be30
2) Caching Data in Web API
Now I have couple of doubts in this approach.
1) Would MemoryCache serve the purpose of caching large JSON data for each unique searches. I mean What will be the Cache Limit for MemoryCache?
2) Would It cause any performance issues with my application?
3) Any other challenges with this approach?
4) Are there any better approaches?


text:
Q: Freedownloadmanager doesn't open after loading for few seconds. No error message is given I tried to install freedownloadmanager from .deb file through terminal and also using Gdebi package installer in Ubuntu 22.04. Install was successful but when I try to open it from search option, it loads for few seconds in topbar but does not open.
Is there any way to fix this?


text:
Q: Connecting to oracle database using Connection string Issue? I have an application which is using config file to connect to mssql server  and odbc is created and used in the config file.
This is the line in my config file to connect to database.
<add key="ConnectionString" value="Data Source=<DSN Name>;Initial Catalog=<DAtabase Name>;Integrated Security=True"></add>

Now we are testing in Oracle,
but the above format is not connecting  and I had tried  many other permutations of connection string like below but so far no luck
This is same like Windows string
<add key="ConnectionString" value="Data Source=<DSN Name>;Integrated Security=True"></add>

Included my Database Name with DSN
  <add key="ConnectionString" value="Data Source=<DSN Name>;Initial Catalog=<DAtabase Name>;Integrated Security=True"></add>

Included Driver and SID here
<add key="ConnectionString" value= Driver=<{Oracle in OraClient11g_home1}>;Server=serverSID;Uid=<myUsername>;password=<password>
></add>

The error I am receiving

Database setup cannot find the database mentioned in the config file

None of them are working wats the correct connection string for Oracle ?

A: Try DBQ= instead of Server= and PWD= instead of password=.
Attribute Server is used for the Microsoft ODBC Driver (see Connection String Format and Attributes). In Oracle the attribute is DBQ (see Using the Oracle ODBC Driver).


text:
Q: Flink how set up initial watermark I am building a streaming app using Flink 1.3.2 with scala, my Flink app will monitor a folder and stream new files into pipeline. Each record in the file has a timestamp associated. I want to use this timestamp as the event time and build watermark using AssignerWithPeriodicWatermarks[T], my watermark generator looks like below:
class TimeLagWatermarkGenerator extends AssignerWithPeriodicWatermarks[Activity] {
    val maxTimeLag = 6 * 3600000L // 6 hours
    override def extractTimestamp(element: Activity, previousElementTimestamp: Long): Long = {
    val format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX")
        val timestampString = element.getTimestamp
    }
    override def getCurrentWatermark(): Watermark = {
      new Watermark(System.currentTimeMillis() - maxTimeLag)
    }
  }

env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)
env.getConfig.setAutoWatermarkInterval(10000L)
val stream = env.readFile(inputformart, path, FileProcessingMode.PROCESS_CONTINUOUSLY, 100)

val activity = stream
      .assignTimestampsAndWatermarks(new TimeLagWatermarkGenerator())
      .map { line =>
        new tuple.Tuple2(line.id, line.count)
      }.keyBy(0).addSink(...)

However, since my folder has some old data there, I don't want to process them. And the timestamp of records in older file are > 6 hours, which should be older than watermark. However, when I start running it, I can still see some initial output been created. I was wondering how the initial value of watermark been set up, is it the before the first interval or after? It might be I misunderstand something here but need some advice.

A: There are no operators in the pipeline you've shown that care about time -- no windowing, no ProcessFunction timers -- so every stream element will pass thru unimpeded and be processed. If your goal is to skip elements that are late you'll need to introduce something that (somehow) compares event timestamps to the current watermark.
You could do this by introducing a step between the keyBy and sink, like this:
...
.keyBy(0)
.process(new DropLateEvents())
.addSink(...)

public static class DropLateEvents extends ProcessFunction<...> {
    @Override
    public void processElement(... event, Context context, Collector<...> out) throws Exception {
        TimerService timerService = context.timerService();
        if (context.timestamp() > timerService.currentWatermark()) {
           out.collect(event);
        }
    }
}

Having done this, your question about the initial watermark becomes relevant. With periodic watermarks, the initial watermark is Long.MIN_VALUE, so nothing will be considered late until the first watermark is emitted, which will happen after 10 seconds of operation (given how you've set the auto-watermarking interval).
The relevant code is here if you want to see how periodic watermarks are generated in more detail.
If you want to avoid processing late elements during the first 10 seconds, you could simply forget about using event time and watermarking entirely, and simply modify the processElement method shown above to compare the event timestamps to System.currentTimeMillis() - maxTimeLag rather than to the current watermark. Another solution would be to use punctuated watermarking, and emit a watermark with the very first event.
Or even more simply, you could detect and drop late events in a flatMap or filter, since you are defining lateness relative to System.currentTimeMillis() rather than to the watermarks.


text:
Q: overflow during operation a+(-a) Asumming a=1
1+(-1) =0
but with 4 bit binary ,using 2's complement
0001+1111=10000 ~ 0000
Isn't signed integer overflow undefined behavior ?
Do we depend on undefined behavior for such trivial result or I am missing something .
from wikipedia:
If the left two carry bits (the ones on the far left of the top row in these examples) are both 1s or both 0s, the result is valid; if the left two carry bits are "1 0" or "0 1", a sign overflow has occurred.

A: Adding signed numbers with opposite signs never generate overflow. Indeed, hardware usually has two flag bits related to addition, i.e., overflow bit and carry bit.
Overflow bit is only set if the container is not large enough to represent the number correctly. For signed number the hardware set this bit after analyzing the sign bit of each operand and the sign of the results. If the signs of operands are differents, it will never set this bit. Otherwise, if the signals of operands are equals, it analyses the sign of result. If it is different from the operands, it set this flag, indicating that the result is in overflow.
In your example, the sign of each operand is different, so there no overflow, but this operation generate a carry bit if you want to use large container to keep operation correct.

A: Signed integer overflow is undefined, but I fail to see how this would be an issue here, since you are adding two signed numbers and the result does fall within range.
For a 4 bit integer type, overflow would be adding 7+7, where the result should be 14 that does not fit in the range -2^3..2^3-1

A: The underlying representation may internally use overflow to get the correct result, but that is irrelevant. The behavior is only undefined if the result of an operation exceeds the range of the type.

A: It is undefined behavior but I'm not sure I understand your question.  Are you asking why it works in that example?  Because those values are within range and the result is in range.  Consider
-8 + -1
In 4 bit
1000 + 1111 -> 10111 -> 0111 -> 7.  Here we no longer have the correct answer


text:
Q: How to Install LuaFileSystem? I'm making a lua application and I am going to need the LFS. However it gives me an error while installing.
`Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\user>luarocks install luafilesystem
Installing http://luarocks.org/repositories/rocks/luafilesystem-1.6.2-2.src.
...

7-Zip 9.10 beta  Copyright (c) 1999-2009 Igor Pavlov  2009-12-22

Processing archive: luafilesystem-1.6.2.tar.gz

Extracting  luafilesystem-1.6.2.tar

Everything is Ok

Size:       122880
Compressed: 27886

7-Zip 9.10 beta  Copyright (c) 1999-2009 Igor Pavlov  2009-12-22

Processing archive: luafilesystem-1.6.2.tar

Extracting  pax_global_header
Extracting  luafilesystem-1.6.2
Extracting  luafilesystem-1.6.2\Makefile
Extracting  luafilesystem-1.6.2\Makefile.win
Extracting  luafilesystem-1.6.2\README
Extracting  luafilesystem-1.6.2\config
Extracting  luafilesystem-1.6.2\config.win
Extracting  luafilesystem-1.6.2\doc
Extracting  luafilesystem-1.6.2\doc\us
Extracting  luafilesystem-1.6.2\doc\us\examples.html
Extracting  luafilesystem-1.6.2\doc\us\index.html
Extracting  luafilesystem-1.6.2\doc\us\license.html
Extracting  luafilesystem-1.6.2\doc\us\luafilesystem.png
Extracting  luafilesystem-1.6.2\doc\us\manual.html
Extracting  luafilesystem-1.6.2\rockspecs
Extracting  luafilesystem-1.6.2\rockspecs\luafilesystem-1.3.0-1.rockspec
Extracting  luafilesystem-1.6.2\rockspecs\luafilesystem-1.4.0-1.rockspec
Extracting  luafilesystem-1.6.2\rockspecs\luafilesystem-1.4.0-2.rockspec
Extracting  luafilesystem-1.6.2\rockspecs\luafilesystem-1.4.1-1.rockspec
Extracting  luafilesystem-1.6.2\rockspecs\luafilesystem-1.4.1rc1-1.rockspec
Extracting  luafilesystem-1.6.2\rockspecs\luafilesystem-1.4.2-1.rockspec
Extracting  luafilesystem-1.6.2\rockspecs\luafilesystem-1.5.0-1.rockspec
Extracting  luafilesystem-1.6.2\rockspecs\luafilesystem-1.6.0-1.rockspec
Extracting  luafilesystem-1.6.2\rockspecs\luafilesystem-1.6.1-1.rockspec
Extracting  luafilesystem-1.6.2\rockspecs\luafilesystem-1.6.2-1.rockspec
Extracting  luafilesystem-1.6.2\rockspecs\luafilesystem-cvs-1.rockspec
Extracting  luafilesystem-1.6.2\rockspecs\luafilesystem-cvs-2.rockspec
Extracting  luafilesystem-1.6.2\src
Extracting  luafilesystem-1.6.2\src\.gitignore
Extracting  luafilesystem-1.6.2\src\lfs.c
Extracting  luafilesystem-1.6.2\src\lfs.def
Extracting  luafilesystem-1.6.2\src\lfs.h
Extracting  luafilesystem-1.6.2\tests
Extracting  luafilesystem-1.6.2\tests\test.lua
Extracting  luafilesystem-1.6.2\vc6
Extracting  luafilesystem-1.6.2\vc6\lfs.def
Extracting  luafilesystem-1.6.2\vc6\luafilesystem.dsw
Extracting  luafilesystem-1.6.2\vc6\luafilesystem_dll.dsp

Everything is Ok

Folders: 7
Files: 31
Size:       86449
Compressed: 122880
cl /MD /O2 -c -Fosrc/lfs.obj -IC:/Program Files/Lua/5.1/include src/lfs.c
'cl' is not recognized as an internal or external command,
operable program or batch file.

Error: Build error: Failed compiling object src/lfs.obj

C:\Users\user>`

I was running as Admin. I have tried looking at other posts and looking at the manual, but to no avail, Can someone help?

A: You need a Microsoft C compiler. There are other C compilers for Windows but they might not have compatible switches.
Microsoft hasn't shipped a C compiler independent of Visual Studio since they began the free Express edition. Install it and you should be good to go.
Build environment means that various environment variables, esp. PATH, are set up for the compiler. This is set up by running a batch file the VS provides. There could be a shortcut for it but if not (I suspect the Express version might not) look for a file like vc*.cmd or vc*.bat and create a shortcut to it or just run it at your command prompt.


text:
Q: Changing space in the supreme, surjectivity argument Let $\Omega$ an open subset of $\mathbb{R}^2$ with continuous boundary and $f:X\to L_0^2(\Omega)$ a surjective function, with $X$ another Hilbert space and $\displaystyle L_0^2(\Omega):=\left\{u\in L^2(\Omega):\int_\Omega u=0\right\}$. We know that
$$||u||_{L^2(\Omega)}=\sup_{v\in L_0^2(\Omega)\setminus 0}\dfrac{\langle u,v\rangle_{L^2(\Omega)}}{||v||_{L^2(\Omega)}}$$
By the surjectivity of $f$, there exists $\phi\in X$ such that $f(\phi)=v$. Furthermore, suppose that $||\phi||_X\leq C||v||_{0,\Omega}$ with $C>0$.
Is it true that
$$||u||_{L^2(\Omega)}=\sup_{v\in L_0^2(\Omega)\setminus 0}\dfrac{\langle u,v\rangle_{L^2(\Omega)}}{||v||_{L^2(\Omega)}}\leq C\sup_{\phi\in X\setminus 0}\dfrac{\langle u,f(\phi)\rangle_{L_0^2(\Omega)}}{||\phi||_X}$$
?

A: Clearly, $f$ is also one-to-one, due to the fact that
$$
\|\varphi\|_X\le C\,\|v\|_{L^2(\Omega)}=C\,\|f(\varphi)\|_{L^2(\Omega)},\tag{1}
$$
and since thus
\begin{align}
\|u\|_{L^2_0(\Omega)}=\sup_{v\in L_0^2(\Omega)\setminus 0}\dfrac{\langle u,v\rangle_{L^2(\Omega)}}{\|v\|_{L^2_0(\Omega)}}=
\sup_{\varphi\in X\setminus 0}\dfrac{\langle u,f(\varphi)\rangle_{L_0^2(\Omega)}}{\|f(\varphi)\|_{L^2_0(\Omega)}}.
\end{align}
But if $\varphi\ne 0$, then \tag{1} implies that
$$
\dfrac{\langle u,f(\varphi)\rangle_{L_0^2(\Omega)}}{\|f(\varphi)\|_{L^2_0(\Omega)}}
\le C\dfrac{\langle u,f(\varphi)\rangle_{L_0^2(\Omega)}}{\|\varphi\|_X}
$$
Hence
$$
\sup_{\varphi\in X\setminus 0}\dfrac{\langle u,f(\varphi)\rangle_{L_0^2(\Omega)}}
{\|f(\varphi)\|_{L^2_0(\Omega)}} \le\sup_{\varphi\in X\setminus 0}
C\dfrac{\langle u,f(\varphi)\rangle_{L_0^2(\Omega)}}{\|\varphi\|_X}.
$$