Wednesday, 28 June 2017

c++ - Defining a template in .h file, vs declaring in .h file and defining in .cpp file

I have code that looks something like this (compiling using the Arduino IDE).



main sketch file:



#include "myHeader.h"


//setup stuff here, including setting up Serial & SerialBT

loop(){
CheckForMessages(&Serial); //Check USB first
CheckForMessages(&SerialBT); //Then check Bluetooth
}


myHeader.h:




#include "Arduino.h"
//other includes

template void CheckForMessages(T *port);

//declarations of other stuff


myHeader.cpp:




#include "myHeader.h"

template void CheckForMessages(T *port){
if(port->available() !=0){
//rest of function...
}

//definitions of other stuff



When I compile, I get the "undefined reference" errors for both calls to CheckForMessages in the main sketch file. This goes away if I move the definition of the template into the .h file.



I have no issues splitting the declaration and definition of functions in this way as far as I can tell, can anyone explain to me why it isn't working for my templates?

pointers - c++ solution fails on leetcode with misaligned address error but runs in visual studio



i'm new to C++ so i'm trying some leetcode problems. i'm currently attempting the min stack problem. i think i've solved it correctly, except i get the following runtime error from leetcode:



Line 24: Char 37: runtime error: member access within misaligned address 0xbebebebebebebebe for type 'struct ListNode', which requires 8 byte alignment (solution.cpp)



here is my visual studio code, with tests - the error originates from the following line in push():



                topStackNode->stackPrev = newNode;


anyone know what would cause this to happen? i read a bit and some people with similar errors say its because ListNode is not initialized to NULL, but i clearly initialize all ListNodes to NULL in my struct. thanks!



#include 
#include

using namespace std;
// design a stack that supports push, pop, top, and retrieving the minimum element in constant time


class MinStack {

struct ListNode {
ListNode* stackNext;
ListNode* stackPrev;
ListNode* minNext;

ListNode* minPrev;
int val;
ListNode(int v) : val(v), stackNext(NULL), stackPrev(NULL), minNext(NULL), minPrev(NULL)
{
}
};

public:
/** initialize your data structure here. */
MinStack() {}


void push(int x) {

ListNode* newNode = new ListNode(x);

if (topStackNode == NULL)
topStackNode = newNode;
else {
topStackNode->stackPrev = newNode;
newNode->stackNext = topStackNode;

topStackNode = newNode;
}

insertNodeMinStack(newNode);
}

void pop() {
removeFromMinStack(topStackNode);
popFromStack();
}


void popFromStack() {
topStackNode = topStackNode->stackNext;
}

void removeFromMinStack(ListNode* node) { // delete the currently popped node from the min stack
if (node != NULL) {
if (node == topMinNode) {
topMinNode = node->minNext;
min = topMinNode->val;

return;
}
if (node->minPrev != NULL)
node->minPrev->minNext = node->minNext;
if (node->minNext != NULL)
node->minNext->minPrev = node->minPrev;
}

}


int top() {
if (topStackNode != NULL)
return topStackNode->val;
else
return NULL;
}

int getMin() {
return min;
}


void insertNodeMinStack(ListNode* node) {
if (topMinNode == NULL) { // inserting node on an empty list
topMinNode = node;
}
else if (node->val < topMinNode->val) { // node has smallest value
topMinNode->minPrev = node;
node->minNext = topMinNode;
topMinNode = node; // set new top min node and update min
min = node->val;

}
else {
ListNode* currentNode = topMinNode;
while (currentNode->minNext != NULL && currentNode->val < node->val) {
currentNode = currentNode->minNext;
}
if (currentNode->minNext == NULL) { // reached end of list, 'node' has largest value in list
currentNode->minNext = node;
node->minPrev = currentNode;
//min remains unchanged

}
else { // we're somewhere in the middle of the list, ie there are nodes surronding 'node'
node->minNext = currentNode->minNext;
node->minPrev = currentNode;
currentNode->minNext = node;
node->minNext->minPrev = node;
}
}
}


private:
int min;
ListNode* topStackNode;
ListNode* topMinNode;
};

int main() {//1,2,6,3,4,5,6
MinStack* ms = new MinStack();

ms->push(5);

ms->push(3);
ms->pop();
ms->push(10);
ms->push(-3);
ms->pop();
ms->pop();
ms->push(-11);

cout << "minstack min = " << ms->getMin() << endl;


}


EDIT - new solution below using shared pointers:



class MinStack {
struct ListNode {
shared_ptr prev;
shared_ptr next;
shared_ptr minNext;

shared_ptr minPrev;
int value;
ListNode(int val) : prev(nullptr), next(nullptr), minNext(nullptr), minPrev(nullptr), value(val) {}
};

public:

shared_ptr topn;
shared_ptr minTop;
shared_ptr node;


MinStack() : topn(nullptr), minTop(nullptr), node(nullptr){}

void push(int value) {

// cout << "pushing value " << value << endl;

if (topn == nullptr) {
topn = make_shared(value);
insertToMinList();

}
else {
node.reset();
node = make_shared(value);
node->next = topn;
topn = node;
insertToMinList();
}
}


void removeFromMinList() {
//removing the node topn from min list
if (topn->minNext != nullptr && topn->minPrev != nullptr) {
// cout << "removing, neither null, " << topn->value << endl;
topn->minNext->minPrev = topn->minPrev;
topn->minPrev->minNext = topn->minNext;
}
else if (topn->minNext != nullptr) {
// cout << "removing, next not null, " << topn->value << endl;
topn->minNext->minPrev = topn->minPrev;

}
else if (topn->minPrev != nullptr) {
// cout << " removing, prev not null, " << topn->value << endl;
topn->minPrev->minNext = topn->minNext;
}
else {
// cout << "no condition met in removign " << endl;
}
if (topn == minTop) {
minTop = topn->minNext;

}

}

void insertToMinList() {
if (minTop == nullptr) {
minTop = topn;
//cout << "min list null, initializing with " << topn->value << endl;
}
else if (topn->value <= minTop->value) {

//cout << "new value is smallest " << topn->value << endl;
minTop->minPrev = topn;
topn->minNext = minTop;
minTop = topn;
}
else {
//cout << "searching list to place value " << topn->value << endl;
shared_ptr temp = make_shared(minTop->value);
temp->minNext = minTop->minNext;


while (temp != nullptr && temp->value < topn->value) { //go down the list
topn->minNext = temp->minNext;
topn->minPrev = temp;
temp = temp->minNext;
}
//while loop completes. now, temp is either nullptr or between two nodes
if (temp == nullptr) {// new value is largest
//cout << "reached end of list, assigning value " << topn->value << endl;
topn->minPrev->minNext = topn;
topn->minNext = nullptr;

}
else { // between two nodes, reassign prev and next
//cout << "in middle of list, assigning vale " << topn->value << endl;
topn->minNext->minPrev = topn;
topn->minPrev->minNext = topn;
}
}
}

void pop() {


//cout << "popping value " << topn->value << endl;
removeFromMinList();
topn = topn->next;


}

int top(){
return topn->value;

}

int getMin() {
return minTop->value;
}
};

Answer



You are not initializing all your class members.




MinStack has members:



int min;
ListNode* topStackNode;
ListNode* topMinNode;


Your constructor for MinStack does not have any member initializer list and doesn't set any of the members:



MinStack() {}



You are using this constructor to construct an object here:



MinStack* ms = new MinStack();


Since the members of MinStack are not declared with any any default initializers specified and the constructor does not provide any initializers for them, they will be default-initialized. Since they are non-class types default-initialization means that no initialization will be performed. The members will keep their indeterminate values.



Then in the next line:




ms->push(5); 


you call push which executes:



if (topStackNode == NULL)


This has undefined behavior, because topStackNode has indeterminate value.







Initialize all your members in the constructor's initializer list or with default member initializers in the class definition:



int min = 0;
ListNode* topStackNode = nullptr;
ListNode* topMinNode = nullptr;



or equivalently:



int min{};
ListNode* topStackNode{};
ListNode* topMinNode{};





Also enable warnings on your compiler.




It will warn you that the initalizer list of ListNode's constructor is not in the same order as the member declarations. It is important that they are in the same order, because the order of initialization is the order of the declarations, not the order of the member initializers. In order to avoid accidentally using an uninitialized member, you should always keep the initializer list order consistent with the member declaration order.



It will also tell you that you are misusing NULL. You are using it as return value for top() which returns int. It is not guaranteed that NULL can be cast to an integer. NULL should only be used to represent a pointer. And since C++11 NULL should not be used at all. Instead use nullptr, which would have given you a proper error that returning it from int top() doesn't make sense.






Also avoid using new. It is not exception-safe, will cause you memory leaks, requires special care to be taken that copy operations of classes are implemented correctly (look up "rule of 0/3/5") and will cause you many headaches.



The new use in main is completely pointless. You can just declare the object directly as variable:




int main() {//1,2,6,3,4,5,6
MinStack ms;

ms.push(5);
ms.push(3);
ms.pop();
ms.push(10);
ms.push(-3);
ms.pop();

ms.pop();
ms.push(-11);

cout << "minstack min = " << ms.getMin() << endl;

}


The new use and use of raw owning pointers in the class can probably also be replaced with std::unique_ptr and std::make_unique. Your class is currently leaking its memory allocations and will likely cause undefined behavior if an instance of it is ever copied (explicitly or implicitly). That would not be a concern when using std::unique_ptr.


javascript - Variables are not being set inside the .then() part of a Promise

return the value at function passed to .then()



var storedUserID = ROBLOX.getIdFromUsername(accountArg)
.then(function(userID) {
return userID;
});



you can then use or change the Promise value when necessary



storedUserID = storedUserID.then(id) {
return /* change value of Promise `storedUserID` here */
});


access and pass the value to message.reply() within .then()



storedUserID.then(function(id) {

message.reply(id);
});


or



var storedUserID = ROBLOX.getIdFromUsername(accountArg);
// later in code
storedUserID.then(function(id) {
message.reply(id);

});

mysql - Having An Issue Backing Up MY Database From Php

the issue that I'm having is with the fopen(), fwrite(), and fclose() function. This is the error I am receiving:



Warning: fopen(/db-backup-salisbury_school-20121128-021138.sql) [function.fopen]: failed to open stream: Permission denied in C:\inetpub\wwwroot\omarejaz\sbyschool\q5.php on line 177



Warning: fwrite() expects parameter 1 to be resource, boolean given in C:\inetpub\wwwroot\omarejaz\sbyschool\q5.php on line 178



Warning: fclose() expects parameter 1 to be resource, boolean given in C:\inetpub\wwwroot\omarejaz\sbyschool\q5.php on line 179




The code for this portion of php can be found below any help would be greatly appreciated!



 * Save SQL to file
* @param string $sql
*/
protected function saveFile(&$sql, $outputDir = '.')
{
if (!$sql) return false;

try

{
$handle = fopen($outputDir.'/db-backup-'.$this->dbName.'-'.date("Ymd-His", time()).'.sql','w+');
fwrite($handle, $sql);
fclose($handle);
}
catch (Exception $e)
{
var_dump($e->getMessage());
return false;
}


return true;
}


}
?>

python max function using 'key' and lambda expression



I come from OOP background and trying to learn python.
I am using the max function which uses a lambda expression to return the instance of type Player having maximum totalScore among the list players.



def winner():
w = max(players, key=lambda p: p.totalScore)



The function correctly returns instance of type Player having maximum totalScore.
I am confused about the following three things:




  1. How does the max function work? What are the arguments it is taking? I looked at the documentation but failed to understand.

  2. What is use of the keyword key in max function? I know it is also used in context of sort function

  3. Meaning of the lambda expression? How to read them? How do they work?




These are all very noobish conceptual questions but will help me understand the language. It would help if you could give examples to explain.
Thanks


Answer



lambda is an anonymous function, it is equivalent to:



def func(p):
return p.totalScore


Now max becomes:




max(players, key=func)


But as def statements are compound statements they can't be used where an expression is required, that's why sometimes lambda's are used.



Note that lambda is equivalent to what you'd put in a return statement of a def. Thus, you can't use statements inside a lambda, only expressions are allowed.







What does max do?




max(a, b, c, ...[, key=func]) -> value



With a single iterable argument, return its largest item. With two or
more arguments, return the largest argument.




So, it simply returns the object that is the largest.







How does key work?



By default in Python 2 key compares items based on a set of rules based on the type of the objects (for example a string is always greater than an integer).



To modify the object before comparison, or to compare based on a particular attribute/index, you've to use the key argument.



Example 1:




A simple example, suppose you have a list of numbers in string form, but you want to compare those items by their integer value.



>>> lis = ['1', '100', '111', '2']


Here max compares the items using their original values (strings are compared lexicographically so you'd get '2' as output) :



>>> max(lis)
'2'



To compare the items by their integer value use key with a simple lambda:



>>> max(lis, key=lambda x:int(x))  # compare `int` version of each item
'111'


Example 2: Applying max to a list of tuples.




>>> lis = [(1,'a'), (3,'c'), (4,'e'), (-1,'z')]


By default max will compare the items by the first index. If the first index is the same then it'll compare the second index. As in my example, all items have a unique first index, so you'd get this as the answer:



>>> max(lis)
(4, 'e')


But, what if you wanted to compare each item by the value at index 1? Simple: use lambda:




>>> max(lis, key = lambda x: x[1])
(-1, 'z')





Comparing items in an iterable that contains objects of different type:



List with mixed items:




lis = ['1','100','111','2', 2, 2.57]


In Python 2 it is possible to compare items of two different types:



>>> max(lis)  # works in Python 2
'2'
>>> max(lis, key=lambda x: int(x)) # compare integer version of each item
'111'



But in Python 3 you can't do that any more:



>>> lis = ['1', '100', '111', '2', 2, 2.57]
>>> max(lis)
Traceback (most recent call last):
File "", line 1, in
max(lis)
TypeError: unorderable types: int() > str()



But this works, as we are comparing integer version of each object:



>>> max(lis, key=lambda x: int(x))  # or simply `max(lis, key=int)`
'111'

url - How can I get query string values in JavaScript?




Is there a plugin-less way of retrieving query string values via jQuery (or without)?




If so, how? If not, is there a plugin which can do so?


Answer



Update: Sep-2018



You can use URLSearchParams which is simple and has decent (but not complete) browser support.



const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('myParam');



Original



You don't need jQuery for that purpose. You can use just some pure JavaScript:



function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;

if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}


Usage:



// query string: ?foo=lorem&bar=&baz
var foo = getParameterByName('foo'); // "lorem"
var bar = getParameterByName('bar'); // "" (present with empty value)

var baz = getParameterByName('baz'); // "" (present with no value)
var qux = getParameterByName('qux'); // null (absent)



Note: If a parameter is present several times (?foo=lorem&foo=ipsum), you will get the first value (lorem). There is no standard about this and usages vary, see for example this question: Authoritative position of duplicate HTTP GET query keys.
NOTE: The function is case-sensitive. If you prefer case-insensitive parameter name, add 'i' modifier to RegExp






This is an update based on the new URLSearchParams specs to achieve the same result more succinctly. See answer titled "URLSearchParams" below.


Tuesday, 27 June 2017

film location - Why was Gotham City moved to New York City in The Dark Knight Rises? - Movies & TV



The Dark Knight was shot in Chicago.



enter image description here




And so was Batman Begins.



But The Dark Knight Rises is clearly shot in New York City.



Why was Gotham moved to a new city for the last part of the trilogy?


Answer



From interviews with director Christopher Nolan, it would appear that the goal was to create a non-specific setting (the film was actually shot in Pittsburgh and LA as well as New York and New Jersey), that felt both "operatic" and real.



From an interview with James Rocchi at MSN Entertainment:





MSN Movies: You knew you were doing a third film. Is the pressure to do things bigger, better -- is that from the studio? Is it from the
audience? Or is it that all from you? Are you the person saying,
"Let's do more with this"?



Christopher Nolan: Well, I was trying to push filmmaking from the point of view of the audience. I'm trying to make a film that I would
want to go see on a Friday night and lay down ten dollars or what have
you and be thrilled and moved by or whatever. And that's what was the
impulse, and so when you know you're dealing with characters the

audience have a relationship with, you're asking the audience to come
back to Gotham City. So you feel a huge creative responsibility to
give them a reason to come back to Gotham City.




From an interview with Emanuel Levy:




For the first time, three separate cities provided locations and
backdrops for Gotham City, with scenes filmed in Pittsburgh, Los

Angeles, and the city sometimes nicknamed Gotham, New York.



Nolan offers, “When you look back on the films, you can see the world
we’re living in reflected, but we don’t want to be specific about it.
We just come at the stories from the point of view of what concerns
us. What gives us fear? What gives us hope? What would require a hero
of Batman’s stature to rise up in our world?”




And from an interview with Alex Tucker at TV-Film-News:





**‘The Dark Knight Rises’ magnifies and resolves the main themes of the
trilogy, one of which is mythmaking, and the discussion of the Batman
Gotham needs.



Christopher Nolan:** One of the things I’ve enjoyed about working with
these characters is that they have the potential to be topical. And
the reason for that is they’re not real. It’s not real life. You’re
dealing with a heightened reality. You’re not dealing with Chicago or

New York; you’re dealing with Gotham City. And that gives you a very
interesting world to be able to play with in a very heightened way, in
a very operatic way.




And some practical reasoning from the Chicago Tribune:




Chicago-less Gotham




Chicago, don't take this personally, but: "The Dark Knight Rises," the
first of Nolan's Batman movies not to be shot here, was wise not to
shoot here this time. For variety's sake, sure. But also, a better
reason: A quick shot of the Chicago skyline screams money and
prosperity. A quick shot of Pittsburgh, where a lot of the film was
shot, reveals working-class areas within yearning range of gleaming
skyscrapers. You'd have to find a pretty wide lens before you could
hold the poor of Chicago and the rich of Chicago within the same
frame. True, in "Rises" the Manhattan skyline is liberally mixed in;
all the better to play up the 1-percenters. (Still, two nods to

Chicago do sneak in, sorta: Batman swings by a historic neighborhood
named "Old Town," and those Gotham license plates are hilariously
reminiscent of Illinois license plates.)



casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...