text:
Q: Doctrine2 + ZF2 - Iterate with sub-categories I'm currently working on a Blog module of ZF2 and I found a way to iterate trough my categories and check if they have children.
The problem, is that I always get this error:
Fatal error: Call to a member function isEmpty() on a non-object in /var/www/microweb2/module/Blog/src/Blog/Entity/CategoryIterator.php on line 19

Here's the line 19: return $this->_data->current()->getSubCategories()->isEmpty();
Well, currently, my CategoryIterator is a class that implements \RecursiveIterator but it doesn't work... I took this code from this blog: http://wildlyinaccurate.com/simple-nested-sets-in-doctrine-2
Here's my code:
My Entity\Category:
<?php

namespace Blog\Entity;

use Doctrine\ORM\Mapping as ORM;
use \Application\Entity\AbstractEntity;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Entity
 * @ORM\Table(name="blog_categories")
 */
class Category extends AbstractEntity {

    // OTHER USELESS CODE

    /**
     * Set parent
     *
     * @param \Blog\Entity\Category $parent
     * @return Category
     */
    public function setParent(\Blog\Entity\Category $parent = null)
    {
        $this->parent = $parent;

        return $this;
    }

    /**
     * Get parent
     *
     * @return \Blog\Entity\Category
     */
    public function getParent()
    {
        return $this->parent;
    }

    /**
     * Add subcategories
     *
     * @param \Blog\Entity\Category $subcategories
     * @return Category
     */
    public function addSubCategory(\Blog\Entity\Category $subcategories)
    {
        $this->subcategories[] = $subcategories;

        return $this;
    }

    /**
     * Remove subcategories
     *
     * @param \Blog\Entity\Category $subcategories
     */
    public function removeSubCategory(\Blog\Entity\Category $subcategories)
    {
        $this->subcategories->removeElement($subcategories);
    }

    /**
     * Get subcategories
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getSubCategories()
    {
        return $this->subcategories;
    }
}

My CategoryIterator:
<?php

namespace Blog\Entity;

use Doctrine\Common\Collections\Collection;

class CategoryIterator implements \RecursiveIterator
{

    private $_data;

    public function __construct(Collection $data)
    {
        $this->_data = $data;
    }

    public function hasChildren()
    {
        return $this->_data->current()->getSubCategories()->isEmpty();
    }

    public function getChildren()
    {
        return new CategoryIterator($this->_data->current()->getSubCategories());
    }

    public function current()
    {
        return $this->_data->current();
    }

    public function next()
    {
        $this->_data->next();
    }

    public function key()
    {
        return $this->_data->key();
    }

    public function valid()
    {
        return $this->_data->current() instanceof \Blog\Entity\Category;
    }

    public function rewind()
    {
        $this->_data->first();
    }

}

And my IndexController::indexAction():
public function indexAction()
{
    $adapter = new SelectableAdapter($this->doctrine()->getRepository('Blog\Entity\Article'));
    $paginator = new Paginator($adapter);
    $paginator->setCurrentPageNumber($this->params()->fromQuery('page', 1))
              ->setItemCountPerPage(10);

    $categories = $this->doctrine()->getRepository('Blog\Entity\Category')->findBy(array(), array('id' => 'ASC'));

    $iterator = new RecursiveIteratorIterator(
        new CategoryIterator(
            new ArrayCollection($categories)
        ),
        RecursiveIteratorIterator::SELF_FIRST
    );

    return new ViewModel(array(
        'articles' => $paginator,
        'categories' => $iterator,
    ));
}

Don't be mad, all of my uses statements are correct!
Here's my partial view that use the categories variable (everything is well passed because it was working before without subcategories...):

Catégories

    <?php foreach ($this->categories as $index => $cat) : ?>
        <?php
        if ($cat->getParent() !== null) {
            continue;
        }

        $class = '';
        if (isset($this->current)) {
            if ($this->current === $cat->getId()) {
                $class = 'class="active"';
            }
        }
        ?>
        <li <?= $class; ?>>
            <a href="<?= $this->url('blog/category', array('alias' => $cat->getAlias())); ?>"><?= $cat->getName(); ?>
            <?php if ($this->categories->hasChildren()) : ?>

                <?php foreach ($this->categories->getChildren() as $scat) : ?>
                <?php $class2 = ($scat->getId() === $this->current ? 'class="active"' : ''); ?>
                    <li <?= $class2; ?>>
                        <a href="<?= $this->url('blog/category', array('alias' => $scat->getAlias())); ?>"><?= $scat->getName(); ?>

                <?php endforeach; ?>

            <?php endif; ?>

    <?php endforeach; ?>

So if someone can tell me why it works for the guy but not for me, well, any idea is welcome!

A: For anyone who lands here with the same issue - the post linked shows the function hasChildren slightly different.
public function hasChildren()
{
    return ( ! $this->_data->current()->getChildCategories()->isEmpty());
}

Once this is added the iterator shows the child elements.


text:
Q: Loop through json file and delete key if it matches I have the following structure on a JSON file:
{
  "channels": [
    "180873781382873088",
    "181268808055521280",
    "183484852287307777",
    "174886257636147201",
    "174521530573651968"
  ]
}

I want to know how I can loop through the file searching for a specific string, and delete it if it matches.
Thank you.
EDIT: A Google search pointed me to using a for loop and using the del command to remove the key, so here's what I tried:
channel = "180873781382873088"

for item in data['channels']:
    del channel

But it only deletes the variable channel, not the key that matches it's value.

A: Try
data['channels'].remove(channel)

instead of the for loop.
This will automatically search the array and remove any key matching your variable. If you need help saving the results to a file I would open another question.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to change screen on double tap I have successfully made a double tap action using - (void) touchesEnded but I would like to make a double tap event that switches to another view like it would if you pushed a button . How would I do this?

A: You will need to do this in code, I think.  You can create the segue in interface builder, give it an identifier, and then call performSegueWithIdentifier when you catch the double-touch event.

A: Using a gesture will be useful and simple. Simply set the count of Touches & you are done.


text:
Q: How to find coefficient of x^m in the polynomial? How to find coefficient of
x^m (m<=n)

in the polynomial of type
(a1+b1x)(a2+b2x)...(an+bnx)? O(n^2)

Algorithm needed!

A: Speaking personally I would use an inductive application of the Binomial Theorem.
http://en.wikipedia.org/wiki/Binomial_theorem
This will solve your base case of two binomials. Then the rest is just repeating the application using the associativity of multiplication.
I don't know enough C to write this though, I'm sorry.

A: Coefficient of m-th element is sum of all possible products of (a or b)[i] for all i between 0 and m such that there are exactly m selections of b (and n - m selections of a).
More procedurally, generate all combinations of integers between 0 and m, multiply elements of a at those indices, get a complement of each combination and multiply the obtained product further by the elements of b at those indices. Add all obtained products together.

A: (a1+b1x)(a2+b2x)...(an+bnx)=b1*b2*...*bn*(a1/b1+x)*(a2/b2+x)...(a/bn+x)

Right part is polynomial with roots (-a1/b1,-a2/b2...-an/bn)
There is O(N^2) algorithm to find coefficients of this polynomial, implemented here
(Don't forget to multiply coefficients by product of b[i])


text:
Q: How i can remove key/value from a list of tuples by key from another list of tuples? I need to remove keys and values in a list of tuples by keys from another list of tuples
list_tuple = [('NHR', 153.065), ('BHS', 153.179), ('KMH', 153.393), ('DRR', 287.987), ('SSW', 487.294), ('EOF', 546.972), ('LHM', 687.54)]

list_tuple_keys = [('DRR', 'Error time'), ('EOF', 'Error time'), ('LHM', 'Error time'), ('SSW', 'Error time')]

example = [('NHR', 153.065), ('BHS', 153.179), ('KMH', 153.393)]

A: Given the code
given = [('NHR', 153.065), ('BHS', 153.179), ('KMH', 153.393), ('DRR', 287.987), ('SSW', 487.294), ('EOF', 546.972), ('LHM', 687.54)]
to_remove = [('DRR', 'Error time'), ('EOF', 'Error time'), ('LHM', 'Error time'), ('SSW', 'Error time')]
expected = [('NHR', 153.065), ('BHS', 153.179), ('KMH', 153.393)

I'd first reduce the list of items to remove to just the minimum information needed:
keys = []
for item in to_remove:
    keys.append(item[0])

or keys = [t[0] for t in to_remove] as a list comprehension.
Then you can go through the list of items to be filtered and skip the unwanted ones:
result = []
for item in given:
    if not item[0] in keys:
        result.append(item)

or result = [t for t in given if not t[0] in keys] as a list comprehension.
Finally
print(result)

results in
[('NHR', 153.065), ('BHS', 153.179), ('KMH', 153.393)]

A: One way is to make a hashmap for filtering target list.
filter_keys = {t[0]: True for t in list_tuple_keys}
result = [t for t in list_tuple if not filter_keys.get(t[0], False)]

A: You can do this with list comprehension
result = [item for item in list_tuple if item[0] not in dict(list_tuple_keys)]

# result
[('NHR', 153.065), ('BHS', 153.179), ('KMH', 153.393)]

Converted list_tuple_keys into a dictionary, so it's easy to check the membership.


text:
Q: SUM fields in SQL server depending on another field and using inner join The title may be a bit vague, but let me explain:
I have a script that creates a database and two tables, one for transactions and one for accounts:
CREATE TABLE Transactions(
        transactionID VARCHAR(10),
        description VARCHAR(70),
        accountID VARCHAR(5) NOT NULL,
        amount MONEY NOT NULL

        CONSTRAINT transactionsPK
            PRIMARY KEY (transactionID)
)

CREATE TABLE Accounts(
        accountID VARCHAR(10),
        accountName VARCHAR(70) NOT NULL,
        bank VARCHAR(70) NOT NULL

        CONSTRAINT accountsPK
            PRIMARY KEY (accountID)
)

I would like to write a SELECT statement to list all of the fields in the accounts table, along with a total column. I thought I could use an INNER JOIN to only display each account, but I am not sure if DISTINCT would work better.
Its purpose is to SUM all of the transactions for each account, and place that amount in the row for the account itself.
I can achieve the product of listing the amount of each transaction, but not the SUM of all tansactions for each Account.
SELECT Accounts.accountID, Accounts.accountName, Accounts.bank, Transactions.amount
    FROM Accounts
    INNER JOIN Transactions
    ON Accounts.accountID = Transactions.accountID

Any help would be greatly appreciated.

A: You just need the SUM() function:
SELECT a.accountID, a.accountName, a.bank, SUM(t.amount)
FROM accounts a
INNER JOIN transactions t
ON a.accountID = t.accountID
GROUP BY a.accountID, a.accountName, a.bank

When you are done you need to group by the accountID. This will effectively sum each group (each account).
Here are some SQL aggregate functions for you.

A: I think this would help :
SELECT a.*,
       sumamt
FROM   Accounts a
       LEFT OUTER JOIN (SELECT accountID,
                               Sum(amount) sumamt
                        FROM   transactions
                        GROUP  BY accountID) AS t
                    ON a.accountID = t.accountID

sample sql fiddle here


text:
Q: How to format date/time in a specific timezone with the JavaScript date-fns library Is there a way to format/output a date in a specified timezone with the date-fns library? I can format a date easily enough:
format(
  new Date(),
  'MM/DD/YYYY'
)

And I can specify a locale (from their docs):
var eoLocale = require('date-fns/locale/eo')
var result = format(
  new Date(2014, 6, 2),
  'Do [de] MMMM YYYY',
  {locale: eoLocale}
)

How can I specify a timezone?

A: I am afraid, that you will have to wait for the time zone support in date-fns till the version 2.0 is released. The time zone support has not been finished yet and it is likely to be added only to the new version, where parsing and formatting is expected to be improved.
In the meanwhile, you have to reach to other libraries, which allow formatting in arbitrary time zone. For example, Moment.js or Day.js:
// Print "06/01/2014 8:00:00 PM GMT-0400 (EDT)"

moment('2014-06-02T00:00:00.000Z')
  .tz('America/New_York')
  .format('MM/DD/YYYY h:mm:ss A [GMT]ZZ (z)')

dayjs('2014-06-02T00:00:00.000Z')
  .format('MM/DD/YYYY h:mm:ss A [GMT]ZZ (z)',
          { timeZone: 'America/New_York' })

Runnable code snippet inserting the result to HTML:

// Initialise day.js extensions
dayjs.extend(dayjs_plugin_timeZone)

// Prepare the canvas
const output = document.getElementById('output')
output.innerHTML = 'Expected:  06/01/2014 8:00:00 PM GMT-0400 (EDT)\n'

// Print "06/01/2014 8:00:00 PM GMT-0400 (EDT)"

const date1 = moment('2014-06-02T00:00:00.000Z')
  .tz('America/New_York')
  .format('MM/DD/YYYY h:mm:ss A [GMT]ZZ (z)')
output.innerHTML += `Moment.js: ${date1}\n`

const date2 = dayjs('2014-06-02T00:00:00.000Z')
  .format('MM/DD/YYYY h:mm:ss A [GMT]ZZ (z)',
          { timeZone: 'America/New_York' })
output.innerHTML += `Date.js:   ${date2}\n`

A: Version 2 saves the day!
  const { startOfDay, endOfDay, format } = require('date-fns') // or use imports
  const { enGb } = require('date-fns/locale/en-GB') // or use imports

  const fromDate = startOfDay(new Date('02-Aug-2001'))
  const toDate = endOfDay(new Date('02-Aug-2001'))
  const from = format(fromDate, 'dd-MMM-yyyy HH:mm:ss', { locale: enGb })
  const to = format(toDate, 'dd-MMM-yyyy HH:mm:ss', { locale: enGb })
  console.log(from) // 02-Aug-2001 00:00:00
  console.log(to) // 02-Aug-2001 23:59:59

https://date-fns.org/v2.21.1/docs/format // official docs
https://www.npmjs.com/package/date-fns-tz#user-content-format // more human readable docs (note date-fns-tz does not need to be installed)


text:
Q: Got operation not permitted while running flutter pub get in jenkins shell I placed the flutter folder under the ~/Documents folder. When I try to execute flutter relevant commands got operation not permitted.
/user/username/Documents/flutter/bin/flutter: Operation not permitted.


text:
Q: Proving that $\left|\frac{1-e^{iz}}{z^2}\right| \le \frac{2}{|z|^2}$? I am wondering if I'm missing some sort of triangle inequality trick to show this, or if I need more context. Can this be solved purely algebraically?
Thanks.
Edit: I've tried this, but I'm not sure I'm using the triangle inequality properly.
$\left|\frac{1-e^{iz}}{z^2}\right| \le \frac{1}{|z|^2} + \left|\frac{-e^{iz}}{z^2}\right| = \frac{1}{|z|^2} + \frac{|-e^{iz}|}{|z^2|} = \frac{1}{|z|^2} + \frac{1}{|z^2|} = \frac{2}{|z|^2}$

A: The usual triangle inequality is enough, as the domain of this inequality is $|z|\ne 0$, it amounts to proving
$$\bigl|1-\mathrm e^{iz}\bigr|\le 2. $$
Now, say $z=x+iy$, we have
$$\bigl|1-\mathrm e^{iz}\bigr|\le 1+ \bigl|\mathrm e^{iz}\bigr|=1+\bigl|\mathrm e^{ix}\bigr|\bigl|\mathrm e^{-y}\bigr|=1+\bigl|\mathrm e^{-y}\bigr|,$$
so it is true if $y\ge 0$.
If $y<0$,  it is easy to see that for each value of the argument, there exists a value of $z$ for which the inequality is false.


text:
Q: Simple: creating tables in database Really simple question. I forgot how to deal with this specific script. With a PHP file I create tables in mysql database. I have $query variable with the following commands:
$query = "CREATE TABLE IF NOT EXISTS `table1` (
              `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
                      `status` int(11) NOT NULL
              )ENGINE=MyISAM DEFAULT CHARSET=utf8;

              CREATE TABLE IF NOT EXISTS `table2` (
              `something` varchar(100) NOT NULL,
              `whatever` text NOT NULL
              )ENGINE=MyISAM DEFAULT CHARSET=utf8;
         ";

It works only if I exec one single command. When I run multiple CREATE / INSERT / DROP ... commands it doesn't work. For sure there's a mistake with the syntax maybe ; and ,.

A: mysql_query() doesn't support multiple statements in the same call.
http://php.net/manual/en/function.mysql-query.php

mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified link_identifier.

A: You're problem doesn't comes from the SQL (well, I didn't checked it properly to be honest), but from mysql_query (assuming you're using it) : it does't allow multiple request.
http://php.net/manual/fr/function.mysql-query.php

A: As others have stated, the mysql_query() function doesn't support multiple queries in a single call.
On a somewhat related note, if you are able you should look into using mysql_i or PDO in place of the old mysql_*() functions, which are inferior for too many reasons to list here.
http://php.net/manual/en/book.mysqli.php
http://php.net/manual/en/book.pdo.php


text:
Q: Working of Scriptlets in jsp I am working on the maintenance of old project that uses scriptlets in JSP (I know it's not good practice but cann't help it ). The JSP Page contains more than one scriptlets(<% %>) -
 1. Are these scriptlets processed before bodyonload or before the DOM loads
 2. whether the order of execution of scriptlets will be from top to bottom.
 3. whether scriptlets runs before the script gets loaded
Thanks in advance !
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page language="java" contentType="text/html; charset=euc-kr"
    pageEncoding="euc-kr" %>

<meta http-equiv="Content-Type" content="text/html; charset=euc-kr">
<title></title>

<%
    String ctxPath = request.getContextPath();
    //get goods_name, cus_name from DB
    String goods_name = "»ç°ú 5kg";
    String cus_name = "È«±æµ¿";

    String ord_num = request.getParameter("ord_num");
    String carrier_code = request.getParameter("carrier_code");
    String carrier_codeOri = request.getParameter("carrier_codeOri");
    String prodClass = request.getParameter("prodClass");
    String linenumber = request.getParameter("linenumber") == null
                        || "".equals(request.getParameter("linenumber"))
                        ? "0" : request.getParameter("linenumber");
    String orddate = request.getParameter("orddate");
    String ordStatus = request.getParameter("ordStatus");
    String OrderTypeItem = request.getParameter("OrderTypeItem");
    String venderId = request.getParameter("venderId");
    String callcenter = request.getParameter("callcenter")== null ? "" : request.getParameter("callcenter");
    String Invoice_Num = request.getParameter("invoice_num")== null ? "" : request.getParameter("invoice_num");
    String InvociesNum = Invoice_Num;
    String agent = request.getParameter("agent")== null ? "" : request.getParameter("agent");

    String strB2BI_FLAG = "";

    //change hanjin furniture express to hanjin express
    if("HF".equals(agent)){
        agent = "HJ";
    }

%>

<%
   String pageUrl = "";    // connection page
   String scriptStr = "";  // call add on script function

   // # if 1
    if(InvociesNum != null && !InvociesNum.equals("")) {  // if has invoice number
                // #  if 2
                    if( "HJ".equals(agent)) {
                        pageUrl = ctxPath+"/jsp/jseig_viewGoods.jsp";

                    } else if ("DH".equals(agent) || "DZ".equals(agent) || "CV".equals(agentd)) {
                        pageUrl = ctxPath+"/jsp/jseig_viewGoodsT.jsp";

                    // hyundai, CJHTH  , CJGLS  , logen
                    } else if("HD".equals(agent) || "HT".equals(agent) || "CJ".equals(agent) || "KG".equals(agent)) {
                        pageUrl = ctxPath+"/jsp/jseig_viewGoodsTra.jsp";

                    // KGB express, yellow cap, dongbu, post office ...
                    } else if( "KL".equals(agent) || "AJ".equals(agent) || "KT".equals(agent) || "KR".equals(agent)
                            || "EP".equals(agent) || "ER".equals(agent) || "YC".equals(agent) || "TR".equals(agent)
                            || "SG".equals(agent) || "FA".equals(agent) || "ND".equals(agent) || "IN".equals(agent)
                            || "DS".equals(agent) || "CI".equals(agent) || "IY".equals(agent) || "KD".equals(agent) ) {
                        pageUrl = ctxPath+"/jsp/jseig_viewGoodsTrackingPHSC2.jsp";

                    } else if("DM".equals(agent)) { // dongyang magic
                        pageUrl = "http://www.tymg.co.kr/scripts/wgate/zs84a/!?VBKD-BSTKD_M="+ ord_num+";
                        scriptStr ="window.resizeTo(626,580);";

                    }else if("WW".equals(agent)) { //wizwid
                        pageUrl ="http://www.wizwid.com/CSW/handler/wizwid/kr/PopupDeliveryStatus-Start?JID=012861&JOrderID="+ord_num;
                        scriptStr  = "window.resizeTo(650,640);";

                    } else {
                        if("3100".equals(carrier_codeOri) && ("A01".equals(prodClass) || "A03".equals(prodClass) || "A05".equals(prodClass) || "A07".equals(prodClass) || "A11".equals(prodClass) || "A25".equals(prodClass))) {

                                scriptStr ="window.resizeTo(626,580);";
                                scriptStr += "document.location.replace('"+ctxPath+"/jsp/jseig_viewInstallGoodsInfo.jsp?returnOrdNum="+ord_num+"')";
                        } else {
                                scriptStr ="document.location.replace('"+ctxPath+"/jsp/viewMyBuy_popup4.jsp')";
                        }
                    }  // # if 2 END

        } else {  // have not invoice number
            if ("DM".equals(agent)){    //dongyang magic
                pageUrl ="http://www.tymg.co.kr/scripts/wgate/zs84a/!?VBKD-BSTKD_M="+ ord_num +"&ITSID=500784&ITSPW=4725";
            }else{
                if("3100".equals(carrier_codeOri) && ("A01".equals(prodClass) || "A03".equals(prodClass) || "A05".equals(prodClass) || "A07".equals(prodClass) || "A11".equals(prodClass) || "A25".equals(prodClass))) {
                    scriptStr = "document.location.replace('"+ctxPath+"/jsp/jseig_viewInstallGoodsInfo.jsp?returnOrdNum="+ord_num+"')";
                } else {
                    scriptStr = "document.location.replace('"+ctxPath+"/jsp/viewMyBuy_popup4.jsp')";
                }
            } // end if from DM
        } // # if 1 END
%>

<form name="invoiceForm" method="post">
  <input type="hidden" name="invoiceNum" value="<%= InvociesNum %>">
  <input type="hidden" name="invoice_num" value="<%= InvociesNum %>">
  <input type="hidden" name="ord_num" value="<%= ord_num %>">
  <input type="hidden" name="goods_name" value="<%= goods_name %>">
  <input type="hidden" name="cus_name" value="<%= cus_name %>">
  <input type="hidden" name="agent" value="<%= agent %>">
  <input type="hidden" name="reqFlag" value="Y">
  <input type="hidden" name="ordNum" value="<%= ord_num %>">
  <input type="hidden" name="lineNum" value="<%= linenumber %>">
<%
  session.setAttribute("callcenter", callcenter);
%>
</form>

ó¸®ÁßÀÔ´Ï´Ù. Àá½Ã¸¸ ±â´Ù·Á fgfg.

A: The scriplets are processed long before anything happens at the browser. They're a server-side feature, and no trace of them (well, no explicit trace) is left once the content reaches the browser. Order of execution is top to bottom, but Java code in the scriptlets can include control flow directives.


text:
Q: python - tkinter print from text box to screen In tkinter, I am trying to print the text entry from text box to screen every time I click the button "click"
This is my code which is working fine
from tkinter import *
def get(s):
        print(s.get())
win=Tk()
s=StringVar()
button=Button(win,text='click',command=lambda:get(s)).grid(row=1)
ent=Entry(win,textvariable=s).grid()

But when I do the same from new window, it is not working.
This is the code that doesn't work
from tkinter import *
def get(s):
        print(s.get())
def newwin():
    win=Tk()
    s=StringVar()
    button=Button(win,text='click',command=lambda:get(s)).grid(row=1)
    ent=Entry(win,textvariable=s).grid()
root=Tk()
but=Button(root,text='New',command=newwin).grid()

Everytime I click the 'click' button, I see a Blank line...
But I want to see the output just like the previous case.
Thanks in Advance !!

A: Change
def newwin():
    win=Tk()
...

to
def newwin():
    win=Toplevel(root)
    ...

Edit (clarification):
Your code would also run if you change
 def newwin():
    win=Tk()
    s=StringVar()
    ...

to
def newwin():
    win=Tk()
    s=StringVar(win)
    ...

but you shouldn't run multiple Tk() instances. See a good explanation here
Edit:
As for restricting selection of old window as asked by OP in a comment, I suggested to add a line to newwin():
def newwin():
    win=Tk(Toplevel(root))
    s=StringVar()
    button=Button(win,text='click',command=lambda:get(s)).grid(row=1)
    ent=Entry(win,textvariable=s).grid()
    win.grab_set() # win will catch all events, until you close it
                   # so user cannot interact with root window widgets
    # root.widthdraw() # alternative approach hides root window
                       # until Toplevel closes

root=Tk()
but=Button(root,text='New',command=newwin).grid()

Edit:
(further enhancement with code rewrite. I think I already answered the OP question but the comments with additional questions can be confusing. Please try to ask a single question at a time in order for you to select the best answer for that question)
Now I just rewrote the thing to look like a more coehrent answer. Look that using grid or pack is not relevant here. I hope you find it educational. Notice the different imports. You can import differently, but this way you do not import all the tkinter module names. ttk widgets are just modern versions of the classic ones. I subclassed Toplevel, assured parent __init__ is called and kept the new window related things together in that class. Note also the use of grab_set and the event callback for when the child toplevel loses focus. This way root window never regains focus unless you close the child. So no window select. This is adapted from selected answer here
Note also that I do not keep any reference to the newly created window. If you need so, you have to adapt (maybe store the result of MyWinddow(root) in a global var)
import tkinter as tk
from tkinter import Tk, ttk

class MyWindow(tk.Toplevel):
    def __init__(self, parent, *kw):
        super().__init__(parent, *kw)
        self.title('New Toplevel Window')
        self.myvar = tk.StringVar()
        self.button = ttk.Button(self, text='Print myvar',
            command=self.print_myvar)
        self.entry = ttk.Entry(self, textvariable=self.myvar)
        self.button.pack(pady=5)
        self.entry.pack(padx=50, pady=5)
        self.grab_set() # capture all the events
        self.bind('<FocusOut>', self.dont_let_focus_go) # cannot focus root

    def print_myvar(self):
        print(self.myvar.get())

    def dont_let_focus_go(self, event=None):
        self.focus_force()

def new_window():
    MyWindow(root)

root = Tk()
root.title('My Application Root Window')

button = ttk.Button(root, text='New Window', command=new_window)
button.pack(padx=50, pady=5)

root.mainloop()


text:
Q: register Google Analytics using C# I am trying to get data from Google Analytics using their api.
I have found this great post about doing it with C#
The thing is when I use its example I can get data from Analytics only if I am already logged on to Google with my business user/pass, otherwise it will direct me to the login page.
What I want is to prevent my marketing personal from knowing the user/pass info, and I don't want them to view all business related data in  Analytics.
I want to let them get the data from my admin site without exposing the business Google account even if they are currently logged on with their private gmail or whatever google service their using at the moment.
Hope I was clear enough.

A: Why don't you just add those users to Google Analytics? They can be given a restricted access.
http://support.google.com/analytics/bin/answer.py?hl=en&answer=1699665
http://support.google.com/analytics/bin/answer.py?hl=en&answer=1009702


text:
Q: In oracle, can I associate a default Schema with my USER ID where SCHEMA <> USERID? I would like to connect to an Oracle database with UserId "MY_SCHEMA" and then be able to perform queries where the table name was not qualified with the schema name:
SELECT * FROM TABLE1

When executing SQL, I would like my unqualified queries to go against a different schema other than my own. In other words, I would like this to be equivalent to
SELECT * FROM SCHEMA_OTHER.TABLE1

instead of
SELECT * FROM MY_SCHEMA.TABLE1

I know it seems a little weird and so I expect that this is not possible.
I do not have any sort of admin rights to the database to see if I can associate a default schema with a login.

A: After you login, you can run the following:
ALTER SESSION SET CURRENT_SCHEMA=schema_other;

If you really want this to happen automatically, you can create a system trigger for the logon action that looks for your username and uses execute immediate to run the alter session command:
CREATE OR REPLACE TRIGGER my_schema_logon
   AFTER LOGON
   ON DATABASE
BEGIN
   IF SYS_CONTEXT ('USERENV', 'CURRENT_USER') = 'MY_SCHEMA' THEN
      EXECUTE IMMEDIATE 'ALTER SESSION SET CURRENT_SCHEMA=schema_other';
   END IF;
END my_schema_logon;
/


text:
Q: Google Spreadsheet V3 API with service account and OAuth2 in Java I have some legacy Java code which uses the V2 Google spreadsheet API to read values from one Google spreadsheet, retrieve some DB values and do some calcs, and update a second Google spreadsheet.  With the imminent cutover to OAuth2 authentication only, I need to migrate to the V3 API.
This process gets run from the command line, so the assumption would be that using a service account and a P12 key would be the way forward -- and indeed, we are doing that for using the Google Calendar service.
But it doesn't seem like there is support in place for the spreadsheet service for service accounts.  I've seen older references (~2 years ago) to Google Data APIs supporting OAuth2 service accounts through the setOAuth2Credentials() method, but that does not seem to be true today.
Has anyone had any luck in getting the V3 spreadsheet API working with an OAuth2 service account in Java, or can point me to recent (~within the last year) code samples?


text:
Q: Redirect url withouth '/' in Shopware6 How to be solved in a professional way without '/' in url redirecting to page with slash. Currently Shopware 6 has 404 error when is link without slash. I resolved it once in kernel event - response by checking uri path and add slash if uri didn't have it. I do not know if it was the right way.
This is my part of code which I tried to solve a problem:
if (str_ends_with($path, '/') && !$event->getResponse() instanceof StorefrontResponse) {
    $response = new RedirectResponse($this->router->generate('frontend.home.page'), 301);
    $event->setResponse($response);

   return;
}

A: KernelEvents::REQUEST should fit. Because you might forward the request.
But, there is also a great plugin solving issues with slashes: https://store.shopware.com/en/kielc49617690410/trailing-slash-redirect.html


text:
Q: insert millions of records into two mysql tables I have 5 tables with me each with millions of lines in each table.
Each table has same format i.e. email, ip address, location. A single email address can be present in any of the five tables or in all of the 5 tables. And there are two other tables namely User_ip and User_location.
I want to store unique ip adress of each email address in User_ip table, and distinct location of each email address in user_location table.
Currently,  I have been following this procedure but this is taking alot of time. Is there any other solution or method???
Statement stmt = connection.createStatement();

        stmt.executeUpdate("insert into temp(email,ip,location) select email,ip,location from Apr_web group by email,ip");
        stmt.executeUpdate("insert into temp(email,ip,location) select email,ip,location from Apr_gov group by email,ip");
        stmt.executeUpdate("insert into temp(email,ip,location) select email,ip,location from Apr_mail group by email,ip");
        stmt.executeUpdate("insert into temp(email,ip,location) select email,ip,location from Apr_pop group by email,ip");
        stmt.executeUpdate("insert into temp(email,ip,location) select email,ip,location from Apr_imap group by email,ip");

stmt1 = connection.createStatement();
stmt1.executeQuery("select distinct email from temp");
        ResultSet rs = stmt1.getResultSet();
        while(rs.next()){
 Statement stmt2 = connection.createStatement();
                stmt2.executeQuery("select distinct substring_index(ip,'.',2) from temp where email='"+email+"'");
                ResultSet rs2 = stmt2.getResultSet();
                while(rs2.next()`enter code here`){
                    ip=rs2.getString(1);

                    Statement stmt3 = connection.createStatement();
                    Statement stmt4 = connection.createStatement();
                    stmt3.executeQuery("select * from user_ip where uid='"+email+"' and ip='"+ip+"'");
                    ResultSet rs3 = stmt3.getResultSet();
                    if(rs3.next()){
                        System.out.println("THE ROW ALREADY EXISTS IN IP TABLE");
                    }
                    else{
                        stmt4.executeUpdate("insert into user_ip(uid,ip) values('"+email+"','"+ip+"')");
                        System.out.println("ROW INSERTED IN USER_IP");
                    }

                }

 Statement stmt5 = connection.createStatement();
                stmt5.executeQuery("select distinct location from temp where   email='"+email+"' and location !='no information found'");
                ResultSet rs4 = stmt5.getResultSet();
                while(rs4.next()){
                    location = rs4.getString(1);
                    //Statement stmt6 = connection.createStatement();
                    //Statement stmt7 = connection.createStatement();

                    pst1 = connection.prepareStatement("select * from user_location where uid=? and location=?");
                    pst1.setString(1, email);
                    pst1.setString(2, location);

                    ResultSet rs5 = pst1.executeQuery();
                    if(rs5.next()){
                        System.out.println("THE ROW ALREADY EXISTS IN USER_LOCATION");
                    }
                    else{
                        pst2 = connection.prepareStatement("insert into user_location(uid,location) values(?,?)");
                        pst2.setString(1,email);
                        pst2.setString(2,location);
                        pst2.executeUpdate();

                        System.out.println("ROW INSERTED IN USER_LOCATION");
                    }
                }
}

A: Have you turned auto-commit off? If not, when you create the connection turn off auto-commit by using the command:
Add SET autocommit=0; to the end of your connection String
Then at the end, when all items are added use the command:
COMMIT;
or is you want to discard all changes (if there was an error):
ROLLBACK;
These commands are sent to the MySQL db as a query to commit or rollback the data. This should allow you to put a lot of items into a table quicker.
Check the documentation out for more details

A: Can't you just do this in 2 SQL statements. Something like the following:-
INSERT IGNORE INTO user_ip (uid,ip)
SELECT DISTINCT email,SUBSTRING_INDEX(ip,'.',2) FROM Apr_web
UNION
SELECT DISTINCT email,SUBSTRING_INDEX(ip,'.',2) FROM Apr_gov
UNION
SELECT DISTINCT email,SUBSTRING_INDEX(ip,'.',2) FROM Apr_mail
UNION
SELECT DISTINCT email,SUBSTRING_INDEX(ip,'.',2) FROM Apr_pop
UNION
SELECT DISTINCT email,SUBSTRING_INDEX(ip,'.',2) FROM Apr_imap

INSERT IGNORE INTO user_location(uid,location)
SELECT DISTINCT email,location FROM Apr_web
UNION
SELECT DISTINCT email,location FROM Apr_gov
UNION
SELECT DISTINCT email,location FROM Apr_mail
UNION
SELECT DISTINCT email,location FROM Apr_pop
UNION
SELECT DISTINCT email,location FROM Apr_imap

A: Will a solution like
stmt.executeUpdate(
  "INSERT INTO user_ip(uid,ip) "+
  "SELECT DISTINCT email,ip FROM temp "+
  "   LEFT JOIN user_id ON "+
  "      (temp.email = user_ip.email AND temp.ip = user_ip.ip) "+
  "    WHERE user_ip.email IS NULL");

work for you?
Explanation: Find the unique pairs of (email, ip) that are present in the temporary table but not already in table user_ip, then add them to user_ip.


text:
Q: display map_canvas div oncheck box i want to show a google maps canvas according to a checkbox selection, but when i click on it i can't see the map fine, it shows the map incorrectly and the 'map functionality' isn't working either..... css link sets de map_canvas div size, if i remove this show function map works perfect.
Here is the code:
  <html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">

<link href="https://developers.google.com/maps/documentation/javascript/examples/default.css" rel="stylesheet">
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=drawing">   </script>

<script type="text/javascript" src="../jquery-1.2.1.pack.js"></script>

<script type="text/javascript">

function lookup(inputString) {

    if(inputString.length == 0) {

        // Hide the suggestion box.

        $('#suggestions').hide();

    } else {

        $.post("do_search.php", {queryString: ""+inputString+""},
function(data){

            if(data.length >0) {
                        alert(data);
                $('#suggestions').show();
                $('#autoSuggestionsList').html(data);
            }
        });
}

} // lookup

//alert(queryString);

</script>

<script>
  function initialize() {
    var mapOptions = {
       center: new google.maps.LatLng(-35.48833, -62.97528),
      zoom: 7,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map = new google.maps.Map(document.getElementById('map_canvas'),
      mapOptions);

    var drawingManager = new google.maps.drawing.DrawingManager({
      drawingMode: google.maps.drawing.OverlayType.MARKER,
      drawingControl: true,
      drawingControlOptions: {
        position: google.maps.ControlPosition.TOP_CENTER,
        drawingModes: [
          google.maps.drawing.OverlayType.POLYGON
        ]
      },
      markerOptions: {
        icon: 'images/beachflag.png'
      },
      circleOptions: {
        fillColor: '#ffff00',
        fillOpacity: 1,
        strokeWeight: 5,
        clickable: false,
        editable: true,
        zIndex: 1
      }
    });
    drawingManager.setMap(map);
    google.maps.event.addListener(drawingManager, 'polygoncomplete',     function(polygon) {
        //alert('Poligono cerrado');

        var coordinates = "";

        var path = polygon.getPath();

        for (var i = 0; i < path.getLength(); i++)
            coordinates += path.getAt(i) + ",";

        //alert(coordinates);
        lookup(coordinates);

        drawingManager.drawingControlOptions.drawingModes = [];
        drawingManager.drawingControl = false;
        drawingManager.setMap(map);

    });
  }

  google.maps.event.addDomListener(window, 'load', initialize);
 </script>
<script>
function fnchecked(blnchecked)
{
if(blnchecked)
{
document.getElementById("map_canvas").style.display = "";
}
else
{
document.getElementById("map_canvas").style.display = "none";
}

}
</script>
</head>
<body>
<input type="checkbox" name="fldcheckbox" id="fldcheckbox"   onclick="fnchecked(this.checked);"/>mapa
<div id="map_canvas" style="display:none;">
    </div>
</body>

Any idea?

A:       function initialize() {
        var mapOptions = {
           center: new google.maps.LatLng(-35.48833, -62.97528),
          zoom: 7,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        var map = new google.maps.Map(document.getElementById('map_canvas'),
          mapOptions);

        var drawingManager = new google.maps.drawing.DrawingManager({
          drawingMode: google.maps.drawing.OverlayType.MARKER,
          drawingControl: true,
          drawingControlOptions: {
            position: google.maps.ControlPosition.TOP_CENTER,
            drawingModes: [
              google.maps.drawing.OverlayType.POLYGON
            ]
          },
          markerOptions: {
            icon: 'images/beachflag.png'
          },
          circleOptions: {
            fillColor: '#ffff00',
            fillOpacity: 1,
            strokeWeight: 5,
            clickable: true,
            editable: true,
            zIndex: 1
          }
        });
        drawingManager.setMap(map);
        google.maps.event.addListener(drawingManager, 'polygoncomplete',
 function(polygon) {
            //alert('Poligono cerrado');

            var coordinates = "";

            var path = polygon.getPath();

            for (var i = 0; i < path.getLength(); i++)
                coordinates += path.getAt(i) + ",";

            //alert(coordinates);
            lookup(coordinates);

            drawingManager.drawingControlOptions.drawingModes = [];
            drawingManager.drawingControl = false;
            drawingManager.setMap(map);

        });
      }

     </script>
    <script>
    function fnchecked(blnchecked)
    {
    if(blnchecked)
    {
        document.getElementById("map_canvas").style.display = "block";
    initialize();
    }
    else
    {
    document.getElementById("map_canvas").style.display = "none";
    }

    }
    </script>

change your code like this


text:
Q: Do all diffs get copied to source branch from destination branch during git merge? I have been trying to get all the diffs from a dst branch to a src branch. I usually follow the following workflow.
git checkout dst (switch to dst branch)
git pull dst     (fetch and merge changes on remote dst to local dst)
git checkout src (switch to src branch)
git merge dst    (pull all diffs from dst to src?)
[optionally if merge conflicts occur, I resolve merge conflicts and do]
git commit

However, after merge, I am seeing that not all diffs are copied to my src branch. For instance  git diff src:somefile dst:somefile shows additions in somefile between the src and dst, however these changes are not copied over to src which I am expecting to happen after merge.
Is there something fundamentally wrong in the way I am thinking about merge? How do I get all the diffs (additions and deletions) from dst to src branch.

A:
Is there something fundamentally wrong in the way I am thinking about merge?

Yes:

... git diff src:somefile dst:somefile ...

This isn't what merge does.  Merging a branch does not mean "make my files the same as theirs".
The commit graph
Let's start with a bit of commit-graph drawing:
... <- B <- C <- D   <-- branch

Here, the uppercase letters stand in for a commit ID, i.e., one of those big ugly 40-character SHA-1 IDs like f931ca0....  Each commit records a source tree (this is how, for instance, you can use <id>:path to see that file's contents as of that commit ID).  It also records some parent commit ID(s): usually just one ID, but sometimes more than one (a "merge" commit) and rarely zero parent IDs (a "root" commit).
The branch is just the name of one of your branches, and it contains commit-ID D, i.e., the branch name "points to" the tip-most commit D on that branch.  Commit D points back to C, which points back to B, and so on.
A graph becomes "branch-y" or "branched"—this term unfortunately collides with the same term we use to talk about the name of a branch—when several different commits point to the same parent.  Remember that the arrows here all point left-ish, even if they point up-and-left or down-and-left; and since text-style graphs don't have room for arrows, we'll just draw a line like - or \ or / here:
... B - C - D   <-- br1
      \
        E - F   <-- br2

Here the tip of branch br1 is commit D, and the tip of branch br2 is commit F.  You can ask git for the actual ID, the concrete 40-character thing, using git rev-parse:
$ git rev-parse br1
e59f6c2d348d465e3147b11098126d3965686098

for instance.  Again, we say that br1 "points to" commit D, which points back to C, which points back to B, and so on.  Meanwhile br2 points to F which points to E which points back to B.
The commit that any given branch-name points to is the "tip commit" of that branch.  When you add a new commit to a branch, git does this by making the new commit store the previous tip's ID as its parent ID, and once the new commit is finalized and safely in the repository, changing the ID stored in the branch-name.  That is, if you add a new commit to br1, the new commit G will point back to D, and git will make br1 point to G:
... B - C - D - G  <-- br1
      \
        E - F   <-- br2

No matter how many new tip commits we make over time, commit B remains especially interesting.  In graph theory terms, the concept here is "reachability": commit B is (always) reachable from both branch-tips.
Merge
So, here's what git merge does.  You give it two branch tip IDs—one of these is the branch you're on now, the other is the one you name—and it:

*

*identifies the nearest commit reachable from both branch tips (this is the "merge base");

*does a diff from the merge-base to the current-branch tip;

*does a diff from the merge-base to the other tip;

*combines these two diffs to see where "both sides" made the same changes;

*applies the changes found in step 3, without re-applying the combined changes found in step 4; and

*if all goes well, makes a new commit with two parents, those two parents being both branch-tips.

Conflicts occur wherever the changes found in steps 2 and 3 affect the same region of the same file, but are not exactly the same (hence can't be subtracted away via step 4).  If conflicts occur, git makes you resolve them; when you do your final git commit this still makes the same kind of "merge commit".
Now, suppose that somewhere along the way in the B-C-D-G line, someone modified the path README.txt to include an exclamation point in the first line.  Meanwhile in B-E-F line, nobody did this to README.txt.  The final merge commit will retain the change made here, but if you compare br1:README to br2:README there will be differences: the first line in br2 won't have the exclamation point.  That's because the changes being merged-in (base-to-br2) don't change this; the changes being retained (base-to-br1) do.  We don't want base-to-br1 changes to get removed, we only want changes that aren't already present (have not been made on "both side") to be added.
In any case, let's draw in the final merge commit H:
... B - C - D - G - H  <-- br1
      \           /
        E ----- F      <-- br2

Now br1:README has the ! but br2:README doesn't.
In short, there's no reason to expect, after a merge, any two files to match in the new branch-tips.  If all the files had to match exactly, you'd wipe out all the work on br1, replacing it with only the work on br2.


text:
Q: Unable to get menu item using querySelectorAll I have the following code and tried getting the item "Menu 8", but here I am getting all menus, not just menu 8, I need to get menu8 and change the class name. What goes wrong with my code?
check here :
https://stackblitz.com/edit/queryselector-x4jzrs?file=index.js,index.html
Check the console for output
var input = document.querySelector('input');
var p = document.querySelector('p.description');
var btn = document.querySelector('button');
const xLinks = [];

document.querySelectorAll('leds-navigation-list > ul').forEach(x => xLinks.push(x));
btn.addEventListener('click',()=>{
  p.textContent = xLinks;
})

console.log("data21", xLinks);

This is the HTML
// Import stylesheets
import './style.css';

// Write Javascript code!
const appDiv = document.getElementById('app');
appDiv.innerHTML = `

Menu 1

<leds-navigation-list _ngcontent-pji-c509="" secondlist="" level="second" _nghost-pji-c444="" ng-reflect-level="second" class="ng-star-inserted">

</leds-navigation-list>

Menu 2

<leds-navigation-list _ngcontent-pji-c509="" secondlist="" level="second" _nghost-pji-c444="" ng-reflect-level="second" class="ng-star-inserted">

</leds-navigation-list>

Menu 3

<leds-navigation-list _ngcontent-pji-c509="" secondlist="" level="second" _nghost-pji-c444="" ng-reflect-level="second" class="ng-star-inserted">

</leds-navigation-list>

Menu 4

<leds-navigation-list _ngcontent-pji-c509="" secondlist="" level="second" _nghost-pji-c444="" ng-reflect-level="second" class="ng-star-inserted">

</leds-navigation-list>

Menu 5

<leds-navigation-list _ngcontent-pji-c509="" secondlist="" level="second" _nghost-pji-c444="" ng-reflect-level="second" class="ng-star-inserted">

</leds-navigation-list>

Menu 6

<leds-navigation-list _ngcontent-pji-c509="" secondlist="" level="second" _nghost-pji-c444="" ng-reflect-level="second" class="ng-star-inserted">

</leds-navigation-list>

Menu 7

<leds-navigation-list _ngcontent-pji-c509="" secondlist="" level="second" _nghost-pji-c444="" ng-reflect-level="second" class="ng-star-inserted">

</leds-navigation-list>

Menu 8

<leds-navigation-list _ngcontent-pji-c509="" secondlist="" level="second" _nghost-pji-c444="" ng-reflect-level="second" class="ng-star-inserted">

Sub Menu 1

Sub Menu 2

Sub Menu 3

Sub Menu 4

</leds-navigation-list>

Menu 9

<leds-navigation-list _ngcontent-pji-c509="" secondlist="" level="second" _nghost-pji-c444="" ng-reflect-level="second" class="ng-star-inserted">

</leds-navigation-list>

Menu 10

<leds-navigation-list _ngcontent-pji-c509="" secondlist="" level="second" _nghost-pji-c444="" ng-reflect-level="second" class="ng-star-inserted">

</leds-navigation-list>

Menu 11

<leds-navigation-list _ngcontent-pji-c509="" secondlist="" level="second" _nghost-pji-c444="" ng-reflect-level="second" class="ng-star-inserted">

</leds-navigation-list>

`;

var input = document.querySelector('input');
var p = document.querySelector('p.description');
var btn = document.querySelector('button');
const xLinks = [];

document.querySelectorAll('leds-navigation-list > ul').forEach(x => xLinks.push(x));
btn.addEventListener('click',()=>{
  p.textContent = xLinks;
})

console.log("data21", xLinks);

Once I get the item "Menu 8" I need to change the class from

le-c-nav-list le-c-nav-list--pin le-c-nav-list--multimenu
le-c-nav-list-sec js-nav-list-sec

to

le-c-nav-list le-c-nav-list--pin le-c-nav-list--multimenu
le-c-nav-list-sec js-nav-list-sec hide

A: As querySelectorAll() returns an NodeList, you should have something like this.
document.querySelectorAll('leds-navigation-list > ul')[7];

A: This works !
document.querySelectorAll('Li > a > DIV > DIV')


text:
Q: Trouble with the combat sections in Heavy Rain In the odd occasion I find myself having to get involved in a fight I always end up getting my ass handed too me. I find switching from the normal motion and action controls to responding to fast quick time prompts very tricky.
How can I react better? Is there any sort of pattern to the type of motions you're asked to do?

A: I've noticed that in a lot of scenes, following the correct prompts or close to it would still get you slapped pretty badly. A lot of the fights look "almost lost" but then you get one saving grace at the end (the doc fight is a good example, I actually restarted twice not realizing hat it wasn't over).
I think that it only hurt me in the last fight.
Not sure if there's a way to react faster-  except replay replay replay. If you play on easy, the prompts are almost always the same.

A: Apart from what has been mentioned, there is also a mode where you specify that you are new to games "Easy - I play video games occasionally" and it gives you more time per action and is a little bit more lenient with accidental buttons.
For the sake of completeness, I felt that the game is significantly harder and tiring with the motion controller, the actions are closer to what you would do in real life but it takes getting used to. So if you want to go that route then you have to try try again.

A: "Is there any sort of pattern to the type of motions you're asked to do?"
Not really. The quick-time actions are meant to approximate the actions of the characters on screen.
Not being very good at the fight sequences isn't really a problem though! The game continues no matter what the result of the fight is. So do the best you can, then sit back and let the story continue.


text:
Q: What is the best way to create a search facility for static content in Symfony? I've built a static website using Symfony 2.6, it has been translated into 8 different languages and includes several forms.
It now requires a search facility, what is the best way to achieve this?

A: Search facility can be gained using:

*

*Special database requests, in mysql SELECT * FROM article WHERE article.body LIKE '%searched_query%'

*Full text search can be achieved using tools like:

*

*Sphinx Search

*Apache Solr
But in both cases you should save your content in database or other files.

*In your case as workaround I suggest to crawl your own site and return links from sites where you found the searched text sort of this stuff
use Symfony\Component\DomCrawler\Crawler;

class InternalCrawler {

    private $crawler;
    private $textToSearch;
    private $matchedUrls;

    public function __construct($textToSearch)
    {
        $this->textToSearch = $textToSearch;
    }

    protected function requestUrl($url)
    {
        //curl the url to crawl
        //...

        return $html;
    }

    protected function getUrlsToCrawl()
    {
        return array(
            'url-to-homepage',
            'url-to-an-article-page',
            ...
        );
    }

    protected function match($url, $html)
    {
        $this->crawler = new Crawler($html);
        $textExists = $this->crawler->filter("html:contains('{$this->textToSearch}')")->count();
        if ($textExists) {
            $this->matchedUrls[] = $url;
        }
    }

    public function getMatchedUrls()
    {
         foreach ($this->getUrlsToCrawl() as $url) {
             $html = $this->requestUrl($url);
             $this->match($url, $html);
         }

         return $this->matchedUrls;
    }
}

As a result you will have the list of urls that matched your searched text.


text:
Q: Where is the GPU? Installed Debian 7.5.0 on Asus X550LD-XX028 (http://www.flipkart.com/asus-x550ld-xx082d-notebook-4th-gen-ci7-8gb-1tb-free-dos/p/itmdvyg4krwqgaes), with Nvidia GeForce 820M. The nvidia-detect (https://packages.debian.org/wheezy/nvidia-detect) command didn't detect any NVIDIA GPU.
Can someone please explain what is happening ?


text:
Q: How to get byte array from list? I am adding some data to super list and trying to convert that list to byte[], but getting class cast exception. Below is my code.
public byte[] getBytes () {
        Byte[] arrayByte = (Byte[])super.toArray();
        byte [] bytes = Utility.toPrimitives(arrayByte);
        return bytes;
    }

Error Log
03-13 11:56:27.480: E/AndroidRuntime(10471): Caused by: java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.lang.Byte[]

A: Your toArray call needs to tell the list what kind of array to create:
Byte[] arrayByte = super.toArray(new Byte[size()]);

That can't otherwise be inferred at execution time, due to type erasure - the list doesn't "know" that it's a List<Byte>.
Now because you're using a method with a declaration of:
<T> T[] toArray(T[] a)

you don't need to cast the result.
Note that you don't have to create an array of the right size - the method will create a new one if it needs to - but specifying the right size to start with avoids creating one array pointlessly, so it's slightly more efficient.


text:
Q: Connect PHP to SQL Server on windows I am trying to connect to a SQL Server (MSSQL) database with PHP. I activated the DBO plugin and am trying to use it, but when I define the object and run the code I get the error: Connection failed: could not find driver
.  As you can see from my code, I have verified that the dbo driver is loaded.
 I downloaded the sqlsrv driver linked to in one of the answers but I still cannot connect.  What am I missing? (the two files index.php and submit.php are in the same directory and that is the whole project)  ((I am on a Windows computer, but this may or may not be relevant))
index.php:

  <form class="my-form" action="submit.php">
      <input type="text" name="field" />
      <input type="submit" value="Submit" />
  </form>

submit.php:

page loaded

<?php if (extension_loaded('pdo')) {
    echo 'pdo extension loaded by php';
} ?>

<?php
$myServer = "xxxxxxxxxxxxxxxx";
$myUser = "xxxxxxx";
$myPass = "xxxxxx";
$myDB = "xxxxxxxxxxxx";

$serverName = $myServer; //serverName\instanceName

// Since UID and PWD are not specified in the $connectionInfo array,
// The connection will be attempted using Windows Authentication.
$connectionInfo = array( "Database"=>$myDB, "UID"=>$myUser, "PWD"=>$myPass);
$conn = sqlsrv_connect( $serverName, $connectionInfo);

if( $conn ) {
     echo "Connection established.
";
}else{
     echo "Connection could not be established.
";
     die( print_r( sqlsrv_errors(), true));
}

?>

A: The mssql* extension has been removed in PHP 7.
https://www.php.net/manual/en/function.mssql-connect.php
You should consider PDO instead.
edit:
PDO for MSSQL requires the appropriate client libraries, which you will find here:
https://learn.microsoft.com/en-us/sql/connect/php/download-drivers-php-sql-server?view=sql-server-2017
Don't let yourself get confused by the version numbers (it's not the PHP version...) check out the description, some drivers are for specific MSSQL server versions only.
Also mind the examples:
https://learn.microsoft.com/en-us/sql/connect/php/download-drivers-php-sql-server?view=sql-server-2017


text:
Q: Network order query using powershell I have written a powershell script to query NIC binding order and the script will look NIC binding order in the format Vethernet,storage if this order is correct then it will print output in green color else it will print in yellow color.
Also I have added one more condition here, i.e if there is no storage NIC found in the binding order it should see Vethernet is the first in order and if the order correct,it should print as green or else it should be yellow.But there seems to be some problem with my script.
The first if condition line work perfect, but the second else if condition doesn't work well. I have tried changing the order , even after changing order it print the color as green.
Can anyone help me correcting this script ?
$results = Invoke-Command -ComputerName $ComputerName {(Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Linkage").Bind | ForEach-Object {
  $guid = ($_ -split '\\')[2]
  Get-WmiObject -Query "SELECT * FROM Win32_NetworkAdapter WHERE GUID='$guid'" |
    Select-Object -ExpandProperty NetConnectionID
}}

$adapteresult = $results -join","

if (($adapteresult.Contains('Storage') -and ($adapteresult -match 'vEthernet\s+\([^)]+\),storage')))
{
Add-Content $report "$adapteresult	"
}
elseif ($adapteresult -NotContains "Storage" -and ($adapteresult -match 'vEthernet\s+\([^)]+\),'))
{
Add-Content $report "$adapteresult	"
}
else
{
Add-Content $report "$adapteresult	"
}

A: To be more precise, you can check the with $Null
Just add the Condition with OR like :
if (($adapteresult -match 'vEthernet\s+\([^)]+\),storage') -or ($adapteresult -eq $null))

As per the update, Why to use multiple if else:
if( ($adapteresult -match 'vEthernet\s+\([^)]+\),storage') -or ($adapteresult -match 'vEthernet*\s+\([^)]+\),') )
{
Add-Content $report "$adapteresult	"
}
else
{
Add-Content $report "$adapteresult	"
}


text:
Q: How to connect a GAE app and a GCE app to the same datastore locally? I am running into an issue similar to this one. I have a GAE app and a GCE app that seem to work fine once in the cloud but I am having trouble getting my local environment working so that both of them access the same datastore.
I have setup the local datastore as described in the link above except my code looks like this (I had to build it this way in order to get it working in the cloud):
print("Connecting to datastore - " + datasetId);

// Get credentials form GCE if not local.
Credential computeEngineCredential = DatastoreHelper.getComputeEngineCredential();

if(computeEngineCredential != null)
{
    print("Compute Engine Credetianls are not null! Access token: " + computeEngineCredential.getAccessToken());
}

DatastoreOptions options = DatastoreHelper.getOptionsfromEnv().credential(DatastoreHelper.getComputeEngineCredential()).dataset(datasetId).build();

print("Connection Host: " + options.getHost());
print("Connection Dataset: " + options.getDataset());

datastore = DatastoreFactory.get().create(options);

When I run the GCE app locally and try to connect to the running GAE datastore I get the following (I have replaced the actual data set id with "myDatasetId" in the output below):

Connecting to datastore - "myDatasetId"
Connection Host: http://localhost:8888
Connection Dataset: "myDatasetId"
com.google.api.services.datastore.client.DatastoreFactory makeClient
WARNING: Not using any credentials
There was a problem running query: Error:
  runQuery  Error 404 Error
  404
      com.google.api.services.datastore.client.DatastoreException: Error 404 Error
  404
          at          com.google.api.services.datastore.client.RemoteRpc.makeException(RemoteRpc.java:114)
          at com.google.api.services.datastore.client.RemoteRpc.call(RemoteRpc.java:80)
          at com.google.api.services.datastore.client.Datastore.runQuery(Datastore.java:109)

My GAE console prints this out (I can access the admin console in the 8888 port just fine):

com.google.appengine.tools.development.AbstractModule startup
INFO: The admin console is running at http://localhost:8888/_ah/admin
com.google.appengine.tools.development.LocalResourceFileServlet doGet
WARNING: No file found for:
/datastore/v1beta2/datasets/"myDatasetId"/runQuery

I have verified the dataset ID in the GCE app and the GAE app match. I have been able to successfully run each app localy on their own and they both are able to properly connect to the local Datastore (this is while using the gcd.cmd tool for the GCE app). Based on the answer in the link above, it sounds like this is possible, am I doing something wrong?
Update
Not sure if this is related but I am getting the following error when starting up the GCD Tool:

SEVERE: Unable to load the App Engine dev agent. Security restrictions
  will not be completely emulated. java.lang.RuntimeException:
  Unexpected exception during cast.
          at com.google.apphosting.utils.clearcast.ClearCast$CasterImpl.cast(ClearCast.java:385)
          at com.google.apphosting.utils.clearcast.ClearCast.staticCast(ClearCast.java:252)
          at com.google.apphosting.utils.clearcast.ClearCast.staticCast(ClearCast.java:263)
          at com.google.appengine.tools.development.agent.AppEngineDevAgent.premain(AppEngineDevAgent.java:61)
          at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
          at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
          at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
          at java.lang.reflect.Method.invoke(Unknown Source)
          at sun.instrument.InstrumentationImpl.loadClassAndStartAgent(Unknown
  Source)
          at sun.instrument.InstrumentationImpl.loadClassAndCallPremain(Unknown
  Source) Caused by: java.lang.IllegalAccessException: Class
  com.google.apphosting.utils.clearcast.ClearCast$CasterImpl can not ac
  cess a member of class
  com.google.appengine.tools.development.agent.$Proxy0 with modifiers
  "public"
          at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
          at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(Unknown
  Source)
          at java.lang.reflect.AccessibleObject.checkAccess(Unknown Source)
          at java.lang.reflect.Constructor.newInstance(Unknown Source)
          at com.google.apphosting.utils.clearcast.ClearCast$CasterImpl.cast(ClearCast.java:383)
          ... 9 more

If this initialized properly, could I somehow connect my GAE App to the GCD Tool datastore? So confused.

A: There's no officially supported way to share Datastore data between the Java Development Server (dev_appserver.sh) and the local Cloud Datastore tool (gcd.sh).
However, if your app is written in Java, you may be able to use the workaround described here and point dev_appserver.sh to the data file generated by gcd.sh by specifying the -Ddatastore.backing_store=<project dir>/WEB-INF/appengine-generated/local_db.bin option.

A: Thanks for replying this was very useful. I was able to point my local GAE to the local_db.bin that the gcd tool uses through eclipse by providing the "-Ddatastore.backing_store" as a VM argument as you suggested.
However, they still seem to have a different views of the datastore. The admin viewer for the GAE app running on the default 8888 port only shows the data added by the GAE app, on the other hand, the gcd one running on the gcd tool port (8080) shows the data added by the GCE app.
I assumed this was just a visibility issue on the admin site so I tried to access the GAE data through my GCE app but the query is unsuccessful, it doesn't seem to find the Entity kind and thus returns no results. I was able to verify that once deployed GCE is able to access the data the GAE app wrote to the datastore with the same query, due to this I am assuming it is not a namespace issue but more of an issue on where the data is held. Even though they are both pointing to the same local_db.bin file it seems the data is still split somewhere.
Am I supposed to run the dev_appserver.cmd directly form the command line maybe? If so, How do I do this for an EAR project (currently on eclipse).


text:
Q: Proving an binomial identity with elementary means For $k<2n$:
$$\sum_{i=0}^k(-1)^{k-i}{2n-k+i\choose n}{k\choose i}={2n-k\choose n}$$
I can prove this is true by relating both sides to certain number-theoretic objects, but I think a proof relying solely on combinatorial methods should be possible. Any hints/tips?

A: It's an inclusion-exclusion calculation, counting the number of $n$-element subsets of $[2n-k]$ in two different ways. The righthand side is clearly that number.
For $i\in[k]$ let $\mathscr{A}_i$ be the set of $n$-element subsets of $[2n]$ that include $i$. If $\varnothing\ne I\subseteq[k]$,
$$\left|\,\bigcap_{i\in I}\mathscr{A}_i\,\right|=\binom{2n-|I|}n\;.$$
Thus,
$$\begin{align*}
\left|\,\bigcup_{i\in[k]}\mathscr{A}_i\,\right|&=\sum_{\varnothing\ne I\subseteq[k]}(-1)^{|I|+1}\left|\,\bigcap_{i\in I}\mathscr{A}_i\,\right|\\
&=\sum_{i=1}^k(-1)^{i+1}\binom{k}i\binom{2n-i}n\;,
\end{align*}$$
since there are $\binom{k}i$ subsets of $[k]$ of cardinality $i$. The $n$-element subsets of $[2n-k]$ are the $n$-element subsets of $[2n]$ that are not in $\bigcup_{i\in[k]}\mathscr{A}_i$, so there are
$$\begin{align*}
\binom{2n}n-\sum_{i=1}^k(-1)^{i+1}\binom{k}i\binom{2n-i}n&=\binom{2n}n+\sum_{i=1}^k(-1)^i\binom{k}i\binom{2n-i}n\\
&=\sum_{i=0}^k(-1)^i\binom{k}i\binom{2n-i}n\\
&=\sum_{i=0}^k(-1)^{k-i}\binom{k}{k-i}\binom{2n-(k-i)}n\\
&=\sum_{i=0}^k(-1)^{k-i}\binom{k}i\binom{2n-k+i}n\;.
\end{align*}$$


text:
Q: How to scale a sprite(2D) using a matrix I have a 2D tower defense game I'm making and I want my sprites to scale to the screen size. So someone suggested using a  matrix. So I tried to use one but I don't really know how to use it and how it works. So, how would I create a matrix and use it to scale 2D sprites in monogame. Thank you!

A: you can scale SpriteBatch using matrix, could be used to zoom in/out to affect whole screen.
ScalingFactor = new Vector3(widthScaling, heightScaling, 1);
Scale = Matrix.CreateScale(ScalingFactor);
spriteBatch.Begin(SpriteSortMode.Immediate, null, null, null, null,null, Scale);


text:
Q: Monte Carlo Simulation of Pi in simple java? I am trying to do the famous Monte Carlo simulation to estimate pi for my Java course.
Here is the Simulation:
 public class Darts
    {
    //"throwing" a dart
    public static boolean [] dartThrow(int r, int d){
        boolean [] booleanArray = new boolean[d];
        for(int i = 0; i < d; i++){
        double xCoord = Math.random() * 2;
        double yCoord = Math.random() * 2;
        if((Math.pow(xCoord,2) + Math.pow(yCoord,2)) <= r){
            booleanArray[i] = true;
        }
        else{
            booleanArray [i] = false;
        }
       }
       return booleanArray;
    }

    //calculating pi from throwing results
    public static double piEstimater(boolean [] h, int d){
        int trueCounter = 0;
        for(int i = 0; i < h.length; i++){
            if(h[i] == true){
                trueCounter++;
            }
        }
        return 4 * ((double)trueCounter / d);
    }

    //printing results
    public static void printer(double [] a){
        System.out.println("     Pi Estimation Tool    ");
        System.out.println("---------------------------");
        for(int i = 0; i < a.length; i++){
            System.out.print("Trial [" + i + "]: pi = ");
            System.out.printf("%6f\n", a[i]);
        }
    }

    public static void main(String[] args){
        //variables
        Scanner in = new Scanner(System.in);
        int radius = 1;
        int darts;
        int trials;

        System.out.println("Enter the number of darts to calculate for: ");
        darts = in.nextInt();
        System.out.println("Enter the number of trials to calculate for: ");
        trials = in.nextInt();

        double [] arrayOfEstimates = new double [trials];
        int i = 0;
        for(double a : arrayOfEstimates){
           boolean [] hitCounter = dartThrow(radius, darts);
           double piEstimate = piEstimater(hitCounter, darts);
           arrayOfEstimates[i] = piEstimate;
           i++;
        }

        printer(arrayOfEstimates);
    }
}

I have created code that executes correctly, except for that the results never go above ~ .8. I would like to just assume that this is happening because the random numbers are so low, but if it happens every time something HAS to be wrong, right? Please keep in mind that this code contains about all the Java techniques I know, so I would appreciate it if you kept from including anything more "advanced." Thanks!

A: The idea of the calculation of PI using the Monte Carlo method is to sample random points in a square, and count the fraction of them that fall within the area of a circle bound by that square. If enough points are uniformly sampled, the fraction would be close to the area of the circle divided by the area of the bounding square :
fraction = PI*r^2/(2r)^2
and therefore
PI = fraction * 4.
Now, since you are sampling only positive coordinates, if we assume that the circle is centered at the origin (0,0), we only sample points within the top-right quarter of the circle and its bounding square, but the equation remains the same.
If your circle has radius r, you should sample coordinates between 0 and r.
Therefore you should change this :
    double xCoord = Math.random() * 2;
    double yCoord = Math.random() * 2;

To this :
    double xCoord = Math.random() * r;
    double yCoord = Math.random() * r;

In addition the condition should be ((Math.pow(xCoord,2) + Math.pow(yCoord,2)) <= r*r).
Of course, you can simplify it by eliminating r and assuming the radius is 1.
In that case the condition would be ((Math.pow(xCoord,2) + Math.pow(yCoord,2)) <= 1) and the coordinates would be sampled between 0 and 1.


text:
Q: How to add a list of keywords to an wit.ai entity? I'm new to wit.ai. I'm building a bot that does voice input for an order processing pipeline. In one field i need to input the client location. And this client_location entity has a keyword search strategy attached to it.
Now i want to add all cities, towns and villages to this entity as keywords. Because only one of this will be considered a valid value for client_location entity.
But there are a couple thousands of them, and adding them by hand, one by one, inside the wit.ai UI, doesn't make much sense.
I want to use a cli tool or a node package or something - to do it programmatically.

How can i do this? And also is ok to have so many keywords for one entity?

A: For now, the node.js library can't do training.
But you can still do it using HTTP REST api, by posting to /samples path.
POST/samples
The docs are here.


text:
Q: Windows Update API with C# not finding any installed updates I have a number of Windows 7 PC's that need patching with a particular Windows update, using the Windows Update API in a C# console app. The API needs to search the installed updates and report back if it's already installed and perform the installation if not.
Whilst testing on a Virtual PC (Windows 7 Professional Hyper-v client) I have a situation similar to the target PCs (Windows 7 Embedded) where the following code returns (very quickly and without any exceptions) 0 updates. Which I know to be wrong. In fact, it even returns this after I install a .msu update.
Code:
 UpdateSession uSession = new UpdateSession();
 IUpdateSearcher uSearcher = uSession.CreateUpdateSearcher();
 uSearcher.Online = false;
 try
 {
    ISearchResult sResult = uSearcher.Search("IsInstalled=1 And IsHidden=0");
    Console.WriteLine("Found " + sResult.Updates.Count + " updates");
    foreach (IUpdate update in sResult.Updates)
    {
       Console.WriteLine(update.Title);
       if (update.Title.ToLower().Contains("kb123456")) {
        //Update is not required
        ReportInstalled();
        return;
       }
     }
     //If we get here, the update is not installed
     InstallUpdate();
  }
  catch (Exception ex)
  {
    Console.WriteLine("Something went wrong: " + ex.Message);
  }

Now for the fun part. If I open up the Windows Update from the Control Panel and click 'Check for updates', it goes off for a while and comes back with a bunch of updates to install. At this point, if I run the above code, it works as expected and reports over 200 installed updates.
It appears that the manual process of searching for updates starts/restarts some services and/or other processes, however, I am struggling to figure out exactly what I need to do to the system to get it into the correct state. I expect the answer will be a simple case of starting service x or process y with a set of args, but which?
Some (not all) of the things I have tried but did not alter the behavior:

*

*Started the BITS service, restarted Windows Update Service

*Tried launching wuauclt.exe with various switches (documented
here in the comments)

With the machine in a state where the code runs correctly (after I run WU manually), I have noticed the process wuauclt.exe appears to start when the above code is run. When it's in the target state (before I run WU manually), wuauclt.exe does not start, and I am not able to launch this manually, I suspect this is a big clue.
One other clue is the state of Windows Update before I run it manually. In the control panel windows update looks like this:

After running WU and installing updates via that method, and the machine is in a state where the code runs as expected WU looks like:

To sum up, I need this process to automate the installation of an update. If I detect 0 installed updates, I know the machine is in a particular state, so I will need to launch/restart some processes and services (programmatically) to get the machine into the correct state before running my code. Knowing what to run/restart is the essence of this problem.

A: Since this question doesn't have an answer at the moment (though the combined comments mostly give the answer), here's what happened here:
This is a very common approach to checking "Do I have the patches I need in order for my program to run successfully?", and it has a short-term and a long-term problem.
The short-term problem:
The search code is doing an offline scan (it's setting IUpdateSearcher::Online to false). That's a common tactic to speed up the search. The problem is that it only processes updates that were available during the previous online scan. If the computer hasn't done an online scan in ages, then the results will be stale. If the computer has had a notable hardware or software configuration change since the last online scan, then the results will be incomplete. If the computer has never done an online scan, then IUpdateSearcher::Search won't return an error -- it will just instantly report that no updates are applicable.
So if you want to try to speed things up by doing an offline scan, it's good coding practice to check IAutomaticResults::LastSearchSuccessDate, which tells you the last time that Automatic Updates did a scan. Since Automatic Updates scans are online, you know that an online scan occurred at that time. If the date is more than a few days old, you should do an online scan instead.
The long-term problem:
This code is assuming that an update KB123456 exists and is relevant to the computer. But that's inherently a time-limited assumption, and the time limit these days is often quite short. If the patches in KB123456 get rolled into a newer cumulative update KB234567, then at some point KB123456 may be expired from Windows Update. At that point your search will always return "not installed", even if the patched code is actually on the PC.
Conclusion
Instead of trying to check "Is KB X installed?", the better approach is to test "Is the fix/feature I need installed?"

*

*If at all possible, check for the fix/feature directly. For example, if you need a particular new Windows API, then you can use API Sets if the OS supports it, or just use LoadLibrary and GetProcAddress to see if the DLL you're after contains the function you need.

*If testing directly for the fix/feature isn't possible, then test the state of Windows itself to see if it's what you need. In Windows 10, you often just need to check the build number. On older versions of the OS, instead of hardcoding a KB number, you can look at the patch notes for the KB, find out what DLLs it updates and what version numbers it updates them to, then use those DLL names and versions for your runtime check.

*Depending on exactly what you're testing and the context in which you're doing the test (scripting, etc.), the DISM command may also be helpful -- if you need a particular Windows package to be present, you can use DISM /ONLINE /GET-PACKAGES and see if your package shows up in the output.


text:
Q: Java AES Encryption not decrypting correctly I have this test below where I'm trying to verify that my AES encryption/decryption with compression/decompression is working correctly. I have a test for just the encryption/decryption and a test for just the compression/decompression and I know individually they work correctly, but for some reason when I combine them the IV gets screwed up after the decompression. I'm stuck and don't know what else to look for, can anyone offer any suggestions or help? If I need to post more code let me know. I think I included the important stuff.
For context: What I'm trying to do is take some sensitive data, encrypt it with AES, encrypt the AES key with a RSA public key and then compress those two pieces of data so they can be sent over the wire. Then on the other end I want to decompress the data, use a RSA private key to decrypt the AES key and then use that to decrypt the data. If there is another way to accomplish this I'm not locked into writing everything my self. If you suggest a library please only suggest libraries that I can use in a commercial product.
@Test
public void testEncryptionDecryptionProcesses() throws SSHException {

    SSHKey key1 = generateKeyPair();

    UnencryptedData data = new UnencryptedData();
    data.setUserName("hardy");
    data.setHashedPassword("somepassword");
    data.setRequest("eat");
    data.setResponse("");
    data.setTimestamp(new Timestamp(new Date().getTime()).toString());
    data.setPublicKeyMod(key1.getPublicMod().toString());
    data.setPublicKey(key1.getPublicKey().toString());

    byte[] bytes = encryptAndCompress(data, key1);

    assertTrue(bytes != null);
    assertTrue(bytes.length > 0);

    UnencryptedData decryptedData = decompressAndDecrypt(bytes, key1);
    assertEquals(data.getDataForEncryption(), decryptedData.getDataForEncryption());

}

public static byte[] encryptAndCompress(UnencryptedData data, SSHKey sshKey) {

    byte[] results = null;

    try {
        byte[] aesKey = createKeyForAES(AES_BIT_LENGTH);
        //this should use the servers public key so that only the server can decrypt it
        //gather data, get a digest, encrypt the data
        UnencryptedData digestedData = createDigest(data);
        //encrypt it
        EncryptedData toCompress = encryptDataAES(digestedData, aesKey);
        String encryptedAESKey = encryptKey(sshKey, aesKey);
        toCompress.setEncryptedAESKey(encryptedAESKey);
        //compress it
        byte[] compressed = compressString(toCompress.getDataForCompression());
        //return the compressed and encrypted data.
        results = compressed;
    } catch(SSHException e) {

        Log.e("SSHFunctions.encryption", "Unable to run the encryption/compression process on the data");
    } catch (UnsupportedEncodingException e) {

        Log.e("SSHFunctions.encryption", "Charset not supported");
    }

    return results;
}

public static UnencryptedData decompressAndDecrypt(byte[] data, SSHKey sshKey) {

    UnencryptedData results = null;

    try {
        //take the data and decompress it, should result in encryptedData|encryptedAESKey
        byte[] decompressed = decompressString(data);
        String decompressedStr = new String(decompressed, CHAR_SET);
        String[] decompressedArr = decompressedStr.split(SPLIT_STRING);
        //using the users private key decrypt the data
        byte[] decryptedKey = decryptKey(sshKey, decompressedArr[1]);
        EncryptedData encryptedData = new EncryptedData();
        encryptedData.setAesEncryptedData(decompressedArr[0].getBytes(CHAR_SET));
        encryptedData.setIV(decompressedArr[2].getBytes(CHAR_SET)); //TODO: this doesn't seem to decompress correctly
        //create a digest from the decrypted data and compare it with the digest that was included.
        UnencryptedData decryptedDate = decryptDataAES(encryptedData, decryptedKey);
        if(validDigest(decryptedDate)) {

            results = decryptedDate;
        }
        //if equal return the data, if not equal return null
    } catch(Exception e) {

        Log.e("SSHFunctions.decryption", "Unable to run the uncompress/decrypt process on the data");
    }

    return results;
}

public static byte[] decompressString(byte[] toDecompress) {

    ByteArrayInputStream bis = new ByteArrayInputStream(toDecompress);
    byte[] uncompressed;

    try {

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        GZIPInputStream is = new GZIPInputStream(bis);

        byte[] tmp = new byte[256];

        while (true) {

            int r = is.read(tmp);
            if (r < 0) {

                break;
            }
            buffer.write(tmp, 0, r);
        }
        is.close();

        uncompressed = buffer.toByteArray();

        try {
            bis.close();
        } catch (IOException e) {
            ;
        }

        try {
            buffer.close();
        } catch (IOException e) {
            ;
        }
    } catch(IOException e) {

        uncompressed = null;
        Log.e("Zipfunctions.decompress", "Unable to decompress");
    }

    return uncompressed;
}

public static byte[] compressString(byte[] toCompress) {

    byte[] toCompressBytes = toCompress;
    byte[] compressed;

    ByteArrayOutputStream bos = new ByteArrayOutputStream(toCompressBytes.length);
    try {
        GZIPOutputStream compressor = new GZIPOutputStream(bos);

        compressor.write(toCompressBytes, 0, toCompress.length);
        compressor.close();

        compressed = bos.toByteArray();

        try {
            bos.close();
        } catch(IOException e) {
            ;
        }
    } catch(IOException e) {

        compressed = null;
        Log.e("ZipFunctions.compress", "Unable to compress data");
    }

    return compressed;
}

A: You're attempting to implement a crypto-system that is similar to OpenPGP. That is, you are wanting to encrypt arbitrary amounts of data with a symmetric key and securely share this key (and the encrypted data) with the recipient(s).
As  a result, I would suggest you consider using the Java OpenPGP libraries provided by the BouncyCastle team.
Their license is very permissive. However, their documentation is infamously poor, so you will need to Google many examples to see how to achieve your goals.

A: First of all, you should not use string-delimiter to separate parts of byte buffer. It would cause problem if your delimiter character exists in your data.
I suggest you to read about TLV structure!
Here is a simple implementation of transport data!
class TransportData {
private byte[] iv;
private byte[] aesKey;
private byte[] encryptedData;

public TransportData() {
}

public TransportData(byte[] iv, byte[] aesKey, byte[] encryptedData) {
this.iv = iv;
this.aesKey = aesKey;
this.encryptedData = encryptedData;
}

public byte[] encode() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeInt(iv.length);
dos.write(iv);
dos.writeInt(aesKey.length);
dos.write(aesKey);
dos.writeInt(encryptedData.length);
dos.write(encryptedData);
dos.close();
return baos.toByteArray();
}

public void decode(byte[] buffer) throws IOException {
ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
DataInputStream dis = new DataInputStream(bais);
iv = new byte[dis.readInt()];
dis.read(iv);
aesKey = new byte[dis.readInt()];
dis.read(aesKey);
encryptedData = new byte[dis.readInt()];
dis.read(encryptedData);
dis.close();
}

public byte[] getAesKey() {
return aesKey;
}
public byte[] getEncryptedData() {
return encryptedData;
}
public byte[] getIv() {
return iv;
}
}


text:
Q: Mobile Safari shows hidden back face when in tab view I made a simple flippable element using common techniques and found some strange behavior in Mobile Safari on iOS 7 (older version also may be affected, unfortunately I can't test them  at the moment older versions also seem to be affected), please see the images below or visit a demo directly on your iOS device.

*

*Editable markup and stylesheet

*Full screen view to visit on your iOS device

    <input id="flippable-trigger" type="checkbox">

            Front

            Back

body {
    font: 1em/0 Arial;
    background-color: silver;
}

.flippable {
    position: relative;
    float: left;
    width: 10rem;
    height: 10rem;
    -webkit-perspective: 800;
}

.flippable input[type="checkbox"] {
    display: none;
}

.flippable-faces,
.flippable-face-front,
.flippable-face-back {
    position: absolute;
    width: 100%;
    height: 100%;
}

.flippable-faces {
    -webkit-transform-style: preserve-3d;
    -webkit-transition: 600ms;
}

.flippable-face-front,
.flippable-face-back {
    position: absolute;
    width: 100%;
    height: 100%;
    line-height: 10rem;
    text-align: center;
    -webkit-box-shadow: 0 0 1rem gray;
    -webkit-backface-visibility: hidden;
}

.flippable-face-front {
    color: black;
    background-color: white;
}

.flippable-face-back {
    color: white;
    background-color: black;
    -webkit-transform: rotateY(180deg);
}

.flippable input[type="checkbox"]:checked ~ .flippable-faces {
    -webkit-transform: rotateY(180deg);
}

A: It appears that repositioning your divs fixes the issue. I don't have an answer as to why that was happening though. Sorry. Working Example | Example for iPhone

    <input id="flippable-trigger" type="checkbox" >

            Back

            Front

    </input>


text:
Q: Countdown timer in UILabel in hidden UITableview section I have an UIView in each section's header as a subview. That View contains start button and a label with countdown timer.
So when the timer is started and the Tableview scrolls, some sections become hidden than shown again, it re creates my View and resets the timer.
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

NSString *arrowName = [arrows objectAtIndex:section];

Workouts *workout = [workoutsArray objectAtIndex:section];

UIView* header;
if (section == 0) {
    header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 76)];
} else header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 68)];
header.backgroundColor = [UIColor colorWithRed:0.133f green:0.125f blue:0.247f alpha:1.00f];

//The View with Timer Label
TodayWorkoutView* headerView = [[TodayWorkoutView alloc] initWithFrame:CGRectMake(16, header.frame.size.height-60, header.frame.size.width-32, 60)];
headerView.workout = workout;

[header addSubview:headerView];

return header;

}
How can I make timers in each section, that will work when TableView is scrolling?

A: I found one solution.
In viewDidLoad method init all Views and add to the new Array:
for (WeekDaysWorkouts *weekWorkout in [self getWokrouts]){

    Workouts *fullWorkout = weekWorkout.workouts;

    [workoutsArray addObject:fullWorkout];

    TodayWorkoutView* headerView = [[TodayWorkoutView alloc] init];
    headerView.workout = fullWorkout;

    [headerViewsArray addObject:headerView];
}

Then I added Views to the section view:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

NSString *arrowName = [arrows objectAtIndex:section];

UIView* header;
if (section == 0) {
    header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 76)];
} else header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 68)];
header.backgroundColor = [UIColor colorWithRed:0.133f green:0.125f blue:0.247f alpha:1.00f];

//The View with Timer Label
TodayWorkoutView* headerView = [headerViewsArray objectAtIndex:section];

headerView.frame = CGRectMake(16, header.frame.size.height-60, header.frame.size.width-32, 60);

[header addSubview:headerView];

return header;}

So, all timers work without interruption, even when scrolling.
If anyone knows better solution, please let me know.


text:
Q: What do i use with LINQ in order to READ database instead of SqlDataReader? I'm trying to use LINQ for the first time and don't understand how to read through the database. I'm sure I am doing something completely stupid and just need a little guidance.
year = year.Where(x => x.statementYear == response[i]).ToList();

SqlDataReader reader;

while (reader.Read())
{

}

Edited question with more info:
This is what I have been trying to get to work.. I don't think I need the con.open() either if I am using the using statement right?
using (SqlConnection con = new SqlConnection(".."))
{
    List<string> paths = new List<string>();

    // Open Connection
    con.Open();

    if (response != null)
    {
        for (var i = 0; i < response.Length; i++)
        {
            if (response != null)
            {
                using (var db = new db())
                {
                    List<ClientStatement_Inventory> years = new List<ClientStatement_Inventory>();

                    years = years.Where(x => x.statementYear == response[i]).ToList();

                    foreach (var year in years)
                    {
                        paths.Add(year.statementPath);
                    }
                }
            }
        }
    }
}

A: When using Linq, there's no use or point in using SqlDataReader....
You really didn't show much to go on - but basically, with Linq, you should have a DbContext (that's your "connection" to the database), and that DbContext should contain any number of DbSet - basically representing the tables in your database. You select from these DbSet's and then you get back a List<Entity> which you just iterate over.
Something along the lines of:
-- select your customers matching a certain criteria
var customers = NorthwindDbContext.Customers.Where(x => x.statementYear == response[i]).ToList();

-- iterate over your customers
foreach (Customer c in customers)
{
     // do whatever with your "Customer" here
}

UPDATE:
from your updated question - all you really need is:
List<string> paths = new List<string>();

using (var db = new FMBDBPRDEntities1())
{
    List<ClientStatement_Inventory> years = new List<ClientStatement_Inventory>();

    years = years.Where(x => x.statementYear == response[i]).ToList();

    foreach (var year in years)
    {
        paths.Add(year.statementPath);
    }
}

That opens the context to access the database, reads some data into a list, iterates over the elements in the list - done. Everything else is useless and can be just deleted.
And you could write this a lot simpler, too:
using (var db = new FMBDBPRDEntities1())
{
    List<string> paths = years.Where(x => x.statementYear == response[i])
                              .Select(y => y.statementPath).ToList();
}

UPDATE #2: if your response is a collection of values (I'm assuming those would be int values), and you need to iterate over it - try something like this:
if (response != null)
{
    List<string> allPaths = new List<string>();

    using (var db = new FMBDBPRDEntities1())
    {
        foreach (int aYear in response)
        {
            List<string> paths = years.Where(x => x.statementYear == aYear)
                                      .Select(y => y.statementPath).ToList();

            allPaths.AddRange(paths);
        }
    }

    return allPaths; // or do whatever with your total results
}

UPDATE #3: just wondering - it seems you never really access the DbContext at all ..... I'm just guessing here - but something along the lines of:
if (response != null)
{
    List<string> allPaths = new List<string>();

    using (var db = new FMBDBPRDEntities1())
    {
        foreach (int aYear in response)
        {
            // access a DbSet from your DbContext here!
            // To actually fetch data from the database.....
            List<string> paths = db.ClientStatement_Inventory
                                   .Where(x => x.statementYear == aYear)
                                   .Select(y => y.statementPath).ToList();

            allPaths.AddRange(paths);
        }
    }

    return allPaths; // or do whatever with your total results
}


text:
Q: How are OpenCV image masks used How are image masks in OpenCV meant to be used? From my understanding I am using it correctly but am not getting the expected results.
I am trying to merge two images. I start out with a result Mat (original image) which looks like this:

I then want to add this new image on top:

To do this I create an image mask (with type 8UC1) that looks like this:

I then use the code image2.copyTo(result, mask); to copy the new image onto the result. In the code image2 is the new image and result is the original image.
The problem is the end result is just the new image, not the new image on top of the original image.
Code for merging the images:
//referenceImg is copied into the original image,
referenceImg.copyTo(result);
cv::Mat mask = createMask(h, image2);

imshow("Result image before", result);

//Translate the image
//Before this image2 is a regular image loaded from disk
cv::warpPerspective(image2, image2, h,
                        cv::Size(referenceImg.cols+image2.cols, referenceImg.rows*2), cv::INTER_CUBIC);

image2.copyTo(result, mask);
std::cout << mask.type() << std::endl; //Returns 0
imshow("Result", result);

cv::waitKey(0);

createMask method code:
cv::Mat App::createMask(cv::Mat homography, cv::Mat image)
{
    cv::Mat grayImage;
    image.copyTo(grayImage);
    grayImage.setTo(cv::Scalar(255, 255, 255));
    cv::cvtColor(grayImage, grayImage, CV_BGR2GRAY);

    cv::Mat mask;
    cv::warpPerspective(grayImage, mask, homography, cv::Size(image.cols*2, image.rows*2), cv::INTER_CUBIC);

    return mask;
}

A: Looks like the size of image2 and result does not match.
So the copyTo function will allocate a new matrix for result matrix. (based on the size of image2)
reference