text:
Q: realm loop in one transaction VS one transaction for each stepin loop Which way is better?

*

*One transaction with a loop inside
public void saveProducts(List<Product> products) {

    Realm realm = Realm.getDefaultInstance();
    realm.executeTransaction(realm1 -> {

        for (Product product : products) {
            Number currentIdNum = realm1.where(Product.class).max("id");
            long nextId;
            if (currentIdNum == null) {
                nextId = 1;
            } else {
                nextId = currentIdNum.longValue() + 1;
            }

            String code = product.getCategory().getCode();
            Category code1 = realm.where(Category.class).equalTo("code", code).findFirst();
            if (code1 == null) {
                Category category = realm.copyToRealmOrUpdate(product.getCategory());
                product.setCategory(category);
            } else {
                product.setCategory(code1);
            }
            product.setId(nextId);
            realm1.insertOrUpdate(product); // using insert API
        }
    });
    realm.close();
}

*A loop with transactions for each element?
public void saveProducts(List<Product> products) {

    Realm realm = Realm.getDefaultInstance();
    for (Product product : products) {
        realm.executeTransaction(realm1 -> {
            Number currentIdNum = realm1.where(Product.class).max("id");
            long nextId;
            if (currentIdNum == null) {
                nextId = 1;
            } else {
                nextId = currentIdNum.longValue() + 1;
            }

            String code = product.getCategory().getCode();
            Category code1 = realm.where(Category.class).equalTo("code", code).findFirst();
            if (code1 == null) {
                Category category = realm.copyToRealmOrUpdate(product.getCategory());
                product.setCategory(category);
            } else {
                product.setCategory(code1);
            }
            product.setId(nextId);
            realm1.insertOrUpdate(product); // using insert API

        });
    }
    realm.close();
}

Or another way? If you know how to do it better please say.

A:
for (Product product : products) {
    realm.executeTransaction(realm1 ->

This one is much worse.
Prefer single transactions.

A: Since you're dealing with Realm Proxy objects then you can follow this approach.
 public void saveProducts(List<Product> products) {

    Realm realm = Realm.getDefaultInstance();
        realm.beginTransaction();

    for (Product product : products) {

        Number currentIdNum = realm1.where(Product.class).max("id");
        long nextId;
        if (currentIdNum == null) {
            nextId = 1;
        } else {
            nextId = currentIdNum.longValue() + 1;
        }

        String code = product.getCategory().getCode();
        Category code1 = realm.where(Category.class).equalTo("code", code).findFirst();
        if (code1 == null) {
            Category category = realm.copyToRealmOrUpdate(product.getCategory());
            product.setCategory(category);
        } else {
            product.setCategory(code1);
        }
        product.setId(nextId);
        realm.insertOrUpdate(product); // using insert API

    }
    realm.commitTransaction();

    realm.close();
}


text:
Q: Why is My Program not Working I am a noob programmer,who just started in C++. I wrote a program, to answer a question. When I try to run it from my cmd.exe, windows tells me "a problem has caused this program to stop working, we'll close the program and notify you when a solution is available".
I have included a link to the well documented source code. Please take a look at the code, and help me out.
link: http://mibpaste.com/ZRevGf
i believe, that figuring out the error, with my code may help several other noob programmers out there, who may use similar methods to mine.
Code from link:
 //This is the source code for a puzzle,well kind of that I saw on the internet. I will include the puzzle's question below.
//Well, I commented it so I hope you understand.

//ALAFIN OLUWATOBI 100L DEPARTMENT OF COMPUTER SCIENCE BABCOCK UNIVERSITY.
//Future CEO of VERI Technologies inc.

/*
* In a corridor, there are 100 doors. All the doors are initially closed.
* You walk along the corridor back and forth. As you walk along the corridor, you reverse the state of each door.
* I.e if the door is open, you close it, and if it is closed, you open it.
* You walk along the corrdor, a total of 200 times.
* On your nth trip, You stop at every nth door, that you come across.
* I.e on your first trip, you stop at every door. On your second trip, every second door, on your third trip every third door and so on and so forth
* Write a program to display, the final states of the doors.
*/

#include <iostream>
#include <cstdlib>
#include <cmath>

using namespace std;

inline void inverse(bool args[]); //The prototype of the function. I made the function inline in the declaration, to increase efficiency, ad speed of execution.

bool doors [200]; //Declaring a global array, for the doors.

int main ()
{
    inverse(doors); //A call to the inverse function

    cout << "This is the state of the 100 doors...\n";

    for (int i = 0 ; i<200 ; i++) //Loop, to dis play the final states of the doors.
    {
        cout << "DOOR " << (i+1) << "\t|" << doors[i] << endl;
    }

    cout << "Thank you, for using this program designed by VERI Technologies. :)"; //VERI Technologies, is the name of the I.T company that I hope to establish.

    return 0;
}

void inverse(bool args [])
{
    for (int n = 1 ; n<= 200 ; n++) //This loop, is for the control of every nth trip. It executes 100 times
    {
        if (n%2 != 0) //This is to control the reversal of the doors going forward, I.e on odd numbers
        {
            for (int b = n, a = 1 ; b<=200 ;b = n*++a) //This is the control loop, for every odd trip, going forwards. It executes 100 times
                args [b] = !args[b] ; //The reversal operation. It reverses the boolean value of the door.
        }
/*
* The two variables, are declared. They will be used in controlling the program. b represents the number of the door to be operated on.
* a is a variable, which we shall use to control the value of b.
* n remains constant for the duration, of the loop, as does (200-n)
* the pre increment of a {++a} multiplied by n or (200-n) is used to calculate the value of b in the update.
* Thus, we have the scenario, of b increasing in multiples of n. Achieving what is desired for the program. Through this construct, only every nth door is considered.
*/

        else if((n%2) == 0) //This is to control the reversal of the doors going backwards, I.e on even numbers
        {
            for (int b = (200-n), a = 1 ; b>=1 ; b = (200-n)*++a) //This is the control loop for every even trip, going backwards. It executes 100 times.
                args [b] = !args[b] ; //The reversal operation. It reverses the boolean value of the door.
        }
    }
}

A: I believe the exception is due to the line:
for (int b = (200 - n), a = 1; b >= 1; b = (200 - n)*++a)

When the exception occurs the following values are assigned to the variables:
b = 3366
n = 2
a = 17

From what I can see, b is calculated by (200 - n) * a.
If we substitute the values given we have: 198 * 17
This gives us the value of 3366 which is beyond the index of doors and throws the exception when the line
args[b] = !args[b];

is executed.
I have created the following solution that should provide the desired results if you wish to use it.
void inverse(bool args[])
{

    //n represents what trip you are taking down the hallway
    //i.e. n = 1 is the first trip, n = 2 the second, and so on
    for (int n = 1; n <= 200; n++){

        //We are on trip n, so now we must change the state of all the doors for the trip
        //The current door is represented by i
        //i.e. i = 1 is the first door, i = 2 the second, and so on
        for (int i = 1; i <= 200; i++){

            //If the current door mod the trip is 0 then we must change the state of the door
            //Only the nth door will be changed which occurs when i mod n equals 0
            //We modify the state of doors[i - 1] as the array of doors is 0 - 199 but we are counting doors from 1 to 200
            //So door 1 mod trip 1 will equal 0 so we must change the state of door 1, which is really doors[0]
            if (i % n == 0){
                args[i - 1] = !args[i - 1];
            }

    }

}

A: EUREKA!!!!!!
I finally came up with a working solution. No more errors. I'm calling it version 2.0.0
I've uploaded it online, and here's the link
[version 2.0.0] http://mibpaste.com/3NADgl
All that's left is to go to excel, and derive the final states of the door and be sure, that it's working perfectly. Please take a look at my solution, and comment on any error that I may have made, or any way you think that I may optimize the code.I thank you for your help, it allowed me to redesign a working solution to the program. I'm sstarting to think that an Out-of-bounds error, might have caused my version 1 to crash, but the logic was flawed, anyway, so I'm scrapping it.
This is ths code:
/**********************************************************************************************
200 DOOR PROGRAM
Version 2.0.0
Author: Alafin OluwaTobi Department of Computer Science, Babcock University
New Additions: I redrew, the algorithm, to geneate a more logically viable solution,
I additionally, expanded the size of the array, to prevent a potential out of bounds error.
**********************************************************************************************/

//Hello. This a program,I've written to solve a fun mental problem.
//I'll include a full explanation of the problem, below.

/**********************************************************************************************
    *You are in a Hallway, filled with 200 doors .
    *ALL the doors are initially closed .
    *You walk along the corridor, *BACK* and *FORTH* reversing the state of every door which you stop at .
    *I.e if it is open, you close it .
    *If it is closed,  you open it .
    *On every nth trip, you stop at every nth door .
    *I.e on your first trip, you stop at every door. On your second trip every second door, On your third trip every third door, etc .

*Write a program to display the final state of the doors .
**********************************************************************************************/

/**********************************************************************************************
                                        SOLUTION
    *NOTE: on even trips, your coming back, while on odd trips your going forwards .
    *2 Imaginary doors, door 0 and 201, delimit the corridor .
    *On odd trips, the doors stopped at will be (0+n) doors .
    *I.e you will be counting forward, in (0+n) e.g say, n = 5: 5, 10, 15, 20, 25
    *On even trips, the doors stopped at will be (201-n) doors.
    *I.e you will be counting backwards in (201-n) say n = 4: 197, 193, 189, 185, 181
**********************************************************************************************/

#include <iostream>
#include <cstdlib>  //Including the basic libraries

bool HALLWAY [202] ;
/*
    *Declaring the array, for the Hallway, as global in order to initialise all the elements at zero.
    *In addition,the size is set at 202 to make provision for the delimiting imaginary doors,
    *This also serves to prevent potential out of bound errors, that may occur, in the use of thefor looplater on.
*/

inline void inverse (bool args []) ;
/*
    *Prototyping the function, which will be used to reverse the states of the door.
    *The function, has been declared as inline in order to allow faster compilation, and generate a faster executable program.
*/

using namespace std ;   //Using the standard namespace

int main ()
{
    inverse (HALLWAY) ; //Calling the inverse function, to act on the Hallway, reversing the doors.

    cout << "\t\t\t\t\t\t\t\t\t\t200 DOOR TABLE\n" ;

    for(int i = 1 ; i <= 200 ; i++ )
    //A loop to display the states of the doors.
    {
        if (HALLWAY [i] == 0)
        //The if construct allows us to print out the state of the door as closed, when the corresponding element of the Array has a value of zero.
        {
            cout << "DOOR " << i << " is\tCLOSED" << endl ;
            for (int z = 0 ; z <= 300 ; z++)
                cout << "_" ;
            cout << "\n" ;
        }

        else if (HALLWAY [i] == 1)
        //The else if construct allows us to print out the state of the door as open, when the corresponding element of the Array has a value of one.
        {
            cout << "DOOR " << i << " is\tOPEN" << endl ;
            for (int z = 0 ; z <= 300 ; z++)
                cout << "_" ;
            cout << "\n" ;
        }
    }

return 0 ; //Returns the value of zero, to show that the program executed properly
}

void inverse (bool args[])`

{

    for ( int n = 1; n <= 200 ; n++)

    //This loop, is to control the individual trips, i.e trip 1, 2, 3, etc..

    {

        if (n%2 == 0)
        //This if construct, is to ensure that on even numbers(i,e n%2 = 0), that you are coming down the hallway and counting backwards
    {
            for (int b = (201-n) ; b <= 200 && b >= 1 ; b -= n)
            /*
                *This loop, is for the doors that you stop at on your nth trip.
                *The door is represented by the variable b.
                *Because you are coming back, b will be reducing proportionally, in n.
                *The Starting value for b on your nth trip, will be (201-n)
                * {b -= n} takes care of this. On the second turn for example. First value of b will be 199, 197, 195, 193, ..., 1
            */
                args [b] = !(args [b]) ;
                //This is the actual reversal operation, which reverses the state of the door.
       }

        else if (n%2 != 0)
        //This else if construct, is to ensure that on odd numbers(i.e n%2 != 0), that you are going up the hallway and counting forwards
        {
            for (int b = n ; b <= 200 && b >= 1 ; b += n)
            /*
                *This loop, is for the doors that you stop at on your nth trip.
                *The door is represented by the variable b.
                *Because you are going forwards, b will be increasing proportionally, in n.
                *The starting value of b will be (0+n) whch is equal to n
                * {b += n} takes care of this. On the third turn for example. First value of b will be 3, 6, 9, 12, ...., 198
            */
                args [b] = !(args [b]) ;
                //This is the actual reversal operation, which reverses the state of the door
        }
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: using GridFS with Tornado templates i've a problem when making a loop using a GridFS pictures:
class VentesHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        user = self.get_secure_cookie("mechtari")
        info = tornado.escape.json_decode(user)
        email = info["personnel"]["email"]
        produits = self.db.users.find({"personnel.email":email},{"produit_up":1, "_id":0}).distinct("produit_up")
        produit_pic_id = self.db.users.find({"personnel.email":email}).distinct("produit_up.avatar.photo")
        orientation = self.db.users.find({"personnel.email":email}).distinct("produit_up.avatar.orientation")
        renderer = self.fs
        self.render("ventes.html", produits=produits, produit_pic_id=produit_pic_id, orientation=orientation, renderer=renderer)

and the template:
{% for produit in produits %}
{% for id in produit_pic_id %}

{% import pymongo %}
{% if orientation=="portrait" %}

 {% else %}

 {% end %}

{% end %}
{% end %}
{% end %}

i got the pictures repeated the time of uploaded products! so if i
uploaded 2 products (product_up), then i'll get 4 products with all
possibles switching of the product pictures!
by the way, note the hack to avoid (self not defined...)
and what about the import? do i make another variable
x = pymongo.son_manipulator

to avoid the template to load the whole module
and uses a lot of memory?

A: solved, there was a loop in a loop.
Answer on Google groups
here is the code:
class VentesHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        user = self.get_secure_cookie("mechtari")
        info = tornado.escape.json_decode(user)
        email = info["personnel"]["email"]
        try:
            produits = self.db.users.find({"personnel.email":email}, {"produit_up":1, "_id":0}).distinct("produit_up")
            renderer = self.fs
        except (errors.AutoReconnect, errors.ConnectionFailure):
            self.redirect("/error")
    self.render("ventes.html", produits=produits, renderer=renderer)

the template:
{% for produit in produits %}

{% from bson import ObjectId %}
{% if produit["avatar"]["orientation"]=="portrait" %}

{% else %}

{% end %}

{% end %}


text:
Q: python setup.py - how to show message after install I am developing a PyQt5 app and making it available via pip install now that pip in python3 can install pyqt5 as dependence. I made an entry point to launch my package, and told setup.py that it's a gui_scripts.
What I would like to do now, is after the person typing pip install package, and the installation is finished, display a message to the person telling that you can now type package in the terminal to load the application. What's the correct way of doing that? Or should I not do this?

A: If you can ensure that

*

*the package is always installed from a source distribution, not a binary wheel, and

*the user uses the -v option for pip install,

you can output text in your setup.py script.
The setup.py is almost a regular Python script.
Just use the print() function at the end of your setup.py file.
In this example the file structure is somedir/setup.py, somedir/test/ and test/__init__.py.
Simple solution
from setuptools import setup

print("Started!")

setup(name='testing',
      version='0.1',
      description='The simplest setup in the world',
      classifiers=[
        'Development Status :: 3 - Alpha',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3.0',
      ],
      keywords='setup',
      author='someone',
      author_email='someone@example.com',
      license='MIT',
      packages=['test'],
      entry_points={
      },
      zip_safe=False)

print("Finished!")

Started! running install running bdist_egg running egg_info writing testing.egg-info/PKG-INFO
  ... ... ...
  Processing dependencies for testing==0.1 Finished processing
  dependencies for testing==0.1 Finished!

Using setuptools.command.install solution
Also, you can subclass the setuptools.command.install command. Check the difference when you change the order of install.run(self) and os.system("cat testing.egg-info/PKG-INFO") in a clean setup.
from setuptools import setup
from setuptools.command.install import install
import os

class PostInstallCommand(install):
    """Post-installation for installation mode."""
    def run(self):
        install.run(self)
        os.system("cat testing.egg-info/PKG-INFO")

setup(name='testing',
      version='0.1',
      description='The simplest setup in the world',
      classifiers=[
        'Development Status :: 3 - Alpha',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3.0',
      ],
      keywords='setup',
      author='someone',
      author_email='someone@example.com',
      license='MIT',
      packages=['test'],
      entry_points={
      },
      cmdclass={
        'install': PostInstallCommand,
      },
      zip_safe=False)

A: Another option would be the logging module.
rasterio for example uses an approach like this which you could adapt for your needs:
import logging
import sys

logging.basicConfig(stream=sys.stderr, level=logging.INFO)
log = logging.getLogger()

...

log.info("Your message")

sys.stderr will be printed by pip.


text:
Q: I have a shopping cart using session, how do do I store multiply rows in an array column? My shopping cart works fine using sessions, for each product_id it stores, quantity, name, price, side_name and price. For example:
Product_ID
[Product_name, Product_price, Quantity, Side_name, Side_price]
which works perfectly so far but the problem I'm facing is, I would like to have multiple sides for each Product_ID but what it seems to be doing now is updating the sides each time I choose a new side. What I would it to do is add on the side rather than updating it. So I can have multiply sides for each Product_ID
Here is the code:
if($_POST["action"] == "add_side")
{

    foreach($_SESSION["shopping_cart"] as $keys => $values)
    {
        if($_SESSION["shopping_cart"][$keys]['product_id'] == $_POST["product_id"])
        {
            foreach($_SESSION["shopping_cart"] as $key => $values)
            {
                $_SESSION["shopping_cart"][$key]['side_name'] = $_POST["side_name"];

            }
        }
    }
}

Adding Products
if(isset($_SESSION["shopping_cart"]))
{
    $is_available = 0;
    foreach($_SESSION["shopping_cart"] as $keys => $values)
    {
        if($_SESSION["shopping_cart"][$keys]['product_id'] == $_POST["product_id"])
        {
            $is_available++;
            $_SESSION["shopping_cart"][$keys]['product_quantity'] =
            $_SESSION["shopping_cart"][$keys]['product_quantity'] +
            $_POST["product_quantity"];
        }
    }
    if($is_available < 1)
    {
        $item_array = array(
            'product_id'   =>     $_POST["product_id"],
            'product_name'  =>     $_POST["product_name"],
            'product_price'  =>   $_POST["product_price"],
            'product_quantity'   =>     $_POST["product_quantity"],
            'side_name'          =>           $_POST["side_name"],
            'side_price'          =>            $_POST["side_price"]
        );
        $_SESSION["shopping_cart"][] = $item_array;
    }
}

A: So there are two changes that you need to make.  One when creating/inserting the product, and then another one when adding sides to an existing product.
When creating the product, if there is data for a side, you will want to create a sides sub-array on the $item_array array.
    $item_array = array(
        'product_id'   =>     $_POST["product_id"],
        'product_name'  =>     $_POST["product_name"],
        'product_price'  =>   $_POST["product_price"],
        'product_quantity'   =>     $_POST["product_quantity"]
    );

    if(!empty($_POST['side_name']))
    {
        $item_array['sides'] = array(array("side_name" => $_POST["side_name"], "side_price" => $_POST["side_price"]));
    }

    $_SESSION["shopping_cart"][] = $item_array;

Then, in the update, you'll add a new sub-array each time, instead of assigning to a fixed index.
if($_POST["action"] == "add_side")
{

    foreach($_SESSION["shopping_cart"] as $keys => $values)
    {
        if($_SESSION["shopping_cart"][$keys]['product_id'] == $_POST["product_id"])
        {
            $_SESSION['shopping_cart'][$keys]['sides'][] = array('side_name' => $_POST['side_name'], 'side_price' => $_POST['side_price']);
        }
    }
}

Example of outputting all sides of all products:
// iterate over all the products in the cart
foreach($$_SESSION["shopping_cart"] as $product)
{
    echo "Sides for productId " . $product["product_id"] . ":
";

    // iterate over each side of the current product
    foreach($product["sides"] as $side)
    {
        echo "Side Name: " . $side["side_name"] . ", Side Price: " . $side["side_price"] . "
";
    }

    echo "
";
}


text:
Q: How to modify the 'totals' area in cart checkout area
In the cart section of my Magento store i'm looking to modify these totals by adding a column (:) infront of each one.
So its laid out like this:

Subtotal:
Grand Total:

I cant figure out what file requires modification to change these.

A: Look into two sections:
app\design\frontend\yourtheme\default\template\tax\checkout\
app\design\frontend\yourtheme\default\template\checkout\total\
Depending on your setup in tax configuration you have to manually add ':' after something like: <?php echo $this->getTotal()->getTitle() ? in:  app\design\frontend\yourtheme\default\template\checkout\total\tax.phtml
or something like:
<?php echo $this->escapeHtml($this->getTotal()->getTitle()); ?> in:  app\design\frontend\youtheme\default\template\checkout\total\default.phtml
So you can edit it into something like this:
<?php echo $this->escapeHtml($this->getTotal()->getTitle()) . ': '; ?>

or:
<?php echo $this->escapeHtml($this->getTotal()->getTitle()); ?>:

More specificaly, edit app\design\frontend\yourtheme\default\template\tax\checkout\subtotal.phtml (if you dont have one copy from base/default/ theme package)
<td style="<?php echo $this->getStyle() ?>" class="a-right" colspan="<?php echo $this->getColspan(); ?>">
        <?php echo $this->getTotal()->getTitle() ?>:
    </td>


text:
Q: jquery update div background I'm trying to update a background-image on the body element of a page, when I hover links with data-* attributes. It works like a charm but I can't find a way to create a smooth fade between the images when a link is hovered. Here is my code :

$(document).ready(function(){
 $('.link').hover(
  function() {
   var bg = $(this).data('fond');

   // alert(bg);

   $('body').css("backgroundImage", 'url(' + bg + ')');
  },
  function () {
             $('body').css("backgroundImage", 'url(http://sport-nc.com/wp-content/uploads/2015/06/India_Surf_Tours_-_17__1_.jpg)');
        }
 );
});
body {
 margin:0;
 background-image: url("http://sport-nc.com/wp-content/uploads/2015/06/India_Surf_Tours_-_17__1_.jpg");
 background-repeat: no-repeat;
 background-size: cover;
 transition: all 1s;
}

header {
 width: 50%;
 margin: 50px auto;
}

h1 {
 text-align: center;
}

nav {
 position: absolute;
 width: 50%;
 top: 50%;
 left: 50%;
 transform: translate(-50%,-50%);
 text-align: center;
}

nav ul {
 padding: 50px;
 background-color: rgba(0, 0, 0, 0.95);
}

nav ul li {
 display: inline-block;
 padding: 0 20px;
}

nav ul li a {
 color: white;
 text-decoration: none;
}

Hover a link, bro

Belharra

Jaws

Mavericks

Nazare

Teahuppo

Bonus: Someone can explain to me why I had to use a second function when the mouse leave a link to give the body the original background image? I thought the .hover() method automatically put a toggle on the targeted element...

The .hover() method binds handlers for both mouseenter and mouseleave events. You can use it to simply apply behavior to an element during the time the mouse is within the element.

Thanks a lot for the help !

A: body {
    margin:0;
    background-image: url("http://sport-nc.com/wp-content/uploads/2015/06/India_Surf_Tours_-_17__1_.jpg");
    background-repeat: no-repeat;
    background-size: cover;
    transition: all 1s;
}

please change your url link url("http://sport-nc.com/wp-content/uploads/2015/06/India_Surf_Tours_-_17__1_.jpg");
it is not correct

A: you can try your jquery like this.
$('body').fadeOut(1000).css("your code").fadeIn(1000);

following html,I have created to get an idea.think this may help to you.just copy and try it.

<title>Welcome !</title>

A: I don't think this can be done with a smooth fade effect.
A better way to achieve this is to put all your images in a div container in your html. All your images need to have a css opacity property to 0. In this way, you can easily change the opacity property beetween your images and have your smooth fade effect.


text:
Q: Problem with changing color of label in checkbox I'm doing a quiz using HTML and JavaScript. Right now, I am trying to do  questions that have more than one answer using checkboxes. When you answer incorrectly, the answer that you have chosen should appear in red and the correct one in green. I tried doing that using this code:
JavaScript
if ( document.getElementById('doc').checked &&
   document.getElementById('prompt').checked &&
   document.getElementById('get').checked &&
   document.getElementById('alert').checked
) {
   document.getElementById("label33").style.color = 'green';
   document.getElementById("label34").style.color = 'green';
   document.getElementById("label35").style.color = 'green';
   document.getElementById("label36").style.color = 'green';
   pkt+=2;
}

HTML
<fieldset>
    <legend>Pytanie14</legend>

Jakimi sposobami można wyświetlić tekst? (Uwaga.Może być więcej niż jedna odpowiedź).

    <input type="checkbox" id="doc"/>document.write("tekst");

    <input type="checkbox" id="prompt"/>prompt("tekst");

    <input type="checkbox" id="get"/>document.getElementById("id").innerHTML="tekst";

    <input type="checkbox" id="alert"/>alert("tekst");
    </select>
</fieldset>

With this code when I check all the checkboxes only one (the last answer) appears in green and the others are in red. I would appreciate any help.


text:
Q: How to set the athentication destails for Symfony DomCrawler? I am trying to crawl some web pages that need authentication, i.e. first you should login and then you can access the pages.
For that I am trying to use Symfony\Component\DomCrawler\Crawler in my application (I am not using the Symfony Framework, I have used symfony/dom-crawler using Composer).
<?php
require_once('/vendor/autoload.php');
use Symfony\Component\DomCrawler\Crawler;

class myTest extends WebTestCase {
    function __construct () {
        $crawler = new Crawler(file_get_contents('http://test.com/index.php'));

        var_dump($crawler->filter('.menu_nav')->eq(0)->text());
    }
}

new myTest;

This is working perfectly fine for the simple pages, but not for authenticated ones, i.e. those that need username and password. So for that I am trying to use  this page  from Symfony website and insert this code:
<?php
require_once('/vendor/autoload.php');
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class myTest extends WebTestCase {
    function __construct () {

        $client = static::createClient(array(), array(
            'PHP_AUTH_USER' => 'username',
            'PHP_AUTH_PW'   => 'pa$$word',
        ));

        // $crawler = new Crawler(file_get_contents('http://test.com/index.php'));
        // var_dump($crawler->filter('.menu_nav')->eq(0)->text());
    }
}

new myTest;

But I am getting this:
Fatal error: Uncaught exception 'RuntimeException' with message 'You must override the KernelTestCase::createKernel() method.' in E:\xampp\htdocs\testCrawler\vendor\symfony\framework-bundle\Symfony\Bundle\FrameworkBundle\Test\KernelTestCase.php on line 44

To solve this I have added phpunit.xml at path/to/my/project/phpunit.xml with this content:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true" bootstrap="vendor/autoload.php">
    <php>
        <server name="KERNEL_DIR" value="path/to/my/project" />
    </php>
    <testsuites>
        <testsuite name="Application Test Suite">
            <directory>./stats/Test/</directory>
        </testsuite>
    </testsuites>
</phpunit>

From command prompt if I type phpunit, I get:
path/to.my/project>phpunit
PHPUnit 4.5.0 by Sebastian Bergmann and contributors.

Configuration read from path/to.my/project\phpunit.xml

Time: 300 ms, Memory: 1.50Mb

No tests executed!

path/to.my/project>phpunit

That shows phpunit knows about the phpunit.xml file, but the error still exists.
Update: The purpose is not to use this program as a part of unit test or any other tests, this purpose is to crawl the pages, by any possible solutions.


text:
Q: What is MyAssembly.XmlSerializers.dll generated for? I am working on a project which generates an assembly. I just noticed that an additional assembly *.XmlSerializers.dll is being generated. Why this file is auto generated and what it is used for?

A: FYI. The exact steps to stop the XmlSerializers.dll from being auto-generated are:

*

*In VS, right-click your project file and select "Properties"

*Click the "Build" tab

*Change the "Generate serialization assembly" dropdown from "Auto" to "Off"

*Rebuild and it will be gone

A: I think this is the JIT (Just in time) compilation of XML serialisers for performance reasons.
You get the same thing with RegEx instances using the RegexOptions.Compiled option turned on.
I'm no .NET CLR expert, sorry for lack of precise technical detail.

A: *.XmlSerializers.dll are generated using the Sgen.exe [XML Serializer Generator Tool]
See Sgen.exe on MSDN
Typically the Sgen.exe is used in Post Build events of Projects. See if your project has a post build event which generates the *.XmlSerializers.dll

A: The project only generates the project.XMLSerialisers.dll for web applications. For other applications you have to run sgen separately.

A: In .NET implementation, the XmlSerializer generates a temporary assembly for serializing/deserializing your classes (for performance reasons). It can either be generated on the fly (but it takes time on every execution), or it can be pregenerated during compilation and saved in this assembly you are asking about.
You can change this behaviour in project options (tab Compile -> Advanced Compile Options -> Generate serialization assemblies, Auto or On, respectively). The corresponding element in the project file is GenerateSerializationAssemblies, for example, <GenerateSerializationAssemblies>Auto</GenerateSerializationAssemblies>.


text:
Q: Select Strings from Windows events via XML I am trying to select property from events I am able to create with script
$events = Get-WinEvent -FilterHashtable @{logname='Security'; ID=4728; } -MaxEvents 1
$event = $events
[xml]$eventXML = [xml]$Event.ToXml()
$eventXML.Event.EventData.Data

if I run this it outputs, I need to select targetname,targetusername,subjectusername, I am not able to get the output, anyhelp will be very much appreciated.

A: As Swonkie already pointed out, Data is an array, and the values you're looking for are actually XML nodes in that array, hence you can't easily select them like you would with the properties of an object.
I would probably create a hashtable for each Data array, filter the array for the nodes you want selected, then build a custom object from each hashtable.
$names = 'TargetName', 'TargetUserName', 'SubjectUserName'

$events | ForEach-Object {
    ([xml]$_.ToXml()).Event.EventData | ForEach-Object {
        $props = @{}

        $_.Data |
            Where-Object { $names -contains $_.Name } |
            ForEach-Object { $props[$_.Name] = $_.'#text' }

        New-Object -Type PSObject -Property $props
    }
}

A: $eventXML.Event.EventData.Data is an array.
$eventXML.Event.EventData.Data | where { $_.Name -eq 'SubjectUserName' } | select -ExpandProperty '#text'

Or for PowerShell 3 and up:
$eventXML.Event.EventData.Data | where Name -eq 'SubjectUserName' | select -ExpandProperty '#text'


text:
Q: Recorder.js single data point I'm using jwegener's recorder.js for audio recording. I am curious if it is possible to poll the flash from the javascript while the recorder is running to get a "frame" of the audio to build a waveform.
In my imagined pseudocode:
function record() {
    Recorder.Record();

    setInterval(function(){
      Recorder.fetchCurrentAudioSnapshot();
    }, 50);
}

Ideally that would give me a numerical value that I could use to plot the waveform.
Thanks for any ideas you can give.

A: I figured it out.
The first thing I did was put the example javascript into an object. Here is the record function I am using:
record: function() {
        this.data = [];
        this.poll = '';

        Recorder.record({
            start: function () {
                alert("recording starts now. press stop when youre done. and then play or upload if you want.");
            },
            progress: function (milliseconds) {
                document.getElementById("time").innerHTML = Voiceover.timecode(milliseconds);
            }
        });

        this.waveform = new Waveform({
            container: document.getElementById("voiceover_waveform"),
            interpolate: false
        });
        var ctx = this.waveform.context;

        var gradient = ctx.createLinearGradient(0, 0, 0, this.waveform.height);
        gradient.addColorStop(0.0, "#f60");
        gradient.addColorStop(1.0, "#ff1b00");
        this.waveform.innerColor = gradient;

        var i=0;

        this.poll = setInterval(function() {
            Voiceover.data.push(Recorder.PollAudioBuffer());
            Voiceover.waveform.update({
                data: Voiceover.data
            });
        }, 70);
    },

This initializes the waveform and sets an interval of 70ms to poll the recorder to get a new datapoint and plot it on the waveform.
In recorder.js, I added the following function:
PollAudioBuffer: function() {
    try {
        var poll = this.flashInterface().pollAudioBuffer();

        console.log(poll);

        if(poll < 0.15) {
                            // Messing around with the math a bit to improve the effect.
                            // The final result just has to be between 0 and 1.
            poll = Math.floor((Math.random()*1.5)+1)/10;
        }

        return poll;
    }
    catch(error) {
        console.log(error);
    }
},

Now to the Action Script. In Recorder.as, I added my pollAudioBuffer() function, which is actually a bit misnamed now.
protected function pollAudioBuffer():Number
    {
        return (microphone.activityLevel*2)/100;
    }

To get the function to work, you need to add a callback reference to addExternalInterfaceCallbacks() in Recorder.as:
ExternalInterface.addCallback("pollAudioBuffer",this.pollAudioBuffer);

These changes allowed me to create a waveform on the fly. Hope this will help somebody else.


text:
Q: Strange output when using union type members My code:
#include<stdio.h>

union U{
    int x;
    char y;
};

int main()
{
    union U u1;
    u1.x = 258;
    u1.y = '0';
    printf("%d%d",u1.x,u1.y);
    return 0;
}

Strangely, the output is 30448.
Can someone please explain how this happens?

A: You maybe missunderstanding the purpose of a union. It is meant to store only one variable at a time, but this variable can have multiple types. The last variable stored will overwrite the previous.
In your case u1.y (which is '0', it's relevant to remind that the 1 byte ASCII decimal representation for '0' is 48), is the last value stored, this corresponds to last 2 digits of your output as you print '0' by its ASCII decimal representation.
As for the first part of the output, note that you overwrite  the int variable 258, which is presumably 4 bytes (but for the sake of explanation I will assume it's 2 bytes) with the 1 byte wide char variable 48.
The binary value for 258 (assuming 2 bytes wide int) is:
|0|0|0|0|0|0|0|1|0|0|0|0|0|0|1|0|

|   2nd byte    |   1st byte    |

The binary value for 48 (1 byte wide char variable) is:
| | | | | | | | |0|0|1|1|0|0|0|0|

                |   1st byte    |

When you overwrite the two byte union variable with a one byte variable only the 8 least significant bits(least significant byte) will be overwritten, so you'll end up with:
|0|0|0|0|0|0|0|1|x|x|x|x|x|x|x|x|
| | | | | | | | |0|0|1|1|0|0|0|0|

|0|0|0|0|0|0|0|1|0|0|1|1|0|0|0|0|

And this is the binary representation of 304.
So yor code first prints the 2 bytes wide (for the sake of the examle) int 304 and next the 1 byte wide int 48 (the ASCII int representation of '0'), hence the output 30448.
Note that this behavior is not undefined.
ISO/IEC 9899:2017 N2176

§ 6.5.2.3
97) If the member used to read the contents of a union object is not the same as the member last used to store a value in the object, the appropriate part of the object representation of the value is reinterpreted as an object representation in the new type as described in 6.2.6 (a process sometimes called "type punning"). This might be a trap representation.
§ 6.2.6.2
6 - When a value is stored in an object of structure or union type, including in a member object, the bytes of the object representation that correspond to any padding bytes take unspecified values.51) The value of a structure or union object is never a trap representation, even though the value of a member of the structure or union object may be a trap representation.
7 - When a value is stored in a member of an object of union type, the bytes of the object representation that do not correspond to that member but do correspond to other members take unspecified values.

For confirmation you can use:
printf("%p %p\n", (void*)&u1.x, (void*)&u1.y);

This will print the memory address of both u1.x and u1.y and you will not be shocked to find that they are the same.

A: You cannot read a member of a union other than the one last written into
#include<stdio.h>
union U{
int x;
char y;
};

int main()
{
    union U u1;
    u1.x = 258; // write into member x: OK
    u1.y = '0'; // write into member y: OK
    printf("%d%d",u1.x,u1.y); // read both member x and y: WRONG
                              // can only read member y
    return 0;
}


text:
Q: AllJoyn Thin Client - Building the services samples on Linux I have tried to build the service samples AllJoyn Thin Client on Linux but I'm getting an error. Does anyone know how to resolve this problem?
The problem is probably in one file called Debug.h, which is missing.
The prompt returns this message: Service.h:20:23: fatal error: qcc/Debug.h: No such file or directory.
More information can be observed on the image: Debug.h error

A: You are building the wrong services with AJTCL. Try to build under the services/base_tcldirectory, which is the thin services base directory.


text:
Q: how to get only the name of the image and not the whole path in Express js I want to add only the name in the mysql table
if I try to utilser req.files.name his works but the problem that the name of the image is encoded in the file
app.use(express.bodyParser({KeepExtensions: true,
                            uploadDir: path.join(__dirname, '/picture')}));

exports.insertPhoto = function(req, res){
   db.addPhoto({name: req.body.name, photo: req.files.picture.path});
   res.redirect('/album');
};

A: Try spliting by the path.sep and getting only the last part:
var filename = req.files.picture.path.split(path.sep).pop();

or even shorter:
var filename = path.basename(req.files.picture.path);

A: Use path.basename(p, [ext]):
path.basename(req.files.picture.path);


text:
Q: Inserting/updating huge amount of rows into SQL Server with C# I have to parse a big XML file and import (insert/update) its data into various tables with foreign key constraints.
So my first thought was: I create a list of SQL insert/update statements and execute them all at once by using SqlCommand.ExecuteNonQuery().
Another method I found was shown by AMissico: Method
where I would execute the sql commands one by one. No one complained, so I think its also a viable practice.
Then I found out about SqlBulkCopy, but it seems that I would have to create a DataTable with the data I want to upload. So, SqlBulkCopy for every table. For this I could create a DataSet.
I think every option supports SqlTransaction. It's approximately 100 - 20000 records per table.
Which option would you prefer and why?

A: Don't do it from C# unless you have to, it's a huge overhead and SQL can do it so much faster and better by itself

Insert to table from XML file using INSERT INTO SELECT

A: You say that the XML is already in the database. First, decide whether you want to process it in C# or in T-SQL.

*

*C#: You'll have to send all data back and forth once, but C# is a far better language for complex logic. Depending on what you do it can be orders of magnitude faster.

*T-SQL: No need to copy data to the client but you have to live with the capabilities and perf profile of T-SQL.

Depending on your case one might be far faster than the other (not clear which one).
If you want to compute in C#, use a single streaming SELECT to read the data and a single SqlBulkCopy to write it. If your writes are not insert-only, write to a temp table and execute as few DML statements as possible to update the target table(s) (maybe a single MERGE).
If you want to stay in T-SQL minimize the number of statements executed. Use set-based logic.
All of this is simplified/shortened. I left out many considerations because they would be too long for a Stack Overflow answer. Be aware that the best strategy depends on many factors. You can ask follow-up questions in the comments.


text:
Q: Cocos2D Library Leak? My Xcode analyze tool is showing a leak coming from the Cocos2D library (CCAtlasNode.m).
Anyway how would I fix this leak?
self.textureAtlas = [[CCTextureAtlas alloc] initWithFile:tile capacity:c];
[textureAtlas_ release];

Thanks!

A: *

*Make sure the same leak happens in a freshly created project, to avoid side effects like this one: How to determine where this memory leak is coming from?

*Once you're 100% sure the leak is coming from cocos2d-iphone, report it to the developers with all the information you have.


text:
Q: Under what circumstances can a git commit not have exactly one parent commit? In git, each commit has one or more parent commits, except for the first one created by the first use of git commit command.  As far as I know, other commits have exactly one parent commit unless they were created with the git merge command.
Are the above the only circumstances in which a git commit does not have exactly one parent commit?  What other reasons might there be for a git commit to not have exactly one parent?

A: A commit in Git is always a commit. A merge commit can only be distinguished from other commits by looking at the number of parents.

*

*0 parents: root commit

*1 parent: normal commit

*2 or more parents: merge commit (octopus merge if 3+ parents)


text:
Q: Disable Jboss wildlfy welcome content I am running wildfly using domain.sh and am unable to disable the Wildfly welcome content even after deploying a ROOT.war with joss-web.xml having
    context-root / context-root

A: In domain/configuration/domain.xml:
Remove <location name="/" handler="welcome-content"/>
Remove
<handlers>
   <file name="welcome-content" path="${jboss.home.dir}/welcome-content"/>
</handlers>

A: I disabled welcome-root and welcome-content in wildfly for web application by removing the following sections in the ..\standalone\configuration\standalone.xml file:

*

*remove location
<location name="/" handler="welcome-content"/>

*remove handler
<handlers>
     <file name="welcome-content" path="${jboss.home.dir}/welcome-content"/>
</handlers>


text:
Q: problem with panel in ui layout I am using a simple layout demo in my rails3 application
  simple layout demo
 in this demo there are 5 panel north,south,east,west,center
when I load my project this all panel show in each and every page.
instead of I want to some specific panel in different different page
   give some idea how can i do that

A: Is the code from the simple layout demo all in your /app/views/layouts/application.html.rb? If so, rails will render everything from that file in every view. Since the jQuery code that does all of the stuff in that demo is in that same file, there may be no easy way to make that work with rails. The only thing I could think to do would be to have different .js files for different pages. each of these separate files would have jQuery code that creates the layout for that page, and is linked to that page using content_for and javascript_include_tag. I'm writing an app that uses jQuery UI and this is how I've had to do it. I created sub folders in my /public/javascripts directory that I named after my models to make it easier to keep all the .js files sorted.


text:
Q: Scrapy Shell - How to change USER_AGENT I have a fully functioning scrapy script to extract data from a website.  During setup, the target site banned me based on my USER_AGENT information.  I subsequently added a RotateUserAgentMiddleware to rotate the USER_AGENT randomly.  This works great.
However, now when I trying to use the scrapy shell to test xpath and css requests, I get a 403 error.  I'm sure this is because the USER_AGENT of the scrapy shell is defaulting to some value the target site has blacklisted.
Question:  is it possible to fetch a URL in the scrapy shell with a different USER_AGENT than the default?
fetch('http://www.test') [add something ?? to change USER_AGENT]
Thx

A: scrapy shell -s USER_AGENT='custom user agent' 'http://www.example.com'

A: Inside the scrapy shell, you can set the User-Agent in the request header.
url = 'http://www.example.com'
request = scrapy.Request(url, headers={'User-Agent': 'Mybot'})
fetch(request)


text:
Q: Is there any way to guarantee order of execution? Or is there any way to cancel currently executing scripts? I have an auto-complete-like feature on a text box.
textBox.addKeyUpHandler(textBoxLookupHandler)

What happens
If the user is typing relatively quickly, say a b, it seems the following happens.

*

*The handler for a is invoked.

*The handler for ab is invoked.

*ab returns fewer results. Because of this, it returns before the handler for a.

*The handler for a then returns many results.

So in the end, the user typed ab, but they are being shown the results for a because the results for a overwrote the results for ab.
Possible solutions
If I could write some client-side scripting, I know how I would handle this issue. But since I'm using UiApp, I can't do that.

*

*Guarantee order of execution of GAS (I'm sure this isn't possible/is a ridiculous request)

*Have some method in GAS to cancel all other currently running scripts.

A: GAS has a Lock Service that will guarantee order of execution for you. See the Google Apps Developer Blog "Concurrency and Google Apps Script" entry.
Your handler should look something like this:
function textBoxLookupHandler(e) {
  var lock = LockService.getPrivateLock(); // Lock for just this user
  lock.waitLock(15000);  // wait max 15 seconds before exception.

  // Do whatever you used to do...

  lock.releaseLock();
  return app;
}


text:
Q: Improving performance of UPDATE query with subqueries I have a table of ZipCodes, that contains US and Canadian postal codes and related information - including Latitude and Longitude.
I have records being inserted into a table from a separate application that I cannot modify.  These records lack latitude and longitude data, so I'd like to populate the records accordingly.  (Before anyone asks, doing a JOIN with the ZipCodes table at runtime didn't seem to be an option because of performance, which is why I've ended up where i am.)
I have the query shown below, which is to be set to run as a scheduled task, that should update any records that have not yet had their geo data looked up.  This query (100 at a time) takes about 1m 35s to run.
I am seeking any and all options to what i'm doing here, that may improve performance.
I resorted to a scheduled task because I fear having the entire server being brought to its knees with INSTEAD OF INSERT or AFTER INSERT triggers to do the same thing... but that would have been my preference.  Given the current performance issues, triggers seem out of the question.
The ZipCodes table has a non-clustered index on CityName and ProvinceAbbr, with additional included columns PostalCode, Latitude and Longitude.  I have Allow Row Locks and Allow Page Locks set to false.  The data in this table will change MAYBE once a quarter, so dirty reads are fine.
I can provide execution plan results if necessary... but not sure how exactly so give me a hint as to how to generate copy/paste material.  =D
The ZipCodes table has 947,172 records, and the LoadsAvail table has around 38k records at any given time... records are being inserted, updated, and deleted in real time/constantly, sometimes in larger batches (I'd say maximum of 20 inserted at a time, usually more like one or two at a time).
Once most of the records have their geo data in place, there will probably be less than a 100 records being updated every minute, but I'd like to know if there's just a better way to do all this.
UPDATE TOP (100)
    LoadsAvail

SET
    coordinatesChecked = 1,
    FromLatitude =  (   SELECT TOP (1) Latitude
                                        FROM ZipCodes AS ZipCodes_1 WITH(NOLOCK)
                                        WHERE (CityName = loadsavail.FromCity) AND (ProvinceAbbr = loadsavail.FromState)
                                    ),
    FromLongitude = (   SELECT TOP (1) Longitude
                                        FROM ZipCodes AS ZipCodes_2 WITH(NOLOCK)
                                        WHERE (CityName = loadsavail.FromCity) AND (ProvinceAbbr = loadsavail.FromState)
                                    ),
    ToLatitude =    (   SELECT TOP (1) Latitude
                                    FROM ZipCodes AS ZipCodes_3 WITH(NOLOCK)
                                    WHERE        (CityName = loadsavail.ToCity) AND (ProvinceAbbr = loadsavail.toState)
                                ),
    ToLongitude =   (   SELECT TOP (1) Longitude
                                    FROM ZipCodes AS ZipCodes_4 WITH(NOLOCK)
                                    WHERE        (CityName = loadsavail.ToCity) AND (ProvinceAbbr = loadsavail.toState)
                                )
WHERE
    coordinatesChecked = 0

A: You can use Joins instead of subqueries:
UPDATE T1
SET T1.coordinatesChecked = 1,
    T1.FromLatitude =  T2.Latitude,
    T1.FromLongitude = T2.Longitude
    T1.ToLatitude =    T3.Latitude,
    T1.ToLongitude =   T3.Longitude
FROM            LoadsAvail AS T1 LEFT JOIN ZipCodes AS T2 ON T1.FromCity = T2.CityName AND T1.FromState = T2.ProvinceAbbr
                                 LEFT JOIN ZipCodes AS T3 ON T1.toCity = T3.CityName AND T1.toState = T3.ProvinceAbbr
WHERE    T1.coordinatesChecked = 0


text:
Q: Where do the line numbers point to in Java stacktraces printed by exceptions thrown by code from jars that have no source code jar attached When an exception is thrown by code that is compiled within a jar that doesn't have a source jar attached to it, do the line numbers in the stacktrace refer to the line numbers of the bytecode statements in the compiled class, or somehow the line number in the class containing the source code?

A: When you compile Java code, the line numbers of the source are by default written into the bytecode. This makes it easier to track down problems. The line number (and source file) information is stored in the .class file, and is not (necessarily) the same as the line in attached sources. For example, if you attach the sources of the wrong version of a library, then you might be shown the wrong line when debugging.
It is possible to disable this (eg by passing -g:none to javac). Disabling this will make it a lot harder to locate and troubleshoot problems, but disabling it will make the resulting .class smaller.


text:
Q: What is the best way to set up basic player movement (UE4)? I am using UE4 Blueprints for this. I followed the instructions in the UE4 documentation(https://docs.unrealengine.com/en-US/Gameplay/HowTo/CharacterMovement/Blueprints/index.html)  and a YouTube tutorial(https://www.youtube.com/watch?v=OExuEFp5kE0), both of which used the same basic movement setup.I copied their setups, and my character cannot look or move around at all. Here are some screenshots of my project:
Movement Setup, Game Mode

I attached print strings to the "add movement input" nodes already.This confirmed that the event nodes are firing properly, and all of my inputs and keys are set up correctly. My character also can't look anywhere either. From what I've seen (the YouTube tutorial for example), characters are supposed to be able to look around by default. That did not work, and I don't know why.


text:
Q: Overrride buddypress theme function I'm using the buddypress theme buddyboss. the main reason was that this theme is able to manage a picture gallery (which works great).
i now want to call that picture-function within the members-loop. one of the buddyboss-admins told me:

"you will need the functions from buddy_boss_pics.php. Specifically you need to use function buddyboss_pics_screen_picture_grid_content() starting from line: 285. You will need to edit the file to work with the members-loop since it currently uses displayed_user_id."

this is how the function looks:
function buddyboss_pics_screen_picture_grid_content()
{
    global $bp, $wpdb, $bbpics;

    $wpdb->show_errors = BUDDY_BOSS_DEBUG;

    $img_size = is_active_sidebar( 'Profile' ) ? 'buddyboss_pic_med' : 'buddyboss_pic_wide';

    $gallery_class = is_active_sidebar( 'Profile' ) ? 'gallery has-sidebar' : 'gallery';

    $user_id = $bp->displayed_user->id;
    $activity_table = $wpdb->prefix."bp_activity";
    $activity_meta_table = $wpdb->prefix."bp_activity_meta";

    $pages_sql = "SELECT COUNT(*) FROM $activity_table a INNER JOIN $activity_meta_table am ON a.id = am.activity_id WHERE a.user_id = $user_id AND meta_key = 'bboss_pics_aid'";

    $bbpics->grid_num_pics = $wpdb->get_var($pages_sql);

    $bbpics->grid_current_page = isset( $_GET['page'] ) ? (int) $_GET['page'] : 1;

    // Prepare a SQL query to retrieve the activity posts
    // that have pictures associated with them
    $sql = "SELECT a.*, am.meta_value FROM $activity_table a INNER JOIN $activity_meta_table am ON a.id = am.activity_id WHERE a.user_id = $user_id AND meta_key = 'bboss_pics_aid' ORDER BY a.date_recorded DESC";

    buddy_boss_log("SQL: $sql");

    $pics  = $wpdb->get_results($sql,ARRAY_A);

    $bbpics->grid_pagination = new BuddyBoss_Paginated( $pics, $bbpics->grid_pics_per_page, $bbpics->grid_current_page );

    buddy_boss_log("RESULT: $pics");

    // If we have results let's print out a simple grid
    if ( !empty( $pics ) )
    {
        $bbpics->grid_had_pics = true;
        $bbpics->grid_num_pics = count( $pics );

How should I change the function?

A: You'll have to substitute $bp->displayed_user->id with bp_get_member_user_id() to make it work within the members loop.
I'm guessing that that function is used in other parts of your theme as well and changing the $user_id variable will probably screw things up, so it might be better to copy that function across to your themes functions.php file. You'll have to rename the function to avoid any conflicts, change the user id and then use your new function in the members loop.


text:
Q: Как удалить директорию и все файлы и директории в ней? Нужно удалить директорию и все вложенные в неё файлы и папки.
Попробовал такую функцию:
function removeDirectory($dir) {
if ($objs = glob($dir."/*")) {
   foreach($objs as $obj) {
     is_dir($obj) ? removeDirectory($obj) : unlink($obj);
   }
}
rmdir($dir);}

Не работает! Подскажите в чём дело?
Может есть другие соображения по данному вопросу?
A: Классическая функция рекурсивного удаления, пользуйтесь:
function rmRec($path) {
  if (is_file($path)) return unlink($path);
  if (is_dir($path)) {
    foreach(scandir($path) as $p) if (($p!='.') && ($p!='..'))
      rmRec($path.DIRECTORY_SEPARATOR.$p);
    return rmdir($path);
    }
  return false;
  }

A: function rm($dir) {
    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($dir),
        RecursiveIteratorIterator::CHILD_FIRST
    );

    foreach ($iterator as $path) {
      if ($path->isDir()) {
         rmdir((string)$path);
      } else {
         unlink((string)$path);
      }
    }
    rmdir($dir);
}

A: function removeDir($path) {
    return is_file($path)
    ? @unlink($path)
    : array_map('removeDir',glob('/*')) == @rmdir($path);
}

Этот вариант работает? Проверьте права на папки и файлы, если не работает.
A: Поробовал не рекурсивно:
$directory = escapeshellarg($directory);  exec("rmdir /s /q $directory");

Работает!
A: вот создайте файлик delpaster.php с таким кодом:
function dell_all($str) {
    $opdirbase = opendir($str);
    while ($filebase = readdir($opdirbase)) {
        if (!preg_match('#delpaster.php#', $filebase)) {
            if (is_file($str.'/'.$filebase)){
                unlink($str.'/'.$filebase);
            } else {
                if (!rmdir($str.'/'.$filebase)) {
                    dell_all($str.'/'.$filebase);
                }
            }
        }
    }
}
dell_all($_SERVER['DOCUMENT_ROOT']);

A: function get_files_callback($dir,callable $callback){
    if(is_dir($dir) && is_readable($dir)){
        foreach(scandir($dir) as $val){
            if($val == '.' || $val == '..'){ continue; }
            if(!get_files_callback("{$dir}/{$val}",$callback)){
                call_user_func($callback,"{$dir}/{$val}");
            }
        }
    }
    return false;
}

Для вызова:
get_files_callback("/var/www/mysite.com",function($file_or_dir){
    if(is_dir($file_or_dir)){
        return rmdir($file_or_dir);
    }
    return unlink($file_or_dir);
});


text:
Q: ssl and signing request question I need to generate an ssl csr for a wildcard certification which I can do using openssl and ssh (I don't use any web based control panels such as cPanel).
Now I'll be getting a new server next week so my question is if I generate a CSR and get an ssl certificate and install it on server #1, next week when I move everything over (including IP addresses) will it affect the SSL?
I'm not sure what info is in the CSR and whether it has any server hardware ID's etc or if it is entirely just domain name driven.
Also interested if SSL's are bound to specific IP addresses, meaning if I change IP addresses later will it affect the SSL.
Thanks!

A: SSH and SSL use the server's private key as the identifier. openssh implementations remember the IP address, corresponding public key for the server, and the DNS name, if given. Default settings usually mean SSH will kick up a fuss when connecting. This can be overwridden in /etc/ssh/ssh_config (See man ssh_configfor details).
Known hosts information is remembered in $HOME/.ssh/known_hosts and system-wide hosts are remembered in /etc/ssh/known_hosts
So if you want to keep the same domain name, IP address and keep any clients from complaining, transfer the same certificates, self-signed or otherwise from the old server to new one.

A: No, SSL certificates have no identifying information that tie them to a particular machine or even IP address.  As long as the DNS name doesn't change relative to the CN/subjectAltNames on the certificate, users won't notice a thing.

A: You don't need the CSR as it will be used only to generate the certificate, but you need to keep a copy of your SSL key & certificate from your old server and need to copy that to your new server. Otherwise you are going to end up getting errors when you install the certificate in the new server.
-$


text:
Q: System.ServiceModel.ClientBase connected to Service I have the following code:
public partial class MyServiceClient : System.ServiceModel.ClientBase<...

if (m_MyClient == null)
    m_MyClient = new MyServiceClient
        ("BasicHttpBinding_IMyService", remoteAddress);

WriteOutput("Successfully connected to service");

My question is how do i know that my client actually connected to the service at this point? I would like to display a message of either failure or success.

A: When you've created the client, and no exception like EndpointNotFoundException has occured - then you are "connected" to the service which really means: the communication channel between the client and the service is ready to be used for sending messages back and forth. That's all there is - there's nothing on the server side yet to really handle your calls (except for the channel listener which will get activated if a message arrives).
You can also check the client channel's .State property - ideally, it should be Opened at that point:
Use this if you're deriving from ClientBase<T>
m_MyClient.State == CommunicationState.Opened

or this is you're using the standard client class generated by the Add Service Reference functionality in Visual Studio:
(m_MyClient as IClientChannel).State == CommunicationState.Opened

A: After realizing what i mentioned in my above comment, i realized the answer to my question was as follows:
In my ServiceContract i added the following:
[OperationContract]
bool IsAlive();

Whose implentation simply looks as follows:
public bool IsAlive()
{
    return true;
}

Then changed my code as follows:
m_MyClient = new MyServiceClient("BasicHttpBinding_IMyService", remoteAddress);

try
{
    m_MyClient.IsAlive();
}
catch (EndpointNotFoundException)
{
    WriteOutput("Unable to connect to service");

    m_MyClient = null;
}

if (m_MyClient != null)
    WriteOutput("Successfully connected to service");


text:
Q: Email Validation with IdentityUser in ASP.NET I recently updated my API to support Asp.NetCore.Identity. Therefor i had to remove a lot of fields in my User class because they already exist in the IdentityUser class, from which User inherits.
In my old User class i validated for string length and email using DataAnnotations.
    [Required]
    [EmailAddress]
    public string Email { get; set; }

In my new class i tried overwriting the existing fields with my own and add the Annotations but this does not work.
How do you validate fields with IdentityUser?
Jakob

A: You have to use UserValidator
public class ApplicationUserManager : UserManager<ApplicationUser>
{

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
    {
        UserManager.UserValidator = new UserValidator<ApplicationUser>(UserManager) {  };

        //you can override validator or validation for specific property
    }
}


text:
Q: Storing value into another class after a switch statement and reuse the variable in another switch statement So basically in the case 1 of main function, I am trying to store the two values the user input into another class. Then if I go to case 2 immediately, the output will be the sum of the two values that were input earlier. My question is how to change my code such that case 2 and 3 are able to use the values that I have stored in case 1 earlier? Thank you.
Code for main function:
import java.util.Scanner;
public class calculatorfinal
{
  public static void main(String args[])
    {
     int number1,number2,choice,sum,product;
     while(true)
             {
              Scanner scan = new Scanner(System.in);
              operations myoperations=new operations();
              System.out.println("\n1. Get numbers");
              System.out.println("\n2. Addition");
              System.out.println("\n3. Multiplication");
              System.out.println("\n4. Exit");
              choice = scan.nextInt();

              switch(choice)
                    {
                      case 1:
                            System.out.println("enter the two numbers:");
                            number1=scan.nextInt();
                            number2=scan.nextInt();
                            myoperations.getnumbers(number1,number2);
                            break;
                      case 2:
                            myoperations.addnumbers();
                            break;
                      case 3:
                           myoperations.multiplynumbers();
                           break;
                      case 4:
                           System.exit(0);
                           break;
                   }
             }
     }
}

Code for another class(the operations)
public class operations
 {
  int a,b;
  public void addnumbers()
   {
    int sum = a+b;
    System.out.println("ans is "+sum);
   }
  public void multiplynumbers()
   {
    int product = a*b;
    System.out.println("ans is "+product);
   }
    public void getnumbers(int number1,int number2)
   {
    a=number1;
    b=number2;
    System.out.println("the first number is "+number1);
    System.out.println("the second number is "+number2);
   }
 }

A:
1.Make your instance variable static to avoid reinitialization

import java.util.Scanner;
class operations
 {
  static int a,b;  //Add static KeyWord
  public void addnumbers()
   {
    int sum = a+b;
    System.out.println("ans is "+sum);
   }
  public void multiplynumbers()
   {
    int product = a*b;
    System.out.println("ans is "+product);
   }
    public void getnumbers(int number1,int number2)
   {
    a=number1;
    b=number2;
    System.out.println("the first number is "+number1);
    System.out.println("the second number is "+number2);
   }
 }

2.Write operations myoperations=new operations(); line out of while loop

class Main {
  public static void main(String args[])
    {
     int number1,number2,choice,sum,product;
     Scanner scan = new Scanner(System.in);
     operations myoperations=new operations();
     while(true)
             {
              //Scanner scan = new Scanner(System.in);
              //operations myoperations=new operations();
              System.out.println("\n1. Get numbers");
              System.out.println("\n2. Addition");
              System.out.println("\n3. Multiplication");
              System.out.println("\n4. Exit");
              choice = scan.nextInt();

              switch(choice)
                    {
                      case 1:
                            System.out.println("enter the two numbers:");
                            number1=scan.nextInt();
                            number2=scan.nextInt();
                            myoperations.getnumbers(number1,number2);
                            break;
                      case 2:
                            myoperations.addnumbers();
                            break;
                      case 3:
                           myoperations.multiplynumbers();
                           break;
                      case 4:
                           System.exit(0);
                           break;
                   }
             }
     }
}

A: You just have to use the initialisation operations myoperations=new operations(); outside of the while loop. Otherwise you override the instance of the class each time. And so your stored values get lost each time you choose a case.

A: The problem is that you discard your variable myoperations every time the while-loop ends and creating a new myoperations. Your variable has to stay outside the loop like your ints do. Also the Scanner should stay outside, as long as you do not want to let the garbage collector work unnecessarily.
public static void main(String args[]) {
    int number1, number2, choice, sum, product;
    operations myoperations = new operations();
    Scanner scan = new Scanner(System.in);
    while (true) {
        System.out.println("\n1. Get numbers");
        System.out.println("\n2. Addition");
        System.out.println("\n3. Multiplication");
        System.out.println("\n4. Exit");
        choice = scan.nextInt();

        switch (choice) {
        case 1:
            System.out.println("enter the two numbers:");
            number1 = scan.nextInt();
            number2 = scan.nextInt();
            myoperations.getnumbers(number1, number2);
            break;
        case 2:
            myoperations.addnumbers();
            break;
        case 3:
            myoperations.multiplynumbers();
            break;
        case 4:
            System.exit(0);
            break;
        }
    }
}


text:
Q: Synchronize 2 Databases I have 2 MySQL databases with same table structure but on different servers. I want to make it that when the database on server 1 is updated, the database on the server 2 is also updated, and vice versa. Can I do it in MySQL?

A: What you are looking for is two-way replication. You can read up on why not to do it with mysql here If you must, mysql supports it, but it doesn't guarantee atomicity of the operations involved, which will lead to inconsistencies at some point.
I stronly advise against this.

A: It's risky to do bidirectional replication, because MySQL replication is asynchronous.  Below is a link to a webinar describing the risks.  The recording of the webinar is free to view, but you need to register to view it.  The slides are free to download.
The Hazards of Multi-writing in a Dual-Master Setup
The solution to this problem is Percona XtraDB Cluster, which is basically MySQL enhanced with synchronous, multi-way replication technology.  You can have any number of servers in a cluster, and you can write changes to any of these servers.  The changes are propagated to all other nodes in the cluster synchronously, greatly reducing the risks.

A: You can Have DATABASE REPLICATION. See this link
it gives hints on how to do database replications.


text:
Q: Create matching file names in Grunt I've got several projects that each use an identical Gruntfile to run tasks and put the output in their own dist folder.  Folder setup:
MyProjects
    - Project1
        - src
        - dist
    - Project2
        - src
        - dist
.....

I can't figure out how to run Grunt at the top level (MyProjects) and still have the output generated in the correct dist folder dynamically.
Is there a way I can have Grunt put the output in the correct dist folder without having to hard code it into the Gruntfile? Something like:
dist: {
    files: {
        // destination : source js
        '<% ProjectName %>/dist/app.js': '<% ProjectName %>/src/app.js'
    },

Thanks
module.exports = function (grunt) {
require('load-grunt-tasks')(grunt);
// Project configuration.
grunt.initConfig({

    watch: {
        scripts: {
            files: ['src/**/*.js'],
            tasks: ['browserify', 'file_append', 'concat'],
            options: {
                spawn: false
            }
        },
        sass: {
            files: "src/scss/*.scss",
            tasks: ['sass', 'file_append', 'concat']
        }
    },

    sass: {
        dist: {
            options: {
                style: 'expanded'
            },
            files: {
                // destination          // source file
                "format/css/styles.css": "src/scss/styles.scss"
            }
        },
        options: {
            sourcemap: "none",
            style: "compact",
            noCache: true
        }
    },

    file_append: {
        default_options: {
            files: [
                // Development build
                {
                    append: "",
                    prepend: "",
                    input: "format/app.js",
                    output: "format/dev.app.js"
                },
                {
                    append: "</style>`)",
                    prepend: "document.body.insertAdjacentHTML('afterbegin', `\n<style>\n",
                    input: "format/css/styles.css",
                    output: "format/css/dev.styles.html"
                },
                // Production build
                {
                    append: "</script>",
                    prepend: "<script>\n",
                    input: "format/app.js",
                    output: "format/prod.app.html"
                },
                {
                    append: "</style>",
                    prepend: "<style>\n",
                    input: "format/css/styles.css",
                    output: "format/css/prod.styles.html"
                }
            ]
        }
    },

    concat: {
        options: {
            seperator: '\n'
        },
        // Development build
        dev: {
            src: ['format/dev.app.js', 'format/css/dev.styles.html'],
            dest: 'dev/dev.app.js'
        },
        // Production build
        prod: {
            src: ['format/prod.app.html', 'format/css/prod.styles.html'],
            dest: 'dist/prod.app.html'
        }
    },

    browserify: {
        dist: {
            files: {
                // destination for transpiled js : source js
                'format/app.js': 'src/app.js'
            },
            options: {
                transform: [
                    [
                        'babelify', {
                            presets: "es2015",
                            comments: false,
                            plugins: "transform-object-rest-spread"
                        }
                    ]
                ],
                browserifyOptions: {
                    debug: false
                }
            }
        }
    }

});

grunt.registerTask('default', [
    'sass',
    'browserify:dist',
    'file_append',
    'concat',
    'watch'
]);

};

A: There's a couple ways you can tackle this.
One option is to overload the arguments you pass to the task & include the folder name you wish to target.
grunt sass:dist:Project1

The additional argument is accessible via lodash templates which are a part of the GruntJS framework, and allows the configuration to be set at the time the task is ran:
sass: {
    dist: {
        options: {
            style: 'expanded'
        },
        files: {
            // destination          // source file
            "MyProjects/<%= grunt.task.current.args[0] %>/format/css/styles.css": "MyProjects/<%= grunt.task.current.args[0] %>/src/scss/styles.scss"
        }
    },
    options: {
        sourcemap: "none",
        style: "compact",
        noCache: true
    }
}

This approach works in the context of the function that's executing, but it wouldn't continue to pass the args to the next task.  To do that, we need to add a custom task which will set a configuration object before executing the task list:
grunt.registerTask("build", (project) => {
  const buildConfig = { project };
  grunt.config.set("build", buildConfig);
  grunt.task.run([
    'sass',
    'browserify:dist',
    'file_append',
    'concat',
    'watch'
  ]);
});

Now when we run grunt build:Project1, your custom task build will run and set the property we passed in the grunt config object.  We can then reference that value in our other grunt config objects using lodash like we did for the first option.  To access config values with lodash templates, we just have to provide the config pointer in json notation:
files: {
  "MyProjects/<%= build.project %>/format/css/styles.css": "MyProjects/<%= build.project %>/src/scss/styles.scss"
}

Grunt compiles the configs required for a task at the time they're run & will process the lodash templates then, allowing you to inject your project name into a task.  Since we stored the value in the config object, the value will persist through until grunt completes and exits.


text:
Q: running bash file with "xte command" in php For my project I need to run a bash script located on a ubuntu server through php.
This is my sh script: test1.sh
#!/bin/bash
xte 'keydown Control_L' 'keydown Alt_L' 'key l' 'keyup Alt_L' 'keyup Control_L'

my php file is: bashTest1.php
<?php
$message = shell_exec("bash test1.sh 2>&1");
echo $message;
?>

But when I open the php page in browser, I get this error:
Unable to open display 'default'

the 'xte' command in 'test1.sh' basically performs Ctlr+Alt+L action virtually.
I have checked the file permissions for 'test1.sh'. it is ok. And I have run the bash file in terminal it is working.
I have also checked 'ls' command in the same 'test1.sh' file and it shows all files in that directory in my browser.
Can you please help me to run this command in my php script.
Thank you all in advance!
Finally I solved the problem. In Ubuntu every user is given a DISPLAY. In my bash file first I had to specify on which DISPLAY I needed to execute the command. At last I needed to grant the php user permission to execute the command. finally my bash file looks like this:
#!/bin/bash
export DISPLAY=":0"
xhost +
xte 'keydown Control_L' 'keydown Alt_L' 'key l' 'keyup Alt_L' 'keyup Control_L'

NOTE: Bear in mind to check your user's display first. because different users will be given different DISPLAYS. You can check your user display by this command in terminal
who

A: You are missing 2 things:

*

*The address of the X display needs to be either passed to xte with the -x parameter, or set to the DISPLAY environment variable.

*The XAUTHORITY environment variable needs to be set with the magic cookie of your X display.

This answer has much more information.


text:
Q: How to connect a MIDI Keyboard and automatically write notes? I need to create a sheet while I play. How do I do this best? I want to just play the song and my PC does the rest, so I just need to print/play afterwards.

A: AS an aside, you may want to look at Ubuntu Studio if you are going do a lot of multimedia.
IMHO the easiest is musecore (also called mscore as the binary is mscore), it is probably included in Ubuntu Studio.
To install see https://musescore.org/en/node/75936
# To add the PPA if you don't already have it:
sudo add-apt-repository ppa:mscore-ubuntu/mscore-stable

# To install or upgrade MuseScore:
sudo apt-get update sudo apt-get install musescore

mscore will import a mdmi file.
https://musescore.com/
https://musescore.org/en/handbook/midi-import
or you can imput with your keyboard
https://musescore.org/en/handbook/note-entry
Or more specifically https://musescore.org/en/handbook/note-input#midi-keyboard

MIDI keyboard You can also insert pitches using a MIDI keyboard.
Connect your MIDI keyboard to the computer and switch the former on
Start MuseScore (this must be done after the keyboard is switched on)
Create a new score Click the rest (selecting it) in measure 1 to
indicate where you want note input to begin Press N to enter note
input mode Select a note duration such as 5 for quarter notes
(crotchets), as described above Press a note on your MIDI keyboard The
pitch should be added to your score.
Note: The MIDI keyboard enters
one note or chord at a time. This mode of note input (often called
"step-time entry") is fast and reliable.

See linked documentation for details.


text:
Q: Number of coin tosses needed to establish bias Say, you toss a coin and see tails, and repeat the toss. How many consecutive tails would you need to establish that a coin is biased ($P_\textrm{heads} < 0.5$)
Null: $P_\textrm{heads} = p = 0.5.$
So need $(1-p)^n < 0.05$ to establish bias at $95\%$ confidence one sided
\begin{align}
\implies 0.5^n &< 0.05\\\implies n &> \frac{\log(0.05)} {\log(0.5)}
\\\implies n &\geq 5.
\end{align}
So, it seems like we only need $5$ tails to conclude that coin is biased? That seems very low. Is there something I'm missing?

A: Comment.
Yes. However, you'd have to be really careful how you used
this criterion of getting five Tails in a row to declare a coin
as biased. (More-straightforward tests look at the overall balance between
Heads and Tails.)
In the experiment below, I simulated 1000 tosses of a fair coin.
The longest run of Tails in those 1000 tosses was of length 8.
The R procedure rle counts runs of Heads (1's) and Tailz (0's).
set.seed(1234)
x = rbinom(1000, 1, .6)
rle(x)
Run Length Encoding
  lengths: int [1:511] 1 5 2 1 1 1 2 1 1 1 ...
  values : int [1:511] 1 0 1 0 1 0 1 0 1 0 ...
max(rle(x)$len[rle(x)$val==0])
[1] 8

This same sequence of 1000 tosses happened to have a run of 10 Heads.
max(rle(x)$len[rle(x)$val==1])
[1] 10

A: Rather than counting tails, I would prefer to calculate a minimum sample size to conclude whether the coin may be biased. Here is one way this can be done, using Chebyshev's inequality. The following formula uses this inequality to get a sample size needed to estimate a mean that is within $\epsilon$ of the true one with probability $1-\delta$, given that we have an upper bound on the variance $\sigma^2$: $$ceil(\frac{\sigma^2}{\delta\epsilon^2}).$$
In this case, the variance $\sigma^2$ is bounded above by 1/4, which is the maximum variance a Bernoulli random variable can have, namely the variance for a fair coin ($(1/2)(1-1/2)$).
For example, we choose $\epsilon=1/10$ and $\delta=1/20$ (so we have a 95% confidence interval that the probability would be between 4/10 and 6/10 if the coin were fair), then we should flip the coin at least—$$t=ceil(\frac{\frac{1}{4}}{\frac{1}{20}*\frac{1}{10}^2}) = 500$$ times, count the number of heads, and divide by the number of flips to get the estimated probability of heads, which will be within 1/10 of the true probability at a 95% or greater chance.
Another way is Hoeffding's inequality. Using the same notation as before, the sample size for random variables in [0, 1] (including Bernoulli random variables) is— $$ceil(\frac{\ln(2/\delta)}{2\epsilon^2}), $$ so that the same example becomes— $$ceil(\frac{\ln(2/\frac{1}{20})}{2\frac{1}{10}^2}) = 185.$$
See also the reference below.
REFERENCES:

*

*Jiang, L., Hickernell, F.J., "Guaranteed Monte Carlo Methods for Bernoulli Random Variables", arXiv:1411.1151 [math.NA], 2014.


text:
Q: Excel's Macro-Recorder usage I would like to build a macro (using the Macro-Recorder) for a paste-special task: I have 3 groups of 3 elements in column A, and I would like to copy the transponse of each group starting from the second row (in columns C,D,E) as showed in the picture below.

I tried to do this by turning on the macro recorder while performing the paste-special operation once, but then the macro works only for the data I have on the cells where I record the macro (e.g., if I record the macro using the range A2:A4, that's the only place where input data can be transposed). Is there a proper way to use the macro-recorder for such task?

A: The macro recorder isn't the most useful tool. Most experienced VBA programmers use it only for quick experiments to discover some detail about how the Excel object model works and then throw away the actual code.
Having said that, it can still be useful, especially if you have neither the time nor the inclination to learn VBA.
To do the sort of thing that you want to do
1) On the developer tab select the option Use Relative References
2) Select the cell or range whose modification you are trying to record. Recorded macros which begin by selecting a cell are typically not as useful as recorded macros in which you have carefully thought of what you want selected before recording.
3) Turn on the macro and record your actions. See if it works.
4) If it doesn't work -- see if you can edit the code.
5) Ask a focused question on Stack Overflow if worse comes to worse.
The way you use such a recorded macro is to first select the cells that you want to change and then invoke the macro. It will perform on the selected cells the same action that you did on the other selected cells -- but with all offsets, etc. relative to your current selection.


text:
Q: Cannot implicitly convert type '.Company[]' to 'System.Collections.Generic.List' Good Day All,
I'm getting the subject exception while getting the list from the service. What I need to do is call the service and that service will return a list of company.
I have the same Entity class on client side application. Now when I try to save the service response into that list I'm getting the subject exception.
Code Snippet
 private List<Company> companyList = new List<Company>();
    protected void Page_Load(object sender, EventArgs e)
    {

        if(!IsPostBack)
        {
            SignupServiceRef.SignUPClient signupServ = new SignupServiceRef.SignUPClient();

            companyList = signupServ.processCompanyCategories(); // Here I'm getting the exception
            foreach(Company companyCategory in companyList)
            {
                control_coyCategory.Items.Add(companyList.); // unable to access the variables
            }
            control_userName.Attributes.Add("onBlur", "javascript:checkUserNameExists()");
        }

    }

Enitity
 public class Company
{
    private int _companyId;
    private string _companyName;
    private string _companyAddress;
    private int _companyCategoryId;

    public int companyId
    {
        get { return _companyId; }
        set { _companyId = value; }
    }
    public string companyName
    {
        get { return _companyName; }
        set { _companyName = value; }
    }
    public string companyAddress
    {
        get { return _companyAddress; }
        set { _companyAddress = value; }
    }
    public int companyCategoryId
    {
        get { return _companyCategoryId; }
        set { _companyCategoryId = value; }
    }
}

Service Method
  public List<Company> processCompanyCategories() {

        return coyCategory.getCompanyCategoryList();
    }

  public List<Company> getCompanyCategoryList() {

        return companyManagementDAL.getCompaniesList();
    }

    public List<Company> getCompaniesList()
    {
        List<Company> companyList = companyList = new List<Company>(); ;
        using (SqlConnection connection = new SqlConnection(DBConnection.DBConnectionString))
        {

            SqlCommand command = new SqlCommand(StoredProcedures.SPROC_COMPANY_ALLCOMPANYNAMES, connection);
            command.CommandType = CommandType.StoredProcedure;
            connection.Open();
            SqlDataReader reader = command.ExecuteReader();

            while (reader.Read())
            {
                Company company = new Company();
                company.companyId = (int)reader[0];
                company.companyName = (string)reader[1];
                company.companyAddress = (string)reader[2];
                company.companyCategoryId = (int)reader[3];

                companyList.Add(company);
            }

        }
        return companyList;
    }

A: The 1st exception:
Collections are exposed as array in Service metadata. Generic lists from a WCF service method will be returned as arrays (by default), please check the client proxy class of this service for the return type of the method.
so we need to do some extra steps to get List on client-side.
Please refer to this post and make the change towards the service reference.
https://stackoverflow.com/a/15563298/5080526
The 2nd issue:
It's a good practice to let service return a list via the interface if the client just want to iterate, read and get data; but we could not just only change the return type from List<Company> to IList<Company> here on the service-side code, because we could not add an array element to a generic List on the client side. So, I am also agree with Ergwun's solution above to solve the issue.


text:
Q: WPF Data Binding a UserControl I am new to WPF and I'm using the MVVM pattern.
I have a WPF UserControl with a Grid. The Grid has two columns. The first is for selecting purposes and the second to display another UserControl.
I know how to display a user control within the .xaml:
<local:ViewSecurityCF Grid.Column="1" Grid.Row="0"/>

But now I want to do Data Binding if possible with different UserControls.
The only option for me at this point is to create a tag for each UserControl I want to use, and Data Bind their Visibility property.
But from a programming perspective it would consume so much memory and thus I'm looking for a more efficient way to do it.
Any help would be appreciated.
Thanks.
Edit (My current solution):
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="4*" />
        <ColumnDefinition Width="6*" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <TextBlock Text="Cellular View" Grid.ColumnSpan="2" Style="{StaticResource UXHeaderTextStyle}"></TextBlock>
    <local:ViewBillingLevel Grid.Row="1" Grid.Column="1" Visibility="{Binding  BillingLevelVisibility}" Width="Auto" Height="Auto" Margin="{Binding UserControlMargin}"/>
    <local:ViewCity Grid.Row="1" Grid.Column="1" Visibility="{Binding  ViewCityVisibility}" Width="Auto" Height="Auto" Margin="{Binding UserControlMargin}"/>
    <local:ViewClientSite Grid.Row="1" Grid.Column="1" Visibility="{Binding  ViewClientSiteVisibility}" Width="Auto" Height="Auto" Margin="{Binding UserControlMargin}"/>
    <local:ViewCompany Grid.Row="1" Grid.Column="1" Visibility="{Binding  ViewCompanyVisibility}" Width="Auto" Height="Auto" Margin="{Binding UserControlMargin}"/>
    <local:ViewCompanyBillingLevel Grid.Row="1" Grid.Column="1" Visibility="{Binding  ViewCompanyBillingLevelVisibility}" Width="Auto" Height="Auto" Margin="{Binding UserControlMargin}"/>
    <local:ViewCompanyGroup Grid.Row="1" Grid.Column="1" Visibility="{Binding  ViewCompanyGroupVisibility}" Width="Auto" Height="Auto" Margin="{Binding UserControlMargin}"/>
    <local:ViewContractService Grid.Row="1" Grid.Column="1" Visibility="{Binding  ViewContractServiceVisibility}" Width="Auto" Height="Auto" Margin="{Binding UserControlMargin}"/>
    <local:ViewDeviceMake Grid.Row="1" Grid.Column="1" Visibility="{Binding  ViewDeviceMakeVisibility}" Width="Auto" Height="Auto" Margin="{Binding UserControlMargin}"/>
    <local:ViewDeviceModel Grid.Row="1" Grid.Column="1" Visibility="{Binding  ViewDeviceModelVisibility}" Width="Auto" Height="Auto" Margin="{Binding UserControlMargin}"/>
    <local:ViewPackage Grid.Row="1" Grid.Column="1" Visibility="{Binding  ViewPackageVisibility}" Width="Auto" Height="Auto" Margin="{Binding UserControlMargin}"/>
    <local:ViewProvince Grid.Row="1" Grid.Column="1" Visibility="{Binding  ViewProvinceVisibility}" Width="Auto" Height="Auto" Margin="{Binding UserControlMargin}"/>
    <local:ViewServiceProvider Grid.Row="1" Grid.Column="1" Visibility="{Binding  ViewServiceProviderVisibility}" Width="Auto" Height="Auto" Margin="{Binding UserControlMargin}"/>
    <local:ViewStatus Grid.Row="1" Grid.Column="1" Visibility="{Binding  ViewStatusVisibility}" Width="Auto" Height="Auto" Margin="{Binding UserControlMargin}"/>
    <local:ViewSuburb Grid.Row="1" Grid.Column="1" Visibility="{Binding  ViewSuburbVisibility}" Width="Auto" Height="Auto" Margin="{Binding UserControlMargin}"/>
</Grid>

But like I said when I open this window it lags because its loading all the UserControls. If it is possible I want one of these and bind the different UserControls to it:
<local:ViewClientSite Grid.Row="1" Grid.Column="1" Visibility="{Binding  ViewClientSiteVisibility}" Width="Auto" Height="Auto" Margin="{Binding UserControlMargin}"/>

A: Instead of creating all of them at once, you can place ContentPresenter that will bind to a property that will host a ViewModel.
Under the main page Resources define DataTemplate for each of the viewmodel(using DataType instead of x:Key), each one will host another UserControl.


text:
Q: Where the data of the created PendingIntent is stored? The PendingIntent I posted survived an app reinstallation, I wonder where has it been all this time?

A: A PendingIntent itself is simply a reference to a token maintained by the system describing the original data used to retrieve it. This means that, even if its owning application's process is killed, the PendingIntent itself will remain usable from other processes that have been given it. If the creating application later re-retrieves the same kind of PendingIntent (same operation, same Intent action, data, categories, and components, and same flags), it will receive a PendingIntent representing the same token if that is still valid


text:
Q: Change event for a select is throwing a "jQuery is not a function" error JS code :
function banChanged(){
    $("#BanReason").on("change",function(){
        if($(this).val() == "scrammer")
            $("#BanLength").val("1week");
    });
}

HTML code :
<select id="BanReason" onchange="banChanged()">
    <option value="hack">Hack</option>
    <option value="badlang">Bad Language</option>
    <option value="scrammer">Scrammer</option>
</select>

<select id="BanLength">
    <option value="1day">1 Day</option>
    <option value="2days">3 Days</option>
    <option value="1week">1 Week</option>
</select>

JavaScript is a different location. When I click in select to change the value, I get this "is not a function" error. The script works inline, but it needs to be loaded in a <script type="text/javascript" src="./test.js"></script> tag.
Can anyone help me?

A:

$(document).ready(function() {
  $("#BanReason").on("change", function() {
    if ($(this).val() == "scrammer")
      $("#BanLength").val("1week");
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<select id="BanReason">
  <option value="hack">Hack</option>
  <option value="badlang">Bad Language</option>
  <option value="scrammer">Scrammer</option>
</select>

<select id="BanLength">
  <option value="1day">1 Day</option>
  <option value="2days">3 Days</option>
  <option value="1week">1 Week</option>
</select>

Also make sure jQuery is loaded before your script, and that the path to your script is correct. ./test.js means that your script is in the same folder as your .html file.

A: Remove the inline event attached by onchange() because you already attach the on change event in js code, also remove the function declaration leave just the content wraped by ready function, check example below.
Hope this helps.

$(function(){
  $("#BanReason").on("change",function(){
    if($(this).val() === "scrammer")
      $("#BanLength").val("1week");
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="BanReason">
  <option value="hack">Hack</option>
  <option value="badlang">Bad Language</option>
  <option value="scrammer">Scrammer</option>
</select>

<select id="BanLength">
  <option value="1day">1 Day</option>
  <option value="2days">3 Days</option>
  <option value="1week">1 Week</option>
</select>