text:
Q: What is special about Knockout's automatic view update? I am learning Knockout.js, and I have a fundamental question, which may sound silly but it's really bugging me for quite a while.
According to official website, one of the main feature of Knockout.js is:
Elegant dependency tracking - automatically updates the right parts of your UI whenever your data model changes.
I understand how that works. (Correct me below if I am wrong in any part.)
Basically, if I have following View:

and following ViewModel:
function FlightVM () {
    this.name = ko.observable("Boieng 120");
    this.status = ko.observable("In Air");
}

ko.applyBindings(new FlightVM());

If I change my data somewhere, it will automatically  update the corresponding html. This I understand well.
My question is, what is different in here than just setting my data in the View as follows:
var name = "Boieng 120";
$("h1").html(name);

Here also, if I change the name, and refresh the page, it will update the html dynamically. What advantage does Knockout give us?

A: No. The accepted answer here falls somewhat short of a complete answer.
Your understanding of what "dependency tracking" actually means is incorrect. What you describe is actually just the data-binding part of knockoutjs. This functionality is very common and is replicated in many ways by many other frameworks.
Dependency tracking is where knockout becomes much, much cleverer.
Say you have two observables:
var firstName = ko.observable("akshay");
var lastName = ko.observable("Khot");

and now you make a computed observable:
var fullName = ko.computed(function(){return firstName()+" "+lastName();});

Now let's make a model:
var model = {
    firstName:firstName,
    lastName:lastName,
    fullName:fullName
}

and bind it:
ko.applyBindings(model);

to the following HTML:

Now, because dependency tracking has calculated that fullName depends on firstName and lastName, when you update either of these values:
model.lastName("is cool");

then the notifications from the dependencies of model.fullName will cause the value of model.fullName to change, and for this value to be updated in the DOM (so it now reads akshay is cool), even though the DOM is not bound to lastName, only something that depends on lastName.
Pretty neat when you think about it and a feature that keeps me coming back to KO as my goto framework.
If this leaves you curious as to how it all works...
http://knockoutjs.com/documentation/computed-dependency-tracking.html
and
http://www.knockmeout.net/2014/05/knockout-dependency-detection.html


text:
Q: Identical class and instance names I recently had the problem that I needed some helper functions to return instances of different types, similar to std::make_pair. My syntax of choice for this was:
Event event(Trigger(...), []() { });

where ... was some simple parameter that created a different trigger type based on ...'s type (e.g., Time, UserInput, etc.).
In addition I wanted some predefined triggers that could be used directly, such as:
Event event(Trigger::OnInit, []() { });

I found that defining a class and instance named Trigger allowed me to support both syntaxes:
static const struct Trigger {
    static const OnceTrigger OnInit;

    TimeTrigger operator()(Time const &) const;
    UserTrigger operator()(UserInput const &) const;
} Trigger;

Notice the identically named type and instance names.
This works in both GCC and MSVC, but I am wondering if and how valid this is according to the standard. Is it "luck" that both compilers support this? Or is name lookup defined such that this is guaranteed to work on all compilers?

A: Being able to name a structure (or class in C++) type the same as an instance of that structure is brought in from C, and it's because structure-names are in a separate namespace (not in the sense of C++ namespace though) compared to variable-names.

A: In the function call syntax Trigger(...), the class is hidden by the instance per 3.3.10:

2 - A class name (9.1) or enumeration name (7.2) can be hidden by the name of a variable, data member, function, or enumerator declared in the same scope. If a class or enumeration name and a variable, data member, function, or enumerator are declared in the same scope (in any order) with the same name, the class or enumeration name is hidden wherever the variable, data member, function, or enumerator name is visible.

In the qualified name lookup syntax Trigger::OnInit, the class is visible per 3.4.3:

1 - [...]  lookup of the name preceding [the] :: considers only namespaces, types, and templates whose specializations are types.

Indeed, the standard has an example which demonstrates how qualified name lookup is not subject to hiding of type names:
class A {
public:
  static int n;
};
int main() {
  int A;
  A::n = 42; // OK
  A b; // ill-formed: A does not name a type
}

So your code is fine per the standard.  (Whether it's a good style is another matter entirely!)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sharepoint rest api Version number increments on Checkout rather than check in Consider a file whose current version number is 1.0.
I am checking out the file through rest api and the UIVersionLabel property of the file, is incremented to 2.0 after checkout operation. When i check the details of the same file on sharepoint site, the version is displayed as 1.0 and only after checkin, the version is updated to 2.0.
But in the case of rest api, the version is incremented to 2.0. Which is the correct property of the file object to retrieve the right version?

A: Assuming that you have only major versions enabled in document library.
SharePoint's default behavior is the same when you are getting the version number in REST query.
The checked in version is: 6.0

After checking out it became 7.0 version.

However, if you want to display the last checked in version of the file you can get that idea from CheckoutUserId property. When you query a particular item, you can check the value of CheckoutUserId is null or not. If it null then the item is currently checked in, if it is not then it checked out.

A: UIVersionLabel  is the correct property to be used.
My solution to the question above is :
When a user checks out a file, the file's version is incremented but only the user who has checked out the file can see this incremented version. Everyone else still can see the non-incremented version. Only when the user checks in, the new incremented version is displayed to all the users.
UIVersionLabel  property contains the correct version number for each user. The user is determined from the authentication token provided along with the Rest Call. Brilliant!


text:
Q: How can I play multiplayer on NBA 2K14 on pc with my friends? I just tried to insert another keyboard in my PC so that I can play with multiple controllers in NBA 2K14, but I am not able to do it. My friends will also be bringing their keyboards. Is there any way we can play on the PC with multiple keyboards?

A: Here is a good question that was asked on SuperUser about using multiple keyboards on one PC.
It would be much more convenient to plug in multiple gaming controllers into one PC, as those can be mapped much easier to each user.


text:
Q: Use string as variable name in Angular 2+ and Typescript In regular JavaScript we can add a property to window global object with name from string, like this:

const str = "myVar";
window[str] = "Value";
console.log(myVar);

But is there a way to do the similar job in Angular 2/4 and Typescript? We can store regular variables in component using this.myVar, but is there a way to create the same variable using string for the variable name? Something like:
const str = "myVar";
this[str] = "Value";
// the result should be the similar as this.myVar = "Value";

A: I think you can access using the following & Typescript accepts this syntax
this["myVar"]

instead of
this.myVar

A: You can allow dynamic properties on your class:
class Test {
  [key: string]: any;

  constructor() {
    const str = "myVar";
    this[str] = "Value";
    console.log(this.myVar);
  }
}

But make sure you really need it because you're loosing typechecking with it:
class Test {

  [key: string]: any;

  constructor() {
    this.teet(); // typo and therefore you will get an error in runtime
  }

  test() {

  }
}


text:
Q: Drawing Keynote Line Style using Tikz What is a simple way to draw a line in tikz with a style similar to the following line created in Apple Keynote?

A:
\documentclass[border=10pt]{standalone}
\usepackage{tikz}
\begin{document}
  \begin{tikzpicture}
    %The targeted space (for reference)
    %\draw[blue](0,0.25)--(5,0.25); % Top line
    %\draw[red](0,0)--(5,0); % Bottom line
    \foreach \x in {1,2,...,2000}{ % 2000 random marks
      % rnd generates a number between [0, 1]
      % X coordinate values are between [0, 5]
      % Y coordinate values are between [0, 0.25]
      \filldraw[red] (rnd*5,rnd/4) circle (0.3pt);
      % Or draw rectanges instead.
      %\filldraw[red] (rnd*5,rnd/4) rectangle ++ (0.5pt, 0.5pt);
    }
  \end{tikzpicture}
\end{document}


text:
Q: Значения каждой цифры при изменении версии При выпуске новых версий ПО, разработчики присваивают продукту новый номер версии.
Так вот, например, есть версия 1.8.3, при следующем апдейте могу присвоить 1.8.4, либо 1.9.0, либо 2.0.0 - отчего будет зависеть какой номер присвоят следующий?

A: Интересный способ версионного контроля : x.xy.xyz
Можно закодировать полезную информацию...
Например, в чем отличия ПО v.1.2.54 от ПО v.1.3.60

x - Глобальные изменения (возможно даже нет обратной совместимости, в данном примере нет изменений)
  xy - Расширен функционал (например, добавлен 1 отчет)
  xyz - Bug Fix (в данном случае было исправлено 6 багов)


text:
Q: Constantly Check Through a List of Times and Current Time and Display Notification I'm currently working on a python to-do application. All user created events are stored in a dictionary called toDoEvents, with title, due_time, remind_time, and description. Right now I'm working on a notification system using toast. I need to constantly check the list of remind_dates for every event and if it matches the current time, calls the toast notification.
I want to do something like this, except constantly checking it every time the minute changes:
from win10toast import ToastNotifier
import time
from datetime import datetime
from PyQt5.QtCore import QDateTime

toDoEvents = {}
class TodoEvent:

    def __init__(self, title, due_time, remind_time, description):
        self.title = title
        self.due_time = due_time
        self.remind_time = remind_time
        self.description = description
        toDoEvents[self.title] = self

    def change_title(self, new_title):
        self.title = new_title

    def change_due_time(self, new_due_time):
        self.due_time = new_due_time

    def change_remind_time(self, new_remind_time):
        self.remind_time = new_remind_time

    def change_description(self, new_description):
        self.description = new_description

event1 = TodoEvent("test", QDateTime(2019, 10, 26, 1, 18).toPyDateTime(), QDateTime(2019, 10, 26, 1, 18).toPyDateTime(), "test description")

for event in toDoEvents.values():

    if event.remind_time.strftime("%m/%d/%Y, %H:%M") == datetime.now().strftime("%m/%d/%Y, %I:%M"):
        toaster = ToastNotifier()
        toaster.show_toast(event.title, event.description, threaded=True, icon_path=None, duration=8)
        while toaster.notification_active():
            time.sleep(0.1)

What is the most efficient way to do this?
Edit: want to execute code every time the minute changes, not every 60 seconds (which assumes the user starts the program at exactly 0 seconds)

A: As a matter of fact, I'm writing almost the same type of program, and I'd suggest to use QTimer instead of constantly checking the current time. Anyway since QTimer default timing has a 5% interval margin (which might be very high for long intervals), you might want to set its timerType to Qt.PreciseTimer.
class TodoEvent:

    def __init__(self, title, due_time, remind_time, description):
        self.title = title
        self.due_time = due_time
        self.remind_time = remind_time
        self.description = description
        toDoEvents[self.title] = self
        self.timer = QTimer(self)
        self.timer.setSingleShot(True)
        self.timer.timeout.connect(self.showReminder)
        self.timer.setTimerType(Qt.PreciseTimer)
        self.change_remind_time(remind_time)

    def change_title(self, new_title):
        self.title = new_title

    def change_due_time(self, new_due_time):
        self.due_time = new_due_time

    def change_remind_time(self, new_remind_time):
        self.remind_time = new_remind_time
        self.timer.start(QDateTime.currentDateTime().msecsTo(self.remind_time))

    def change_description(self, new_description):
        self.description = new_description

    def showReminder(self):
        toaster = ToastNotifier()
        toaster.show_toast(self.title, self.description, threaded=True, icon_path=None, duration=8)

event1 = TodoEvent("test",
                   QDateTime(2019, 10, 26, 1, 18),
                   QDateTime(2019, 10, 26, 1, 18),
                   "test description")

Note that QTimer intervals are expressed in milliseconds as integer, so there might problems with date intervals higher than the maximum value of a 32bit integer. Standard integers have a maximum positive value of 2147483647, which, when referred to milliseconds, is 24 days, 20 hours, 31 minutes, 23 seconds and 647 ms.
This means that if you have a reminder due to a date with a ms interval higher than that value, you'll get an invalid timer (with an interval equal to -1).
While it's unlikely that a normal person will keep his/her computer on for that amount of time, that's not impossible (think about portable devices that often run for weeks without restarting), so you might want to add a function that checks the due time for too high intervals and, eventually, add a further timer that will "restore" itself until the interval has become valid, then start the actual timer for the notification.

A: I'm adding another answer as the update to the question has made the other one a bit off topic, but I prefer to leave it there as I believe that it could be useful to others, even if slightly unrelated to the topic at matter.
The example below subclasses QTimer making it a timer that "timeouts" at minute changes only. It might seem a bit complicated, but that's due to the nature of QTimers, which can be not as precise as one would expect (as most timers are); nonetheless it allows better implementation while avoiding unnecessary timeout signal emissions, as sometimes the timeout signal could be emitted before the end of the minute, thus emitting it again when the minute actually changes.
The singleShot setting is really not required, as the timer will be restarted anyway with the correct interval (constant checks are required, as some hard working process might happen in the meantime, causing the timer to shift after the minute change). I just added it as I think it might slightly improve performance in case of high amount of timers, but I may be wrong. In any case, it will work anyway even without it.
class MinuteTimer(QTimer):
    customTimeout = pyqtSignal()
    def __init__(self, parent=None):
        super(MinuteTimer, self).__init__(parent)
        self.setSingleShot(True)
        # default timer is CoarseTimer, which *could* fire up before, making it
        # possible that the timeout is called twice
        self.setTimerType(Qt.PreciseTimer)
        # to avoid unintentional disconnection (as disconnect() without
        # arguments disconnects the signal from *all* slots it's connected
        # to), we "overwrite" the internal timeout signal attribute name by
        # by switching it with our customTimeout signal instead, keeping
        # its consistency with QTimer objects, at least by object naming
        self._internalTimeout = self.timeout
        self._internalTimeout.connect(self.startAdjusted)
        self._internalTimeout.connect(self.customTimeout)
        self.timeout = self.customTimeout

    def start(self):
        now = QTime.currentTime()
        nextMinute = QTime(now.hour(), now.minute()).addSecs(60)
        # if the next minute happens at or after the midnight of the day
        # after (in this specific case, when "now" is at 23:59), msecsTo()
        # will return a negative value, since QTime has no date reference:
        # 14:30:00 to 14:29:00 is -60 seconds, so 23:59:00 to 00:00:00 is
        # -86340 seconds; using the % modulus operator against the
        # millisecond count in a day can give us the correct positive
        # difference that can be used as an interval for QTimer
        QTimer.start(self, now.msecsTo(nextMinute) % 86400000)

    def startAdjusted(self):
        now = QTime.currentTime()
        # even when using a PreciseTimer, it is possible that the timeout
        # is called before the minute change; if that's the case, we
        # add 2 minutes, just to be "better safe than sorry"
        addSecs = 120 if now.second() > 50 else 60
        nextMinute = QTime(now.hour(), now.minute()).addSecs(addSecs)
        QTimer.start(self, now.msecsTo(nextMinute) % 86400000)

def minuteEvent():
    print('minute changed!')

    for event in toDoEvents.values():
        if event.remind_time.strftime("%m/%d/%Y, %H:%M") == datetime.now().strftime("%m/%d/%Y, %I:%M"):
            toaster = ToastNotifier()
            toaster.show_toast(event.title, event.description,
                threaded=True, icon_path=None, duration=8)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    minuteTimer = MinuteTimer()
    minuteTimer.timeout.connect(minuteEvent)
    minuteTimer.start()
    sys.exit(app.exec_())

Obviously, it is possible that the timer emits its signal before the minute change (resulting in a failed notification if the next signal is emitted after its minute change), but that's mostly due to your implementation, and I believe that's up to you to check for a time range to ensure that each todo is catched when it should be.
As a possible alternative, you can emit a signal with the expected "HH:mm" timing (using statements similar to the addSecs = 120 if now.second() > 50 else 60 I used) and then check for the actual timing of the reminder.


text:
Q: How to dispatch a custom event in Iframe from a parent? I currently have addEventListener and dispatchEvent in the same file as seen below:
<!DOCTYPE html>
<html>
<body>
<script>
    addEventListener("hello", function(event) {
        console.log( event.detail.name);
    });

    dispatchEvent(new CustomEvent("hello", {
        detail: { name: "Patrick" }
    }));
</script>
</body>
</html>

This works fine, but my goal is to split these two into separate files. The addEventListener would be located in an external file and loaded via Iframe and dispatchEvent would be sent from the main file.
How can I dispatch events in Iframes from the parent?

A: If someone else is still looking for an answer, I figured out that you can just call functions from the Iframe by using:
frames[0].myFunction();

So technically you can just create a new function inside the Iframe, e.g. myFunction, and use it to dispatch the event.


text:
Q: Exclude Endpoint for Flask Session Timeout I have a Flask application that is using Flask-Sessions in order to manage my sessions.
flask.permanent_session_lifetime = timedelta(minutes=30)
After 30 minutes of activity, the session will be terminated and my user will have to login again to continue use of the application.
However, I would like to exclude a specific URL Endpoint from this session timeout behavior. What I mean is, I have a constant polling that happens in my application where the web client calls a GET /status endpoint on a 30 second interval. Every 30 seconds the page asks for updated status of tasks from the server, and updates progress bars, etc.
Due to the above GET /status call constantly being reached, the user could be completely away-from-computer and the session will never timeout because the GET /status call is continuously polling.
Is there a way I can exclude this endpoint in the timeout behavior, such that calls to GET /status DO NOT extend the life of the current user session? If not, what would the recommended approach be in this case? I would prefer not to have to implement my own version of Session behavior in this application.

A: You have to options:

*

*subclass SecureCookieSessionInterface and override should_set_cookie method

*register after_request handler and there remove 'Set-Cookie' header if url matches


text:
Q: Convert MySQL insert from comma separated to piping I have a problem to insert detail from one table into another in MySQL table. The compatibility differs as the one table accepts commas to separate detail in a column and the other table accepts piping. What PHP code can I use to convert the commas into piping?
Ok guys let me re-phrase. I am doing a data dump from another db to my db, the problem is that the content formats of the two tables aren't compatible, meaning that my one table uses UPPERCASE and the other one uses camelCase, and that the one uses (,) without spaces behind or infront where the other table uses (|) with spaces on both sides. I'm lost and need help

A: Take a look at http://php.net/manual/en/function.strtr.php

A: I found the answer:
$replace =  str_replace(", "," | ", $result2);


text:
Q: What is the difference between AWS site-to-site VPN and AWS client VPN? I know that site-to-site is using IPSec (layer 3), but client is using TLS (application layer). It seems like both are actually site to site vpns after reading articles/ docs online.
I guess the protocol (IPSec vs TLS) is their only difference, which has implications on when you would use which one. I would guess that both are equally good, and you should always use TLS on the application layer anyway, even on top of client VPN.
How do you decide which one to use, and why?

A:
you should always use TLS on the application layer anyway, even on top of client VPN

TLS is a protocol that has many different uses. The most common one is in HTTPS but many other protocols use it too as it's a standard way to encrypt network traffix. That's the application level.
In AWS Client VPN it's being used one level down - to encrypt the actual network layer traffic (level 3), regardless of what's passing through the tunnel. They chose to use TLS because it's a standard well known protocol.
Amazon could have implemented Client VPN with IPsec or even invent their own protocol but they chose TLS because it's a proven technology.
And yes, you can indeed use HTTPS over this VPN which is technically TLS over TLS but with different endpoints and certificates.

A: In general the protocol doesn't have much to do with it. You can have IPSec tunnels in both site-to-site or client (aka road warrior) configurations, just like you can have OpenVPN (TLS) tunnels in both site-to-site or client setups. It's a matter of configuration and purpose, not the protocol used.
Site-to-Site VPN

*

*typically 1-to-1 configurations

*both sides in general have similar configuration

*both sides have fixed IP address

*either side can initiate or restart the connection

*both typically have a network behind them (e.g. two office networks connected)

*you can run a routing protocol (BGP, OSPF, ...) over the tunnel

*the networks can communicate both ways

Client-to-Site VPN

*

*typically N-to-1 configurations, with N clients connecting to 1 server

*server and client configs are different

*clients don't need fixed IP address

*only clients initiate the connections (because the server doesn't know the client's current IP)

*client is typically just a single laptop with no network behind it

*routing only permits one IP per client, no BGP or OSPF supported

*only client to the site behind the server connectivity is permitted, generally the site can't initiate connection to the client

That's roughly the difference between site to site and client to site VPNs.
In AWS the VPN Gateway uses IPsec protocol and the Client VPN uses OpenVPN protocol but that's just how AWS implemented the services. However in general it's perfectly possible to use either protocol in either setup.
Hope that helps :)

A:
I know that site-to-site is using IPSec (layer 3),

This does appear to be the case.

but client is using TLS (application layer).

Not sure where you are reading that? the documentation seems to indicate that AWS client VPN is openvpn based
OpenVPN uses TLS for negotiation, but does not use it for the actual data.

It seems like both are actually site to site vpns after reading articles/ docs online.

Openvpn is capable of performing both client and site to site VPN tasks, but AWS seems to be using it as a client VPN, I don't see anything in the documentation that would allow you to say allocate a whole netblock to an individual VPN client.
Of course you could run a NAT on the VPN client, to allow all the devices behind it to use the VPN, but that would not be using the service as-intended.

I guess the protocol (IPSec vs TLS) is their only difference

Site to site and client VPNs have different priorities, which drives different typical protocol choices.
The problem with ipsec is it was designed in an era before pervasive NAT. The result is it runs directly on top of IP and does not have anything analagous to TCP/UDP port numbers that NATs can use to disambiguate multiple client sessions.
So using an IPsec VPN from behind a NAT is a dicey proposition. It may not work at all, or more insidiously it may work, but only for one client at a time.
For a site to site VPN this is not usually a big deal, your edge device will most likely have a public IPv4 from a consistent ISP.
For a client on the go, it's a big issue. So using a VPN soloution that runs on top of UDP or even TCP (openvpn can do either, I'm not sure which configuration amazon use) is likely a good idea. Even if it is less efficient.


text:
Q: Changing admin menu style I want to change my admin menu, Horizontal to vertical . I have attached the Screenshot for the same.
please suggest me how to do that.
thanks!
Screenshot
in my opencart->admin->view->common->header.tpl
menu is like this

<img src="view/image/logo.png" title="<?php echo $heading_title; ?>" onclick="location = '<?php echo $home; ?>'" />

    <?php if ($logged) { ?>

 <?php echo $logged; ?>

    <?php } ?>

  <?php if ($logged) { ?>

<a href="<?php echo $home; ?>" class="top"><?php echo $text_dashboard; ?>

<?php echo $text_catalog; ?>

<a href="<?php echo $category; ?>"><?php echo $text_category; ?>

<a href="<?php echo $product; ?>"><?php echo $text_product; ?>

<?php echo $text_attribute; ?>

<a href="<?php echo $attribute; ?>"><?php echo $text_attribute; ?>

<a href="<?php echo $attribute_group; ?>"><?php echo $text_attribute_group; ?>

<a href="<?php echo $option; ?>"><?php echo $text_option; ?>

<a href="<?php echo $manufacturer; ?>"><?php echo $text_manufacturer; ?>

<a href="<?php echo $download; ?>"><?php echo $text_download; ?>

<a href="<?php echo $review; ?>"><?php echo $text_review; ?>

<a href="<?php echo $information; ?>"><?php echo $text_information; ?>

I want this menu to be displayed vertically instead of horizontal.
in stylesheet, menu is defined like this
#menu {
    background: url('../image/menu.png') repeat-x;
    position: relative;
    z-index: 1;
    height: 34px;
    clear: both;
    padding: 0px 30px;
    min-width: 900px;
}
#menu > ul.left {
    float: left;
}
#menu > ul.right {
    float: right;
}
#menu > ul {
    position: relative;
    margin: 0;
    padding: 0;
}
#menu > ul ul {
    list-style: none;
    margin: 0;
    padding: 0;
    background: url('../image/transparent.png');
}
#menu > ul a {
    display: block;
    color: #FFFFFF;
    text-decoration: none;
    padding: 5px;
}
#menu > ul > li + li {
    background: url('../image/split.png') center left no-repeat;
}
#menu > ul .top, #menu > ul li li.sfhover {
    padding: 10px 15px 9px 17px;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 12px;
    color: #FFFFFF;
    text-align: center;
}
#menu > ul ul li {
    padding: 2px;
}
#menu > ul .selected .top {
    background: url('../image/selected.png') repeat-x;
    color: #FFFFFF;
}
#menu > ul .selected:hover a.top, #menu > ul .sfhover a.top {
}
#menu > ul .parent {
    background: url('../image/arrow-right.png') 95% center no-repeat;
}
#menu > ul li {
    float: left;
    list-style: none;
}
#menu > ul li ul {
    position: absolute;
}
#menu > ul li li {
    clear: both;
}
#menu > ul li ul a {
    color: #FFFFFF;
    height: 15px;
    width: 145px;
}
#menu > ul li ul ul {
    margin: -27px 0 0 157px;
}
#menu > ul li li:hover, #menu > ul li li.sfhover {
    background: #333;
    color: #000000;
}
#container {
    height: 100%;
}

here i am not getting how to change this. So please suggest me where exactly i should change

A: It will be easiest if you change the images to your images or background-colors of your choice and then put a break after every

<a href="<?php echo $attribute; ?>"><?php echo $text_attribute; ?>

<a href="<?php echo $attribute_group; ?>"><?php echo $text_attribute_group; ?>

To Change heading names remove the php text and add your own.

<a href="<?php echo $category; ?>">Add/Edit Category

<a href="<?php echo $product; ?>">Add/Edit Products

If you want an accordion function then you just need to download this jquery script or another like it, in which case you don't even have to worry about that mess of css styling and you can write a far simpler version from scratch.
*UPDATE
To create the accordion navigation follow the tutorial here. I recommend demo 1 for your purposes.
I also recommend posting a new question if you need help.


text:
Q: How can I build the mongoose web server on Linux? I apologize if this seems like a stupid question, but I guess I am more used to packages that come with Makefiles or configure scripts.
I downloaded the Mongoose source tar file from the site, and untarred it.
I then tried to compile an executable out of it using
gcc -g -c mongoose.c -o main.o -lpthread  -ldl.
However, after trying to execute,  I get the error -bash: ./main.o: cannot execute binary file
When I looked into mongoose.c source, I did not find a main function.
Where can I get the main function so that the Linux mongoose web server can be compiled to work the same way as the Windows mongoose.exe?

A: Mongoose does come with a Makefile, and will compile as a standalone command-line program. Lua and SQLite are included.
The easiest way to compile the latest version is to cd into the "build" directory and run make unix. I'm not sure about the archived version on the downloads page, but trunk has been pretty stable.
I just checked out a clean copy of Mongoose from github earlier tonight and built it with no problems, so I can confirm that this works (assuming you have any other dependencies set up properly, of course).

A: It's because mongoose is not supposed to be used standalone, but to "embed" it into your program. You need to create a program which calls the correct function from mongoose.c.
Also, the -c flag to GCC tells it to create an object file, which needs to be linked to create an executable. So you try to execute a file which is not executable.


text:
Q: Building a custom PayPal return URL before POST I have a PayPal Button form and I need to generate the return URL from form data. I am looking for suggestions on good way to accomplish this with the example below:
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
<?php
$Fname = $_POST["first_name"];
$Lname = $_POST["last_name"];
?>
<input type="text" name="first_name" value="">
<input type="text" name="last_name" value="">
<?php
$fullname = $Fname . " " . $Lname;
$urlstring = "http://somedomain.com/someapp.php?fullname=" . $fullname;
?>
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" NAME="address_override" VALUE="1">
<input type="hidden" NAME="return" VALUE="<?php echo $urlstring; ?>">
<input type="hidden" name="hosted_button_id" value="aaabbbcccdddeee">
<input type="image" src="https://www.paypalobjects.com/en_US/GB/i/btn/btn_buynowCC_LG.gif"        border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">

</form>

Anyone?

A: You need to first enable the 'Auto Return' option in you paypal account.
Then just add return to you're form with the wanted url
    <input type="hidden" name="return" value="https://www.yoursite.com/checkout_complete.php">

If you want to have a more reliable information about the transaction you should also use the notify url parameter wich will send
    <input type="hidden" name="notify_url" value="https://www.yoursite.com/ipn.php">

More information here : https://www.paypal.com/cgi-bin/webscr?cmd=p/pdn/howto_checkout-outside
And here : https://www.paypal.com/cgi-bin/webscr?cmd=p/mer/express_return_summary-outside


text:
Q: Sending compiled objects to Closure Templates If I call a template from JavaScript with:
namespace.template(record);

where record is an instance of:
/** @typedef {{var: string}} */

and I use the Google Closure Compiler in advanced mode, which rewrites var, then how can I receive var in the template? Is using 'var' instead of var to prevent rewriting the only way to do this?
I'm thinking that, ideally, it would be nice if I could provide types for the template's @params, just like I can for the JavaScript code, which should let the compiler know what rewritten name to use...

It looks like this doesn't happen for any value of var. It does happen though if the key is named default, because SoyToJsSrcCompiler generates code using 'default' (for this special name only, not for any other name I used so far), thus preventing Closure Compiler from renaming it, but the property is renamed in the JavaScript code, because I'm using default without quotes.

A: If your template looks something like:
/**
 * Foo
 * @param rec
 */
{template .Foo}

{$rec.var}

{/template}

Then the SoyToJsSrcCompiler will produce code similar to:
/**
 * @param {Object.<string, *>=} opt_data
 * @param {(null|undefined)=} opt_ignored
 * @return {string}
 * @notypecheck
 */
namespace.Foo = function(opt_data, opt_ignored) {
  return '
' + soy.$$escapeHtml(opt_data.rec.var) + '
';
};

This generated template function is meant to be included in the compilation with your source file. Since the output property access is of the form rec.var the compiler should rename it correctly.


text:
Q: Highscores don't always get saved playerprefs unity3d i want to save the highscores from each level idividually and write these in a different scene i also want to keep a total of all highscores from each level, this is working partially.
when i finish the first level the system seems to work fine, i got 5482, total says 5482
on the second level it also works and i got 2299, total says 7781, this is all correct
when i finsh level 3 however i get 0 and the total stays on 7781, there is no difference in the way the level finishes and everything in the editor has been set up properly.
the 4th level also gives 0, total remains the same, etc.
part of a bigger script but here's the code that writes score to text.
public int scorelevel;
public Text findText;
public bool highscore;
public bool totalhighscore;

void Start()
{
    findText = GetComponent<Text>();
    if(highscore){
        if (PlayerPrefs.GetInt ("highscorelevel" + scorelevel) > 0) {
            findText.text = "Highest score: " + PlayerPrefs.GetInt ("highscorelevel" + scorelevel);
        } if(GameObject.Find ("LockedLevel" + (scorelevel)).active == true) {
            findText.text = null;
        }
    }
    if (totalhighscore) {
        for (int j = 1; j < LockLevel.levels; j++){
            PlayerPrefs.SetInt ("totalHighscore", PlayerPrefs.GetInt ("totalHighscore") + PlayerPrefs.GetInt ("highscorelevel"+j));
        }
        findText.text = "Total Score: " + PlayerPrefs.GetInt ("totalHighscore");
    }

larger script but here's the part that saves the scores:
public class UnlockLevel : MonoBehaviour {

    protected string currentLevel;
    protected int levelIndex;
    protected int levelIndex2;

    void Start () {
        //save the current level name
        currentLevel = Application.loadedLevelName;

    }

    //check if the player hits the Finish
    void OnTriggerEnter(Collider other){
                if (other.gameObject.tag == "Finish") {
                                Highscores ();

                }
        }

        public void  Highscores (){
            for(int h = 1; h < LockLevel.levels; h++){
                if(currentLevel == "Level"+h.ToString()){
                    //worldIndex  = (i+1);
                    levelIndex2  = (h);
                if(ScoreManager.score > PlayerPrefs.GetInt("highscorelevel"+levelIndex2.ToString())){
                    PlayerPrefs.SetInt("highscorelevel"+levelIndex2.ToString(), (int) ScoreManager.score);
                }
                }
            }
        }
    }


text:
Q: Unable to write into user settings. Please open the user settings to correct errors/warnings in it and try again I am aware that there are some similar questions on this website with similar errors. However, it seems as if this error is different from person to person and I don't quite know how to solve it.
I get that error and when I open the settings in vs code, I have this:
{
    "files.autoSave": "afterDelay",
    "editor.formatOnPaste": true,
    "editor.formatOnSave": true
    "terminal.integrated.shellArgs.windows": [
        "-ExecutionPolicy",
        "Bypass"
    ]
}

VS Code is saying that there is an error from the fifth line (starting with: "terminal....") until the end. When I hover my mouse over the error, it says:
The command line arguments to use when on the Windows terminal. Read more about configuring the shell.
Does anyone know how to fix this?


text:
Q: How to define custom vendor specific err code in kannel opensmppbox I have added a function in opensmppbox but I need to generate a custom vendor specific err code to ESME users
            octstr_destroy(smpp_queued_response_pdu->pdu->u.data_sm_resp.message_id);
            smpp_queued_response_pdu->pdu->u.data_sm_resp.message_id = NULL;
            smpp_queued_response_pdu->pdu->u.data_sm_resp.command_status = **CUSTOM STATUS HERE**;
            msg_destroy(smpp_queued_response_pdu->msg);
            smpp_queued_response_pdu->msg = NULL;
            smpp_queues_add_outbound(smpp_queued_response_pdu);

How can I add my custom error code?

A: add a new case SMPP_ESME_RXXXXXXXXX: with your status message
const char *smpp_error_to_string(enum SMPP_ERROR_MESSAGES error)
{
    switch (error) {
        case SMPP_ESME_ROK:
        .........
...............
case SMPP_ESME_RXXXXXXXXX:
            return "Your return status message";

 default:
            /* tell the user that we have a vendor-specific beast here */
            if (error >= 0x0400 && error <= 0x04FF)
                return "Vendor-specific error, please refer to your SMPP provider";
            else
                return "Unknown/Reserved";
    }

You have define SMPP_ESME_RXXXXXXXXX and its err code in gw/smsc/smpp_pdu.h
    /*
 * Some SMPP error messages we come across
 */
enum SMPP_ERROR_MESSAGES {
    SMPP_ESME_ROK = 0x00000000,
............
.............
    SMPP_ESME_RXXXXXXXXX = 0x00000432,
};

In your code,
smpp_queued_response_pdu->pdu->u.data_sm_resp.command_status = SMPP_ESME_RXXXXXXXXX;


text:
Q: Storing value in a multidimensional array (Javascript) What is the quickest way to store a value in an array at position, let's say, [30][1][0] ...
I tried var myArray[30][1][0] = new Date(); but it won't work without doing var myArray = []; myArray[30] = []; myArray[30][1] = [];  beforehand.
What am I doing wrong?
EDIT:  My issue is that I don't know, first, if the variable myArray already exists and, second, if there's already a value at position, let's say, [29][2][15], which I wouldn't want to overwrite.

A: The correct way to do what you want would be:
var array = [[[new Date()]]];

However, the resulting multidimensional array will not have exactly 30 elements on the third dimension and 1 on the second, like you had in your original code. Not sure if that's going to be a problem for you.
When you do myArray[30][1][0], JavaScript is trying to access element 30 in the array myArray, but, since myArray variable was not initialized to anything yet, it has the value undefined. So your code is equivalent with:
var myArray;
myArray[30] = new Date();

This code is going to issue the error Cannot set property '30' of undefined.
Edit:
If you want to make sure the array exists before assigning values and avoid overriding existing values, the most elegant way I can think of is:
// Store a value in the array, at index (posX, posY, posZ), only if
// that position in the array is currently empty
function storeDateNoOverride(theArray, posX, posY, posZ, date) {
    var theArray = theArray || [];
    theArray[posX] = theArray[posX] || [];
    theArray[posX][posY] = theArray[posX][posY] || [];
    theArray[posX][posY][posZ] = theArray[posX][posY][posZ] || date;
}

// If variable theArray doesn't have a value yet, assign it to a new array
var theArray = theArray || [];

storeDateNoOverride(theArray, 30, 1, 0, new Date());

A:
What is the quickest way to store a value in an array at position, let's say, [30][1][0] ...

The classic way is
array[30] = array[30] || [];
array[30][1] = array[30][1] || [];
array[30][1][0] = array[30][1][0] || [];
array[30][1][0].push(value);

or the equivalent in suitably parameterized fashion.
You could make a little helper:
function subarray(array, n) {
  return array[n] = array[n] || [];
}

Then you could write
subarray(subarray(subarray(array, 30), 1), 0).push(value)

You could also write the helper to do all the accessing and checking in one fell swoop:
function getNestedElement(array, firstIndex, ...indices) {
  if (firstIndex === undefined) return array;
  return getNestedElement(array[firstIndex] = array[firstIndex] || [], ...indices);
}

And then write
getNestedElement(array, 30, 1, 0).push(value)

A: You can not initialize a nested object like that. There are two ways. If you know your ND array size in advance you should first instantiate it as follows;

Array.prototype.clone = function(){
  return this.map(e => Array.isArray(e) ? e.clone() : e);
};
function arrayND(...n){
  return n.reduceRight((p,c) => c = (new Array(c)).fill().map(e => Array.isArray(p) ? p.clone() : p ));
}

var arr = arrayND(5,5,5,void 0); // create 5x5x5 array and fill each cell with "undefined"
arr[3][2][1] = arr[3][2][1] || new Date(); // if falsey value then insert current date.
console.log(arr);

However if you don't know the multidimensional size in advance and would like to grow your array dynamically you can use a function like getNestedValue() and setNestedValue(). In this particular case i will extend the Object.prototype. In production code this should be done through Object.defineProperty() tool though.

Object.prototype.getNestedValue = function(...a) {
  return a.length > 1 ? (this[a[0]] !== void 0 && this[a[0]].getNestedValue(...a.slice(1))) : this[a[0]];
};

Object.prototype.setNestedValue = function(...a) {
  a.length > 2 ? typeof this[a[0]] === "object" && this[a[0]] !== null ? this[a[0]].setNestedValue(...a.slice(1))
                                                                       : (this[a[0]] = typeof a[1] === "string" ? {} : new Array(a[1]),
                                                                         this[a[0]].setNestedValue(...a.slice(1)))
               : this[a[0]] = a[1];
  return this;
};

var arr = [];
arr.getNestedValue(30,1,0) || arr.setNestedValue(30,1,0,new Date()); // if exists don't overwrite it;
console.log(arr[30][1][0]);


text:
Q: Construtor de botoes em JavaScript canvas Estou com uma dúvida ao criar um construtor de botões para Canvas no JS, eu já consigo detectar o clique na área do botão, mas gostaria de simplificar o código com um construtor, para agilizar meu processo de criação do conteúdo, porém não faço ideia de como faze-lo.
Aqui um exemplo do meu código:

var bt = new Botao(0,0, 100, 50); // cria o botao

//construtor de botoes simples.
// eu utilizo um construtor de canvas por isso o parâmetro "canvas".
function Botao(x,y,w,h, canvas){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.render = function(){
   canvas.context.fillRect(this.x,this.y,this.w,this.h);
 }
}

// aqui eu detecto o click do usuário.
function click (evt) {

var rectNav = game.canvas.getBoundingClientRect(); //obtêm as coordenadas do mouse na janela do cliente.
var pos = {
    x: evt.clientX - rectNav.left,
    y: evt.clientY - rectNav.top
 };

    if(pos.x>bt.x && pos.x<(bt.x+bt.w) && pos.y>bt.y && pos.y<(bt.y+bt.h)) {
    alert("click")};    // verifica se o click foi na area do botao "bt".

};

A minha dúvida é: como faço para colocar todo esse código da detecção do "clique" dentro do meu criador de botões, onde eu possa apenas chamar a função, por exemplo, bt.click(codigo para ser executado) dentro de uma função que eu atualize constantemente sem ter que criar esse código adicional, e sem ter que criar um eventListener para tal.
Grato!

A: Não vejo como possas criar um event handler com a criação do botão pois o canvas não tem elementos como o SVG. O que tens de fazer é calcular onde foi clicado e ter uma array de botões que possas verificar quando houver um clique.
Algo assim:

var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');

//construtor de botoes simples.
// eu utilizo um construtor de canvas por isso o parâmetro "canvas".
var botoes = [];

function Botao(x, y, w, h) {
  this.x = x;
  this.y = y;
  this.w = w;
  this.h = h;
  this.render = function (color) {
    ctx.fillStyle = this.color = color || '#000';
    ctx.fillRect(this.x, this.y, this.w, this.h);
  }
  botoes.push(this); // <------------------------ inserir o botão
}

function onTarget(pos, bt) {
  return pos.x > bt.x && pos.x < (bt.x + bt.w) && pos.y > bt.y && pos.y < (bt.y + bt.h);
}

// aqui eu detecto o click do usuário.
function click(evt) {
  var rectNav = canvas.getBoundingClientRect(); //obtêm as coordenadas do mouse na janela do cliente.
  var pos = {
    x: evt.clientX - rectNav.left,
    y: evt.clientY - rectNav.top
  };

  botoes.forEach(function (btn) { // <---------- verificar os botões
    var clicado = onTarget(pos, btn);
    if (clicado) btn.render(btn.color == '#000' ? '#ccf' : '#000');
  })
};

canvas.addEventListener('click', click);

var bt = new Botao(0, 0, 100, 50).render(); // cria o botao
var bt = new Botao(30, 30, 100, 50).render(); // cria o botao

Clica-me!

<canvas></canvas>

jsFiddle: http://jsfiddle.net/hd8ermpf/
Edit:
Para usar funções diferentes em cada botão pode usar-se uma lógica de callback assim:
function Botao(x, y, w, h, callback) {
  this.cb = callback;
  // ... etc

jsFiddle http://jsfiddle.net/hd8ermpf/2/


text:
Q: How to configure openerp7.0?? I can see "Database Management Screen" I'm running ubuntu 13.04
openerp 7.0
and installed postgreSQL
Please help me for setting up the database. i"m new to openerp!

A: These are commands which you can simply copy and paste one by one (since you've already installed just verify them)
Step 1 - Install Postgres
$ sudo apt-get install postgresql-9.1

Step 2 - change password to postgres user
$ sudo passwd postgres

Step 3 - Login to postgres user
$ su postgres

Step 4 - login to postgres database
$ psql

Step 5 - Create a user for openerp
postgres=# create user openerp70 with password 'yourpassword';

Step 6 - Grant openerp user with create db priviledge
postgres=# alter user openerp70 createdb;

Step 7 - Log out from postgres and restart postgres server
postgres=# \q
$ sudo service postgresql restart

Now in openerp-server.conf which is located on your openerp installation dir / install
[options]
; This is the password that allows database operations:
; admin_passwd = admin
db_host = localhost
db_port = 5432
db_user = openerp70
db_password = yourpassword

xmlrpc_port=7575
netrpc_port=7576

Now restart the server and create a database by clicking on manage database link on the login page
Check out these resources for more information
http://www.youtube.com/watch?v=5jRC27vbhN4
How to install openERP in ubuntu 13.04 desktop?
Cheers!!


text:
Q: $x^3 +y^2 +z =100z+10y+x$ What is the largest and smallest integer that satisfies this equation. $x^3 + y^2 +z=\overline{zyx}$, where $\overline{zyx}$ denotes the sequence of the digits.
$x^3 +y^2 +z =100z+10y+x$,where $x,y,z>0$
The maximum value of $x$, $y$, $z$ individually can only be $9$.
$\text{Maximum value}= 9^3 + 9^2 + 9 = 819$
So, $100z+10y+z<819$
Then I'm lost here a bit. What do I do next?

A: $$x^3+y^2+z=100z+10y+x$$
$$x(x+1)(x-1)=y(10-y)+99z$$
No needs to check $x=1$ and $y$ have symmetrical sense (e.g. if $y=1$ satisfies so as $y=9$).
Also, $9\leq y(10-y) \leq 25$ hence $$9(1+11z)\leq x(x+1)(x-1) \leq 25+99z$$
$$108\leq x(x+1)(x-1) \leq 916$$
$$\because \quad 3\times 4\times 5 < 108 < 4\times 5\times 6 \implies x\geq 5$$
Now,
$$4\times 5\times 6 \leq y(10-y)+99z \leq 8\times 9\times 10$$
$$120-25 \leq 99z \leq 720-9 \implies 1\leq z \leq 7$$

This can further confine to $5\leq x \leq 8$; and in turn, furthermore confine to $1\leq z\leq 5$.

Simple search gives
$$\overline{zyx}=135,\, 175,\, 518,\, 598$$

A: Brute force solution using your computer and vbscript:

For i = 111 to 999
  $\ \ \ \ \ $    x = i Mod 10
  $\ \ \ \ \ $    y = ((i-x) \ 10) Mod 10
  $\ \ \ \ \ $    z = i \ 100
  $\ \ \ \ \ $    If (( z+y^2+x^3) = i) Then Msgbox (i)
  Next

Result: 135,175,518,598
However Ng Chung Tak's solution is much more elegant.


text:
Q: Would twisting 3 wires together be as effective (or close) to a twisted pair? Would twisting 3 wires together like a twisted pair would be as effective as an ordinary twisted pair? Or at least a definite improvement to not twisting them at all?

simulate this circuit – Schematic created using CircuitLab
I need to measure the current of each load and I can only do it near the voltage source. Although I plan to use an ethernet UTP cable of which I can just use another wire for a second ground. I am curious if a 3 wire twisted cable is as effective as the twisted pair or it might be not as effective but close.
Intuitively speaking it should still work because the EMI would still cancel out assuming the wires are twisted properly.

A: The effectiveness of a good twisted pair cable relies on these things to largely eradicate differential-mode induction: -

*

*What source feeds it and

*What receive circuit it connects to

So, if the send and return wires (and their associated transmit and receive circuits) don't present a balanced impedance to ground, then twisting is not effective at countering magnetic interference.

Intuitively speaking it should still work because the EMI would still
cancel out assuming the wires are twisted properly.

*

*The return wire will have less capacitance to ground hence it won't be balanced

*The receive circuit input impedance is not balanced

*The transmit circuit may not be very well balanced

*Twisting by itself isn't a solution to electric field interference

You are probably wasting time twisting them under these circumstances.

A: For the cancellation of magnetic fields, you want to use machine_twisted wires, not human_twisted wires.
And dense twists ---  many twists per inch --- are required, otherwise the field variations will not be cancelled.
And the imperfect alignment of the wires inside the field will not be uniform, so cancellation will not be perfect.
Again, use machine_twisted pairs, that have many twists per inch.


text:
Q: Why button is being clicked twice <div class="btn-group btn-group-toggle button-div" data-toggle="buttons">
     <label class="btn btn-secondary" onclick="alert('option1');">
       <input type="radio" name="options" id="option1" autocomplete="off"> Option 1
     </label>
     <label class="btn btn-secondary" onclick="alert('option2');">
      <input type="radio" name="options" id="option2" autocomplete="off"> Option 2
     </label>
</div>

Hello, when I click any of these radio buttons, it seems to be clicked twice. Because I get two similar alerts. How to fix this? Bootstap 5.
Currently, I get an alert "option 1", then again "option 1".
Expected: only one alert "option 1".

A: The solution was to change the "onclick" action to "change" action. Thank you all for the support towards the solution.

A: Your on click is causing the issue, wrapping it in a function will do the trick, hopefully someone can add and explain why this happens as I have completely forgotten, and can't for the life of me remember.
You basically want to change your code from this
onclick="alert('option1');"

// to this

onclick="() => alert('option1');"


text:
Q: Существует ли карта Google maps API По клику добавляю карту
$("body").on("click", ".search_show_map", function(){
    $("#result_search").html('

');
    var map;
    function initMap() {
      map = new google.maps.Map(document.getElementById('map_canvas'), {
        center: {lat: -34.397, lng: 150.644},
        zoom: 8
      });
    }
    initMap();
});

Можно ли как нибудь проверить существует ли на странице карта, а то  при повторном клике Вместо карты серый фон

A: Вынесите var map; за пределы обработчика. Затем внутри обработчика проверяйте значение на undefined
var map;

$("body").on("click", ".search_show_map", function(){
    $("#result_search").html('

');
    function initMap() {
      map = new google.maps.Map(document.getElementById('map_canvas'), {
        center: {lat: -34.397, lng: 150.644},
        zoom: 8
      });
    }
    if (map === undefined) {
      initMap();
    }
});

A: Можно проверить кол-во созданных блоков:
$("body").on("click", ".search_show_map", function(){
    if($("#result_search .search_result_map").length == 0){
        $("#result_search").html('

');
        var map;
        function initMap() {
          map = new google.maps.Map(document.getElementById('map_canvas'), {
            center: {lat: -34.397, lng: 150.644},
            zoom: 8
          });
        }
        initMap();
    }
});


text:
Q: Django Returns 403 Forbidden for Email view I'm trying to create a simple contact form in Django, but I'm stuck with a 403 Forbidden error. How can I pinpoint a 403 error with Django? The page I'm redirected to doesn't seem to explain anything:

Reason given for failure:
CSRF token missing or incorrect.

I'm following the guide from djangobook.com Chapter 7: Forms and I'm on Making a Contact Form
This is pretty much exactly what I have for my contact view:
def contact(request):
    errors = []
    if request.method == 'POST':
        if not request.POST.get('subject', ''):
            errors.append('Enter a subject.')
        if not request.POST.get('message', ''):
            errors.append('Enter a message.')
        if request.POST.get('email') and '@' not in request.POST['email']:
            errors.append('Enter a valid e-mail address.')
        if not errors:
            send_mail(
                request.POST['subject'],
                request.POST['message'],
                request.POST.get('email', 'cinicraftmatt@gmail.com'),
                ['cinicraftmatt@gmail.com'],
            )
            return HttpResponseRedirect('/contact/thanks/')
    return render(request, 'contact_form.html',
        {'errors': errors})

How could someone pinpoint this problem and solve it with little explanation given?

A: Most possibly you miss the {% csrf_token %} in your html template between the form tags.

A: Turns out the book barely mentions that you need to add smtp info to your settings.py file
Here's an example if you use gmail:
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'YourGmail@gmail.com'
EMAIL_HOST_PASSWORD = 'password123'
DEFAULT_FROM_EMAIL = 'replyService@gmail.com'
DEFAULT_TO_EMAIL = 'Optional@gmail.com'


text:
Q: How to solve Transfer function with step function appplied to the input? I'm trying to solve this problem of the book "Automatic Control Systems" by Benjamin Kuo.

I really don't get the answer the book has:

Since I thought the answer would have to be:
$$
F(s)=
\dfrac{880(s+6.818)}{s(s+6)(s+10)}
\dfrac{1}{s}
$$
or
$$
F(s)=
\dfrac{880(s+6.818)}{s(s+6)(s+10)}
E(s)
$$
since \$e(t)=u(t)\$
My question is why in the answer it seems they multiply \$F(s)/E_c(s)\$ by the step function since in the original function it is multiplying by the other side of the equation and there's only one instance of \$u(t)\$.
$$
\dfrac{1}{s}
G(s)
$$

A: The Laplace transform \$F(s)\$ of the response of the system to a unit step input is   $$ F(s) = \frac{880. (1. s+6.81818)}{s (s+6.) (s+10.)} $$
The Laplace transform \$E(s)\$ of the input signal (unit step) is
$$ E(s) = \frac{1}{s} $$
The transfer function \$G(s)\$ relates the input and output by \$F(s)=G(s) E(s)\$.
Therefore, $$G(s)=\frac{F(s)}{E(s)} = \frac{880. (1. s+6.81818)}{(s+6.) (s+10.)}$$


text:
Q: Where can I find a particular version of the IBM JDK/JRE for Windows? I'm trying to get a rather JDK-sensitive piece of Oracle software working with Websphere, and I need to find some particular versions of the IBM JDK to try.  The problem is that IBM doesn't really make these readily available like Sun/Oracle does with theirs, and all the versions I've been able to get my hands on haven't worked for one reason or another.
Specifically, I need one of:
IBM Java 5 SR9 for Windows (ideal)
IBM Java 5 SR2 for Windows
IBM Java 5 SR10 for Windows
How could I get these directly from IBM?  My company has a support contract for Websphere, and I hopefully could have one of our Websphere engineers download it if I can tell them where to go.

A: (Unless you work for IBM) there is no way to download the IBM JDK separately. It's shipped with the IBM Rational Suite of Software IBM develops.
The IBM JDK comes also with IBM Java Profiler (which isn't free).
The Eclipse Platform that is found here https://www.ibm.com/developerworks/eclipse/downloads/helios/#download is similar to the Eclipse download found on the Eclipse Site. IBM makes it easier for those who can't afford WebSphere Application Developer or Rational Application Developer (which are both Eclipse flavour) to use Eclipse.

A: Currently, (July 12 2017) you can find the older bundles for java 6, 7 and 7.1 here https://www.ibm.com/developerworks/java/jdk/eclipse/index.html
The latest one can be downloaded from here https://developer.ibm.com/javasdk/downloads/eclipse/

A: I don't know if this is still true(but this was certainly true in the past), but here is the story.
Due to Java License restrictions earlier, the JDK cannot be provided alone by vendors like IBM.
I am unable to pull this info from any IBM site at the moment but i am pretty certain about these license restrictions in the past.
Here is a post by another gentleman in this space:
From : http://www.ibm.com/developerworks/forums/thread.jspa?messageID=14514070

Unfortunately you can get hold of the JDK only as part of another IBM product (say, Websphere or any Rational product) that you purchased. Our licensing agreement with Sun/Oracle forbids us from providing direct downloads of the IBM JDK on any platforms that Oracle/Sun also support (namely Windows and Linux). If you look at the Java downloads section of the developerWorks website, you'll only find SDKs for AIX, z/OS and Linux on System p/z, since those are IBM owned platforms that Oracle doesn't support.
Since the JDK is shipped along with Websphere/Rational/Tivoli products, you can use it if you already have one of them deployed(though even then you may have SR8 FP1, unless you also install the very latest fix packs for those products).

A: Yes IBM JRE/JDK is typically shipped with products, not stand-alone.
How about you get the WebSphere version that is the target for your activity and install that? Won't that give you what you need? The Single server edition is comparatively small footprint.

A: Here's a page with some IBM JDKs made available on developerWorks that may be useful to you.
https://www.ibm.com/developerworks/java/jdk/

A: the SR9 fix pack for WAS V6.1.0.25 is available here - http://www-01.ibm.com/support/docview.wss?uid=swg24023276. Click on the FTP link to download the PAK file (and rename to zip).

A: Previously I've found that the Eclipse bundles from IBM also contain the IBM JVM.  This might still be the case but the bundles are too big for me to check now.
See http://www.ibm.com/developerworks/eclipse/downloads/

A: I hate to answer with the obvious... but if you have a support contract with IBM, why not just call IBM support?  If you haven't seen it already, IBM's main JDK page is at:  https://www.ibm.com/developerworks/java/jdk/.
However, the Windows offerings are pretty pitiful.  IBM hasn't released a new JDK for the Windows platform since early-2006.  That JDK was of the Java 5 generation, but there's no indication on the download page (or in the installer's file name) of an SR version.  I can't install it and check for you, because of the other Windows caveat of which I hope you're aware:  The IBM JDK will not install on a Windows machine unless the installer detects an IBM BIOS.
Given that IBM sold their PC division to Lenovo, I'm not even sure that it is possible AT ALL to install their standalone JDK on a contemporary box.  I would contact IBM support if you have a contract... they might be able to tell you differently.
Either way, the preceding answer points at another possibility.  IBM frequently bundles its JDK/JRE, without the crazy restrictions found in the standalone version, inside of other downloads.  For instance, I know that WebSphere Community Edition (i.e. IBM's version of Apache Geronimo) comes with one.  Good luck finding the specific version you need... but if you do, and don't mind the possibility of violating some license legalese, then you can just ZIP up that directory and copy it to the target machine.
This whole topic is a damn shame.  In terms of bechmarks and runtime performance, the IBM JDK/JRE has always been awesome.  However, on the larger "ecosystem" level it's always sucked.


text:
Q: Apache not rendering Bugzilla cgi I've just tried to install Bugzilla on my machine for test purposes. I'm going to evaluate the Bugzilla REST API for a company i'm currently interning at. The problem is that when I go to http://localhost/bugzilla/ this is what i'm seeing.
#!/usr/bin/perl -wT
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# This Source Code Form is "Incompatible With Secondary Licenses", as
# defined by the Mozilla Public License, v. 2.0.

###############################################################################
# Script Initialization
###############################################################################

# Make it harder for us to do dangerous things in Perl.
use strict;

# Include the Bugzilla CGI and general utility library.
use lib qw(. lib);

use Bugzilla;
use Bugzilla::Constants;
use Bugzilla::Error;
use Bugzilla::Update;

# Check whether or not the user is logged in
my $user = Bugzilla->login(LOGIN_OPTIONAL);
my $cgi = Bugzilla->cgi;
my $template = Bugzilla->template;
my $vars = {};

# And log out the user if requested. We do this first so that nothing
# else accidentally relies on the current login.
if ($cgi->param('logout')) {
    Bugzilla->logout();
    $user = Bugzilla->user;
    $vars->{'message'} = "logged_out";
    # Make sure that templates or other code doesn't get confused about this.
    $cgi->delete('logout');
}

###############################################################################
# Main Body Execution
###############################################################################

# Return the appropriate HTTP response headers.
print $cgi->header();

if ($user->in_group('admin')) {
    # If 'urlbase' is not set, display the Welcome page.
    unless (Bugzilla->params->{'urlbase'}) {
        $template->process('welcome-admin.html.tmpl')
          || ThrowTemplateError($template->error());
        exit;
    }
    # Inform the administrator about new releases, if any.
    $vars->{'release'} = Bugzilla::Update::get_notifications();
}

# Generate and return the UI (HTML page) from the appropriate template.
$template->process("index.html.tmpl", $vars)
  || ThrowTemplateError($template->error());

I added
<directory /var/www/>
Addhandler cgi-script .cgi .pl
Options +Indexes +ExecCGI +FollowSymLinks
AllowOverride All
</directory>

to the 000-default.conf file to allow CGI-script in all areas.

A: My CGI module was not enabled.
I went to the terminal and typed a2enmod which then gave me a choice of modules to enable. I entered cgi, it enabled it. Then I ran service apache2 restart and that solved my problem.


text:
Q: Visual D code template Visual D code template looks like this:
module main;

import std.stdio;

int main(string[] argv)
{
   writeln("Hello D-World!");
   return 0;
}

Is it possible to change the template into:
module main;

import std.stdio;

void main() {

}

A: You can change the templates in the VisualD installation folder:
C:\Program Files (x86)\VisualD\Templates\

I changed the file below and the new Console App Project template reflected the change.
C:\Program Files (x86)\VisualD\Templates\ProjectItems\ConsoleApp\main.d


text:
Q: PHP variable reverts back to last assigned after intensive curl operation I'm querying one api and sending data to another. I'm also querying a mysql database. And doing all this about 40 times in one second. Then waiting a minute and repeating. I have a feeling I'm at the limit of what PHP can do.
My question is about two variables that will randomly revert back to their last value, from the previous loop. They only change their value after the call to self::apiCall() (below in the second function). Both $product and $productId will randomly change their value, about once every 40 loops or so.
I boosted PHP to 7.2, increased memory to 512, and assigned some variables to null to save memory. I'm not getting any official memory warnings, but watching the variables randomly go back to their last value is perplexing. Here's what the code looks like.
/**
* The initial create products loop which calls the secondary function where
* the variables can change.
**/
public static function createProducts() {
    // Create connection
    $conn = new mysqli(SERVERNAME, USERNAME, PASSWORD, DBNAME, PORT);

    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    // This will go through each row and echo the id column
    $productResults = mysqli_query($conn, "SELECT * FROM product_creation_queue");
    if(mysqli_num_rows($productResults) > 0) {
        $rowIndex = 0;
        while($row = mysqli_fetch_assoc($productResults)){
            self::createProduct($conn, $product);
        }
    }

}

/**
* The second function where I see both $product and $productId changing
* from time to time, which completely breaks the code. Their values
* only change after the call to self::createProduct() which is simply a
* curl function to hit an api endpoint.
**/
public static function createProduct($mysqlConnection, $product) {

    // convert back to array from json
    $productArray = json_decode($product, TRUE);

    // here the value of $productId is one thing
    $productId = $productArray['product']['id'];

    // here is the curl call
    $addProduct = self::api_call(TOKEN, SHOP, ENDPOINT, $product, 'POST');

    // and randomly here it can revert to it's last value in a previous loop
    echo $productId;

}

A: The problem was that the entire 40-query procedure took more than one minute to complete. And the cron job that started the procedure on the minute would start the next one before the first one had completed, thereby somehow re-assigning variables on the fly. The queries usually took less than one minute, but when it was longer, the conflicts appeared, thus leading to the appearance of randomness.
I reduced the number of queries per minute so now the process completes in less than 60 seconds and no variables are ever overwritten. I still don't understand how the variables would change if two php processes are happening at the same time--it seems like they would be siloed.


text:
Q: How to go to a specific file in Chrome Developer Tools? I am developing a web application with a heavy front-end approach. By using Dojo and the AMD-way, I currently have testing screens which may easily load over a hundred different javascript files.
When I want to debug for any specific problem, or verify if I am seeing an old version of a specific file, I find it really hard to find my files in the Sources tab in the Chrome Developer Tools.
Is there any shortcut or action I can make that will let me type the name of a file and will take me to the source of that file?

A: In Windows:
Use CTRL+SHIFT+F  to search for content in files.
Use CTRL+SHIFT+O  to search for file names.

A: CTRL + P brings up the search input in Windows.

⌘ + P — in Mac.

A: While in the sources tab use CTRL+O (⌘+O for Mac) to search scripts, stylesheets and snippets by filename.
(use CTRL+SHIFT+O to filter/navigate to a JavaScript function/CSS rule when viewing a file)
[Chrome Devtools Cheatsheet]

A: Mac: Command + O
Windows: Ctrl + O


text:
Q: Many windows appears of click on Button ADD -MVVM WPF I have Button ADD. When I click on it, I have a new window. I add the new Customer, my datagrid refreshes but just the first time!
Then every time I click on Button Add, I have a new window with the same information and so on... I get many windows ADD!
ViewModel:
        private ObservableCollection<Custmor> _loadDataBinding;
    public ObservableCollection<Custmor> loadDataBinding
    {
        get
        {
            return _loadDataBinding;
        }
        set
        {
            _loadDataBinding = value;
            OnPropertyChanged("loadDataBinding");
        }
    }

     public ViewModel1()
    {
             //Display my DataGrid
        using (Test1Entities context = new Test1Entities())
        {
            _loadDataBinding = new ObservableCollection<Custmor>(context.Custmor.ToList());
        }

        //To Show the Window ADD from Window MainWindow
        addCustomerMainWindow = new RelayCommand(add, canexecute);

        CustomerToAddObject = new Custmor();

        addCustomer1 = new RelayCommand(ADDFunction);
    }

    //To Show the Window ADD from Window MainWindow
    private ICommand addCustomerMainWindow;
    public ICommand AddCustomerMainWindow
    {
        get { return addCustomerMainWindow; }
    }

    private void add(object obj)
    {
        Add addView = new Add();
        addView.DataContext = this;
        addView.Show();
    }

    //The Button ADD from Window ADD
    private ICommand addCustomer1;
    public ICommand AddCustomer1
    {
        get { return addCustomer1; }
    }

    private void ADDFunction(object obj)
    {
        using (Test1Entities context = new Test1Entities())
        {
            context.Custmor.Add(customerToAddObject);
            context.SaveChanges();
            MessageBox.Show("Customer a été ajouté avec succès!");
        }

        _loadDataBinding.Add(CustomerToAddObject);
    }

   //textBox for window ADD: CustomerToAddObject.nom ;CustomerToAddObject.prenom and CustomerToAddObject.reference
  private Custmor customerToAddObject;

    public Custmor CustomerToAddObject
    {
        get { return customerToAddObject; }
        set { customerToAddObject = value; }
    }

How can I fix it for when I ADD a customer, the window ADD closes, and the Mainwindow still updates and so on? Clicking on the button ADD and it adds new customers, as many times as I want?
The result of my error:

Thanks for your help,

A: You could store a reference to the Add window and close it using this one. Something like this:
private Add addView;
private void add(object obj)

    if (addView != null)
        addView.Close();

    addView = new Add();
    addView.DataContext = this;
    addView.Show();
}

private void ADDFunction(object obj)
{
    using (Test1Entities context = new Test1Entities())
    {
        context.Custmor.Add(customerToAddObject);
        context.SaveChanges();
        MessageBox.Show("Customer a été ajouté avec succès!");
    }

    _loadDataBinding.Add(CustomerToAddObject);

    if (addView != null)
        addView.Close();
    CustomerToAddObject = new Custmor();
}


text:
Q: pandas compare two dataframe and count equal keyword Here is my sentence 'sentence' datafrme
(It is just sample. Data is so big.)
sentence = pd.DataFrame({'sentence':['I like to go to starbucks', 'I do not like coffee', 'how can i sign in instagram', 'gift']})

'db_keyword' dataframe
db_keyword = pd.DataFrame({'lv1':['event', 'event', 'event', 'gift', 'gift'],
                         'lv2':['event', 'starbucks', 'instagram', 'gift', 'voucher'],
                         })

db_keyword

I wnant this result, how can i do?

A: out = (db_keyword.groupby('lv1')
       .agg(lambda x: sentence['sentence'].str.count('|'.join(x)).sum())
       .reset_index())

out
    lv1     lv2
0   event   2
1   gift    1


text:
Q: Java Lambdas and Closures I hear lambdas are coming soon to a Java near you (J8). I found an example of what they will look like on some blog:
SoccerService soccerService = (teamA, teamB) -> {
    SoccerResult result = null;
    if (teamA == teamB) {
        result = SoccerResult.DRAW;
    }
    else if(teamA < teamB) {
        result = SoccerResult.LOST;
    }
    else {
        result = SoccerResult.WON;
    }

    return result;
};

So right off the bat:

*

*Where are teamA and teamB typed? Or aren't they (like some weird form of generics)?

*Is a lambda a type of closure, or is it the other way around?

*What benefits will this give me over a typical anonymous function?

A: *

*Where are teamA and teamB typed? Or aren't they (like some weird form of generics)?

Lambda's use target typing, much like generic method calls (since 1.5) and the diamond [not an] operator (since 1.7). Roughly, where the type the result applied to is stated (or can be inferred) that is used to supply the type of the Single Abstract Method (SAM) base type and hence the method parameter types.
As an example of generic method inference in 1.5:
Set<Team> noTeams = Collections.emptySet();

And diamond operator in 1.7:
Set<Team> aTeams = new HashSet<>();

Team, team, team, team, team, team. I even love saying the word team.

*

*Is a lambda a type of closure, or is it the other way around?

A lambda is a limited form of closure in almost exactly the same way as anonymous inner classes, but with some random differences to catch you out:
The outer this is not hidden by an inner this. This means that the same text in a lambda and an anonymous inner class can mean subtly but completely different things. That should keep Stack Overflow busy with odd questions.
To make up for the lack of inner this, if assigned directly to a local variable, then that value is accessible within the lambda. IIRC (I could check, but wont), in an anonymous inner class the local will be in scope and hide variables in an outer scope but you can't use it. I believe the lack of an instance initialiser makes this much easier to specify.
Local fields that do not happen to be marked final but could be, are treated as if they are final. So not are they in scope, but you can actually read (though not write) them.

*

*What benefits will this give me over a typical anonymous function?

A briefer syntax. That's about it.
Of course the rest of the Java syntax is just as hopelessly bad as ever.
I don't believe this is in the initial implementation, but instead of being implemented as [inner] classes, lambdas can use method handles. The performance of method handles falls somewhat short of earlier predictions. Doing away with classes, should reduce bytecode footprint, possibly runtime footprint and certainly class loading time. There could be an implementation where most anonymous inner classes (not Serializable, trivial static initialiser) didn't go through the poorly conceived class loading mechanism without any particularly noticeable incompatibilities.
(Hope I've got the terminology wrt hiding correct.)

A: The Lambda expression is just syntactic sugar to implement a target interface, this means that you will be implementing a particular method in the interface through a lambda expression. The compiler can infer the types of the parameters in the interface and that's why you do not need to explicitly define them in the lambda expression.
For instance:
Comparator<String> c = (s1, s2) -> s1.compareToIgnoreCase(s2);

In this expression, the lambda expression evidently implements a Comparator of strings, therefore, this implies the lambda expression is syntactic sugar for implementing compare(String, String).
Thus, the compiler can safely assume the type of s1 and s2 is String.
Your target interface type provides all the information the compiler needs to determine what are the actual types of the lambda parameters.
Briant Goetz, Java Language Architect at Oracle Corportion has published a couple of articles of the work in progress in JDK 8 Lambdas. I believe the answers to your questions are there:

*

*State of Lambda.

*State of Lambda Libraries Edition.

*Translation of Lambda Expressions

*JVMLS 2012: Implementing Lambda Expressions in Java
This second article explains how the lambda expressions are implemented at the bytecode level and may help you delve into the details of your second question.

A: See this page for a full version of that example (however, the relevant parts are shown below).
The types are inferred from the SoccerService interface and SoccerResult enum, not shown in your snippet:
enum SoccerResult{
    WON, LOST, DRAW
}

interface SoccerService {
    SoccerResult getSoccerResult(Integer teamA, Integer teamB);
}

The benefit (of lambdas versus standard anonymous classes) is just reduced verbosity:
(x, y) => x + y

versus something like:
new Adder()
{
  public int add(int x, int y)
  {
    return x + y;
  }
}

For the difference between a closure and a lambda, see this question.


text:
Q: How to pass input request to foreach loop in controller to store data I'm building a site with localizations using laravel. Trying to store names and texts in 3 languages using a form. I have a model for each article and another for article translations.
Using inputs for names and texts with input names like name_en, text_en, name_de, text_de etc...
But i can't figure out how to pass input values to a foreach loop in the store method in my controller.
I tried to pass (Request $request) object into foreach loop but it returns an error. Code is below:
public function store(Request $request)
{
    $test = new Test;
    $test->isActive = true;
    $test->save();

    //TRANSLATED INPUTS = name_tr,text_tr,name_en,text_en,name_de,text_de

    foreach (['tr', 'en', 'de'] as $locale => $request)//OBVIOUSLY WRONG
    {
        $test->translateOrNew($locale)->name = $request->input('name_'.$locale);
        $test->translateOrNew($locale)->text = $request->input('body_'.$locale);
    }

    $test->save();
    dd($test);
    //echo 'Created new article with some translations!';
}

Trying to get translated inputs itno database.

A: It is possible to do this the way you have it set up.  You could use a series of if str contains, then str replace on name, and text, until you get the right language.  But that's potentially a lot of work and likely pretty confusing if you have many names and texts coming from your form (which I assume you do from the need for a foreach on the incoming data).
I suggest you re-work your form slightly to return a bit more information.  Consider the following as possible elements to return from the form:

*

*name[]

*text[]

*language[]

Then, in your store method you can run through each of these in a number of ways, but to explain, I'll use the clearest (though not the most efficient):
Set an index:
$i = 0;

Run through all of the form's returns, and get the corresponding text and language that comes with the name (through the same index):
foreach($request->get('name') as $name){
     $lang = $request['language'][$i];
     $test->translateOrNew($lang)->name = $name;
     $test->translateOrNew($lang)->text = $request['text'][$i];
     $i ++;
}

This is almost pseudo code, and you will have to re-factor to make it work for you, but it should give you one idea on how you might do this.  You will need to validate that the user provides each set (name, text, language) as complete, or the index will fail.


text:
Q: using angular factory in multiple controllers I am using angular ui grid. At first I implemented this in a controller and it works fine after all my customization. As I am using multiple grids I cannot write a long controller each time. So, I converted it to factory. I kept the common function in factory and column definition and data in controller. Now when I use this factory in more than 1 controllers, the last controller is overriding all others.
1) Is it correct to make this grid in a factory?
2) If yes how do I overcome this problem?
3) By using factory for this grid, my gridObj.gridApi.pagination.on is throwing error(gridObj is the singleton object that I am returning).
Any suggestion is welcome. Thanks a lot in advance.

A: You should use a Directive instead. Factories create a single Instant (see Angular Provider Documentation and wont create a private scope, which you need to not override your data.

Note: All services in Angular are singletons.

But Directives provide a private scope and create new instances every time they are called in HTML if you want them to.
//directive
scope: { // this option creates isolated scopes
  something : '=',
},

I created a Plunkr showcasing a possible setup. For some more written details please see my answer from few days ago.
Your HTML might look like this afterwards
<my-grid options="all.firstOptions" class="grid"></my-grid>

Where my-grid is your directive and options="" are your special settings (and whatever else you wish to use in the directive). In your directive you declare the default settings and merge them with the special ones.
scope.gridOptions = {
          data: scope.options.data, //private scoped from options : '=',
          columnDefs: scope.options.colDef || defaultColDef, // optional setting or default setting
          // ... some more default data
        };

If you have any specific questions, let me know.


text:
Q: How to AutoMapper a Source's Member's Property to Destination Property? In these 3 classes, how do you map SourceString to DestinationString?
public class MySourceClass
{
   public AnotherClass AnotherClass { get; set; }
}

public class AnotherClass
{
   public string SourceString { get; set; }
}

// [AutoMap(typeof(MySourceClass))] // <--this doesn't seem to help
public class MyDestinationClass
{
   //[SourceMember( nameof(AnotherClass.SourceString) )] <--not a winner
   public string DestinationString { get; set; }  // <-- this should map to AnotherClass.SourceString
}

If there were a way to do this in the CreateMap method, it seems like a better place to keep the logic. Any help is appreciated!

A: On your automapper configuration you need to create a map for the 2 classes, because the properties are with different names you should add specific map.
CreateMap<AnotherClass , MyDestinationClass>()
    .ForMember(x => x.DestinationString, x => x.ResolveUsing(y => y.SourceString));


text:
Q: Pipeline Diagram of IO2I Microarchitecture Is my pipeline correct for the given sequence of instructions? If it is not, can you shine some light on where I went wrong? EDIT: I forgot to add the issue stage of the mul instruction.
MUL R6, R7, R8
ADD R9, R10, R11
ADD R11, R12, R13
ADD R13, R14, R15
ADD R19, R13, R10
LW R2, R3
ADD R12, R16, R19
LW R5, R2
ADD R15, R20, R21

MUL     IF ID I  Y0 Y1 Y2 Y3 Y4 W  C
ADD        IF ID I  X0 W  r        C
ADD           IF ID I  X0 W  r         C
ADD              IF ID I  X0 W  r          C
ADD                 IF ID I  I  X0 W   r       C
LW                     IF ID ID I  L0  L1  W   r   C
ADD                       IF IF ID I   I   X0  W   r   C
LW                              IF ID  ID  I   L0  L1  W  r  C
ADD                                IF  IF  ID  I   I   X0 W  r  C


text:
Q: how do i tell nginx to handle the file after fastcgi rewrites it? I have a asp.net app and i am using nginx with fastcgi&mono. When i visit static.mysite.com/type/258/nicename.png i need nginx to grab the file from apppath/public/uploads/00/00/01/02 which is hex of 258. ATM i have asp.net rewriting the file however i am positive asp.net is still handling the file instead of nginx. I'm sure nginx would be faster and since i have the static subdomain i can skip asp.net if i have a way to tell nginx how to map the url to file
How do i get nginx to handle the file transfers?

A: Check XSendFile.


text:
Q: Need help setting up multiple Realms in Tomcat I'm trying to set up two Realms in tomcat and it isn't letting me for some reason.  I'd like to use the standard UserDatabaseRealm (conf/tomcat-users.xml) for doing admin things (like deploying webapps) but I'd like a custom realm for doing authentication for a specific webapp.
So, I tried putting this in the context of my webapp:
<Context>
  <GlobalNamingResources>
    <Resource name="CustomDatabase" auth="Container"
      type="org.apache.catalina.UserDatabase"
      description="User database that can be updated and saved"
      factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
      pathname="/usr/java/apache-tomcat-6.0.35/conf/tomcat-users.xml"
    />
  </GlobalNamingResources>
  <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
    resourceName="CustomDatabase"
   />
</Context>

Which is really just a copy of what is in server.xml with a couple changes:

*

*The name is changed to CustomDatabase from UserDatabase.

*The pathname is the absolute pathname (and the same I use for the main realm).
I always get this same error:
LifecycleException:  No UserDatabase component found under key CustomDatabase

And I don't know what it is telling me.  What component is it talking about?
Along with the context above I've tried a couple other things, but it always gives the same error:

*

*I've tried wrapping the Resource with the GlobalNamingResources tag and whether there or not same error.

*I've tried changing the auth attribute of the Resource to both Container and Application and get the same error.
What am I missing?  All the help from google is mostly people messing up their main realm (which mine is fine) not trying to configure a second realm.

A: You may use org.apache.catalina.realm.CombinedRealm. From the Tomcat documentation:
<Realm className="org.apache.catalina.realm.CombinedRealm" >
  <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
         resourceName="UserDatabase"/>
  <Realm className="org.apache.catalina.realm.DataSourceRealm"
         dataSourceName="jdbc/authority"
         userTable="users" userNameCol="user_name" userCredCol="user_pass"
         userRoleTable="user_roles" roleNameCol="role_name"/>
</Realm>

A: So, I don't have a real answer, but I'll explain what I did.
I wasn't able to get the second UserDatabaseRealm working, but I really just needed two realms for testing, and it didn't matter the type (eventually, the second realm would be LDAP).
So I was looking at the available realms and chose a MemoryRealm for my secondary test realm and it worked just as it should have.  I then made it a LDAP realm and that also worked fine.
So, sorry to those that actually need two UserDatabaseRealms, I don't have a solution for you.
NOTE: It's strange that the UserDatabaseRealm uses JNDI and the JNDIRealm is used for LDAP (and from what I can tell, JDNI isn't involved).  I'm sure this is just some legacy naming problem, but it's confusing.


text:
Q: Unity quick launch icon opens another program icon on program start I prepared a custom .desktop file for my chromium browser that loads a different user profile. When ever i click the icon now it open the browser, but also uses a new icon on the launcher bar (not locked to the launcher). Is there any way to tell the program to keep connected to the first icon?
[Desktop Entry]
Type=Application
Name=Second Browser
Exec=chromium-browser --user-data-dir="/home/patrick/bin/chrome-profiles/second"
TryExec=chromium-browser
Icon=/home/patrick/.local/share/applications/icons/browser.png
MimeType=text/html;

A: NO, not easily.
This will often occur after an update, where Ubuntu / Unity no longer thinks this is the exact same application.  I also often get this with LibreOffice.

Suggested workarounds:
(1.) Lock the icon that opens to the Unity bar, and remove (detach) the other.
OR
(2.) Recreate your custom launcher, based on the default launcher.  See my posting: How can I edit/create new launcher items in Unity by hand?

A: I found an easy way to accomplish exactly what I am trying to do:
StartupWMClass=www.domainname.com__some_path

will group all windows of the same domain and/or path. You can find out the WM_CLASS by executing the following command on the shell and clicking the window you want to find the class out for:
xprop WM_CLASS

This way you can have more than one Chromium-browser entry on your launchbar and the entries stay grouped together.


text:
Q: Why use a LengthFieldPrepender/LengthFieldBasedFrameDecoder I thought about this for sometime now, why should I use a LengthFieldPrepender and LengthFieldBasedFrameDecoder in a TCP connection?
I don't get the reason my only idea was to ensure that the data is transferred correctly and check the length but if my understanding of TCP is correct TCP itself should handle that the data is transferred correctly.

A: TCP is a stream protocol. It is up to the application to frame the data, i.e. determine where a unit of data - a packet or a message - starts and where it ends. The two basic methods to achieve this reliably are either to prepend the length of the message or to append a delimiter. There are many ways to encode the prepended length and there are many possibilities for a delimiter. The TCP protocol does not guarantee that the data that was sent by means of a single write will be received by a single read, although this is often the case for short messages.

A: You're correct that the TCP protocol should handle that the data is transferred correctly.  Though in many cases, the amount of data being sent is not known at the time of reception (i.e. a variable amount).
To solve this, the length of the data being sent is added to the header of the packet.  If we know that the length is of a fixed size n, then we can read n bytes, then the next length bytes which holds the data.


text:
Q: Detecting if an app was preinstalled on a device My application is going to be preinstalled on a vendor device (eg. Vodafone/T-Mobile/ATT is going to sell phones with my app preinstalled).  This preinstalled app is very lightweight - only landing page with Update button, which redirects to the Google Play.
I'd like to track how many users coming from this preinstalled app (how many of them sign up, bought subscription, etc.).
Scenario 1:

*

*User starts a phone for a first time

*User opens preinstalled app

*I can save in shared preferences that user opened app and read it in real updated version

Scenario 2:

*

*User starts a phone for a first time

*Preinstalled app is being updated in background through Play Store

*I do not recieve any broadcasts (eg. BOOT_COMPLETED) because app was never opened

*User opens updated version -> I do not know if he's coming from preinstalled app or not

My question is how to solve scenario 2?

A: I had that problem too, but didn't find a solution that fit my needs (other than don't update the store version for a few months after releasing the OEM version). You can't save anything if the app wasn't opened, but maybe you can try to read the install date:
long installed = context
.getPackageManager()
.getPackageInfo(context.getPackageName(), 0)
.firstInstallTime;

(copy&paste from https://stackoverflow.com/a/5311917/2694254, there are also other solutions to get the install date on that site)
You would still have to make some assumptions, like "if app was installed but not opened on the same day" if your App is already publicly released before the OEM App is installed.


text:
Q: XSD Files in asp.net preview data I have created a Stored Procedure in SQL and have configured it to be used with DataTables. The stored Procedure accepts 3 variables.
1. 3635 (Int)
2. NotMeeting (AnsiString)
3. 1 (Boolean)
When i want to preview the output after inserting values into the "Preview Data" function in DataTables, i get the following error:
"Failed to convert parameter value from a String to a Boolean".
I tried putting single speechmarks around '1' & double speechmarks of "1" but it makes no difference.
This works fine if i execute it in SQL Server Management Studio
(i.e.
exec dbo.EXSP_CIA_Events_Timeline_List @Ext_Acquisition_ID=3635,@CalcType='NotMeeting',@UseCompleteTasks=1
)
Any clues?

A: I think you are maybe using ADO.net, in which case, you don't pass 1 to the SqlParameter, you would pass an actual boolean value (e.g. true/false).


text:
Q: c++ find var in vector of structs I'm trying to make a c++ program where I can dynamically add points to a list, and then search for if those points are in the list.
I was trying originally to use sets, but am now trying to use vectors. My code below will run, but gets an error involving the search if statement.
#include <stdio.h>       /* printf */
#include <bits/stdc++.h> /* vector of strings */
#include <algorithm>
#include <vector>
using namespace std;

void solve_point(vector<vector<char>> &board)
{
    printf("solve_point\n");
    board[2][2] = 'c';
}

struct point
{
    int x;
    int y;
};

int main()
{

    vector<point> vec;
    point point1{4, 1};
    point point1{8, 3};
    vec.push_back(point1);

    if (find(vec.begin(), vec.end(), point1) != vec.end())
    {
        printf("point1 found in vec\n");
    }
    else
    {
        printf("point1 not found in vec\n");
    }

   }

This leads to some errors saying:
/usr/include/c++/7/bits/predefined_ops.h:241:17: error: no match for 'operator==' (operand types are 'point' and 'const point')
  { return *__it == _M_value; }

  ..and..

  /usr/include/c++/7/bits/predefined_ops.h:241:17: note:   'point' is not derived from 'const __gnu_cxx::new_allocator<_Tp>'
  { return *__it == _M_value; }

I encountered an error similar to this earlier when I was trying to insert a point into a set, is there something wrong with my struct point initialization? Thanks

A: You are experiencing two problems:

*

*std::find() needs a way of comparing two struct point instances. For this, it defaults to using point::operator==() which is not defined. You have to add this manually:

struct point
{
    int x;
    int y;

    bool operator==(const point& rhs) const {
        return x == rhs.x and y == rhs.y;
    }
};

Alternatively you can use std::find_if() which allows you to supply a lambda. However, instances of a class like point will most likely need to be compared in a lot of places so defining operator==() is definitely a good idea.

*You're redeclaring point1. Rename it to for example point2.

Working example:
#include <bits/stdc++.h> /* vector of strings */
#include <algorithm>
#include <vector>
using namespace std;

void solve_point(vector<vector<char>> &board)
{
    printf("solve_point\n");
    board[2][2] = 'c';
}

struct point
{
    int x;
    int y;

    bool operator==(const point& rhs) const {
        return x == rhs.x and y == rhs.y;
    }
};

int main()
{

    vector<point> vec;
    point point1{4, 1};
    point point2{8, 3};
    vec.push_back(point1);

    if (find(vec.begin(), vec.end(), point1) != vec.end())
    {
        printf("point1 found in vec\n");
    }
    else
    {
        printf("point1 not found in vec\n");
    }

   }


text:
Q: console.trace() not showing all the traces in Electron For some reason console.trace() doesn't show all traces in Electron application

function test ()
{
  setTimeout(() => console.trace("test"));
}

test();

If you run this snippet and than open browser console, it shows 1 trace line, but if you run it again while console already opened, it shows 4 lines of traces:

In Electron it only shows 1 line:

Any ideas why this happening and how to fix it?
Here is electron fiddle I'm testing it with