text:
Q: Need to convert array of objects that has parent child relationship and convert to primeng tree table nodes Given list of flatten array of objects that has parent child relationship among them. I need to convert to prime ng tree table data structure.
I would like to expand all the children at one time.
My end goal would be have following structure:
[{
        "data":{
            "name":"Pictures",
            "size":"150kb",
            "type":"Folder"
        },
        "children":[
            {
                "data":{
                    "name":"barcelona.jpg",
                    "size":"90kb",
                    "type":"Picture"
                }
            },
            {
                "data":{
                    "name":"primeui.png",
                    "size":"30kb",
                    "type":"Picture"
                }
            },
            {
                "data":{
                    "name":"optimus.jpg",
                    "size":"30kb",
                    "type":"Picture"
                }
            }
        ]
    }]

Given json array:
 data = [
    {
        dataId: 1,
        name: test1,
        description: 'some desc',
        parentId: null
    },
    {
        dataId: 2,
        name: test1,
        description: 'some desc',
        parentId: 2
    },
    {
        dataId: 3,
        name: test1,
        description: 'some desc',
        parentId: 1
    },
    {
        dataId: 4,
        name: test1,
        description: 'some desc',
        parentId: null
    }
]

A: Solution with recursive function

function getDataByParentId(data, parent) {
  const result = data
    .filter(d => d.parentId === parent);

  if (!result && !result.length) {
    return null;
  }

  return result.map(({ dataId, name, description }) =>
    ({ dataId, name, description, children: getDataByParentId(data, dataId) }))
}

const data = [{
    dataId: 1,
    name: 'test1',
    description: 'some desc',
    parentId: null
  },
  {
    dataId: 2,
    name: 'test2',
    description: 'some desc',
    parentId: 1
  },
  {
    dataId: 3,
    name: 'test3',
    description: 'some desc',
    parentId: 1
  },
  {
    dataId: 4,
    name: 'test4',
    description: 'some desc',
    parentId: null
  },
  {
    dataId: 5,
    name: 'test5',
    description: 'some desc',
    parentId: 4
  },
  {
    dataId: 6,
    name: 'test6',
    description: 'some desc',
    parentId: 5
  }
];

console.log(getDataByParentId(data, null));

A:

data = [
{
    dataId: 1,
    name: "test1",
    description: 'some desc',
    parentId: null
},
{
    dataId: 2,
    name: "test2",
    description: 'some desc',
    parentId: 1
},
{
    dataId: 3,
    name: "test3",
    description: 'some desc',
    parentId: 4
},
{
    dataId: 4,
    name: "test4",
    description: 'some desc',
    parentId: null
}
]

// find leaf who does not have child using recursive
function findLeaf(data, curIndex, parIndex) {
    const childId = data[curIndex].dataId;
    for(let i = 0; i < data.length; i++) {
        if(data[i].parentId == childId) {
            return findLeaf(data, i, curIndex);
        }
    }
    return [curIndex, parIndex];
}

// check if array contains child
// and returns child index and parent index
function getChildIndex(data) {
    for(let i = 0; i < data.length; i++) {
        if(data[i].parentId != null) {
            for(let j = 0; j < data.length; j++) {
                if(data[j].dataId == data[i].parentId)
                    return [i, j];
            }
        }
    }
    return [-1];
}

function normalize(data) {
    // get child and start from it
    let childIndex = getChildIndex(data);
    while(childIndex[0] !== -1) {
        // check if dataId and parentId are same
        // if it's same, set parentId to null
        // to remove infinite recursive call
        if(childIndex[0] == childIndex[1]) {
            data[childIndex[0]].parentId = null;
            childIndex = getChildIndex(data);
            continue;
        }
        // get leaf index and its parent index
        const [cIndex, pIndex] = findLeaf(data, childIndex[0], childIndex[1]);
        // correcting data structure before inserting child to parent
        if(data[pIndex].children == undefined)
            data[pIndex].children = [];
        delete data[cIndex].parentId;
        delete data[cIndex].dataId;
        if(data[cIndex].children != undefined) {
            cchildren = data[cIndex].children;
            delete data[cIndex].children;
            data[cIndex] = { data: data[cIndex], children: cchildren };
        }
        // insert children to parent
        data[pIndex].children.push({ data: data[cIndex] });
        // reconfiguring data by removing inserted child
        data = [...data.slice(0, cIndex), ...data.slice(cIndex+1)];
        // check if there is child left, to loop again
        childIndex = getChildIndex(data);
    }
    // there is no child, it's time to normalize parent structure.
    for(let i = 0; i < data.length; i++) {
        delete data[i].dataId;
        delete data[i].parentId;
        //const children = data[i].children;
        //delete data[i].children;
        //data[i] = children ? { data: data[i], children: children } : { data: data[i] }
    }

    return data;
}

console.log(normalize(data));

A: Here's a possible solution that "misuses" filter. The idea is to first build a simple mapping from dataId to node and then use it to build the tree in the filter iteration.

const data = [{
    dataId: 1,
    name: 'test1',
    description: 'some desc',
    parentId: null
  },
  {
    dataId: 2,
    name: 'test2',
    description: 'some desc',
    parentId: 1
  },
  {
    dataId: 3,
    name: 'test3',
    description: 'some desc',
    parentId: 1
  },
  {
    dataId: 4,
    name: 'test4',
    description: 'some desc',
    parentId: null
  },
  {
    dataId: 5,
    name: 'test5',
    description: 'some desc',
    parentId: 4
  },
  {
    dataId: 6,
    name: 'test6',
    description: 'some desc',
    parentId: 5
  }
];

let dataMap = data.reduce((m, d) => {
  m[d.dataId] = Object.assign({}, d);
  return m;
}, {});

const trees = data.filter(d => {
  if (d.parentId !== null) { // assign child to its parent
    let parentNode = dataMap[d.parentId];
    if (!('children' in parentNode)) parentNode['children'] = [];
    parentNode.children.push(dataMap[d.dataId]);
    return false;
  }
  return true; // root node, do nothing
}).map(d => dataMap[d.dataId]);

console.log(trees);

Of course, you can make further adjustments to only pluck certain properties from your data objects.


text:
Q: Rails 3.1 assets precompilation I'm working on a rails 3 app and trying to deploy it on a production environment.
I'm using capistrano to deploy my app and configured it to precompile the assets after the update_code task.
The thing is everything works fine when I deploy the app.
By following the server production logs I see this :
Compiled application.js  (6ms)  (pid 7552)
Compiled jquery.js  (4ms)  (pid 7552)
Compiled jquery_ujs.js  (0ms)  (pid 7552)
Compiled home.js  (94ms)  (pid 7552)
Compiled libs/dd_belatedpng.js  (0ms)  (pid 7552)
Compiled libs/modernizr-1.7.min.js  (0ms)  (pid 7552)
Compiled plugins.js  (0ms)  (pid 7552)
Compiled script.js  (0ms)  (pid 7552)
Compiled user_sessions.js  (93ms)  (pid 7552)
Compiled users.js  (92ms)  (pid 7552)
Compiled application.css  (3ms)  (pid 7552)
Compiled handheld.css  (0ms)  (pid 7552)
Compiled home.css  (55ms)  (pid 7552)
Compiled style.css  (0ms)  (pid 7552)
Compiled user_sessions.css  (1ms)  (pid 7552)
Compiled users.css  (0ms)  (pid 7552)
Compiled application.js  (6ms)  (pid 7541)
Compiled jquery.js  (4ms)  (pid 7541)
Compiled jquery_ujs.js  (0ms)  (pid 7541)
Compiled home.js  (95ms)  (pid 7541)
Compiled libs/dd_belatedpng.js  (0ms)  (pid 7541)
Compiled libs/modernizr-1.7.min.js  (0ms)  (pid 7541)
Compiled plugins.js  (0ms)  (pid 7541)
Compiled script.js  (0ms)  (pid 7541)
Compiled user_sessions.js  (93ms)  (pid 7541)
Compiled users.js  (94ms)  (pid 7541)
Compiled application.css  (2ms)  (pid 7541)
Compiled handheld.css  (0ms)  (pid 7541)
Compiled home.css  (1ms)  (pid 7541)
Compiled style.css  (0ms)  (pid 7541)
Compiled user_sessions.css  (0ms)  (pid 7541)
Compiled users.css  (0ms)  (pid 7541)

But if I try to display the main page in a browser, I get this :
ActionView::Template::Error (style.css isn't precompiled):
    14:
    15:     %link{:rel => "shortcut icon", :href => "/favicon.ico" }
    16:     %link{:rel => "apple-touch-icon", :href => "/apple-touch-icon.png"}
    17:     = stylesheet_link_tag    "style"
    18:     = javascript_include_tag "libs/modernizr-1.7.min"
    19:     = javascript_include_tag "application"
    20:
  app/views/layouts/application.html.haml:17:in         `_app_views_layouts_application_html_haml__1713356285_69878424198520'

I just can't understand how the server is able to tell me the assets are compiled and just after it tells me that, actually, the files aren't compiled.
Does anyone encountered this kind of problem ?
Thanks for your help.

A: One solution is to tell the production environment not to check for pre-compiled in the config/environments/production.rb and set the line:
config.assets.compile = false

to
config.assets.compile = true

Restart your server and then you should check where HALM is looking for the style.css which should be assets/style.css

UPDATE
Here's another option
Tell your config/environments/production.rb to compile that exactly file to make sure It's being compiled.
config.assets.precompile += %w( style.css )
Saw this on https://stackoverflow.com/a/7541958/295228

redpajama_set_name: RedPajamaStackExchange


text:
Q: python map vs itertools.map: Make the iterator version behave like the former Consider the following example code. The example is given just to highlight the different functionality between map and itertools.imap. What I really want to do cannot be
done with a list comprehension because in my real problem I am not creating a list but filling a larger numpy array with small arrays. So in response to the code below, please do not suggest: [f(x) for x in range(3)]
Example:
g = []

def f(x):
    g.append(x)

The results I get with map and itertools.map:
map(f, range(3)) # Results in g = [0,1,2]

itertools.imap(f, range(3)) # Does not change g

I want the g to change as done by the map function.
However, I have heard that map will (or does) behave like
itertools.imap in Python 3. Even though I am using Python 2.7 I want to learn the correct way of using an iterator version of the map. How do I use itertools.imap to achieve
the same outcome as I get with map?
I can do:
b = itertools.imap(f, range(3))
list(b) # This gives g = [0,1,2] if starting with an empty g.

Is this the correct way, or is there a better way?
Thanks in advance.

A: You are using map() incorrectly.  It should not be used for the side effects of the function call, but to transform an iterable.
You can use list(itertools.imap(f, range(3))) to get the behavior you want, but I would argue that you should change your entire approach to use a normal for loop:
for i in range(3):
    f(i)

This makes it clear that the return values from the f() calls are not being used.

A: itertools functions return generators; they only operate when iterated over.  So itertools.imap(f, range(3)) won't actually do anything until you run it to completion e.g. with list.
Per http://docs.python.org/2/library/itertools.html#recipes, the most efficient way to consume an iterator is with a zero-length deque:
collections.deque(itertools.imap(f, range(3)), maxlen=0)

However, if you're calling a function for its side effects you should be using an imperative as opposed to functional syntax:
for i in range(3):
    f(i)

A: The difference is that map in Python 2.x is the equivalent of list(map(...)) in Python 3. That's it - nothing special...


text:
Q: BigDecimal constructor performance - string vs numeric new BigDecimal("10000");
new BigDecimal(10000);

I know the string constructor is used if the number is bigger than the compiler would accept, but are either of the constructors faster than the other?

A: Passing a String to the constructor of BigDecimal requires a parsing of the String and a check char by char.
Passing an int is faster because it results only in a single assignment.
In any case the time difference is not signifiant.
Here the code of BigDecimal with an int parameter:
public BigDecimal(int val) {
    intCompact = val;
}

The code of BigDecimal constructor with a String calls BigDecimal(char[], int, int) that has around 140 rows of code.

A:
I know the string constructor is used if the number is bigger than the compiler would accept

That's not the only reason for using the String constructor. Another reason for using the String constructor is to keep the value as-is when the BigDecimal is created.
If you don't really care about precision, you should stick to using double instead of BigDecimal.

but are either of the constructors faster than the other

This is something you have to find out yourself by benchmarking your code. That being said, you should prefer using the valueOf method instead of creating a new BigDecimal since valueOf will return cached values. (Currently, this ranges from 0 to 10 but this range can be higher for different JVM implementations and future implementations of the HotSpot VM as well so you are better of using valueOf)

A: You can look at source code.
public BigDecimal(int val) {
    intCompact = val;
}

public BigDecimal(String val) {
    this(val.toCharArray(), 0, val.length());
}

public BigDecimal(char[] in, int offset, int len) {
       ...very long
}

Obviously, who is faster.

A: The Constructor new BigDecimal(10000) should be faster because it does not have to convert a string into a number. The under-the-hood there has to be a cast or another call to a string function which would cause some additional overhead.
public class benchmark {

    public static void main(String [ ] args) {
        timeFunction();
    }

static void timeFunction() {
     long startTime = System.nanoTime();

     BigDecimal v1 = new BigDecimal("10000");
     System.out.println("new BigDecimal(\"10000\") : " + (System.nanoTime() - startTime) / 1000000 + " ms");

     startTime = System.nanoTime();

     BigDecimal v2 = new BigDecimal(10000);
     System.out.println("new BigDecimal(10000) : " + (System.nanoTime() - startTime) / 1000000 + " ms");
}

}

OUTPUT
new BigDecimal("10000") : 4 ms
new BigDecimal(10000) : 0 ms

A: Find the time difference yourself & analyse. Like :-
BigDecimal big = null;
long startTime = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
    big = new BigDecimal("10000");
}
long endTime = System.currentTimeMillis();
System.out.println("time Taken In String : " + (endTime - startTime));

startTime = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
    big = new BigDecimal(10000);
}
endTime = System.currentTimeMillis();
System.out.println("time Taken in Numeric : " + (endTime - startTime));

PS:- Keep in consideration the Garbage Collection. Consider the above code as a reference only.


text:
Q: Time Machine says Time Capsule is full even though all backups are much smaller than HDD I have several machines backing up via Time Machine to a 1TB Time Capsule.
Lately one of my Macs said he had to delete an old backup in order to create the new backup. I was surprised about this since I formatted the whole Time Capsule not too long ago.
After I check the Time Capsule's network share, I selected all files in Finder, i.e. all machines' backups and opened the combined info panel. It told me that all files are only around 350GB big, which is much less than the capacity of the Time Capsule.
I thought that maybe there are some hidden files so I checked in Terminal (ls -a) and there were no more files than in Finder (that would take up a lot of space).
When I went one level up in Finder and asked Finder for the info of the whole network drive, it told me that the capacity is indeed 1TB and only few GB are left on the disk.
How can I now find out what's wrong with the Time Capsule and what is apparently taking up space on it?


text:
Q: How to bind event Jquery to page? I have Jquery function that executes AJAX query to server.
How can I call this after load page in the specified url page? May I bind this to element HTML, I mean:

A: One way using jQuery:
$(document).ready( function() {
 //do whatever you need, you can check if some element exists and then, call your function
  if($("#graph").length > 0)
    callfunction();
});

No jQuery, only vanilla js:
window.onload = function() {
    if(document.getElementById("graph"))
       callfunction();
}

A: jQuery handles the HTML file with a variable called document.
Document has two popular event states

*

*load when the page has been loaded

*ready when the page has been loaded and all other decorations to the HTML have been applied.

jQuery provides hooks for these states.
To run javascript code after each of the events listed above, you have to put the function within the appropriate event scope.
For loading, this would be…
$(document).load(function() {
  // javascript code you want to execute
})

After the page has been ready, but not yet rendered, you can apply some other javascript code using
$(document).ready(function() {
  // javascript code you want to execute
})


text:
Q: Intrinsics - Get only all matching indexes I'm comparing two vectors using System.Runtime.Intrinsics and would like to know the fastest way to get all matching Indexes only.
At the moment my code looks like below:
static void CompareVectors(Vector128<byte> first, Vector128<byte> second)
{
    var matches = Avx2.MoveMask(Avx2.CompareEqual(first, second));
    if (matches == 0) return;
    var firstIndex = BitOps.TrailingZeroCount(matches) / sizeof(byte);
    for (var j = firstIndex; j < Vector128<sbyte>.Count; j++)
    {
        var matchingValue = first.GetElement(j);
        //do stuff
    }
}

Problem:
If first index matches it iterates over all elements in the vector, even if just the first index is a match.
How can I get all matching Indexes only to speed it up?


text:
Q: How would I graph this implicit function in geogebra? I am trying to graph the below equation in geogebra.
\begin{equation}
 x\cos { (xy) } = 4 -y
\end{equation}
I was able to get wolframalpha to graph it but I am unsure on how to in geogebra. I am assuming I should be using an implict type function. Anyone one know how I can do this?
http://www.wolframalpha.com/input/?i=xcos%28xy%29+%3D+4+-+y

A: Write the equation in standard form ($f(x,y)=0$) and use the ImplicitCurve command:


text:
Q: MariaDB updating json attribute across array in JSON
Goal
  I have a json column in my table which I want to update in MariaDB 10.3.18.

CREATE TABLE IF NOT EXISTS `json_data` (
  `name` VARCHAR(255),
  `config_json` MEDIUMTEXT(10000)
);

config_json field has value like this.
{
    "one": {
        "filters": [
            {
                "type": "campaign_categories_5",
                "title": "Title1"
            }
        ],
        "value1": "one",
        "containers": [],
        "combined": false
    },
    "description": "",
    "columns": [
        {
            "dataType": "STRING",
            "title": "Title1"
        },
        {
            "dataType": "STRING",
            "title": "Title2"
        },
        {
            "dataType": "STRING",
            "title": "Title3"
        },
        {
            "dataType": "STRING",
            "title": "Title1"
        }
    ]
}

I am trying to update every entry in the table by replacing attribute "title" of config_json in the path column[*].title by replacing value "Title1" with "Updated Title1", "Title2" with "Updated Title2" and "Title3" with "Updated Title3".
Updated json should look like this
{
    "one": {
        "filters": [
            {
                "type": "campaign_categories_5",
                "title": "Title1"
            }
        ],
        "value1": "one",
        "containers": [],
        "combined": false
    },
    "description": "",
    "columns": [
        {
            "dataType": "STRING",
            "title": "Updated Title1"
        },
        {
            "dataType": "STRING",
            "title": "Updated Title2"
        },
        {
            "dataType": "STRING",
            "title": "Updated Title3"
        },
        {
            "dataType": "STRING",
            "title": "Updated Title1"
        }
    ]
}

As you can see above I shouldn't change title attribute in other path.
I am trying this
drop FUNCTION  if EXISTS modify_json;
create FUNCTION modify_json(myvar json)
returns json
deterministic
begin

    SET @i = 0;
    SET @len = JSON_LENGTH(myvar, '$.columns');
    while i < @len do
        IF JSON_CONTAINS(myvar, '"Title1"', concat('$.columns[', i, '].title')) THEN
            set myvar = json_replace(myvar, concat('$.columns[', i, '].title'), '"Updated Title1"');
        END IF;
        IF JSON_CONTAINS(myvar, '"Title2"', concat('$.columns[', i, '].title')) THEN
            set myvar = json_replace(myvar, concat('$.columns[', i, '].title'), '"Updated Title2"');
        END IF;
        IF JSON_CONTAINS(myvar, '"Title3"', concat('$.columns[', i, '].title')) THEN
            set myvar = json_replace(myvar, concat('$.columns[', i, '].title'), '"Updated Title3"');
        END IF;
        set i = i + 1;
    end while;
    return myvar;
end;

update config_suite_reports_element set config_json = modify_json(config_json)
where json_contains_path(config_json, 'one', '$.columns[*].title');

But I am getting following error
Error occurred during SQL script execution

Reason:
SQL Error [1064] [42000]: (conn=5434951) You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 6

A: I found the problem.
1. Delimiter
2. variable naming convention in latest mariaDB 10.3
DROP FUNCTION IF EXISTS func;
DELIMITER //

CREATE FUNCTION func(myvar json) RETURNS json DETERMINISTIC
BEGIN
  DECLARE i TINYINT;
  DECLARE len TINYINT;
  SET i = 0;
  SET len = JSON_LENGTH(myvar, '$.columns');
  while i < len do
    IF JSON_CONTAINS(myvar, '"Title1"', concat('$.columns[', i, '].title')) THEN
        set myvar = json_replace(myvar, concat('$.columns[', i, '].title'), 'Updated Title1');
    ELSEIF JSON_CONTAINS(myvar, '"Title2"', concat('$.columns[', i, '].title')) THEN
        set myvar = json_replace(myvar, concat('$.columns[', i, '].title'), 'Updated Title2');
    ELSEIF JSON_CONTAINS(myvar, '"Title3"', concat('$.columns[', i, '].title')) THEN
        set myvar = json_replace(myvar, concat('$.columns[', i, '].title'), 'Updated Title3');
    END IF;
    set i = i + 1;
  end while;
  RETURN myvar;
END

//

DELIMITER ;

Thank you @BillKarwin


text:
Q: Unexpected "No matches" error for selected table node I am trying to obtain the table on this website:
https://ultrasignup.com/results_event.aspx?did=31930
I want all attributes (all columns and rows) of the table.
I used chrome developer to look at the css attributes of the table and determined that the ID was list_results. Therefore I used list_results in my code.
library(rvest)
library(magrittr)

data <- html_session("https://ultrasignup.com/results_event.aspx?did=31930")

data %>%
html_node("#jqgh_list_formattime , #jqgh_list_gender , #jqgh_list_age , #jqgh_list_state , #jqgh_list_city , #jqgh_list_firstname , #jqgh_list_place") %>%
html_text()

This produces the following error:
Error: No matches
I am new to using rvest and scraping webpages. Any advice/pointers are appreciated.


text:
Q: How to check if an email address exists or not without sending an email? I have a bunch of mails ids and I want to check all that mail is valid or not.
How it's possible to check without sending any mail.

A: Syntax Validation: The most obvious part, people - however - know least about. There's more to email syntax validation than the simple PHP RegEx rule you're using. There's the IETF Standards (all the RFCs), but you'll also have to look at ISP-specific syntax checking, quoted words, domain literals, non-ASCII domains, etc.
Disposable & Free Emails: Next, before you use any server side code to check the given email address, it's recommended to check whether or not you're dealing with disposable emails (e.g. mailinator.com) or free emails (Gmail, Yahoo!, etc.) and act accordingly.
Obvious Typos: Now is the time to check for obvious misspellings and typos. (e.g. user@gnail.com would be corrected to user@gmail.com)
DNS validation, including MC record(s) lookup: Verify the DNS MX-Records for the given domain.
SMTP connection, catch-all check: Now for the meaty part, but also the most risky. Validating email addresses by establishing and then aborting an SMTP connection to the given mail server is still the only way to really find out if a mailbox actually exists. However, if executed in the false way, you will - really quickly - be blacklisted and considered a spammer.
From:
https://www.quora.com/Is-there-a-way-to-check-if-an-e-mail-address-is-valid-without-e-mailing-it
mailboxlayer API - my clear favourite. It's basically free, safe, and comes with each and every validation tool necessary in order to properly validate email addresses.
Kickbox.io - great product, but this will cost you a little more. Advantage: They also offer list-cleaning.
email-validator.net - great, but costly.


text:
Q: Ejecutar procedimiento almacenado. Typescript, Nodejs, SQL Server Estoy intentando ejecutar un procedimiento almacenado pero me arroja un error.EREQUEST.
No sé que podría estar mal.
Tengo un procedimiento almacenado que es dbo.obtenerUsuarios tal como se muestra en la imagen.

Y el error que obtengo es el siguiente:

Conexion:
export const obtenerConexionDB = async (): Promise<any> => {
   try {

       const pool = await sql.connect(dbConfiguracion)
       return pool;

   } catch (err) {
       console.log("error conexión", JSON.stringify(err));
   }
}

Servicio o data
export const psObtenerUsuario  = async () => {
const pool = await connection.obtenerConexionDB();
pool.connect(() => {
    try {
        const request = new sql.Request()
        const result = request.execute(constantes.procedimientosAlmacenados.obtenerUsuarios)
        return result
    } catch (error) {
    }
})}

La conexión está bien, porque si ejecuto un request.query(), me retorna los resultados de la db. Agradezco algo de ayuda, no sé donde podría estar el error.

A: Ya lo solucioné:
const pool = await connection.obtenerConexionDB();
let result = await pool.request().execute(constantes.procedimientosAlmacenados.obtenerUsuarios);
//let result = await pool.request().query("select * from [User]");
console.log(result)
return result;


text:
Q: Returning Failure if File does not exist I am running the below script in SQL Server Agent.
All the subsequent steps in job are dependent upon this step. This is pretty simple Looking for a file and exits with failure if file is not found.
  $file = "C:\\Data\\FileDrop\\.done"
  $CheckFile = Test-Path -Path $file

  if (!($CheckFile))  {exit 1 }

However when the agent job runs, it says the step failed because file not found and existing with code 0 - success.
What am I doing wrong here?

A: I don't think the return value / error code of the job has anything to do with whatever value the script returns.
If you want to fail with an error message, try this:
# make sure to stop on errors
$ErrorActionPreference = 'Stop'
$path = 'C:\Data\FileDrop\.done'
# check for file explicitly (in case a directory with that name exists)
if(![System.IO.File]::Exists($path)) {
    # throwing an exception will abort the job
    throw (New-Object System.IO.FileNotFoundException("File not found: $path", $path))
}
# anything after this will not be executed on error...

This should fail the job entirely and show the error message in the job's history.

A: Maybe this is what you're looking for:
if(!(Test-Path "C:\Data\FileDrop\.done")){
    return 1
}
else {
    return 0
}

A: This is not going to be a great answer because I have not found the documentation that explains this but the use of Exit followed by a number seems to not have any effect on the exit code.
The following example works, with the general idea taken from a blog.
First create a test script like the following:
$host.SetShouldExit(12345)
exit

Next call this script from the Powershell command line as in the following example:
$command = "C:\YourTestScriptPathAndName.ps1"
Powershell -NonInteractive -NoProfile -Command $command

The script will run and exit, and we can then check the exit code from the Powershell prompt by writing out the contents of $LASTEXISTCODE
$LASTEXITCODE

In this case $LASTEXISTCODE would contain 12345.
In the case of using this with Test-Path it would look like this:
#using a path that does not exist
if(Test-Path -Path 'C:\nope'){
   $host.SetShouldExit(1234)
}
else{
   $host.SetShouldExit(2222)
}

This sets the exit code to 2222 when invoked from the command line, but when I invoke that test script from another script instead of from the command line the $LASTEXITCODE variable is set to 0 still.


text:
Q: 'int' object has no attribute 'append' while appending with indexes errors = [[[]]]
x = 0
y = 0
fun = 0
zen = 0

def solve():
    cntBe = set()
    global fun
    global zen
    global errors
    global x
    global y
    global arr
    for i in range(0, 8):
        if arr[x][i] != 0 or arr[i][y] != 0:
            cntBe.add(arr[x][i])
            cntBe.add(arr[i][y])
    cntBe.discard(0)
    errors.append(x)
    errors[zen].append(y) #error here
    #errors[zen][fun].append(list(cntBe)) #error here
    fun += 1
    zen += 1

plz don't jusge my variable names, its a work in progress. However, it tells me the error of the title whenever i try to append stuff with the indexes in the array, I have used this many times in the program and it worked, but for some reason, it does not work here. I am trying to append these values in an array. so, the x axis goes in one dimension, the y axis goes in another, and the set of numbers goes in another dimension. It is for a soduku program, in order to keep track of a boxes position and the numbers it cannot be. The for loop tests the rows and columns to see what the numbers cannot be. Then I subtract 0 because that just means it is an empty space. arr is a list of all the nubers in the soduku grid, and errors is the array i am trying to make as explained above. it is currently, just an empty list 3d list, and the x and y variables correspond with square positions. fun and zen are just numbers to hold index values and they both start at 0

A: The error that you are getting is because errors is a one dimensional list or array. If it were a 2d list you would not get that error.
This :
zen = 0
errors = [[]]
error [zen].append ('anything')

will not give that error.
This :
zen = 0
errors = []
error [zen].append ('anything')

will!


text:
Q: Why is $\int_{\pi/2}^0 \cos x dx$ negative? $$\int_{\pi/2}^0 \cos x dx = -1$$
But we know that integration is an area under the curve.
$\cos x$ is positive between $0$ and $\pi/2$. So, the area should be positive. But why is the integration negative?

A: The integral is a directed area. And by swapping the lower and upper limit, you change the direction of every area. Which is why you have to invert the sign of the integral if you do. So we have
$$\int_{\frac\pi2}^0\cos (x)\mathrm dx=-\int_0^{\frac\pi2}\cos (x)\mathrm dx=-1.$$


text:
Q: where to paste the java file into the android studio project I am new to android studio.I am doing the "Send Data From Android To SQL Server Using RESTful API" using Visual Studio and Android Studio.
There is a one instruction that i do not understand is that

*

*Copy and paste the RestAPI.java file into your project.

I have to copy the RESTAP.java file into my Android studio project but I do not know where should i put inside my android studio (eg., file path location).
below attached is the screenshot that i just create in Android Studio:

A: Paste it in the folder containing the MainActivity. Normally the package name would change automatically in Android Studio but if it doesn't then remember to change the package name appropriately.
You can also create a new folder to store all the java files to segregate your API from your main code. That will be just be like another package in your android studio.


text:
Q: Storing ISO-8601 timestamp in hive STACK -
HDP 3.1.0.0
Hive 3.1.0
Trying to store timestamps like 2020-01-03T02:46:21.148+02:00 in an ORC hive table.
Storing the timestamps using the timestamp datatype gives NULL on querying which is expected as this is not the format hive expects it's timestamps to be.
But as per the documentation if we set the appropriate timestamp format serde property then hive should be able to read the timezones.
"On the table level, alternative timestamp formats can be supported by providing the format to the SerDe property "timestamp.formats" (as of release 1.2.0 with HIVE-9298). For example, yyyy-MM-dd'T'HH:mm:ss.SSS,yyyy-MM-dd'T'HH:mm:ss."
However despite  ALTER TABLE  SET SERDEPROPERTIES ("timestamp.formats"="yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX");  the property seems to have no effect and hive is still not able to read it. I tried multiple variations of the format but none worked.
Creating the table as textfile doesn't help either.
To replicate -
create table default.test_tz (tt timestamp) stored as orc;
insert into default.test_tz values ("2020-01-03T02:46:21.148+02:00"), ("2017-02-16T11:24:29.000Z"), ("2017-02-16 11:24:29"), ("2019-06-15T15:43:19");
ALTER TABLE default.test_tz SET SERDEPROPERTIES ("timestamp.formats"="yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX");
Should I just store it as string? What is the best practice in such cases.


text:
Q: Cannot get DocuSign Connect working with Salesforce: Object reference not set to an instance of an object I'm new to DocuSign and have just been playing around setting up DocuSign for Salesforce. I have a DocuSign demo environment and a Salesforce developer environment. I've installed DocuSign for Salesforce (dfs) and added the "Send to DocuSign" and DocuSign Status items to the page layout of the SF Contract object.
I hit "Send to DocuSign" on a new Contract and after some time this seemed to work, a new DocuSign status was added in the Status section of the Contract. It took a while, so I wanted to set up Connect so that it would be faster, or at least that's how I thought it should work.
I followed the documentation to set up Connect and activated the DocuSign Status Object and Enabled Logging. I then hit "Send to DocuSign" again. The Status section doesn't get updated with any new DocuSign Status objects. The output in the logs says:
10/15/2015 10:58:23 AM
Salesforce Connect Config: <sfconfig log="1" ackl="0" password="Idxhauns2N2DyYGT1jEm2Q==" sfenvironment="production" senderselectable="Contract,Lead,Opportunity,Case,Account" senderoverride="0" username="jen@jenscompany.com"><dsevents><dsevent event="Completed" level="Envelope" /><dsevent event="Declined" level="Envelope" /><dsevent event="Delivered" level="Envelope" /><dsevent event="Sent" level="Envelope" /><dsevent event="Signed" level="Envelope" /><dsevent event="Voided" level="Envelope" /><dsevent event="Completed" level="Recipient" /><dsevent event="Declined" level="Recipient" /><dsevent event="Delivered" level="Recipient" /><dsevent event="Sent" level="Recipient" /></dsevents><dsusers all="1"><dsuser userId="78c3e1da-085a-45a0-9bcf-1dcddbc48158" /></dsusers><sfobject object="dsfs__DocuSign_Status__c" objectName="dsfs__DocuSign_Status__c" active="1" insert="1" oncompleteonly="0"><updatefield sffield="dsfs__DocuSign_Envelope_ID__c" dsnode="Envelope" dsattr="EnvelopeId" /><updatefield sffield="dsfs__Sent_Date_Time__c" dsnode="Envelope" dsattr="SentInitial" /><updatefield sffield="dsfs__Sender__c" dsnode="Envelope" dsattr="UserName" /><updatefield sffield="dsfs__Sender_Email__c" dsnode="Envelope" dsattr="Email" /><updatefield sffield="dsfs__Envelope_Status__c" dsnode="Envelope" dsattr="Status" /><updatefield sffield="dsfs__Completed_Date_Time__c" dsnode="Envelope" dsattr="Completed" /><updatefield sffield="dsfs__Subject__c" dsnode="Envelope" dsattr="Subject" /><updatefield sffield="dsfs__Company__r" dsnode="EnvelopeCustomField" dsattr="##SFAccount" /><updatefield sffield="dsfs__Case__r" dsnode="EnvelopeCustomField" dsattr="##SFCase" /><updatefield sffield="dsfs__Contract__r" dsnode="EnvelopeCustomField" dsattr="##SFContract" /><updatefield sffield="dsfs__Opportunity__r" dsnode="EnvelopeCustomField" dsattr="##SFOpportunity" /><updatefield sffield="dsfs__Declined_Date_Time__c" dsnode="Recipient" dsattr="Declined" /><updatefield sffield="dsfs__Declined_Reason__c" dsnode="Recipient" dsattr="DeclineReason" /><updatefield sffield="dsfs__Voided_Date_Time__c" dsnode="Envelope" dsattr="Voided" /><updatefield sffield="dsfs__Voided_Reason__c" dsnode="Envelope" dsattr="VoidedReason" /><updatefield sffield="dsfs__Envelope_Link__c" dsnode="Envelope" dsattr="EnvelopeId" dslink="1" /><updatefield sffield="dsfs__Viewed_Date_Time__c" dsnode="Recipient" dsattr="Delivered" /><updatefield dsnode="##docattachment" dsattr="Document,0,1,NamePDFReplaceExt" /><updatefield sffield="##docattachment" dsnode="##docattachment" dsattr="Document,0,1,NamePDFReplaceExt" dslink="0" /><selectfield sffield="dsfs__DocuSign_Envelope_ID__c" dsnode="Envelope" dsattr="EnvelopeId" /></sfobject></sfconfig>
10/15/2015 10:58:23 AM
Envelope Data: <Certificate><Envelopes><Envelope EnvelopeId="1A7BCB46-E398-41AA-ACD1-18BCD2C1E9C5" AccountId="5CB10BDC-1DAB-4CA7-A2E7-BEB2AEA280CB" UserId="78C3E1DA-085A-45A0-9BCF-1DCDDBC48158" UserName="Jennifer Cheung" Email="striderwho@hotmail.com" SenderIP="182.50.78.8 " SigningLocation="Online" SourceEnvelopeId="" Status="Sent" Created="10/15/2015 10:58:02 AM" CreatedBy="78C3E1DA-085A-45A0-9BCF-1DCDDBC48158" Deleted="" DeletedBy="" ACStatus="Original" ACStatusDate="10/15/2015 10:58:02 AM" ACHolder="Jennifer Cheung" ACHolderEmail="striderwho@hotmail.com" ACHolderLocation="DocuSign" Sent="10/15/2015 10:58:03 AM" SentInitial="10/15/2015 10:58:03 AM" Delivered="" Signed="" Completed="" Declined="" TimedOut="" Voided="" VoidedReason="" Subject="Documents for your DocuSign Signature" AutoNav="Enabled" EnvelopeIdStamping="Enabled"><Owners><Owner ACStatus="Original" ACStatusDate="10/15/2015 10:58:02 AM" ACHolder="Jennifer Cheung" ACHolderEmail="striderwho@hotmail.com" ACHolderLocation="DocuSign" /></Owners></Envelope></Envelopes><Documents><Document DocumentId="FD5B3331-8709-4851-ACC6-2D899252E9FE" Sequence="1" DocumentType="Content" Name="PRIMEDIRECTIVE.pdf" Extension="pdf" Pages="1" Created="10/15/2015 10:58:03 AM" Status="Created" Hash="fLF+/G8FCge71UO2CWj57Glz+Jc=" /></Documents><Pages><Page PageId="99A23D55-B32D-4F89-A6D3-2FE6AEC475E7" DocumentId="FD5B3331-8709-4851-ACC6-2D899252E9FE" PageType="Content" Sequence="1" Status="Active" /></Pages><Tabs /><Recipients><Recipient RecipientId="0DD36920-7E09-4E4D-B108-E8DB4DFCF637" EnvelopeId="1A7BCB46-E398-41AA-ACD1-18BCD2C1E9C5" RecipientType="Signer" UserId="78C3E1DA-085A-45A0-9BCF-1DCDDBC48158" AccountId="5CB10BDC-1DAB-4CA7-A2E7-BEB2AEA280CB" Email="striderwho@hotmail.com" UserName="Jen Cheung" CompanyName="ServiceRocket" JobTitle="" SignatureImageId="" InitialsImageId="" AccessCodeRequired="False" IDCheckRequired="False" Sent="Sent: 10/15/2015 10:58:03 AM" Delivered="" Signed="" Declined="" DeclineReason="" Status="Sent" IPAddress="" SigningGroupName="" SigningGroupUsers="" SignedOnMobile="" AccountEsignId="" RoutingOrder="1" InPersonID="" WetSigned="no" Offline="false" SignatureImageHash="" InitialsImageHash="" SecurityLevel="Email, Account Authentication (None)" RecipientSuppliesTabs="true" ExternalUserName="" ExternalCompanyName="" CustomField1="##SFUser:00528000001Jds1AAC:Jen Cheung" CustomField2="" CustomField3="" /></Recipients><FormFields /><EnvelopeCustomFields><EnvelopeCustomField Name="DSXPartnerApplication" Value="DSFS 3.10" Required="False" Show="False" /><EnvelopeCustomField Name="PlatformName" Value="Salesforce" Required="False" Show="False" /><EnvelopeCustomField Name="AppName" Value="DocuSignForSalesforce" Required="False" Show="False" /><EnvelopeCustomField Name="DSFSSourceObjectId" Value="800280000000qON~Contract" Required="False" Show="False" /><EnvelopeCustomField Name="##SFContract" Value="800280000000qON" Required="False" Show="False" /><EnvelopeCustomField Name="##SFAccount" Value="00128000008iNC0AAM" Required="False" Show="False" /><EnvelopeCustomField Name="Company" Value="DocuSign" Required="False" Show="False" /></EnvelopeCustomFields></Certificate>
10/15/2015 10:58:24 AM
SalesForceIntegration failed, Salesforce User: jen@jenscompany.com, message: Object reference not set to an instance of an object.

I've tried a whole number of config changes and can't seem to get rid of that error. And nothing is appearing in the Status section of the Contract object in Salesforce.
Does anyone have any pointers?


text:
Q: Get a total of two different columns I need to get generate a combined total of two different columns.
My query looks like this
SELECT 0 AS OTHER_AMT, ABS([MISC AMT]*100) AS MISC_AMT FROM ESCHEATMENT_FINAL WHERE [TRAN DT] < '6/30/2012' AND [MISC AMT]<>0

UNION ALL

SELECT ABS([DEP AMT]*100+[INT AMT]*100) AS OTHER_AMT, 0 AS MISC_AMT FROM [CCC_Escheatment].[dbo].[ESCHEATMENT_FINAL] WHERE [TRAN DT] < '6/30/2014' AND [DEP AMT]<>0

I need a combined total amount for both MISC_AMT and OTHER_AMT .  How would I go about doing this

A: select sum(other_amt) + sum(misc_amt) from (
    SELECT 0 AS OTHER_AMT, ABS([MISC AMT]*100) AS MISC_AMT FROM ESCHEATMENT_FINAL WHERE [TRAN DT] < '6/30/2012' AND [MISC AMT]<>0

    UNION ALL

    SELECT ABS([DEP AMT]*100+[INT AMT]*100) AS OTHER_AMT, 0 AS MISC_AMT FROM [CCC_Escheatment].[dbo].[ESCHEATMENT_FINAL] WHERE [TRAN DT] < '6/30/2014' AND [DEP AMT]<>0
)


text:
Q: Broken Pipe exception on idle server I am using a dropwizard server to serve http requests. This dropwizard application is backed my mysql server for data storage. But when left idle (overnight) it gives a 'broken pipe exception'
 I did a few things that I thought might help. I set the jdbc url in the yaml file to'autoConnect=true'. I also added a 'checkOnBorrow' property. I have increased the jvm to use 4gb
none of these fixes worked.
 Also the wait_timeout and 'interactive_timeout for mysql serveris set to 8 hours.
does this need to more more/less?
Also is there a configuration property that can be set in the dropwizard yaml file? Or in other words how is connection pooling managed in dropwizard?

A: The problem:
MySql server has a timeout configured after which it terminates all connections idle in the connection pool. This in my case was the default (8 hrs). However the database connection pool is unaware of the terminated connections in the pool. So when a new request comes in, a dead connection is accessed from teh connection pool which results in a 'Broken Pipe' exception.
Solution:
So to fix this, we need to get rid of the dead connections and make the pool aware if the connection it is trying to borrow is a dead connection. This can be achieved by setting the following in the .yml configuration.
checkOnReturn: true
checkWhileIdle: true
checkOnBorrow: true


text:
Q: INNER JOIN in three models of DJANGO RF Here My Models:
Model
I need to make a Join between these three tables, I need a list with the field machine_name, which are in the Action table, based on the resetter_uuid of the machine.
class Machine(models.Model):
    machine_uuid = models.UUIDField(default=uuid.uuid4,unique=True)
    machine_created_date = models.DateTimeField(default=timezone.now)
    machine_name = models.CharField(max_length=50, null=True, default=None, blank=True)
    machine_time_up = models.CharField(max_length=10, null=True, default=None, blank=True)
    resetter_uuid = models.ForeignKey(Resetter, to_field="resetter_uuid", db_column="resetter_uuid", related_name='Resetters', on_delete=models.CASCADE, null=True)

    class Meta:
        db_table = 'Machine'

class Resetter(models.Model):
    resetter_uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
    resetter_created_date = models.DateTimeField(default=timezone.now)
    class Meta:
        db_table = 'Resetter'

class Action(models.Model):
    action_uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
    action_created_date = models.DateTimeField(default=timezone.now)
    action_change_port = models.PositiveSmallIntegerField(null=True, default=None)
    action_reset_machine = models.PositiveSmallIntegerField(null=True, default=None)
    machine_uuid = models.ForeignKey(Machine, to_field="machine_uuid", db_column="machine_uuid", related_name='Machines', on_delete=models.CASCADE)
    action_status = models.BooleanField()

    class Meta:
        db_table = 'Action'

With MySQL I have solved the query in this way:
SELECT
    m.machine_name
FROM
    machine m
INNER JOIN
    resetter r
ON
    m.resetter_uuid =r.resetter_uuid
INNER JOIN
    xem_api.action a
ON
    a.machine_uuid = m.machine_uuid
WHERE
    m.resetter_uuid    = '5b94e54e7fd644359374146fe78eaea4' and a.action_status = true and a.action_reset_rig = 1;

I have used prefetch_related() and select_related() in the views but, without success how would the best way to get that result?

A: I believe the join will work with select_related / prefetch_related. Try the code below. Remember select_related is used to query a single field (the one side of a relation) and prefetch is used to query the many field.
Machine.objects.select_related('Resetters').prefetch_related('Machines).all()

You can double check that the join is working by adding a logging config to your settings file. Add the code below, do your query, and check your logs.
LOGGING = {
    'version': 1,
    'filters': {
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        }
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'filters': ['require_debug_true'],
            'class': 'logging.StreamHandler',
        }
    },
    'loggers': {
        'django.db.backends': {
            'level': 'DEBUG',
            'handlers': ['console'],
        }
    }
}


text:
Q: how to map the response of getlistitems web service of sharepoint I have basic question on sharepoint application.
There are some webservices provided by MS to access sharepoint services.
lets take example of GetListItems service.
i wanted to know, how to identify from XML parser that, a item is folder or file? what Tag i should look into to recognize the item as folder or file
how to get attributes of a file or folder(last accesed date, read only etc etc).
Please guide me in right direction.

A: A typical response from the web service looks like below:
<rs:data ItemCount="4">
  <z:row ows_Modified="2012-05-31 12:34:01" ows_ContentTypeId="0x01200082B0C5829FE047A1BF58F68DA1DAB12500C7BCD99F82ACA340A0131D59CE62371B" ows__ModerationStatus="0" ows__Level="1" ows_ID="1" ows_Created_x0020_Date="1;#2012-05-31 12:34:01" ows_PermMask="0x7fffffffffffffff" ows_FileRef="1;#depts/it/Lists/CTADocuments/mygroup" />
  <z:row ows_Modified="2012-05-31 12:36:51" ows_ContentTypeId="0x01200082B0C5829FE047A1BF58F68DA1DAB12500C7BCD99F82ACA340A0131D59CE62371B" ows__ModerationStatus="0" ows__Level="1" ows_ID="2" ows_Created_x0020_Date="2;#2012-05-31 12:36:51" ows_PermMask="0x7fffffffffffffff" ows_FileRef="2;#depts/it/Lists/CTADocuments/mygroup/another one" />
  <z:row ows_Modified="2012-05-31 17:49:45" ows_ContentTypeId="0x010100EB5D8789C471B04E80E2A7481607C23B" ows__ModerationStatus="0" ows__Level="1" ows_ID="9" ows_Created_x0020_Date="9;#2012-05-31 17:49:45" ows_PermMask="0x7fffffffffffffff" ows_FileRef="9;#depts/it/Lists/CTADocuments/Just_the_Essentials_Publishing.master" />
  <z:row ows_Modified="2012-06-07 17:05:11" ows_ContentTypeId="0x010100EB5D8789C471B04E80E2A7481607C23B" ows__ModerationStatus="0" ows__Level="1" ows_ID="10" ows_Created_x0020_Date="10;#2012-06-07 17:05:11" ows_PermMask="0x7fffffffffffffff" ows_FileRef="10;#depts/it/Lists/CTADocuments/mygroup/another one/junk.txt" />
</rs:data>

First two z:row are folders (look at the ContentTypeId) the others are documents.
ContentTypeIds: http://msdn.microsoft.com/en-us/library/aa543822.aspx


text:
Q: Maximum and minimum of sets In a city of 1000, 900 people have dogs and 500 people have cats. The minimum number of people with both dogs and cats are A, and the maximum number is B. determine A+B
for the minimum people i calculated it with the venn diagram and got 400,
900+500-x=1000
for the maximum I am not sure but is it 400 too? or 500 considering all the people that have cats have both dogs and cats?

A: It is $500$. If $500$ have cats and $900$ have dogs, the maximum number of both cats and dogs will be the number in the smallest set, as it can obviously be contained in the larger set. Hope that helped!


text:
Q: How much to read from socket when using select I'm using select() to listen for data on multiple sockets. When I'm notified that there is data available, how much should I read()?

*

*I could loop over read() until there is no more data, process the data, and then return back to the select-loop. However, I can imagine that the socket recieves so much data so fast that it temporarily 'starves' the other sockets. Especially since I am thinking of using select also for inter-thread communication (message-passing style), I'd like to keep latency low. Is this an issue in reality?

*The alternative would be to always read a fixed size of bytes, and then return to the loop. The downside here would be added overhead when there is more data available than fits into my buffer.
What's the best practice here?

A: Not sure how this is implemented on other platforms, but on Windows the ioctlsocket(FIONREAD) call tells you how many bytes can be read by a single call to recv(). More bytes could be in the socket's queue by the time you actually call recv(). The next call to select() will report the socket is still readable, though.

A: The too-common approach here is to read everything that's pending on a given socket, especially if one moves to platform-specific advanced polling APIs like kqueue(2) and epoll(7) enabling edge-triggered events. But, you certainly don't have to! Flip a bit associated with that socket somewhere once you think you got enough data (but not everything), and do more recv(2)'s later, say at the very end of the file-descriptor checking loop, without calling select(2) again.
Then the question is too general. What are your goals? Low latency? Hight throughput? Scalability? There's no single answer to everything (well, except for 42 :)


text:
Q: Is that possible to estimate the VC dimension for GBM (or more specific XGBoost)? Is there any simple way to estimate the VC dimension for GBM? Or, for more specific implementation XGBoost?
XGBoost usually has large variability when training on a dataset with less than 500 samples more than 1000 features. Is there any way to estimate the model complexity of XGBoost with certain hyperparameters?


text:
Q: Why is my image splitting up from my div on smaller screens? so on a website that I'm creating, I have a wavy type image on top of a div to give the div that kind of wavy effect. And it looks fine on desktop screens:
Desktop Pic
Although right around 450-pixel width, the image starts to separate from the div, and I'm not entirely sure why it's doing this, there's no bottom margin or anything applied to the img:
Mobile Pic
If anybody knows a solution, it'd help out a lot. Thanks!
Also, these are the only two CSS styles I've applied to those images. The dimensions are 1000 width by 44 height
width: 100%;
height:auto;

A: Try giving the div margin-top when the screen size 450px.
div{
     margin-top:-20px;
}


text:
Q: ClassNotFoundException: javax.wsdl.extensions.ExtensibilityElement I write a webservice follow spring-ws tutorial, i get a error.
Caused by: java.lang.ClassNotFoundException:javax.wsdl.extensions.ExtensibilityElement
But my path really have wsdl4j.jar.

EndpointConfig only have a bean that return a SimpleWsdl11Definition with orders.wsdl.
pom.xml
<dependencies>
    <dependency>
        <groupId>org.springframework.ws</groupId>
        <artifactId>spring-ws-core</artifactId>
        <version>2.2.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>jaxen</groupId>
        <artifactId>jaxen</artifactId>
        <version>1.1.6</version>
    </dependency>
    <dependency>
        <groupId>org.jdom</groupId>
        <artifactId>jdom2</artifactId>
        <version>2.0.6</version>
    </dependency>
    <dependency>
        <groupId>wsdl4j</groupId>
        <artifactId>wsdl4j</artifactId>
        <version>1.5.1</version>
    </dependency>
</dependencies>

A: Add this to the pom.xml
    <dependency>
        <groupId>wsdl4j</groupId>
        <artifactId>wsdl4j</artifactId>
    </dependency>

A: I am using below pom.xml and it works, In case if you want to try.
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/maven-v4_0_0.xsd">
    <artifactId>spring-server-final</artifactId>
    <modelVersion>4.0.0</modelVersion>
    <packaging>war</packaging>
    <groupId>spring-server-final</groupId>
    <version>1.0-SNAPSHOT</version>
    <name>spring-server-final</name>
    <url>http://maven.apache.org</url>
    <repositories>
        <repository>
            <id>spring-maven-milestone</id>
            <name>Springframework Maven Repository</name>
            <url>http://maven.springframework.org/milestone</url>
        </repository>
    </repositories>
    <properties>
        <spring.version>4.2.5.RELEASE</spring.version>
        <spring.ws.version>2.2.4.RELEASE</spring.ws.version>
        <log4j.version>1.2.16</log4j.version>
        <apache.ws.version>1.6.19</apache.ws.version>
        <context.path>spring-server</context.path>
    </properties>
    <dependencies>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.ws</groupId>
            <artifactId>spring-ws-core</artifactId>
            <version>${spring.ws.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.ws</groupId>
            <artifactId>spring-ws-security</artifactId>
            <version>${spring.ws.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.ws</groupId>
            <artifactId>spring-xml</artifactId>
            <version>${spring.ws.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.ws.xmlschema</groupId>
            <artifactId>xmlschema-core</artifactId>
            <version>2.2.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.ws.security</groupId>
            <artifactId>wss4j</artifactId>
            <version>${apache.ws.version}</version>
        </dependency>
        <dependency>
            <groupId>wsdl4j</groupId>
            <artifactId>wsdl4j</artifactId>
            <version>1.6.2</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>spring-server-final</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.1</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

A: It could be possible you are using different version. Please check whether your jar actually contains this class -
javax.wsdl.extensions.ExtensibilityElement


text:
Q: New feature in .NET Framework? I have a research about feature "Data Access Application Block" in EntLib. I find some codes:
public static class MapBuilder<TResult> where TResult : new()
{
    //...
}

I don't understand about meaning of declaring of this class when using "where TResult : new()". I think this is new feature in .NET Framework to declare a class. Please give me a document or link to explain about this feature. Thanks.

A: It's a generic type parameter constraint. It's been around since the introduction of generics, in .net 2.0.
Constraints on Type Parameters (MSDN)
The particular constraint you've mentioned means only a class with a public parameterless constructor can be used as the type TResult.

See also: Generics (MSDN)

A: where TResult : new() adds a constraint on the generic type parameter (TResult). The type argument must have a parameterless constructor.


text:
Q: How can I run my Django app with gunicorn and daphna on heroku? I try to make a chat. There are some functions that work with "original" Django (def index(request) and so on) but also there are functions, where I need to use websockets. I installed channels to make a websocket interface. So, I have two systems: gunicorn interconnects with HTTP(S) and daphna interconnets with WS(S) interface.
On my local machine I set up all files (asgi.py, consumers.py, routing.py and settings.py) and I type: python manage.py runserver - everything works. But when I deploy it to heroku, I get a lot of errors.
I tried everything, but didn't find the solution. Ask for your help.
Here are my files:
chat/Procfile
web: daphne Chat.asgi:channel_layer --port $PORT
web2: gunicorn Chat.wsgi

chat/chat/asgi.py
import os
import channels.asgi

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Chat.settings')
channel_layer = channels.asgi.get_channel_layer()

chat/chat/routing.py
from channels.routing import route

channel_routing = {
    'websocket.connect': 'user_chating.consumers.ws_connect',
    'websocket.receive': 'user_chating.consumers.ws_message',
    'websocket.disconnect': 'user_chating.consumers.ws_disconnect',
    #'send_email': 'user_chating.consumers.send_email_consumer'
}

chat/chat/settings.py
...

# Application definition

INSTALLED_APPS = [
    'user_chating',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'channels',
]

CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'asgiref.inmemory.ChannelLayer',
        'ROUTING': 'Chat.routing.channel_routing',
    },
}
ASGI_APPLICATION = "Chat.routing.application"

MIDDLEWARE = [
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'Chat.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR, 'templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'Chat.wsgi.application'

...

chat/chat/wsgi.py

import os

from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Chat.settings')
application = get_wsgi_application()

chat/user_chatting/consumers.py
import json
import time

from django.core.mail import send_mail
from channels.channel import Group

def ws_connect(message):
    Group('chat').add(message.reply_channel)
    message.reply_channel.send({"accept": True})

def ws_message(message):
    Group('chat').send({'text': json.dumps({'message': message.content['text'],
                                            'sender': message.reply_channel.name})})

def ws_disconnect(message):
    Group('chat').discard(message.reply_channel)

Can anybody help me please?


text:
Q: Setting the capability for aws cloudformation template-validate I am trying to validate a Cloudformation template. The command I am issuing is:
▶ aws cloudformation validate-template --template-body file://template.json

The response I am getting, however, is:
"CapabilitiesReason": "The following resource(s) require capabilities:
  [AWS::IAM::Role]",

I can't find any way to set the capability unfortunately.
How do you set the capability?

A: The Capabilities and CapabilitiesReason outputs from validate-template are not errors. They are normal outputs listing resources requiring capabilities that will need to be specified (via --capabilities) when running create-stack or update-stack in the future.
You can confirm that a validation succeeded without errors by checking that the return code is 0 indicating the command completed successfully.
The documentation for the validate-template outputs is as follows:

Capabilities -> (list)
The capabilities found within the template. If your template contains IAM resources, you must specify the CAPABILITY_IAM or CAPABILITY_NAMED_IAM value for this parameter when you use the create-stack or update-stack actions with your template; otherwise, those actions return an InsufficientCapabilities error.
  For more information, see Acknowledging IAM Resources in AWS CloudFormation Templates.
CapabilitiesReason -> (string)
The list of resources that generated the values in the Capabilities response element.


text:
Q: Stream file log to cloudwatch I have an EC2-instance running docker using docker-compose.
I would like all logs written to a file by one of the applications to send that data async to CloudWatch. It would be ideal to have a separate container that is sharing the logs directory with the application container and runs something like tail -f and sends the output to CloudWatch.
I am no expert, but I imagine that Filebeat does something similar, but Don't know if I can configure it to send to CloudWatch.

A: So I ended up using this docker image
This is my service in my docker-compose.yml
  cloudwatch:
    image: iconara/awslogs:latest
    command: "--region eu-central-1 --config-file /etc/awslogs/app.conf"
    volumes:
      - ./environment/cloudwatch/conf/awscli.conf:/etc/awslogs/app.conf
      - ./environment/cloudwatch/state:/var/lib/awslogs/
      - ./logs:/app-logs/general/
      - ./project/storage/logs:/app-logs/laravel/
      - ~/.aws:/root/.aws

I am mounting the credentials so I can use this for development on Mac OSX which is probably not needed on an EC2 instance, depending on your setup.
I also mounted the state file so that the same logs wont be pushed twice if the container is restarted.
This is my ./environment/cloudwatch/conf/awscli.conf
[general]
state_file = /var/lib/awslogs/agent-state
use_gzip_http_content_encoding = true

[/app-logs/logs/laravel.log]
datetime_format = %Y-%m-%d %H:%M:%S
file = /app-logs/laravel/laravel.log
buffer_duration = 5000
#log_stream_name = {instance_id}
log_stream_name = development
initial_position = start_of_file
log_group_name = /app-logs/laravel/laravel.log
multi_line_start_pattern = {datetime_format}


text:
Q: XNA Erase/Remove a Texture2D i'm new to XNA 4.0 and i want to create a space ship shooter game. When i kill the enemy i want to draw a explode texture where it death and the explode texture will disappear for 2 seconds. I managed to draw a explode texture when enemy died by using boolean if enemy is die or not in Draw method but i don't know how to remove it after 2 seconds. Thank you for your help.
if (alive)
sp.Draw(enemyTexture, enemyPos, Color.White);

else
sp.Draw(explode, enemyPos, Color.White);

A: Do a similar check for two second interval between the start of the explosion and its end. You could just save the time of explosion and check if it is 2 seconds or more older than the current time, like so:
TimeSpan explosionTime;
if (itsTimeToExplode)
    explosionTime = gameTime.TotalGameTime;

Then you make a check to see if it is time to remove the explosion animation:
if (gameTime.TotalGameTime.TotalMilliseconds - explosionTime.TotalMilliseconds >= 2000) // 2000 milliseconds is 2 seconds
    RemoveExplosionAnimation();

You can put the explosionTime inside your enemy class and only delete the enemy after it's dead and the explosion animation has been played.

A: You need to count the time inside Update method using gameTime variable.
When your counter reaches 2s, just make alive = false;
But better idea is to make class for your explosion sprite with update and draw methods
and handle the counting and rendering from there.


text:
Q: Java problem with servlet and stacktrace thrown I have the following in which I have to write a servlet that takes an age, marital status, house income and number of kids, goes out to a DB, and then returns the updated averages to the user. However, I am encountering this stacktrace:
java.lang.NullPointerException
    at HouseSurvey$SurveyResults.access$200(HouseSurvey.java:86)
    at HouseSurvey.doPost(HouseSurvey.java:43)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    at org.apache.catalina.servlets.InvokerServlet.serveRequest(InvokerServlet.java:419)
    at org.apache.catalina.servlets.InvokerServlet.doPost(InvokerServlet.java:169)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:868)
    at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:663)
    at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
    at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
    at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
    at java.lang.Thread.run(Unknown Source)

What the heck does this all mean? I figure I am getting a NullPointerException, but I don't see where. Here is my prog.:
import java.text.DecimalFormat;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HouseSurvey extends HttpServlet
{
    private final static String SURVEY_FILE = "HouseSurvey.dat";
    SurveyResults results;
    Household h;
    DecimalFormat form = new DecimalFormat("#,###,#00.00");

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        PrintWriter out = response.getWriter();  //make a printwriter to print the page
        File survey = new File(SURVEY_FILE);
        if(!survey.exists())    //check to see if the file exists
            results = new SurveyResults();
        else
        {     //If the file exists, read it the latest survey tallies
            try
            {
                ObjectInputStream ips = new ObjectInputStream(new FileInputStream(survey));
                results = (SurveyResults)ips.readObject(); //read the file into 'results'
                ips.close();   //close the input stream
            }
            catch(ClassNotFoundException e) {e.printStackTrace();}
            catch(FileNotFoundException f)  {f.printStackTrace();}
            catch(IOException ioe)          {ioe.printStackTrace();}
        }
        int       ageValue = Integer.parseInt(request.getParameter("age")),
        childValue = Integer.parseInt(request.getParameter("children"));
        double incomeValue = Double.parseDouble(request.getParameter("income"));
        Boolean marriedValue = true;
        if (request.getParameter("status").equals("married"))
            marriedValue = true;
        else
           if(request.getParameter("status").equals("single"))
           marriedValue = false;
        Household h = new Household(ageValue,childValue,incomeValue,marriedValue);
        results.totalResults(h);
        //Write results to disk.
        try
        {
            ObjectOutputStream ops = new ObjectOutputStream(new FileOutputStream(survey));
            ops.writeObject(results); ops.flush(); ops.close();
        }
        catch(IOException ioe)          {ioe.printStackTrace();}
        response.setContentType("text/html");       //contnent type for the responding webpage
            out.println("\n"+
                "<title>Thanks!</title>"+
                ""+
                "
RRC BIT Department - Household Survey
"+
                "

"+
                "
Up to Date Survey Results
"+
                "
Average Age: "+form.format(results.getAvgAge())+"
"+
                "
Average Number of Children: "+form.format(results.getAvgKids())+"
"+
                "
Average Number of Married Respondents: "+form.format(results.getTotalMarried())+"
"+
                "
Average Number of Single Respondents: "+form.format(results.getTotalSingle())+"
"+
                "
Average Income: "+form.format(results.getAvgIncome())+"
");
    }
    private class Household
    {
        private int age, children;
        private double income;
        private boolean married=false;
        /**Method: Household
         * Constructor
         * @ param age - age of person surveyed:int
         * @ param children - number of children person surveyed has:int
         * @ param married - true or false, used to determine married or single:boolean
         * @ param income - the family income of the person surveyed:double
         */
        private Household(int age, int children, double income, boolean married)
        {
            this.age=age; this.children=children; this.income=income; this.married=married;
        }
        //Getters
        private int getAge()         {return age;}
        private int getChildren()    {return children;}
        private double getIncome()   {return income;}
        private boolean getMarried() {return married;}
    }
    private class SurveyResults implements Serializable
    {
        private double totalAge, totalChildren, totalMarried, totalSingle, totalIncome;
        /**Method: SurveyResults
         * Used for totals
         * @ param h - Household object created above:Household
         */
        private void totalResults(Household h)
        {
            totalAge += h.getAge(); totalChildren += h.getChildren(); totalIncome += h.getIncome();
            if(h.getMarried()) totalMarried += 1;
               else
                  totalSingle += 1;
        }
        private double getTotalHouseholds() {return totalSingle + totalMarried;}
        private double getAvgAge()          {return totalAge/getTotalHouseholds();}
        private double getAvgKids()         {return totalChildren/getTotalHouseholds();}
        private double getTotalMarried()    {return totalMarried;}
        private double getTotalSingle()     {return totalSingle;}
        private double getAvgIncome()       {return totalIncome/getTotalHouseholds();}
    }
}

Originally in my HTML output, I accidentally had the line
"Average Number of Married Respondents: "+form.format(results.getTotalMarried())+"
"

as
"Average Number of Married Respondents: "+form.format(results.getAvgKids())+"
"

and that worked fine.  Then I switched it to the former to get the totalMarried, and now it is giving me the exception.  Where is the issue?
Thanks in advance.

A: I am adding this as a separate answer because it is a completely different train of thought. If it would be better to edit let me know, and I will delete the duplicate.
It looks like you will be having an IOException thrown when reading the results object. The reason is, the class you are attempting to serialize is not serializable. Since SurveyResults is an inner class, to be serialized it will have to serialize the containing class as well (in this case, your Servlet). I would recommend changing your classes to static nested classes, or perhaps default scoped top-level classes. (With changes to method access levels as needed.)
You also may need to delete your survey results data file and start over, as well. In my testing, it had references to the non-serializable classes and I was not able to get the code to run until it was deleted.

A: HouseSurvey$SurveyResults.access$200() is a synthetic accessor method that the compiler generates and inserts into the inner class to allow the enclosing class (here, HouseSurvey) to call a private method of the inner class.  I admit I'm not yet seeing where the NullPointerException is coming from, though.
Also, have you decided whether or not Household and SurveyResults should be inner classes (as they currently are) rather than static nested classes and does making them static nested classes change what happens?  This SO question on inner vs. static nested classes might help you make that decision.
Update:
I tried making this into a standalone class (only showing changes I made):
public class HouseSurvey
{
    public static void main(String[] args) {
        HouseSurvey h = new HouseSurvey();
        h.doPost(args);
    }

 public void doPost(String[] data) throws Exception {
    PrintWriter out = new PrintWriter(System.out);
    File survey = new File(SURVEY_FILE);
    if (!survey.exists()) {
        results = new SurveyResults();
    } else {
        ObjectInputStream ips = new ObjectInputStream(new FileInputStream(survey));
        results = (SurveyResults) ips.readObject();
        ips.close();
    }

    int ageValue = Integer.parseInt(data[0]);
    int childValue = Integer.parseInt(data[1]);
    double incomeValue = Double.parseDouble(data[2]);
    boolean marriedValue = Boolean.parseBoolean(data[3]);
    Household h = new Household(ageValue, childValue, incomeValue, marriedValue);
    results.totalResults(h);

    ObjectOutputStream ops = new ObjectOutputStream(new FileOutputStream(survey));
    ops.writeObject(results);
    ops.flush();
    ops.close();

    out.println("Average Age: " + form.format(results.getAvgAge()) +
            "\nAverage # of Children: " + form.format(results.getAvgKids()) +
            "\nAverage # of Married Respondents: " + form.format(results.getTotalMarried()) +
            "\nAverage # of Single Respondents: " + form.format(results.getTotalSingle()) +
            "\nAverage Income: " + form.format(results.getAvgIncome()));
    out.flush();
    out.close();
}

[snip]

}

When I ran this I got the following exception trace:
Exception in thread "main" java.io.NotSerializableException: HouseSurvey
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1164)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1518)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1483)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1400)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1158)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:330)
    at HouseSurvey.doPost(HouseSurvey.java:36)
    at HouseSurvey.main(HouseSurvey.java:9)

which while it isn't the NullPointerException you got, it does demonstrate that there's a serialization issue that Sean alludes to is his answers.  Once I change Household and SurveyResults to be static nested classes instead of inner classes, the exception went away and the program appears to work correctly.

A: I have not personally used the ObjectInputStream API, but I am only seeing a couple possibilities for the NullPointerException you are listing. Is it possible for the following line to return null:
results = (SurveyResults)ips.readObject();

I am not sure if readObject can ever return null, or if it would just throw an exception if the object could not be read.
Another possibility is that an exception is being thrown before the results object is loaded. You have 3 empty catch blocks that just print exceptions -- are they being executed? (In other words, do you see other exceptions being thrown?)
Other than that, it would be possible to get a null pointer unboxing your a Boolean into a boolean (as you do with marriedValue), although in the code listed I don't see that being possible.


text:
Q: MiKTeX in R - how can I align the resulting equations I am using MiKTeX in R. Using this code,
$$
1 - p(X) = 1 - \frac{\mathrm{e}^{\beta_0 + \beta_1 X}}{1 + \mathrm{e}^{\beta_0 + \beta_1 X}} \\

&= \frac{1 + \mathrm{e}^{\beta_0 + \beta_1 X}}{1 + \mathrm{e}^{\beta_0 + \beta_1 X}} - \frac{\mathrm{e}^{\beta_0 + \beta_1 X}}{1 + \mathrm{e}^{\beta_0 + \beta_1 X}} \\

&= \frac{1 + \mathrm{e}^{\beta_0 + \beta_1 X} - \mathrm{e}^{\beta_0 + \beta_1 X}}{1 + \mathrm{e}^{\beta_0 + \beta_1 X}} \\

&= \frac{1}{1 + \mathrm{e}^{\beta_0 + \beta_1 X}}
$$

Result:

How can I align the resulting equations to the '=' lines up for each line?

A: You need to use a
\begin{align*}
  ...
\end{align*}

construction, placing an & to the left of every =:
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
\begin{align*}
1 - p(X) &= 1 - \frac{\mathrm{e}^{\beta_0 + \beta_1 X}}{1 + \mathrm{e}^{\beta_0 + \beta_1 X}} \\
&= \frac{1 + \mathrm{e}^{\beta_0 + \beta_1 X}}{1 + \mathrm{e}^{\beta_0 + \beta_1 X}} - \frac{\mathrm{e}^{\beta_0 + \beta_1 X}}{1 + \mathrm{e}^{\beta_0 + \beta_1 X}} \\
&= \frac{1 + \mathrm{e}^{\beta_0 + \beta_1 X} - \mathrm{e}^{\beta_0 + \beta_1 X}}{1 + \mathrm{e}^{\beta_0 + \beta_1 X}} \\
&= \frac{1}{1 + \mathrm{e}^{\beta_0 + \beta_1 X}}
\end{align*}

Also, you can't have any blank lines inside align* in general.


text:
Q: Google Page Speed - what do these messages mean? I ran the Google Page Speed Firefox extension on a few pages, and under "efficient CSS selectors" it listed various things that are inefficient in my CSS.
But some of the messages seem a bit cryptic - what do these (in bold) mean:

div#menu h3.soon small
Tag key with 2 descendant selectors and ID overly qualified with tag and Class overly qualified with tag
table.data tr:nth-child(2n) td
Tag key with 2 descendant selectors and Class overly qualified with tag
table.data tr.disabled td
Tag key with 2 descendant selectors and Class overly qualified with tag and Class overly qualified with tag

I'm assuming they think descendant selectors are bad but there are lots of "overly qualified" as well. I probably won't go to too much effort fixing all these up (there are many) but it would be nice to know what Google actually means here!

A: Stephen said it well.
The reason they're flagging your selectors is that CSS rules are matched right to left.
Prepending an ID with an element (as in div#content) is unnecessary because the browser has already matched the selector by the time it reaches "div".  But the browser is still forced to evaluate it.
Descendant selectors are expensive because the browser has to check all instances of the dom element referenced in the right-most simple selector against all possible ancestors. Multiple descendants compound the performance penalty.
That said, the performance gain achieved from optimizing selectors (in most cases) is negligible.

A: First off, I have never used Page Speed, but the message is not that cryptic if you take a second to read it.

div#menu h3.soon small
Tag key with 2 descendant selectors and ID overly qualified with
  tag and Class overly qualified with
  tag

Tag key with 2  descendant selectors: How many small tags do you have that are not contained in another tag with class soon? None? The CSS nesting would be totally unnecessary in this case.
ID overly qualified with tag: #menu does not need to be prepended with div.
You most likely don't have any other tags in your markup with id menu (you shouldn't, its an ID!), so prepending menu with div in redundant.
Class overly qualified with tag: .soon does not need to be prepended with h3.
You most likely don't have any other tag in your markup with class soon other than h3 tags, so prepending .soon with h3 is unnecessary.
The other messages follow similarly.
-Stephen

A: It is saying there is no reason to use the tag since you give a class so you are already limiting it and it have to do extra searching.
For example:
div#menu h3.soon .small

Here there is no reason to start with div  since you will only look at class small in class soon in an h3 tag below html element with id menu.
They are suggesting something like this
#menu .soon .small {...}

or even
#menu {...}

.soon {...}

.small {...}


text:
Q: Why is my form not submitting? I am using zurb's foundation as my css framework and unfortunately it won't let me submit the form. Even if I fill out everything and click the submit button nothing happens. Here is my current code.

        <form action="record-time-out.php" method="POST" data-abide>

                    PURPOSE

                    <input type="text" name="txt_purpose" required>
                    Input your purpose.

                    DESTINATION

                    <input type="text" name="txt_destination" required>
                    Input your destination.

                    Expected TIME-IN

                    <input type="text" name="txt_time" required>

                 <input type="submit" class="button" value="OUT"/>

        </form>

A: Remember the form code is always executed by the browser, so it won't know where is the "record-time-out.php"
My suggestion is just add the url of your site and it will work, test it, would be something like this:

    <form action="http://example.com/record/record-time-out.php" method="POST" data-abide>

                PURPOSE

                <input type="text" name="txt_purpose" required>
                Input your purpose.

                DESTINATION

                <input type="text" name="txt_destination" required>
                Input your destination.

                Expected TIME-IN

                <input type="text" name="txt_time" required>

             <input type="submit" class="button" value="OUT"/>

    </form>

A: Hope this may help you.
Add
Input Expected TIME-IN.

after Expected TIME-IN text box.

A: Adding novalidate might help.
<form action="record-time-out.php" method="POST" data-abide novalidate>

In your form, You might have hidden input having required attribute.


text:
Q: run spring boot mongodb api application in docker. Exception opening socket error I was trying to run a spring boot mongodb api application in docker but encounter the Exception opening socket error.
Exception in monitor thread while connecting to server localhost:27017
com.mongodb.MongoSocketOpenException: Exception opening socket

After some research I added @EnableAutoConfiguration(exclude={MongoAutoConfiguration.class}) in my main class
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;

@SpringBootApplication
@EnableAutoConfiguration(exclude={MongoAutoConfiguration.class})

public class Main {

    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }
}

But I got this error while trying to run the application
***************************
APPLICATION FAILED TO START
***************************

Description:

Field studentRepository in com.example.demo.controllers.StudentController required a bean named 'mongoTemplate' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)

Action:

Consider defining a bean named 'mongoTemplate' in your configuration.

The application could run very well on localhost before this. Any idea what should I do?
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>MongoProject</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>MongoProject</name>
    <description>mongodb with Spring Boot</description>
    <packaging>jar</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

    </dependencies>

    <build>

        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.3.RELEASE</version>
                <configuration>

                    <mainClass>com.example.demo.Main</mainClass>
                    <layout>ZIP</layout>
                </configuration>
                <executions>
                    <execution>
                        <goals>

                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <!-- Build an executable JAR -->
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.1.0</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <mainClass>com.example.demo.Main</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>

        </plugins>

    </build>

</project>

application.properties
spring.data.mongodb.database=testing
spring.data.mongodb.port=27017
spring.data.mongodb.host=localhost


text:
Q: Lesbian fanfiction: Greek woman whose girlfriend is a Greek goddess, or an alien dressed as one I read this story in 2011 on Fanfiction.net. It featured a Greek woman and her girlfriend. The girlfriend was either an alien dressed like a Greek goddess or an actual Greek goddess.  It also featured statues and the sort you see in the Minecraft Zeus world.
That's all I remember. I hope it doesn't get put on hold as "too broad."


text:
Q: How to get the value of input with Selenium IDE How to retrieve the field value "value" from input via the Selenium IDE (this value is variable so I want to recover its value for reuse)
My input field:
    <input class="myClass" type="text" value="15" name="myName">

When I tried the following code:

    store
    xpath("//input[@name='myName']").getAttribute("value");
    x

    echo
    ${x}

I have:
[info] echo: xpath("//input[@name='myName']").getAttribute("value");

instead of:
15

thanks for help

A: You are confusing javascript with the store method.  getAttribute() is a javascript method.
Also, to store an attribute, you want the storeAttribute method combined with CSS:

  storeAttribute
  css=input[name='myName']@value
  x

If you are trying to execute javascript, then use storeEval.

A: I resolve my problem thanks @sircapsalot
solution of my problem below:
storeEval | window.document.getElementsByName('myName')[0].value; | x

A: storeValue works for input elements. Depending on what you need, that may be preferable to using storeEval.


text:
Q: Joomla: Can't make a plugin using onUserAfterSave work Tried this half a dozen different ways and it's still not working. Joomla 1.7.3 on a local machine. The plugin does nothing, but it's not actually breaking anything - yet. As far as I can tell, the naming conventions are okay.
What I'm trying to do is insert a new row in a database table with the userid of a new user. The table has already been created and I checked the SQL query to make sure it worked.
<?php
// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

// Import library dependencies
jimport('joomla.plugin.plugin');

class plgUserCNPluginUpdate extends JPlugin
{
    function onUserAfterSave ($user, $isnew, $success, $msg)
    {
        if (!$success)
        {
            return false;
        }
        if ($isnew)
        {
            $db = JFactory::getDbo();
            $db->setQuery(
                'INSERT INTO `#__cnuser_cginfo`(`RecordID`,`UserID`) VALUES (NULL,'.(int) $user['id'].')'
            );
            $db->Query();
            return true;
        }
    }
}

Am I missing something obvious here? I've been looking around and any solution I try just doesn't work. It's in the right place and I can see it on the plugin manager screen. Hope someone can give me some advice on this.

A: Assuming this on Joomla 1.6/7/2.5... and if you have it in the right place i.e. /plugins/user/cnpluginupdate/ wrap your db code in some error checking like this:
try
{
    $db = JFactory::getDbo();
    $db->setQuery(
        'INSERT INTO `#__cnuser_cginfo`(`RecordID`,`UserID`)
         VALUES (NULL,'.(int) $user['id'].')'
    );

    if (!$db->query()) {
        throw new Exception($db->getErrorMsg());
    }

    catch (JException $e)
    {
        $this->_subject->setError($e->getMessage());
        return false;
    }
}

*

*Currently you just return true no matter what happened so no error will be reported. Use a try as shown above to catch a possible error...

*Are you sure it's making it past the if (!$success) - normally you would check all the inputs prior to doing any work and you would only return a false if your code encountered an error.
eg.
function onUserAfterSave($data, $isNew, $result, $error)
{
    $userId = JArrayHelper::getValue($data, 'id', 0, 'int');

    if ($userId && $result && isset($data['profile']) && (count($data['profile'])))
    {
      // then 'try' your code here
    }


text:
Q: Compute "inwards derivative" of a 2d grid I'll expose the problem in 2d, but need to eventually solve it in 3 dimensions.
Let's say I have the following grids
import numpy as np
ge = np.arange(36).reshape((6, 6))
gu = ge + 10
f = ge - 2*gu**2

Now f looks like this:
array([[ -200,  -241,  -286,  -335,  -388,  -445],
       [ -506,  -571,  -640,  -713,  -790,  -871],
       [ -956, -1045, -1138, -1235, -1336, -1441],
       [-1550, -1663, -1780, -1901, -2026, -2155],
       [-2288, -2425, -2566, -2711, -2860, -3013],
       [-3170, -3331, -3496, -3665, -3838, -4015]])

I can get the outer grid points as via this answer as:
def edge_mask(x):
    mask = np.ones(x.shape, dtype=bool)
    mask[x.ndim * (slice(1, -1),)] = False
    return mask
edge_mask(f)
Out[56]:
array([[ True,  True,  True,  True,  True,  True],
       [ True, False, False, False, False,  True],
       [ True, False, False, False, False,  True],
       [ True, False, False, False, False,  True],
       [ True, False, False, False, False,  True],
       [ True,  True,  True,  True,  True,  True]], dtype=bool)

Now, for all of these boundary points, I want to compute the "inward derivatives". For now, we can assume that the space between all grid points on e and u is one. Then, the grid inward derivative for f[0, 1] can be computed as
(-571-(-241))/(1) = -330

For the corner point [0, 0], the inward derivative is w.r.t. the diagonal element [1,1], and we can compute it here as
(-571 - (-200)/1 =  371

For [4, 5], we have (-2860-(-3838))/1 = 987.
The main problem I'm facing is to compute the derivative in different directions, always inwards. Otherwise, this would simply be a case of np.diff(). What's an efficient way to do this that would also hold for at least 3 dimensions?

A: Using Till Hoffmann's great comment, I can at least  get almost there.
gradient get's the sign wrong when working with a binary matrix, but with integers we get
mask = edge_mask(f)
a, b = np.gradient(mask.astype(int))

which gives us the (inverse) sign (whether the derivative needs to be computed inwards or outwards):
a
Out[90]:
array([[ 0. , -1. , -1. , -1. , -1. ,  0. ],
       [ 0. , -0.5, -0.5, -0.5, -0.5,  0. ],
       [ 0. ,  0. ,  0. ,  0. ,  0. ,  0. ],
       [ 0. ,  0. ,  0. ,  0. ,  0. ,  0. ],
       [ 0. ,  0.5,  0.5,  0.5,  0.5,  0. ],
       [ 0. ,  1. ,  1. ,  1. ,  1. ,  0. ]])
b
Out[91]:
array([[ 0. ,  0. ,  0. ,  0. ,  0. ,  0. ],
       [-1. , -0.5,  0. ,  0. ,  0.5,  1. ],
       [-1. , -0.5,  0. ,  0. ,  0.5,  1. ],
       [-1. , -0.5,  0. ,  0. ,  0.5,  1. ],
       [-1. , -0.5,  0. ,  0. ,  0.5,  1. ],
       [ 0. ,  0. ,  0. ,  0. ,  0. ,  0. ]])

So then, we can do
-a * mask * np.gradient(f)[0]
Out[88]:
array([[   0., -330., -354., -378., -402.,    0.],
       [   0.,   -0.,   -0.,   -0.,   -0.,    0.],
       [   0.,    0.,    0.,    0.,    0.,    0.],
       [   0.,    0.,    0.,    0.,    0.,    0.],
       [   0.,    0.,    0.,    0.,    0.,    0.],
       [   0.,  906.,  930.,  954.,  978.,    0.]])
-b * mask * np.gradient(f)[1]
Out[89]:
array([[   0.,    0.,    0.,    0.,    0.,    0.],
       [ -65.,   -0.,    0.,    0.,    0.,   81.],
       [ -89.,   -0.,    0.,    0.,    0.,  105.],
       [-113.,   -0.,    0.,    0.,    0.,  129.],
       [-137.,   -0.,    0.,    0.,    0.,  153.],
       [   0.,    0.,    0.,    0.,    0.,    0.]])

All that is missing now, are the corners -- and I'm kind of stuck here.


text:
Q: How to get cart items at creating new order in the backend? I've tried to load all items from the backend order.
Example:
$quote->getAllItems();

It works fine in the frontend, but not in the backend.
I've googled so much, as i can see there is no solution for this problem?
I need the items, because otherwise i can't get successful response from an external api.
Also it should run from magento 1.4+ CE.

A: Mage::getSingleton('adminhtml/session_quote')->getQuote()->getAllItems();