text:
Q: TypeError: Cannot read properties of undefined (reading 'length') when using mongoose i'm making a todolist (angela yu), i'm trying to write to a new database, but i keep getting error.this is the error:
C:\Users\tunji\Desktop\webdev\todolist-v2-starting-files\node_modules\mongoose\lib\model.js:3519
        for (let i = 0; i < error.writeErrors.length; ++i) {
                                              ^

TypeError: Cannot read properties of undefined (reading 'length')
    at C:\Users\tunji\Desktop\webdev\todolist-v2-starting-files\node_modules\mongoose\lib\model.js:3519:47
    at collectionOperationCallback (C:\Users\tunji\Desktop\webdev\todolist-v2-starting-files\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:133:26)
    at Timeout.<anonymous> (C:\Users\tunji\Desktop\webdev\todolist-v2-starting-files\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:160:11)
    at listOnTimeout (node:internal/timers:564:17)
    at process.processTimers (node:internal/timers:507:7)

this is the code:
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");

const app = express();
mongoose.connect('mongodb://localhost:27017/todolistDB');

app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));

// const itemsSchema = {
//   name: String
// };

const itemsSchema = new mongoose.Schema({
  name: String
});

const Item = mongoose.model("Item", itemsSchema);

const item1 = new Item({name: "Workout"});
const item2 = new Item({name: "skydive"});
const item3 = new Item({name: "bungee"});

const defaultItems = [item1, item2, item3];

Item.insertMany(defaultItems, function(err){
  if (err){
    console.log(err + "yea");
  } else {
    console.log("good to go");
  }
});

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

  res.render("list", {listTitle: "Today", newListItems: items});

});

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

i've checked the server, deleted and installed the node module ,everything, still no fix,nothing at all

A: I think you cannot connect to mongoose, as per mongoose documentation connect is an async method.
Try waiting for connection to be established, then write to the database
example:
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");

const app = express();
app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));

app.get("/", function(req, res) {
  res.render("list", {listTitle: "Today", newListItems: items});
});

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

async function connect() {
    try {
        await mongoose.connect('mongodb://localhost:27017/todolistDB');
        console.log('Connected to MongoDB');
    } catch (error) {
        console.log('Could not connect to MongoDB');
        throw error;
    }
    const itemsSchema = new mongoose.Schema({
        name: String
    });

    const Item = mongoose.model("Item", itemsSchema);
    const item1 = new Item({name: "Workout"});
    const item2 = new Item({name: "skydive"});
    const item3 = new Item({name: "bungee"});

    const defaultItems = [item1, item2, item3];

    Item.insertMany(defaultItems, function(err){
    if (err){
        console.log(err + "yea");
    } else {
        console.log("good to go");
    }
    });

}

connect();

``

A: Instead of using localhost:27017
Rather use 127.0.0.1:27017
So it should look like this:
mongoose.connect("mongodb://127.0.0.1:27017/todolistDB")


text:
Q: How Can I Output Enterprise Features List To CSV? I am trying to output to a CSV file the list of activate enterprise features in our sites with DisplayName, GUID and Scope as the content that is written to the CSV file.
I have the following Powershell script but it does not output the DisplayName or the Scope or the GUID - it will only output the url and title of the site that the feature is activated on:
$sites = Get-SPSite -Limit All -ErrorAction SilentlyContinue

foreach ($site in $sites)
{
    $webs = Get-SPWeb -site $site.Url -Limit ALL -ErrorAction SilentlyContinue

foreach ($web in $webs)
{

    $premiumfeatures = Get-SPFeature "SharePoint Server Enterprise Site features" -Web $web.Url -ErrorAction SilentlyContinue | select DisplayName, Scope, ID | Sort -Property Scope,DisplayName | FT -GroupBy Scope DisplayName,Id

    foreach ($premiumfeature in $premiumfeatures)
    {
        $featureEnabled = "Feature Enabled On: " + $web.Url + " " + $web.Title + " " + $premiumfeature.DisplayName
        Write-Host $featureEnabled
        Add-Content c:\activated_enterprise_features.csv $featureEnabled
    }
    $web.Dispose()
}
$site.Dispose()
}

How can I output the DisplayName, Scope and ID for a feature to CSV?

A: You can use this command simply
Get-SPFeature -Site "siteurl" | Sort DisplayName | FT DisplayName,scope,Id  > Desktop\feature.csv

FYI:- Powershell command to find active features for site collection

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to access the dynamically created controls In my website I am able to create controls (textbox and dropdown) dynamically using UPDATE PANEL control. But I am unable to access these controls. Even while viewing in source code in the browser during debug, the dynamically created controls are absent! I am wondering how come we are able to see the dynamicallly created controls while the definition for them are absent in the source view of the o/p. Could you please clear my this doubt. Thanks a lot.
Code:

    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel11" runat="server">
        <ContentTemplate>
            <%--<asp:UpdatePanel ID="updPnlAssociatedInc" runat="server" UpdateMode="Conditional">
                                                <ContentTemplate>--%>
            <asp:Label ID="lblcount" runat="server" Text="1" Visible="false"></asp:Label>
            <asp:Table ID="someTBL" runat="server" Style="width: 100%">
                <asp:TableRow>
                    <asp:TableCell HorizontalAlign="right" Style="width: 200px">
                        <asp:Label ID="lblAssociatedIncNo" runat="server" Text="Associated Incident(s)# :"></asp:Label>

                            <asp:Button runat="server" ID="BtnAddAssoInc" OnClick="btnAddNewRowAssocInc_Click"
                                Text="Add Associated Incidents" />

                    </asp:TableCell>
                    <asp:TableCell HorizontalAlign="left" Style="width: 320px;">
                        <asp:TextBox ID="txtAssocIncRec0" name = "txtAssoc0" runat="server" MaxLength="12"></asp:TextBox>
                    </asp:TableCell>
                    <asp:TableCell HorizontalAlign="right" Style="width: 200px">
                        <asp:Label ID="lblAssociatedSeverity" runat="server" Text="Severity :"></asp:Label>
                    </asp:TableCell>
                    <asp:TableCell HorizontalAlign="left" Style="width: 320px;">
                        <asp:DropDownList ID="ddlbAssocIncRec0" name="ddlbAssoc0" runat="server">
                        </asp:DropDownList>
                    </asp:TableCell>
                </asp:TableRow>

            </asp:Table>
        </ContentTemplate>
    </asp:UpdatePanel>

and the corresponding code behind is
        protected void Page_Load(object sender, EventArgs e)
    {
        int intRowCount = Convert.ToInt32(ViewState["No_of_Rows"]);
        for (int i = 1; i <= intRowCount; i++)
        {
            TableRow row = new TableRow();
            TableCell cell1 = new TableCell();
            TableCell cell2 = new TableCell();
            TableCell cell3 = new TableCell();
            TableCell cell4 = new TableCell();
            TextBox tb = new TextBox();
            DropDownList ddl = new DropDownList();
            Label lbl1 = new Label();
            Label lbl2 = new Label();

            row.ID = "rwAssocIncRec" + i;

            cell1.ID = "cAssocIncRec" + i + "1";
            cell2.ID = "cAssocIncRec" + i + "2";
            cell3.ID = "cAssocIncRec" + i + "3";
            cell4.ID = "cAssocIncRec" + i + "4";
            cell2.Attributes.Add("align", "left");
            cell4.Attributes.Add("align", "left");

            tb.ID = "txtAssocIncRec" + i;
            tb.MaxLength = 12;
            tb.EnableViewState = true;

            lbl1.ID = "lblAssocIncRec" + i + "01";
            lbl2.ID = "lblAssocIncRec" + i + "02";

            ddl.ID = "ddlbAssocIncRec" + i;

            cell1.Controls.Add(lbl1);
            cell2.Controls.Add(tb);
            cell3.Controls.Add(lbl2);
            cell4.Controls.Add(ddl);
            ddl.Items.Add(new ListItem("--Select--", "0"));
            ddl.Items.Add(new ListItem("1", "1"));
            ddl.Items.Add(new ListItem("2", "2"));

            row.Cells.Add(cell1);
            row.Cells.Add(cell2);
            row.Cells.Add(cell3);
            row.Cells.Add(cell4);

            someTBL.Rows.Add(row);
        }

    }
    protected void btnAddNewRowAssocInc_Click(object sender, EventArgs e)
    {

        TableRow newRow = new TableRow();
        newRow.ID = "trAssocIncRec" + lblcount.Text;

        TableCell newCell1 = new TableCell();
        newCell1.ID = "tdAssocIncRec1" + lblcount.Text;
        Label lbl = new Label();
        lbl.Text = "";
        lbl.ID = "lblAssocIncRec" + lblcount.Text;
        newCell1.Controls.Add(lbl);
        newRow.Cells.Add(newCell1);

        TableCell newCell2 = new TableCell();
        newCell2.ID = "tdAssocIncRec2" + lblcount.Text;
        TextBox txtBox = new TextBox();
        txtBox.ID = "txtAssocIncRec" + lblcount.Text;
        txtBox.MaxLength = 12;
        newCell2.Attributes.Add("align", "left");
        newCell2.Controls.Add(txtBox);
        newRow.Cells.Add(newCell2);

        TableCell newCell3 = new TableCell();
        newCell3.ID = "tdAssocIncRec3" + lblcount.Text;
        Label lbl2 = new Label();
        lbl2.Text = "";
        lbl2.ID = "lblAssocIncRec2" + lblcount.Text;
        newCell3.Controls.Add(lbl2);
        newRow.Cells.Add(newCell3);

        TableCell newCell4 = new TableCell();
        newCell4.ID = "tdAssocIncRec4" + lblcount.Text;
        DropDownList ddlb = new DropDownList();
        ddlb.ID = "ddlbAssocIncRec" + lblcount.Text;
        newCell4.Attributes.Add("align", "left");
        newCell4.Controls.Add(ddlb);
        ddlb.Items.Add(new ListItem("--Select--", "0"));
        ddlb.Items.Add(new ListItem("1", "1"));
        ddlb.Items.Add(new ListItem("2", "2"));
        newRow.Cells.Add(newCell4);

        someTBL.Rows.Add(newRow);
        ViewState["No_of_Rows"] = Convert.ToInt32(lblcount.Text);

        lblcount.Text = Convert.ToString(Convert.ToInt32(lblcount.Text) + 1);

    }

A: What you need to do is recreate these in either the Load event, or the Init event of the page every time. This is so that the values can be retrieved.
I would then find the controls you have created and add them to a list in a viewstate(so it gets destroyed when the user leaves the page)
ViewState["DynamicControls"] = list;

Then you have the values stored which you can come back to.


text:
Q: Error when removing white spaces with trim functions C++ I have a cpp file that grabs lines and trims them but i'm getting an error.
The error says:
error C2784: 'std::basic_istream<_Elem,_Traits> &std::getline(std::basic_istream<_Elem,_Traits> &,std::basic_string<_Elem,_Traits,_Alloc> &)' : could not deduce template argument for 'overloaded function type' from 'overloaded function type'
I'm not sure what it means... but this is the script...:
#include <string>
#include <iostream>
#include <algorithm>
#include <vector>
#include <fstream>
#include <cctype>
#include "settings.h"

using namespace std;

// trim from start
static inline std::string& line_trim(std::string& s) {

    //erase
    s.erase(
            //pointer start location
            s.begin(),

            //find from pointer which is set to begin
                std::find_if( s.begin(),
            //check to the end
                s.end(),
            //look for spaces
                std::not1( std::ptr_fun<int, int>(std::isspace) ) ) );

    //return the result
        return s;
}

// trim from end
static inline std::string& end_trim(std::string& s) {

    //erase
    s.erase(

            //find from the pointer set to end of line
                std::find_if(s.rbegin(),

            //check to the beginning (because were starting from end of line
                s.rend(),

            //look for spaces
                std::not1(std::ptr_fun<int, int>(std::isspace))).base(),
                s.end());
        return s;
}

static inline std::string& trim(std::string &s) {
    return line_trim(end_trim(s));
}

ifstream file(std::string file_path){
string line;

    std::map<string, string> config;

    while(std::getline(file, line))
    {
        int pos = line.find('=');
        if(pos != string::npos)
        {
            string key = line.substr(0, pos);
            string value = line.substr(pos + 1);
            config[trim(key)] = trim(value);
        }
    }
    return (config);
}

The error is occuring in the 3rd function on this like:
while(std::getline(file, line))
EDIT: This is my settings.h
#include <map>
using namespace std;

static inline std::string &line_trim(std::string&);

static inline std::string &end_trim(std::string&);

static inline std::string &trim(std::string&);

std::map<string, string> loadSettings(std::string);

Any ideas what I'm doing wrong?

A: Where is the var file?
ifstream file(std::string file_path){
string line;

    std::map<string, string> config;

    while(std::getline(file, line))

In here file is function, and getline expects basic_istream
thus the failure

A: I'm piecing two and two together based on your settings.h file... I think you've forgotten to write out your function header.  This bit:
ifstream file(std::string file_path){
string line;

    std::map<string, string> config;

should be:
std::map<string, string> loadSettings(std::string file_path) {
    ifstream file(file_path);
    string line;
    std::map<string, string> config;

With your current implementation, file is a function (because it has scope from the opening {), so it is not the expected argument to getline.


text:
Q: HTML5 Cache Manifest: Fallback for external resources I'm trying to create a manifest like :
CACHE MANIFEST

CACHE:
offline.jpg
http://externalSite/cacheDemo/offline.jpg

FALLBACK:
/   offline.jpg
http://externalSite/    http://externalSite/cacheDemo/offline.jpg

and then in my html

I get the fallback for the local unavailable image to work, but no for the external... is it possible to specify fallbacks for external resources? Cant find documentation about this in particular...

A: It's unfortunate that it's outside of the specification, and I haven't found any solid justification on why. This is a legitimate need for anyone using a CDN, or for developers developing as 12 factor style application (e.g. for hosting on Heroku), where uploaded images can not modify local state, and instead need to be saved to an attached resource.
Luckily, we can still accomplish what we need in Javascript, but it varies depending on the type of resource you're trying to fallback for.
For images specifically, you can rely on the onError attribute:

Note that we're wiping out the onError to prevent infinite loops if the fallback image isn't available. You can read more strategies about this at: jQuery/JavaScript to replace broken images
For .js or .css, however, this technique is not as reliable, because their onError attribute isn't as supported. However, situations for falling back on offsite .js and .css are less common, since normally you can explicitly cache all of those resources in advance.


text:
Q: I get the following error for all my android projects after updating android sdk and adt plugin for eclipse Following is a screenshot of the error.

Click for full size.

A: Try adding this to the manifest.
<manifest>
      .....
      <uses-sdk android:minSdkVersion="lowest_sdk_supported" />
</manifest>

Its one of the warnings that says "Application does not specify an API level requirement.


text:
Q: Hidden class css I try to create project on frontendMentor and have an issue. When i complete the form and click button element form doesnt hide. There are many new lines and this element is on the bottom. What is the problem?
Code:

const cardName = document.querySelector('.name');
const cardNumber = document.querySelector('.number');
const cardMonth = document.querySelector('.month');
const cardYear = document.querySelector('.year');
const cardCode = document.querySelector('.code');
const btn = document.querySelector('.button');
const resultName = document.querySelector('.card__name');
const resultNumber = document.querySelector('.header__cards-number');
const resultExpiry = document.querySelector('.card__expiry');
const resultCvv = document.querySelector('.header__cvv');
const summary = document.querySelector('.summary');
const form = document.querySelector('.form');
// const resultDate = document.querySelector();
btn.addEventListener('click', function () {
    resultName.innerHTML = cardName.value;
    resultNumber.innerHTML = cardNumber.value;
    resultExpiry.innerHTML = `${cardMonth.value}/${cardYear.value}`;
    resultCvv.innerHTML = cardCode.value;
    summary.classList.remove('hidden');
    form.classList.add('hidden');
});
$white: hsl(0, 0%, 100%);
$lightGrayishViolet: hsl(270, 3%, 87%);
$darkGrayishViolet: hsl(279, 6%, 55%);
$veryDarkViolet: hsl(278, 68%, 11%);
$red: hsl(0, 100%, 66%);
$linearGradient: hsl(249, 99%, 64%) to hsl(278, 94%, 30%);

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-size: 18px;
    font-family: 'Space Grotesk', sans-serif;
    height: 100vh;
    width: 100%;
    max-width: 375px;
    display: flex;
    flex-direction: column;
    font-weight: 500;
}

.header {
    flex-basis: 35%;
    background-image: url('../images/bg-main-mobile.png');
    &__card {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 300px;
        height: 150px;

        border-radius: 0.5em;
    }

    &__cards {
        &-back {
            position: relative;
            margin-top: 1.5em;
            margin-left: 3em;
            background-color: $white;
        }
        &-front {
            display: flex;
            flex-direction: column;
            position: absolute;
            background-image: url('../images/bg-card-front.png');
            color: $white;
            top: 117px;
            left: 15px;

            z-index: 10;
            overflow: hidden;
            padding: 1em 1em;
        }
        &-logo {
            flex-basis: 50%;
            width: 100%;

            svg {
                text-align-last: left;
                margin-left: -1em;
                transform: scale(0.5);
            }
        }
        &-number {
            flex-basis: 20%;
            width: 100%;
            text-align: center;
            letter-spacing: 2px;
        }
        &-details {
            width: 100%;
            flex-basis: 30%;
            display: flex;
            justify-content: space-between;
            align-items: flex-end;
            text-align: center;
            font-size: 0.7em;
            letter-spacing: 2px;
            text-transform: uppercase;
        }
    }

    &__magneticbar {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 30px;
        margin-top: 1em;
        background-color: #333;
    }
    &__cvv {
        width: 80%;
        height: 30px;
        text-align: right;
        padding-right: 1em;
        background-color: $lightGrayishViolet;
        line-height: 30px;
        border-radius: 0.2em;
        color: $white;
        font-size: 0.7em;
        color: $white;
        letter-spacing: 2px;
    }

    .content {
        flex-basis: 65%;
    }
}

.content {
    flex-basis: 65%;
    padding: 1em;

    .description {
        text-transform: uppercase;
        letter-spacing: 2px;
        font-size: 0.7em;
        text-align: left;
        color: $veryDarkViolet;
        margin-bottom: 0.3em;
    }
    .form {
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: flex-end;
        align-items: center;
        text-align: center;

        &__item {
            width: 100%;
            margin-bottom: 0.5em;
            input {
                width: 100%;
                height: 3em;
                border-radius: 0.3em;
                border: 1px solid $lightGrayishViolet;
            }
            input::placeholder {
                font-size: 1.3em;
                color: $lightGrayishViolet;
            }
        }

        &__row {
            display: flex;

            .form__item {
                input {
                    width: 23%;
                    text-align: center;
                }
                .code {
                    width: 50%;
                }
                span {
                    margin-left: 2em;
                }
            }
        }
        &__button {
            width: 100%;
            height: 3em;
            margin-top: 1em;
            margin-bottom: 2em;
            line-height: 3em;
            background-color: $veryDarkViolet;
            color: $white;
            border-radius: 0.5em;
        }
    }
}

.summary {
    display: flex;
    height: 100%;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    text-align: center;
    &__icon {
        margin: 2em 0;
    }
    &__text {
        h1 {
            text-transform: uppercase;
            letter-spacing: 3px;
        }
        p {
            color: $darkGrayishViolet;
            margin: 1em 0;
        }
    }
    &__button {
        margin-top: 2em;
        background-color: lime;
    }
}

.hidden {
    display: none;
}
<!DOCTYPE html>

        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />

        <link
            rel="icon"
            type="image/png"
            sizes="32x32"
            href="./images/favicon-32x32.png"
        />

        <title>Frontend Mentor | Interactive card details form</title>
        <link rel="preconnect" href="https://fonts.googleapis.com" />
        <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
        <link
            href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@500&display=swap"
            rel="stylesheet"
        />
        <link rel="stylesheet" href="./css/style.css" />

000

                        <svg
                            width="84"
                            height="47"
                            fill="none"
                            xmlns="http://www.w3.org/2000/svg"
                        >
                            <ellipse
                                cx="23.478"
                                cy="23.5"
                                rx="23.478"
                                ry="23.5"
                                fill="#fff"
                            />
                            <path
                                d="M83.5 23.5c0 5.565-4.507 10.075-10.065 10.075-5.559 0-10.065-4.51-10.065-10.075 0-5.565 4.506-10.075 10.065-10.075 5.558 0 10.065 4.51 10.065 10.075Z"
                                stroke="#fff"
                            />
                        </svg>

0000 0000 0000 0000

Jane Appleseed

00/00

                    <svg
                        width="80"
                        height="80"
                        fill="none"
                        xmlns="http://www.w3.org/2000/svg"
                    >
                        <circle cx="40" cy="40" r="40" fill="url(#a)" />
                        <path
                            d="M28 39.92 36.08 48l16-16"
                            stroke="#fff"
                            stroke-width="3"
                        />
                        <defs>
                            <linearGradient
                                id="a"
                                x1="-23.014"
                                y1="11.507"
                                x2="0"
                                y2="91.507"
                                gradientUnits="userSpaceOnUse"
                            >
                                <stop stop-color="#6348FE" />
                                <stop offset="1" stop-color="#610595" />
                            </linearGradient>
                        </defs>
                    </svg>

Thank you!

We've added your card details

Continue

Cardholder Name

                    <input
                        type="text"
                        name="name"
                        id="name"
                        class="name"
                        placeholder=" e.g. Jane Appleseed"
                    />

Card Number

                    <input
                        type="text"
                        name="number"
                        id="number"
                        class="number"
                        placeholder="e.g. 1234 5678 9123 0000"
                        maxlength="19"
                    />

                            Exp. Date (MM/YY)CVC

                        <input
                            type="text"
                            name="month"
                            id="month"
                            class="month"
                            placeholder="MM"
                            maxlength="2"
                            minlength="2"
                        />
                        <input
                            type="text"
                            name="year"
                            id="year"
                            class="year"
                            placeholder="YY"
                            maxlength="2"
                            minlength="2"
                        />
                        <input
                            type="text"
                            name="code"
                            id="code"
                            class="code"
                            placeholder="e.g. 123"
                            minlength="3"
                            maxlength="3"
                        />

Confirm

I add some images too
I know that my code is bad but i dont use any tutorials and hints.

A: Because of specificity.
In your SASS(?) your .form is nested inside .content which when compiled looks something like this .content .form { ... and this has higher specificity than .hidden, so make it more specific to override or use !important:

.content .form {
  display: flex;
  height: 80px;
  background-color: lightblue;
}

.hidden {
  display: none;
}

/* More specific */
.content .form.super-hidden {
  display: none;
}

/* Using !important */
.important-hidden {
  display: none !important;
}

I am visible to the world

Why am i not hidden?

I am definitely hidden

I am definitely hidden

A: It took me some time to do this, but you can also try this. Maybe it helps.

const confButton = document.getElementById("confButton");
const actSect = document.getElementById("active");
const hidSect = document.getElementById("hidden");

confButton.addEventListener("click", () => {
  actSect.classList.remove("active");
  actSect.classList.add("hidden");

  hidSect.classList.remove("hidden");
  hidSect.classList.add("active");

});
:root {
  --white:              hsl(0, 0%, 100%);
  --lightGrayishViolet: hsl(270, 3%, 87%);
  --darkGrayishViolet:  hsl(279, 6%, 55%);
  --veryDarkViolet:     hsl(278, 68%, 11%);
  --red:                hsl(0, 100%, 66%);
  --linearGradient:     hsl(249, 99%, 64%) to hsl(278, 94%, 30%);
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

section {
  display:         flex;
  flex-direction:  column;
  align-items:     center;
  justify-content: space-between;
  padding:         1rem;
  height:          100vh;
  width:           100%;
}

body {
  font-size:       18px;
  font-family:     "Space Grotesk", sans-serif;
  height:          100vh;
  width:           100%;
  max-width:       375px;
  display:         flex;
  flex-direction:  column;
  font-weight:     500;
}

.header__card {
  display:         flex;
  justify-content: center;
  align-items:     center;
  width:           300px;
  height:          150px;
  border-radius:   0.5em;
}

.header__cards-back {
  position:          relative;
  margin-top:        1.5em;
  margin-left:       3em;
  background-color:  var(--white);
}

.header__cards-front {
  display:             flex;
  flex-direction:      column;
  position:            absolute;
  background:          rgb(137, 119, 241);
  background:          linear-gradient( 124deg, rgba(137, 119, 241, 1) 0%, rgba(116, 81, 245, 1) 16%, rgba(116, 55, 231, 1) 39%, rgba(194, 73, 219, 1) 64%, rgba(179, 119, 176, 1) 78%, rgba(108, 144, 220, 1) 100%);
  color:              var(--white);
  top:                117px;
  left:               15px;
  z-index:            10;
  overflow:           hidden;
  padding:            1em 1em;
}

.header__cards-logo {
  flex-basis:         50%;
  width:              100%;
}

.header__cards-logo svg {
  text-align-last:    left;
  margin-left:        -1em;
  transform:          scale(0.5);
}

.header__cards-number {
  flex-basis:         20%;
  width:              100%;
  text-align:         center;
  letter-spacing:     2px;
}

.header {
  flex-basis:         35%;
  padding:            .5rem;
  background:         rgb(35, 14, 55);
  background:         linear-gradient( 144deg, rgba(35, 14, 55, 1) 0%, rgba(69, 27, 62, 1) 62%, rgba(33, 8, 46, 1) 100%);
}

.header__cards-details {
  width:               100%;
  flex-basis:          30%;
  display:             flex;
  justify-content:     space-between;
  align-items:         flex-end;
  text-align:          center;
  font-size:           0.7em;
  letter-spacing:      2px;
  text-transform:      uppercase;
}

.header__magneticbar {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 30px;
  margin-top: 1em;
  background-color: #333;
}

.header__cvv {
  width: 80%;
  height: 30px;
  text-align: right;
  padding-right: 1em;
  background-color: var(--lightGrayishViolet);
  line-height: 30px;
  border-radius: 0.2em;
  color: var(--white);
  font-size: 0.7em;
  color: var(--white);
  letter-spacing: 2px;
}

.content {
  flex-basis: 65%;
}

.description {
  text-transform: uppercase;
  letter-spacing: 2px;
  font-size: 0.7em;
  text-align: left;
  color: var(--veryDarkViolet);
  margin-bottom: 0.3em;
}

.form__item {
  width: 100%;
  margin-bottom: 0.5em;
}

.form__item input {
  width: 100%;
  height: 3em;
  border-radius: 0.3em;
  border: 1px solid var(--lightGrayishViolet);
}

.form__item input::placeholder {
  font-size: 1.3em;
  color: var(--lightGrayishViolet);
}

.form__item input {
  width: 100%;
  text-align: center;
}

.form__row .form__item input {
  width: 23%;
}

.form__item .code {
  width: 50%;
}

.form__item span {
  margin-left: 2em;
}

.form__button {
  width: 100%;
  height: 3em;
  margin-top: 1em;
  margin-bottom: 2em;
  line-height: 3em;
  background-color: var(--veryDarkViolet);
  color: var(--white);
  border-radius: 0.5em;
}

.form {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  align-items: center;
  text-align: center;
}

.content {
  flex-basis: 65%;
  padding: 1em;
}

.summery__text h1 {
  text-transform: uppercase;
  letter-spacing: 3px;
}

.summery__text p {
  color: var(--darkGrayishViolet);
  margin: 1em 0;
}

.summery__icon {
  margin: 2em 0;
}

.summery__button {
  margin-top: 2em;
  background-color: lime;
}

.summary {
  display: flex;
  height: 100%;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
}

.hidden {
  display: none;
}

000

          <svg width="84" height="47" fill="none" xmlns="http://www.w3.org/2000/svg">
                <ellipse
                  cx="23.478"
                  cy="23.5"
                  rx="23.478"
                  ry="23.5"
                  fill="#fff"
                />
                <path
                  d="M83.5 23.5c0 5.565-4.507 10.075-10.065 10.075-5.559 0-10.065-4.51-10.065-10.075 0-5.565 4.506-10.075 10.065-10.075 5.558 0 10.065 4.51 10.065 10.075Z"
                  stroke="#fff"
                />
              </svg>

0000 0000 0000 0000

Jane Appleseed

00/00

        <svg width="80" height="80" fill="none" xmlns="http://www.w3.org/2000/svg">
              <circle cx="40" cy="40" r="40" fill="url(#a)" />
              <path
                d="M28 39.92 36.08 48l16-16"
                stroke="#fff"
                stroke-width="3"
              />
              <defs>
                <linearGradient
                  id="a"
                  x1="-23.014"
                  y1="11.507"
                  x2="0"
                  y2="91.507"
                  gradientUnits="userSpaceOnUse"
                >
                  <stop stop-color="#6348FE" />
                  <stop offset="1" stop-color="#610595" />
                </linearGradient>
              </defs>
            </svg>

Thank you!

We've added your card details

Continue

Cardholder Name

        <input type="text" name="name" id="name" class="name" placeholder=" e.g. Jane Appleseed" />

Card Number

        <input type="text" name="number" id="number" class="number" placeholder="e.g. 1234 5678 9123 0000" maxlength="19" />

Exp. Date (MM/YY)CVC

          <input type="text" name="month" id="month" class="month" placeholder="MM" maxlength="2" minlength="2" />
          <input type="text" name="year" id="year" class="year" placeholder="YY" maxlength="2" minlength="2" />
          <input type="text" name="code" id="code" class="code" placeholder="e.g. 123" minlength="3" maxlength="3" />

Confirm

Thank you


text:
Q: Loading a gif from URL in Processing with gifAnimation Library I am currently trying to load a gif into a processing sketch from a url. I am using the gifAnimation library and when I load a gif stored on my computer it works fine. I just cant seem to get it when I load from url, nothing shows up. Currently I can load the first frame using default Processing like this:
webGif= loadImage(url, "gif");
image(webGif,0,0,720,720);

If I try and load a gif using the library from the url
webGif= new Gif(this, url);
image (webGif, 0 , 0);
webGif.loop();

It doesn't load anything and my program freezes.

A: Loading a gif from URL seems to work as expected:
import gifAnimation.*;

Gif loopingGif;
public void setup() {
  size(400, 200);
  frameRate(100);

  loopingGif = new Gif(this, "https://s-media-cache-ak0.pinimg.com/originals/1f/d4/83/1fd4831252c28010546e872d5b85bb70.gif");
  loopingGif.loop();
}

void draw() {
  background(255 / (float)height * mouseY);
  image(loopingGif, 10, height / 2 - loopingGif.height / 2);
}

tested with gifAnimation 3.1 using Processing 3.2.3
Also double check the URL is valid and the file is a valid gif, before checking Processing and library versions.


text:
Q: Reshaping the output of a logistic regression I have defined a logistic regression model as a network with one layer followed by a sigmoid activation using tf.layers. The predictions come out as a 2D tensor of shape (n,1), n being the size of the batch. However, in order to calculate the loss function, I need a 1D tensor of shape n. Of course I can reshape the tensor (and that's what I currently do), but somehow it feels like there should be something more elegant to do. Is there?

Code to reproduce the issue
import tensorflow as tf
import numpy as np

data = np.random.random((20, 6))
data[:, -1] = data[:, -1] > 0.5

e = tf.data.Dataset.from_tensor_slices(data).batch(2).make_one_shot_iterator().get_next()
x, y_ = e[:, :-1], e[:, -1]

y = tf.layers.dense(x, 1, activation=tf.nn.sigmoid)
loss_wrong = - tf.reduce_mean(tf.add(tf.multiply(y_, tf.log(y)), tf.multiply((1. - y_), tf.log(1. - y))))

y2 = tf.reshape(y, [-1])  # ugly reshape I would like to get rid of
loss_correct = - tf.reduce_mean(tf.add(tf.multiply(y_, tf.log(y2)), tf.multiply((1. - y_), tf.log(1. - y2))))

with tf.Session() as sess:
    tf.global_variables_initializer().run()

    a, b, b2, lw, lc = sess.run([y_, y, y2, loss_wrong, loss_correct])
    print(a)  # a 1D array with the real labels
    print(b)  # a dangerous array of arrays!
    print(b2)  # notice how nice and flat this is
    print(lw)  # wrong when all labels are not the same
    print(lc)  # correct (can test by hand with the data printed)

A: There is tf.squeeze (docs). This removes all axes of size 1. So
y2 = tf.squeeze(y)

Note however that this can lead to issues if some variable dimension (e.g. batch size) also ever happens to be 1 -- squeeze will remove such axes as well (which you probably don't want). You can use
y2 = tf.squeeze(y, axis=1)

to prevent this (note that this will crash in case axis 1 does not have size 1!).
Interestingly, it seems like tf.squeeze will always result in at least a 1d tensor, never a scalar. This is different from the numpy version. I.e.
tf.squeeze([[1]]) -> array([1])
np.squeeze([[1]]) -> array(1)

Hope this is elegant enough.


text:
Q: Entity Framework populate only the database fields in domain model I have a domain model that has a properties that don't exist in the database. For example ...
public class DomainModel: IKeyedEntity
{
    //Id for the table
    public int DomainModelID { get; set; }

    //Foreign key value
    public int FooID { get; set; }

    //Text value
    public string Value { get; set; }

    //Generic reference to the id of the table
    public int Key { get { return this.DomainModelID; } }

    //No a column in the database
    public Guid ArchiveIdentifier
    {
        get { return Foo.ArchiveIdentifier; }
        set { Foo.ArchiveIdentifier = value }
    }

    //Navigation Property
    public virtual Foo Foo { get; set; }
}

As you can see the properties Key and ArchiveIdentifier are not columns in the DomainModels table. When I run a query Entity Framework treats the property ArchiveIdentifier as if it was a column in the database. Here is an example of the generated SQL when fetching all DomainModels.
SELECT
[Extent1].[DomainModelID] AS [DomainModelID],
[Extent1].[FooID] AS [FooID],
[Extent1].[Value] AS [Value],
[Extent1].[ArchiveIdentifier] AS [ArchiveIdentifier]
FROM  [dbo].[DomainModels] AS [Extent1]

Entity Framework doesn't try to populate the Key property since it doesn't have a set method however it treats ArchiveIdentifier as if it was a column in the table. Is there any annotation or method to tell Entity Framework that ArchiveIdentifier is not a column?

A: Use the NotMappedAttribute:
[NotMapped]
public Guid ArchiveIdentifier
{
    get { return Foo.ArchiveIdentifier; }
    set { Foo.ArchiveIdentifier = value; }
}

A: Use [NotMapped] data annotation on your ArchiveIdentifier property


text:
Q: Do I get more reputation from keeping a majority species happy? My settlements often end up very specialised. For example, my last settlement had about 70% humans.
When it comes to reputation gain from resolve, would making the humans happy give more reputation than keeping the single harpy above the threshold? If not, am I better off investing in those minorities since I'd need far less to keep one harpy happy than a large number of humans?

A: The rate is based on population. This means that yes, keeping more populous species happy gives faster reputation. This screenshot shows the extreme- a single happy harpy earns 0.01 reputation/minute.

This would take 100 minutes- approximately 10 in game years- to earn a single reputation point.


text:
Q: Given $f(x) =\frac{2}{x}$, find $f'(x)$ by determining $\lim \limits_{x\to a} \frac{f(x)-f(a)}{x-a}$ I already solved this problem and got $\frac{2}{a^2}$. However I am not sure if I solved it correctly.

A: $$\lim \limits_{x\to a} \frac{\frac 2x-\frac{2}{a}}{x-a} = \lim \limits_{x\to a} \frac{\frac{2a - 2x}{xa}}{x-a} = -2\lim_{x \to a} \frac{x-a}{xa(x-a)} = -2\lim_{x \to a} \frac{1}{xa} = -\frac{2}{a^2}$$


text:
Q: v-data-table: bind a custom property to "items" slot I need to create a table where every row represents an item. In the first column, I'm going to use a v-autocomplete component for choosing the item from a List of objects. Since the v-autocomplete is going to be inserted in the item template of v-data-table, I'm having problems binding a computed property to "v-bind:items" of v-autocomplete. The computed property is in the same file but it can't be found.
I tried to bind the computed property to the template with no result.
<template>
  <v-data-table
    :headers="headers"
    :items="desserts"
    class="elevation-1"
  >
    <template slot="items" slot-scope="props">

        <v-autocomplete
          :items="saleables"
          :item-text="i => i.name"
          :item-value="i => i.id"
          hide-details
        ></v-autocomplete>

      {{ props.item.calories }}
      {{ props.item.fat }}
      {{ props.item.carbs }}
      {{ props.item.protein }}
    </template>
  </v-data-table>
<template>

[...]
computed: {
  saleables: function () {
    return this.$store.getters['saleables/items']
  }
}
[...]

A: You should wrap your template by <v-app> tag as follows:
  <template>
     <v-app>
      <v-data-table ...
        ...
      </v-data-table>
    </v-app>
 <template>

as mentioned in official docs:

In order for your application to work properly, you must wrap it in a v-app component. This component is required for determining grid breakpoints for the layout. This can exist anywhere inside the body, but must be the parent of ALL Vuetify components. v-content needs to be a direct descendant of v-app.


text:
Q: GMP(MPIR) linker errors on linux I wrote a public-private key generator using mpir(on windows) and it works fine.
When I try to compile it on a linux machine using gmp library, it throws a whole bunch of linker errors.
/usr/bin/ld: /usr/lib/debug/usr/lib/crt1.o(.debug_info): relocation 0 has invali
d symbol index 11
/usr/bin/ld: /usr/lib/debug/usr/lib/crt1.o(.debug_info): relocation 1 has invali
d symbol index 12
/usr/bin/ld: /usr/lib/debug/usr/lib/crt1.o(.debug_info): relocation 2 has invali
d symbol index 2
/usr/bin/ld: /usr/lib/debug/usr/lib/crt1.o(.debug_info): relocation 3 has invali
d symbol index 2
/usr/bin/ld: /usr/lib/debug/usr/lib/crt1.o(.debug_info): relocation 4 has invali
d symbol index 11
/usr/bin/ld: /usr/lib/debug/usr/lib/crt1.o(.debug_info): relocation 5 has invali
d symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/crt1.o(.debug_info): relocation 6 has invali
d symbol index 13
...
/usr/lib/gcc/x86_64-linux-gnu/4.4.3/../../../../lib/crt1.o: In function `_start'
:
(.text+0x20): undefined reference to `main'
collect2: ld returned 1 exit status

I'm using g++ -lgmp prime.cpp. I haven't used any non-gmp function. Any idea? I'm not adding code as there's a lot of it.

A:
I'm using g++ -lgmp prime.cpp

This command line is broken in two ways:

*

*You neglected to provide definiton of main

*You specified library before source that references it. Should be:
g++ main.cpp prime.cpp -lgmp
The order of libraries and sources/objects on command line matters.
Update:

There are several files.. main file depends on them, so before building it.. I was trying to build the other files.

In that case, correct command is:
# Compile, but don't link, prime.cpp
g++ -c prime.cpp


text:
Q: Waste in memory allocation for local variables This my program:
void test_function(int a, int b, int c, int d){
    int flag;
    char buffer[10];

   flag = 31337;
   buffer[0] = 'A';
}

int main() {
    test_function(1, 2, 3, 4);
}

I compile this program with the debug option:
gcc -g my_program.c

I use gdb and I disassemble the test_function with intel syntax:
(gdb) disassemble test_function
Dump of assembler code for function test_function:
0x08048344 <test_function+0>:   push   ebp
0x08048345 <test_function+1>:   mov    ebp,esp
0x08048347 <test_function+3>:   sub    esp,0x28
0x0804834a <test_function+6>:   mov    DWORD PTR [ebp-12],0x7a69
0x08048351 <test_function+13>:  mov    BYTE PTR [ebp-40],0x41
0x08048355 <test_function+17>:  leave
0x08048356 <test_function+18>:  ret
End of assembler dump.

And I disassemble the main:
(gdb) disassemble main
Dump of assembler code for function main:
0x08048357 <main+0>:    push   ebp
0x08048358 <main+1>:    mov    ebp,esp
0x0804835a <main+3>:    sub    esp,0x18
0x0804835d <main+6>:    and    esp,0xfffffff0
0x08048360 <main+9>:    mov    eax,0x0
0x08048365 <main+14>:   sub    esp,eax
0x08048367 <main+16>:   mov    DWORD PTR [esp+12],0x4
0x0804836f <main+24>:   mov    DWORD PTR [esp+8],0x3
0x08048377 <main+32>:   mov    DWORD PTR [esp+4],0x2
0x0804837f <main+40>:   mov    DWORD PTR [esp],0x1
0x08048386 <main+47>:   call   0x8048344 <test_function>
0x0804838b <main+52>:   leave
0x0804838c <main+53>:   ret
End of assembler dump.

I place a breakpoint at this adresse: 0x08048355 (leave instruction for the test_function) and I run the program.
I watch the stack like this:
(gdb) x/16w $esp
0xbffff7d0:     0x00000041      0x08049548      0xbffff7e8      0x08048249
0xbffff7e0:     0xb7f9f729      0xb7fd6ff4      0xbffff818      0x00007a69
0xbffff7f0:     0xb7fd6ff4      0xbffff8ac      0xbffff818      0x0804838b
0xbffff800:     0x00000001      0x00000002      0x00000003      0x00000004

0x0804838b is the return adress, 0xbffff818 is the saved frame pointer (main ebp) and flag variable is stocked 12 bytes further. Why 12?
I don't understand this instruction:
0x0804834a <test_function+6>:   mov    DWORD PTR [ebp-12],0x7a69

Why we don't stock the content's variable 0x00007a69 in ebp-4 instead of 0xbffff8ac?
Same question for buffer. Why 40?
We don't waste the memory? 0xb7fd6ff4 0xbffff8ac and 0xb7f9f729      0xb7fd6ff4 0xbffff818 0x08049548 0xbffff7e8 0x08048249 are not used?
This the output for the command gcc -Q -v -g my_program.c:
Reading specs from /usr/lib/gcc-lib/i486-linux-gnu/3.3.6/specs
Configured with: ../src/configure -v --enable-languages=c,c++ --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --with-gxx-include-dir=/usr/include/c++/3.3 --enable-shared --enable-__cxa_atexit --with-system-zlib --enable-nls --without-included-gettext --enable-clocale=gnu --enable-debug i486-linux-gnu
Thread model: posix
gcc version 3.3.6 (Ubuntu 1:3.3.6-15ubuntu1)
 /usr/lib/gcc-lib/i486-linux-gnu/3.3.6/cc1 -v -D__GNUC__=3 -D__GNUC_MINOR__=3 -D__GNUC_PATCHLEVEL__=6 notesearch.c -dumpbase notesearch.c -auxbase notesearch -g -version -o /tmp/ccGT0kTf.s
GNU C version 3.3.6 (Ubuntu 1:3.3.6-15ubuntu1) (i486-linux-gnu)
        compiled by GNU C version 3.3.6 (Ubuntu 1:3.3.6-15ubuntu1).
GGC heuristics: --param ggc-min-expand=99 --param ggc-min-heapsize=129473
options passed:  -v -D__GNUC__=3 -D__GNUC_MINOR__=3 -D__GNUC_PATCHLEVEL__=6
 -auxbase -g
options enabled:  -fpeephole -ffunction-cse -fkeep-static-consts
 -fpcc-struct-return -fgcse-lm -fgcse-sm -fsched-interblock -fsched-spec
 -fbranch-count-reg -fcommon -fgnu-linker -fargument-alias
 -fzero-initialized-in-bss -fident -fmath-errno -ftrapping-math -m80387
 -mhard-float -mno-soft-float -mieee-fp -mfp-ret-in-387
 -maccumulate-outgoing-args -mcpu=pentiumpro -march=i486
ignoring nonexistent directory "/usr/local/include/i486-linux-gnu"
ignoring nonexistent directory "/usr/i486-linux-gnu/include"
ignoring nonexistent directory "/usr/include/i486-linux-gnu"
#include "..." search starts here:
#include <...> search starts here:
 /usr/local/include
 /usr/lib/gcc-lib/i486-linux-gnu/3.3.6/include
 /usr/include
End of search list.
 gnu_dev_major gnu_dev_minor gnu_dev_makedev stat lstat fstat mknod fatal ec_malloc dump main print_notes find_user_note search_note
Execution times (seconds)
 preprocessing         :   0.00 ( 0%) usr   0.01 (25%) sys   0.00 ( 0%) wall
 lexical analysis      :   0.00 ( 0%) usr   0.01 (25%) sys   0.00 ( 0%) wall
 parser                :   0.02 (100%) usr   0.01 (25%) sys   0.00 ( 0%) wall
 TOTAL                 :   0.02             0.04             0.00
 as -V -Qy -o /tmp/ccugTYeu.o /tmp/ccGT0kTf.s
GNU assembler version 2.17.50 (i486-linux-gnu) using BFD version 2.17.50 20070103 Ubuntu
 /usr/lib/gcc-lib/i486-linux-gnu/3.3.6/collect2 --eh-frame-hdr -m elf_i386 -dynamic-linker /lib/ld-linux.so.2 /usr/lib/gcc-lib/i486-linux-gnu/3.3.6/../../../crt1.o /usr/lib/gcc-lib/i486-linux-gnu/3.3.6/../../../crti.o /usr/lib/gcc-lib/i486-linux-gnu/3.3.6/crtbegin.o -L/usr/lib/gcc-lib/i486-linux-gnu/3.3.6 -L/usr/lib/gcc-lib/i486-linux-gnu/3.3.6/../../.. /tmp/ccugTYeu.o -lgcc --as-needed -lgcc_s --no-as-needed -lc -lgcc --as-needed -lgcc_s --no-as-needed /usr/lib/gcc-lib/i486-linux-gnu/3.3.6/crtend.o /usr/lib/gcc-lib/i486-linux-gnu/3.3.6/../../../crtn.o

NOTE: I read the book "The art of exploitation" and I use the VM provides with the book.

A: The compiler is trying to maintain 16 byte alignment on the stack. This also applies to 32-bit code these days (not just 64-bit). The idea is that at the point before executing a CALL instruction the stack must be aligned to a 16-byte boundary.
Because you compiled with no optimizations there are some extraneous instructions.
0x0804835a <main+3>:    sub    esp,0x18        ; Allocate local stack space
0x0804835d <main+6>:    and    esp,0xfffffff0  ; Ensure `main` has a 16 byte aligned stack
0x08048360 <main+9>:    mov    eax,0x0         ; Extraneous, not needed
0x08048365 <main+14>:   sub    esp,eax         ; Extraneous, not needed

ESP is now 16-byte aligned after the last instruction above. We move the parameters for the call starting at the top of the stack at ESP. That is done with:
0x08048367 <main+16>:   mov    DWORD PTR [esp+12],0x4
0x0804836f <main+24>:   mov    DWORD PTR [esp+8],0x3
0x08048377 <main+32>:   mov    DWORD PTR [esp+4],0x2
0x0804837f <main+40>:   mov    DWORD PTR [esp],0x1

The CALL then pushes a 4 byte return address on the stack. We then reach these instructions after the call:
0x08048344 <test_function+0>:   push   ebp     ; 4 bytes pushed on stack
0x08048345 <test_function+1>:   mov    ebp,esp ; Setup stackframe

This pushes another 4 bytes on the stack. With the 4 bytes from the return address we are now misaligned by 8 bytes. To reach 16-byte alignment again we will need to waste an additional 8 bytes on the stack. That is why in this statement there is an additional 8 bytes allocated:
0x08048347 <test_function+3>:   sub    esp,0x28

*

*0x08 bytes already on stack because of return address(4-bytes) and EBP(4 bytes)

*0x08 bytes of padding needed to align stack back to 16-byte alignment

*0x20 bytes needed for local variable allocation = 32 bytes.
    32/16 is evenly divisible by 16 so alignment maintained

The second and third number above added together is the value 0x28 computed by the compiler and used in sub esp,0x28.
0x0804834a <test_function+6>:   mov    DWORD PTR [ebp-12],0x7a69

So why [ebp-12] in this instruction? The first 8 bytes [ebp-8] through [ebp-1] are the alignment bytes used to get the stack 16-byte aligned. The local data will then appear on the stack after that. In this case [ebp-12] through [ebp-9] are the 4 bytes for the 32-bit integer flag.
Then we have this for updating buffer[0] with the character 'A':
0x08048351 <test_function+13>:  mov    BYTE PTR [ebp-40],0x41

The oddity then would be why a 10 byte array of characters would appear from [ebp+40](beginning of array) to [ebp+13] which is 28 bytes. The best guess I can make is that compiler felt that it could treat the 10 byte character array as a 128-bit (16-byte) vector. This would force the compiler to align the buffer on a 16 byte boundary, and pad the array out to 16 bytes (128-bits). From the perspective of the compiler, your code seems to be acting much like it was defined as:
#include <xmmintrin.h>
void test_function(int a, int b, int c, int d){
    int flag;
    union {
        char buffer[10];
        __m128 m128buffer;      ; 16-byte variable that needs to be 16-bytes aligned
    } bufu;

   flag = 31337;
   bufu.buffer[0] = 'A';
}

The output on GodBolt for GCC 4.9.0 generating 32-bit code with SSE2 enabled appears as follows:
test_function:
        push    ebp     #
        mov     ebp, esp  #,
        sub     esp, 40   #,same as: sub esp,0x28
        mov     DWORD PTR [ebp-12], 31337 # flag,
        mov     BYTE PTR [ebp-40], 65     # bufu.buffer,
        leave
        ret

This looks very similar to your disassembly in GDB.
If you compiled with optimizations (such as -O1, -O2, -O3), the optimizer could have simplified test_function because it is a leaf function in your example. A leaf function is one that doesn't call another function. Certain shortcuts could have been applied by the compiler.
As for why the character array seems to be aligned to a 16-byte boundary and padded to be 16 bytes? That probably can't be answered with certainty until we know what GCC compiler you are using (gcc --version will tell you). It would also be useful to know your OS and OS version. Even better would be to add the output from this command to your question gcc -Q -v -g my_program.c

A: Unless you're trying to improve gcc's code itself, understanding why un-optimized code is as bad as it is will mostly be a waste of time.  Look at output from -O3 if you want to see what a compiler does with your code, or from -Og if you want to see a more literal translation of your source into asm.  Write functions that take input in args and produce output in globals or return values, so the optimized asm isn't just ret.

You shouldn't expect anything efficient from gcc -O0.  It makes the most braindead literal translation of your source.
I can't reproduce that asm output with any gcc or clang version on http://gcc.godbolt.org/.  (gcc 4.4.7 to gcc 5.3.0, clang 3.0 to clang 3.7.1).  (Note that godbolt use g++, but you can use -x c to treat the input as C, instead of compiling it as C++.  This can sometimes change the asm output, even when you don't use any features C99 / C11 has but C++ doesn't.  (e.g. C99 variable-length arrays).
Some versions of gcc default to emitting extra code unless I use -fno-stack-protector.
I thought at first that the extra space reserved by test_function was to copy its args down into its stack frame, but at least modern gcc doesn't do this.  (64bit gcc does store its args into memory when they arrive in registers, but that's different.  32bit gcc will increment an arg in place on the stack, without copying it.)
The ABI does allow the called function to clobber its args on the stack, so a caller that wanted to make repeated function calls with the same args would have to keep storing them between calls.
clang 3.7.1 with -O0 does copy its args down into locals, but that still only reserves 32 (0x20) bytes.
This is about the best answer you're going to get unless you tell us which version of gcc you're using...


text:
Q: In node.js why can't I get child_process.execSync to play nicely with sendmail? The variable "out" is defined thusly:
var out = "To: doug@my_domain.com\n";
out += "From: no_reply@my_domain\n";
out += "Subject: Form Submission\n\n";
out += "Hello, world!\n";
out += ".\n";

If I do this:
child_process.execSync('cat - > /tmp/look', { input : out }).toString();

The contents of the "out" variable is written to "/tmp/look" exactly as one would expect.  However, if I do this:
child_process.execSync('sendmail -t', { input : out }).toString();

sendmail does NOT email the contents of the "out" variable as one would expect.  The complaint in the maillog is that there is no recipient address in the message header.  Further investigation reveals that sendmail is just not getting any part of the "out" variable.  Does anyone know why that would be?  Thanks for any help.
  ... doug

PS:  I think that I neglected to mention one very important fact.  This is a CGI script.  Everything works just fine when I call the script manually (i.e., "./script_name" at the command prompt).  I'm only experiencing the problem when I trigger the running of the script by submitting a form.  Here is the exact error message that I am receiving:  "May 20 01:29:15 vm0-61 postfix/sendmail[22223]: fatal: apache(48): No recipient addresses found in message header".  Thanks.  Sorry for the omission.

A: Try this out:
var out = "To: doug@my_domain.com\n";
out += "From: no_reply@my_domain\n";
out += "Subject: Form Submission\n\n";
out += "Hello, world!\n";
out += ".\n";

child_process.execSync('sendmail -vt <', { input : out }).toString();


text:
Q: My WPF UserControl doesn't receive input when hosted in a WinForm Form I've added a WPF user control to a WinForms Form but I'm not able to receive events on my WPF control.
I've tried to subscribe the MouseEnter event but the event handler method is never called.
I'm adding the WPF control with the Visual Studio (2010 Express edition) designer. I add an ElementHost and then associate my control to the host.
Here is a screenshot of the form:

The WPF control is an help ad below toolstrip. There is a link at the end of the control that, when added to the winform elementhost, won't receive any input events.
Here is the xaml code of the component:
<UserControl x:Class="Telbit.TeStudio.View.Forms.HelpAd"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="30" Width="500"
x:Name="HelpAdControl"
Background="#FFD3DCE6"
BorderBrush="#FFB9C4D2"
BorderThickness="0 0 0 1">
<Grid>
        <StackPanel Orientation="Horizontal">
        <Image Name="icnHelpAd"
           HorizontalAlignment="Center" VerticalAlignment="Center"
           Visibility="{Binding ElementName=HelpAdControl, Path=HasIcon}"/>
        <TextBlock Name="txtHelpType" Margin="5 0 0 0"
               Visibility="{Binding ElementName=HelpAdControl, Path=HasType}"
               Text="{Binding ElementName=HelpAdControl, Path=HelpType}"
               TextBlock.FontFamily="Verdana" TextBlock.FontSize="10" FontWeight="Bold" Foreground="#FF939FBB"
               VerticalAlignment="Center" />
        <TextBlock Name="txtHelpDescription" Margin="5 0 0 0"
               Visibility="{Binding ElementName=HelpAdControl, Path=HasDescription}"
               Text="{Binding ElementName=HelpAdControl, Path=HelpDescription}"
               TextBlock.FontFamily="Verdana" TextBlock.FontSize="10" Foreground="#FF444444"
               VerticalAlignment="Center" />
        <TextBlock Name="lblHelpLink" VerticalAlignment="Center" Margin="5 0 0 0">
            <Hyperlink Name="lnkHelpLink"
                       TextBlock.FontFamily="Verdana" TextBlock.FontSize="10" Foreground="#FF255BC8"
                       Click="lnkHelpLink_Click" NavigateUri="{Binding ElementName=HelpAdControl, Path=HelpKey}">
                <TextBlock Text="{Binding ElementName=HelpAdControl, Path=HelpLinkDescription}" />
            </Hyperlink>
        </TextBlock>
        <TextBlock Name="lblNextHelp"
                   Margin="5 0 0 0" Width="16" VerticalAlignment="Center" HorizontalAlignment="Right" ToolTip="Next Help Tip"
                   TextBlock.FontFamily="Verdana" TextBlock.FontSize="10">
            <Hyperlink Name="lnkNextHelp" Click="lnkNextHelp_Click" NavigateUri="www.mock.com">
                »
            </Hyperlink>
        </TextBlock>

    </StackPanel>
</Grid>

Just another note: the mouse cursor is not changed when the mouse is hover the link component. It seems to me that the events are not being send to WPF control.
Any idea of waht may be causing this problem?


text:
Q: EXECUTE IMMEDIATE Temp table in oracle does not get created ORA-00942 Based on this answer I was trying to create temp table, however I am getting exception ORA-00942:table or view does not exist I would assume there is something wrong with 'CREATE OR REPLACE GLOBAL TEMPORARY TABLE TempQandA(column1 number) ON COMMIT PRESERVE ROWS' statement, it fails on insert into TempQandA(column1) VALUES (1);.
Please find SQL statement below.
DECLARE
TransactioDetailId numeric := 3132;
HomePhoneNumber varchar(20);
MobileNumber varchar(20);
Email varchar(20);
whatever varchar(20);
BEGIN
EXECUTE IMMEDIATE 'CREATE OR REPLACE GLOBAL TEMPORARY TABLE TempQandA(column1 number) ON COMMIT PRESERVE ROWS';

        BEGIN
        SELECT contactvalue into HomePhoneNumber  FROM customercontact CC
         inner join TRANSACTIONMAIN tm on tm.customerid = CC.customerid
         inner join transactiondetail td on td.transactionid = tm.transactionid
         where contacttypeid = 2 and td.transactiondetailid = TransactioDetailId;
         EXCEPTION
         WHEN NO_DATA_FOUND THEN
         HomePhoneNumber := NULL;
                         begin
                         SELECT  contactvalue into MobileNumber  FROM customercontact CC
                         inner join TRANSACTIONMAIN tm on tm.customerid = CC.customerid
                         inner join transactiondetail td on td.transactionid = tm.transactionid
                         where contacttypeid = 3 and td.transactiondetailid = TransactioDetailId;
                         EXCEPTION
                         WHEN NO_DATA_FOUND THEN
                         MobileNumber := NULL;
                                      begin
                                      SELECT  contactvalue into Email  FROM customercontact CC
                                      inner join TRANSACTIONMAIN tm on tm.customerid = CC.customerid
                                      inner join transactiondetail td on td.transactionid = tm.transactionid
                                      where contacttypeid = 1 and td.transactiondetailid = TransactioDetailId;
                                      EXCEPTION
                                      WHEN NO_DATA_FOUND THEN
                                      Email := NULL;

                                            begin
                                            insert into TempQandA(column1) VALUES (1);
                                             end;
                                     end;
                     end;
         end;
END;

A: You dynamically create the GTT, so your INSERT too should be dynamic..
Note that, PL/SQL validates every static query before even executing it.
Thats why you get ORA-942 Table or view doesn't exist error  even at compilation time!
So, to escape this semantic check, we have to make the call dynamic.
    BEGIN
    EXECUTE IMMEDIATE 'CREATE GLOBAL TEMPORARY TABLE TempQandA(column1 number) ON COMMIT PRESERVE ROWS';

.....

    EXECUTE IMMEDIATE ' insert into TempQandA(column1) VALUES (1)';
    END;

And Finally, you should not be creating the GTT on run time.. To avoid such issues. The GTT is anyway going to local to every session.
EDIT: As Lalit says, GTT's DDL doesn't accept CREATE OR REPLACE

A:
'CREATE OR REPLACE GLOBAL TEMPORARY TABLE TempQandA(column1 number) ON
  COMMIT PRESERVE ROWS';

The keyword REPLACE is incorrect. You need to simply create the GTT and insert the values into it using EXECUTE IMMEDIATE :
SQL> BEGIN
  2  EXECUTE IMMEDIATE 'CREATE GLOBAL TEMPORARY TABLE Temp_gtt(column1 number) ON COMMIT PRESERVE ROWS';
  3  EXECUTE IMMEDIATE 'insert into temp_gtt(column1) values(1)';
  4  END;
  5  /

PL/SQL procedure successfully completed.

SQL>
SQL> select * from temp_gtt;

   COLUMN1
----------
         1

SQL>


text:
Q: unable to mount volume to spark.kubernetes.executor I am trying to read a file from server in spark cluster mode using kubernetes, so i put my file on all workers and i mount driver volume using
val conf = new SparkConf().setAppName("sparksetuptest")
.set("spark.kubernetes.driver.volumes.hostPath.host.mount.path", "/file-directory")
Everything works fine here but when i execute it shows that file not found at specific location.
So i mount directory to executor with .set("spark.kubernetes.executor.volumes.hostPath.host.mount.path", "/file-directory")
But now i am not able to execute program it stuck in a never ending process while fetching data.
Please suggest something, so that i can mount my directory with executor and read that file.

A: this is an example from nfs-example
spark.kubernetes.driver.volumes.nfs.images.options.server=example.com
spark.kubernetes.driver.volumes.nfs.images.options.path=/data

I think you need to declare the path that you want to mount under options.path and the spark.kubernetes.driver.volumes.[VolumeType].[VolumeName].mount.path is the mount path in your container
For example:
If I want to mount /home/lemon/data on the node of k8s to the path /data the docker container with VolumeName exepv, then
conf.set("spark.kubernetes.executor.volumes.hostPath.exepv.mount.path","/data")
conf.set("spark.kubernetes.executor.volumes.hostPath.exepv.options.path", "/home/lemon/data")

after this, you can access the path /data in your executor container


text:
Q: Inputting data row by row from a large data set into a hypertable (Postgre) I have a csv file with 5 columns of data and 5000+ rows. My task is to input the data ONE by ONE into a hypertable which I already created.
My question is : the COPY function copies the entire file into the hypertable. I could just sit and  use the INPUT function and input the data one by one - however, this is very painful and very time consuming.
I'm not sure how the conditional loops work, the documentation available is a little hazy. I have experience in C and python if that helps.
Any guidance is much appreciated!


text:
Q: Windows phone: Animate a PhoneTextBox like the search text box in People hub app Im developing a Windows phone 7.1 app and I need to animate the search textbox(toolkit:PhoneTextBox) just like it happens in people app. Slide in from the top of the screen on becoming Visible  and slide out on Collapsed.
I searched for resources online but did not find any.
EDIT: My code for starting the animations. The slide in works, I tried slide out similarly, it doesnt.
 void SearchBox_Click(object sender, System.EventArgs e)
        {
            {
                if (SearchBox.Visibility == System.Windows.Visibility.Collapsed)
                {
                    (this.Resources["ShowSearchTextbox"] as Storyboard).Begin();
                    SearchBox.Focus();
                    SearchBox.Visibility = System.Windows.Visibility.Visible;
                    SearchBox.Foreground = new SolidColorBrush(Colors.Gray);
                }
                else
                {
                    SearchFilter.Instance.SearchText = String.Empty;
                    SearchBox.Text = string.Empty;
                    (this.Resources["HideSearchTextbox"] as Storyboard).Begin();
                    SearchBox.Visibility = System.Windows.Visibility.Collapsed;
                }
            }
        }

A: You could use a Storyboard:
<Storyboard x:Key="showsearchtextbox">
    <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TranslateTransform.Y)" Storyboard.TargetName="searchtextbox">
        <DiscreteDoubleKeyFrame KeyTime="0" Value="-100"/>
        <EasingDoubleKeyFrame KeyTime="0:0:0.500" Value="0">
            <EasingDoubleKeyFrame.EasingFunction>
                <CubicEase EasingMode="EaseOut"/>
            </EasingDoubleKeyFrame.EasingFunction>
        </EasingDoubleKeyFrame>
    </DoubleAnimationUsingKeyFrames>
</Storyboard>

With following TextBox:
<TextBlock x:Name="searchtextbox">
    <TextBlock.RenderTransform>
        <TranslateTransform Y="-100"/>
    </TextBlock.RenderTransform>
</TextBlock>

And then when the user presses on the search icon:
(this.Resources["showsearchtextbox"] as Storyboard).Begin();
searchtextbox.Focus();


text:
Q: Define one-to-many relationship among Room entities for Chat model I started using Room database and went through several docs to create room entities.
These are my relations. A Chat Channel can have Many Conversations. So this goes as one-to-many relationship. Hence i created entities as below.
Channel Entity
@Entity(primaryKeys = ["channelId"])
@TypeConverters(TypeConverters::class)
data class Channel(
    @field:SerializedName("channelId")
    val channelId: String,
    @field:SerializedName("channelName")
    val channelName: String,
    @field:SerializedName("createdBy")
    val creationTs: String,
    @field:SerializedName("creationTs")
    val createdBy: String,
    @field:SerializedName("members")
    val members: List<String>,
    @field:SerializedName("favMembers")
    val favMembers: List<String>
) {
  // Does not show up in the response but set in post processing.
  var isOneToOneChat: Boolean = false
  var isChatBot: Boolean = false
}

Conversation Entity
@Entity(primaryKeys = ["msgId"],
    foreignKeys = [
        ForeignKey(entity = Channel::class,
                parentColumns = arrayOf("channelId"),
                childColumns = arrayOf("msgId"),
                onUpdate = CASCADE,
                onDelete = CASCADE
        )
    ])
@TypeConverters(TypeConverters::class)
data class Conversation(

    @field:SerializedName("msgId")
    val msgId: String,
    @field:SerializedName("employeeID")
    val employeeID: String,
    @field:SerializedName("channelId")
    val channelId: String,
    @field:SerializedName("channelName")
    val channelName: String,
    @field:SerializedName("sender")
    val sender: String,
    @field:SerializedName("sentAt")
    val sentAt: String,
    @field:SerializedName("senderName")
    val senderName: String,
    @field:SerializedName("status")
    val status: String,
    @field:SerializedName("msgType")
    val msgType: String,
    @field:SerializedName("type")
    val panicType: String?,
    @field:SerializedName("message")
    val message: List<Message>,
    @field:SerializedName("deliveredTo")
    val delivered: List<Delivered>?,
    @field:SerializedName("readBy")
    val read: List<Read>?

) {

data class Message(
        @field:SerializedName("txt")
        val txt: String,
        @field:SerializedName("lang")
        val lang: String,
        @field:SerializedName("trans")
        val trans: String
)

data class Delivered(
        @field:SerializedName("employeeID")
        val employeeID: String,
        @field:SerializedName("date")
        val date: String
)

data class Read(
        @field:SerializedName("employeeID")
        val employeeID: String,
        @field:SerializedName("date")
        val date: String
)

    // Does not show up in the response but set in post processing.
    var isHeaderView: Boolean = false
}

Now as you can see Conversation belongs to a Channel. When user sees a list of channels, i need to display several attributes of last Conversation in the list item. My question is,  is it enough if i just declare relation like above or should i contain Converstion object in Channel class? What are the other ways in which i can handle it? Because UI needs to get most recent conversation that happened along with time, status etc. in each item of the channel list when user scrolls. So there should not be any lag in UI because of this when i query.
And how can i have recent Converstaion object in Channel object?

A: I suggest create another class (not in DB, just for show in UI) like this:
data class LastConversationInChannel(
    val channelId: String,
    val channelName: String,
    val creationTs: String,
    val createdBy: String,
    val msgId: String,
    val employeeID: String,
    val sender: String,
    val sentAt: String,
    val senderName: String
    .
    .
    .
)

Get last Conversation in each Channel by this query:
 SELECT Channel.*
 ,IFNULL(LastConversation.msgId,'') msgId
 ,IFNULL(LastConversation.sender,'') sender
 ,IFNULL(LastConversation.employeeID,'') employeeID
 ,IFNULL(LastConversation.sentAt,'') sentAt
 ,IFNULL(LastConversation.senderName,'') senderName
 from Channel left join
 (SELECT * from Conversation a
 WHERE a.msgId IN ( SELECT b.msgId  FROM Conversation AS b
                    WHERE a.channelId = b.channelId
                    ORDER BY b.sentAt DESC  LIMIT 1 )) as LastConversation
 on Channel.channelId = LastConversation.channelId

then use it in your dao like this:
 @Query(" SELECT Channel.*\n" +
            " ,IFNULL(LastConversation.msgId,'') msgId\n" +
            " ,IFNULL(LastConversation.sender,'') sender\n" +
            " ,IFNULL(LastConversation.employeeID,'') employeeID\n" +
            " ,IFNULL(LastConversation.sentAt,'') sentAt\n" +
            " ,IFNULL(LastConversation.senderName,'') senderName\n" +
            " from Channel left join \n" +
            " (SELECT * from Conversation a  \n" +
            " WHERE a.msgId IN ( SELECT b.msgId  FROM Conversation AS b \n" +
            "                    WHERE a.channelId = b.channelId \n" +
            "                    ORDER BY b.sentAt DESC  LIMIT 1 )) as LastConversation\n" +
            " on Channel.channelId = LastConversation.channelId")
    fun getLastConversationInChannel(): LiveData<List<LastConversationInChannel>>

is it enough if i just declare relation like above or should i contain Converstion object in Channel class?

You should not contain Conversation in Channel class, because Room will create some columns for it in Conversation table.

A: You can have an LastConversation which is an Conversation object inside the Chanel. You have to update this every time the lastConversation is updated by modify the table Chanel from Room layer. (Not take so much performance for update db). By implement sorting for the Chanel list (Comparable). Your UI update will be cool. And your logic from UI or ViewModel is simpler. I did it this way too.


text:
Q: Show facebook user detail in ios app After the user sing in whit Facebook to my app i wont to display his first name and profile pic, I get the data from AppDelegate class and add it to a property (UserNameLable) in the view controller,
in AppDelegate all the nslogs shows the data
in the view controller nslogs shows null
how can i loud the data in to my property in the mainViewController ?
in AppDelegate this is the code
AppDelegate.h
@property (retain, nonatomic) NSString *first_name_property;

AppDelegate.m
- (void)sessionStateChanged:(FBSession *)session
                      state:(FBSessionState) state
                      error:(NSError *)error
{
    switch (state) {
        case FBSessionStateOpen:

            [[NSNotificationCenter defaultCenter]
             postNotificationName:SCSessionStateChangedNotification
             object:session];

                [[FBRequest requestForMe] startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {

                    if (error) {

                        NSLog(@"error");
                    }

                    else
                    {
                        NSLog(@"FB user first name:%@",user.first_name);
                        NSLog(@"FB user last name:%@",user.last_name);

                        // Add the data to the property I crated
                        first_name_property = user.first_name;

                    }
                }];

            }

            break;
        case FBSessionStateClosed:
        case FBSessionStateClosedLoginFailed:
            [FBSession.activeSession closeAndClearTokenInformation];
            break;

        default:
            break;

//this is the code to display the data in my view
mainViewController.h
@property (strong, nonatomic) IBOutlet UILabel *UserNameLable;

mainViewController.m
-(void)viewDidAppear:(BOOL)animated{

    if (!UserNameLable) {
        UserNameLable.text=((AppDelegate *)[UIApplication sharedApplication].delegate).first_name_property;

    }
    else{
        UserNameLable.text=@"not set";}
}

A: Use first_name_property instead of first_name.
Try
UserNameLable.text=((AppDelegate *)[UIApplication sharedApplication].delegate).first_name_property;


text:
Q: Can't manage to get jVectorMap's getRegionName into div I've been trying all day long to get country information from jVectorMap onClick into another
. After some research I found out that I needed to make a mapObject to use getRegionName but I still can't get it to work (new to jQuery).
Basically, I want to see a country's name in the div info-box after clicking on the country.
Here's the map stuff:
jQuery(function(){
      var $ = jQuery;
   $('#focus-au').click(function(){
        $('#world-map').vectorMap('set', 'focus', 'AU');
      });
      $('#focus-us').click(function(){
        $('#world-map').vectorMap('set', 'focus', 3, 0.1, 0.4);
      });
      $('#focus-eu').click(function(){
        $('#world-map').vectorMap('set', 'focus', 3, 0.5, 0.3);
      });
      $('#focus-as').click(function(){
        $('#world-map').vectorMap('set', 'focus', 2.5, 0.72, 0.0025);
      });
      $('#focus-home').click(function(){
        $('#world-map').vectorMap('set', 'focus', 1, 0, 0);
      });
      $('#world-map').vectorMap({
        map: 'world_mill_en',

        focusOn: {
          x: 0.5,
          y: 0.5,
          scale: 1
        },

        backgroundColor: '#FFFFFF',

        onRegionClick: function(event, code) {
        var map = $('#world-map').vectorMap('get', 'mapObject');
        $('.info-box').html('' + map.getRegionName(code) + '');
        },
         series: {
            regions: [{
                values: clrData,
                scale: ['#0071A4', '#C8EEFF'],
                normalizeFunction: 'polynomial'
                    }]
            },

        onRegionLabelShow: function(e, el, code){
        el.html(el.html()+' (Cost of Living and Rent Index - '+clrData[code]+')');
        },

      });
    })

There's the div:

Info Box

And finally the info-box' CSS (although I think it doesn't matter):
.info-box {
    line-height:30px;
    background-color:#fff;
    color: black;
    height:300px;
    width:100px;
    float:left;
    padding:5px;
}

In the mean time it suddenly worked, once, but after changing some stuff in the CSS (z-indexes and positions of world map and sidebar, which are overlapping each other) it stopped working again.

A: I made it work using the initialization style found in the markers.html example:
var map = new jvm.Map({
    container: $('#map1'),
    map: 'world_mill_en',
    onRegionClick: function(event, code) {
        $('.info-box').html('
' + map.getRegionName(code) + '
');
    }
});

jQuery.noConflict();
jQuery(function() {
    var $ = jQuery;

    $('#focus-single').click(function() {
        $('#map1').vectorMap('set', 'focus', {
            region: 'AU',
            animate: true
        });
    });
    $('#focus-multiple').click(function() {
        $('#map1').vectorMap('set', 'focus', {
            regions: ['AU', 'JP'],
            animate: true
        });
    });
    $('#focus-coords').click(function() {
        $('#map1').vectorMap('set', 'focus', {
            scale: 7,
            lat: 35,
            lng: 33,
            animate: true
        });
    });
    $('#focus-init').click(function() {
        $('#map1').vectorMap('set', 'focus', {
            scale: 1,
            x: 0.5,
            y: 0.5,
            animate: true
        });
    });
    var map = new jvm.Map({
        container: $('#map1'),
        map: 'world_mill_en',
        panOnDrag: true,
        focusOn: {
            x: 0.5,
            y: 0.5,
            scale: 2,
            animate: true
        },
        onRegionClick: function(event, code) {
            //var map = $('#world-map').vectorMap('get', 'mapObject');
            console.log(map.getRegionName(code));
            $('.info-box').html('
' + map.getRegionName(code) + '
');
        },
        series: {
            regions: [{
                scale: ['#C8EEFF', '#0071A4'],
                normalizeFunction: 'polynomial',
                values: {
                    "AF": 16.63,
                    "AL": 11.58,
                    "DZ": 158.97,
                    "AO": 85.81,
                    "AG": 1.1,
                    "AR": 351.02,
                    "AM": 8.83,
                    "AU": 1219.72,
                    "AT": 366.26,
                    "AZ": 52.17,
                    "BS": 7.54,
                    "BH": 21.73,
                    "BD": 105.4,
                    "BB": 3.96,
                    "BY": 52.89,
                    "BE": 461.33,
                    "BZ": 1.43,
                    "BJ": 6.49,
                    "BT": 1.4,
                    "BO": 19.18,
                    "BA": 16.2,
                    "BW": 12.5,
                    "BR": 2023.53,
                    "BN": 11.96,
                    "BG": 44.84,
                    "BF": 8.67,
                    "BI": 1.47,
                    "KH": 11.36,
                    "CM": 21.88,
                    "CA": 1563.66,
                    "CV": 1.57,
                    "CF": 2.11,
                    "TD": 7.59,
                    "CL": 199.18,
                    "CN": 5745.13,
                    "CO": 283.11,
                    "KM": 0.56,
                    "CD": 12.6,
                    "CG": 11.88,
                    "CR": 35.02,
                    "CI": 22.38,
                    "HR": 59.92,
                    "CY": 22.75,
                    "CZ": 195.23,
                    "DK": 304.56,
                    "DJ": 1.14,
                    "DM": 0.38,
                    "DO": 50.87,
                    "EC": 61.49,
                    "EG": 216.83,
                    "SV": 21.8,
                    "GQ": 14.55,
                    "ER": 2.25,
                    "EE": 19.22,
                    "ET": 30.94,
                    "FJ": 3.15,
                    "FI": 231.98,
                    "FR": 2555.44,
                    "GA": 12.56,
                    "GM": 1.04,
                    "GE": 11.23,
                    "DE": 3305.9,
                    "GH": 18.06,
                    "GR": 305.01,
                    "GD": 0.65,
                    "GT": 40.77,
                    "GN": 4.34,
                    "GW": 0.83,
                    "GY": 2.2,
                    "HT": 6.5,
                    "HN": 15.34,
                    "HK": 226.49,
                    "HU": 132.28,
                    "IS": 12.77,
                    "IN": 1430.02,
                    "ID": 695.06,
                    "IR": 337.9,
                    "IQ": 84.14,
                    "IE": 204.14,
                    "IL": 201.25,
                    "IT": 2036.69,
                    "JM": 13.74,
                    "JP": 5390.9,
                    "JO": 27.13,
                    "KZ": 129.76,
                    "KE": 32.42,
                    "KI": 0.15,
                    "KR": 986.26,
                    "KW": 117.32,
                    "KG": 4.44,
                    "LA": 6.34,
                    "LV": 23.39,
                    "LB": 39.15,
                    "LS": 1.8,
                    "LR": 0.98,
                    "LY": 77.91,
                    "LT": 35.73,
                    "LU": 52.43,
                    "MK": 9.58,
                    "MG": 8.33,
                    "MW": 5.04,
                    "MY": 218.95,
                    "MV": 1.43,
                    "ML": 9.08,
                    "MT": 7.8,
                    "MR": 3.49,
                    "MU": 9.43,
                    "MX": 1004.04,
                    "MD": 5.36,
                    "MN": 5.81,
                    "ME": 3.88,
                    "MA": 91.7,
                    "MZ": 10.21,
                    "MM": 35.65,
                    "NA": 11.45,
                    "NP": 15.11,
                    "NL": 770.31,
                    "NZ": 138,
                    "NI": 6.38,
                    "NE": 5.6,
                    "NG": 206.66,
                    "NO": 413.51,
                    "OM": 53.78,
                    "PK": 174.79,
                    "PA": 27.2,
                    "PG": 8.81,
                    "PY": 17.17,
                    "PE": 153.55,
                    "PH": 189.06,
                    "PL": 438.88,
                    "PT": 223.7,
                    "QA": 126.52,
                    "RO": 158.39,
                    "RU": 1476.91,
                    "RW": 5.69,
                    "WS": 0.55,
                    "ST": 0.19,
                    "SA": 434.44,
                    "SN": 12.66,
                    "RS": 38.92,
                    "SC": 0.92,
                    "SL": 1.9,
                    "SG": 217.38,
                    "SK": 86.26,
                    "SI": 46.44,
                    "SB": 0.67,
                    "ZA": 354.41,
                    "ES": 1374.78,
                    "LK": 48.24,
                    "KN": 0.56,
                    "LC": 1,
                    "VC": 0.58,
                    "SD": 65.93,
                    "SR": 3.3,
                    "SZ": 3.17,
                    "SE": 444.59,
                    "CH": 522.44,
                    "SY": 59.63,
                    "TW": 426.98,
                    "TJ": 5.58,
                    "TZ": 22.43,
                    "TH": 312.61,
                    "TL": 0.62,
                    "TG": 3.07,
                    "TO": 0.3,
                    "TT": 21.2,
                    "TN": 43.86,
                    "TR": 729.05,
                    "TM": 0,
                    "UG": 17.12,
                    "UA": 136.56,
                    "AE": 239.65,
                    "GB": 2258.57,
                    "US": 14624.18,
                    "UY": 40.71,
                    "UZ": 37.72,
                    "VU": 0.72,
                    "VE": 285.21,
                    "VN": 101.99,
                    "YE": 30.02,
                    "ZM": 15.69,
                    "ZW": 5.57
                }
            }]
        }
    });
});
<link rel="stylesheet" media="all" href="//rawgit.com/bjornd/jvectormap/master/jquery-jvectormap.css" />

Info Box

<button id="focus-single">Focus on Australia</button>
<button id="focus-multiple">Focus on Australia and Japan</button>
<button id="focus-coords">Focus on Cyprus</button>
<button id="focus-init">Return to the initial state</button>


text:
Q: Hyper-V: Create shared folder between host and guest with internal network Set up:

*

*Host: Windows 10 Enterprise

*Guest: Windows 10 Professional

*Hypervisor: Hyper-V

Aim:

*

*Create a shared folder between Host and Guest via an internal network to exchange files

How can I achieve this?

A: *

*Open Hyper-V Manager

*Create a new internal virtual switch (e.g. "Internal Network Connection")

*Go to your Virtual Machine and create a new Network Adapter -> choose "Internal Network Connection" as virtual switch

*Start the VM

*Assign both your host as well as guest an IP address as well as a Subnet mask (IP4, e.g. 192.168.1.1 (host) / 192.168.1.2 (guest) and 255.255.255.0)

*Open cmd both on host and guest and check via "ping" if host and guest can reach each other (if this does not work disable/enable the network adapter via the network settings in the control panel, restart...)

*If successfull create a folder in the VM (e.g. "VMShare"), right-click on it -> Properties -> Sharing -> Advanced Sharing -> checkmark "Share this folder" -> Permissions -> Allow "Full Control" -> Apply

*Now you should be able to reach the folder via the host -> to do so: open Windows Explorer -> enter the path to the guest (\192.168.1.xx...) in the address line -> enter the credentials of the guest (Choose "Other User" - it can be necessary to change the domain therefore enter ".\"[username] and [password])

There is also an easy way for copying via the clipboard:

*

*If you start your VM and go to "View" you can enable "Enhanced Session". If you do it is not possible to drag and drop but to copy and paste.

Enhanced Session

A: For those who are having trouble getting the "Edit Session Settings..." dialog, I found that I could get to the dialog box by having the guest machine running in windowed mode so that the top menu ("File Action Media Clipboard View Help") was visible, then selecting "File > Exit" (or clicking on the "X" at the top right of the guest machine window).
After that, the dialog would launch from the Hyper-V Manager Actions "Edit Session Settings..." link.

A: Share Files, Folders or Drives Between Host and Hyper-V Virtual Machine
Prerequisites

*

*Make sure you have a Pro or Enterprise version of the Windows OS. The Home version does not provide you with this functionality! From the official documentation:

The virtual machine must have Remote Desktop Services enabled, and run Windows 10, Windows 8.1, Windows Server 2016, or Windows Server 2012 R2 as the guest operating system.

*Ensure that Enhanced session mode settings are enabled on the Hyper-V host.
Start Hyper-V Manager, and in the Actions section, select "Hyper-V Settings".

Make sure that enhanced session mode is allowed in the Server section. Then, make sure that the enhanced session mode is available in the User section.

*Enable Hyper-V Guest Services for your virtual machine
Right-click on Virtual Machine > Settings. Select the Integration Services in the left-lower corner of the menu. Check Guest Service and click OK.

Steps to share devices with Hyper-v virtual machine:

*

*Start a virtual machine and click Show Options in the pop-up windows.

Or click "Edit Session Settings..." in the Actions panel on the right

It may only appear when you're (able to get) connected to it. If it doesn't appear try Starting and then Connecting to the VM while paying close attention to the panel in the Hyper-V Manager.

*View local resources. Then, select the "More..." menu.

*From there, you can choose which devices to share. Removable drives are especially useful for file sharing.

*Choose to "Save my settings for future connections to this virtual machine".

*Click Connect. Drive sharing is now complete, and you will see the shared drive in this PC > Network Locations section of Windows Explorer after using the enhanced session mode to sigh to the VM. You should now be able to copy files from a physical machine and paste them into a virtual machine, and vice versa.

Source (and for more info): Share Files, Folders or Drives Between Host and Hyper-V Virtual Machine
Drawbacks

*

*While this solution is easy and probably works faster then when using internal network, it has its own drawback: the drive is mapped only while there is a connection via the VMConnect client. If you run a vm with some background services or you connect to it via RDP, this approach isn't gonna work. (thanks @sich for pointing this out)

A: My version is Hyper-V Version: 10.0.22509.1000,I think the best and most convenient way in windows is that configuring the host and the vm in the same subnet,So you can just use the ctrl+c and ctrl+v Seamlessly between host and vm.


text:
Q: High response time - programmatically move mouse using pyautogui In a python script, the response time for pyautogui.moveRel(b, a) is currently .1 sec. Is that the intended time for this function? If so, is there any way I can shorten this response time using another technique in python, or other languages? My goal response time is about 0.01 sec, which is the 60HZ rate.

A: The results @mertyildiran obtained are to be expected, since PyAutoGUI has a default 0.1 second pause between actions as a failsafe.
To speed things up, you can set the pause to a lower value, or even zero, like so:
pyautogui.PAUSE = 0

A: The code for checking the response time in microseconds(0.01 seconds = 10000 microseconds):
import pyautogui
import datetime

for x in range(0, 9):
    start = datetime.datetime.now()
    pyautogui.moveRel(None, 50)
    end = datetime.datetime.now()

    elapsed_time = end - start

    print elapsed_time.microseconds

Output:
269017
112927
113071
113061
112761
112561
113115
112107
112448

That means yeah it's approximately 0.1 seconds with this library and Python. So my recommendation is go with a deeper level programming language like C++.
Stimulate mouse event with C++ in Windows: https://stackoverflow.com/a/7492837/2104879
Stimulate mouse event with C++ in Linux: https://stackoverflow.com/a/8791599/2104879


text:
Q: latex-suite F9 completion key works in gvim but not in vim I am setting up a latex-suite environment for my vim. I discovered that the F9 key that is used to complete references (be them \ref{ or \cite{) only works when I edit the file in gvim (showing that the setup is correct) but not in vim (konsole or xterm terminals tested). Has anybody experienced such a situation? How could one fix this problem ? Thanks a lot for your help.
~~~
System:
VIM - Vi IMproved 7.4 in a Debian GNU/Linux box

A: For me the problem was in the vimrc. I had set paste in there and after I removed it, F9 would work again.
If you want to find out, if it is related to the vimrc, you can create another one and use that one with vim -u ~/.vimrc_latex


text:
Q: Spring security - resource j_spring_security_check not avaiable I am trying to build a Spring based web application and I would like to start with configuring a simple authentication system based on username & password tuples stored in a database table.
It is my understanding that this can be easily achieved using Spring security, but I cannot get it to work.
The following is my web.xml file.
<?xml version="1.0" encoding="UTF-8"?>
<web-app
    version="2.5"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <servlet>
        <servlet-name>Servlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/Servlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Servlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

Follows the servlet-context.xml file. The bob and sam users are there for testing purposes. After I get this right I will switch to a JDBC based user service.
<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:sec="http://www.springframework.org/schema/security"
    xsi:schemaLocation="
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">

    <sec:http use-expressions="true">
        <sec:intercept-url pattern="/**" access="permitAll" />
        <sec:form-login
            login-page="/home.html"
            login-processing-url="/j_spring_security_check"
            authentication-failure-url="/login-error.html"
            default-target-url="/welcome.html" />
        <sec:logout logout-success-url="/home.html" />
    </sec:http>

    <sec:authentication-manager>
        <sec:authentication-provider>
            <sec:password-encoder hash="md5"/>
            <sec:user-service>
                <sec:user name="bob" password="12b141f35d58b8b3a46eea65e6ac179e" authorities="ROLE_SUPERVISOR, ROLE_USER" />
                <sec:user name="sam" password="d1a5e26d0558c455d386085fad77d427" authorities="ROLE_USER" />
            </sec:user-service>
        </sec:authentication-provider>
    </sec:authentication-manager>

    <context:component-scan base-package="cz.dusanrychnovsky.whattoreadnext" />
    <mvc:annotation-driven />
</beans>

This is my Home controller.
@Controller
public class HomeController
{
    @RequestMapping(value = "/home.html")
    public String home() {
        return "home";
    }

    @RequestMapping(value = "/login-error.html")
    public String loginError(Model model) {
        model.addAttribute("loginError", true);
        return "home";
    }
}

And this is my thymeleaf based view.
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring3-3.dtd">

        <title>Contacts</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

Welcome to the site!

Wrong user or password

            <form th:action="@{/j_spring_security_check}" method="post">
                Email address:
                <input type="text" id="j_username" name="j_username" />

                Password:
                <input type="password" id="j_password" name="j_password" />

                <input type="submit" value="Log in" />
             </form>

When I deploy the WAR file to my local Tomcat installation and visit the http://localhost:8080/test/home.html URL, the home page opens fine. When I fill in the form, though, which gets submitted to http://localhost:8080/test/j_spring_security_check, I get a 404 - The requested resource () is not available. error.
What am I doing wrong? Please bear with me as I'm  a newcomer to both Spring MVC/Security and Thymeleaf.

A: *

*You need to configure Spring Security filter in web.xml

*You cannot configure Spring Security in servlet-context.xml, because servlet-context.xml belongs to specific DispatcherServlet, but Spring Security filter works before request reaches any servlet.
You need to create a root application context using ContextLoaderListener and put Spring Security configuration there.
Actually, as long as you don't need separate servlet-context.xml and applicationContext.xml, I'd suggest you to move everything from servlet-context.xml to applicationContext.xml and leave servlet-context.xml effectively empty (that is, leave its <beans> element empty).