text:
Q: Can't add multiple items to express checkout paypal Before someone marks as duplicate, i have read all the other posts regarding adding multiple items to express checkout and have not been able to solve my issue.
I am using a working shopping cart demo supplied by PayPal, though all their demos or documentation only provide examples with a single item added to the cart, it's not possible in the demos to add multiple items. No where can i find any documentation on how to add multiple items properly.
In the code below(directly taken from paypal demo but with an additional product i added) it allows the transaction to be valid, but when the user logs into their paypal account it only displays the first product, BUT also the price of that product is the total of the two products.
for example it displays as follows:

*

*DSLR Camera         $20.00 USD

*Tax                 $2.00 USD

*Shipping            $5.00 USD

*Shipping discount   $-3.00 USD

*Handling            $1.00 USD

*Insurance           $2.00 USD

*Total               $27.00 USD

It doesn't show the second product. Any ideas? thanks
Code:

<form class="form" action="paypal_ec_redirect.php" method="POST">

 DIGITAL SLR CAMERA

 Buyer Credentials:

Email-id:   <input type="text" id="buyer_email" name="buyer_email" readonly></input>

Password:<input type="text" id="buyer_password" name="buyer_password" readonly></input>

 Item Specifications:

Item Name:	<input type="text" name="L_PAYMENTREQUEST_0_NAME0" value="DSLR Camera"></input>

Item ID: 	<input type="text" name="L_PAYMENTREQUEST_0_NUMBER0" value="A0123"></input>

Description:	<input type="text" name="L_PAYMENTREQUEST_0_DESC0" value="Autofocus Camera"></input>

Quantity:	<input type="text" name="L_PAYMENTREQUEST_0_QTY0" value="1" readonly></input>

Quantity:	<input type="text" name="L_PAYMENTREQUEST_0_AMT0" value="10.00" readonly></input>

Item Name:	<input type="text" name="L_PAYMENTREQUEST_0_NAME1" value="Item 2"></input>

Item ID: 	<input type="text" name="L_PAYMENTREQUEST_0_NUMBER1" value="12345"></input>

Description:	<input type="text" name="L_PAYMENTREQUEST_0_DESC1" value="Description"></input>

Quantity:	<input type="text" name="L_PAYMENTREQUEST_0_QTY1" value="1" readonly></input>

Quantity:	<input type="text" name="L_PAYMENTREQUEST_0_AMT1" value="10.00" readonly></input>

Price:	<input type="text" name="PAYMENTREQUEST_0_ITEMAMT" value="20.00" readonly></input>

Tax:	<input type="text" name="PAYMENTREQUEST_0_TAXAMT" value="2" readonly></input>

Shipping Amount:	<input type="text" name="PAYMENTREQUEST_0_SHIPPINGAMT" value="5" readonly></input>

Handling Amount:	<input type="text" name="PAYMENTREQUEST_0_HANDLINGAMT" value="1" readonly></input>

Shipping Discount:	<input type="text" name="PAYMENTREQUEST_0_SHIPDISCAMT" value="-3" readonly></input>

Insurance Amount:	<input type="text" name="PAYMENTREQUEST_0_INSURANCEAMT" value="2" readonly></input>

Total Amount:	<input type="text" name="PAYMENTREQUEST_0_AMT" value="27" readonly></input>

<input type="hidden" name="LOGOIMG" value=<?php echo('http://'.$_SERVER['HTTP_HOST'].preg_replace('/index.php/','img/logo.jpg',$_SERVER['SCRIPT_NAME'])); ?>></input>

Currency Code:	<select name="currencyCodeType">
            <option value="AUD">AUD</option>
            <option value="BRL">BRL</option>
            <option value="CAD">CAD</option>
            <option value="CZK">CZK</option>
            <option value="DKK">DKK</option>
            <option value="EUR">EUR</option>
            <option value="HKD">HKD</option>
            <option value="MYR">MYR</option>
            <option value="MXN">MXN</option>
            <option value="NOK">NOK</option>
            <option value="NZD">NZD</option>
            <option value="PHP">PHP</option>
            <option value="PLN">PLN</option>
            <option value="GBP">GBP</option>
            <option value="RUB">RUB</option>
            <option value="SGD">SGD</option>
            <option value="SEK">SEK</option>
            <option value="CHF">CHF</option>
            <option value="THB">THB</option>
            <option value="USD" selected>USD</option>

Payment Type: 	<select>
                                               <option value="Sale">Sale</option>
                                               <option value="Authorization">Authorization</option>
                                               <option value="Order">Order</option>
                                             </select>

 -- OR --

<input type="Submit" alt="Proceed to Checkout" class="btn btn-primary btn-large" value="Proceed to Checkout" name="checkout"/>

</form>

A: I figured it out, their demo code only manually checks for one item in the post data.
The POST data and return and cancel URLs are sent to a CallShortcutExpressCheckout function (paypal_functions.php) that only checks for predetermined parameters rather than actually looping through any of the POST data.
For example it only manually checks for if a parameter issset(), but only for one item:
function CallShortcutExpressCheckout( $paramsArray, $returnURL, $cancelURL) {

        //it manually checks for all the paramters, i just have shown one for example
        if(isset($paramsArray["PAYMENTREQUEST_0_SHIPDISCAMT"])){
            $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPDISCAMT=" . $paramsArray["PAYMENTREQUEST_0_SHIPDISCAMT"];
            $_SESSION['shippingDiscAmt'] = $paramsArray["PAYMENTREQUEST_0_SHIPDISCAMT"];
        }

        //And here it only looks for one item
        if(isset($paramsArray["L_PAYMENTREQUEST_0_NAME0"]))
        $nvpstr = $nvpstr . "&L_PAYMENTREQUEST_0_NAME0=" . $paramsArray["L_PAYMENTREQUEST_0_NAME0"];

        if(isset($paramsArray["L_PAYMENTREQUEST_0_NUMBER0"]))
        $nvpstr = $nvpstr . "&L_PAYMENTREQUEST_0_NUMBER0=" . $paramsArray["L_PAYMENTREQUEST_0_NUMBER0"];

        if(isset($paramsArray["L_PAYMENTREQUEST_0_DESC0"]))
        $nvpstr = $nvpstr . "&L_PAYMENTREQUEST_0_DESC0=" . $paramsArray["L_PAYMENTREQUEST_0_DESC0"];

        if(isset($paramsArray["L_PAYMENTREQUEST_0_AMT0"]))
        $nvpstr = $nvpstr . "&L_PAYMENTREQUEST_0_AMT0=" . $paramsArray["L_PAYMENTREQUEST_0_AMT0"];

        if(isset($paramsArray["L_PAYMENTREQUEST_0_QTY0"]))
        $nvpstr = $nvpstr . "&L_PAYMENTREQUEST_0_QTY0=" . $paramsArray["L_PAYMENTREQUEST_0_QTY0"];

        if(isset($paramsArray["LOGOIMG"]))
        $nvpstr = $nvpstr . "&LOGOIMG=". $paramsArray["LOGOIMG"];

I just deleted all the code and put in a simple foreach loop:
function CallShortcutExpressCheckout( $paramsArray, $returnURL, $cancelURL)
{

    if(isset($returnURL))
    $nvpstr = $nvpstr . "&RETURNURL=" . $returnURL;

    if(isset($cancelURL))
    $nvpstr = $nvpstr . "&CANCELURL=" . $cancelURL;

    foreach ($paramsArray as $k => $value){
        $nvpstr = $nvpstr . "&" . $k . "=" . $value;
    }

And on top of that, for some reason in the paypal_ec_redirect.php they make sure to change the individual product item amount to the sum of all items amount as if to make sure that only one item is being sent, otherwise it throws a totals of the cart item amounts do not match order amounts (Error Code: 10413).
I just commented it out and everything works great now and i can place multiple item orders.
//$_POST["L_PAYMENTREQUEST_0_AMT0"] = $_POST["PAYMENTREQUEST_0_ITEMAMT"];

I hope this helps someone, i did see another stackoverflow question with the exactsame problem. Why they would make their demo code to purposely only accept one item is beyond me.


text:
Q: Populating a FieldType: Choice field with multiple options using an FDF via Pdftk in PHP I am using Pdftk and pdftk-php (which is based on forge-fdf). I'd like to generate an FDF that can be merged with a PDF to fill out a dropdown text box with multiple options. The way pdftk-php works by default, it will only fill dropdowns with a single value; passing it an array doesn't work.
Here is the relevant output from pdftk filename dump_data_fields.
FieldType: Choice
FieldName: VehicleIDData1
FieldFlags: 4587520
FieldJustification: Left

According to this example from the PDF 1.2 specification, dropdowns seem to require the /Opt option in the FDF.
%FDF-1.2
1 0 obj <<
/FDF <<
/Fields
[
<<
/T (My Children)
/V (Tali)
/Opt [(Maya) (Adam) (Tali)]
November 12, 1996
: 379
>>
]
/F (Dependents.pdf)
>>
>>
endobj
trailer
<</Root 1 0 R>>
%%EOF

This is supported by the table on page 717 in the 1.7 specification
Opt
array
(Required; choice fields only) An array of options to be presented to the user. Each element of the array can take either of two forms:
•A text string representing one of the available options
•A two-element array consisting of a text string representing one of the available options and a default appearance string for constructing the item's appearance dynamically at viewing time (see "Variable Text" on page 677)

pdftk-php doesn't use /Opt; if you pass it an array of values for a field, it will use /Kids, which isn't filling out the other dropdown entries. I've tried to modify the program to use /Opt instead, but there's no difference in the resulting PDFs. What am I doing wrong?
protected function forge_fdf_fields( &$fdf,
          &$fdf_data,
          &$fields_hidden,
          &$fields_readonly,
          $accumulated_name,
          $strings_b ) // true <==> $fdf_data contains string data
    //
    // string data is used for text fields, combo boxes and list boxes;
    // name data is used for checkboxes and radio buttons, and
    // /Yes and /Off are commonly used for true and false
{
    if( 0< strlen( $accumulated_name ) ) {
        $accumulated_name.= '.'; // append period seperator
    }

    foreach( $fdf_data as $key => $value ) {
    // we use string casts to prevent numeric strings from being silently converted to numbers
        $fdf.= "<< "; // open dictionary

        if( gettype($value)== 'array' ) { // parent; recurse
            $fdf.= "/T (".$this->escape_pdf_string( (string)$key ).") "; // partial field name
            $fdf .= "/V (" . $this->escape_pdf_string((string)$value[0]) . ") ";

            $fdf .= "/Opt [";
            foreach ($value as $option) {
                $fdf .= "(" . $this->escape_pdf_string((string)$option) . ") ";
            }

            /* This is the older code I'm replacing.
            $fdf.= "/Kids [ ";                                    // open Kids array

            // recurse
            $this->forge_fdf_fields( $fdf,
                $value,
                $fields_hidden,
                $fields_readonly,
                $accumulated_name. (string)$key,
                $strings_b );
            */

            $fdf.= "] "; // close Kids array
        } else {

            // field name
            $fdf.= "/T (".$this->escape_pdf_string( (string)$key ).") ";

            // field value
            if( $strings_b ) { // string
                $fdf.= "/V (".$this->escape_pdf_string( (string)$value ).") ";
            }
            else { // name
                $fdf.= "/V /".$this->escape_pdf_name( (string)$value ). " ";
            }

            // field flags
            $this->forge_fdf_fields_flags( $fdf,
                        $accumulated_name. (string)$key,
                        $fields_hidden,
                        $fields_readonly );
        }
        $fdf.= ">> \x0d"; // close dictionary
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Read empty string as Null Athena I want to create a table in Amazon Athena over csv file on s3. Csv file looks like
id,name,invalid
1,abc,
2,cba,y

Code for creating table looks like
CREATE EXTERNAL TABLE IF NOT EXISTS {schema}.{table_name} (
id int,
name string,
invalid string
)
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe'
WITH SERDEPROPERTIES (
  'serialization.format' = ',',
  'field.delim' = ','
)
LOCATION '{s3}'
TBLPROPERTIES ('has_encrypted_data'='false','compressionType'='gzip')

So, my problem is Athena reads empty string as actually empty string but I'd like to see it like null. I haven't found any property for that in docs.

A: LazySimpleSerDe will interpret \N as NULL by default, but you can configure it to use other strings with the serialization.null.format serde property.
For this guide on CSV and Athena for more details.


text:
Q: Anaconda install of Tensorflow missing 'audio_ops' from contrib framework I'm trying to follow along the Audio Recognition Network tutorial.
I've created an Anaconda environment with python 3.6 and followed the install instruction accordingly for installing the GPU whl.
I can run the 'hello world' TF example.
When I go to run 'train.py' in the Audio Recognition Network tutorial/example, I get:
Traceback (most recent call last):
  File "train.py", line 79, in <module>
    import input_data
  File "/home/philglau/speech_commands/input_data.py", line 35, in <module>
    from tensorflow.contrib.framework.python.ops import audio_ops as contrib_audio
ImportError: cannot import name 'audio_ops'

The code in the tutorial that fails is:
from tensorflow.contrib.framework.python.ops import audio_ops as contrib_audio

I then backed up that chain until I could import some part of it:
import tensorflow.contrib.framework as test ==> works
import tensorflow.contrib.framework.python as test --> fail:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'tensorflow.contrib.framework' has no attribute 'python'

Not sure where I'm going wrong on my install.
Details:
Ubuntu 16.04
Anaconda env with python 3.6
Followed the 'anaconda' instruction on the TF install page. (GPU version)

I also tried using a python 2.7 env for anaconda but got the same results.

A: It looks like they're releasing the audio_ops modules in version 1.4 (https://github.com/tensorflow/tensorflow/issues/11339#issuecomment-327879009).
Until v1.4 is released, an easy way around this is to install the nightly tensorflow build
pip install tf-nightly

or with the docker image linked in the issue comment.

A: The short answer:
  The framework is missing the "audio_ops.py" and the example wont work until the file is released. Or you code the wrappers.
More on this:
  If you go to the: tensorflow.contrib.framework.python.ops local folder you can find other *_ops.py files but not the "audio_ops.py".
If you get it from the Master at: https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/framework/python/ops
You will find the file is almost empty and with import labels wrong: "audio_ops" vs "gen_audio_ops".
With almost empty I mean that: decode_wav, encode_wav, audio_spectrogram , mfcc are not implemented/wrapped.
So, no working example and no fun.
We need to check again when "audio_ops.py" is released.
Here:
https://github.com/tensorflow/tensorflow/issues/11339
You can find a Developer saying: "we don't actually want to make them public / supported yet. I'm sorry this decision wasn't better documented"


text:
Q: Same python virtualenviroment different OS if this is not consider a valid question or problem to solve, I can try in other category.
I used to work with python virtualenvs stored on OneDrive and run the projects from different PCs. Now I have to work from Mac OS and virtual enviroments don't seem to be equals.
Is there a way to accomplish this from both OS ?
Thanks in advance.


text:
Q: how to add our menu item in existing application i want to make an application in which ,if user is sending sms through default messenger by blackberry,for sending there are certain menuitems appears.
i want to add mymenuitem on that list how could i do that plz help me..
thkz alot.

A: I'm not sure exactly which application you're referring to, but if it's in ApplicationMenuItemRepository then you can register an ApplicationMenuItem with it and it will show up in that application's menu.


text:
Q: Normal matrix and eigenvectors Let $A \in M_n(\mathbb{C})$ show that if every eigenvector of $A$ is an eigenvector of $A^*$ then $A$ is normal.
This question is equivalent to If every eigenvector of $T$ is also an eigenvector of $T^{*}$ then $T$ is a normal operator. The first answer uses unitary triangularization but I didn't understand why the fact that $e_1$ is an eigenvector of $T^*$ implies $a_{1j}=0$ for $j>1$. In the second answer there is a hint but how does it complete the proof?

A: First we show:

If $T$ is triangular and the eigenvectors of $T$ are the eigenvectors of $T^*$, then $T$ is diagonal.

Proof by induction: The statement is trivially satisfied for $n=1$. Assume it's true for $(n-1)\times(n-1)$ matrices and let the (upper) triangular $T$ have the form
$$
T=\begin{bmatrix}\tau&t^*\\0&\tilde{T}\end{bmatrix}.
$$
The matrix $T$ has an eigenvalue $\tau$ with the eigenvector $e_1=[1,0,\ldots,0]^T$, that is, $Te_1=\tau e_1$. We have
$$
T^*e_1=\begin{bmatrix}\bar{\tau}&0\\t&\tilde{T}^*\end{bmatrix}\begin{bmatrix}1\\0\end{bmatrix}=\begin{bmatrix}\bar{\tau}\\t\end{bmatrix}.
$$
By the assumption, $e_1$ is the eigenvector $T^*$. This is possible only if $t=0$, that is, $T$ has the form
$$
T=\begin{bmatrix}\tau&0\\0&\tilde{T}\end{bmatrix}.
$$
By the induction assumption, the matrix $\tilde{T}$ is diagonal since it has the same eigenvectors as $\tilde{T}^*$.
Second, consider the Schur decomposition of $T$, $T=QRQ^*$, where $Q$ is unitary and $R$ upper triangular. Note that $Tx=\lambda x$ is equivalent to $(Q^*TQ)(Q^*x)=\lambda(Q^*x)$, that is, $R(Q^*x)=\lambda(Q^*x)$ and $T^*x=\mu x$ is equivalent to $(Q^*T^*Q)(Q^*x)=\mu(Q^*x)$, that is, $R^*(Q^*x)=\mu(Q^*x)$. Hence $x$ is a common eigenvector of $T$ and $T^*$ if and only if $Q^*x$ is a common eigenvector of the triangular factor $R$ of the Schur decomposition of $T^*$. Using the statement we proved, we see that $T$ and $T^*$ have common eigenvectors if and only if $R$ is diagonal and hence $T=QRQ^*$ (with diagonal $R$) is normal.

A: Here is a start. Fi rst of all notice this

if $\lambda $ is an eigenvalue of $A$, then $\overline{\lambda}$ is an eigenvalue of $A^*$.

Now, we have
$$ Au = \lambda u $$
which implies
$$ A^* u= \overline{\lambda }u, $$
since they have the same eigenvector.  Apply $A^*$ and $A$ to the last two equations respectively and try to finish the problem.

A: let v is eigen vector of T for eigen value ɳ
and v is eigen vector of T* for eigen value µ
then
Tv = ɳv
T*v = µv,   operating T* on 1st and T on 2nd:
T*Tv = ɳT*v = ɳµv
TT*v = uTv = ɳµv;  Thus TT*v = T*Tv for all L.I. eigen vectors, Hence TT* = T*T


text:
Q: Updating JSON values are not replacing with old values I have values in JSON format in server and getting these values then displaying into mobile app textview. I'm storing the values into local database then getting from it, but if i change any values in server JSON and the text view is not loading new values it always showing old values. How can i replace the table with new data everytime user check the JSON?
 @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub

  String CREATE_TABLE_BEACON = "CREATE TABLE " + TABLE_BEACON + "("
                    + KEY_NAME + " VARCHAR,"+ KEY_UUID + " VARCHAR,"+ KEY_MAJOR_ID + " INTEGER,"+ KEY_MINOR_ID + " INTEGER,"+ KEY_TYPE + " VARCHAR,"+ KEY_ACTION + " VARCHAR)";
            db.execSQL(CREATE_TABLE_BEACON);

        }

      public long insertBeaconDetails(BeaconDetails beacondetailstore)
        {
            SQLiteDatabase db = this.getWritableDatabase();

            ContentValues values = new ContentValues();

             values.put(KEY_NAME,beacondetailstore.name);
             values.put(KEY_UUID,beacondetailstore.uuid);
             values.put(KEY_MAJOR_ID,beacondetailstore.major);
             values.put(KEY_MINOR_ID,beacondetailstore.minor);
           //  values.put(KEY_NOTIFICATION,beacondetailstore.notification);
             values.put(KEY_TYPE,beacondetailstore.type);
            values.put(KEY_ACTION,beacondetailstore.action);

             long rowId = db.replace(TABLE_BEACON, null, values);
             db.close();
             return rowId;
        }

A: you can use update query and every time the user check new json  load your data from database into ur textview.
Like :
         db.update( "TABLE_NAME",
                  values,
                   TABLE_COLUMN_NAME + " = ?",
                    new String[] { OLD_VALUE_OF_TABLE_COLUMN_NAME });
then :
     retreive the data from database and load it again into your textview


text:
Q: difflib.SequenceMatcher not returning unique ratio I am trying to compare 2 street networks  and when i run this code it returns a a ratio of .253529...  i need it to compare each row to get a unique value so i can query out the streets that dont match. What can i do it get it to return unique ratio values  per row?
# Set local variables
inFeatures = gp.GetParameterAsText(0)
fieldName = gp.GetParameterAsText(1)
fieldName1 = gp.GetParameterAsText(2)
fieldName2 = gp.GetParameterAsText(3)
expression = difflib.SequenceMatcher(None,fieldName1,fieldName2).ratio()

# Execute CalculateField
    arcpy.CalculateField_management(inFeatures, fieldName, expression, "PYTHON_9.3")

A: If you know both files always have the exact same number of lines, a simple approach like this would work:
ratios = []

with open('fieldName1', 'r') as f1, open('fieldName2', 'r') as f2:
    for l1, l2 in zip(f1, f2):
        R = difflib.SequenceMatcher(None,l1,l2).ratio()
        ratios.append((l1, l2, R))

This will produce a list of tuples like this:
[("aa", "aa", 1), ("aa", "ab", 0.5), ...]

If your files are different sizes you'll need to find some way to match up the lines, or otherwise handle it


text:
Q: Sorting arrays with Quicksort C++ I am working on a projekt (for school) and one of the requirements is to sort an array.
So I decided to use the quicksort. (I chose it because it is an algorithm that I don't know by now) I managed to understand how it works and I also found an option of its implementation in c++.
void quicksort(size_t v[], size_t start_pos, size_t end_pos)
{
    size_t i, j, di, dj;
    if (start_pos < end_pos)
    {
        i = start_pos, j = end_pos;
        di = 0, dj = 1;
        do
        {
            while (i < j && (v[j] > v[i] || v[j] == v[i])) i += di, j -= dj;
            if (i < j)
                std::swap(v[i], v[j]), di = (di + 1) % 2, dj = (dj + 1) % 2;
        } while (i < j);
        if (i - start_pos > 1)
            sort(v, start_pos, i - 1);
        if (end_pos - i > 1)
            sort(v, i + 1, end_pos);
    }
}

What I don't understand is... why in the last 2 if statements is used ">1"?
I hope someone can clarify this for me. Thank you! :)

A: Both calculations provides the size of the left and right subdivision respectively.
If the size is 1 or zero, that part is already sorted and doesn't need any further processing.
    if (i - start_pos > 1)
        sort(v, start_pos, i - 1);

The sort call is only made if the range is two or more elements.  As Barry points out, this should probably be
    if (i - start_pos > 1)
        quicksort(v, start_pos, i - 1);

Victors comment is also on point.

A: If you look carefully, the upper portion of the code does the arranging the array corresponding to pivot element which is indexed at i and the last two if's sort the remaining portion i.e. to the right and left of the pivot element but in case your pivot index has already reached end_pos you don't need to sort elements to right of the pivot element thus there is an if condition whether i < end_pos.


text:
Q: TPanel color is black when I drop a XPManifest control on my form This is a continuation of a previous post: TPanel color is black no matter what
The problem is this: All TPanels that have a TForm as parent, turn black when I use a XPManifest. Anybody knows why?

A: Change Panel1.ParentBackground to true then change it back to false.

A: There is no other solution for this than deleting the XPManifest.


text:
Q: Should a linear amplifier be considered as a current source or a voltage source? Linear amplifiers such as class A, B, and AB can deliver current to the load. Then should it be regarded as a current source?
However, a current source should have a high output impedance while a voltage source should have a low output impedance. Now consider the following class B amplifier. It is in the emitter follower configuration. The impedance looking into the emitter is low and hence the output impedance should be low. So in this case, should this linear amplifier be regarded as a voltage source instead of a current source?

Source: https://www.electronics-tutorials.ws/amplifier/class-ab-amplifier.html
Consider another class B amplifier configuration in the following diagram. Now it is in a common source configuration. The impedance looking into the course is high and the output impedance is also high. So in this case, should the power amplifier be considered as a current source?

Source: https://www.sciencedirect.com/science/article/pii/S0026269219304719?casa_token=r_fOAPtZPQEAAAAA:1msPiihOEI1AHetzlhnBU4VSO_zqVF2TYRrsCU39GQ73phPj05mjhYxolI9JbNH2DCQJs6s8
So as a whole, can we say that a linear amplifier can either be a current voltage or a voltage source depending on its configuration?

A: From the Thevenin and Norton theorems we know that any source (aside from an ideal voltage or current source) can be considered as either a voltage source (Thevenin equivalent) or current source (Norton equivalent).
Practically, if the source has a low output impedance, it will behave more like an ideal voltage source (its output voltage will be insensitive to the load impedance) and it's usually more useful to describe it as a voltage source. And if it has a high output impedance, it will behave more like an ideal current source (its output current will be insensitive to the load impedance) and it's usually more useful to describe it as a current source.
A class B amplifier is designed to have a low output impedance, therefore we will usually describe its output as a voltage source.
Even a class A amplifier, which is a common emitter or common source stage, and has a higher output impedance than a class B amplifier, usually has a lower output impedance than the load it's designed to drive, so it will usually be described as a voltage source.
If you want an example of a current source, look for things like current mirror circuits, or op-amp circuits designed to deliver (near) constant current to their loads.
All of these are linear circuits. But that is a very wide category --- basically meaning the output is proportional to the input --- and isn't restricted to only voltage sources or only current sources.

A: In the great majority of cases, there will be voltage negative feedback such that the output impedance of the entire circuit can be considered very low - being much lower than the load that will be connected.
As a result, the circuit can be considered a voltage source.
In very rare cases there will be current negative feedback to give high impedance, in such cases, it can be considered a current source. The applications for a current source are very limited though are unusual.


text:
Q:  loading time issue in lightning component Lightning component is having table which contains row of records.
Each record row has 2 date input fields.
I am using <ui:inputDate> for date fields.
<ui:inputDate aura:id="endDate" label="End Date"
              value="{!v.account.End_Due_Date__c}"
              displayDatePicker="true" />

If table contains around 50-70 records then the loading time is very long and it takes around 21-25 seconds to load the table.
I also tried keeping displayDatePicker="false" but this doesn't help in anyways.
Is there any trick/solution or better alternatives which can solve this problem.
Appreciate if code snippets are given with solution.
Adding code:
Iteration code generating date component:
<aura:iteration items="{!v.milestone.deliverables}" var="deliverable" indexVar="i">
    <c:FormInputComponent deliverable="{!deliverable}" index="{!i}" />
</aura:iteration>

FormInputComponent having date fields:

<aura:component>
    <aura:attribute name="deliverable" type="object" />

                <form class="slds-form--inline">

                        <ui:outputText value="{!v.deliverable.name}" />

                        <ui:inputCheckbox aura:id="cancel" label="Cancel" />

                    **

                        <ui:inputDate aura:id="startDate" label="Start Date" value="{!v.deliverable.startDate}" displayDatePicker="true" class="slds-input" />

                        <ui:inputDate aura:id="dueDate" label="Due Date" value="{!v.deliverable.dueDate}" displayDatePicker="true" class="slds-input" />

                    **

                        <ui:inputTextArea aura:id="Description" value="{!v.deliverable.description}" label="Deliverable Description" rows="2" class="slds-input" />

                        <ui:button label="Delete" press="{!c.deleteDeliverable}" class="slds-button slds-button--brand" />

                </form>

</aura:component>


text:
Q: One-sided tangents? I was trying to solve this problem:
Find the angle between the one-sided tangents to the curve at the point x = 0.
$$f(x) =\sqrt{1-e^{-x^2}}$$
I obtained the point (0,0) and I have computed the first derivative
$$f'(x)=\frac{-xe^{-x^2}}{\sqrt{1-e^{-x^2}}}$$ but when I try to substitute by $0$ I get that the slope is $0$. How can I solve it ?

A: There are a couple of mistakes:
First,
$$f'(x) = \frac{xe^{-x^2}}{\sqrt{1-e^{-x^2}}}. \tag 1$$
Now, it is easy to prove that
$$\lim_{x \to 0^{+}}f'(x)=1, \tag 2$$
and
$$\lim_{x \to 0^{-}}f'(x)=-1. \tag 3$$
Therefore, the tangents are $y=x$ and $y=-x$, and the angle between them is $\pi/2$.


text:
Q: Best way around combine_array with identical keys? I was using combine_array to update a MySQL table from a CSV file. I thought everything was working like a champ, but it turns out the data source isn't amazing. There are multiple columns with the same name and those columns become the keys in an array. Example take the two arrays:
array 1
[0]=>"name"
[1]=>"email"
[2]=>"shoe size"
[3]=>"email"

array 2
[0]=>"Jake Doe"
[1]=>"jake@example.mail"
[2]=>"10.5"
[3]=>""

if I was to use array_combine($array1,$array2) I would get:
["name"]=>"Jake Doe"
["email"]=>""
["shoe size"]=>"10.5"

The problem is that I'd obviously prefer to have the email not get overwritten by a blank value. What I can up with is the function below. What I'm looking for is just a second set of eyes. Is this there a better way to do this? I hate that I have two nested ifs, but I'm not sure how I'd go about making it cleaner or if that's even possible.
//array_combine simply overwrites repeat keys, this only overwrites if the value is empty
//if the first instance of the key has a value, it ignores duplicate keys
function new_array_combine($key_array,$value_array){
    foreach($value_array as $key=>$value){
        if(array_key_exists($key_array[$key],$new_array)){
            if(empty($new_array[$key_array[$key]]))$new_array[$key_array[$key]]=$value;
        }else{
            $new_array[$key_array[$key]]=$value;
        }
    }
    return $new_array;
}

A: Blah. Trying to rescue this response, since my first obviously missed the entire point of the post.
If you're only worried about those blank values, then I would say you could walk the arrays once through first, 'cleaning' them by deleting indexes with no corresponding value:
<?php
// $a and $b as defined in the example

foreach($a as $k => $v) {
    if(empty($b[$k])) {
        unset($a[$k]);
        unset($b[$k]);
    }
}

$c = array_combine($a, $b);
print_r($c);

Output:
Array(
    [name] => Jake Doe
    [email] => jake@example.mail
    [shoesize] => 10.5
)

Edit: To include blank values (but still not let blanks override existing values), first get the unique keys from $a and use it to build an empty result array, then just skip blank values while looping through...
<?php
// $a and $b as defined in the example

$result = array();
$keys = array_unique($a);
foreach($keys as $key) $result[$key] = '';

foreach($a as $k => $v) {
    if(empty($b[$k])) continue;
    $result[$v] = $b[$k];
}

print_r($result);

Output:
Array(
    [name] => Jake Doe
    [email] => jake@example.mail
    [shoesize] => 10.5
)

A: The only problem I see with your program is when key names do not match in each array
array 1
[0]=>"name"
[1]=>"email"
[2]=>"shoe size"
[3]=>"email"

array 2
[0]=>"Jake Doe"
[1]=>"jake@example.mail"
[3]=>"10.5"
[4]=>""

Suggested modifications:
function new_array_combine($a1, $a2){
   $result=Array();
   reset($a1);
   foreach($a2 as &$v){
      $key=current($a1);
      if (!isset($result[$key])||empty($result[$key]))
          $result[$key]=$v;
      next($a1);
   }
   return $result;
}


text:
Q: Вычислить расстояние через геокоординаты Даны координаты 2-х городов на Земле. Нужно вычислить расстояние между ними. Как это можно сделать?
Радиус Земли: R = 6 371 302 м. Ответ необходимо получить в километрах.
Допустим: даются 4 значения (координаты обоих точек: широта1, долгота1, широта2, долгота2) 55 37.620393 43.116418 131.882475.
После чего, с помощью каких то преобразований, должно выйти число 6458.
Вот код, который выдает неверное значение (выходит - 8836):
#include <iostream>
#include <math.h>
#define PI 3.14159265
using namespace std;
int main() {
    int res = 0, R = 6371302;
    double alet, along, blet, blong;
    cin >> alet >> along >> blet >> blong;
    alet = alet*(180/PI);
    blet = blet*(180/PI);
    along = along*(180/PI);
    blong = blong*(180/PI);
    res = R* acos(sin(alet)*sin(blet)+cos(alet)*cos(blet)*cos(along-blong))/1000;
    cout << res;
    return 0;
}

A: Расстояние через геокоординаты (две пары чисел широта и долгота) в километрах, можно вычислить так:
#include <math.h>
#include <cmath>
#define earthRadiusKm 6371.0

// This function converts decimal degrees to radians
double deg2rad(double deg) {
  return (deg * M_PI / 180);
}

//  This function converts radians to decimal degrees
double rad2deg(double rad) {
  return (rad * 180 / M_PI);
}

/**
 * Returns the distance between two points on the Earth.
 * Direct translation from http://en.wikipedia.org/wiki/Haversine_formula
 * @param lat1d Latitude of the first point in degrees
 * @param lon1d Longitude of the first point in degrees
 * @param lat2d Latitude of the second point in degrees
 * @param lon2d Longitude of the second point in degrees
 * @return The distance between the two points in kilometers
 */
double distanceEarth(double lat1d, double lon1d, double lat2d, double lon2d) {
  double lat1r, lon1r, lat2r, lon2r, u, v;
  lat1r = deg2rad(lat1d);
  lon1r = deg2rad(lon1d);
  lat2r = deg2rad(lat2d);
  lon2r = deg2rad(lon2d);
  u = sin((lat2r - lat1r)/2);
  v = sin((lon2r - lon1r)/2);
  return 2.0 * earthRadiusKm * asin(sqrt(u * u + cos(lat1r) * cos(lat2r) * v * v));
}

Ссылки:

*

*Источник enSO

*Формулы http://mapgroup.com.ua/glavnaya/astronomicheskie-kalkulyatory/1009-rasstoyanie-mezhdu-dvumya-koordinatamirasstoyanie-mezhdu-dvumya-koordinatami

*Вики http://en.wikipedia.org/wiki/Great_circle_distance

*Калькулятор http://www.garmin.com.ua/tools/calc.php

A: Найдите угол между векторами из центра к этим точкам (переведите полярные координаты в декартовы) и умножьте на радиус.

ответ в кМ

разделите в конце на тысячу )


text:
Q: Outlook meeting for 2nd working day of month Is there a way to set a recurring monthly meeting for the 2nd working day of each month.
(assume Sat & Sun are non working days)
So if the month starts on a Saturday the meeting would be Tuesday 4th.
If the month started on a Wednesday the meeting would be Thursday 2nd.
From the available recurring options, working day does not seem to be an option, so I'm not that hopeful, but maybe with VBA ?

A: In your screenshot, the option below selected is: The first tuesday of every 1 month.
If you set this enabled, those options can be changed. First can be changed to Second and Tuesday can be changed to weekday by scrolling up, and it will do exactly what you want.


text:
Q: Check if Python Package is installed What's a good way to check if a package is installed while within a Python script? I know it's easy from the interpreter, but I need to do it within a script.
I guess I could check if there's a directory on the system that's created during the installation, but I feel like there's a better way. I'm trying to make sure the Skype4Py package is installed, and if not I'll install it.
My ideas for accomplishing the check

*

*check for a directory in the typical install path

*try to import the package and if an exception is throw, then install package

A: As of Python 3.3, you can use the find_spec() method
import importlib.util

# For illustrative purposes.
package_name = 'pandas'

spec = importlib.util.find_spec(package_name)
if spec is None:
    print(package_name +" is not installed")

A: Open your command prompt type
pip3 list

A: Updated answer
A better way of doing this is:
import subprocess
import sys

reqs = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze'])
installed_packages = [r.decode().split('==')[0] for r in reqs.split()]

The result:
print(installed_packages)

[
    "Django",
    "six",
    "requests",
]

Check if requests is installed:
if 'requests' in installed_packages:
    # Do something

Why this way? Sometimes you have app name collisions. Importing from the app namespace doesn't give you the full picture of what's installed on the system.
Note, that proposed solution works:

*

*When using pip to install from PyPI or from any other alternative source (like pip install http://some.site/package-name.zip or any other archive type).

*When installing manually using python setup.py install.

*When installing from system repositories, like sudo apt install python-requests.

Cases when it might not work:

*

*When installing in development mode, like python setup.py develop.

*When installing in development mode, like pip install -e /path/to/package/source/.

Old answer
A better way of doing this is:
import pip
installed_packages = pip.get_installed_distributions()

For pip>=10.x use:
from pip._internal.utils.misc import get_installed_distributions

Why this way? Sometimes you have app name collisions. Importing from the app namespace doesn't give you the full picture of what's installed on the system.
As a result, you get a list of pkg_resources.Distribution objects. See the following as an example:
print installed_packages
[
    "Django 1.6.4 (/path-to-your-env/lib/python2.7/site-packages)",
    "six 1.6.1 (/path-to-your-env/lib/python2.7/site-packages)",
    "requests 2.5.0 (/path-to-your-env/lib/python2.7/site-packages)",
]

Make a list of it:
flat_installed_packages = [package.project_name for package in installed_packages]

[
    "Django",
    "six",
    "requests",
]

Check if requests is installed:
if 'requests' in flat_installed_packages:
    # Do something

A: As an extension of this answer:
For Python 2.*, pip show <package_name> will perform the same task.
For example pip show numpy will return the following or alike:
Name: numpy
Version: 1.11.1
Summary: NumPy: array processing for numbers, strings, records, and objects.
Home-page: http://www.numpy.org
Author: NumPy Developers
Author-email: numpy-discussion@scipy.org
License: BSD
Location: /home/***/anaconda2/lib/python2.7/site-packages
Requires:
Required-by: smop, pandas, tables, spectrum, seaborn, patsy, odo, numpy-stl, numba, nfft, netCDF4, MDAnalysis, matplotlib, h5py, GridDataFormats, dynd, datashape, Bottleneck, blaze, astropy

A: In the Terminal type
pip show some_package_name

Example
pip show matplotlib

A: You can use the pkg_resources module from setuptools. For example:
import pkg_resources

package_name = 'cool_package'
try:
    cool_package_dist_info = pkg_resources.get_distribution(package_name)
except pkg_resources.DistributionNotFound:
    print('{} not installed'.format(package_name))
else:
    print(cool_package_dist_info)

Note that there is a difference between python module and a python package. A package can contain multiple modules and module's names might not match the package name.

A: If you want to have the check from the terminal, you can run
pip3 show package_name

and if nothing is returned, the package is not installed.
If perhaps you want to automate this check, so that for example you can install it if missing, you can have the following in your bash script:
pip3 show package_name 1>/dev/null #pip for Python 2
if [ $? == 0 ]; then
   echo "Installed" #Replace with your actions
else
   echo "Not Installed" #Replace with your actions, 'pip3 install --upgrade package_name' ?
fi

A: if pip list | grep -q \^'PACKAGENAME\s'
  # installed ...
else
  # not installed ...
fi

A: You can use this:
class myError(exception):
 pass # Or do some thing like this.
try:
 import mymodule
except ImportError as e:
 raise myError("error was occurred")

A: Method 1
to search weather a package exists or not use pip3 list command
#**pip3 list** will display all the packages and **grep** command will search for a particular package
pip3 list | grep your_package_name_here

Method 2
You can use ImportError
try:
    import your_package_name
except ImportError as error:
    print(error,':( not found')

Method 3
!pip install your_package_name
import your_package_name
...
...

A: If you mean a python script, just do something like this:
Python 3.3+ use sys.modules and find_spec:
import importlib.util
import sys

# For illustrative purposes.
name = 'itertools'

if name in sys.modules:
    print(f"{name!r} already in sys.modules")
elif (spec := importlib.util.find_spec(name)) is not None:
    # If you choose to perform the actual import ...
    module = importlib.util.module_from_spec(spec)
    sys.modules[name] = module
    spec.loader.exec_module(module)
    print(f"{name!r} has been imported")
else:
    print(f"can't find the {name!r} module")

Python 3:
try:
    import mymodule
except ImportError as e:
    pass  # module doesn't exist, deal with it.

Python 2:
try:
    import mymodule
except ImportError, e:
    pass  # module doesn't exist, deal with it.

A: I'd like to add some thoughts/findings of mine to this topic.
I'm writing a script that checks all requirements for a custom made program. There are many checks with python modules too.
There's a little issue with the
try:
   import ..
except:
   ..

solution.
In my case one of the python modules called python-nmap, but you import it with import nmap and as you see the names mismatch. Therefore the test with the above solution returns a False result, and it also imports the module on hit, but maybe no need to use a lot of memory for a simple test/check.
I also found that
import pip
installed_packages = pip.get_installed_distributions()

installed_packages will have only the packages has been installed with pip.
On my system pip freeze returns over 40 python modules, while installed_packages has only 1, the one I installed manually (python-nmap).
Another solution below that I know it may not relevant to the question, but I think it's a good practice to keep the test function separate from the one that performs the install it might be useful for some.
The solution that worked for me. It based on this answer How to check if a python module exists without importing it
from imp import find_module

def checkPythonmod(mod):
    try:
        op = find_module(mod)
        return True
    except ImportError:
        return False

NOTE: this solution can't find the module by the name python-nmap too, I have to use nmap instead (easy to live with) but in this case the module won't be loaded to the memory whatsoever.

A: I would like to comment to @ice.nicer reply but I cannot, so ...
My observations is that packages with dashes are saved with underscores, not only with dots as pointed out by @dwich comment
For example, you do pip3 install sphinx-rtd-theme, but:

*

*importlib.util.find_spec(sphinx_rtd_theme) returns an Object

*importlib.util.find_spec(sphinx-rtd-theme) returns None

*importlib.util.find_spec(sphinx.rtd.theme) raises ModuleNotFoundError

Moreover, some names are totally changed.
For example, you do pip3 install pyyaml but it is saved simply as yaml
I am using python3.8

A: If you'd like your script to install missing packages and continue, you could do something like this (on example of 'krbV' module in 'python-krbV' package):
import pip
import sys

for m, pkg in [('krbV', 'python-krbV')]:
    try:
        setattr(sys.modules[__name__], m, __import__(m))
    except ImportError:
        pip.main(['install', pkg])
        setattr(sys.modules[__name__], m, __import__(m))

A: A quick way is to use python command line tool.
Simply type import <your module name>
You see an error if module is missing.
$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
>>> import sys
>>> import jocker
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named jocker
$

A: Hmmm ... the closest I saw to a convenient answer was using the command line to try the import. But I prefer to even avoid that.
How about 'pip freeze | grep pkgname'? I tried it and it works well. It also shows you the version it has and whether it is installed under version control (install) or editable (develop).

A: I've always used pylibcheck to check if a lib is installed or not, simply download it by doing pip install pylibcheck and the could could be like this
import pylibcheck

if not pylibcheck.checkPackage("mypackage"):
     #not installed

it also supports tuples and lists so you can check multiple packages and if they are installed or not
import pylibcheck

packages = ["package1", "package2", "package3"]

if pylibcheck.checkPackage(packages):
     #not installed

you can also install libs with it if you want to do that, recommend you check the official pypi

A: The top voted solution which uses techniques like importlib.util.find_spec and sys.modules and catching import exceptions works for most packages but fails in some edge cases (such as the beautifulsoup package) where the package name used in imports is somewhat different (bs4 in this case) than the one used in setup file configuration. For these edge cases, this solution doesn't work unless you pass the package name used in imports instead of the one used in requirements.txt or pip installations.
For my use case, I needed to write a package checker that checks installed packages based on requirements.txt, so this solution didn't work. What I ended up using was subprocess.check to call the pip module explicitly to check for the package installation:
import subprocess

for pkg in packages:
    try:
        subprocess.check_output('py -m pip show ' + pkg)
    except subprocess.CalledProcessError as ex:
        not_found.append(pkg)

It's a bit slower than the other methods but more reliable and handles the edge cases.

A: Go option #2.  If ImportError is thrown, then the package is not installed (or not in sys.path).

A: Is there any chance to use the snippets given below? When I run this code, it returns "module  pandas  is not installed"
a = "pandas"

try:
    import a
    print("module ",a," is installed")
except ModuleNotFoundError:
    print("module ",a," is not installed")

But when I run the code given below:
try:
    import pandas
    print("module is installed")
except ModuleNotFoundError:
    print("module is not installed")

It returns "module pandas is installed".
What is the difference between them?


text:
Q: What are the eigenvalues and eigenvectors of $A^2 - 3A + 4I$, given the eigenvalues and eigenvectors of $A$?
Let eigenvalues of $2 \times 2$ matrix $A$ be $1,-2$ and eigenvectors be $x_1$ & $x_2$ respectively. Then eigenvalues and eigenvectors of $A^2-3A+4I$ would be?

We know that eigenvalues can be calculated by substituting in the equation of new matrix. But what is the relation of eigenvectors with new matrix in such cases?

A: Hint: if $A v = \lambda v$, and $P$ is a polynomial, then $P(A) v = P(\lambda) v$.

A: The eigenvectors stay the same. For convenience take the eigenvalue 1 and eigenvector x1. Then,
((A^2) - 3A + 4I) .x1=((1) ^2)x1 - 3.(1.x1)+ 4 (x1) =2.x1. Similarly the others.


text:
Q: How to group records based on a child record in Amazon Quicksight Is there any way to categorise an aggregated record in Amazon Quicksight based on the records being aggregated?
I'm trying to build a pivot table an Amazon Quicksight to pull out counts of various records split down by what state the record is in limited to a date range where the record first had activity.
This is all being done in SPICE since the raw data is CSV files in S3. The two CSV files are:
Student

*

*Id: String

*Current State: One of pass / fail

*Department: String

Test

*

*Id: String

*Student Id: String

*DateOfTest: DateTime

*State: One of pass / fail
The pivot table I'm trying to build would have a row for each department and 3 columns:

*

*fail - Count of students in the department where the current state is fail

*pass-never-failed - Count of students in the department where the current state is pass and there are no failed tests for the Student

*pass-failed-some - Count of students in the department where the current state is pass and there is at least one failed test

To do this I've created a dataset that contains Student joined to Test. I can then create a Pivot table with:

*

*Row: Department

*Column: Current State

*Value: Count Distinct(Id[Student])
I thought I'd be able to create a calculated field to give me the three categories and use that in place of Current State using the following calculation:
ifelse(
    {Current State} = 'pass',

    ifelse(
        countIf({Id[Test]}, {State} = 'fail') = 0,
        'pass-never-failed',
        'pass-failed-some'
    ),

    {Current State}
)

But that shows invalid with the following error:
Mismatched aggregation. Custom aggregations can't contain both aggregate "`COUNT`" and non-aggregated fields "COUNT(CASE WHEN "State" = _UTF16'fail' THEN "Id[Test]" ELSE NULL END)", in any combination.

Is there any way to categories the Students based on an aggregation of the Tests in quicksight or do I have to pre-calculate this information in the source data?
I've been able to workaround this for now by defining three separate calculations for the three columns and adding these as values in the quicksight pivot rather than setting a column dimension at all.
Count Passed Never Failed
distinct_countIf({Id[Student]}, maxOver(
    ifelse({State[Test]} = 'fail' AND {Current State[Student]} = 'pass',
        1, 0)
, [{Id[Student]}], PRE_AGG) = 0)

Count Passed Failed Some
distinct_countIf({Id[Student]}, maxOver(
    ifelse({State[Test]} = 'fail' AND {Current State[Student]} = 'pass',
        1, 0)
, [{Id[Student]}], PRE_AGG) > 0)

Count Failed
distinct_countIf({Id[Student]}, {Current State[Student]} = 'fail')

This works, but I'd still like to know if it's possible to build a dimension that I could use for this as it would be more flexible if new states are added without the special handling of pass.


text:
Q: I have some tables in my db and i want to delete this on click button which i select on the option tag I have some tables in my db and i want to delete this on click button which i
       select on the option tag
    <?php
  $db = mysqli_connect('localhost','root','','post15');
  if (isset($_POST['submit2'])) {
  $query = $db->query("DELETE FROM posted WHERE title");
  if ($query) {
    echo "Post DELETED";
  }

 }?>
  <form method="post" action="admin.php">
     <select name="categoryBox">

            <?php
                 $query = $db->query("SELECT * FROM posted");
                    while ($row = $query->fetch_object()){
                        echo "<option value='".$row->id."'>".$row->title."
              </option>";
                    }
            ?>

            </select>
        <input type="submit" name="submit2">
    </form>

A: The code you provided will not work, you are trying to delete using a title but your drop-down option values are id's not titles therefore you should look at deleting the id of the selected title
 if (isset($_POST['submit2'])) {
  $query = $db->prepare("DELETE FROM posted WHERE id = ? ");
  $query->bind_param("i",$_POST['categoryBox']);
  if ($query->execute()) {
    echo "Post DELETED";
  }

A: Try like this one.
  <form method="post">
Id: < input type="text" name="id">
<input  type="submit" value="submit">
</form>
<?php
$_POST['id']
$db=mysql_connect("localhost","root","");
mysql_select_db("post15",$db);
mysql_query("DELETE FROM posted WHERE id=$id",$db);
echo"ID ".$_POST['id']." has been Deleted ";
?>


text:
Q: scaling a CCMenuItem in Cocos2d (Objective-C) I'm trying to make a CCMenuItem that has scaled images. For example, I tried:
CCSprite* normalSprite = [CCSprite spriteWithFile:@"button_play.png"];
CCSprite* selectedSprite = [CCSprite spriteWithFile:@"button_play.png"];
selectedSprite.scale = 1.2;

CCMenuItem menuItem = [CCMenuItemSprite
                       itemFromNormalSprite:normalSprite
                       selectedSprite:selectedSprite
                       target:self
                       selector:@selector(onPlay:)];

But it looks like CCMenuItemSprite ignores the scale of the underlying sprites. Is there a way to do this (aside from just creating scaled versions of the underlying images)? Thanks.

A: Thyrgle is correct about how CCMenuItem works.
However, there certainly is a way to do what you want.  All you need to do is subclass CCMenuItem and override the selected and unselected methods to achieve what you want.  In fact, I'm pretty sure you could just cut and paste the code from CCMenuItemLabel, because scaling the item to 1.2 is exactly what it does.  (In fact, it does it better, since it animates the scale change.)
-(void) selected
{
    // subclass to change the default action
    if(isEnabled_) {
        [super selected];
        [self stopActionByTag:kZoomActionTag];
        CCAction *zoomAction = [CCScaleTo actionWithDuration:0.1f scale:1.2f];
        zoomAction.tag = kZoomActionTag;
        [self runAction:zoomAction];
    }
}

-(void) unselected
{
    // subclass to change the default action
    if(isEnabled_) {
        [super unselected];
        [self stopActionByTag:kZoomActionTag];
        CCAction *zoomAction = [CCScaleTo actionWithDuration:0.1f scale:1.0f];
        zoomAction.tag = kZoomActionTag;
        [self runAction:zoomAction];
    }
}

A: CCMenuItemImage Class is also available for displaying image with its scale in CCMenu.Please Check this link http://www.cocos2d-iphone.org/forum/topic/8310
[mainMenu alignItemsVerticallyWithPadding:15.0f];

A: No there is not another way. The thing is that menuItem is only acknowledging the files part of the sprites. It is not looking at other properties such as the scale property.


text:
Q: E: Unable to locate package handbrake-cli I am trying to install handbrake on my raspberry pi 3 running Ubuntu 18.04.3 LTS (GNU/Linux 4.15.0-1041-raspi2 aarch64).
I keep trying all kinds of ways to install handbrake onto my pi, but everything is to no avail. The internet seems to have a consensus on doing it the following way below, but I keep getting the error E: Unable to locate package handbrake-cli. what does this mean?
sudo apt-get install handbrake-cli

Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package handbrake-cli

A: On Ubuntu platforms, there is an official HandBrake PPA, and thus you can install HandBrake directly from the PPA as follows.
$ sudo add-apt-repository ppa:stebbins/handbrake-releases
$ sudo apt-get update
$ sudo apt-get install handbrake-gtk handbrake-cli


text:
Q: Is ther a Join function in vba to combine multiple fields rather than using concatenate function in access? Thank you to all your responses.
I have a table with one id field and R1-R30 fields.
I was able to concatenate R1-R30 fields in a query using
Route: Trim([R1] & IIf([R2]="","","   ") & [R2] & IIf([R3]="","","   ") & [R3] & IIf([R4]="","","   ") & [R4] & IIf([R5]="","","   ") & [R5] & IIf([R6]="","","   ") & [R6] & IIf([R7]="","","   ") & [R7] & IIf([R8]="","","   ") & [R8] & IIf([R9]="","","   ") & [R9] & IIf([R10]="","","   ") & [R10] & IIf([R11]="","","  ") & [R11] & IIf([R12]="","","   ") & [R12] & IIf([R13]="","","   ") & [R13] & IIf([R14]="","","   ") & [R14] & IIf([R15]="","","   ") & [R15] & IIf([R16]="","","   ") & [R16] & IIf([R17]="","","   ") & [R17] & IIf([R18]="","","   ") & [R18] & IIf([R19]="","","   ") & [R19] & IIf([R20]="","","   ") & [R20] & IIf([R21]="","","   ") & [R21] & IIf([R22]="","","   ") & [R22] & IIf([R23]="","","   ") & [R23] & IIf([R24]="","","   ") & [R24] & IIf([R25]="","","   ") & [R25] & IIf([R26]="","","   ") & [R26] & IIf([R27]="","","   ") & [R27] & IIf([R28]="","","   ") & [R28] & IIf([R29]="","","   ") & [R29] & IIf([R30]="","","   ") & [R30])

My question is if the Join function I found can be applied to a query where the delimeter could be a spare, comma or slash.
Join (source_array,[delimiter])
Thanks

A: This would be the code to take all values of 1 single recordset into a bidimensional array, and then take those values into a unidimensional array (excluding null values, because null values cannot be joined with JOIN).
I think it would be better just looping trough every field with the loop, but in case it might help, i'll post it.
To replicate your issue, I just created a database with 1 single table with 2 records:

I'll concatenate all fields, excluding ID field. So with an easy query, I can get a recordset of 1 single record, using ID field as parameter:
SELECT Tabla1.Field1, Tabla1.Field2, Tabla1.Field3, Tabla1.Field4
FROM Tabla1
WHERE (((Tabla1.Id)=1));

And then the VBA code to Msgbox the fields joined, using a comma as delimiter.
Sub JOIN_RST()
Dim rst As Recordset

Dim vArray As Variant
Dim SingleArray() As Variant

Dim i As Long

Dim MySQL As String
Dim STRJoined As String

MySQL = "SELECT Tabla1.Field1, Tabla1.Field2, Tabla1.Field3, Tabla1.Field4 " & _
    "FROM Tabla1 WHERE (((Tabla1.Id)=2));" 'query to get a single recordset.

Set rst = Application.CurrentDb.OpenRecordset(MySQL, 2, 4)
DoEvents

If rst.RecordCount > 0 Then
    rst.MoveLast
    rst.MoveFirst
    vArray = rst.GetRows
    ReDim SingleArray(UBound(vArray))

    For i = 0 To UBound(SingleArray)
        If IsNull(vArray(i, 0)) = True Then
            SingleArray(i) = ""
        Else
            SingleArray(i) = vArray(i, 0)
        End If
    Next i

    Debug.Print vArray(0, 0) 'Field 1
    Debug.Print vArray(1, 0) 'Field 2
    Debug.Print vArray(2, 0) 'Field 3
    Debug.Print vArray(3, 0) 'Field 4

    STRJoined = Join(SingleArray, ",")

    Debug.Print STRJoined
End If

Set rst = Nothing
Erase vArray
Erase SingleArray
DoEvents

End Sub

If I execute this code using as WHERE parameter ID=1 , in debugger Window I get:
First Record
 1
Null
My first record. Got a null value in Field 3 (it's empty)
First Record,1,,My first record. Got a null value in Field 3 (it's empty)

With ID=2 I get:
Second Record
 2
Not null
Second Record
Second Record,2,Not null,Second Record

So this kinda works. I hope you can adapt it to your needs. but as i said. looking at the code, I think it would be easier just looping trough fields in a single query with all records. something like this:
Sub LOOPING_TROUGHT_FIELDS()
Dim RST As Recordset
Dim Joined_Records() As Variant
Dim i As Long
Dim MySQL As String
Dim STRJoined As String

Dim FLD As Field

MySQL = "SELECT Tabla1.Field1, Tabla1.Field2, Tabla1.Field3, Tabla1.Field4 " & _
    "FROM Tabla1;" 'query to get all recordset you want to join
Set RST = Application.CurrentDb.OpenRecordset(MySQL, 2, 4)
DoEvents

If RST.RecordCount > 0 Then
    RST.MoveLast
    RST.MoveFirst

    i = 0
    ReDim Joined_Records(RST.RecordCount)

    Do Until RST.EOF = True
        For Each FLD In RST.Fields
            If IsNull(FLD.Value) = True Then
                STRJoined = STRJoined & "" & ","
            Else
                STRJoined = STRJoined & FLD.Value & ","
            End If

        Next FLD
        Joined_Records(i) = Left(STRJoined, Len(STRJoined) - 1) 'we get 1 minus because there is an extra comma at end
        i = i + 1
        STRJoined = ""
        RST.MoveNext
    Loop

End If

Set RST = Nothing
Set FLD = Nothing

For i = 0 To UBound(Joined_Records) Step 1
    Debug.Print Joined_Records(i)
Next i

Erase Joined_Records

End Sub

I don't know how many records you got. Try both and check how long does each option takes, and then choose 1.
Hope you can adapt all this to your needs. Welcome to SO.


text:
Q: ESP32 trouble receiving broadcast UDP packets (ESP IDF) I'm attempting to configure a number of connected ESP32 stations via a single ESP32 AP. The easiest way for me to do this would be to send a single broadcast UDP packet to 255.255.255.255. However, my stations which are listening with an open UDP port are not receiving broadcast data at all. Is there something else I need to configure on the station/AP for this to be possible?
I've done a bit of reading and it seems like lwip/opt.h may have been prohibiting detecting broadcast packets, but after setting IP_SOF_BROADCAST and IP_SOF_BROADCAST_RECV I've seen no difference.
Here's my current station UDP listening task:
static void udp_listen_task(void *pvParameters)
{

    while (1) {

        struct sockaddr_in dest_addr;
        dest_addr.sin_addr.s_addr = htonl(INADDR_ANY);
        dest_addr.sin_family = AF_INET;
        dest_addr.sin_port = htons(PORT);
        int addr_family = AF_INET;
        int ip_protocol = IPPROTO_IP;
        inet_ntoa_r(dest_addr.sin_addr, addr_str, sizeof(addr_str) - 1);

        int sock = socket(addr_family, SOCK_DGRAM, ip_protocol);
        if (sock < 0) {
            ESP_LOGE(TAG, "Unable to create socket: errno %d", errno);
            break;
        }
        //ESP_LOGI(TAG, "Socket created");

        int err = bind(sock, (struct sockaddr *)&dest_addr, sizeof(dest_addr));
        if (err < 0) {
            ESP_LOGE(TAG, "Socket unable to bind: err %d", err);
        }

        while (1) {

            struct sockaddr_in6 source_addr;
            socklen_t socklen = sizeof(source_addr);
            int len = recvfrom(sock, &controller_msg, sizeof(controller_msg), 0, (struct sockaddr *)&source_addr, &socklen);

            //Error occurred during receiving
            if (len < 0) {
                ESP_LOGE(TAG, "recvfrom failed: errno %d", errno);
                break;
            }
            // Data received
            else {

                // Get the sender's ip address as string
                if (source_addr.sin6_family == PF_INET) {
                    inet_ntoa_r(((struct sockaddr_in *)&source_addr)->sin_addr.s_addr, addr_str, sizeof(addr_str) - 1);
                } else if (source_addr.sin6_family == PF_INET6) {
                    inet6_ntoa_r(source_addr.sin6_addr, addr_str, sizeof(addr_str) - 1);
                }

                // Post event to act on message
                xEventGroupSetBits(conn_evt, CONN_EVT_UDP_RECEIVED);

            }
        }

        if (sock != -1) {
            ESP_LOGE(TAG, "Shutting down socket and restarting...");
            shutdown(sock, 0);
            close(sock);
        }
    }
    vTaskDelete(NULL);
}

A: Looks like your listening socket is missing the SO_BROADCAST option. You need something like this after creating the socket:
int bc = 1;
if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &bc, sizeof(bc)) < 0) {
    ESP_LOGE(TAG, "Failed to set sock options: errno %d", errno);
    closesocket(sock);
    break;
}

Have a look at this example
Hint: if this doesn't help, then perhaps you also need a quick check to verify that the sender is actually broadcasting. Hook a computer to the same WiFi network and run WireShark to see the UDP packets in the air.


text:
Q: Apache: Why on IE .htaccess rewrites non Latin character URLs to urlencode? How to solve it? Apache: Why on IE .htaccess rewrites non Latin character URLs to urlencode? How to solve it?
domain.com//контакты rewrites to domain.com/%D0%BA%D0%BE%D0%BD%D1%82%D0%B0%D0%BA%D1%82%D1%8B
RewriteEngine On
# Rewrite multiple slashes with single slash after domain
RewriteCond %{THE_REQUEST} ^[A-Z]+\s//+(.*)\sHTTP/[0-9.]+$ [OR]
RewriteCond %{THE_REQUEST} ^[A-Z]+\s(.*/)/+\sHTTP/[0-9.]+$
RewriteRule .* http://%{HTTP_HOST}/%1 [R=301,NE,L]

A: Seems there still are no solution for IE and it depends of browser address-bar encoding.
Like Chrome 12 shows UTF-8 url domain.com/контакты, but on Ctr+C, Ctr+P you will get Unicode url http://domain.com/%D0%BA%D0%BE%D0%BD%D1%82%D0%B0%D0%BA%D1%82%D1%8B

A:
@Pekka: Yes. On newest browsers any URLs has UTF-8 encoding. And they rewrites domain.com//контакты to domain.com/контакты, like it is excepted to be.

As far as I know, this is not entirely correct and this may be the reason why it doesn't work for you.
What new browsers are really doing is they show you the URL in its native form контакты, but internally still make the request in percent encoded form.
This seems to be the crux: You type something in, IE recognizes the Unicode characters, but the subsequent 301 redirect leads to a (correct) percent encoded URL. A modern browser will automatically "decode" the percent encoded URL; IE and older browsers might not.
I don't know whether there is a workaround for this. One thing you could try is have a PHP script do the URL rewriting, and have that script redirect to the (however invalid!) URLDecoded URL:
<?php header("location: http://example.com/контакты"); ?>

I have no idea whether this'll work, though.
Reference: Unicode characters in URLs
Related IE setting


text:
Q: Google Play Music way too fast, accelerated I turn to Google Play to listen to my mp3's most of the time.  lately, on my desktop, they are accelerated when I'm using Google Play, through chrome.  They sound like chipmunks!
If I play the mp3's on my hard disk through movie player, they play at the correct speed.  Any idea why this is?

A: Having the same issue using the latest Chromium on Ubuntu 13.04
Changing back to Flash from HTML5 solved the issue for me.
Super obnoxious though and I would love to use HTML5 instead.

A: fixed in an automatic update using the ubuntu updater.


text:
Q: How to do mutual tls authentication in C# I have my desktop application. I would like to send post request to server URL using mutual authentication in C#. I have written following code:
System::Net::ServicePointManager::SecurityProtocol = SecurityProtocolType::Tls12;
WebRequestHandler ^ clientHandler = gcnew WebRequestHandler();
X509Certificates::X509Certificate2^ modCert = gcnew X509Certificates::X509Certificate2("Dev.pfx", "test");
clientHandler->ClientCertificates->Add(cerInter);
clientHandler->AuthenticationLevel = System::Net::Security::AuthenticationLevel::MutualAuthRequested;
clientHandler->ClientCertificateOptions = ClientCertificateOption::Manual;
httpClient = gcnew HttpClient(clientHandler);
HttpContent ^ httpContent = gcnew ByteArrayContent(state->postBody);
httpContent->Headers->ContentType = gcnew MediaTypeHeaderValue("application/octet-stream");
resultTask = httpClient->PostAsync(state->httpRequest, httpContent);

Now post request is throwing exception that it is connection is forcefully closed by remote host. I have used wireshark and it shows that client certificate in client response is of zero length. Even if I don't add any certificate in WebRequestHandler, I get the same response. Can someone please help me to solve this issue or guide me for possible solutions.

EDIT
Hi All, I have found the issue. I have to set client certificate in local store.
X509Certificates::X509Store store(X509Certificates::StoreName::Root, X509Certificates::StoreLocation::LocalMachine);
store.Ostore. Openrtificates::OpenFlags::ReadWrite);
store. Add(cerInter);

However, I am facing the issue that if I don't run my application as administrator, then it throws access right exception.
If I use StoreLocation::CurrentUser, it pop up message for approval.
Can someone please suggests, how can I Use it with StoreLocation::CurrentUser without prompting the message?
Besides it, I will really appreciate if someone can suggests, if this is the right approach?

A: By Windows' design, you cannot add certificates to the per-user store without a prompt. You can add certificates to the Local Machine store, but only when running with Administrative rights.
You should only need to add the certificate to the user's store once (e.g. during first run or setup).


text:
Q: Как выровнять вложенные листы относительно внешних? Как в латехе выровнять внутренние листы относительно внешних? Т.е. чтобы чёрточки второго itemize были на уровне текста первого?
\begin{itemize}
  \item 1
  \begin{itemize}
    \item 2
  \end{itemize}
\end{itemize}

A: Надо добавить [left=0ex] во вложенный itemize.


text:
Q: extjs 4 dynamic store I must to update some label that takes data from a store. I must load into the store new data for ex. each 10 seconds.
It's easy - use setInternal() (because TaskRunner isn't work o_0)_ and call the store.load event.
But my task much more specific.
I also have a grid that contains of two columns and takes some data from the store and some data is custom.
It means that before columns with a clear store dataindexes there are a few new records in a store with custom string data and some numeric data...
It's may be hard to explain by word, but in code it looks so:
//---Store---
Ext.define('App.store.Data', {
    extend: 'Ext.data.Store',
    autoLoad: false,
    storeId:'Data',
    model: 'App.model.DataModel',
    proxy   : {
    type    : 'ajax',
    url: 'http://mybackend',
    reader: {
        type: 'json'
    }
    },
    data:[first = true],
    listeners:{
        load: function()
        {
            if(first){
            first=false;
            myApp.getController('App.controller.Controller').StoreLoadHandler();
            setInterval(function (){myApp.getController('App.controller.Controller').StoreLoadHandler();},10000);
            }

        }
    }
});
//---Controller---
StoreLoadHandler: function(){
    var store = this.getStore('Data');
    //upload data from base into store
    store.reload();
    store.add(
            [
                {
                    fio: 'somedata',
                    //calculate some data and write it into store. All dataindexes are existsin model
                    operCount: parseInt(this.getStore('Data').first().get('isQuick')),
                    opersvod: (this.getStore('Data').first().get('opersvod')),
                    isQuick:parseInt(this.getStore('Data').first().get('isQuick')),
                    ipk: (this.getStore('Data').first().get('ipk')),
                    allCount: (this.getStore('Data').first().get('allCount')),
                    id: 0
                },
                {
                    fio:
                    ...
                    id: 1
                },
                {
                    fio:
                    ...
                    id: 2
                }
            ]
        );

       //takes my labels and use setText, works brilliant
    Ext.ComponentQuery.query('#TopPanel')[0].items.getAt(0).items.get('inW').setText(this.StoreCalc('iw'));
    Ext.ComponentQuery.query('#TopPanel')[0].items.getAt(1).items.get('isClose').setText(this.StoreCalc('isClose'));
    Ext.ComponentQuery.query('#TopPanel')[0].items.getAt(2).items.get('denied').setText(this.StoreCalc('denied'));
    Ext.ComponentQuery.query('#BottomPanel')[0].items.getAt(0).items.get('allCount').setText(store.getAt(3).get('allCount'));

    //use sort
    store.sort([
    {
        property : 'id',
        direction: 'ASC'
    },
    {
        property : 'fio',
        direction: 'ASK'//'DESC'
    }
    ]);
    store.destroy();
    }

In this case when I call a store.load() method or store.reload() my custom records in store are lost.
If I delete this operation from listing my custom data is saves and render in grid with 2 columns (dataindexes are - 'fio' and 'operCount')...
Where problem is?

A: It looks like you calling add method with no data in store. Use callback option of reload method:
store.reload({callback: function() {
          store.add(...);
  }
})

Note: do not configure reloading timer from load method - it's bad for understanding


text:
Q: Autodesk Forge: WorkItem failing due to AppPackage Issues My AppPackage fails to load, and I'm unable to find the exact answer in the documentation or by the error message/code.
I tested the bundle by unzipping it into the "C:\Program Files\Autodesk\ApplicationPlugins" on my local machine, and it runs/loads as expected.
The AppPackage indicates that it is created successfully, which I'm sure is the most up-to-date version.
The addin is a .NET DLL file.
Error Report Message
[02/15/2019 18:44:48] Starting work item ffbcfc1ca50546fc9a6372424b2cdae1
[02/15/2019 18:44:48] Start download phase.
[02/15/2019 18:44:48] Start downloading file <CENSORED>.
[02/15/2019 18:44:48] Start preparing AppPackage <CENSORED>.
[02/15/2019 18:44:48] Download bits and install app to local cache.
[02/15/2019 18:44:48] End downloading file <CENSORED>.
[02/15/2019 18:44:48] End download phase.
[02/15/2019 18:44:48] Error: Failed to prepare app package(s).
[02/15/2019 18:44:48] Error: An unexpected error happened during phase Downloading of job.
[02/15/2019 18:44:48] Job finished with result FailedEnvironmentSetup

PackageContents.XML
<?xml version="1.0" encoding="utf-8" ?>
<ApplicationPackage SchemaVersion="1.0" AutodeskProduct="AutoCAD"
                    AppVersion="0.1.0"
                    ProductType="Application"
                    Name="CENSORED"
                    Description="CENSORED"
                    Author="CENSORED"
                    FriendlyVersion="0.1.0"
                    ProductCode="{CENSORED}"
                    UpgradeCode="{CENSORED}"
                    Helpfile="./help.html"
                    Icon="./my-icon.jpeg">

    <CompanyDetails Name="CENSORED" Phone="CENSORED" Email="CENSORED"/>

    <Components>
        <RuntimeRequirements SeriesMin="R22.0" Platform="AutoCAD*" OS="Win64"/>

        <ComponentEntry AppName="CENSORED" Version="0.1.0" ModuleName="./CENSORED.dll" AppType=".Net"
                        AppDescription="CENSORED" LoadOnAutoCADStartup="True">
        </ComponentEntry>
    </Components>

</ApplicationPackage>

Activity Definition:
Note I had to manually expand some inline functions here, since I have this broken into multiple parts.  If I have a typo, rest assured the code actually runs syntactically.
let activity = <CreateActivityRequest>{
            Id: id,
            Version: 1,
            IsPublic: false,
            AppPackages: ['PACKAGE_NAME'],
            Instruction: {Script: 'D6 '},
            RequiredEngineVersion: '22.0',
            Parameters: {
                InputParameters: [{Name: 'HostDwg', LocalFileName: '$(HostDwg)'}],
                OutputParameters: [{Name: 'output', LocalFileName: `output.json`}]
            },
            HostApplication: undefined,
            AllowedChildProcesses: []
        };

Entry from AppPackages Listing:
{
  References: [],
  Resource: '...',
  RequiredEngineVersion: '22.0',
  IsPublic: false,
  IsObjectEnabler: false,
  Version: 1,
  Timestamp: '2019-02-15T19:32:33.527Z',
  Description: '',
  Id: 'CENSORED'
},

A: Make sure to double check how you zipped the AppPackage you uploaded.  If you look inside your zip file, make sure you have a folder with the name PACKAGE_NAME.bundle and the PackageContents.XML file is inside that PACKAGE_NAME.bundle folder.


text:
Q: Programatically import custom fields using wp all import I have a csv with a lot of custom fields that I need to import. It would take too much time to manually set up the fields using the interface and it also is not very client friendly to ask them to make sure the values match up. Many of the values must also be mapped from the csv to a different value in the custom field in WordPress.

A: WP All Import has a lot of undocumented features in the various hooks, actions and filters implemented in the code. The easiest way to do such a mapping is to add a filter to the pmxi_options_options and add custom rules. These rules will show up under the Custom Fields accordion during the import configuration step.
<?php
add_filter( 'pmxi_options_options', function( $options ) {
  // Match the desired custom post type
  if ( $options['custom_type'] != 'product' ) {
    return $options;
  }
  // Configure the custom fields
  $options['custom_name']['custom_field_name'] = '_custom_field_name';
  $options['custom_value']['custom_field_name'] = '{csv_column[1]}';
  $options['custom_mapping_rules']['custom_field_name'] = json_encode( [
    'value_from_csv' => 'value_to_custom_field',
    'en' => 'English',
  ] );
  return $options;
} );


text:
Q: ¿Cómo puedo sumar las entradas de un solo input con Keyup? Estoy intentado sumar todo lo que trae un input, es decir por cada numero
que pongo en el input tiene que sumar, sin embargo no puedo lograrlo,
dentro del keyup mando a llamar la función para sumar.
Muestro mi código

$.fn.delayPasteKeyUp = function(fn, ms)
{
    var timer = 0;
    $(this).on("propertychange input", function()
    {
        clearTimeout(timer);
        timer = setTimeout(fn, ms);
    });
};

$(document).ready(function()
{
  $("#ingreso").delayPasteKeyUp(function(){
   $("#respuesta").append("Producto registrado: "+ $("#ingreso").val() +"
");
    $("#ingreso").val("");
}, 200);
sumar();
});

function sumar()
{
  const $total = document.getElementById('total');
  let subtotal = 0;
  [ ...document.getElementsByClassName( "ingreso" ) ].forEach( function ( element ) {
    if(element.value !== '') {
      subtotal += parseFloat(element.value);
    }
  });
  $total.value = subtotal;
}

<input type="text" name="delay" id="ingreso" class="itemTotalNeto" autofocus onchange="sumar();">

TOTAL
<input type="number" id="total" value="0" readonly/>

buena tarde amigos.
Estoy intentado sumar todo lo que trae un input, es decir por cada numero
que pongo en el input tiene que sumar, sin embargo no puedo lograrlo,
dentro del keyup mando a llamar la función para sumar.
Muestro mi código

A: Esta es mi propuesta para resolver tu problema, a ver que te parece:

$("#ingreso").on("propertychange input", function() {
  sumar();
  $("#respuesta").append("Producto registrado: " + $(this).val() + "
");
  $(this).val("");
});

function sumar() {
  const total = document.getElementById('total');
  $("#total").val(parseFloat($("#total").val()) + parseFloat($("#ingreso").val()))
}

<input type="text" name="delay" id="ingreso" class="itemTotalNeto" autofocus>

TOTAL
<input type="number" id="total" value="0" readonly/>

Como ves, he reducido tu código a la mínima expresión, porque tenias cosas que sobraban para realizar esta tarea más específica.
Explicación de los cambios:

*

*He cambiado el orden de la función sumar() y lo he puesto al principio despues de llamar al evento propertychange input del campo con id ingreso porque si lo dejaba donde estaba su valor era 0, pues en tu código eliminabas su value antes de llamar a la suma.

*He usado $(this) en lugar de $(#ingreso) dentro de la captura del evento para dejarlo más limpio y claro. No hacia falta tanta redundancia cuando el $(this) ya representa al objeto llamado dentro de la función.

*He reducido la función sumar() a la minima expresión, dejando el sumatorio deseado en esta línea:

$("#total").val(parseFloat($("#total").val()) + parseFloat($("#ingreso").val()))

La cual asigna al elemento total el valor resultante de sumar su valor actual (parseFloat($("#total").val())) al nuevo valor contenido en el elemento con el id ingreso (parseFloat($("#ingreso").val()).
Comprueba si te funciona como esperabas pulsando sobre ejecutar y agregando números al input y nos cuentas.


text:
Q: how to get sum of the numbers in for loop laravel I have a loop where each step I get the price of the day. Now I want to get the sum of all days and show them to the user. Here is my attempt below:
for ($f = 0; $f < count($room_ids); $f++) {
    $data = Price::whereIn('id',$room_ids)
        ->whereDate('from_date', '<', $from_date)
        ->whereDate('to_date', '>   ', $to_date)
        ->orderBy('created_at', 'asc')
        ->take(1)
        ->get();
//    $sum_price += array_sum($data[$f]->sales_price)
//or this one
//    $sum_price += $data[$f];
    $data_array[] = $data[$f]->sales_price.'======'.$dates[$i].'==============' ;
}

but each time I get the price for 1 day and don't get the sum of all days. How can I achieve that?

A: You can use sum function in Laravel Eloquent. Please check here for detail.
$sum_price = 0;
$data = Price::
      whereIn('id',$room_ids)
      ->whereDate('from_date', '<', $from_date)
      ->whereDate('to_date', '>   ', $to_date)
      ->orderBy('created_at', 'asc')
       ->sum('price');
$sum_price = $data[0];
echo $sum_price; // This will give you total price.

A: $sum_price = 0;
$data = Price::
      where`enter code here`In('id',$room_ids)
      ->whereDate('from_date', '<', $from_date)
      ->whereDate('to_date', '>   ', $to_date)
      ->orderBy('created_at', 'asc')
       ->sum('price');
$sum_price = $data[0];
echo $sum_price;

A: Your code is very confusing and doesn't make much sense.
For example why you are using a for loop? your query will always return the same result, so whats the point of the loop?
what is $i?
Since your query always returns one result ->take(1) so only $data[0] will have a value, what is $data[$f] supposed to return for example $data[1], $data[2] etc.
You could just sum the prices with the query builder
$sum = Price::whereIn('id', $room_ids)
    ->whereDate('from_date', '<', $from_date)
    ->whereDate('to_date', '>', $to_date)
    ->orderBy('created_at', 'asc')
    ->sum('sales_price');

A: Try This:
$sum_price[] = $data[$f]->sales_price;
// here use this and outside of your loop do an array sum
$sum = array_sum($sum_price);


text:
Q: Star schema with both many-to-many relations and inheritance The problem
I am trying to make a star schema of the following situation, concerning transactions on a stock market. I have summarized the scenario here:

*

*Each transaction traded on the market has

*

*1 or more buyers, which can either be a person or a venue

*1 or more sellers, which can either be a person or a venue

The attempt
I have tried looking up best practices on modelling many to many relationships and inheritance in a star schema, and combined these. This gives me the following star schema
Type       Name                   Description
Fact       Transaction            Fact containing all transaction details
Dim        EntityGroup            Groupings of entities (just there to make a complete model - no attributes)
Dim        Entity                 Superclass of all entities (just there to make a complete model - no attributes)
Bridge     EntityGroup_Entity     Bridge for the many-to-many relationship between entities and groups
Dim        Person                 Subclass of entities, holding all attributes of persons (shares the primary key with Dim Entity)
Dim        Venue                  Subclass of entities, holding all attributes of venues

The question
Am i right that this would be best practice for a star schema, or can you point out any places the design is faulty?


text:
Q: Android - How to stop background image to extend into the titlebar? Folks,
I just created a new Android application. In the main activity, I specified a background image.
<FrameLayout
    ...
    android:background="@drawable/mypic">

</FrameLayout>

Within eclipse, in the graphical layout view, this looks fine. I see a title bar at the top and the rest of the screen is occupied by the background image.
However, when I run this on the device, I see that the background image extends all the way into the title bar.
I would like the title bar to stay as is, that is, with the default black background. Is there a setting I can change somewhere?
I suspect it has something to do with the default generated style "FullScreenTheme."
Thank you in advance for your help.
Regards,
Peter

A: Your suspect seems to be right. Unless you share your styles file and your manisfest, we can't say definitively. Change your style to Theme.Holo.Light or Theme.Light in your styles.xml file  .


text:
Q: (Why) does this design suck? I'm designing an Open Hardware door-lock-controller for our hackerspace, to these basic requirements:

*

*Be made exclusively from available and inexpensive parts.

*Read external Wiegand keyboard

*Read external Wiegand RFID reader

*Control various door-locks and other actuators.

*Read 125 kHz EM4100 RFID directly with an onboard reader.

*Passive POE powered, to make cabling easier.

*Run off unregulated 15-30V DC (cheap and easy high-capacity UPS via SLA)

*Provide a regulated 12V DC out @ 300 mA to 1.5A peak for external gear.

*Talk Ethernet to the server.

*Keep a local list of allowable keys, so only power is needed to let us in.

*Control external 230V gear using two relays.

This is the second spin of the PCB with a few changes to fix the problems I've found, the biggest change I've made is to throw away the LDO that regulated the 3.3V rail, in exchange for a simple MC34063 based switcher.
I'm pretty sure it's going to work, but I'd like some comments to check if I've overlooked something.
Compromises I've had to make in the design are:

*

*The primary (35V) capacitor is stacked on top of the Ethernet transformer to save space.

*The Ethernet transformer is huge, but I have a bunch of them and they were cheap, so I'm going to use them, even if they are huge.

Main questions

*

*Is there a cheaper and better way to implement the two power supplies (I need around 200mA@3.3V and 300mA@12V with peaks to 1.5A) ?

*Does the MC34063 switcher circuit/layout look sane?

*I have no idea how inefficient the MC34063 is so I've tried to heat sink it as well as possible using the copper I have available, any hints for improvements?

Schematic in pdf
Click to embiggen PCB image

A: I'd be really surprised if this operates, at least with any reliability.  You desperately need a power plane and a ground plane with components like these.
For instance the ENC28J60SS is a current mode driver, those traces from it to the pulse transformer to the jack are going to be carrying high currents switching at high speeds with no reasonable supply or ground path for them.  I'd also be concerned with the crystal as its tuning capacitors have a very long high inductance path to ground.  I would guess that this design will emit a ton of EMI, possibly enough to interfere with any nearby electronics.
The layout for the switcher is also huge, i would expect you to have serious amounts of noise and supply ringing throughout this design coming from the switcher and the ethernet components.
You also mentioned POE but there is no POE controller on this board.  If your planning to just plug into a POE switch there is a negotiation procedure to request power (in various levels).  The only way you could power this off the ethernet port as is would be to find a mid run injector that just dumped voltage on the unused pairs in 10/100 Base-T.  If you plugged this into a gigabit switch that could cause major problems.  Those pairs also aren't center tapped as they should be for POE.  Dumping pins 7/8 directly to ground could cause major problems for both this device and the switch.
There is a lot i could go into but 90% of it is a result of not having power/ground planes, clear that up first.
Also the mid point of R5 and R6 should not be connected to the center tap of the pulse transformer and the jack side of the Output transformer should have a small, high voltage cap to chassis ground at its center tap


text:
Q: LINQ Query across complex parent/child/parent/child relationships This is probably a snap for a LINQ pro, but this is beyond my basic capacity.  We have six tables accessed through Entity Framework:
Stores { Storeid, Description }
ShoppingDays { ShoppingDayid, Date, Storeid }
Transactions { Transactionid, Amount, ShoppingDayid, PaintColorid }
PaintColors { PaintColorid }
DyeAllocations { DyeAllocationid, PaintColorid, Percent, DyeId }
Dyes { DyeId, Name }

The Stores, ShoppingDays, and Transactions tables are straightforward and don't need commenting.  However, each transaction purchases a single color of paint.  Each color of paint consists of a mix of color dye percentages that add up to 100%.
I'd like to sum up all of the dollars spent on each dye on each day at each store.  Imagine store1 has two transactions on day 1.  One transaction for $30 for a purchase of Purple Paint (40% Red, 40% Blue, 20% Black) and another for $20 of Pink Paint (20% Red, 80% White).  The results would look like
Store1,1,Red,$16
Store1,1,Blue,$12
Store1,1,Black,$6
Store1,1,White,$16
Any help would be most appreciated.  I'm not really even sure where to start.  I did an inner join of all the tables and then put the data into an excel pivot table to extract the data.  Obviously that's not correct.
I started with the following.  It provides a table that shows each dye purchase for each transaction.  I'd like to sum up those purchases for each store and shopping day, but I'm not sure how.
var dyeValues = (from store in db.stores
                           join sd in db.shoppingdays on store.storeId equals sd.storeId
                           join tr in db.transactions on sd.shoppingdayId equals tr.shoppingdayId
                           join pc in db.paintcolors on tr.paintcolorId equals pc.paintcolorId
                           join da in db.dyeallocations on pc.paintcolorId equals da.paintcolorId
                           where da.percent > 0.0m
                           select new
                           {
                               store.Description,
                               shoppingdayDate = sd.Date,
                               da.dye.Name,
                               da.percent,
                               Allocation = da.percent * tr.Amount
                           });

A: Here is the equivalent of the classical SQL way.
First a subquery that groups by {ShoppingDayId, DyeId} and calculates Sum(Percent * Amount):
var dyeAllocations =
    from tr in db.Transactions
    join pc in db.PaintColors on tr.PaintColorId equals pc.PaintColorId
    join da in db.DyeAllocations on pc.PaintColorId equals da.PaintColorId
    where da.Percent > 0.0m
    group new { Allocation =  da.Percent * tr.Amount }
    by new { tr.ShoppingDayId, da.DyeId } into g
    select new { g.Key.ShoppingDayId, g.Key.DyeId, Allocation = g.Sum(e => e.Allocation) };

Then join to other tables to get the additional information needed:
var dyeValues =
    from da in dyeAllocations
    join dye in db.Dyes on da.DyeId equals dye.DyeId
    join sd in db.ShoppingDays on da.ShoppingDayId equals sd.ShoppingDayId
    join store in db.Stores on sd.StoreId equals store.StoreId
    select new
    {
        store.Description,
        sd.Date,
        dye.Name,
        da.Allocation
    };

The subquery could be embedded in the actual query, I've used a separate variable just for readability (it has no effect on the EF generated SQL query). Also you may need to update the field names / casing to match the actual models, but this should give you the idea.

A: I modified Ivan's answer into a single query.  It's very slow, but it works!
var deyValues = from cs in account.stores
       join sd in db.shoppingdays on cs.storeId equals sd.storeId
       join tr in db.transactions on sd.shoppingdayId equals tr.shoppingdayId
       join pc in db.paintcolors on tr.paintcolorId equals pc.paintcolorId
       join da in db.dyeallocations on pc.paintcolorId equals da.paintcolorId
       where da.AfterTaxOptimalPortion > 0.0m
       group new { Allocation = da.Percent * tr.Amount }
       by new { AccountName = cs.Account.Name, ShoppingDate = sd.Date, DyeName = da.dye.Name } into g
       select new { g.Key.AccountName, g.Key.ShoppingDate, g.Key.DyeName, Total = g.Sum(el => el.Allocation) };


text:
Q: TreeView keeps adding content after button click I am working in a ASP website. I am inserting data to a TreeView dynamically using some table from SQL Server. I want to add a feature, which use a button to create a new child-node.
The problem is that when I click the button the page seems to 'refresh' and then it add again the content which was already populated when the page loaded. I have get the solution for this, using the IsPostBack inside the PreRender. However, I need to click the button twice to open a popup window to enter the name of the child-node.
Searching over Google, said that I need to use the !IsPostBack, or the PreRender method for the TreeView. However, neither of these methods worked for me. Below is my code,

 <asp:Label ID="lblTitle" runat="server" Text="Documents"></asp:Label>

        Click Here for Upload

        <asp:TreeView ID="TreeViewDocuments" runat="server" ExpandDepth="0"
            ImageSet="Simple" Visible="False" onprerender="TreeView_PreRender">
            <HoverNodeStyle Font-Underline="True" ForeColor="#5555DD" />
            <LeafNodeStyle NodeSpacing="10px" />
            <Nodes>
                <asp:TreeNode Text="System" Value="Systems" Expanded="False"
                    SelectAction="Expand">
                </asp:TreeNode>
                <asp:TreeNode Text="Document" Value="Documents" Expanded="False"
                    SelectAction="Expand">
                </asp:TreeNode>
            </Nodes>
            <NodeStyle Font-Names="Tahoma" Font-Size="Medium" ForeColor="Black"
                HorizontalPadding="0px" NodeSpacing="7px" VerticalPadding="0px" />
            <ParentNodeStyle Font-Bold="False" />
            <SelectedNodeStyle Font-Underline="True" ForeColor="#5555DD"
                HorizontalPadding="0px" VerticalPadding="0px" />
        </asp:TreeView>

            <asp:Button ID="btnNewFolder" runat="server" Text="New Folder"
            onclick="btnNewFolder_Click" UseSubmitBehavior="False"/>
            <asp:Button ID="btnRenameFolder" runat="server" Text="Rename Folder" />
            <asp:Button ID="btnDeleteFolder" runat="server" Text="Delete Folder" />

Code behind,
        protected void Page_Load(object sender, EventArgs e)
    {
            if (!HttpContext.Current.User.Identity.IsAuthenticated) {
                TreeViewDocuments.Visible = false;
                lblTitle.Text = "You need to be logged in.";
            }
            else
                TreeViewDocuments.Visible = true;
    }
    protected void TreeView_PreRender(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
           AddNewNode();
        }
    }
    // Some Code to pop
     protected void AddNewNode()
     {
      ...
     }
    .
    .
    .
    protected void btnNewFolder_Click(object sender, EventArgs e)
    {
        if (TreeViewDocuments.Nodes[0].ChildNodes[0].Checked)
        btnNewFolder.Attributes.Add("onclick", "PopupCenter('NewFolderPopup.aspx', 'Add Folder',340,125);");
    }

A: As I understand you should call AdNewNode() when button is clicked.
In your case, when button is clicked, the refresh happens and the new row is added again and again. But it is added even without click, no?
EDIT:
This line:
btnNewFolder.Attributes.Add("onclick", "PopupCenter('NewFolderPopup.aspx', 'Add Folder',340,125);");

You should put it inside the pre-render but not click.


text:
Q: regex is right - yet match returns nil - why? Good sirs.
I seem to have a decent regex to capture the url I want...

So how am I using it wrong?
2.0.0-p451 :237 > resbody
 => "{"provider_url": "http://www.popsci.com", ...
2.0.0-p451 :240 > resbody.match(/"thumbnail_url":"([^"]*)"/)
 => nil
2.0.0-p451 :241 > resbody.scan(/"thumbnail_url":"([^"]*)"/)
 => []
2.0.0-p451 :242 > resbody[/"thumbnail_url":"([^"]*)"/,1]
 => nil

A: That string looks like JSON. Therefore the following should return the what you need:
require 'json'
JSON.parse(resbody)['thumbnail_url']