text:
Q: Difficult inequality with 4 variables I am struggling with this inequality from the book Advanced Olympiad Inequalities: Algebraic & Geometric Olympiad Inequalities, any idea please? Thanks.
Question: Let $a,b,c,d>0$ such that $a^2+b^2+c^2+d^2=4$. Prove that:
$$ \frac{a}{b}+\frac{b}{c}+\frac{c}{d}+\frac{d}{a}+abcd \geq 5 $$
Approach 1: using AM-GM: $$ \frac{a}{b}+\frac{b}{c}+\frac{c}{d}+\frac{d}{a}\geq 4 $$ but $abcd \leq 1$ so I am not able to conclude.
Approach 2: I have also tried Cauchy-Schwarz, but I am not sure if the inequality that I got is true or not:
$$ \frac{a}{b}+\frac{b}{c}+\frac{c}{d}+\frac{d}{a}+abcd \geq \frac{(a+b+c+d)^2}{(a+c)(b+d)}+abcd \geq 5$$
But I don't think the last inequality is true...

A: Actually the Buffalo Way works. This is outline of a proof.
WLOG, assume that $a = \min(a, b, c, d)$. Let $b=a+u, \ c = a+v$ and $d = a+w$ with $u, v, w\ge 0$.
It suffices to prove that
$$\frac{a}{b}+\frac{b}{c}+\frac{c}{d}+\frac{d}{a} + \frac{16abcd}{(a^2+b^2+c^2+d^2)^2} \ge 5$$
or
$$q_6 a^6 + q_5a^5 + q_4 a^4 + q_3 a^3 + q_2a^2 + q_1a + q_0 \ge 0$$
where
\begin{align}
q_6 &= 4(u-v+w)^2, \\
q_5 &= -8(uv-3uw-vw)(u-v+w), \\
q_4 &= 7 u^4+(-24 v+4 w) u^3+(30 v^2-16 v w+54 w^2) u^2\\
&\quad +(-8 v^3-12 v^2 w+16 v w^2+4 w^3) u+7 v^4-24 v^3 w+30 v^2 w^2-8 v w^3+7 w^4,\\
q_3 &= 3 u^5+(-5 v+11 w) u^4+(10 v^2-48 v w+22 w^2) u^3+(6 v^3+22 v^2 w+42 v w^2+22 w^3) u^2\\
&\quad +(7 v^4-48 v^3 w+50 v^2 w^2-24 v w^3+11 w^4) u\\
&\quad +3 v^5-5 v^4 w+10 v^3 w^2+6 v^2 w^3+7 v w^4+3 w^5 ,\\
q_2 &= w^6+(3 u+2 v) w^5+(11 u^2+6 u v+7 v^2) w^4+(6 u^3+2 u v^2) w^3\\
&\quad +(11 u^4+4 u^3 v+46 u^2 v^2+8 u v^3+7 v^4) w^2\\
&\quad +(3 u^5-10 u^4 v-6 u^3 v^2-12 u^2 v^3-9 u v^4-2 v^5) w\\
&\quad +u^6-2 u^5 v+7 u^4 v^2+7 u^2 v^4+2 u v^5+v^6  , \\
q_1 &= (u+v) w^6+(u^2+u v) w^5+(2 u^3+6 u^2 v+7 u v^2+2 v^3) w^4\\
&\quad +(2 u^4-2 u^3 v+2 u^2 v^2-2 u v^3) w^3\\
&\quad +(u^5+5 u^4 v+8 u^3 v^2+6 u^2 v^3+7 u v^4+v^5) w^2\\
&\quad +(u^6-3 u^5 v+2 u^4 v^2-6 u^3 v^3+u^2 v^4-3 u v^5) w\\
&\quad +u^5 v^2+2 u^3 v^4+u v^6 , \\
q_0 &= u^5 v w^2+2 u^3 v^3 w^2+2 u^3 v w^4+u v^5 w^2+2 u v^3 w^4+u v w^6.
\end{align}
Clearly, $q_6 \ge 0$ and $q_0\ge 0$.
We can use Mathematica Resolve to verify $q_4, q_3, q_2, q_1\ge 0$. I hope to see nice proof of them.
Then, it suffices to prove that $q_6 a^6 + q_5a^5 + q_4 a^4 + q_3 a^3 \ge 0$
or $F(a) = q_6a^3 + q_5a^2 + q_4a + q_3 \ge 0$. We can use Mathematica Resolve to verify it. I hope to see nice proof of it.
We are done.

A: Tchebychef's inequality-If $a_1,a_2..a_n$ and $b_1,b_2..b_n$ are real numbers then $$\frac{a_1b_1+a_2b_2+ .. +a_nb_n}{n}\geq\left(\frac{a_1+a_1+...+a_n}{n}\right)\left(\frac{b_1+b_1+...+b_n}{n}\right)$$Set $a_i,b_i$ to $a,b,c,d$ .You will quickly get this$$16\geq(a+b+c+d)^2\rightarrow4\geq a+b+c+d$$Now use AM-GM inequality on $a,b,c,d$ to get $$a+b+c+d\geq 4(abcd)^{\frac{1}{4}}$$From the couple of results which have been derived above it is evident that $abcd\leq 1$ . Now applying a final AM-GM inequality.$$\frac{\frac{a}{b}+\frac{b}{c}+\frac{c}{d}+\frac{d}{a}+abcd}{5}\geq(acbd)^{\frac{1}{5}}$$$$\frac{a}{b}+\frac{b}{c}+\frac{c}{d}+\frac{d}{a}+abcd\geq5(abcd)^{\frac{1}{5}}$$and we know RHS can never exceed 5 because $abcd\leq1$ , hence the inequality is proven.https://brilliant.org/wiki/chebyshev-inequality/#=  (for Tchebychef's inequality)

A: It's a very long for the comment.
Let $a=\min\{a,b,c,d\}$, $b=a+u$, $c=a+v$ and $d=a+w$.
Thus, we need to prove that
$$\frac{a}{b}+\frac{b}{c}+\frac{c}{d}+\frac{d}{a}+\frac{16abcd}{(a^2+b^2+c^2+d^2)^2}\geq5$$ or
$$4(u-v+w)^2a^6+8(u-v+w)(3uw+vw-uv)a^5+$$
$$+(7u^4+7v^4+7w^4+4u^3w-24u^3v-8v^3u-24v^3w+4w^3u-8w^3v+$$
$$+30u^2v^2+54u^2w^2+30v^2w^2-16u^2vw+12v^2uw-16w^2uv)a^4+...\geq0.$$
The expression, which I wrote can be negative,
which says that if even there is a proof by BW  so it's very hard.


text:
Q: Holder continuous map preserves $F_\sigma$ sets Let $F\subset \mathbb{R}^n$ be an $F_\sigma$-set and $\Phi:F\to \mathbb{R}^d$ be an $\alpha$-Holder continuous map, that is
$$|\Phi(x)-\Phi(y)|_\infty \le L|x-y|_\infty^\alpha\; \forall x,y\in F$$ with constant $L$ and exponent $\alpha \in (0,1]$.
Now assume that $J$ is a square of side-length $s<1$ and centre $c\in \mathbb{R}^n$. Then because of the above condition, we have
$$\Phi(J)=\Phi\Big(\prod_{k=1}^n[c_k-\frac{1}{2}s,c_k+\frac{1}{2}s)\Big)\subset\prod_{k=1}^d[\Phi_k (c)-\frac{L}{2}s^{1/\alpha},\Phi_k(c)+\frac{L}{2}s^{1/\alpha})$$
$|\cdot|_\infty$ is the maximum norm of the vector in the Euclidean space.
I tried showing this by putting $y\in J$, then $|y_k-c_k|\le \frac{1}{2}s$, so $|\Phi(y_k)-\Phi(c_k)|\le |\Phi(y)-\Phi(c)|_\infty \le L|y-c|_\infty^\alpha \le L (\frac{s}{2})^\alpha$. But I don't see how to get the bound $\frac{L}{2}s^{1/\alpha}$ as required. I would greatly appreciate it if anyone could help me.

A: The statement seems to be wrong. Take $\Phi(x)=\sqrt{|x|}$.
For $0\le x<y$,
$$\sqrt{y}-\sqrt{x} \\
=(y-x)/(\sqrt{y}+\sqrt{x}) \\
\le(y-x)^{1/2}(y+x)^{1/2}/(\sqrt{y}+\sqrt{x}) \\
\le(y-x)^{1/2}(y^{1/2}+x^{1/2})/(\sqrt{y}+\sqrt{x}) \\
=(y-x)^{1/2},$$
similarly for $y<x\le 0$, and for $x<0<y$,
$$|\sqrt{y}-\sqrt{-x}| \\
\le |y-(-x)|^{1/2} \\
\le (|y|+|x|)^{1/2} \\
=(y-x)^{1/2}.$$
So, it is $\tfrac{1}{2}$-Holder with $L=1$. Now, $[-1/4,1/4)$ is mapped onto $[0,1/2]$ which is not a subset of $[-1/8,1/8)$.
Unless I am missing something here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: getContentPane() not recognized when java.awt is imported ANSWERED / CLOSED
to make things simple, I've just pulled code directly from the java applet tutorial.
The code is:
private void createGUI() {
JLabel label = new JLabel(
    "You are successfully running a Swing applet!");
    label.setHorizontalAlignment(JLabel.CENTER);
    label.setBorder(BorderFactory.createMatteBorder(1,1,1,1,Color.black));
    getContentPane().add(label, BorderLayout.CENTER);
}

The only thing is, getContentPane() isn't recognized even though I have the following imports
import java.applet.*;
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.JFrame;

could someone please tell me what I have to do to get Eclipse Kepler to recognize getContentPane()?
Thanks


text:
Q: Filtering DataTable and copying results to two different DataTables I'm trying to filter results from a method that returns a DataTable, by a certain column value (of type DateTime) and inserting them into two distinct DataTables, as follows:
var vAllItems = myClass.GetAllResults(x,y,z);
DataTable dtExpiredItems = new DataTable();
DataTable dtActiveItems = new DataTable();

var expiredItems = vAllItems.AsEnumerable().Where(r => r.Field<DateTime?>("ExpDate") <= DateTime.Now && r.Field<DateTime?>("ExpDate").HasValue);
var activeItems = vAllItems.AsEnumerable().Where(r => r.Field<DateTime?>("ExpDate") > DateTime.Now || !r.Field<DateTime?>("ExpDate").HasValue);

foreach(DataRow row in expiredItems)
     dtExpiredItems.Rows.Add(row);

foreach (DataRow row in activeItems)
     dtActiveItems.Rows.Add(row);

rptExpiredItems.DataSource = dtExpiredItems;
rptExpiredItems.Bind();
pchExpiredItems.Visible = dtExpiredItems.Rows.Count > 0;

rptActiveItems.DataSource = dtActivetItems;
rptActiveItems.Bind();
pchActiveItems.Visible = dtActiveItems.Rows.Count > 0;

Thing is, on the second foreach loop the following error occurs:
This row already belongs to another table.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: This row already belongs to another table.

Any help is appreciated! Thanks!

A: A DataRow can only belong to a one DataTable, you should create a new row from given row values.
Use ItemArray property of the DataRow to get values and pass object[] as an input to create new row.
dtExpiredItems.Rows.Add(row.ItemArray);

or use ImportRow
dtExpiredItems.ImportRow(row);

Another option is using CopyToDataTable (DataTable)extension to create new table from Linq output, then use new table for your binding.
dtExpiredItems = expiredItems.CopyToDataTable<DataRow>();

A: Where you are doing the following
dtExpiredItems.Rows.Add(row);
dtActiveItems.Rows.Add(row);

You could instead do
dtExpiredItems.ImportRow(row);
dtActiveItems.ImportRow(row);


text:
Q: SimpleXML, iteration on all element I have a stock report file (coming from an outer source, therefore I can't modify in any way) and I would like to iterate over all elements (I have to save them into a MySQL table). As I see the $xml->Stockfile is an array of objects (2 items), so I tried to put it into an array.
For some reason the $myarray contains only the first element after the $myarray = $xml->StockFile assignment.
here is my code:
$xml = simplexml_load_file("../docs/stock.xml");
print_r($xml);
$myarray = $xml->StockFile;
print_r($myarray);

stock.xml:
<NewDataSet>
  <StockFile>
    <MatrixID>1533</MatrixID>
    <Brand>myBrand</Brand>
    <ProductCode>001</ProductCode>
    <RRP>29.99</RRP>
    <Image2Name />
    <Image3Name />
  </StockFile>
  <StockFile>
    <MatrixID>1534</MatrixID>
    <Brand>myBrand</Brand>
    <ProductCode>002</ProductCode>
    <RRP>29.99</RRP>
    <Image2Name />
    <Image3Name />
  </StockFile>
</NewDataSet>

Why I'm getting only one item instead of all?
What should I do do retrieve the whole array?

A: Take care with SimpleXMLElement. It has a lot of magic. Know the magic or get puzzled by print_r or var_dump or similar output. Your example extended:
$myarray = $xml->StockFile;
print_r($myarray); # shows one element

# foreach has both elements:
foreach($myarray as $name => $stockfile)
{
    echo $name, ":\n", $stockfile->asXML(), "\n\n";
}

Even though it is the same variable ($myarray) it behaves differently depending on context it is used in. Inside a foreach the SimpleXMLElement (that is the type of that object) will provide an iterator over the child-elements named StockFile as specified here:
$myarray = $xml->StockFile;

However using that variable in some kind of single context, it will for example return the inner string of the first child-element with that name:
echo $myarray, "\n";

(which in your case is just some lines of whitespace).
See Demo: https://eval.in/83787
Running into this "trap" by SimpleXML is actually pretty common. I suggest to understand the basic usage by the example given in the manual:

*

*Basic SimpleXML usage

A: change the last two lines to
foreach ($xml->StockFile as $nextStockFile) {
    print_r ($nextStockFile);
}


text:
Q: Low Fps on face tracking C++ I have written this code to track a person's face but however, I'm getting very low fps. When I only do video my fps is a lot higher.
I have tried changing the resolution but that did not work.
#include "opencv2/core.hpp"
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <opencv2/objdetect.hpp>
#include <opencv2/imgproc.hpp>

using namespace cv;
using namespace std;
int main(int argv, char** argc)
{

    CascadeClassifier faceCascade;
    faceCascade.load("C:\\Users\\farha\\OneDrive\\Desktop\\OpenCV4\\OpenCv\\install\\etc\\haarcascades\\haarcascade_frontalface_alt_tree.xml");

    Mat frame;
    Mat frameGray;
    VideoCapture cap(0);

    while (1)
    {
        cap >> frame;
        cvtColor(frame, frameGray, COLOR_RGB2GRAY);
        vector<Rect> faces;
        faceCascade.detectMultiScale(frame, faces);
        for (int i = 0; i < faces.size(); i++)
        {
            //int x1 = faces[i].x;
            //int y1 = faces[i].y;
            Point pt1(faces[i].x, faces[i].y);
            Point pt2(faces[i].x + faces[i].width, faces[i].height + faces[i].y);//, (faces[i].y, faces[i].width)
            rectangle(frame, pt1, pt2, Scalar(0, 0, 255), 2, 8, 0);

        }
        waitKey(1);
        imshow("Window", frame);
    }
    return 0;
}


text:
Q: Merging specific column from one table to another in pandas By utilizing pandas, I'm trying to add data from df2 to df1 by matching the ID for each row entry. However, I do not want to add information relevant to all the columns, only the columns that already exist in the initial dataframe. In the example below, I want to add the data from the color and size columns in df2, but not the length column. Additional, not all IDs from df1 will match an ID from df2, so those rows should just remain unchanged. The resultant dataframe shows the outcome I want after the "merge" of data. Something important to note is that the column exists already in the initial DF.
When I use the solution detailed here, the merged columns get added to the end of the dataframe rather than adding to existing columns: Python Pandas merge only certain columns
DF 1

ID
Shape
Color
Size

213
square
NaN
NaN

2321
circle
NaN
NaN

2011
circle
NaN
NaN

DF 2

ID
Length
Color
Size

213
long
blue
big

2321
short
red
small

Resultant DF1

ID
Shape
Color
Size

213
square
blue
big

2321
circle
red
small

2011
circle
NaN
NaN


text:
Q: selenium.mouseOver does not open the menu I have an application where I need to do mouseOver over a particular menu. The issue is that selenium.mouseOver is not able to open the respective menu, it just seems to highlight that div [it appears to be in pressed down state].
This div has 'onmouseover' attribute available which calls a javascript to expand this menu.
Seems that when using selenium.mouseover this javascript is not getting called. It works fine when executed manually.
I am using firefox 3.6 and it is a Richface application.
I also tried with mouseDown and click but it does not work. Is there any solution or workaround available for this?

A: There are some issues (such as these for jquery) with regards to Selenium and mouseover events.  You might try, if your browser supports it, the mouseenter event.

A: Try this

Actions builder = new Actions(driver);
  Actions hoverOverRegistrar = builder.moveToElement(driver.findElement(By.xpath("blah blah")));
  hoverOverRegistrar.perform();


text:
Q: Kotlin having trouble scanning two different QR code and store value
Using google mobile version to scan QR code, having two steps to scan two QR code:
Step 1: Click button1 to get first QR code's information then show it on Textview1 in MainActivity.
Step 2: Click button2 to get second QR code's information then show it on Textview2 in MainActivity.
My problem is that I can only pass QR code's value to my MainActivity separately, it means after I get first QR code and then click button2 to scan the second one , i will lose my first value in my textview1.

My MainActivity get Values from two Qrcode Activties:
override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        btn_2.setOnClickListener {
            val intent = Intent(this, FirstQrcodeActivity::class.java)
            startActivity(intent)
        }
        btn_1.setOnClickListener {
            val box_intent = Intent(this, SecondQrcodeActivity::class.java)
            startActivity(box_intent)
        }

    }
override fun onStart() {
        super.onStart()
        val First_qrcode= intent?.getStringExtra("First_Qrcode")
        val Second_qrcode= intent?.getStringExtra("Second_Qrcode")
        if(First_qrcode!=null){
            text_view1.text = First_qrcode
        }
        if(Second_qrcode!=null){
            text_view2.text= Second_qrcode
        }

    }

Main code in First QRcode Activity , passing values to MainActivity:
        val builder = AlertDialog.Builder(this)
        svBarcode = findViewById(R.id.sv_Firstbarcode)
        detector = BarcodeDetector.Builder(this).setBarcodeFormats(Barcode.ALL_FORMATS).build()
        detector.setProcessor(object : Detector.Processor<Barcode> {
            @SuppressLint("MissingPermission")
            override fun receiveDetections(p0: Detector.Detections<Barcode>?) {
                val barcodes = p0?.detectedItems
                if (barcodes!!.size() > 0) {
                    builder.setMessage("barcodes.valueAt(0).displayValue)
                    builder.setOnCancelListener{
                        val intent = Intent(this@FirstQrcodeActivity, MainActivity::class.java)
                        intent.putExtra("First_Qrcode",barcodes.valueAt(0).displayValue)
                        startActivity(intent)
                    }
                    taskHandler.post(runnable)
                }
            }
        })

Main code in Second QRcode Activity , passing values to MainActivity:
        val builder = AlertDialog.Builder(this)
        svBarcode = findViewById(R.id.sv_Secondbarcode)
        detector = BarcodeDetector.Builder(this).setBarcodeFormats(Barcode.ALL_FORMATS).build()
        detector.setProcessor(object : Detector.Processor<Barcode> {
            @SuppressLint("MissingPermission")
            override fun receiveDetections(p0: Detector.Detections<Barcode>?) {
                val barcodes = p0?.detectedItems
                if (barcodes!!.size() > 0) {
                    builder.setMessage("barcodes.valueAt(0).displayValue)
                    builder.setOnCancelListener{
                        val intent = Intent(this@SecondQrcodeActivity, MainActivity::class.java)
                        intent.putExtra("Second_Qrcode",barcodes.valueAt(0).displayValue)
                        startActivity(intent)
                    }
                    taskHandler.post(runnable)
                }
            }
        })

With these function I can successfully scan QR code and get value , but I can't put both value in both textview by two steps.
Once I click another button to scan second QR code and scan successfully, first value in my Textview will become Null. Help me please.

A: When you start MainActivity then it's every variable will reinitiate i.e. will become null
You have 2 solutions,

*

*Save your values in SharedPreferences so that older value will not get
refer below tutorial for details
https://www.simplifiedcoding.net/android-sharedpreferences-example/

*use onActivity Result which will return back value from the second activity
In order to start an activity which should return result to the calling activity, you should do something like below. You should pass the requestcode as shown below in order to identify that you got the result from the activity you started.
startActivityForResult(new Intent("YourFullyQualifiedClassName"),requestCode);

In the activity you can make use of setData() to return result.
Intent data = new Intent();
String text = "Result to be returned...."
//---set the data to pass back---
data.setData(Uri.parse(text));
setResult(RESULT_OK, data);
//---close the activity---
finish();

So then again in the first activity you write the below code in onActivityResult()
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == request_Code) {
        if (resultCode == RESULT_OK) {
            String returnedResult = data.getData().toString();
            // OR
            // String returnedResult = data.getDataString();
        }
    }
}

EDIT based on your comment:
If you want to return three strings, then follow this by making use of key/value pairs with intent instead of using Uri.
Intent data = new Intent();
data.putExtra("streetkey","streetname");
data.putExtra("citykey","cityname");
data.putExtra("homekey","homename");
setResult(RESULT_OK,data);
finish();

Get them in onActivityResult like below:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == request_Code) {
        if (resultCode == RESULT_OK) {
            String street = data.getStringExtra("streetkey");
            String city = data.getStringExtra("citykey");
            String home = data.getStringExtra("homekey");
        }
    }
}

A: First when starting ScannerActivity from MainActivity, start it with  startActivityForResult().
When returning result from ScannerActivity  replace startActivity() with setResult().
And then listen results not onStart(), but onActivityResult() in MainActivity
Here is Documentation for this


text:
Q: Counterexample: Convergence in probability does not imply convergence in sample mean Consider the random variable $X_n$ defined by $X_n = 2^n$ with probability $\frac{1}{n}$ and $0$ else, for each $n >0 $. It's easy to show that $X_n$ converges to $0$ in probability. How do we show that $S_n / n $, the sample mean, fail to converge to $0$?

A: I presume (but it definitely must be stated!) that the $X_n$ are supposed to be independent.  Hint: use one of the Borel-Cantelli lemmas.


text:
Q: JSON Parse objective c I´ve got the next json code:
{

"person_1":{
      "name" :"person",
      "pictures":[
                  {"images":{
                             "picture_1": "url1",
                             "picture_2": "url1",
                            }
                  }
               ],
}
}

Can anybody tell me how to get the element "picture_1"?
I am using touchJson for objective c.
Best Regards

A: First, I would recommend using yajl as I found it very convenient for my work.
NSBundle * personBundle = [[yourstring yajl_JSON] valueForKey:@"person_1"];
NSArray * picturArray = [personBundle valueForKey:"pictures"];
NSBundle * imagesBundle = [picturArray objectAtIndex:0];
NSString * myUrl = [imagesBundle valueForKey:"picture_1"];

This should pretty much do it.


text:
Q: How to set nested record using "set()"? I'm facing problem in setting my record value.
I have nested record inside store like this :
- data
act_reading // I can set value of this record using -> record.set('act_reading', 'dsds');
adj_reading
act_reading_nested
    - data
        arr_act_colour // How can I set this record?
        arr_act_rating // How can I set this record?
        arr_act_ferrous // How can I set this record?
    idrectype1 // How can I set this record?
adj_reading_nested
    - data
        arr_adj_colour
        arr_adj_rating
        arr_adj_ferrous
    idrectype2

How can I set idrectype1 value inside act_reading_nested?
I also have to do the same thing for arr_act_colour, arr_act_rating, & arr_act_ferrous.
Thanks in Advance

A: Assuming record is variable holding reference to your recrd, wouldn't that work?
record.get('act_reading_nested').set('arr_act_colour','value');
record.get('act_reading_nested').idrectype1 = 'something';

Yes it would. Just checked.

A: From my experience with current implementation of the Store you can not :( I'm facing with such kind issue too, when I'd like to edit a non-plain Store in the GridPanel. see http://www.sencha.com/forum/showthread.php?119573-Event-beforeedit-in-EditableGridPanel&highlight=afteredit
I did not check it myself (rather found a hack workaround), but more clean way is to fix it with your own Store implementation using of Ext.override(Ext.Store, { ...}) facility.
See how I did it for 'standard' HttpProxy implementation.
Ext.override (Ext.data.HttpProxy, {
    buildUrl : function (action, record) {
        var ret = '';
        if (window.location.pathname != '/') {
            ret = window.location.pathname;
        };
        return ret + Ext.data.HttpProxy.superclass.buildUrl.call(this, action, record);
    }
});

It requires a bit deep Extjs internal knowledge though.


text:
Q: Points at which partial derivatives exist and are continuous Given $ E = (xy : xy \neq 0 ) $ . Let $ f : \mathbb R^{2}\longrightarrow \mathbb R$ be defined by
$$f(x,y)=\cases{0,& if $xy=0$\\y\sin\left(\frac{1}{x}\right)+x\sin\left(\frac{1}{y}\right),& otherwise} .$$
Let $ S_1  $ be set of points in $ \mathbb R^{2}$  , where $f_x$ exists and $S_2 $ be set of points where $ f_y$ exists . Let $E_1$ be points where partial wrt x is continous and $E_2$ be set of points where $f_y$ is continous
I heed to determine what $S_i$ and $E_i$ are, $i=1,2 $
ATTEMPT : I calculated partial derivatives as
$f_x$ = $ -(y/x^{2}) \cos(1/x) + x\sin(1/y)$
$f_y = \sin1/x - (x/y^{2} )\cdot\cos (1/y) $
These both partials do not exist at X axis and Y axis and origin. At other points in xy plane they exist. Same for continuity. Is that enough, I'm not confident? Can anyone please elaborate? Thanks

A: let us look at $f_x.$ you have the formula $f_x = -\dfrac{y}{x^2}\cos(1/x) + \sin(1/y)$
it is clear that $f_x$ is continuous everywhere except possibly on the $x$ and $y$ axis. we will look at the axes in turn.
on the $x$-axis, $f$ is identically zero. so $f_x(x, 0) = 0$ for all $x.$
on the $y$-axis, we will use the definition of $f_x$ to compute $f_x.$
for
$y \neq 0, f_x(0,y) = \lim_{h \to 0}\dfrac{f(h, y)}{h}
=\dfrac{y \sin (1/h) + h\sin (1/y)}{h} = \sin(1/y)+ y\lim_{h \to 0}\dfrac{\sin (1/h)}{h}$ does not exist.
so the set $S_1 = \{(0,y) \colon y \neq 0 \}$
can you do the rest?


text:
Q: FinanceApp.getHistoricalStockInfo call does not return proper values When I try to get the historical quotes using the following block of code, the stockInfo array is coming back empty.  Based on the criteria specified in the FinanceApp.getHistoricalStockInfo function call, I should get the prices for GOOG stock for the trading day 11/30/2012.
function TestMethod()
{
  var ss = SpreadsheetApp.getActiveSheet();
  var date = new Date(2012, 11, 30);
  var retValue = FinanceApp.getHistoricalStockInfo("GOOG", date, date, 1);
  var ret = retValue.stockInfo[0];

  Logger.log(ret);  /* This comes back as 'undefined' */
  Logger.log(retValue.close);  /* This comes back as 'undefined' */

  if (retValue != undefined && retValue.stockInfo[0] != undefined)
    Logger.log(retValue);
}

This method used to work properly until about 10 days ago.  I have tried posting this to the google groups forums also but no one has responded yet.

A: When you put the interval of 1 day, then you will have to have difference of at lease one day between start and end date.
e.g
function TestMethod(){
  var ss = SpreadsheetApp.getActiveSheet();
  var startDate = new Date(2012, 10, 30);
  var endDate = new Date(2012, 11, 1);
  var retValue = FinanceApp.getHistoricalStockInfo('GOOG', startDate, endDate, 1);
  var ret = retValue.stockInfo[0];

  Logger.log(ret);
  Logger.log(retValue);
}


text:
Q: Not able to connect to Oracle using Service Name I have hit a strange problem where I am not able to connect to Oracle as normal -
username@service, and then type in the password.
When I do follow this pattern I get the following error - ORA-12514: TNS:listener does not currently know of service requested in connect descriptor.
If I type in with username/pwd@hostname/servicename it will connect. The tnsnames file is fine, it has never changed at all. It is also strange that this problem also exists not with one database, but with a couple of others.
Can anyone give me some direction for a solution?


text:
Q: Creating CSize wrapper from QSize I am trying to create a wrapper for QSize class of Qt.
Here is the code snippet.
class CSize
{
private:
    QSize m_szSize;

public:
    int cx,cy;

CSize();
CSize(int cx,int cy)
{

}
CSize(const CSize& obj)
{
    m_szSize.setWidth(obj.cx);
    m_szSize.setHeight(obj.cy);
}
};

But when following situation arrives,
CSize sz;
sz.cx = 10;
sz.cy = 20;

How can i update the values of m_szSize.
Someone please help me out.

A: You need to put cx and cy as private, and add accessors for cx and cy:
void setCx(int p_cx) { cx = p_cx; m_szSize.setWidth(cx); }
void setCy(int p_cy) { cy = p_cy; m_szSize.setHeight(cy); }
int getCx() const { return cx; }
int getCy() const { return cy; }

A: It might be safer to keep the data in a qsize and just create the CSize when needed.
eg if you need a csize for a call to some exisitng API
CallToSomeOldAPI(CSize(m_qsize.x,m_qsize.y));


text:
Q: Static variable simultaion: classes vs generators I was curious about using static variables in python, and ended up at: Why doesn't Python have static variables?
In the accepted answer, which I found informative, it is said "If you want your function's behavior to change each time it's called, what you need is a generator".
However I was a bit confused, since the example used there can be done with a class as well:
class Foo(object):
    def __init__(self, bar):
        self.bar = bar

    def __call__(self):
        self.bar = self.bar * 3 % 5
        return self.bar

foo = Foo(bar)
print foo()
print foo()

This makes more sense to me (but probably only because I haven't used generators properly before).
So my question is whether there is some other advantage to using generators over classes when the function needs to change behavior each time it's called.

A: Generators (the simple ones, not getting into coroutines) have a single, very specific purpose: Writing iterators. To this end, you get implicit capture of local variable and a keyword to suspend (as opposed to "terminate" - you can resume) execution and give the caller the next value of the iterator. The advantages are:

*

*The logic reads more naturally, as you don't need to chop it into several method invokations - all state is preserved, including the program counter - you can use control flow across yielding . You could replace yield x with results.append(x) and return results at the end and get a function that's equivalent to list(the_original_generator(...)).

*You don't need to explicitly make values long-lived by putting them into self - less to type and less to read.

*You don't need a class declaration with two method declarations (a few lines of boilerplate, which is considerable by Python standards).

You can use the "capture of local variable" thing to implement an iterable which behaves as, except that you can have multiple ones and you don't invoke a function but use an iterator (next_val = next(vals) instead of next_val = vals()). Whether it is appropriate depends.

A: There's nothing you can do with a generator that you couldn't do with a class.
The reason to use generators is simply that they're shorter, and in many cases read more naturally than classes. Obviously this depends what you're doing. In the example you give, you just want to repeatedly perform the same operations and spit out the number, so a generator makes perfect sense. For more complex situations, you'd use a class.

A: A proper generator class looks like this:
class Foo(object):
    def __init__(self, bar):
        self.bar = bar

    def __iter__(self):
        return self

    def next(self):
        self.bar = self.bar * 3 % 5
        return self.bar

foo = Foo(3)
print next(foo)
print next(foo)

The equivalent generator function takes half the code:
def Foo(bar):
    while True:
        bar = bar * 3 % 5
        yield bar

foo = Foo(3)
print next(foo)
print next(foo)

Generator functions are just a shortcut for the most common, basic iteration pattern. When you need something more complex a class allows for that.

A: For generators there's no other way to access the variable, except by calling a function, while in a class-based variant, you can modify it directly. This can be both advantage and disadvantage depending on your use-case. Also the code is simpler. For a more detailed discussion see: http://wiki.python.org/moin/Generators


text:
Q: 'Display: contents' does not work with tree-structure pseudo-classes (:first-child,: last-child, etc.)? My question: is this intentional? I can't find any literature or conversation about it.
The selector spec says it's for inclusive siblings - https://www.w3.org/TR/selectors/#child-index - but doesn't display: contents in effect simulate the contents as belonging to the grandparent element?
Per docs, the element is entirely removed from the accessibility-tree, and a grandparent flex will treat the removed element's children as its own (thus as siblings to its own). However, tree-structure pseudo-classes, such as :last-child, do not recognize the children's adoption, and instead operate as if they were still children of the removed element.
I suppose this is because the element is not removed from the actual DOM tree, and the pseudo selectors only operate upon the concrete DOM?
My use case is along the lines of:
<Accordion>
  <form style={{ display: contents }}>
    <Accordion.Section />
    <Accordion.Section />
  <form>
  <Accordion.Section />
</Accordion>

... In which I was expecting the form would display its children into the Accordion and I could select the last child.

A: OP Question:

but doesn't display: contents in effect simulate the contents as belonging to the grandparent element?

No, here's a quoted explanation from here

display: contents makes that the div doesn't generate any box, so its background, border and padding are not rendered. However the inherited properties like color and font have effect on the child (span element) as expected.

Also good reading on display: contents:

*

*Get Ready for display: contents;

*Vanishing boxes with display contents

The display property doesn't change how the DOM is rendered just style it, so a last-child it always be a last-child no matter the display you use (even using display: none)
As you can see in the snippet below the properties belonging to box-model don't get inherit by children when parent is display: contents

.section {
  margin: 10px
}

form {
  background: lightblue;
  border: 10px solid red;
  padding: 10px
}

.section:first-child {
  box-shadow: 0 0 0 5px green;
}

.section:last-child {
  box-shadow: 0 0 0 5px blue;
}
<Accordion>
  <form style="display: contents">

first child of form

last child of form

  </form>

first and last child of Accordion

</Accordion>

<Accordion>
  <form style="display: flex">

first child of form

last child of form

  </form>

first and last child of Accordion

</Accordion>

<Accordion>
  <form>

first child of form

nth child 2 of form - even if last child is display:none

last child of form

  </form>

first and last child of Accordion

</Accordion>


text:
Q: postgres public schema function aliasing I am currently running postgres 8.4.4 and I have the need to override calls to functions that reside in the public schema of my database.  For instance in pg_catalog there exists a function

upper(text)

I have a function placed within the public schema that overrides

upper(text)

My question comes down to overriding the call to public.upper(text).  That is to say I have to execute the function call like so:

select public.upper(text);

Whereas I want to be able to call public.upper(text) in this manner:

select upper(text);

How does one go about doing this?

A: You can set schema search path and place pg_catalog at the end of your search path.
See 5.7.3. The Schema Search Path and 5.7.5. The System Catalog Schema in Postgres manual.


text:
Q: Capturar click en todo el Padre Borro lo anterior...
A ver si consigo encontrar una solución, porque se vuelve a repetir en otro caso y no consigo encontrar una solución válida para ambos...
<ion-item (click)="selectContact($event)" class="contact-item" *ngFor="let contact of contactsFound">

{{contact?.displayName}}

    {{num.value}}

</ion-item>

Lo que ocurre es que si hago click sobre cualquier parte del item... el evento click se captura correctamente pero...
Si desde angular pongo... event.target.nodeValue NO me devuelve el contenido... de donde haga click...
Si desde angular pongo... event.target.firstChild.nodeValue...
En caso de hacer el click sobre el
 obtengo el contenido del mismo...
En caso de hacer click sobre el
 obtengo el contenido del mismo...
Mi intención es que independientemente del lugar en el que haga click en el interior del item obtenga el contenido del

O tambien, que al hacer click sobre cualquier parte del item, pueda acceder desde angular a traves de event.target al contenido de los dos hijos... ¿Como lo haría?
Es como si el evento click del <ion-item> se trasladara a los hijos y que al clickear sobre un hijo event.target.childNodes.length por ejemplo, devuelve en caso de hacer click sobre el
 -- 1, en caso de hacer click sobre la caja <ion-item> -- 2.

A: Aca te dejo lo que te comentaba, osea la diferencia entre this y event.target :

var el = document.getElementById("diferencias");

el.addEventListener("click", function(e) {
  console.log(e.target.textContent + "  usando: event.target");
  console.log(this.textContent + "usando: this");
})

haz click en aqui abajo para apreciar la diferencia en la consola

{{contact?.displayName}}

{{num.value}}

si no tenes modo de usar el this podrias hacer algo equivalente que seria lo siguiente :

var el = document.getElementById("diferencias");

el.addEventListener("click", function(e) {
  console.log(e.target.textContent + "  usando: event.target");
  console.log(e.currentTarget.textContent + "   usando: event.currentTarget");

  // en tu caso haria asi :
  console.log(e.currentTarget.firstElementChild.textContent + "  solo el contenido del h2");
})

haz click en aqui abajo para apreciar la diferencia en la consola

{{contact?.displayName}}

{{num.value}}

osea usar event.currentTarget que seria equivalente al this
espero que te ayude a solucionar el problema, exitos !

A: Trabajando con Angular/Ionic es mejor olvidarse del DOM y aprovechar la potencia de las plantillas: Pasa a la función lo que necesita directamente, haciendo algo como:
<ion-item (click)="selectContact(contact)" class="contact-item" *ngFor="let contact of contactsFound">

{{contact?.displayName}}

    {{num.value}}

</ion-item>

De este modo tu compomente obtendrá sin complicaciones el contacto cuyo nombre está en el
, sin tener que preocuparte por el evento o el DOM:
selectContact(contact) {
  // ...
}


text:
Q: An inequality with matrix ranks Problem:

Prove that if the formula below makes sense, then
  $$\DeclareMathOperator{\rank}{rank}
\rank {AB} + \rank {BC}  \le \rank {ABC} + \rank B$$

I really don't know where to start. Can you give me a hint?


text:
Q: hibernate - why mocked method throws NullPointerException I'm trying to prepare some easy parking service api and i'm stuck at testing.
i have ParkingService like:
@Service
@RequiredArgsConstructor
public class ParkingService {
      private final CarsAndParkingsRepository carsAndParkingsRepository;
      private final ParkingsRepository parkingsRepository;

and simple custom method in repositories
public boolean checkFreeSlots(String idParking) {
    return carsAndParkingsRepository.findAmountOfTakenSlotsOnParking(idParking)
            < parkingsRepository.findByIdParking(idParking).getNumberOfParkingSlots();
}

and test:
 @Test
public void checkFreeSlotsIfIsCorrect() {
    //given

    //when
    when(carsAndParkingsRepository.findAmountOfTakenSlotsOnParking("5")).thenReturn(5);
    when(parkingsRepository.findByIdParking("5").getNumberOfParkingSlots()).thenReturn(10);
    when(parkingService.checkFreeSlots("5")).thenCallRealMethod();
    boolean result = parkingService.checkFreeSlots("5");

    //then
    assertEquals(true, result);
}

but the problem is i'm getting NullPointerException at line:
when(parkingsRepository.findByIdParking("5").getNumberOfParkingSlots()).thenReturn(10);

Previous mocked method when(carsAndParkingsRepository.findAmountOfTakenSlotsOnParking("5")).thenReturn(5) works correctly, its return 5 but in next line other repository throws exception.
Is there any other way to test it or i'm doing something wrong? Ofc, i have mocked repositories :)

A: The problem is in line:
when(parkingsRepository.findByIdParking("5").getNumberOfParkingSlots()).thenReturn(10);

The argument to when needs to get evaluated before the call:

*

*parkingsRepository.findByIdParking("5") is called and return null

*null.getNumberOfParkingSlots() is called and throws NPE

You have following options:
Use a POJO for the Parking
var parking5 = new Parking(
    5, //id
   10, //number of slots
   // ... other arguments
);
when(parkingsRepository.findByIdParking("5")).thenReturn(parking5);

This is the preferred option, but if your object is difficult to construct (it should not be the case for hibernate entity), you can use a mock
Use an mock of the Parking
var parking5 = mock(Parking.class);
when(parkingsRepository.findByIdParking("5")).thenReturn(parking5);
when(parking5.getNumberOfParkingSlots()).thenReturn(10);

Note that you can use chained calls in this approach, but this requires that you stub the methods in order.
var parking5 = mock(Parking.class);
when(parkingsRepository.findByIdParking("5")).thenReturn(parking5);
when(parkingsRepository.findByIdParking("5").getNumberOfParkingSlots()).thenReturn(10);

In my opinion, first flavour is easier to use, and lets you to reorder stubbings.


text:
Q: Python function with multiple parameter brackets Having python code like that which is only an idea:
def f(a):
    def g(b):
        def h(c):
            return a + b - c
        return h
    return g
print(f(2)(3)(4))    # 1

Is it possible to modify above code to write a function which allowed for that?
f(7) -> 7
f(1)(2)(3) -> 1 + 2 - 3 -> 0
f(-5)(10)(3)(9) -> -5 + 10 - 3 + 9 -> 11

A: Do you want to create a function with optional arguments?
If yes, you could use *args.
For example:
def fun(a, *args):
    if len(args) == 1:
        return a + args[0]
    elif len(args) == 2:
        return a + args[0] - args[1]
    else:
        return a

Another solution could be using prenamed optional arguments arguments:
def foo(a, b=None, c=None):
    if b:
        return a + b
    elif b and c:
        return a + b - c
    else:
        return a

print(foo(1, 2, 3))
>>>3
print(fun(7))
>>>7

A: With a callable class instead of a function it's possible to do something like this, which will produce the desired output for the two cases you supplied:
class f:
    def __init__(self, value, multi=1):
        self.value = value
        self.multi = multi

    def __call__(self, value):
        return f(self.value + (value * self.multi), self.multi * -1)

    def __str__(self):
        return str(self.value)

print(f(1)(2)(3))
print(f(-5)(10)(3)(9))


text:
Q: How do I draw text with GLUT / OpenGL in C++? How do I draw a text string onto the screen using GLUT / OpenGL drawing functions?

A: There are two ways to draw strings with GLUT
glutStrokeString will draw text in 3D

(source: uwa.edu.au)
and glutBitmapString will draw text facing the user

(source: sourceforge.net)

A: void RenderString(float x, float y, void *font, const char* string, RGB const& rgb)
{
  char *c;

  glColor3f(rgb.r, rgb.g, rgb.b);
  glRasterPos2f(x, y);

  glutBitmapString(font, string);
}

And you can call it like;
RenderString(0.0f, 0.0f, GLUT_BITMAP_TIMES_ROMAN_24, "Hello", RGB(1.0f, 0.0f, 0.0f));


text:
Q: Meteor - Google Maps InfoWindow Event Not Firing Using Meteorjs and dburles google map package for Meteor.
The Goal:
Is to have the markers map out on the canvas, and then onclick to reveal the infoWindows. I am having an issue firing the google map event in order for the window to reveal.
My Code:
 Template.myMap.helpers({
   mapOptions: function() {
    var locations = [
       ['Kroger', 34.069201, -84.231052, 5],
       ['Fresh Produce', 34.069802, -84.234164, 4],
       ['Starbucks', 34.069003, -84.236323, 3],
       ['Mall of Georgia', 34.069204, -84.232016, 2],
       ['Avalanche', 34.069705, -84.238207, 1]
      ]

// Make sure the maps API has loaded
if (GoogleMaps.loaded()) {
  // We can use the `ready` callback to interact with the map API once the map is ready.
  GoogleMaps.ready('myMap', function(map) {
    var infowindow = new google.maps.InfoWindow(),
        marker, i;

    for (i = 0; i < locations.length; i++) {
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map.instance
      });

      google.maps.event.addListener(marker, 'click', function() {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      });
    }
  });
  return {
    center: new google.maps.LatLng(34.069705, -84.238),
    zoom: 16
  };
}
}

});

A: You're returning a function from the event handler rather than just handling the event, for reasons that aren't clear.  Try this:
google.maps.event.addListener(marker, 'click', function() {
  infowindow.setContent(locations[i][0]);
  infowindow.open(map, marker);
});

UPDATE
The other problem is that you're trying to add it to the GoogleMaps map object, not the instance itself.  It should be:
infowindow.open(map.instance, marker);

Also, I haven't run your code, but I think you're going to run into problems with the way you've structured this, as the value of i will not be as intended when the handler is actually fired (because the loop will have subsequently continued).  Consider using forEach instead (below via underscore) so that each handler is declared in its own closure.
  _.forEach(locations, function(location) {
      var marker = new google.maps.Marker({
            position: new google.maps.LatLng(location[1], location[2]),
            map: map.instance
          });

      google.maps.event.addListener(marker, 'click', function() {
          infowindow.setContent(location[0]);
          console.log(map, marker, infowindow);
          infowindow.open(map.instance, marker);
      });
  });


text:
Q: Covering $S^{n-1}$ with $n+1$ closed sets containing no antipodal points For proving the equivalence of the Theorems of Borsuk-Ulam and Lusternik-Schnirelmann, we need to cover $S^{n-1}$ with closed sets $F_1,\dots,F_{n+1}$ such that none of the $F_i$ contains a pair of antipodal points. I've read that we can do that by taking a regular $n$-simplex inscribed in $S^{n-1}$ and projecting its faces to $S^{n-1}$, but I'm not satisfied by that argument, since it seems quite hard to specify the vertex coordinates of a regular $n$-simplex inside $S^{n-1}$.
Is there a simpler closed cover to make this work, or a not too messy way to make the simplex-argument rigorous?

Edit: Can we set it up this way?
For $k=1,\dots,n$ let $F_k$ be the set of $(x_1,\dots,x_n)\in S^{n-1}$ where at least one $x_i\le 0$ and $x_k\le x_i$ for all $i$. Let $F_{n+1}$ be the set where all $x_i\ge 0$. All of the $F_k$ are closed, since we are just taking unions and intersections of closed half-spaces. Assuming $x,-x\in F_k$ for $k\le n$ we have $x_k=x_i$ for all $i$, so all coordinates of $x$ are equal and less or equal to $0$, but then $-x\in F_k$ can only happen for $x=0$, a contradiction to $x\in S^{n-1}$. Thus $F_k$ does not contain antipodal points for $k\le n$. We easily verify that $F_{n+1}$ doesn't contain antipodal points either.

A: Consider the hyperplane, $H$, $x_1+x_2+\dots+x_{n+1}=1$ in $\mathbb R^{n+1}$. It is an $n$-dimensional space. Then consider the points in that hyperplane, $$x_1=(1,0,\dots,0), x_2=(0,1,\dots,0),\dots,x_{n+1}=(0,0,\dots,1)$$ Their convex hull is a regular $n$-simplex.
The points are also points on the sphere in $H$ with center $(\frac1{n+1},\frac1{n+1},\dots,\frac1{n+1})$ and radius $\frac{\sqrt{n^2+n}}{n+1}$.
So all you really need to do is find an isometry between $H$ and $\mathbb R^n$ sending the center to $0$, and you've got your regular $n$-simplex.
It's not pretty, but it's not hard.


text:
Q: Difference between the two autodifficulty commands in CS:GO I want to know the difference between the two bots autodifficulty commands -
bot_autodifficulty_threshold_low
bot_autodifficulty_threshold_high
Are they min. and max value of difficulty scaling range?

A: On the Valve developer community you can see that bot_autodifficulty_threshold_high    corresponds with the amount above avg human contribution score, above which a bot should lower its difficulty.
bot_autodifficulty_threshold_low corresponds with the amount below avg human contribution score, below which a bot should raise its difficulty.


text:
Q: Javascript "while hovered" loop Can anybody help me on this one...I have a button which when is hovered, triggers an action. But I'd like it to repeat it for as long as the button is hovered.
I'd appreciate any solution, be it in jquery or pure javascript - here is how my code looks at this moment (in jquery):
var scrollingposition = 0;

$('#button').hover(function(){
++scrollingposition;
    $('#object').css("right", scrollingposition);
    });

Now how can i put this into some kind of while loop, so that #object is moving px by px for as #button is hovered, not just when the mouse enters it?

A: OK... another stab at the answer:
$('myselector').each(function () {
  var hovered = false;
  var loop = window.setInterval(function () {
    if (hovered) {
      // ...
    }
  }, 250);

  $(this).hover(
    function () {
      hovered = true;
    },
    function () {
      hovered = false;
    }
  );
});

The 250 means the task repeats every quarter of a second. You can decrease this number to make it faster or increase it to make it slower.

A: Nathan's answer is a good start, but you should also use window.clearInterval when the mouse leaves the element (mouseleave event) to cancel the repeated action which was set up using setInterval(), because this way the "loop" is running only when the mouse pointer enters the element (mouseover event).
Here is a sample code:
  function doSomethingRepeatedly(){
    // do this repeatedly when hovering the element
  }

  var intervalId;

  $(document).ready(function () {

    $('#myelement').hover(function () {
      var intervalDelay = 10;
      // call doSomethingRepeatedly() function repeatedly with 10ms delay between the function calls
      intervalId = setInterval(doSomethingRepeatedly, intervalDelay);
    }, function () {
      // cancel calling doSomethingRepeatedly() function repeatedly
      clearInterval(intervalId);
    });

  });

I created a sample code on jsFiddle which demonstrates how to scroll the background-image of an element left-to-right and then backwards on hover with the code shown above:
http://jsfiddle.net/Sk8erPeter/HLT3J/15/

A: If its an animation you can "stop" an animation half way through. So it looks like you're moving something to the left so you could do:
var maxScroll = 9999;
$('#button').hover(
    function(){ $('#object').animate({ "right":maxScroll+"px" }, 10000); },
    function(){ $('#object').stop(); } );

A: var buttonHovered = false;
$('#button').hover(function () {
  buttonHovered = true;
  while (buttonHovered) {
    ...
  }
},
function () {
  buttonHovered = false;
});

If you want to do this for multiple objects, it might be better to make it a bit more object oriented than a global variable though.
Edit:
Think the best way of dealing with multiple objects is to put it in an .each() block:
$('myselector').each(function () {
  var hovered = false;
  $(this).hover(function () {
    hovered = true;
    while (hovered) {
      ...
    }
  },
  function () {
    hovered = false;
  });
});

Edit2:
Or you could do it by adding a class:
$('selector').hover(function () {
  $(this).addClass('hovered');
  while ($(this).hasClass('hovered')) {
    ...
  }
}, function () {
  $(this).removeClass('hovered');
});

A: var scrollingposition = 0;

$('#button').hover(function(){
    var $this = $(this);
    var $obj = $("#object");
    while ( $this.is(":hover") ) {
        scrollingposition += 1;
        $obj.css("right", scrollingposition);
    }
});


text:
Q: How can I iterate over list of URL's to scrape the data in Scrapy? import scrapy
class oneplus_spider(scrapy.Spider):
    name='one_plus'
    page_number=0
    start_urls=[
        'https://www.amazon.com/s?k=samsung+mobile&page=3&qid=1600763713&ref=sr_pg_3'
    ]

    def parse(self,response):
        all_links=[]
        total_links=[]
        domain='https://www.amazon.com'
        href=[]
        link_set=set()

        href=response.css('a.a-link-normal.a-text-normal').xpath('@href').extract()
        for x in href:
            link_set.add(domain+x)
        for x in link_set:
            next_page=x
            yield response.follow(next_page, callback=self.parse_page1)

    def parse_page1(self, response):
        title=response.css('span.a-size-large product-title-word-break::text').extract()
        print(title)

Error after running the code - (failed 2 times): 503 Service Unavailable.
I tried many ways but failed. Please help me. Thanks in advance!

A: Check url by "curl" first. like,
curl -I "https://www.amazon.com/s?k=samsung+mobile&page=3&qid=1600763713&ref=sr_pg_3"

then, you can see 503 response.
HTTP/2 503

In other words, your request is wrong.
you have to find proper request.
Chrome DevTools will help you. like

I think that user-agent ( like browser ) must be needed.
curl 'https://www.amazon.com/s?k=samsung+mobile&page=3&qid=1600763713&ref=sr_pg_3' \
  -H 'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36' \
   --compressed

so... It may work,
import scrapy
class oneplus_spider(scrapy.Spider):
    name='one_plus'
    page_number=0
    user_agent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36"
    start_urls=[
        'https://www.amazon.com/s?k=samsung+mobile&page=3&qid=1600763713&ref=sr_pg_3'
    ]

    def parse(self,response):
        all_links=[]
        total_links=[]
        domain='https://www.amazon.com'
        href=[]
        link_set=set()

        href=response.css('a.a-link-normal.a-text-normal').xpath('@href').extract()
        for x in href:
            link_set.add(domain+x)
        for x in link_set:
            next_page=x
            yield response.follow(next_page, callback=self.parse_page1)

    def parse_page1(self, response):
        title=response.css('span.a-size-large product-title-word-break::text').extract()
        print(title)


text:
Q: I want to provide dynamic values to the paramaters of Citrus annotation(@CitrusXmlTest) The values I want to provide dynamically  is TestCase Name  and Package name. How can I do this. If I am providing values through variable then it is giving the following error "The value for annotation attribute CitrusXmlTest.name must be a constant". Now I am giving like this
@CitrusXmlTest(name="Test",packageName="file:D://xitrus//myFirstTest.xml")

I want above statement to be
@CitrusXmlTest(name=variable name,packageName=variable name)

or in some other way to insert values dynamically  please help me...
pom image 1,image 2,image 3

A: What you are trying to do is against Java annotation specification and is not possible due to these language limitations. Not sure what you are trying to achieve here.
In case you need to load test cases in a dynamic way you can use packageScan option in @CitrusXmlTest annotation:
@CitrusXmlTest(packageScan = "com.something.foo")
public void citrusPackageScanIT() {}

This will load and execute all XML test case definitions in package com.something.foo. The XML test definitions are free to use different test names then.
If you want to pass some dynamic data to your test case you should use a TestNG data provider (example given here: https://github.com/christophd/citrus-samples/tree/master/sample-dataprovider).


text:
Q: Bypass Socks for localhost I'm in the process of shifting an application from one VM Instance to another within the Azure cloud. The new instance is now hosted behind (multi?) firewalls. For HTTPS I had to configure -Dhttps.proxyHost=my.https.proxy and for a required SFTP connection I had to configure -DsocksProxyHost=my.socks5.proxy in both cases the required connections seem to be working fine.
However, I am now finding that the application SQL statements (JDBC) are running really really slowly. The MSSQL Server is located on the same server as the Java application, so the connection uses localhost. I did some searching and found a post (somewhere) which claimed that the option -Dhttp.nonProxyHosts="localhost|127.*|[::1]" could be used to bypass the socks proxy, even though it is not stated within the documentation, see:
https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/net/doc-files/net-properties.html
I've now tested the nonProxyHosts and noticed zero performance improvements.
My suspicion is that the issue is being cause by the SQL network traffic being routed out to the Socks proxy and back again, I don't know - maybe the performance issue lies somewhere else?
If socks is the issue, how can I bypass it for localhost connections? If socks isn't the issue, then what can I do to try and find out why the JDBC is soooo slooooow?
Thanks

A: Without knowing what those firewalls are doing it is like shooting with the eyes closed, maybe you can try to disable the firewall for loopback traffic
https://superuser.com/questions/948084/pf-firewall-how-to-disable-all-filtering-on-loopback-interface-except-specific


text:
Q: javascript user's input validation I'm creating a program in which I need to validate user input.
The User should be able to write float numbers and some letters like 'k' for thousand or 'm' for million.   Allowed are: digits, and only one letter from the list(g,k,m,n,u) and only one '.' for decimal numbers. If user puts different sign, two letters from the list, two dots, follows letter by another sign - nothing displays in textbox.
What i did so far is not working at all. I cannot even create a list with allowed signs. How can i solve this? I've seen almost every page on the web about regexp..
function signFilter(e)
{
    var keynum;
    var keychar;
    var numcheck;

    if(window.event) // IE
    {
        keynum = e.keyCode;
    }
    else if(e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
    }
    keychar = String.fromCharCode(keynum);
    numcheck = /[0-9GMkmpu.]/;
    return numcheck.test(keychar);
}

http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onkeydown
Here is sample code for input. Nothing i try gives resonable result. (of course, i removed '!'from return).

A: Your regex is just testing the presence of one of the chars into [ and ]. What you are trying to do is testing for the presence of any other char in the string.
I suggest you had a ^ sign like : [^0-9GMkmpu.], so you will be able to detect any wrong char in the string.
With the regex you wrote something like : aaaaaaaaakhhhhhhhhh will return yes.

A: From the code you provided, it looks like you are testing the string one character at a time.
The code you have to only validates that correct letters are inputted, but as a whole, the final string created from the keypresses may not be in the format you expect.
For example, a string 123.123.321.m are all valid characters, but the final string is not valid.
Basically, you need to add validation that checks the final string inputted.
A regexp like this could help you in validating the final string input.
numcheck = /^[0-9]*\.?[0-9]+[gkmnu]?$/

This regexp says

*

*optionally match 0-9

*next, optionally match a dot

*next, match at least one number

*the end of the string may end in one character from the set

A: /^[0-9]*[\.]*[0-9]*[Mkmpu]*$/

This one is quite flexible and handles sereval cases such as ".57m" "57" "57m" "57.m" "57.57m".

A: This works
http://jsfiddle.net/mplungjan/KvJQx/
window.onload=function() {
  document.getElementById("t1").onkeypress=function(e) {
    var keyNum =  (window.event)?window.event.keyCode:e.which;
    var keyChar = String.fromCharCode(keyNum);
    return /[0-9GMkmpu\.]/.test(keyChar);
  }
}


text:
Q: Anonymous functions in MySQL? I wrote a query for a client that used a stored procedures. Turns out they can't grant my user write access to the database, so I can't store my procedure. Can I turn my stored procedure into an anonymous function inside my query, as to keep the functionality without using a stored procedure?
$establishFunction = mysql_query("DROP FUNCTION IF EXISTS fn_distance_cosine;
CREATE FUNCTION fn_distance_cosine (
    latitude_1 DOUBLE,
    longitude_1 DOUBLE,
    latitude_2 DOUBLE,
    longitude_2 DOUBLE
)
RETURNS DOUBLE
DETERMINISTIC
SQL SECURITY INVOKER
RETURN ACOS(
      SIN(RADIANS(latitude_1)) * SIN(RADIANS(latitude_2))
      + COS(RADIANS(latitude_1)) * COS(RADIANS(latitude_2))
      * COS(RADIANS(longitude_2 - longitude_1))
    ) * 3956.547;
");

mysql_query("SET @input_lat :=" . $lat . ";");
mysql_query("SET @input_lon :=" . $lon . ";");

mysql_query("SET @max_latitude := @input_lat + DEGREES(50.0/3956.547);");
mysql_query("SET @min_latitude := @input_lat - DEGREES(50.0/3956.547);");
mysql_query("SET @max_longitude := @input_lon + DEGREES(50.0/3956.547/COS(RADIANS(@input_lat)));");
mysql_query("SET @min_longitude := @input_lon - DEGREES(50.0/3956.547/COS(RADIANS(@input_lat)));");

if($result = mysql_query("SELECT
      *,
      fn_distance_cosine(lat, lon, @input_lat, @input_lon) AS distance_in_miles,
      COUNT(*) AS store_number_count
    FROM stores
    JOIN items_stores
    ON stores.store_number=items_stores.store_number
    WHERE `lat` BETWEEN @min_latitude AND @max_latitude
      AND `lon` BETWEEN @min_longitude AND @max_longitude
    GROUP BY stores.store_code
    HAVING store_code_count > 1
    ORDER BY distance_in_miles
    LIMIT 10;
    ")){
        while ($r = mysql_fetch_assoc($result)){
        $rows[] = $r;
    }
}else{
    //failed.
    echo (mysql_error ());
}

print json_encode($rows);

A: If you can't do stored procedures, you probably can't do functions either because they won't have the security rights for that either.
Option #1 - Have their own DBA vet the SQL statements and then make the modification to the database to house the stored procedure.
Option #2 - Your other option is to move that code out of the database and into the PHP. So yes, you can move it into the PHP but it won't be nearly as fast or efficient as having the database engine do it.

A: No you can't have anonymous functions.  If your client can't grant you proper permissions to add this function, then why did they ask you to write one? If your DB user account can't install the function, then surely that have someone with proper user account to be able to create this function for you  based on your SQL.
Also why a function instead of a stored procedure?  You could put all of that logic you are doing in several DB queries in a single call like:
call give_me_my_data(lat, long)
It seems odd that you would use some db-based logic and some php-based logic (with a number of unnecessary queries) to get at the data you need, rather than just go all the way and define a stored procedure that would clean up your PHP code to make only a single query.

A: Can you get a separate database on the same mysql server? Then you might be able to declare the procedure in there and then use it in your query by explicitly prefixing with the database name. I'm not entirely sure if it'll actually work, but I would guess it does.


text:
Q: Converting contacts for UbuntuOne I run Ubuntu 11.10 with Thunderbird as main address book; I also have the thunderbird-couchdb package installed.
I know the U1 Contacts service status has not been working lately:

Contacts
2011-11-29 Syncing of contacts is not working for some users due to server issues. On 2011-10-10 we released an update to all clients
  to help ease the load on the server and improve reliability of
  syncing. We're now working on finishing up adding additional server
  hardware.

, but I would like to start making my local contact couchdb database (so my main address book would not be TB one anymore), so it could be synced when the service restarts in a stable manner (and I could access to it from anywhere).
Here is the screenshot of my address books in TB:

In details I would like to:

*

*Understand if and where web address books (the ones with the globe icon) are stored in my fylesystem, so I can backup them;

*understand which web address book gets synced with U1 (surely it's the one named Ubuntu One, but I cannot get any useful property from TB)

*Copy (and not move) my TB contacts (the ones with the book icon) to the couchdb database that will get synced;

*Copy (and not move) my Google contacts to the couchdb database that will get synced;

Any step-by-step idea?
Thanks in advance!

A: The Ubuntu One contacts integration in its current form is going away for P (12.04), and doesn't currently work at all well. I'd recommend removing it from the desktop completely until Q (12.10).

A: Duane from support sent me this answer which I thought would be useful for people regarding this matter:

HI,
Currently Ubuntu One mobile contact sync is being completely redesigned.
  Syncing contacts to your iphone/ipod will be available later this year. The
  desktop syncing of contacts is a similar story. In its current form it does not
  work well and is going away for Ubuntu 12.04. I would recommend not using it
  until Ubuntu 12.10.

FYI: I've asked for permission to post this here.


text:
Q: PHP array for jQuery Remote Autocomplete I am trying to get remote autocomplete array
$items = array(
    "PR-1001"=>"Product 1",
    "PR-1002"=>"Product 2"
);

Input autocomplete suggection will be PR-1001 and PR-1002 and div will be appended with Product 0 or Product 2 depending on selection of autocomplete. I tried using following code but can't Please help me to get array as mentioned above.
$query = "SELECT * FROM products";
$results = mysql_query($query, $connection);
confirm_query($results);
$count = mysql_num_rows($results);
while($row = mysql_fetch_array($results)) {
    $codes =array("{$row['pr_code']}");
    $names =array("{$row['pr_name']}");
        $i = 0;
        $items[$i] = "\"" . $codes[$i] ."\"=>\"" . $names[$i] ."\", ";
        $items = implode(", ", $items);
        $i++;
    }

I need a php array that show print_r
Array ( [DJ-1001] => Product 1 [DJ-1002] => Product 2 )

Thank you in advance.

Here's answer
$items = array();
while($row = mysql_fetch_array($results)) {
  $items[$row['pr_code']] = $row['pr_name'];
}

Thank you friends!

A: Without having any idea what your schema looks like:
$items = array();
while($row = mysql_fetch_array($results)) {
    $items[$row['pr_code']] = $row['pr_name'];
}
echo json_encode($items);

A: in PHP you can have associative array where the key can either be an integer or a string. The value can be of any type. given that you can do straight assignement of key=>value from your query and then return the array in json (jquery-ui autocomplete it's modeled around it so just take a snippet from the official documentation to see how it works):
$items = array();
while($row = mysql_fetch_array($result))
    $items[$row['pr_code']] = $row['pr_name'];

echo json_encode($items);

A: The data from local data, a url or a callback can come in two variants:
• An Array of Strings:
[ "Choice1", "Choice2" ]
• An Array of Objects with label and value properties:
[ { label: "Choice1", value: "value1" }, ... ]
$arr   = array();
while($row = mysql_fetch_array($results)) {
    array_push($arr,'{ label: "' . $row['pr_code'] . '", value: "' . $row['pr_name'] . '" }');
}

echo "[" . implode(',',$arr) . "]";


text:
Q: Kendo datgrid not sending sort field parameter to server I have a kendo datagrid that retrieves data through an ajax transport. The paging features work perfectly. However, the control keeps sending a blank sort field parameter when clicking a column heading to sort the data.
Interestingly, the control still sends the sort direction, just not the field name.
I've set sortable to true, DataSource, set serverPaging to true, and defined data types for each column. Is there anything else I am missing?
Unfortunately I can't post code right now, but can put something together if I can't resolve this through something simple.
Here is the post that's being sent to the web service:
endDate: "10/31/2013 12:00 AM"
page: 1
pageSize: 20
skip: 0
sort: [{field:[], dir:asc, compare:null}]
    0: {field:[], dir:asc, compare:null}
       compare: null
       dir: "asc"
       field: []
startDate: "10/1/2013 12:00 AM"
take: 20

A: In this case, the problem was caused by the way in which I was creating the DataSource.schema.model.fields object. Initially I had passed a multidimensional array, like:
var fields = [
    fields['Field1'] = [];
    fields['Field1']['type'] = 'string';
    fields['Field1']['editable'] = false;
    fields['Field1']['sortable'] = true;
];

Changing this to key/value pairs solved the sorting issue:
var fields = {
  Field1: {
     type: 'string',
     editable: false,
     sortable: true
  }
};

the fields object is then passed to DataSource.schema.model.fields.


text:
Q: Visual Studio not setting assembly version as per my AssemblyVersionAttribute value I am setting this as the version in my AssemblyInfo.cs file.
[assembly: AssemblyVersion("1.13.1231.*")]

However, upon compiling, I see in the Windows Explorer file properties that the Product Version is still 1.0.0.0.
What am I missing? I've done this before.
I am using Visual Studio 2010 Web Developer Express.

A: You need to set the AssemblyInformationalVersion which sets the ProductVersion
[assembly: AssemblyInformationalVersion("1.0.0.0")]

Note there is also a File Version as well.
[assembly: AssemblyFileVersion("1.0.0.0")]

This answer provides more details:
What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?


text:
Q: how to call php in html file anybody please help me with this, I've been stuck with this for a week
This is my coding
attandance_kehadiran_saya.html

attendance_kehadiran_saya.php

                                    Masa
                                    Jenis
                                    Tujuan

                                <?php
                                $q_attendance = $cls_waa->kehadiransaya($id, $date);
                                foreach($q_attendance as $r_attendance)
                                {
                                    $wa_time_in = $r_attendance['wa_time_in'];
                                    $wa_time_out = $r_attendance['wa_time_out'];

                                ?>

                                    <?php echo $wa_time_in; ?>
                                    <?php echo $wa_time_out; ?>

                                <?php } ?>

suppose at my html page, php page will replace there, but it not, without showing any error. Can anybody help me please

A: The problem appears to be that you are POSTing to a PHP page where you are trying to retrieve data from. Considering you're not passing any JavaScript variables, instead of using AJAX at all, why not simply echo the contents of the PHP page into the DIV you want in the HTML itself?
Assuming attendance_kehadiran_saya.php displays the exact output that you want to inject as part of attandance_kehadiran_saya.html, inside the kehadiransaya div, just change attandance_kehadiran_saya.html to:

    <?php include('attendance_kehadiran_saya.php'); ?>

Hope this helps!


text:
Q: Google Analytics incised of Facebook i wanna put the google analytics inside of Facebook.
I use the static HTML and the FBML , and i put the code of Google Analytics in the page (the javascript). However i can't get any results in google analytics.
Can someone tell how can i resolve that issue ?

A: That is probably impossible. Facebook should provide their own analytics.
Reason, you can't have it is because facebook probably eliminates Javascript form the content you post for security reasons.
Start here:
https://www.facebook.com/help/336893449723054/


text:
Q: How do you iterate a JavaScript object in reverse order? I have a nested object containing years and a publication identifier. How do I list the publications by year, latest to earliest? I read here that order of objects is predictable as of ES6. In my code, I have a function that produces a dropdown list of years (addOption) and another that populates a div with the publications for the selected year or all years (populatePubs). If a user selects all years, the publications are presented in order from earliest to latest (ascending), but I want the publications to display in reverse chronological order. Is there a built-in JavaScript object method that can do this?

const testPubs = {
  2019 : {
    '19-6N': {
      'author' : 'jimbo',
      'title' : 'test title'
    },
    '19-7N': {
      'author' : 'jimmy',
      'title' : 'test title 2'
    }
  },
  2018 : {
    '18-6N': {
      'author' : 'joey',
      'title' : 'test title'
    },
    '18-7N': {
      'author' : 'jeffy',
      'title' : 'test title 2'
    }
  },
  2017 : {
    '17-6N': {
      'author' : 'bob',
      'title' : 'test title'
    },
    '17-7N': {
      'author' : 'bobby',
      'title' : 'test title 2'
    }
  },
}

const startYear = 1984;
const currentYear = new Date().getFullYear();

function addOption() { // adds years to dropdown menu
  const select = document.querySelector('#selectYears');
  let blank_option = document.createElement("option");
  blank_option.setAttribute("selected", true);
  blank_option.setAttribute("disabled", true);
  blank_option.textContent = `Year`;
  select.appendChild(blank_option);
  for (let i = currentYear; i >= startYear; i--){
    let option = i;
    let el = document.createElement("option");
    el.textContent = option;
    select.appendChild(el);
  }
  const allYears = document.createElement("option");
  allYears.textContent = `All Years`;
  select.appendChild(allYears)
}
addOption(); // add years dropdown

function populatePubs(year){
  const pubsForYear = document.querySelector("#pubsByYear");
  pubsByYear.class = year;
  while (pubsForYear.firstChild){
    pubsByYear.removeChild(pubsByYear.firstChild);
  }
  if (year in testPubs){
    for (let pub in testPubs[year]){ // add publications for specified year
      let doc = document.createElement("div");
      doc.id = pub;
      doc.textContent = `${testPubs[year][pub].author} - ${testPubs[year][pub].title} - ${pub}`;
      pubsByYear.appendChild(doc);
  }
} else if (year === 'All Years') { // need to ensure order of object is descending
    for (let yr in testPubs){ // add publications for all years
        const yearHeader = document.createElement("h4");
        yearHeader.innerText = yr;
        pubsByYear.appendChild(yearHeader);
      if (typeof testPubs[yr] === 'object'){
        for (let pub in testPubs[yr]) {
          pubsByYear.class = `All Years`;
          const doc = document.createElement("div");
          doc.id = testPubs[yr][pub];
          doc.textContent = `${testPubs[yr][pub].author} - ${testPubs[yr][pub].title} - ${pub}`;
          pubsByYear.appendChild(doc);
        }
      }
    }
  }
}
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Test Publications by Year</title>

  <select id="selectYears" onchange="populatePubs(this.value)"></select>

A: You could just use the built in reverse method on arrays in combination with the Object.keys method :
function populatePubs(year) {
  const pubsForYear = document.querySelector("#pubsByYear");
  pubsByYear.class = year;
  while (pubsForYear.firstChild) {
    pubsByYear.removeChild(pubsByYear.firstChild);
  }
  if (year in testPubs) {
    for (let pub in testPubs[year]) { // add publications for specified year
      let doc = document.createElement("div");
      doc.id = pub;
      doc.textContent = `${testPubs[year][pub].author} - ${testPubs[year][pub].title} - ${pub}`;
      pubsByYear.appendChild(doc);
    }
  } else if (year === 'All Years') { // need to ensure order of object is descending
    const years = Object.keys(testPubs).reverse();
    for (let yr of years) { // add publications for all years
      const yearHeader = document.createElement("h4");
      yearHeader.innerText = yr;
      pubsByYear.appendChild(yearHeader);
      if (typeof testPubs[yr] === 'object') {
        for (let pub in testPubs[yr]) {
          pubsByYear.class = `All Years`;
          const doc = document.createElement("div");
          doc.id = testPubs[yr][pub];
          doc.textContent = `${testPubs[yr][pub].author} - ${testPubs[yr][pub].title} - ${pub}`;
          pubsByYear.appendChild(doc);
        }
      }
    }
  }
}


text:
Q: Deduplicate: Different File Contents Found Error for SBT and Scala I am trying to build a JAR file through SBT, with my driver script being in Scala. However, when I run 'sbt assembly' I receive a large slew of:
deduplicate: different file contents found in the following:

The entire list of directories displaying that message is too large to post here, so I attached a screenshot which you can view below. My build file contains the following:
libraryDependencies ++= Seq("org.apache.spark" %% "spark-core" % "2.0.0" % "provided", "org.apache.spark" %% "spark-mllib" % "2.0.0")

I attempted the solution offered by Onilton Maciel to this question, but to no avail. I am also confused as to how to implement the solution offered by Martin Senne, as the setup instructions on the 'Setup' section for the Assembly plugin are not clear on how to implement his code snippet. Any help would be appreciated. Thanks

A:
as the setup instructions on the 'Setup' section for the Assembly plugin are not clear on how to implement his code snippet.

It means you should add merge strategy in build.sbt or in root directory sbt files.
There is an example from sbt-assembly official document and update it with your conflicts:
import sbtassembly.MergeStrategy
assemblyMergeStrategy in assembly := {
  case PathList("org", "apache", "hadoop", "yarn", "factories", "package-info.class")         => MergeStrategy.discard
  case PathList("org", "apache", "hadoop", "yarn", "provider", "package-info.class")         => MergeStrategy.discard
  case PathList("org", "apache", "hadoop", "util", "provider", "package-info.class")         => MergeStrategy.discard
  case PathList("org", "apache", "spark", "unused", "UnusedStubClass.class")         => MergeStrategy.first
}

Hopeful it's helpful for you.


text:
Q: Publisher subscriber pattern communication between Angular 6 applications via iframe I'm working on a solution where an angular application is consumed inside an iframe of another angular application. The child app need some parameters to show the correct information into the app parent. I read a lot of solution around the web and a good solution is to apply the design pattern publisher/subscriber.
A lot of example are between component inside the same application and I'm wondering if the same solution with rxjs objects is the right way (as shown here).
My doubt is: how I subscribe the child application to the parent (an external publisher)?
I was thinking on a REST API exposed by the parent for registration and unregistration of subscriber, but I'm not sure.
Any experience with this situation? Thanks in advance

A: The only way that I've seen this done, is via CustomEvent objects.
The page that wants to send a notification does it using this:
<script>
    window.onload = function () {
        /* The parent window hosts the Angular application */
        const parent = window.parent;
        /* Send an event to the message handler */
        const event = new CustomEvent('example-unique-string', { field1: 'value', field2: 'value' });
        parent.dispatchEvent(event);
    };
</script>

You then handle this message using:
window.addEventListener('example-unique-string', () => { /* some function */ }, false);

And of course, you can do it in both directions.
I would of course avoid using the iframe at all if I can, but you'll know what's appropriate for your situation.

A: you can make a use of window.postmessage method to post the messsage across iframe and parent application. You can also post the data along with the event.
https://javascript.info/cross-window-communication
You can refer to above link to post the message to and from iframe.


text:
Q: Wrong content-type(old header sent) being received by server side I updated afnetwork to 2.0 due to 64 bit. I made a mistake at first using AFHTTPRequestSerializer, but the server side accept Json only. The wried thing was it works fine for me even I used AFHTTPRequestSerializer, so I didn't notice this problem and released the error app to public. Then I keep receiving user complain and somehow I rebuild my app on my device, and local server can catch my wrong content-type(application/x-www.form-urlencoded). After I updated the AFHTTPRequestSerializer to AFJSONRequestSerializer, it doesn't fix the problem, but the user still keep sending wrong content-type to server even they updated the app. New user has no problem, only happen on old user.
Is this related to cache problem?
Server Log:
10:22:53 AM] Mark 1 contentType is: application/x-www-form-urlencoded,      method is: POST  headers are: Connection=keep-alive&Content-Length=1880739&Content-Type=application%2fx-www-form-urlencoded&Accept=*%2f*&Accept-Encoding=gzip%2c+deflate&Accept-Language=en%3bq%3d1&Cookie=ASP.NET_SessionId%3dbby5dlk5afmsnqnoqpprvqpw&Host

10:04:56 AM]        contentType is: application/json,                       method is: POST header is: Connection=keep-alive&Content-Length=40352  4&Content-Type=application%2fjson        &Accept=*%2f*&Accept-Encoding=gzip%2c+deflate&Accept-Language=en%3bq%3d1&Cookie=ASP.NET_SessionId%3dcw3gdkg3sff1f0j50z2rnism&Host

my code is
 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];

AFHTTPRequestOperation *operation = [manager POST:_url parameters:requestParams success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"operation success: %@\n %@", operation, responseObject);
    NSDictionary *decoded = [self processResponce:responseObject failureBlock:failureBlock];

                            if (!decoded) return;
                            BOOL containsError = [self checkErrorStatus:decoded failureBlock:failureBlock];
                            if (containsError) return;
                            successBlock(decoded[@"Data"]);

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        failureBlock(FailureTypeUnknown, [error localizedDescription]);
}];

[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
progressBlock(bytesWritten,totalBytesWritten,totalBytesExpectedToWrite);
}];

A: as per your response, please set your manager's content type as below
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];


text:
Q: Should I use the Too Many Rows Error as my exception clause in my Oracle Update statement? I have a series of update statements that I need to use in my Oracle package. It's rare but there may be an occasional and unavoidable user error that would result in one of the update statements throwing a "Single row sub-query returns one or more rows" Error.
I've been looking into exception handling for oracle PL/SQl and I'm a bit stuck on how and what to use to catch this exception so the package doesn't crash.
I know of the pre-built "Too Many Rows" exception clause that exists but everything I read seems to say it is used for improper insert statements.
Can I use this as my exception? Or do I need to build my own exception clause. I've never built one myself before and have only a rough idea on where to put everything needed for it.
The following code is basically how the updates are set up in this particular procedure
but for the sake of brevity I'm only using a bare bones example of how it looks.
INSERT INTO TempTable... --(Initial insert statement)

UPDATE TempTable t SET t.Row_one = (SELECT (Statement_One))
WHERE T.Row_One is NULL

UPDATE TempTable t SET t.Row_one = (SELECT (Statement_Two))
WHERE T.Row_One is NULL

UPDATE TempTable t SET t.Row_one = (SELECT (Statement_Three))
WHERE T.Row_One is NULL

-- Does the exception clause start here?
EXCEPTION
    WHEN TOO_MANY_ROWS THEN
(What do I tell the Procedure to do here, what am I able to tell it to do?)

--end of updates that need the exception handling

-- more insert statements into other tables based on data from the preceding Temp Table

END;

Will this work or do I need to build a custom exception?
Thanks in advance.

A: First, the TOO_MANY_ROWS exception will not catch the case where your select statements return multiple rows. The TOO_MANY_ROWS exception is for ORA-01422 when you issue a SELECT .. INTO statement that returns more than one row. The exception you'll encounter in your case is ORA-01427, Single row subquery returns more than one row.
If you want to handle this specific error in your procedure, use the EXCEPTION_INIT pragma to associate an exception name with the error:
too_many_values EXCEPTION;
PRAGMA EXCEPTION_INIT(too_many_values, -1427);

Then you can reference this name in your exception handler:
EXCEPTION
    WHEN TOO_MANY_VALUES THEN
       {perform your handler here}

What you put in the handler depends on what your procedure does. Many times you'll want to return some sort of error code/message to your caller:
PROCEDURE my_proc(p_one VARCHAR2, p_err OUT VARCHAR2) IS
    too_many_values EXCEPTION;
    PRAGMA EXCEPTION_INIT(too_many_values, -1427);
BEGIN
...
EXCEPTION
   WHEN TOO_MANY_VALUES THEN
      p_err := 'More than one value available to assign in the update';
      RAISE;  -- re-raise the exception for the caller

   WHEN OTHERS THEN
      p_err := SQLERRM;  -- return the oracle message for the unexpected error
      RAISE;
END;

Another approach is to skip the specific exception handlers and return generic oracle messages in the WHEN OTHERS handler:
EXCEPTION
  WHEN OTHERS THEN
    p_err := SQLERRM;
END;

The advantage with the first approach is you can customize your messages to be more end-user friendly when the output from the process is fed directly back to the user. The advantage with the latter approach is there is less coding involved. Error handling is an important and often skimped on aspect of any application.
The documentation from Oracle is here.
EDIT:
If this is a package, and you want to avoid passing a long chain of error variables through a series of procedure calls, you could declare an error variable with package scope, set it when the error is encountered, and RAISE the error again.
PACKAGE BODY my_pkg is
  g_err  VARCHAR2(256);

PROCEDURE procx(... , p_err OUT VARCHAR2) IS...
  ...
  proc_y(p1);
EXCEPTION
  WHEN OTHERS THEN
    p_err := NVL(g_err, SQLERRM);
END;

PROCEDURE proc_y(p1 VARCHAR2) IS
...
proc_z(p2);

END;

PROCEDURE proc_z(p2 VARCHAR2) IS
  too_many_values EXCEPTION;
  PRAGMA EXCEPTION_INIT(too_many_values, -1427);
BEGIN
  ....
EXCEPTION
   WHEN TOO_MANY_VALUES THEN
      g_err := 'More than one value available to assign in the update';
      RAISE;  -- re-raise the exception for the caller
END;

When the exception is raised in proc_z, it is handled and then raised again. It propagates back through proc_y (no handler there) and then gets returned to the user in proc_x. Errors not set in the global g_err get the generic Oracle error message. This avoids having to pass the initial error parameter throughout the package.


text:
Q: Tell if specific char in string is a long char or a short char Be prepared, this is one of those hard questions.
In Farsi or Persian language ی which sounds like y or i and is written in 4 different shapes according to it's place in word. I'll call ی as YA from now for simplification.
take a look at this image

All YA characters are painted in red, in the first word YA is attached to it's previous (right , in Farsi we right from RIGHT to LEFT) character and is free at the end whereas the last YA (3rd word, left-most red char) is free both from left or right.
Having said this long story, I want to find out if a part of a string ends with long YA (YA without points) or short YA (YA with two points beneath it).
i.e تحصیلداری (the 3rd word) ends with long YA but تحصیـ which is a part of 3rd word does not ends with short YA.
Question: How can I say تحصیلداری ends whit which unicode? I just have a simple string, "تحصیلداری", how can I convert its characters to unicode?
I tried the unicodes
string unicodes = "";
foreach (char c in "تحصیلداری")
{
    unicodes += c+" "+((int)c).ToString() + Environment.NewLine;
}
MessageBox.Show(unicodes);

result :

but at the end of the day unfortunately all YAs have the same unicode.

Bad news : YA was an example, a real one though. There are also a dozen of other characters like YA with different appearances too.

Additional info :
using this useful link about unicodes I found unicode of different YAs

A: Despite there are different YEHs in Unicode, it must noticed that all presentation forms of YEHs are same Unicode character with code 0x06cc. You can not determine presentation forms by their Unicode code.
But you can reach your goal be checking to see what characters is before or after YEH.
You can also use Fardis to see Unicode codes of strings.

A: We solved similar problem the way bellow:
We had a core banking application, the customer sub-system needed a full text search on customers name, family, father name etc.
Different encoding, legacy migrated data, keyboard layouts and Farsi fonts ... made search process inaccurate.
We overcame the problem by replacing problematic characters with some standard one and saving the standard string for search purpose.
After several iterations, the replacement is as bellow that may come in handy:
Formula="UPPER(REPLACE(REPLACE(REPLACE
(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE
(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE
(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE
(REPLACE(REPLACE(REPLACE(REPLACE
(REPLACE(FirsName || LastName || FatherName,
 chr(32),''),
 chr(13),''),
 chr(9),''),
 chr(10),''),
 '-',''),
 '-',''),
 'آ','ا'),
 'أ', 'ا'),
 'ئ', 'ي'),
 'ي', 'ي'),
 'ك', 'ک'),
 'آإئؤةي','اايوهي'),
 'ء',''),
 'شأل','شاال'),
 'ا.','اله'),
 '.',''),
 'الله','اله'),
 'ؤ','و'),
 'إ','ا'),
 'ة','ه'),
 ' ا لله','اله'),
 'ا لله','اله'),
 ' ا لله','اله'))"


text:
Q: How to get NSToolbar Height? How do I know NSToolbar height? When I place a NSView inside a NSWindow with a NSToolbar on, how do I set the height of the NSView so it can take all available height in the window?

A: In macOS 11 or newer, you can make use of safeAreaInsets to determine the height of the toolbar in case you have enabled setting 'Full Size Content View':
guard let contentView = window?.contentView else {
    return
}

let toolbarHeight = contentView.safeAreaInsets.top

A: If you set/replace the contentView of the window, the window will automatically and necessarily resize it to the right size (or resize itself if the view's size is constrained with greater priority than NSLayoutConstraint.Priority.windowSizeStayPut).
If you're putting your view within the provided content view, then the content view's bounds indicates the rectangle within which your view will be placed.
If you just want the content rect of the window, you can get that with window.contentRect(forFrameRect:window.frame).

A: In my experience you don't need to account for the toolbar height; the runtime does that for you automatically.  Just add the view as you ordinarily would.  Programmatically it would look like this:
let view = CustomView( frame:NSMakeRect(0, 0, _wndW, _wndH) )
 window.contentView!.addSubview (view)


text:
Q: X11 connection rejected because of wrong authentication in Mininet I am getting this message whenever I run xterm from within mininet:
mininet> xterm h1
mininet> X11 connection rejected because of wrong authentication.

However, if I run it as:
mininet@mininet-vm:~$ xterm

It shows the window as normal.
I only experience this issue with Mininet running on virtual box with ubuntu 20.04.02.
With other ubuntu version (14.04.06), xterm works fine.
Any help on this would be appreciated..

A: I struggled with the same error but adding -E while creating the topology fixed it for me.

*

*sudo -E mn or sudo -E mn --custom.... for custom topologies

*xterm h1 h2

xterm works as it normally would.

A: Had a similar issue at some point. The problem was that when you are running the mininet console you do that as root and not as the ssh'ed user - mininet in your case. I vaguely remember resolving it by creating .Xauthority files and giving the root user and the mininet user permissions to them... Can't remember the whole procedure now, hopefully this would give you a clue.
Page #27 of this document suggests a possible resolution.
What they suggest is:

*

*As your non-root user do xauth list $DISPLAY. This should return a line describing the display. in my case,
ubuntu-bionic/unix:0 MIT-MAGIC-COOKIE-1 SOME_HASH. Copy that line.

*Now, log-in as the super user sudo -s

*Authorize that display information for the root user xauth add LINE_YOU_COPIED_IN_1.

*That should be it
If you see an error about .Xauth not existing follow this link to create one and go back to step 1.


text:
Q: Why use survival function to find p-value for t-test? The documentation for SciPy's stats module describes the following method for finding the p-value from a two-sided (one-sample) t-test:

We can use the t-test to test whether the mean of our sample differs in a statistically significant way from the theoretical expectation.
   >>> print 't-statistic = %6.3f pvalue = %6.4f' %  stats.ttest_1samp(x, m)
   t-statistic =  0.391 pvalue = 0.6955`

The pvalue is 0.7, this means that with an alpha error of, for example, 10%, we cannot reject the hypothesis that the sample mean is equal to zero, the expectation of the standard t-distribution.
As an exercise, we can calculate our ttest also directly without using the provided function, which should give us the same answer, and so it does:
    >>> tt = (sm-m)/np.sqrt(sv/float(n))  # t-statistic for mean
    >>> pval = stats.t.sf(np.abs(tt), n-1)*2  # two-sided pvalue = Prob(abs(t)>tt)
    >>> print 't-statistic = %6.3f pvalue = %6.4f' % (tt, pval)
    t-statistic =  0.391 pvalue = 0.6955

If look carefully, you'll notice the authors use stats.t.sf(), the survival function (1-CDF), to calculate the p-value.
Why not just use the regular CDF? Is there a particular reason the survival function was used? This seems obtuse.

A: I am assuming you're not asking "why calculate this quantity" (which is a question about the definition of a p-value) but rather "why calculate the quantity as $2S(|t|)$ when you could calculate it from $2(1-F|t|)$?".
The answer is mostly a matter of numerical accuracy. For large $x$, $S(x)$ can be computed to high accuracy and then doubled, while the corresponding $F$ is very close to $1$, leading to catastrophic cancellation when computing $1-F$.


text:
Q: getting substrings in each array index using a delimeter given an array
String original[]={"string0,10","string1,45","string2,3", "string3,67"};

how would I use the comma as a delimeter to create another array with only the names?
I need an array that looks something like this:
String result[]={"string0","string1","string2", "string3"};

A: You can use streams and map from java 8 to do it:
String[] strings = Arrays.stream(test)
            .map(string -> string.split(",")[0])
            .toArray(String[]::new);

A: public static void main(String[] args) {
    String original[]={"string0,10","string1,45","string2,3", "string3,67"};
    int len = original.length;
    String result[] = new String[len];
    for(int i=0; i<len;i++) {
        result[i] = original[i].split(",")[0];
    }

    System.out.println(Arrays.toString(result));
}

*

*DeclareString result[] array

*Iterate the array

*Split the record for every Iteration using , as delimiter

*Now the split operation will return the array of size 2.  It contains name at index 0.

*assign the value the result array.

A:

import java.util.Arrays;
import java.util.stream.Collectors;

public class ArraySubstring {

    public static void main (String args[]) {
        String test[]={"string0,10","string1,45","string2,3", "string3,67"};

        String test2[] = Arrays.stream(test).map(s -> s.substring(0, s.indexOf(","))).toArray(String[]::new);
        for (String s : test2) {
            System.out.println(s);
        }
    }
}


text:
Q: Getting object Object in request & parameters Observing following in rails server logs:
Started GET "/jwt_api/navbar_stats?brand_id=%5Bobject%20Object%5D&user_id=%5Bobject%20Object%5D" for ::1 at 2022-11-29 12:24:04 +0530
Processing by JwtApi::NavbarStatsController#show as JSON
  Parameters: {"brand_id"=>"[object Object]", "user_id"=>"[object Object]"}

Request raised from React side:
import { isEqual, get } from 'lodash'
import Cookies from 'js-cookie'

export const REQUEST_NAVBAR_STATS = 'REQUEST_NAVBAR_STATS';
export const RECEIVE_NAVBAR_STATS = 'RECEIVE_NAVBAR_STATS';

const requestNavbarStats = () => ({ type: REQUEST_NAVBAR_STATS });
const receiveNavbarStats = (data) => ({ type: RECEIVE_NAVBAR_STATS, data });

export const fetchNavbarStats = () => (dispatch) => {
  console.log("bId", Cookies.get('bId'));
  console.log("uId", Cookies.get('uId'));
  dispatch(requestNavbarStats());
  $.ajax({
    method: 'get',
    url: `${process.env.REACT_APP_BASE_URL}/jwt_api/navbar_stats`,
    data: { brand_id: Cookies.get('bId'), user_id: Cookies.get('uId') },
    success(data) {
      dispatch(receiveNavbarStats(data));
    },
    error(xhr) {
      console.log(xhr)
      // dispatch(receiveServerErrors(xhr));
    },
  });
};

Rails NavbarStatsController#show code is as follows:
class JwtApi::NavbarStatsController < JwtApiController
  def show
    render json: {
      counts: counts,
      current_user: current_user,
      brands: brands,
      currentBrand: current_brand,
      brandPicture: current_brand.try(:picture),
      roles: current_user.roles.pluck(:name),
      priority_notification: {
        new_videos_count: new_videos,
        trending_videos_count: t_videos,
      }
    }
  end
end

Expecting to get brand_id & user_id in request & parameters as follows:
Started GET "/jwt_api/navbar_stats?brand_id=62181bf113d9c187cb00004c&user_id=58bd3736acce3487e7000001" for ::ffff:103.179.39.185 at 2022-11-29 07:08:58 +0000
Processing by JwtApi::NavbarStatsController#show as JSON
  Parameters: {"brand_id"=>"62181bf113d9c187cb00004c", "user_id"=>"58bd3736acce3487e7000001"}

Using MongoDB as database.