text:
Q: Shopping Cart Delete List To Also Update Total Price I am using JavaScript to make a website with a shopping cart system. I have made most of the shopping cart and succeeded pretty well after following YouTube videos (considering my noob skills). However, I don't seem to be able to make the functionality of deleting a product list from the cart while also updating the cart.
Here is my JavaScript code to remove the product list from the cart that doesn't update the total price:
const removeBtn = document.querySelectorAll('.remove-product')
removeBtn.forEach (function (rBtn) {
    rBtn.addEventListener('click', function () {
        cartItem.remove();
    });
});

Can anyone help me fix this problem? It would be very appreciated to have an answer...
Here is my HTML, CSS, and the rest of my JS:
HTML:

                Creator

                Men

                Women

                    0

                <input type="text" placeholder="Search">

 No products in cart.

 $0

 Extended Play

 $420.69

                            Add to Cart

 Heartache

 $999.99

                            Add to Cart

                ...

CSS:
/* Navigation Bar */

.main-nav {
    display: flex;
    justify-content: space-around;
    align-items: center;
    height: fit-content;
    position: fixed;
    width: 100%;
    transition: ease-in 0.1s;
    z-index: 100;
    background-color: white;
    border-bottom: #d3d3d3 solid 1px;
    padding: 20 0;
}

/* Logo */

.logo {
    width: 130px;
    margin-left: 70px;
    animation-delay: 0s;
    animation-duration: 1s;
    transition: 0.5s ease;
    outline: none;
}

.logo img {
    width: 100px;
}

.red {
    display: none;
}

.normal {
    display: block;
}

.logo:hover .red {
    display: block;
}

.logo:hover .normal {
    display: none;
}

/* Desktop Navigation Links */

.nav-links {
    display: flex;
    align-items: center;
    justify-content: space-around;
    width: 40%;
    position: relative;
    margin-bottom: 0;
}

.nav-links li {
    list-style: none;
    transition: ease-in 0.5s;
}

.nav-links li:first-child {
    animation-duration: 1s;
    animation-delay: 0.5s;
}

.nav-links li:nth-child(2) {
    animation-duration: 1s;
    animation-delay: 1s;
}

.nav-links li:last-child {
    animation-duration: 1s;
    animation-delay: 1.5s;
}

.nav-links li a {
    text-decoration: none;
    font-family: 'Montserrat', serif;
    font-size: 14px;
    font-weight: bold;
    text-transform: uppercase;
    letter-spacing: 5px;
    color: black;
    user-select: none;
}

.nav-links li a:hover {
    color: rgb(196, 8, 8);
    transition: 0.5s ease;
}

/* Nav Small */

.nav-small {
    display: flex;
    align-items: center;
    justify-content: space-around;
}

/* Nav Icons */

.nav-icons {
    display: flex;
    align-items: center;
    justify-content: space-around;
    width: 70px;
    margin-bottom: 0;
    margin-right: 5vw;
}

.nav-icons li {
    list-style: none;
    transition: ease-in 0.5s;
    cursor: pointer;
}

.nav-icons li:hover {
    color: rgb(196, 8, 8);
}

.nav-icons li:first-child {
    animation-duration: 1s;
    animation-delay: 2s;
}

.nav-icons li:nth-child(2) {
    animation-duration: 1s;
    animation-delay: 2.5s;
}

.nav-icons input {
    position: absolute;
    top: 157.813;
    right: 30;
    opacity: 0;
    transform: translateX(100vw);

    width: 350px;
    padding: 15 20;
    outline: none;
    border: #d3d3d3 solid 1px;
    transition: ease-in 0.1s;
}

.nav-icons input::placeholder {
    font-size: 13;
    letter-spacing: 4px;
    color: #222;
}

#cart-button i sup {
    font-family: 'Montserrat';
    color: white;
    background-color: #222;
    border: 2px solid white;
    border-radius: 100%;
    padding: 2 7;
    font-size: 10px;
    font-weight: lighter;
    margin-left: -7;
    top: -1.3em;
    transition: ease-in 0.5s;
}

#cart-button i:hover > sup {
    background-color: rgb(196, 8, 8);
}

/* Shopping Cart List */

.shop-cart {
    position: absolute;
    top: 157.813;
    right: 30;
    transform: translateX(100vw);

    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    width: 400px;
    max-height: 480px;
    padding: 15 20;
    outline: none;
    border: #d3d3d3 solid 1px;
    background-color: #fff;
    transition: ease-in 0.1s;
}

.cart-list {
    height: fit-content;
    max-height: 1000px;
    overflow-y: scroll;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: flex-start;
}

.cart-list li {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    cursor: default;
    padding-right: 20;
}

.cart-img {
    width: 70px;
    margin-right: 30;
    cursor: pointer;
    user-select: none;
}

.cart-text {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: center;
    margin-top: 15;

    font-family: 'Montserrat';
    color: #222;
    letter-spacing: 2px;
}

.cart-text h3 {
    font-size: 16px;
    text-transform: uppercase;
    font-weight: bold;
    color: #222;
    cursor: pointer;
    user-select: none;
}

.cart-text h3:hover {
    color: rgb(196, 8, 8);
}

.cart-text p {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    color: #222;
    cursor: text;
}

.cart-text p span {
    margin: 0 5;
}

.cart-text p span:first-child {
    margin-left: 0;
}

.cart-text .x {
    font-size: 10px;
}

.remove-product {
    margin-left: 30;
    font-size: 18px;
    cursor: pointer;
    color: #222;
}

.remove-product:hover {
    color: rgb(196, 8, 8);
}

.no-product {
    margin-top: 10;
    display: flex;
    align-items: center;
    justify-content: center;
}

.no-product h3 {
    user-select: auto;
}

.no-product h3:hover {
    color: #222;
    cursor: text;
}

.total-price {
    display: flex;
    align-items: center;
    justify-content: center;

    border-top: 1px solid #d3d3d3;
    margin-top: 10;
    padding-top: 20;
    width: 80%;
    text-align: center;
}

.total-price h3 {
    user-select: auto;
}

.total-price h3:hover {
    color: #222;
    cursor: text;
}

.price {
    font-weight: normal;
}

@keyframes slide {
    from {
        opacity: 0;
        transform: translateX(500px);
    }
    to {
        opacity: 1;
        transform: translateX(0);
    }
}

/* Burger Navigation Links */

.burger {
    display: none;
    cursor: pointer;
    animation-delay: 0s;
    animation-duration: 1s;
    width: 50px;
}

.line {
    width: 25px;
    height: 3px ;
    background-color: #222;
    margin: 4px;
    margin-right: 100px;
    transition: ease 0.5s;
}

.burger:hover .line {
    background-color: rgb(196, 8, 8);
}

.burger:hover .line:nth-child(1) {
    margin-left: -5px;
}

.burger:hover .line:nth-child(2) {
    margin-left: 3px;
    width: 30;
}

.burger:hover .line:nth-child(3) {
    width: 20;
    margin-left: -3px;
}

JS:
// Cart Slides in on Button Click

    const cartButton = document.querySelector("#cart-button");

    body.addEventListener("click", () => {

        // On Body Click, Make Shopping Cart Dissapear
        shopCart.style.animation = "";

    });

    cartButton.addEventListener("click", (ev) => {

        // Cart Button Click SLides In Shopping Cart
        if (shopCart.style.animation === "") {
            shopCart.style.animation = "slide 0.3s ease-in forwards";
        } else {
            shopCart.style.animation = "";
        }

        // Remove Search Bar
        searchBar.style.animation = "";

        // Stop Body Clicl From Interrupting
        ev.stopPropagation();
    });

    shopCart.addEventListener("click", (ev) => {
        // Stop Body Clicl From Interrupting
        ev.stopPropagation();
    });

// Add Items To Cart On Button Click

    (function () {

        // Adding the Product Item
        const cartBtn = document.querySelectorAll(".product-button");
        cartBtn.forEach (function (btn) {
            btn.addEventListener('click', function(event) {

                // Fetch Image
                let fullPath = event.target.parentElement.previousElementSibling.children[0].src;
                let pos = fullPath.indexOf("Niels") + 5;
                let partPath = fullPath.slice(pos);

                // Fetch Product Name
                let productName = event.target.previousElementSibling.previousElementSibling.textContent;

                // Fetch Product Cost
                let productCost = event.target.previousElementSibling.textContent;
                let finalPrice = productCost.slice(2).trim();

                // Initialize Item Description
                const item = {};
                    item.img = `..${partPath}`;
                    item.name = productName;
                    item.price = finalPrice;

                // Create the List Item
                const cartItem = document.createElement('li');
                cartItem.classList.add('product-cart-item');
                cartItem.innerHTML = `

 ${item.name}

$${item.price}

                `;

                // Insert Product Item Into Cart as a List Item
                const cartList = document.querySelector('.cart-list');
                cartList.appendChild(cartItem);
                alert('Item added to cart.');

                // Remove Product List on Remove Button Click -- !DOES NOT WORK! --
                const removeBtn = document.querySelectorAll('.remove-product')
                removeBtn.forEach (function (rBtn) {
                    rBtn.addEventListener('click', function () {
                        cartItem.remove();
                    });
                });

                // Update Total
                showTotals();

            });
        });

        // Showing the Total Price
        function showTotals () {
            const total = [];
            const items = document.querySelectorAll('.price');

            // Fetch Prices As Numbers Into Array
            items.forEach (function (item) {
                itemCartPriceDollar = item.textContent;
                itemCartPrice = itemCartPriceDollar.slice(1);
                total.push(parseFloat(itemCartPrice));
            });

            // Add the Prices
            const totalMoney = total.reduce(function (total, item) {
                  total += item;
                  return total;
              }, 0);
            const finalMoney = totalMoney.toFixed(2);

            // Display into Total
            document.querySelector('.total-price h3').textContent = `$${finalMoney}`;
            document.querySelector('.item-count').textContent = total.length;
        }

            // Remove "No Products in Cart" Text if there is Products
            let noProduct = document.querySelector('.no-product');
            if (total.length == 0) {
                noProduct.style.display = 'flex';
            } else {
                noProduct.style.display = 'none';
            }
    }) ();

A: Ok so make the total variable globall so that you can update it on remove and add product case. Then pass to the dom as well to display. Below you can see the working example. Hope it helps :)

//Ad Items To Cart On Button Click
(function () {
let total = [];
let cartItem;
let finalMoney;
    // Adding the Product Item
    const cartBtn = document.querySelectorAll(".product-button");
    cartBtn.forEach (function (btn) {
        btn.addEventListener('click', function(event) {

            // Fetch Image
            let fullPath = event.target.parentElement.previousElementSibling.children[0].src;
            let pos = fullPath.indexOf("Niels") + 5;
            let partPath = fullPath.slice(pos);

            // Fetch Product Name
            let productName = event.target.previousElementSibling.previousElementSibling.textContent;

            // Fetch Product Cost
            let productCost = event.target.previousElementSibling.textContent;
            let finalPrice = productCost.slice(2).trim();

            // Initialize Item Description
            const item = {};
                item.img = `..${partPath}`;
                item.name = productName;
                item.price = finalPrice;

            // Create the List Item
            cartItem = document.createElement('li');
            cartItem.classList.add('product-cart-item');
            cartItem.innerHTML = `

 ${item.name}

$${item.price}

                remove button
            `;

            // Insert Product Item Into Cart as a List Item
            const cartList = document.querySelector('.cart-list');
            cartList.appendChild(cartItem);
            alert('Item added to cart.');

            // Remove "No Products in Cart" Text if there is Products
            let noProduct = document.querySelector('.no-product');
            const cartHeight = document.querySelector('.cart-list').offsetHeight;
            if (cartHeight >= 79) {
                noProduct.style.display = 'none';
            } else {
                noProduct.style.display = 'flex';
            }

            // Remove Product List on Remove Button Click -- !DOES NOT WORK! --
            const removeBtn = document.querySelectorAll('.remove-product')
            removeBtn.forEach (function (rBtn) {
                rBtn.addEventListener('click', removeCartItems);
            })

            // Update Total
            showTotals();

        });
    });

  function removeCartItems(e){
    let selectedItem = event.target.parentElement;

 finalMoney= (total)?(finalMoney -total.pop()).toFixed(2): 0;

    //Display Total Cart Items
    document.querySelector('.item-count').textContent = total.length;

    //Display into Total
    document.querySelector('.total-price h3').textContent = `$${finalMoney}`;

    selectedItem.remove();
  }

  // Showing the Total Price
  function showTotals () {
    total = [];
    const items = document.querySelectorAll('.price');

    // Fetch Prices As Numbers Into Array
    items.forEach (function (item) {
      itemCartPriceDollar = item.textContent;
      itemCartPrice = itemCartPriceDollar.slice(1);
      total.push(parseFloat(itemCartPrice));
    });

    // Add the Prices
    const totalMoney = total.reduce(function (total, item) {
      total += item;
      return total;
    }, 0);
    finalMoney = totalMoney.toFixed(2);

    // Display into Total
    document.querySelector('.total-price h3').textContent = `$${finalMoney}`;
    document.querySelector('.item-count').textContent = total.length;
  }

}) ();
<!DOCTYPE html>

    <title>Website Project</title>

    <link href="css/style.css" rel="stylesheet" type="text/css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

                Creator

                Men

                Women

                    0

                <input type="text" placeholder="Search">

 No products in cart.

 $0

 Extended Play

 $420.69

                            Add to Cart

 Heartache

 $999.99

                            Add to Cart

                ...


text:
Q: Array Out of Bounds Exception in 2D array - how can I avoid this? I'm a begginer in Java and I am writing a program to solve mazes, as an assignment. Right now, I'm having a hard time with something that may be pretty stupid on the part that reads the maze from a cvs file, but I just can't fix it.
I get ArrayOutOfBounds exception for the line that says "while (info[x] != null) {", for some reason. I need to check if the array element is empty or not for my program to run, but it's not working. Any ideas?
public class Project5v2
{

static String mazecsv = "/Users/amorimph/Documents/COMP 182/Project 5/mazeinput.csv";
static File solvedMaze = new File("/Users/amorimph/Documents/COMP 182/Project 5/solvedMaze.txt");
static int[][] maze = new int[50][50];
static int trigger = 0;
static int mazeWidth;
static int mazeHeight;

public static void main(String[] args) {

    readCSV(mazecsv);
    start(maze);
    mazeToString(maze);

}

public static void readCSV(String csvfile) {

    BufferedReader br = null;
    String line = "";
    String csvSplitBy = ",";
    int x = 1;
    int y = 0;

    try {

        br = new BufferedReader(new FileReader(csvfile));
        br.readLine();

           while ((line = br.readLine()) != null) {

               String[] info = line.split(csvSplitBy);

               while (info[x] != null) {
                   maze[x][y] = Integer.parseInt(info[x]);
                   x++;
                   mazeWidth = x;
               }
               y++;
               x = 1;
               mazeHeight = y;

           }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

A: change this to a for loop
while (info[x] != null) {
      maze[x][y] = Integer.parseInt(info[x]);
      x++;
      mazeWidth = x;
}

to:
for (int x = 0; x < info.length; x++) {
      maze[x][y] = Integer.parseInt(info[x]);
}
mazeWidth = info.length;

This is assuming that info will not be greater than 50, which is the size that you have defined for maze.  If this is not guaranteed then
for (int x = 0; x < info.length && x < maze.length; x++) {

A: You are getting the error on that line because there is nothing to stop x from incrementing to a number BEYOND the greatest row value in maze. So one thing that you could do if you wanted to keep the while loop is add another condition.
Just add this to your while loop, IFF you need or want to keep the while around.
while(info[x] != null && x < maze.length)
{
     //magicalness
}

The additional boolean statement prevents the OutOfBounds error by making sure x is not greater than the number of rows in the 2D array or the length of the array called info.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Apex update trigger - update lookup field I'm trying to write my first Apex update trigger and struggling slightly as I'm trying to set the value of a custom lookup field.
I have an object called Deployment__c which is the master in a master-detail relationship with an object called Service__c (names simplified!)
The Service__c field has no Owner in Salesforce as it is the child/detail in a master-detail relationship. Therefore we have created a pseudo-owner field called Owner__c on this object, which is a lookup field looking up the User object in Salesforce.
The aim of the trigger is to set the value of Service__c.Owner__c to that of the user who is the owner of Deployment__c, if there is no Owner__c already set on Service__c.
The code I have is as follows:
trigger AfterServiceUpdate on Service__c (before update) {
    for (Service__c oldService : Trigger.new) {
        if (oldService.Owner__c == null) {
            User defaultUser = [Select Id FROM User WHERE User.Id = :oldService.Deployment__r.OwnerId];
            oldService.Owner__c = defaultUser.Id;
        }
    }
}

However, I get an error when I try to save this trigger:

Error: Compile Error: Invalid field Owner__c for SObject ASE_Deployment__c at line 5 column 13

I've verified that I have the field name correct, but can't get this to work. Any pointers welcome!

A: I just recreated that object structure you described in a test org and was unable to reproduce the error you got. On another note I was able to get the trigger you described to work with the following code which has been bulkified for you:
trigger AfterServiceUpdate on Service__c (before update)
{
    //instantiate set to hold unique deployment record ids
    Set<Id> deplomentIds = new Set<Id>();
    for(Service__c s : Trigger.new)
    {
        deplomentIds.add(s.Deployment__c);
    }

    //instantiate map to hold deployment record ids to their corresponding ownerids
    Map<Id, Deployment__c> deploymentOwnerMap = new Map<Id, Deployment__c>([SELECT Id, OwnerId FROM Deployment__c WHERE Id IN: deplomentIds]);

    for (Service__c s : Trigger.new)
    {
        if (s.Owner__c == null && deploymentOwnerMap.containsKey(s.Deployment__c))
        {
            s.Owner__c = deploymentOwnerMap.get(s.Deployment__c).OwnerId;
        }
    }
}

I also created a test class for you to test the result:
@isTest
private class AfterServiceUpdateTest {

    @isTest static void test_method_one() {
        Deployment__c d = new Deployment__c();
        insert d;

        Service__c s = new Service__c();
        s.Deployment__c = d.Id;
        insert s;

        Id deploymentOwnerId = [SELECT Id, OwnerId FROM Deployment__c WHERE Id=:d.Id].OwnerId;

        test.startTest();

        update s;

        Service__c updatedService = [SELECT Id, Owner__c FROM Service__c WHERE Id=:s.Id];

        system.assertEquals(deploymentOwnerId, updatedService.Owner__c);

        test.stopTest();
    }

}

Hope this helps!

A: Try change owner__c to Ownerld


text:
Q: Force another application SendToBack I need my form in front of an application. However, the common methods do not work.
Methods already tried
//method #1

PostMessage(HD, WM_USER, 0, 0);
SetWindowPos(HD, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE);

//method #2
dwThreadID := GetWindowThreadProcessId(HD, nil);
dwCurrentThreadID := GetCurrentThreadId;
AttachThreadInput(dwCurrentThreadID, dwThreadID, true);
BringWindowToTop(Aff.handle);
ShowWindow(Aff.handle, SW_SHOW);

Application in question

Comments
The application in question only works in full screen mode.
I do not want complete code, only a way forward.
Excuse me for my bad English and thanks for your time.

A: You are setting your form to the bottom. To make it topmost:
SetWindowPos(handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOACTIVATE or SWP_NOMOVE or SWP_NOSIZE);

Another approach, if you really want to force external application to the background you need to get its handle. For example, if such application is named calc:
hCalc := FindWindow('calc', nil);
SendMessage(hCalc , WM_SYSCOMMAND, SC_MINIMIZE, 0); // you can also minimize the application
SetWindowPos(hCalc , HWND_BOTTOM, 0, 0, 0, 0,  SWP_NOACTIVATE or SWP_NOMOVE or SWP_NOSIZE);

A: You can try this:
function ForceForegroundWindow(AHandle: THandle): Boolean;
var
  Input: TInput;
begin
  Result := True;

  ZeroMemory(@Input, SizeOf(Input));
  SendInput(1, Input, SizeOf(Input));
  SetForegroundWindow(AHandle);
end;

Credits to Sertac Akyuz from (How to bring my application to the front?)


text:
Q: Remove or hide a menu item in Odoo I have this menu item, and I want to hide or remove it.

A: No need to create a group and assign a group to the menu. You can simply make the menu inactive by setting menu active="False". Here is an example,
<menuitem id="module.menu_id" active="False"/>

A: If you want to hide it, go to the views section of your module, find that item and edit your list of groups with users, able to see it. For example, one of my menu items down below:
 <menuitem id="tabel_menu_emp_by_division" name="Employees by division"
              parent="tabel_menu"
              action="tabel_list_emp_action_group_by_division"  sequence="5" groups="Tabel.group_manager,Tabel.group_accountant,Tabel.group_eco"/>

As we can see, only listed groups (Tabel.group_manager,Tabel.group_accountant,Tabel.group_eco) can see that menu item.
If you want to remove it, just delete it from the views section.

A: if it has no sub-menus you can reuse it with your own action and name and parent
    <menuitem id="module.old_menu_id" name="your string here" parent="your_parent_menu_id"
action="your_action_id"
sequence="10"
groups="your_groups_here"/>

with this way it will hide from its location and appear in your parent menu with your action

A: First create a dummy group with no users in it
<record id="make_invisible" model="res.groups">
    <field name="name">Invisible</field>
 </record>

Replace all users in the group. The eval statement here means, replace all ids in the groups_id field with the id for group make_invisible.
<record model="ir.ui.menu" id="module.menu_name">
    <field name="groups_id" eval="[(6,0,[ref('make_invisible')])]"/>
</record>

You can find more information on how the eval works here

A: Create a new group with no users in it and assign the menu item to this group.

A: If you are looking for a solution with no group then try active="false" after overriding the menuitem.


text:
Q: How do i verifying User password from mysql DB I have a problem by verifying a user password from my mySQL DB.
At first i hash my Password and write it to my DB:
First my register Handler:
class RegisterHandler
{
    /**
     * @var RegisterQuery
     *
     */
    private $register;

    /**
     * @var HashPassword
     *
     */
    private $HashPassword;

    /**
     * @var string
     *
     */
    private $getUsername;

    /**
     * @var string
     *
     */
    private $username;

    public function __construct()
    {
        $this->username = $_POST['username'];
        $this->register = new RegisterQuery;
        $this->checkUsername = new SelectUsernameQuery;
        $this->HashPassword = new HashPassword($_POST['password']);
    }

    public function execute()
    {
        $hashedPassword = $this->HashPassword->getHashedPassword();
        $salt = $this->HashPassword->getSalt();

        $dbUser = $this->checkUsername->execute($this->username);
        $dbUser->bindValue( 1, $this->username);
        $dbUser->execute();

        if( !$dbUser->rowCount() == 0 ) { # If rows are found for query
            echo "Username found";
            return;
        }

        $this->register->execute($this->username, $hashedPassword, $salt, $_POST['name']);

    }
}

You can see i hash my password in the execute function with this code: (forget salt i dont use it anymore)
class HashPassword
{
    /**
     * @var string
     *
     */
    private $salt = 'x';

    /**
     * @var string
     *
     */
    private $hashedPassword;

    public function __construct($password)
    {
        $this->hashedPassword = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
        $this->getHashedPassword();
    }

    public function getHashedPassword()
    {
        return $this->hashedPassword;
    }
}

after hashing the password i write the hash into de DB.
And now is my question:
How do i get the password from DB to verify it?
i tried it:
class LoginHandler
{

    private $databaseWrapper;

    /**
     * @var SelectUsernameQuery
     *
     */
    private $checkUsername;

    private $checkPassword;

    /**
     * @var string
     *
     */
    private $enteredUsername;

    /**
     * @var string
     *
     */
    private $enteredPassword;

    /**
     * @var HashPassword
     *
     */
    private $passwordHasher;

    public function __construct()
    {
        $this->databaseWrapper = new DatabaseWrapper;
        $this->checkUsername = new SelectUsernameQuery;
        $this->checkPassword = new SelectPasswordQuery;
        $this->enteredUsername = $_POST['username'];

        $this->passwordHasher = new HashPassword($this->enteredPassword);
    }

    private function createSessionName()
    {
        $_SESSION['name'] = $this->enteredUsername;
    }

    public function execute()
    {
        $this->verifyUser();
    }

    private function verifyUser()
    {
        $this->enteredPassword = $_POST['password'];
        $userDBHash = $this->checkPassword->execute($this->enteredUsername);
        $userDBHash->execute();
        if(password_verify($this->enteredPassword, $userDBHash))
        {
            echo 'password is valid';
        }

        $dbUsername = $this->checkUsername->execute($this->enteredUsername);
        $dbUsername->bindValue( 1, $this->enteredUsername);
        $dbUsername->execute();

        if( !$dbUsername->rowCount() == 0 ) { # If rows are found for query
            echo 'Username: '."$this->enteredUsername".' was found!';
            $this->createSessionName();
            return;
        }

        echo 'Ups, This Username: '."$this->enteredUsername".' was not found!';    }
    }
}

In the verifyUser class i write the enteredpassword in a variable
After that i get the hash from DB in $userDBHash with this query:
private function getUsername($username)
{
    return $this->databaseWrapper->getPDO()->prepare(
           "SELECT password FROM users WHERE username = '$username'");
}

After that I try to password_verify($this->enteredPassword, $userDBHash)
but i get the following error:
Warning: password_verify() expects parameter 2 to be string, object given in /var/www/c2b/src/Handlers/LoginHandler.php on line 72

A: Your problem seems to be, how to get the password hash from the database. I made a quick example out of my head (not tested), but it should get you started.
private function getPasswordHashFromDatabase($username)
{
  $pdo = $this->databaseWrapper->getPDO();
  $stmt = $pdo->prepare('SELECT password FROM users WHERE username = ?');
  $stmt->bindParam(1, $username);
  if ($stmt->execute())
  {
    if ($row = $stmt->fetch())
    {
      return $row[0];
    }
  }
  return '';
}

Note the ? in the select statement, using prepared statements protects your application from SQL-injection.


text:
Q: /bin/python: No module named typing; 'pip' is a package and cannot be directly executed [root@VM-4-13-centos ~]#  python -m pip install Django
/bin/python: No module named typing; 'pip' is a package and cannot be directly executed
[root@VM-4-13-centos ~]# sudo apt install python-pip python3-pip
sudo: apt: command not found
[root@VM-4-13-centos ~]# sudo yum install python-pip python3-pip
Loaded plugins: fastestmirror, langpacks
Repository epel is listed more than once in the configuration
Loading mirror speeds from cached hostfile
Package python2-pip-8.1.2-14.el7.noarch already installed and latest version
Package python3-pip-9.0.3-8.el7.noarch already installed and latest version
Nothing to do
[root@VM-4-13-centos ~]#  python -m pip install Django
/bin/python: No module named typing; 'pip' is a package and cannot be directly executed

A: *

*Try running pip install Django

*Or upgrade python to 3.* something and then try python[version] -m pip install Django
Or here is the answer which I find helpful
I had the same issue and none of the previous answers solved it for me.
The error appeared when I uninstalled and reinstalled python to my PC. As it appears the previously existing version of pip wasn't completely removed and when I was trying to import it with python -m pip install package it was actually trying to call the previous version.
To solve it first manually delete the pip folders in the following locations:
C:\Users\username\pip
C:\Users\username\AppData\Local\pip
C:\Users\username\AppData\Local\Programs\Python\Python**\lib\site-packages\pip***
C:\Python**\pip

Then download get-pip.py.
Finally, navigate to the folder where you downloaded it and run:
python get-pip.py

This procedure should reinstall pip and fix the issue.


text:
Q: Golang SSH session ANSI Escape Codes I'm creating an scp-tui but I can't get terminal colors to work, I need them because I have to differenciate folders from files. When I call the command ls it returns only the string with the list of the files without colors. How can I get it working?
    session, err := sshClient.NewSession()
    handleError(err)
    defer session.Close()

    // Set up terminal modes
    modes := ssh.TerminalModes{
        ssh.ECHO:          0, // disable echoing
        ssh.ECHOCTL:       0,
        ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
        ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
    }

    err = session.RequestPty("xterm", 80, 40, modes)

    handleError(err)

    var output []byte
    output, err = session.Output("ls")

    fmt.Printf("output: %v\n", output)
    return string(output), err

P.S. Are there better ways to get a list of files and folders of the current directory?
Update: I temporarely resolved the issue by executing two distinct commands to get first the files and then the directories.

A: Not quite sure how the terminal output color is implicitly rendered based on the code provided. That said I found this piece and hope it helps out. https://twin.sh/articles/35/how-to-add-colors-to-your-console-terminal-output-in-go.


text:
Q: Google map marker with Fresco for android problem on Oreo I tried to display images in Google map marker using SimpleDraweeView via URI, but only drawable is displayed.
My SimpleDraweeView work just fine from another activity and I can see the images
but when using map marker it doesn't show me any Uri images only drawable is shown on Oreo (8)  it worked fine with the version before 8
I tried to use drawee controller same problem
Please check and advise
thank you
MapActivity.class
public void markProjects() {
    View marker = ((LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE)).
 inflate(R.layout.custom_marker_layout, null);

    for (int i = 0; i < userResult.size(); i++) {
        final UserModel fillMapModel = userResult.get(i);
        double lon = fillMapModel.getLongitude();
        double lat = fillMapModel.getLatitude();
        LatLng latlng = new LatLng(lat, lon);
        int pinId;
        if (myProfile.getIdUser().
 equals(Integer.toString(fillMapModel.getIdUser())))
            pinId = R.drawable.my_pin;
        else
            pinId = R.drawable.user_pin;

        String titleSub;
        String fullName;
        if (!fillMapModel.getFullName().equals(""))
            fullName = fillMapModel.getFullName();
        else

            fullName = fillMapModel.getFirstName() + " " + fillMapModel.getLastName();

        if (fullName.length() < 26)
            titleSub = fullName;
        else
            titleSub = fullName.substring(0, 25) + "...";

        mMap.addMarker(new MarkerOptions()
                .position(latlng)
                .title(titleSub)
                .icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(marker, fillMapModel.getImage()))));

        mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
            public void onInfoWindowClick(Marker marker) {
                openProjectDetails(marker);

            }

        });
        mOverlayMap.setVisibility(View.GONE);
    }
}

public Bitmap createDrawableFromView(View view, String url) {
    DisplayMetrics displayMetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    view.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
    view.measure(displayMetrics.widthPixels, displayMetrics.heightPixels);
    view.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels);
    SimpleDraweeView image = (SimpleDraweeView) view.findViewById(R.id.user_image);
    if (!url.equals("0") && !url.equals("")) {
        image.setImageURI(Uri.parse(url));
    } else {
        image.setImageResource(R.drawable.user_pin_pic);
    }
    view.buildDrawingCache();
    Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);

    Canvas canvas = new Canvas(bitmap);
    view.draw(canvas);

    return bitmap;
}

activity_maps.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    </android.support.design.widget.AppBarLayout>

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <fragment
            android:id="@+id/map"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context=".ui.MapActivity"
            class="com.inmob.chatin.fragment.MySupportMapFragment"/>

        <com.inmob.chatin.views.OverlayMyMap
            android:id="@+id/mapOverLayView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:background="@color/dark_light_transparent"
            android:visibility="gone" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:gravity="center_vertical"
            android:layout_alignParentRight="true"
            android:orientation="vertical"
            android:paddingBottom="50dp"
            android:layout_marginBottom="20dp">

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/fab_button_my_location"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right"

         android:layout_marginBottom="@dimen/codelab_fab_margin_bottom"
                android:layout_marginRight="@dimen/codelab_fab_margin_right"
                android:paddingTop="@dimen/codelab_fab_padding_bottom"
                android:src="@drawable/current_location"
                app:backgroundTint="@color/white"
                app:fabSize="normal" />

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/fab_button_draw"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right"

  android:layout_marginBottom="@dimen/codelab_fab_margin_bottom"
                android:layout_marginRight="@dimen/codelab_fab_margin_right"
                android:paddingBottom="@dimen/codelab_fab_padding_bottom"
                android:src="@drawable/map_pen"
                app:backgroundTint="@color/colorPrimary"
                app:fabSize="normal" />

        </LinearLayout>

    </RelativeLayout>

</LinearLayout>

</RelativeLayout>

custom_marker_layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:fresco="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content">

<ImageView
    android:layout_width="94dp"
    android:layout_height="94dp"
    android:src="@drawable/user_pin" />

<com.facebook.drawee.view.SimpleDraweeView
    android:id="@+id/user_image"
    android:layout_width="90dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="1dp"
    android:layout_marginTop="6dp"
    fresco:actualImageScaleType="focusCrop"
    fresco:fadeDuration="300"
    fresco:placeholderImage="@color/colorAccent"
    fresco:placeholderImageScaleType="fitCenter"
    fresco:roundAsCircle="true"
    fresco:roundingBorderWidth="2dp"
    fresco:viewAspectRatio="1.33" />
    </RelativeLayout>

Gradle
android {
compileSdkVersion 27
buildToolsVersion "27.0.3"
useLibrary 'org.apache.http.legacy'

sourceSets.main {
    jniLibs.srcDir 'libs'
    jni.srcDirs = [] //disable automatic ndk-build call
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation files('libs/libjingle_peerconnection.jar')

implementation project(":simple-crop-image-lib")
implementation project(":autobahn")
//compile project(":xmpp")
implementation project(":xmpplibrary")

implementation project(":linkedin-sdk")
implementation('com.facebook.fresco:fresco:0.13.0+') {
    exclude group: 'com.parse.bolts', module: 'bolts-applinks'
    exclude module: 'bolts-android'
    exclude group: 'com.parse.bolts', module: 'bolts-tasks'
}

implementation('com.crashlytics.sdk.android:crashlytics:2.5.5@aar') {
    transitive = true
}
implementation 'com.googlecode.libphonenumber:libphonenumber:8.7.1'
implementation group: 'com.nineoldandroids', name: 'library', version:
'2.4.0'
implementation 'com.android.support:multidex:1.0.1'
//noinspection GradleCompatible
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support:mediarouter-v7:27.1.1'
implementation 'com.android.support:design:27.1.1'
implementation 'com.android.support:cardview-v7:27.1.1'
implementation 'com.android.support:recyclerview-v7:27.1.1'
implementation 'com.android.support:support-v4:27.1.1'
implementation 'com.google.code.gson:gson:2.8.0'
implementation 'link.fls:swipestack:0.3.0'
implementation 'com.nispok:snackbar:2.11.0'
implementation 'com.facebook.android:facebook-android-sdk:4.26.0'
implementation 'com.google.android.gms:play-services-maps:15.0.1'
implementation 'com.google.android.gms:play-services-location:15.0.1'
implementation 'com.google.android.gms:play-services-identity:15.0.1'
implementation 'com.google.android.gms:play-services-gcm:15.0.1'
implementation 'com.google.android.gms:play-services-plus:15.0.1'
implementation 'com.google.android.gms:play-services-auth:15.0.1'
implementation 'com.google.android.gms:play-services-places:15.0.1'
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'com.squareup.okhttp3:okhttp:3.8.0'
implementation 'it.sephiroth.android.library.easing:android-easing:1.0.3'
implementation 'com.romainpiel.shimmer:library:1.4.0'
implementation 'com.tonicartos:stickygridheaders:1.0.1'
implementation 'com.github.chrisbanes.photoview:library:1.2.2'
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
testImplementation 'junit:junit:4.12'
implementation 'org.glassfish:javax.annotation:10.0-b28'
implementation 'com.google.android.gms:play-services-analytics:16.0.1'
}
apply plugin: 'com.google.gms.google-services'

version below 8:

version 8:


text:
Q: tinkerpop gremlin clear console not working i'm a newbie to tinkerpop gremlin. querying neptune DB using apache-tinkerpop-gremlin-console

gremlin> :c
gremlin> :clear

is not clear the screen / console as "cls" command clears the screen in windows cmd. Please comment / give suggestions to clear the gremlin console

A: On Windows there is no easy way to clear the screen. On Linux and on Mac OS X typing CTRL-L will clear the screen.
:c and :clear will reset the terminal after a query fails with an error or is asking for more input and you want to abort the query.
Edited to add:
If the Gremlin console is in local mode (in other words you type :remote console to put it into local mode) you can do this:
gremlin> def cls() {
......1> for (a in 1..50) println " " }

then typing cls() will clear the screen
Edited again to add:
On more recent Windows 10 updates try this command in the Gremlin Console when in local mode.
println("\033[H\033[2J")

Or if your are already connected to the remote server try just entering the string on its own.
"\033H\033[2J\033[H"


text:
Q: C++ How to avoid friend template functions with home-made intrusive lists I need an intrusive, sorted, double-linked list.  I do not want to use boost::intrusive, so I'm doing this myself and running into an issue
For a doubly-linked list there are several operations, here is just one of them which will help to illustrate my point:
template<typename LIST, typename NODE>
void insertAfter(LIST *list, NODE *node, NODE *newNode)
{
    newNode->prev_ = node;
    newNode->next_ = node->next_;
    if(nullptr == node->next_)
        list->last_ = newNode;
    else
        node->next_->prev_ = newNode;
    node->next_ = newNode;
}

Now suppose I have a set of objects that are in one such list BUT I want their guts private:
struct Object
{
private:
    Object *prev_, *next_;
};

Now I create my List (please ignore the fact that when the list is empty there will be a nullptr exception...).
struct List
{
    Object *first_, *last_;

    void addObject(Object *o)
    {
        insertAfter(this, last_, o);  // not correct when list empty
    }
};

This will not compile because prev_ and next_ are private and insertAfter does not have access.  It can be solved easily with this:
// Fwd decl
struct List;

struct Object
{
    friend void insertAfter<List, Object>(List *, Object *, Object *);
private:
    Object *prev_, *next_;
};

struct List
{
    Object *first_, *last_;

    void addObject(Object *o)
    {
        insertAfter(this, last_, o);
    }
};

But this opens an access hole such that anyone can use insertAfter to affect Object's private members.  What I really want is for List to be a friend of Object.
I could solve this by not using templates for my linked list operation (use plain macros instead) but this obviously has its downside.  What's the right way to go here?

A: How about something along these lines?
template<class ObjectType>
class List
{
    ObjectType *first_, *last_;

public:
    void addObject(ObjectType *o)
    {
        insertAfter(this, last_, o);
    }

    void insertAfter(ObjectType *node, ObjectType *newNode)
    {
        newNode->prev_ = node;
        newNode->next_ = node->next_;
        if(nullptr == node->next_)
            this->last_ = newNode;
        else
            node->next_->prev_ = newNode;
        node->next_ = newNode;
    }
};

class Object
{
private:
    Object *prev_, *next_;

    friend class List<Object>;
};

int main() {}

I can't see how it's really less offensive than what you've been doing already, though: template code is inline anyway, so you can't stop people from rewriting your class to their liking. Just relax and have reasonable degree of trust in your clients :)

A: You may do encapsulate the intrusive data, something like:
template <typename Object>
class List
{
public:
    class PrivateData
    {
        friend class List;
    public: // minimal stuff which should be public go here
        PrivateData() : prev_(nullptr), next_(nullptr) {}
    private:
        // other stuff
        Object *prev_, *next_;
    };

    // Other stuff

};

And then in your Object:
class Object
{
public:
    List<Object>::privateData listData_;
private:
    // internal data.
};

As all things in ListData are private, user can't do anything with listData_
but can be accessed by List which is friend.


text:
Q: Is there a recommended approach to referencing an instantiated class object in React / Nextjs? Let's say I have a Node.js library that I need to instantiate in my React app.
const awesomeLibrary = new AwesomeLibrary('someID', options);

awesomeLibrary allows me to do things like awesomeLibrary.configure(), awesomeLibrary.specifyCustomProperty() and awesomeLibrary.fireEvent().
I would like to instantiate it once and then call those methods from the instantiated reference (awesomeLibrary) around my application. What is the best way to that?
Would I instantiate it in top-level entry component (e.g. _app.tsx), export it, import it into other components and call the methods? In order to export it, I'd have to instantiate it outside the component, instead of in the lifecycle of the component. Is that a bad practice?
Alternatively, could I relegate the instantiation to a hook? Say useAwesomeLibrary() in which I instantiate and export the methods? But wouldn't doing that create an instance every time the hook is called from different components?
I'm really not sure how to handle this.

A: Instantiating class before exporting it is a fairly common practice and one of the possible implementations of singleton in JavaScript/React. For example, you can use popular i18next library in this way:
services/i18n.js:
import i18n from 'i18next';

i18n.init({
  // pass translations and other config
});

export default i18n;

_app.js:
import i18n from 'services/i18n';

// snip

<I18NextProvider i18n={i18n} /> // consume already instantiated i18n object

The difference between this and instantiating object in a hook is WHEN it will be instantiated. When you do this in hook, it will instantiate every time you mount component with this hook. When in separate file (module), then it will be once per page load.
Is that a bad practice? I don't know, it depends on how you'd use it. There is nothing bad in doing this per se, and even it has its advantages (in the example above we delegated responsibility of creating and configuring i18n service from _app.js, which is very good from Single Responsibility Principle perspective). But keep in mind that codebase bloated with singletons will probably become hard to maintain.


text:
Q: Should this C# code be refactored to use the Lazy class instead? I have the following code which could be called via multiple web-requests at the same second. As such, I don't want the second+ request hitting the database, but waiting until the first one does.
Should I refactor this to use the Lazy<T> keyword class instead? If 10 calls to a Lazy<T> piece of code occur at the same time, do 9 of those calls wait for the first one to complete?
public class ThemeService : IThemeService
{
    private static readonly object SyncLock = new object();
    private static IList<Theme> _themes;
    private readonly IRepository<Theme> _themeRepository;

    <snip snip snip>

    #region Implementation of IThemeService

    public IList<Theme> Find()
    {
        if (_themes == null)
        {
            lock (SyncLock)
            {
                if (_themes == null)
                {
                    // Load all the themes from the Db.
                    _themes = _themeRepository.Find().ToList();
                }
            }
        }

        return _themes;
    }

    <sip snip snip>

    #endregion
}

A: As @BrokenGlass pointed out it is safe. But I couldn't resist and had to make a test...
Only one thread id is printed...
private static Lazy<int> lazyInt;

// make it slow
private int fib()
{
    Thread.Sleep(1000);
    return 0;
}

public void Test()
{
    // when run prints the thread id
    lazyInt = new Lazy<int>(
        () =>
        {
            Debug.WriteLine("ID: {0} ", Thread.CurrentThread.ManagedThreadId);
            return fib();
        });

    var t1 = new Thread(() => { var x = lazyInt.Value; });
    var t2 = new Thread(() => { var x = lazyInt.Value; });
    var t3 = new Thread(() => { var x = lazyInt.Value; });

    t1.Start();
    t2.Start();
    t3.Start();

    t1.Join();
    t2.Join();
    t3.Join();
}

But, which one is faster? From the results I got...
Executing the code 100 times
[   Lazy: 00:00:01.003   ]
[  Field: 00:00:01.000   ]

Executing the code 100000000 times
[   Lazy: 00:00:10.516   ]
[  Field: 00:00:17.969   ]

Test code:
Performance.Test("Lazy", TestAmount, false,
    () =>
    {
        var laz = lazyInt.Value;
    });

Performance.Test("Field", TestAmount, false,
    () =>
    {
        var laz = FieldInt;
    });

Test method:
public static void Test(string name, decimal times, bool precompile, Action fn)
{
    if (precompile)
    {
        fn();
    }

    GC.Collect();
    Thread.Sleep(2000);

    var sw = new Stopwatch();

    sw.Start();

    for (decimal i = 0; i < times; ++i)
    {
        fn();
    }

    sw.Stop();

    Console.WriteLine("[{0,15}: {1,-15}]", name, new DateTime(sw.Elapsed.Ticks).ToString("HH:mm:ss.fff"));
}

A: Yes you can use Lazy<T>
From MSDN:

By default, Lazy objects are thread-safe. That is, if the
  constructor does not specify the kind of thread safety, the Lazy
  objects it creates are thread-safe. In multithreaded scenarios, the
  first thread to access the Value property of a thread-safe Lazy
  object initializes it for all subsequent accesses on all threads, and
  all threads share the same data. Therefore, it does not matter which
  thread initializes the object, and race conditions are benign.

And yes, it's not a keyword - its a .NET framework class that formalizes the often required use case for lazy initialization and offers this out of the box so you don't have to do it "manually".


text:
Q: Eclipse Debugger will not show the shared area I've had this error before in pydev perspectives in the past, and the only solution I've ever managed was to remove the broken perspective and start a new one.
The problem is this:
Normally the different panes of the workspace can be minimized, maximized, and regular size. Right now, I cannot get the "shared area" code section of the debug perspective to show up at all. I can peak at it while it's minimized, but that's all I can manage.
What's more, eclipse automatically switches to debug, so it's basically impossible for me to debug code right now.
I'd really like to know why this is happening to me, and how to avoid and/or fix it.
Also, I'm currently running java 7, I have not updated yet.

A: You can go to Window, Reset Perspective which will give you your shared area back, although also obviously reset any other views you may have.


text:
Q: WSo2 ESB saving records in database I want to make simple wso2 web service in XML that save records in database and print logs.

A: To save the record in the database you can use the "DB Report Mediator"
<dbreport xmlns="http://ws.apache.org/ns/synapse">
    <connection>
        <pool>
            <driver>com.mysql.jdbc.Driver</driver>
            <url>jdbc:mysql://localhost:3306/db_name</url>
            <user>xxxx</user>
            <password>xxxx</password>
        </pool>
    </connection>
    <statement>
        <sql><![CDATA[insert into table_name (column1, column2, column3) values ( ?,?,? )]]></sql>
        <parameter type="VARCHAR" value="column1_entry"/>
        <parameter type="VARCHAR" value="column2_entry"/>
        <parameter type="VARCHAR" value="column3_entry"/>

    </statement>
</dbreport>

To get a record from a database, you can use the DBLookup Mediator
  <dblookup>
    <connection>
        <pool>
            <driver>com.mysql.jdbc.Driver</driver>
            <url>jdbc:mysql://localhost:3306/db_name</url>
            <user>xxxx</user>
            <password>xxxx</password>
        </pool>
    </connection>
    <statement>
        <sql><![CDATA[select * from table_name where column1 =  ?]]></sql>
        <parameter type="VARCHAR" value="column1_value"/>
        <result column="column1_name" name="result1"/>
        <result column="column2_name" name="result2"/>
        <result column="column3_name" name="result3"/>
    </statement>
  </dblookup>

We can log the results from the above dblookup statement using the Log Mediator
<log level="custom">
    <property expression="get-property('result1')" name="log1"/>
    <property expression="get-property('result2')" name="log2"/>
    <property expression="get-property('result3')" name="log3"/>
</log>

A: You can use the DB Report Mediator for writing data and also use the log mediator for printing logs. For exposing the service you can create either a proxy service or a rest api


text:
Q: Exporting a table in .png format I am trying to export a data table in PNG format. I evaluated
Ptr = {{1, 5, 10, 20, 30}};

Ttr = {{300, 300, 300, 300, 300}};

P = {{382, 390, 400, 420, 440}};

T = {{}};
m = Join[Transpose[Ttr], Transpose[Ptr], Transpose[P], Transpose[T], 2];
firstRow = {{"", "Ttr(K)", "Ptr(kPa)", "P(kPa)", "T(K)"}};
mainRows = Join[Transpose[{{"n=11", "n=12", "n=13", "n=14", "n=15"}}], m, 2];

t = Join[firstRow, mainRows];
grid =
  Text @
    Grid[t,
      Dividers -> {2 -> True, 2 ->  True},
      ItemStyle -> {Bold, Red},
      Spacings -> {2, 1}];

 SetDirectory[NotebookDirectory[]];
 Export["grid.PNG", grid,  ImageResolution -> 400,
 Background -> None];

Unfortunately, I get the image shown below in which the top side and left side are not so well exported!

I tried to solve this problem with Spacing. But it didn't work. In addition, when I exported the table as a PDF file, it worked, but I wish the image in PNG format or JPG format.

A: May be this helps:
grid = Rasterize[
   Text@Grid[t, Dividers -> {2 -> True, 2 -> True},
     ItemStyle -> {Bold, Red}, Spacings -> {2, 1}], RasterSize -> 300];

SetDirectory[NotebookDirectory[]];
Export["grid.PNG", grid, ImageSize -> 800];


text:
Q: Loop through an array ignores \n @edit
Below is the JSON getting saved as $content
[
    {
        "date_created": 1234,
        "fingerprint_hash": null,
        "address": "xx:xx:xx:xx:xx:xx",
        "name": null,
        "manufacturer": "xxx",
        "date_updated": 1234,
        "active": true,
        "date_last_active": 1234,
        "mac_group_info": {
            "name": null,
            "id": 0,
            "remarks": null
        },
        "id": 1234,
        "remarks": null,
        "arp_mapping_info": [
            {
                "ip_info": {
                    "date_changed": 1234,
                    "date_last_kerberos_login": null,
                    "dns_name": "xxxx",
                    "id": 6,
                    "remarks": null,
                    "date_created": 1234,
                    "kerberos_user_name": null,
                    "ip_group_info": {
                        "remarks": null,
                        "id": 0,
                        "name": null
                    },
                    "address": "x.x.x.x"
                },
                "interface_info": [
                    {
                        "link": "on",
                        "name": "x",
                        "discovery_info": null,
                        "speed": 1234,
                        "host_info": {
                            "backup_sensor_id": 0,
                            "type": "xxxx",
                            "radius_coa_flags": null,
                            "moment": 1,
                            "name": null,
                            "host_group_info": {
                                "name": null,
                                "id": 0,
                                "remarks": null
                            },
                            "interface_mib": "D",
                            "uplink_count": 1,
                            "sensor_info": {
                                "id": 1,
                                "os_version": "xxxx",
                                "architecture": "xxxx",
                                "remarks": null,
                                "last_contact": "xxxx",
                                "queue": 0,
                                "address": "x.x.xx",
                                "status": "active",
                                "os_name": "linux",
                                "name": "xxxx",
                                "version": "x.x.x-x"
                            },
                            "mode": "xx",
                            "address": "x.x.x.x",
                            "radius_secret": null,
                            "arp_mib": "2",
                            "cam_count": 1,
                            "discovery2_mib": "C",
                            "discovery1_mib": "3",
                            "radius_coa_port": null,
                            "radius_requests_count": 0,
                            "vlan_count": 1,
                            "access_to_port": 1,
                            "vlan_mib": "C",
                            "interval": 1,
                            "snmp_traps_community": null,
                            "engine_mode": "dynamic",
                            "manufacturer": "ciscoSystems",
                            "engine_id": null,
                            "snmp_traps_version": "1",
                            "mib_options": null,
                            "remarks": null,
                            "snmp_write_version": "2c",
                            "snmp_write_community": "private",
                            "access_to_cam": 1,
                            "status": "ok",
                            "access_to_cto": 1,
                            "access_to_interface": 1,
                            "snmp_read_version": "1",
                            "snmp_read_community": "public",
                            "id": 1,
                            "cam_mib": "C",
                            "arp_count": 1,
                            "access_to_arp": 1,
                            "port_count": 1,
                            "main_sensor_id": 1
                        },
                        "status": "on",
                        "index": 1,
                        "protocols": [
                            "ARP",
                            "NDP"
                        ],
                        "id": 1,
                        "remarks": null,
                        "sniffer_mode": null
                    }
                ],
                "host_id": 1
            }
        ],
        "cam_mapping_info": []
    }
]

Thats my code:
foreach ($content){
    $content =~ s/\[/\[\n\t/g;
    $content =~ s/{/{\n\t/g;
    $content =~ s/\]/\n\]/g;
    $content =~ s/}/}\n/g;
    $content =~ s/,/\n\t/g;
print $content;
}

Todo: get the same output as the JSON above but with a perl skript runing it withouth any modules, normaly we use postman for it. As I asked my "couch" for help he only said: just learn to programm. Yeah...
The output I get with my regex is almost the solution. It just stops tabing after the first tab, doent repeat it on another opening bracket.

A: $line eq "{" || "[" is interpreted as
(($line eq '{') or '[')

(as Deparse would show you). Use
$line eq '{' || $line eq '['

Moreover, $data is a scalar variable, i.e. it contains a single value. Iterating over it makes just a single step.
Normally, you'd iterate over an array:
foreach my $line (@lines)

or maybe an array reference:
foreach my $line (@$data)

or whatever else
foreach my $line ($line1, $line2, @rest_of_lines)
# or
foreach my $line (split /\n/, $message)

A: Using the YAML module, you can get a quick human readable format. I'm sure there are other and/or better ways to format your text, but this is one example. The benefit here is that you can transform a JSON data structure (using JSON::PP, a core Perl module that comes pre-installed) into a Perl data structure and then into a YAML structure that you can print easily. I did this with a few lines of code and a few modules, using some sample JSON data.
use strict;
use warnings;
use JSON::PP;
use YAML;

my $text = do { local $/; <DATA> };
my $json = decode_json($text);
print Dump $json;

__DATA__
{
    "ITEM":[
        {
            "-itemID": "1000000" ,
            "-itemName": "DisneyJuniorLA" ,
            "-thumbUrl": "" ,
            "-packageID": "1" ,
            "-itemPrice": "0" ,
            "-isLock": "true"
        },
        {
            "-itemID": "1000001" ,
            "-itemName": "31 minutos" ,
            "-thumbUrl": "" ,
            "-packageID": "1" ,
            "-itemPrice": "0" ,
            "-isLock": "true"
        },
        {
            "-itemID": "1000002" ,
            "-itemName": "Plaza SÚsamo" ,
            "-thumbUrl": "" ,
            "-packageID": "1" ,
            "-itemPrice": "0" ,
            "-isLock": "true"
        }
    ]
}

Output:
---
ITEM:
  - -isLock: true
    -itemID: 1000000
    -itemName: DisneyJuniorLA
    -itemPrice: 0
    -packageID: 1
    -thumbUrl: ''
  - -isLock: true
    -itemID: 1000001
    -itemName: 31 minutos
    -itemPrice: 0
    -packageID: 1
    -thumbUrl: ''
  - -isLock: true
    -itemID: 1000002
    -itemName: Plaza S┌samo
    -itemPrice: 0
    -packageID: 1
    -thumbUrl: ''

EDIT: With the new json data, I get this output:
- active: !!perl/scalar:JSON::PP::Boolean 1
  address: xx:xx:xx:xx:xx:xx
  arp_mapping_info:
    - host_id: 1
      interface_info:
        - discovery_info: ~
          host_info:
            access_to_arp: 1
            access_to_cam: 1
            access_to_cto: 1
            access_to_interface: 1
            access_to_port: 1
            address: x.x.x.x
            arp_count: 1
            arp_mib: 2
            backup_sensor_id: 0
            cam_count: 1
            cam_mib: C
            discovery1_mib: 3
            discovery2_mib: C
            engine_id: ~
            engine_mode: dynamic
            host_group_info:
              id: 0
              name: ~
              remarks: ~
            id: 1
            interface_mib: D
            interval: 1
            main_sensor_id: 1
            manufacturer: ciscoSystems
            mib_options: ~
            mode: xx
            moment: 1
            name: ~
            port_count: 1
            radius_coa_flags: ~
            radius_coa_port: ~
            radius_requests_count: 0
            radius_secret: ~
            remarks: ~
            sensor_info:
              address: x.x.xx
              architecture: xxxx
              id: 1
              last_contact: xxxx
              name: xxxx
              os_name: linux
              os_version: xxxx
              queue: 0
              remarks: ~
              status: active
              version: x.x.x-x
            snmp_read_community: public
            snmp_read_version: 1
            snmp_traps_community: ~
            snmp_traps_version: 1
            snmp_write_community: private
            snmp_write_version: 2c
            status: ok
            type: xxxx
            uplink_count: 1
            vlan_count: 1
            vlan_mib: C
          id: 1
          index: 1
          link: on
          name: x
          protocols:
            - ARP
            - NDP
          remarks: ~
          sniffer_mode: ~
          speed: 1234
          status: on
      ip_info:
        address: x.x.x.x
        date_changed: 1234
        date_created: 1234
        date_last_kerberos_login: ~
        dns_name: xxxx
        id: 6
        ip_group_info:
          id: 0
          name: ~
          remarks: ~
        kerberos_user_name: ~
        remarks: ~
  cam_mapping_info: []
  date_created: 1234
  date_last_active: 1234
  date_updated: 1234
  fingerprint_hash: ~
  id: 1234
  mac_group_info:
    id: 0
    name: ~
    remarks: ~
  manufacturer: xxx
  name: ~
  remarks: ~

A: Asked a coworker for help and he has just writen it in 5 minutes without big thinking...
use strict;
use warnings;

my $content = #JSON#
my @arr = split //, $content;
my $length = scalar @arr;
my $tabcounter = 0;
for (my $i=0; $i < $length; $i++) {

   print $arr[$i];
   if ( $arr[$i] eq '[' || $arr[$i] eq ']' || $arr[$i] eq '{' || $arr[$i] eq '}' || $arr[$i] eq ',') {
        print "\n";
        if ( $arr[$i] eq '[' || $arr[$i] eq '{' ) {
            $tabcounter++;
        }
        if ( $arr[$i] eq '}' || $arr[$i] eq ']' ) {
            $tabcounter--;
        }
        for (my $j=0; $j < $tabcounter; $j++) {
            print "\t";
        }
   }
}

So if anyone has to read and print out of a JSON file without any modules, here is the solution.


text:
Q: How to determine the "humanish" part of a git repository If I clone a git repository like this
git clone <some-repository>

git creates a directory, named as the 'humanish' part of the source repository. (according to the man page).
Now I want to create a bash script that clones a repository, 'cds' into the newly created directory, and does some stuff. Is there an easy way for the bash script to know the name of the created directory, without explicitly providing a directory to the 'git clone' command?

A: To add to Hiery's answer, you will find a complete shell script example in the git repo itself:
contrib/examples/git-clone.sh, with the relevant extract:
# Decide the directory name of the new repository
if test -n "$2"
then
    dir="$2"
    test $# = 2 || die "excess parameter to git-clone"
else
    # Derive one from the repository name
    # Try using "humanish" part of source repo if user didn't specify one
    if test -f "$repo"
    then
        # Cloning from a bundle
        dir=$(echo "$repo" | sed -e 's|/*\.bundle$||' -e 's|.*/||g')
    else
        dir=$(echo "$repo" |
            sed -e 's|/$||' -e 's|:*/*\.git$||' -e 's|.*[/:]||g')
    fi
fi

Note that it takes into account cloning a bundle (which is a repo as one file, useful when working with a repository in the cloud).

A: You need to get the url and parse it to get the latest part and strip off the .git.
#!/bin/bash
URL=$1

# Strip off everything from the beginning up to and including the last slash
REPO_DIR=${URL##*/}
# Strip off the .git part from the end of the REPO_DIR
REPO_DIR=${REPO_DIR%%.git}

git clone $URL
cd $REPO_DIR
....


text:
Q: Bluemix push notification displayed in phone OS, when clicked, won't launch the app I'm developing an App using Bluemix push notification. When the app is at foreground or background, didReceiveRemoteNotification() with completion handler is called and all is fine.
But when the app is not launched, and notification is sent by another device. the phone does display the push notification in the system notifications when you swipe down from the top, but clicking the notification won't launch the app. It just dismisses the notification. This is the same for Android and IOS.
How can I launch the app by clicking the notification?
Thanks and Best Regards,
Jen

A: For Android you must ensure you have the following in your AndroidManifest.xml, within the desired Activity you'd like to start when your app launches after clicking the notification:
<!--Notification Intent -->
<intent-filter>
   <action android:name="<Your_Android_Package_Name.IBMPushNotification"/>
   <category  android:name="android.intent.category.DEFAULT"/>
</intent-filter>

Don't forget to use your package name in place of Your_Android_Package_Name
See the helloPush example for more details.

A: For iOS you need to make sure you are also registering the application to the APNs service successfully. Once this is completed you will be able to open the application by clicking on the push notification that is received.
Objective-c:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0){
     [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:categories]];
     [[UIApplication sharedApplication] registerForRemoteNotifications];
     }
     else{
     [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
     (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)];
     }

     return YES;
}

Swift:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let notificationTypes: UIUserNotificationType = UIUserNotificationType.Badge | UIUserNotificationType.Alert | UIUserNotificationType.Sound
let notificationSettings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: categories)

application.registerUserNotificationSettings(notificationSettings)
application.registerForRemoteNotifications()
}

You can see more information regarding Push registration here:
Enabling iOS applications to receive push notifications
I would also recommend looking at our Bluemix Push Sample:
BMS iOS helloPush Sample


text:
Q: My gazebo robot with TEB local planner ignores dynamic obstacles I want to ask something.
I have a plan to use TEB local planner to avoid dynamic obstacles.
I have been following TEB local planner tutorial:

http://wiki.ros.org/teb_local_planner/Tutorials

and it works well the tutorial simulation like below picture:
dynamic obstacle avoidance with TEB local planner tutorial
And I tried to apply it for my own robot simulation, but it ignores dynamic obstacles like this:
custom_robot simulation
After comparing all of parameters with original TEB local planner, I had changed them exactly same with originals by rqt_reconfigure, but it doesn't work.
Can I sure that it must be parameter's problem or it could be another problem?


text:
Q: How can I loop over Callback functions in Java/JavaScript? I have a list of books:
List<Book> books = new ArrayList<Book>();

Now I will iterate over this list an call a function myFunction() on each object.
for(Book book: books) {

  book.myFunction();

}

Now, I have a Callback interface which is called when myFunction() finishes:
public interface MyHandler {
  void onDone();
}

So myFunction is something like:
public void myFunction(MyHandler handler) {

   ...
   handler.onDone();

}

How can I iterate over a list of books and call myFunction(MyHandler handler)?
Note that you can only continue after onDone() is called.

A: The only thing that doesn't fit is your call to myFunction(), which result in a compile error because the MyHandler parameter is missing.
You just have to provide an object that implements MyHandler to your myFunction() method. You can do this via an anonymous class like this:
for(Book book: books) {
    book.myFunction(new MyHandler() {
        void onDone() {
            // put some code you want to execute here
        }
    });
}

Side note: For posterity, in a context where you can use Java 8, you can even use a lambda expression instead of the anonymous class:
for(Book book: books) {
    book.myFunction(() -> { /* insert code for onDone() here */ });
}

A: Since you've tagged this as GWT i'm going to assume that your myFunction() call is actaully doing something asynchronous, and that is why you can't simply wait for it to return.  In this case you could do the following, although it's a bit messy:
final Iterator<Book> iter = books.iterator();
MyHandler handler = new MyHandler() {
    @Override
    public void onDone() {
        if (iter.hasNext())
            iter.next().myFunction(this);
    }
};

//
// Start it going
//
if (iter.hasNext())
    iter.next().myFunction(handler);

Note that this is now recursive, so if you have a lot of book objects the call stack is going to get quite deep, and this imposes an upper limit on the number of books before you overflow the stack (an upper limit that you can't reliably know, either)  This is not such a problem if you're using a GWT service to trigger the callback, since the stack will have unwound due to the network stuff.
I don't mean to second-guess you here, but if you are calling an async gwt service then it's going to result in a lot of calls back and forth over the network.  If this is the case then you could consider simply passing a list of Book objects to be processed to the service, instead of sending them one at a time.

A: To avoid the async calls, create a method on the server that loops thru the books and thus avoiding the rescursive calls. So you could gave just one call processMybooks(Books)


text:
Q: Is it possible to webscrape video links from Youtube search? I used Python code in the past to retrieve search result from Youtube.
I tried to use the same code again, however the HTML seems to be an empty skeleton:
import urllib.request
from bs4 import BeautifulSoup

def url_to_video(text_to_search):
    query = urllib.parse.quote(text_to_search)
    url = "https://www.youtube.com/results?search_query=" + query

    response = urllib.request.urlopen(url)
    html = response.read()
    response.close()
    soup = BeautifulSoup(html, 'html.parser')

    url_list = []
    for vid in soup.findAll(attrs={'class': 'yt-uix-tile-link'}):
        url_list.append('https://www.youtube.com' + vid['href'])
    return url_list

Did Youtube find a way to block webscraping? Is there a working alternative?


text:
Q: Self hosted SignalR with MVC Is it possible to use a self hosted signalR server with an MVC(4) application such that it is totally seperate from the signalR server?
I tried Tim and Patrick's beautifully executed SignalR intro tutorial, and was wondering if I could try that? And even if I could, would that offer any performance advantages over an integrated service as is metioned in the tutorial.

A: It is absolutely possible to self-host a SignalR 2.0 server with OWIN and accessing this server from within any Website (which may be a MVC application). The only thing you need is to enable CORS (app.UseCors(CorsOptions.AllowAll); in your Startup file of the Owin Host) since it's not on the same domain as your Website. Obviously you can't use SignalR within the MVC application itself this way (e.g. to publish messages).
I'm using a self-hosted ASP.NET Web API 2 and SignalR 2 server with OWIN to serve data to clients. You can find an example server using this scenario here. Tho advantage in this approach is to have your views & styles sepparated from your data and business logic. Making everything very easy to cache and scale.


text:
Q: The label that's applied to this item prevents it from being moved or renamed. Check the item's label for more details Hi all I have written a WF which copy a document from one library to another but now copy action is not working as destination library labeling have been done
Is there any way to replace the new version of the file without removing it from the label?

A: I could recreate your issue on my own tenant: if a retention label is set on a document, Power Automate will not let you copy to that document. However, through the UI is is indeed possible. Strange.
If you in your Power Automate flow instead of Copy File use Create file it will. Below is a screen shot of a test flow that grabs the content of the source file and creates the file at the target library. One thing to remember here is that in order to overwrite the existing target document you need to set Allow Chunking off by clicking Settings on the Create file action and set to off (also screen shotted this one).


text:
Q: Integral defined as a limit using regular partitions Definition. Given a function $f$ defined on $[a,b]$, let $$\xi_k \in [x_{k-1},x_k],\quad k=1,\ldots,n$$ where $$ x_k=a+k\frac{b-a}n, \quad k=0,\ldots,n \; .$$
One says that $f$ is integrable on $[a,b]$ if the limit $$\lim_{n\to\infty}\frac{b-a}n\sum_{k=1}^n f(\xi_k)$$
exists and is independent of the $\xi_k$.
I seek a proof of the:
Theorem. If $a<c<b$ and $f$ is integrable on $[a,c]$ and $[c,b]$, then $f$ is integrable on $[a,b].$

A: HINT:
Take Two cases:
1.When $c$ is a tag of a sub-interval $[x_{k},x_{k+1}]$ of $\dot{P}$,where $\dot{P}$ is your tagged partition ${(I_{i},t_{i})}_{i=1}^{n}$,such that $I_{i}=[x_{i},x_{i+1}]$
2.When $c$ is an end-point of a sub-interval of $\dot{P}$.

A: Your version of integrability is equivalent to the standard one but (to me at least) seems rather awkward to work with.  Thus I would begin by verifying that your definition implies that $f$ is Darboux Integrable: use Darboux's Integrability Criterion (Theorem 8.7 of these notes) and notice that by suitable choices of $\xi_k$'s you can make your sums arbitrarily close to the upper and lower sums.
Your theorem is one of the basic properties of the Darboux integral, so is proved in all the standard texts (see e.g. Theorem 8.8 of loc. cit.).


text:
Q: Node.js, Proxy HTTPS traffic without re-signing I'm building a proxy using Node.js to be run on my local machine that will log all domains accessed. Kind of the same way Fiddler works, but my program is more simple, I don't need to look at the data or decrypt anything.
I got this working fine for HTTP but for HTTPS it resigns the traffic with the self-signed certificate provided. This results in that the browser displays a warning. The same thing doesn't happen in fiddler unless you choose to decrypt HTTPS traffic.
So my question is: How do I proxy HTTPS traffic using Node.js so that it is completely transparent for the user?
This is the code I'm using right now, using the Node.js http-proxy. Based on the Github project, proxy-mirror.
var httpProxy = require('http-proxy'),
https = require('https'),
connect = require('connect'),
logger = connect.logger('dev'),
EventEmitter = require('events').EventEmitter,
util = require('util'),
Iconv = require('iconv').Iconv,
convertBuffer = require('./convertBuffer'),
fs = require('fs'),
net = require('net'),
url = require('url'),
path = require('path'),
certDir = path.join(__dirname, '/../cert'),
httpsOpts = {
    key: fs.readFileSync(path.join(certDir, 'proxy-mirror.key'), 'utf8'),
    cert: fs.readFileSync(path.join(certDir, 'proxy-mirror.crt'), 'utf8')
};

var Session = function (sessionId, req, res) {
EventEmitter.call(this);
var that = this;
this.id = req._uniqueSessionId = res._uniqueSessionId = sessionId;
this.request = req;
this.request.body = {asString: null, asBase64: null};
this.response = res;
this.response.body = {asString: null, asBase64: null};
this.state = 'start';

var hookInResponseWrite = function () {
    var response = that.response;
    var _write = response.write;
    var output = [];
    response.write = function (chunk, encoding) {
        output.push(chunk);
        _write.apply(response, arguments);
    };
    return output;
}, hookInRequestData = function () {
    var request = that.request,
        output = [];

    request.on('data', function (chunk, encoding) {
        output.push(chunk);
    });

    request.on('end', function () {
        var buffersConcatenated = Buffer.concat(output);
        request.body.asString = buffersConcatenated.toString();
        that.emit('request.end', that);
    });

    return output;
};

this.response.bodyBuffers = hookInResponseWrite();
this.request.bodyBuffers = hookInRequestData();

this.ended = function () {
    var buffersConcatenated = Buffer.concat(this.response.bodyBuffers);
    this.response.body.asString = convertBuffer.convertEncodingContentType(buffersConcatenated,this.response.getHeader('content-type') || '');
    this.response.body.asBase64 = buffersConcatenated.toString('base64');
    this.removeAllListeners();
 };
 };
 util.inherits(Session, EventEmitter);
 Session.extractSessionId = function (req) {
 return req._uniqueSessionId;
 };

var SessionStorage = function () {
var sessionHash = {},
    sessionIdCounter = 0,
    nextId = function () {
        return sessionIdCounter += 1;
    };

this.startSession = function (req, res) {
    var sessionId = nextId(), session;
    sessionHash[sessionId] = session = new Session(sessionId, req, res);
    return session;
};

this.popSession = function (req) {
    var sessionId = Session.extractSessionId(req),
        session = sessionHash[sessionId];

    delete sessionHash[sessionId];

    return session;
};

};

var ProxyServer = function ProxyServer() {
EventEmitter.call(this);

var proxyPort = 8888,
    secureServerPort = 8887,
    parseHostHeader = function (headersHost, defaultPort) {
        var hostAndPort = headersHost.split(':'),
            targetHost = hostAndPort[0],
            targetPort = parseInt(hostAndPort[1]) || defaultPort;

        return {hostname: targetHost, port: targetPort, host: headersHost};
    },
    sessionStorage = new SessionStorage(),
    adjustRequestUrl = function(req){
        if (requestToProxyMirrorWebApp(req)) {
            req.url = req.url.replace(/http:\/\/localhost:8889\//, '/');
        }
        req.url = url.parse(req.url).path;
    },
    proxyServer = httpProxy.createServer({
        changeOrigin: true,
        enable: {
            xforward: false
        }
    }, function (req, res, proxy) {
        var parsedHostHeader = parseHostHeader(req.headers['host'], 80),
            targetHost = parsedHostHeader.hostname,
            targetPort = parsedHostHeader.port;
        req.originalUrl = req.url;
        adjustRequestUrl(req);
        logger(req, res, function () {
            proxy.proxyRequest(req, res, {
                host: targetHost,
                port: targetPort
            });
        })

    }),
    proxy = proxyServer.proxy,
    secureServer = https.createServer(httpsOpts, function (req, res) {
        var parsedHostHeader = parseHostHeader(req.headers.host, 443);
 //            console.log('secure handler ', req.headers);
        req.originalUrl = req.url;
        if(!req.originalUrl.match(/https/)){
            req.originalUrl = 'https://' + parsedHostHeader.host + req.url;
        }
        adjustRequestUrl(req);
        logger(req, res, function () {
            proxy.proxyRequest(req, res, {
                host: parsedHostHeader.hostname,
                port: parsedHostHeader.port,
                changeOrigin: true,
                target: {
                    https: true
                }
            });
        });
    }),
    listening = false,
    requestToProxyMirrorWebApp = function (req) {
        var matcher = /(proxy-mirror:8889)|(proxy-mirror:35729)/;
        return req.url.match(matcher) || (req.originalUrl &&     req.originalUrl.match(matcher));
    };

[secureServer,proxyServer].forEach(function(server){
    server.on('upgrade', function (req, socket, head) {
 //            console.log('upgrade', req.url);
        proxy.proxyWebSocketRequest(req, socket, head);
    });
});

proxyServer.addListener('connect', function (request, socketRequest, bodyhead) {
    //TODO: trying fixing web socket connections to proxy - other web socket connections won't work :(
//        console.log('conenct', request.method, request.url, bodyhead);
    var targetPort = secureServerPort,
        parsedHostHeader = parseHostHeader(request.headers.host);
    if(requestToProxyMirrorWebApp(request)){
        targetPort = parsedHostHeader.port;
    }
    var srvSocket = net.connect(targetPort, 'localhost', function () {
        socketRequest.write('HTTP/1.1 200 Connection Established\r\n\r\n');
        srvSocket.write(bodyhead);
        srvSocket.pipe(socketRequest);
        socketRequest.pipe(srvSocket);
    });
});

this.emitSessionRequestEnd = function (session) {
    this.emit('session.request.end', session);
};

this.startSession = function (req, res) {
    if (requestToProxyMirrorWebApp(req)) {
        return;
    }
    var session = sessionStorage.startSession(req, res);
    this.emit('session.request.start', session);
    session.on('request.end', this.emitSessionRequestEnd.bind(this));
};
this.endSession = function (req, res) {
    if (requestToProxyMirrorWebApp(req)) {
        return;
    }
    var session = sessionStorage.popSession(req);
    if (session) {
        session.ended();
        this.emit('session.response.end', session);
    }
};

this.start = function (done) {
    done = done || function () {
    };
    proxy.on('start', this.startSession.bind(this));
    proxy.on('end', this.endSession.bind(this));
    proxyServer.listen(proxyPort, function () {
        secureServer.listen(secureServerPort, function () {
            listening = true;
            done();
        });
    });
};

this.stop = function (done) {
    done = done || function () {
    };
    proxy.removeAllListeners('start');
    proxy.removeAllListeners('end');
    if (listening) {
        secureServer.close(function () {
            proxyServer.close(function () {
                listening = false;
                done();
            });
        });
    }
};
 };
 util.inherits(ProxyServer, EventEmitter);

module.exports = ProxyServer;


text:
Q: NullPointerException triggering while creating custom Adapter I'm trying to create an activity with a fragment. The fragment holds a gridview that contain "Movie Objects". Each object has to be represented using an image in the gridview. The image is a url that I save inside the object as a string and that I load with Picasso.
For some reason, when I instantiate my adapter, it triggers a nullPointerException and I can't for my life, figure out why.
This is my Activity:
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (savedInstanceState== null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new MovieListFragment())
                    .commit();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

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

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

This is my fragment:
public class MovieListFragment extends Fragment {

    private final String LOG_TAG = MovieListFragment.class.getSimpleName();

    MovieAdapter mMovieAdapter = new MovieAdapter(
            getContext(),
            R.id.image_thumbnail,
            new ArrayList<Movie>()
    );

    public MovieListFragment() {
    }

    @Override
    public void onCreate(Bundle SavedInstanceState) {
        super.onCreate(SavedInstanceState);
        // We want to add options to the Menu bar.
        setHasOptionsMenu(true);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.movielist_fragment, menu);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // We inflate and store the rootView
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        // We sotre the gridview and set a custom adapter to it. It is defined below
        GridView gridView = (GridView) rootView.findViewById(R.id.gridview);
        gridView.setAdapter(mMovieAdapter);

        // The gridView will react to a user clicking on it.
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(getActivity(),position,Toast.LENGTH_SHORT);
            }
        });
        return rootView;
    }

    private void retrieveMovies() {
        FetchMoviesTask moviesTask = new FetchMoviesTask();
        moviesTask.execute();
    }

    @Override
    public void onStart() {
        super.onStart();
        retrieveMovies();
    }

    // Custom adapter to display Movies on a gridView
    public class MovieAdapter extends ArrayAdapter<Movie> {
        //Context member variable
        private Context mContext;
        //Constructor
        public MovieAdapter(Context context, int imgViewResourceId,
                            ArrayList<Movie> items) {
            super(context, imgViewResourceId, items);
            mContext = context;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            // If the view passed is null, we initialize it
            if (convertView == null) {
                imageView = new ImageView(mContext);
                imageView.setLayoutParams(new GridView.LayoutParams(80,80));
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setPadding(2,2,2,2);
            } else {
                imageView = (ImageView) convertView;
            }

            String url = getItem(position).getUrlPath();

            Picasso.with(mContext)
                    .load(url)
                    .resize(80,80)
                    .centerCrop()
                    .into(imageView);

            return imageView;
        }

    }

And this is the exception itself:
Process: com.example.madelenko.movierating, PID: 5326
 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.madelenko.movierating/com.example.madelenko.movierating.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
     at android.app.ActivityThread.-wrap11(ActivityThread.java)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:148)
     at android.app.ActivityThread.main(ActivityThread.java:5417)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
     at android.view.LayoutInflater.from(LayoutInflater.java:229)
     at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:178)
     at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:163)
     at com.example.madelenko.movierating.MovieListFragment$MovieAdapter.<init>(MovieListFragment.java:101)
     at com.example.madelenko.movierating.MovieListFragment.<init>(MovieListFragment.java:44)
     at com.example.madelenko.movierating.MainActivity.onCreate(MainActivity.java:21)
     at android.app.Activity.performCreate(Activity.java:6251)
     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
     at android.app.ActivityThread.-wrap11(ActivityThread.java)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:148)
     at android.app.ActivityThread.main(ActivityThread.java:5417)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

A: The problem is the MovieListFragment is not yet associated with a Context when you are initializing your MovieAdapter so getContext() is returning null.
To fix this first only declare the adapter:
MovieAdapter mMovieAdapter;

and set its value later after the context is attached to the Fragment. This is anytime after onAttach is called in the Fragment life cycle such as in the onCreateView method you have:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    mMovieAdapter = new MovieAdapter(
        getContext(),
        R.id.image_thumbnail,
        new ArrayList<Movie>()
    );
    ....
}