text:
Q: Android Hide Soft Keyboard from EditText while not losing cursor I've come about as far as this which gets me halfway there, but not quite.
I have a dialer Fragment that has all the usual Buttons to enter a number including backspace, so I don't need the soft keyboard. I'd also like to give the user the ability to paste text (long click... works fine per default), as well as to edit what has been entered so I need the cursor.
The easiest way I found to make sure the soft keyboard doesn't pop up if the user clicks inside the EditText is to set the inputType to null - but that kills the cursor as well.
So, how do I declare my EditText and what kind of commands should I launch to have my EditText field never ever show the soft keyboard no matter what the user attempts, but still retain paste functionality and the cursor?
I've also tried android:windowSoftInputMode="stateAlwaysHidden" in my manifest, but to no avail.

A: I have finally found a (for me) working solution to this.
First part (in onCreate):
// Set to TYPE_NULL on all Android API versions
mText.setInputType(InputType.TYPE_NULL);
// for later than GB only
if (android.os.Build.VERSION.SDK_INT >= 11) {
    // this fakes the TextView (which actually handles cursor drawing)
    // into drawing the cursor even though you've disabled soft input
    // with TYPE_NULL
    mText.setRawInputType(InputType.TYPE_CLASS_TEXT);
}

In addition, android:textIsSelectable needs to be set to true (or set in onCreate) and the EditText must not be focused on initialization.  If your EditText is the first focusable View (which it was in my case), you can work around this by putting this just above it:
<LinearLayout
  android:layout_width="0px"
  android:layout_height="0px"
  android:focusable="true"
  android:focusableInTouchMode="true" >
    <requestFocus />
</LinearLayout>

You can see the results of this in the Grapher application, free and available in Google Play.

A: This worked for me:
        // Update the EditText so it won't popup Android's own keyboard, since I have my own.
    EditText editText = (EditText)findViewById(R.id.edit_mine);
    editText.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            v.onTouchEvent(event);
            InputMethodManager imm = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null) {
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
            return true;
        }
    });

A: Setting the flag textIsSelectable to true disables the soft keyboard.
You can set it in your xml layout like this:
<EditText
    android:id="@+id/editText"
    ...
    android:textIsSelectable="true"/>

Or programmatically, like this:
EditText editText = (EditText) findViewById(R.id.editText);
editText.setTextIsSelectable(true);

The cursor will still be present, you'll be able to select/copy/cut/paste but the soft keyboard will never show.

A: Best solution from @Lupsaa here:
Setting the flag textIsSelectable to true disables the soft keyboard.
You can set it in your xml layout like this:
<EditText
android:id="@+id/editText"
...
android:textIsSelectable="true"/>

Or programmatically, like this:
EditText editText = (EditText) findViewById(R.id.editText);

editText.setTextIsSelectable(true);
The cursor will still be present, you'll be able to select/copy/cut/paste but the soft keyboard will never show.

A: If your min SDK is 21, you can this method from java code:
editText.setShowSoftInputOnFocus(false);

Credits to Chen Su article.

A: use
android:windowSoftInputMode="stateHidden"

in your manifest file instead of android:windowSoftInputMode="stateAlwaysHidden"

A: This is what I did.
First, in manifest inside activity
android:windowSoftInputMode="stateAlwaysHidden|adjustNothing"

Second, in onCreate if inside activity or onActivityCreated if inside fragment
editText.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            hideSoftKeyboard(v);
        }
    });

Do not forget to request focus to the editText
editText.requestFocus();

Then add the hideSoftKeyboard(v) method same as the other answer.
private void hideSoftKeyboard(View v){
    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
}

The key here is to requestFocus before clicking the EditText. If without focus, first click will make the keyboard show up(my experience). However, this is applied if you have a single EditText in an activity. With this, you still can type with custom keyboard(if any), can copy and paste, and cursor is still visible.

A: The exact functionality that you require is provided by setting the flag textIsSelectable in EditText to true. With this, the cursor will still be present, and you'll be able to select/copy/cut/paste, but SoftKeyboard will never show. Requires API 11 and above.
You can set it in your xml layout like this:
<EditText
    android:textIsSelectable="true"
    ...
/>

Or programmatically, like this:
EditText editText = (EditText) findViewById(R.id.editText);
editText.setTextIsSelectable(true);

For anyone using API 10 and below, hack is provided here :
 https://stackoverflow.com/a/20173020/7550472

A: This works perfectly (for me) in 2 steps:

*

*<activity... android:windowSoftInputMode="stateHidden"> in manifest file

*Add these properties in your editText XML code
android:focusable="true"
android:focusableInTouchMode="true

You have to put both 1 and 2, only then it will work.
Cheers

A:     EditText text = (EditText) findViewById(R.id.text);
    if (Build.VERSION.SDK_INT >= 11) {
        text.setRawInputType(InputType.TYPE_CLASS_TEXT);
        text.setTextIsSelectable(true);
    } else {
        text.setRawInputType(InputType.TYPE_NULL);
        text.setFocusable(true);
    }

A: First add android:windowSoftInputMode="stateHidden" in your manifest file, under the activity.  like this
<activity... android:windowSoftInputMode="stateHidden">

The on your xml add this android:textIsSelectable="true" . This will make the pointer visible.
Then on onCreate method of the activity, add this:
EditText editText = (EditText)findViewById(R.id.edit_text);
edit_text.setOnTouchListener(new OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        v.onTouchEvent(event);
        InputMethodManager inputMethod = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethod!= null) {
            inputMethod.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
        return true;
    }
});

A: i found this very useful code and it work as charm, it head the Keyboard totaly, but keeping cursor and you can copy past, move the cursor...ect
using :
hideSoftKeyboard(editText);

methode :
  public void hideSoftKeyboard(EditText edit) {
           if (android.os.Build.VERSION.SDK_INT <= 10) {
               edit.setInputType(InputType.TYPE_NULL);
           } else {
               this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
               try {
                   Class<EditText> cls = EditText.class;
                   Method setSoftInputShownOnFocus;
                   setSoftInputShownOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
                   setSoftInputShownOnFocus.setAccessible(true);
                   setSoftInputShownOnFocus.invoke(edit, false);
               } catch (Exception e) {
                   e.printStackTrace();
               }
           }
       }

A: EditText editText = (EditText)findViewById(R.id.edit_mine);
    editText.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        v.onTouchEvent(event);
        InputMethodManager imm = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
        return true;
    }
});

ha... this is the correct way of doing...this job done... this gonna work !

A: You can use the following line of code in the activity's onCreate method to make sure the keyboard only pops up when a user clicks or touch into an EditText Field. I tried lots of methods and codes from stackoverflow but didnt work any but this
Works Perfectly for me!! Try this.. :)`
 this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

A: You can use the following line of code in the activity's onCreate method to make sure the keyboard only pops up when a user clicks or touch into an EditText Field. I tried lots of methods and codes from stackoverflow but didnt work any but this Works Perfectly for me!! Try this.. :)`
        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);


text:
Q: System of equations that I'm having trouble with $a/(x+y) - b/(x-y) = 1$
$b/(x+y) + a/(x-y) = (b^2-a^2)/2ab$
The answer to the values of $x$ and $y$ are given as $x=a-b, y=a+b$.
How is that achieved?

A: One way to solve that is to let $u=x+y$, $v=x-y$, and solve for $u$ and $v$. Then use
$$x=\frac{u+v}2,\quad y=\frac{u-v}2$$
That is probably easier than solving for $x$ and $y$ directly.

A: Here is a straightforward solution without using any trick, but you can follow it step by step. First, we multiply the first equation by $x^2-y^2$ to obtain a polynomial equation
$$
ax - ay - bx - by - x^2 + y^2=0
$$
Similarly, we multiply the second equation by $2ab(x^2-y^2)$ to obtain a polynomial equation. Then we compute $(a^2-b^2)$ times the first equation minus the second one. This gives a third equation, namely
$$
(a^2 + b^2)(ax - ay + bx + by)=0.
$$
We can dispose of $a^2+b^2=0$, because we assume $ab\neq 0$ from the beginning.
Hence we obtain $x(a+b)+y(b-a)=0$. Substituting $x$ from this in the first equation gives $(a+b-y)aby=0$ hence $y=a+b$. Then $x=a-b$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: kubernetes: cannot access service on VirtualBox cluster via ClusterIP / NodePort I created a 3-node kubernetes cluster (1 master + 2 workers) on VirtualBox using the instructions here. I am using Flannel for the overlay network.
I set sysctl -w net.bridge.bridge-nf-call-iptables=1 and sysctl -w net.bridge.bridge-nf-call-ip6tables=1 on the master during installation. I hadn't set them on the workers at that time, but I set them later and rebooted both nodes.

*

*I have a trivial web app written in Go, listening on port 8080. I created a pod + replication controller thus:
kubectl run foo --image=<...> --port=8080 --generator=run/v1

I am able to access my service using the POD IP and port 8080.

*I also created a ClusterIP service.
kubectl expose rc foo --name=foo-http --port=8081 --target-port=8080                   # ClusterIP service

# kubectl get svc foo-http
NAME       TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)    AGE
foo-http   ClusterIP   10.106.88.24   <none>        8081/TCP   14m

When I run this from any cluster node, it hangs:
curl http://10.106.88.24:8081   # that's the ClusterIP

By running strace, I can see that curl initiates a non-blocking connect, and spins in a loop on poll, without the socket ever becoming ready for a read - so the connection doesn't go through.

*If I create a NodePort service instead, I simply get connection refused.
# cat svc_nodeport.json
apiVersion: v1
kind: Service
metadata:
  name: foo-http
spec:
  type: NodePort
  ports:
  - port: 8081
    targetPort: 8080
    nodePort: 31123
  selector:
    app: foo

# kubectl create -f svc_nodeport.json
# kubectl get svc foo-http
NAME       TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)          AGE
foo-http   NodePort    10.104.78.88   <none>        8081:31123/TCP   7m

When I try connecting via port 31123:
# curl http://<node-ip>:31123    # Tried on master and both workers
curl: (7) Failed connect to <node-ip>:31123; Connection refused

How do debug this?

A: I think your service manifest selector isn't selecting the pod.
Try to describe the pod and check for the labels.
Kubectl describe pod
Then change your service manifest according to your pod labels.
Best practice is to use declarative ways by writing the deployment or pod manifest, instead of using the imperative commands of kubectl, such as run or create.

A: check first if something wrong :
kubectl describe service foo-http

and try other network cluster (for example: remove current network and deploy weave network)
 kubectl get -n kube-system daemonset | grep -i Flannel |cut -f1 -d ' '| kubectl delete daemonset -n kube-system
 kubectl apply -f "https://cloud.weave.works/k8s/net?k8s-version=$(kubectl version | base64 | tr -d '\n')"

and for testing change "port" and "targetPort" to 8080 as you mentioned (or remove "targetPort") , like :
ports:
      - port: 8080
        targetPort: 8080
        nodePort: 31123

then
kubectl delete service foo-http

and create your service again Ex.
kubectl create -f UrServiceScript.yaml


text:
Q: Each request of ajax give the data in response The Following code give the same product id on each request
What is causing the problem.
This is form code which is associated with each product.
  <form  action="" method="" id="formproduct">
  <input type="hidden" name="id" class="productid"
  value="<?php echo $row['Product-id'];?>" >
   <button  name="submit" class="btn">Add To Cart</button>
       </form>

This is the ajax requst code.
   var formData = {
        'product': jQuery(".productid").attr("value")
    };

jQuery.ajax({
            type: "POST",
            url: "server-cart.php",///contain the url of ajax
            data:formData,
            dataType:"json",

Here i am getting the id from request.
 $id=$_REQUEST["product"];

A: .attr() returns original value set at html , .val() returns current value of input element. Try substituting .val() for .attr() , use .change() to retrieve current value of input element

$("input").change(function() {
   // `$(this).attr("value")` : `123` : original `value` set at `input`
   // `$(this).val()` : current `value` of `input` element
   console.log($(this).val(), $(this).attr("value"))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input value="123" />

A: You have to like
here you have multiple forms i think
<form  action="" method="" id="formproduct">
  <input type="hidden" name="id" class="productid"
  value="<?php echo $row['Product-id'];?>" >
   <button  name="submit" class="btn" onclick="saveProduct(this)">Add To Cart</button>
       </form>

jQuery
function saveProduct(thisObj){
           //here we find productid value of current row
           var formData = {
                  'product': jQuery(thisObj).closest(".productid").val();
                };

           jQuery.ajax({
            type: "POST",
            url: "server-cart.php",///contain the url of ajax
            data:formData,
            dataType:"json",
            success:function(data){
            }
           });
}

A: So I guess you have multiple forms on your page with a number of different products. You have to rewrite your script to depend on correct form:
$("form").on("click", "button[name=submit]", function(){

    var form = $(this).closest("form"); // find the form to relate to
    var data = { product: $(".productid", form).val() }; // here we fetch product id from the input inside the form

    // do ajax-request
    // ...

    return false;
});


text:
Q: Is using assign() a good way to initialise my C++ vector of structs? The struct
struct Vanish
{
  int iCount;
  int iRow;
};

I defined a std::vector of Vanish as a member of my class, and want to initialise it in the constructor like this:
class BigClass
{
  public:
    BigClass();
  private:
    std::vector<Vanish> tovanish;
};

void BigClass::BigClass()
{
  Vanish empty = {0,0};
  tovanish.assign(MAX_VANISH, empty);
}

Is there a better way, or is this considered OK?

A:
Is there a better way?

Yes, sure,
BigClass::BigClass() : tovanish(MAX_VANISH) {}

This gives you a vector with MAX_VANISH value-initialized Vanish elements.

A: It is better to do that in the constructor's initializer list:
BigClass::BigClass()
: tovanish(MAX_VANISH)
{

}

That way, you'll avoid possible vector reallocations. Note that you vector's constructor will value-initialize its elements. Value-initialization of the int members in Vanish just zeroes them.
Note that in C++11, using uniform-initialization you could specify other values easily:
BigClass::BigClass()
: tovanish(MAX_VANISH, {42, 24})
{

}


text:
Q: Why was the Rebel Blockade Runner so close to Tatooine? At the beginning of Star Wars: A New Hope, we see the Rebel Blockade Runner with Princess Leia and the Droids being pursued by a Star Destroyer above the planet Tatooine.  Practically directly above it, close enough that it could almost be in orbit.
It seems an incredibly strange coincidence that they should run so close to a planet that just happens to play host to Darth Vader's estranged son and former mentor before his turn to the Dark Side.  Moreso that they'd fly so close to any planet at all, when space is so vast and empty.
What reason did the Rebel Blockade Runner have for being so close to Tatooine during this chase?

A: This is not a coincidence at all.
Princess Leia was travelling to Tatooine to meet Obi-Wan Kenobi and ask him to help the Rebel Alliance. When her ship is intercepted, she has to improvise, so she sends R2-D2 to the planet's surface with a message for Obi-Wan:

General Kenobi. Years ago, you served my father in the Clone Wars. Now
  he begs you to help him in his struggle against the Empire. I regret
that I am unable to present my father's request to you in person, but
  my ship has fallen under attack and I'm afraid my mission to bring you
  to Alderaan has failed.

A: This is addressed directly in the new (canon) Star Wars novelisation. Simply put, Leia's mission had two parts. Firstly, to collect the plans for the Death Star and secondly, to collect Obi-Wan Kenobi from his hiding place on Tatooine.

Admitting she failed made the words taste bitter in her mouth. Though
she and the crew of the Tantive IV had downloaded the information and
made the jump to Tatooine, she wouldn't be able to complete the second
part of the mission. Her father had requested that she seek out an old
friend, one General Kenobi, because, in his own words, "a war demanded
warriors" to fight. A legendary Jedi Knight, Kenobi had gone into
secret exile on the remote desert planet to avoid the deadly purge
that had wiped out his order.
A New Hope: The Princess, the Scoundrel, and the Farm Boy

This would obviously explain her proximity to the planet.


text:
Q: Intersection of 3D curves parameterised by piecewise defined functions I need to calculate the intersection of two 3D parametric curves $\vec{C_1}$ and $\vec{C_2}$.

Those curves are parameterised by piecewise functions.
$\vec{C_1}= \begin{pmatrix}x_1(t)\\y_1(t)\\z_1(t)\end{pmatrix}\\
\vec{C_2}= \begin{pmatrix}x_2(t)\\y_2(t)\\z_2(t)\end{pmatrix}$
For example, $x_1(t)$ could look like this:

Ultimately, I need to calculate the intersection in C++ where I could use an arbitrary solver library, but first I need to get the math straight.
How can I transform this problem to a computer solvable formulation?

A: As long as your curves can be described either as by a function or even from data points, you can try to find the value of $t$ that the difference of the two curves to $0$, or approximately $0$ since you are implementing this.:
$$\hat C_1(t) - \hat C_2(t) = 0$$
One problem is that these may not necessarily intersect but that will only be known once it is attempted.


text:
Q: hide the div when scroll down the remaining 100px I want to hide my div, when scrolling down the remaining 100px.
If you have any answer please help me

$(document).scroll(function() {
  var y = $(this).scrollTop();
  if (y > 2300) {
    $('.bottomMenu').show();
  } else if { ?
  } else {
    $('.bottomMenu').hide();
  }
});
.bottomMenu {
  display: none;
  position: fixed;
  top: 10%;
  width: 100%;
  height: 60px;
  border-top: 1px solid #000;
  background: red;
  z-index: 1;
}

ikanbakar

A: This should be the code. you should add a class in css as

bottomMenu.active{}

to define your styles there.
$(window).on("scroll", function() {
    if($(window).scrollTop() > 2300) {
        $(".bottomMenu").addClass("active");
    } else {
       $(".bottomMenu").removeClass("active");
    }
});

A: well if you want this here is the example hope it can help you

$(window).on("scroll", function() {
    if($(window).scrollTop() < 300) {
    //you have to change the value according to your content
        $(".bottomMenu").addClass("game");
    } else {
       $(".bottomMenu").removeClass("game");
    }
});
.bottomMenu{display:none;}
.game {
  display:block;
position: fixed;
top: 10%;
width: 100%;
height: 60px;
border-top: 1px solid #000;
background: red;}

.nav {
  font-weight: normal;
  list-style: none;
  text-align: center;
  width: 100%;
  top: 0;
  padding: 20px 0 20px 0;
  background-color: #4F4F4F;
}

.nav li {
  display: inline-block;
  padding: 0 25px 0 25px;
}

.nav li a {
  text-decoration: none;
  color: #ffffff;
}

.nav li a:hover {
  color: #c1c1c1;
}

.footer {
float:left;

  list-style: none;
  text-align: center;
  position:relative;
  width: 100%;
  bottom: 0;
  padding: 20px 0 20px 0;
}

.footer li {
  display: inline-block;
  padding: 0 25px 0 25px;
  font-weight: lighter;
}

.footer li a {
  text-decoration: none;
  color: #ffffff;
}
header {
    display: inline-block;
    width: 100%;
}

.footer {
    background: #333;
}
body{ margin:0px auto;}

HOME

PROJECTS

ABOUT

    Ensure growth and profitability by extending our product portfolio in other categories of HPC business in domestic and international markets.
    Continuously improve our system and products to enhance customer satisfaction.
    Continue with our commitment to operate business in an ethical manner.
    Develop & motivate ZIL people to build a high performance culture.
    Deliver high quality branded and innovative products and services to ensure customer satisfaction.
    Simplify business processes and reduce complexity to achieve business growth.
    Optimize resources to ensure competitiveness.
    Ensure regulatory and statutory compliance and embed best practices of corporate governance.

ikanbakar

    Ensure growth and profitability by extending our product portfolio in other categories of HPC business in domestic and international markets.
    Continuously improve our system and products to enhance customer satisfaction.
    Continue with our commitment to operate business in an ethical manner.
    Develop & motivate ZIL people to build a high performance culture.
    Deliver high quality branded and innovative products and services to ensure customer satisfaction.
    Simplify business processes and reduce complexity to achieve business growth.
    Optimize resources to ensure competitiveness.
    Ensure regulatory and statutory compliance and embed best practices of corporate governance.

Made by Lumo © 2017

A: can you try this ?
$(document).scroll(function () {
    if(($(document).height() - $(document).scrollTop()) > 100 ) {
       $('.bottomMenu').show();
    } else {
       $('.bottomMenu').hide();
    }
});

or javascript way like
document.documentElement.scrollHeight - document.documentElement.scrollTop


text:
Q: How to fix CentOS 5.5 update dependency? It always has this problem.
--> Finished Dependency Resolution
perl-AnyEvent-5.240-1.el5.rf.noarch from rpmforge has depsolving problems
  --> Missing Dependency: perl(Net::SSLeay) >= 1.33 is needed by package perl-AnyEvent-5.240-1.el5.rf.noarch (rpmforge)
Error: Missing Dependency: perl(Net::SSLeay) >= 1.33 is needed by package perl-
AnyEvent-5.240-1.el5.rf.noarch (rpmforge)

 You could try using --skip-broken to work around the problem
 You could try running: package-cleanup --problems
                        package-cleanup --dupes
                        rpm -Va --nofiles --nodigest
The program package-cleanup is found in the yum-utils package.

I tried to install perl-AnyEvent-5.240-1.el5.rf.noarch.rpm
But it cannot be fixed.
[root@hosted-by pear]# rpm -ivh perl-AnyEvent-5.240-1.el5.rf.noarch.rpm
error: Failed dependencies:
        perl(EV) >= 3.05 is needed by perl-AnyEvent-5.240-1.el5.rf.noarch
        perl(Guard) >= 1.02 is needed by perl-AnyEvent-5.240-1.el5.rf.noarch
        perl(JSON) >= 2.09 is needed by perl-AnyEvent-5.240-1.el5.rf.noarch
        perl(JSON::XS) >= 2.2 is needed by perl-AnyEvent-5.240-1.el5.rf.noarch
        perl(Net::SSLeay) >= 1.33 is needed by perl-AnyEvent-5.240-1.el5.rf.noarch

A: This sounds like the suggested fix at http://mattdanger.net/2010/12/perl-net-ssleay-dependency-error-when-installing-memcached-with-yum/ would help.
But I'm not an rpm user, so be careful.


text:
Q: how to parse `sidx` of MP4 dash file I'm trying to parse the sidx segment to use it on dash streaming! ( I prefer to use javascript for it )
I have the sidx range and I have already buffered it .. but it's all in hexadecimal.
.
I'm trying to make it as a known object to calculate segments range and buffer it into sourcebuffer.
here's the sidx
0000 01dc 7369 6478 0000 0000 0000 0001
0001 5f90 0000 0000 0000 0000 0000 0025
0002 9ae6 0006 df92 9000 0000 0002 95b8
0006 df92 9000 0000 0002 96d5 0006 df92
9000 0000 0002 96d7 0006 df92 9000 0000
0002 97d2 0006 df92 9000 0000 0002 a0ae
0006 df92 9000 0000 0002 990c 0006 df92
9000 0000 0002 9814 0006 df92 9000 0000
0002 967f 0006 df92 9000 0000 0002 929c
0006 df92 9000 0000 0002 98a3 0006 df92
9000 0000 0002 96b3 0006 df92 9000 0000
0002 9715 0006 df92 9000 0000 0002 95bb
0006 df92 9000 0000 0002 956e 0006 df92
9000 0000 0002 9513 0006 df92 9000 0000
0002 9816 0006 df92 9000 0000 0002 9e21
0006 df92 9000 0000 0002 9603 0006 df92
9000 0000 0002 99aa 0006 df92 9000 0000
0002 9956 0006 df92 9000 0000 0002 9c49
0006 df92 9000 0000 0002 988e 0006 df92
9000 0000 0002 97a6 0006 df92 9000 0000
0002 9992 0006 df92 9000 0000 0002 9d00
0006 df92 9000 0000 0002 9567 0006 df92
9000 0000 0002 93bd 0006 df92 9000 0000
0002 9775 0006 df92 9000 0000 0002 99c3
0006 df92 9000 0000 0002 920f 0006 df92
9000 0000 0002 96cd 0006 df92 9000 0000
0002 00bd 0006 df92 9000 0000 0002 96f5
0006 df92 9000 0000 0002 97f2 0006 df92
9000 0000 0001 5ee9 0006 df92 9000 0000
0000 37e3 0001 b7d5 9000 0000

and I have to get this from it:
Screenshot from mp4parser
and I have some references for this but I can't get it completely
ref1
ref2

A: Resolve
Actually, I found the solution myself. Thanks to @kanongil from bitparser now I can parse the bits easily. the structure was the same as the mp4parser and the bit length was on references I shared. you can find everything you need from the links I shared.


text:
Q: Point splitting technique in Peskin and Schroeder One of the cornerstones of point splitting technique of calculating chiral anomaly (Peskin and Schroeder 19.1, p.655) is a symmetric limit $\epsilon \rightarrow 0$. And this is the point that I don't get. Is it really possible to take such a limit?
For example, consider the expression
$$
\text{symm}\,\text{lim}_{\epsilon \rightarrow 0} \Bigl\{\frac{\epsilon^{\mu}\epsilon^{\nu}}{\epsilon^2}\Bigr\} = \frac{g^{\mu \nu}}{d} \tag{19.23}
$$
in $d=2$ spacetime dimensions. Let $\mu = \nu = 0$. Then
$$
\frac{\epsilon^{0}\epsilon^{0}}{\epsilon^2} = \frac{1}{1-(\frac{\epsilon^1}{\epsilon^0})^2}.
$$
But the latter expression either greater than 1 or less than 0 and so can't be equal to $$\frac{g^{00}}{2} = \frac{1}{2}.$$

A: The symmetric limit (19.23)
$$S^{\mu\nu}~:=~ \text{symm}\,\lim_{\epsilon \rightarrow 0} \left\{\frac{\epsilon^{\mu}\epsilon^{\nu}}{\epsilon^2}\right\}, \qquad \epsilon^2~:=~\epsilon^{\mu}g_{\mu\nu}\epsilon^{\nu},$$
should be thought of as a regularization prescription. It is part of a symmetric point splitting regularization scheme, cf. Ref. 1. The traditional notion of limit
$$\lim_{\epsilon \rightarrow 0} \left\{\frac{\epsilon^{\mu}\epsilon^{\nu}}{\epsilon^2}\right\}$$
does not exist. The prescription
$$S^{\mu\nu}~:=~\frac{g^{\mu\nu}}{d}$$
is motivated by three things:

*

*The prescription $S^{\mu\nu}$ can only depend on the metric.

*$S^{\mu\nu}$ should be a (2,0) tensor wrt. Lorentz transformations.

*If we contract $S^{\mu\nu}$ with $g_{\mu\nu}$, the result should be $1$.
References:

*

*M.E. Peskin & D.V. Schroeder, An Intro to QFT; Section 19.1, p. 655.

A: Same logic used in (7.87) in Peskin itself:
$l^{\mu}l^{\nu} \rightarrow \frac{1}{d}l^2 g^{\mu\nu}$.
Ref. Peskin & Schroeder, Section 7.5, p. 251.


text:
Q: Error Handling in Web service XML request I've been trying to perform an XML request. I've faced so many problems that I managed to solve. But this one I couldn't solve.
this is the script:
$url ="WebServiceUrl";
$xml="XmlRequest";
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_MUTE, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
            curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $output = curl_exec($ch);
            curl_close($ch);
 echo $output;

It is giving me this error:
System.InvalidOperationException: Request format is invalid: text/xml. at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters() at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
I'm still a noob at this. So go easy on me:)
thanks.

A: Looks like you're sending stuff as text/xml, which is not what it wants. Find the docs for this web service e.g. WSDL stuff if it's there, and find out what data formats it accepts.
Be sure e.g. that it's not really saying it will respond in XML, after receiving a request as standard HTML POST variables.

A: There are two main content types used with the HTTP POST method: application/x-www-form-urlencoded and multipart/form-data.
The content-type determines what the format of the CURLOPT_POSTFIELDS should be. If you are using the default, which is "application/x-www-form-urlencoded" you probably want to use build_http_query() to construct the url encoded query string.
If you are sending non-ASCII data you canpass an associative array with keys that match the field names and values that correspond to the value for the field. Using this technique will cause the request to be issued with a multipart/formdata content-type.
At this point, it sounds like your next step should be figuring out what fields the API is expecting.
application/x-www-form-urlencoded or multipart/form-data?


text:
Q: is.null on lists vs. other objects Consider the following scenario:
demo <- list()
is.null(demo$first)
is.null(undefined_object)

The first scenario returns TRUE as it's a NULL element of the list. Why doesn't undefined_object return NULL as it's not an object in the global environment?

A: If we need a similar TRUE option, one option is to reference that object with .GlobalEnv and check if it is NULL
is.null(.GlobalEnv$undefined_object)
#[1] TRUE

with OP's example, we are checking whether the 'first' is NULL in the environment of 'demo' object which is already created, but the undefined_object is not created and thus we can check it in context with the global environment
is.null(demo$first)
#[1] TRUE
is.null(.GlobalEnv$demo$first)
#[1] TRUE

A: demo$first calls the function $, and that function returns NULL if the right hand argument is not found.
undefined_object is not a function call, it's just the name of an object, but that object doesn't exist.
If you just print the two expressions, you'll see that they are different:
> demo$first
NULL
> undefined_object
Error: object 'undefined_object' not found

So when you put them in the is.null() call, you get different results, as you saw.


text:
Q: Как объединить два одномерных массива A,B в массив C A-n\
B-m\
A:1,2,3,4\
B:5,6,7,8,9\
C:1,2,3,4,5,6,7,8,9\

Такой ответ должен быть

A: Пусть корзина "А" вмещает n яблок, а корзина "B" - m, тогда для объединения вам необходимо взять корзину "C" с минимальным объемом m+n и по одному яблоку начать перекладывать из корзины "A" в корзину "С".
Перед тем как доставать яблоко из корзины необходимо посмотреть, а есть ли они там (т.е. яблок больше 0). Если есть, то достать очередное яблоко из корзины "А" и положить в корзину "С". Когда в корзине "А" яблок не останется нужно по одному яблоку перекладывать из корзины "B" в корзину "C". Когда в корзине "B" яблок не останется - вы выполнили задачу


text:
Q: How should I approach analysis of many binary predictors and one continuous outcome? beginner here. I have a spreadsheet with data from 70 videos. Most of the data is binary (ex: is this mentioned or not) with one outcome variable (conversion rate). What would be a general process to analyze, and how do I measure significance?
My approach:

*

*look at the videos for more context

*visualize data using box plots to find interesting relationships (I've been told I should figure which predictor variables are most important but not sure how)

*run two way t-tests to assess significance (I've been told to consider logistic regression or one-way ANOVA as well, but not too sure)

Any help would be appreciated.


text:
Q: How can we remove SQL error code 1405 in C I have written following piece of code in C:
EXEC SQL begin declare section;
    int     A;
    char    B[5];
    int     C;
    int     D;
    dtime_t E;
    char    F[13];
EXEC SQL END DECLARE SECTION;
char E_dt[16];
D=0;
memset(F, 0, sizeof(F));

EXEC SQL declare log3 cursor for select A, B, C, D, E, F from tbl WHERE C=123;
if(sqlca.sqlcode)
{
    return;
}

EXEC SQL fetch log3
    into
     :A, :B, :C, :D, :E, :F,
if(sqlca.sqlcode)
{
    if (sqlca.sqlcode != DB_NORECORDS)
    {
        return;
    }
    break;
}

When we run this piece of code, where the value of F is Null in the table tbl. It gives error code 1405. I have tried memset function for setting its default value as 0. But it did not work. And one more thing can i fetch more than 90 field at a time, when i was trying to do that it gives me Bus Error at the time of compilation. Thanks in advance please help me out.

A: You have 2 basic options:

*

*Use an indicator to record the presence of the NULL. You probably should use this option when you want a specific action to be taken when a NULL arises.

*Use the NVL function to convert the retrieved NULL to another value, such as zero or blank. This is the simplest solution.

Edit:
Example with NVL for log3 cursor. Choose whatever default values you want. In the example I have used ' ' for character fields, 0 for numeric fields and Jan 1st year 1 for dates.
EXEC SQL declare log3 cursor for select NVL(A, 0),
                                        NVL(B, ' '),
                                        NVL(C, 0),
                                        NVL(D, 0),
                                        NVL(E, to_date('0001', 'YYYY')),
                                        NVL(F, ' ')
                                   from tbl
                                  WHERE C=123;


text:
Q: return and echo my array from a function I have a function that returns either a value into a variable if it is successful or it returns an errors array. see part of it below.
function uploadEmploymentDoc($var, $var2){

$ERROR = array();

if(empty($_FILES['file']['tmp_name'])){
$ERROR[] = "You must upload a file!";
}

//find the extensions
$doctypeq = mysql_query("SELECT * FROM `DocType` WHERE `DocMimeType` = '$fileType'");
$doctype = mysql_fetch_array($doctypeq);
$docnum = mysql_num_rows($doctypeq);
if($docnum == 0){
$ERROR[] = "Unsupported file type";
}

if(empty($ERROR)){
// run my code
return $var;
} else{
return $ERROR;
}

then when I run my code
$result =  uploadEmploymentDoc(1, 2);

if($result !=array()){
// run code
} else {
   foreach($result as $er){
   echo $er."
";
   }
}

Now my question is this.  Why is my function running my code and not showing me an error when I upload an unsupported document type.  Am I defining my foreach loop correctly?  For some reason I cant get my errors back.

A: you should write like this-
if(is_array($result)){
   foreach($result as $er){
    echo $er."
";
   }
} else {
  //your code for handling error
}

You can get more info :http://us2.php.net/is_array

A: Try use
$result =  uploadEmploymentDoc(1, 2);
if(!is_array($result)){
    // run code
} else {
   foreach($result as $er){
       echo $er."
";
   }
}

Probably will be better add parameter by reference to function for the errors array. From function return "false" if error and value if no error occurred.


text:
Q: Automatic update for jar in maven I am using Drools 6.4 and KieScanner for automatic updates in KieBase. I have setup remote repository and specified it in settings.xml.
<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
    <profiles>
        <profile>
            <id>useArtifactory</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <repositories>
                <repository>
                    <id>abc</id>
                    <url>My remote artifactory</url>
                    <releases>
                        <enabled>true</enabled>
                    </releases>
                    <snapshots>
                        <enabled>true</enabled>
                    </snapshots>
                </repository>
            </repositories>
        </profile>
    </profiles>
    <activeProfiles>
        <activeProfile>useArtifactory</activeProfile>
    </activeProfiles>
</settings>

When my application runs for the first time , It doesn't find jar in local maven so it downloads from remote repository. I have KieScanner which scans the maven repo in every 10 seconds. BUT the problem is if there any update in remote repo then the updates are not being downloaded on the fly. I am using fixed version 1.0 of the jar. What am I missing here ?

A: If you want a version to be updated, you have to declare it as SNAPSHOT version, i.e. 1.0.0-SNAPSHOT.
SNAPSHOT versions are replaced on a regular interval (standard is every 24 hours),
while release versions (like 1.0) are never updated. You can force the update of
a SNAPSHOT version by using the -u parameter in Maven.
SNAPSHOT versions are meant for development (so they can change), while release versions are considered to be stable so that everyone can depend on them without expecting change.


text:
Q: How do you stub out calls to get properties? Consider the following interface...
public interface MyInterface
{
    bool MyProperty { get; }
}

I am attempting to stub out a call to the get function of this property in fakeiteasy.
[Test]
public void Foo()
{
    var fake = A.Fake<MyInterface>();
    var sut = new MySUT(fake);
    A.CallTo(() => fake.MyProperty).Returns(true);

    var result = sut.Foo();

    Assert.IsTrue(result);
}

The system-under-test's Foo() method simply returns the value of the MyProperty get property call. Unfortunately, this test always fails. When debugging, it seems the get property is always returning false.
How can I stub out the return value of a get property call?
EDIT - Adding MySUT class's code (as requested in comments)
public class MySUT
{
    private readonly MyInterface _myInterface;

    public MySUT(MyInterface myInterface)
    {
        _myInterface = myInterface;
    }

    public bool Foo()
    {
        return _myInterface.MyProperty;
    }
}

A: I changed
var sut = MySUT(fake);

to
var sut = new MySUT(fake);

and then it worked in my test solution.
I used FakeItEasy 1.7.4257.42 and NUnit for the test. The main project and test project was separated in 2 different assemblies.


text:
Q: Flutter: How use flutter_localizations in package I plan to move some common function / page to "flutter package"
But how to handle localization in these package ?
I try to follow step https://docs.flutter.dev/development/accessibility-and-localization/internationalization
But it seem app-level localization, How to add localization in submodule/package ?
Update:
I tried to add flutter_intl / flutter_localizations in submodule, let it work like app-level.
I also add module delegate in localizationsDelegates like this
    return MaterialApp(
      localizationsDelegates: const [
        S.delegate,
        module_a.S.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ], ...

After test, here is result:

*

*it can build.

*but it seem not use submodule's translation. it always show english at this case.

*If I copy translate items from submodule to app, it seem work. it look like app translate string will override submodule's translate string

Am I use correct way to implement translation in flutter sub-module ?

A: I am not able to test your code, but I hope this helps.
Regarding

*but it seem not use submodule's translation. it always show english at this case.

As stated in MaterialApp's documentation:
///  * [supportedLocales], which must be specified along with
///    [localizationsDelegates].

If I do not specify the supportedLocales, my app is only shown in english.
Regarding

*If I copy translate items from submodule to app, it seem work. it look like app translate string will override submodule's translate string

I think you are right, that the first S.type, in this case the S.delegate, is selected, because both S.delegate and module_a.S.delegate have the same LocalizationsDelegate.type=S.
Something similar can be found in MaterialApp's documentation:
/// Constructing a [MaterialApp] with a `FooLocalizationsDelegate` overrides
/// the automatically included delegate for [MaterialLocalizations] because
/// only the first delegate of each [LocalizationsDelegate.type] is used and
/// the automatically included delegates are added to the end of the app's
/// [localizationsDelegates] list.

I split my flutter project into different packages, and the solution I choose is to generate a separate delegate class for each package (module).
Example for a module l10n.yaml:
arb-dir: lib/l10n
template-arb-file: app_en.arb
output-class: moduleALocalizations
output-localization-file: module_a_localizations.dart
synthetic-package: false # important, if you want to import the delegate in another package or app
output-dir: lib/l10n/generated # this is optional, if synthetic-package=false and not stated, defaults to arb-dir location

I set output-class and output-localization-file to the class and filename I want to use for the module. The delegate is added as to the [localizationsDelegates] as usual.


text:
Q: How much does/should your style imply about your skill in a language? Two things I've noticed in the past week that make me wonder:

*

*An interview where my Perl skills were reviewed. I always use C-style for loops and use map about once in every 10,000 lines of code, so I almost always have to reference it before using it. While I can interpret others code using that, it's not my style and that is for reasons involving readability and ease of changing between languages. I at least perceived that I was dinged for that.

*This answer to my question in which the answerer proceeded to refactor and bullet-proof my tiny script. I admit I was a little bit offended and kind of annoyed at that, though I can understand how that as a habit may be helpful.

I understand that in a team, my style will need to adapt what the team has decided is correct -- this is necessary in every project and everybody has their own ideas. Yet I feel like I'm judged for what is syntactically fine and readable code.
How much does the style of your smaller snippet code weigh in? Does code like that imply to others that I don't have control of the language because I didn't use all the features? Does my code imply that I'm not familiar with unit testing and proper testing because I didn't fully error-protect a tiny script?

A: 1) Like ikegami, I spend a fair bit of time on SO answering Perl questions and one of my common pieces of advice is "don't use C-style for loops in Perl; use the list iterating version instead because it's harder to mess it up".  If you write for my $i (1 .. 10), there's no way you're going to get the boundary conditions wrong, plus it's quicker to write and requires less thought than the C-style equivalent.  If I were an interviewer and saw you write for (my $i = 1; $i <= 10; $i++) instead, I would question how well you know Perl and whether you were writing Perl directly or if you were thinking in C, then translating it to Perl.
If I saw you write for (my $i = 1; $i <= 10; $i++) { $data = $some_array[$i];... } instead of for my $data (@some_array) { ... }, on the other hand, then I would conclude that you clearly don't know Perl very well and the interview would be pretty well over in my mind, assuming it was for an experienced Perl position.  (Unless $i was going to be used for something else beyond just sequentially indexing into @some_array, but even then I'd favor for (..) over for (;;).)
Style does matter, especially with a language that's as TIMTOWTDI as Perl.  There are many ways to do it, but not all are equally good (for any given value of "good", which does vary from situation to situation).  Using all the language features isn't necessary for good style, but using the right ones when they're appropriate will get you pretty far in that direction.
2) Regarding the linked answer, your code there looks fine to me overall.  The main thing I question is the & prefix on your final function call.  You don't need it (unless you're writing Perl 4, in which case you have far bigger problems!) and it's generally discouraged these days because it has side-effects which aren't immediately obvious.  Definite bonus points for using strict, three-arg open, lexical filehandles, and CPAN modules, though.
On the larger point of your second question, I frequently rewrite people's code to clean it up and show (at least some elements of; I try to match it to their apparent skill level) how I would do it.  It's not meant as a slight on the original author; it's an attempt to help and to educate beyond the immediate question at hand.  It's usually pretty fun, too.  But, perhaps most importantly, the simple fact of the matter is that Perl has an image problem.  There are a lot of people out there (*cough*Job*cough*) who think that "there is no such thing as good Perl style" and I feel that it's important to disprove that belief by showing off well-written, maintainable Perl code when the opportunity presents itself.

A: I don't think the particular style matters in an interview code question, but it is good to see that you have one and are aware of why you do things the way you do it.
Based on your question, it sounds like you may not have reacted favorably to the criticism. You say you realize your style will need to adapt, but you may not have given that impression. Do you think you were defensive? That can be interpreted as unwilling to change.

A: Most popular modern languages have a similar syntax (with small tweaks here and there). But each language has its own very unique style of being used. This style has usually developed over many years and is result of how the language works underneath combined with the experience of users to avoid nasty problems in the language.
When most developers migrate from one language to another they take the style of their favorite language with them and try and apply it to the new language. Now this is fine while you are learning (as you have no other reference to go by). I am not good at perl so I write perl like C++ (with a few tweaks (but I recognize my perl is not good)). I see Java developers try and use C++ like Java and it makes a complete mess of the code (because it does not fit well).
But in the long term this is a bad approach. The language has a particular style for a reason and it is best to try and understand this and learn the style for that language. It makes the learning curve steeper (and you may fall back to your old style now and then to get things done) but in the long term it will definitely be advantageous to learn the correct style for the language.
Reason to learn the correct language style:

*

*Integrate with existing code better

*Avoid pitfalls of the language that are not obvious

*Allow other users to easily understand your code

*

*You can always work it out but reading code that is styled differently to what you expect is a lot harder work than reading it the style you expect.

A:
Does code like that imply to others that I don't have control of the language because I didn't use all the features?

Yes, it does.  Good Perl programmers know Perl well, and use it effectively.
If you are writing five lines of Perl where one would do very nicely, do not expect a warm welcome from a team of Perl programmers.  Teams choose Perl and similar languages to get more done with less code.  It's not just a question of style, it's a matter of time and money.  It takes a lot longer to read and understand:
my @selectedThings
for (my $i = 0; $i <= $#things; ++$i) {
  my $t = $thing[$i]
  if ($t ... ) {
    @selectedThings.push $t
  }
}

than:
my @selectedThings = @things.grep { ... }

The grep call is clear to a Perl programmer.  The multi-line equivalent could say anything, and could easily contain a bug.
There is a huge difference in the cost to develop and maintain a 25,000 line application than a 5,000 line application, even if they do exactly the same thing.

I always use C-style for loops and use map about once in every 10,000 lines of code, so I almost always have to reference it before using it.

This is a form of what Larry Wall called "false laziness".  Each time you could use map, but instead write longer but more familiar code, you save a few seconds one time.  But taking a few minutes to really learn map would save you hundreds of lines of code and many hours in the future.

While I can interpret others code using that, it's not my style and that is for reasons involving readability and ease of changing between languages.

This attitude does not work well in a team.  The team knows Perl, and does not have time to wade through extra code because it's not your style.

A:
While I can interpret others code using that, it's not my style and
  that is for reasons involving readability and ease of changing between
  languages.

This seems odd to me. I find it much more difficult to switch between two similar languages than to switch between two that are very different. When two languages have a lot in common, there's a tendency to fit them both into a common mental model and you end up having to constantly remind yourself about all the differences.
I'm sure that anyone who uses both C and C++ has at some point let some C++ slip into their C code or forgotten to take advantage of useful language features in C++. You never have that problem when you switch between, say, C++ and Scheme, because the two languages aren't remotely alike.


text:
Q: Re-use report in modal page to show different tables I'm working in Apex 5
I have a modal page, with a report.
It is the simplest report. It just shows columns from a table.
But I want to re-use the same modal page to show any table with the same structure.
One thing I could do is to pass the table name to the modal page, when I call the page.
The problem is that it becomes a target for SQL injection. If I pass the table name, anybody could change the name, and watch another table.
What is the general solution for this problem?

I had been asked to post code, so, I may have 10 tables with this format:
CREATE TABLE table1
(
  column1 varchar(20)
  column2 number
);

The modal page is a report with this query:
SELECT column1, column2
from table1

I have 10 tables with the same column names. Each table is named:
copper
explain
fated
truck
neat
unite
branch
educated
tenuous
hum
decisive
notice

And I want to use the same modal page to display all of the tables.
I have 10 buttons on the application (on different pages), one for each table, which open the modal page.
I made an example application in apex.oracle.com
Workspace: nekagav_ws
User:test
pass:test

A: APEX has a built-in protection for this, called Session State Protection (SSP).  This adds a checksum to URLs based on the values it contains. If the user tries to change a value by manipulating the URL when SSP is being used, the checksum will no longer be correct and an error will be shown instead of the page:

No checksum was provided to show processing for a page that requires a
  checksum when one or more request, clear cache, or argument values are
  passed as parameters.
Contact your application administrator.

To enable SSP properly you need to do three things:

*

*Enable SSP at application level: edit the appplication properties and under security set Session State Protection to Enabled. (Your example app already has this value.)

*Enforce SSP at page level: edit the target page properties (page 3 in your example) and under Security set Page Access Protection to Arguments Must Have Checksum. (You currently have it set to Unrestricted.)

*Enforce SSP at item level: edit the item properties of the target item (P3_TABLE_NAME in your example) and under Security set Session State Protection to one of the Checksum Required... options. (You currently have it set to Unrestricted.) I usually use Checksum Required - Session Level.

The reason for the item level setting isn't immediately obvious: if you have set page 3 to require a checksum, why would you also need to protect individual items on that page? The reason is that it is possible to set the session state of an item on any page in the URL.  So if you had another page that had SSP set to unrestricted, a user might be able to construct a URL to go to that page and set P3_TABLE_NAME to some value, and then navigate to page 3 without clearing cache or setting a value and see the data for the value they chose.

A:
What is the general solution for this problem?

Example you created doesn't really reflect what you described (no different buttons; it is unclear what you exactly pass to page 3 as button navigates to it, but no values are passed over there).
Therefore, I was free to modify your application and did the following:

*

*created P3_TABLE_NAME hidden item

*report type is now "Classic report (based on function)"

*query is return 'select COLUMN1, COLUMN2 from ' || :P3_TABLE_NAME;

*Use Generic column names is set to "Yes", with 2 generic columns

*region's "Server-side condition" is set to "PL/SQL Function Body and
it names only valid table names, such as return lower(:P3_TABLE_NAME) IN ('copper', 'explain', 'fated');

*on P1, button now redirects to Page 3 but passes P1_LIST_OF_TABLES to
P3_TABLE_NAME

*on P1, Select list item must have the same display and return
values; you can't pass a number (12) which is then used as a table
name on Page 3 - must be "copper" (for example).

That's more or less all; have a look, adjust it if you have to.


text:
Q: combination and probability There are $k$ sets of numbers:
$$\lbrace0,1,2,\ldots,m_1\rbrace, \lbrace0,1,2,\ldots,m_2\rbrace, \ldots,\lbrace0,1,2,\ldots,m_k\rbrace$$
Such that $m_1 \lt m_2 \lt \cdots \lt m_k$.

*

*How many combinations of k elements can be made taken 1 element from each set such that each set has all distinct elements (no two elements are equal)?

*What is the probability that any two sets will have at least one element common?
I have found that the number of such permutations will be $(m_1+1)m_2(m_3-1)......(m_k-k+2)$, but what will be the number of combinations? Clearly it cannot be just = No. of permutations/$k!$.


text:
Q: Expressions in SSRS I am trying to get a certain expression to work in SSRS. My query pulls up a category, sub category and a count statement grouped by the sub category for tracking incidents. This is my query:
SELECT Category, Sub_Category, CAST(Count(incident) AS decimal) As Total_Incidences
FROM service_req
GROUP BY Sub_Category

I am trying to break these down into percentages, for example a specific sub category accounts for 67% of a certain main category incidences, and would also like to have a percentage of main categories vs total calls, i.e. 12% of all incidences are from this certain category.
My math is not coming out right when trying to make it work, and I cant figure out the best way to do this. Any suggestions? I know I have to divide the count statement by the sum of all incidences in the subcategory to get that percentage, and all sub category sums by the total incidences to get the first percentage however I am not sure how to use a group by with these expressions (or even if I can) to get this to work. Any help would be appreciated!

A: The problem can be solved not in SSRS but rather in the query that returns data. You need 2 separate groupings - one by category, another by category/subcategory combination. Then you can join them like this:
SELECT Sub.Category, Sub.Sub_Category, Sub.Total_IncidencesSub*100/Main.Total_IncidencesMain AS Percentage FROM

(SELECT Category, CAST(Count(incident) as DECIMAL) As Total_IncidencesMain
FROM service_req
GROUP BY Category) Main

INNER JOIN

(SELECT Category, Sub_Category, CAST(Count(incident) AS DECIMAL) As Total_IncidencesSub
FROM service_req
GROUP BY Category, Sub_Category) Sub

ON Main.Category = Sub.Category

Here is live demo: http://sqlfiddle.com/#!3/eee07/7


text:
Q: How to use JWT authentication with a per user model in pouchdb/couchdb? I want to let people sign in with google. At that point, they should connect to a database with their id, if the database doesn't exist, it should be created. This should be the only way to create databases.
Sign in with google works with a JWT token.
So, the logic I need is something like: Only someone with a token signed by google, where the id is x, should be able to connect to the database with the name x.


text:
Q: Detect change in apps and user who made changes by a separate app Django. I'm trying to create an app, say activitylogapp in the project that detects if in another app say Employeeapp some models are changed/updated and keep a log. I don't want touch Employeeapp. I can access changes by using signals in the models.py of activitylodapp. By this:
from django.db.models.signals import post_save
from anotherapp.models import Employee
from django.dispatch import receiver

@receiver(post_save, sender=Employee)
def save_handler(sender, instance, created, **kswargs):
    "Things I want to do"

The problem is I also want to access which user made these changes, like request.user.username that is used in views.py.
Is it possible without explicitly injecting request object from view to activitylog app?

A: You can add a primitive middleware into your "activitylogapp" with process_request to store the request.
As for storing the request, I see 2 options:

*

*Ugly but fast to implement. Save the request globally. It shouldn't affect anything as you get a fresh new cloned thread for each request, which dies right after the request has been processed.

*More sophisticated, without globals. Utilize the fact, that Django signals create weak references to their receiver functions. So you can attach save_handler to the request itself, and they will get GC-ed together in the end. Something like that:
class MyMiddleware(object):

    def process_request(request):

        def save_handler(sender, instance, created, **kswargs):
            user = request.user
            "do the stuff you want to do"

        # without the following line, the save_handler will be
        # garbage collected right away since nothing references it
        request._my_save_handler_instance = save_handler

        post_save.register(save_handler, ...)


text:
Q: Менять пароль пользователя в ходе выполнения скрипта Доброго времени суток, у меня стоит интересная задачка в ходе корой мне необходимо менять пароль пользователя в ходе выполнения скрипта. Из всего что я знаю о фряхе я остановился на команде passwd, но так как она получает пароль только при вводе, пытался вызвать ее через popen и в поток забить новый пасс, но увы ничего не удалось...
P.S. по факту мне нужно создать пользователя, но команда pw не принимает пароль, насколько я понял. и связи с этим приходится искать решение выше указанного геморроя
A: Думаю, man 3 forkpty это то, что Вам нужно.
Там через псевдотерминал (pty) надо работать. В принципе, не очень сложно написать некий двунаправленный аналог popen() на псевдотерминале вместо pipe. Например, expect делает так в spawn.
Например, можно почитать здесь. Или покороче здесь. Идея в том, что Вы делаете псевдотерминал (это как бы связка из двух устройств -- master и slave (ведет себя аналогично обычному tty)), делаете fork и там dup дескрипторов 0,1,2 на slave, после exec passwd она считает, что работает с терминалом. Родительский процесс обменивается байтиками по master.

ответ составлен из комментариев, написанных avp к вопросу.


text:
Q: setcookie() does not set cookie I have an internal network running XAMPP. I am trying to set a cookie for an item when someone logs in. I use the following code. $Access will be a 1 if user authenticates correctly. When a user enters their username and password it passes to a CheckAuth page with the following code.
$Access = authenticateUser($_POST['Username'],$_POST['Password']);
setcookie("Access", $Access, time()+3600);
header('Location:Newpage.php');

On the NewPage it if I do a $_COOKIE['Access'] it will show me 1 and set everything correctly. If I click a link to another page, say Inventory.php, within the same folder, $_COOKIE['Access'] shows 0 instead of 1.
What could be the issue that the cookie is magically gone? I have checked the IE files for the cookie when it is made and it doesn't show up.

A: The super global, $_COOKIE, only contains cookies that were given by the browser to the server in the incoming Request.
setcookie() only sets up HTTP headers for the outgoing Response that will instruct the browser to set a cookie.
If you want this cookie to be available in $_COOKIE, you'll need to set it manually at the same time as you call set_cookie():
setcookie('Access', $Access);
$_COOKIE['Access'] = $Access;

A: $Access = authenticateUser($_POST['Username],$_POST['Password']);

Missing a quote after $_POST['Username
$Access = authenticateUser($_POST['Username'],$_POST['Password']);


text:
Q: How would one solve for a process where a stochastic random variable is divided by a deterministic random variable? I'm currently working on a problem where I am trying to model a stochastic process where a stochastic random variable is divided by a deterministic random variable following a normal distribution. Its been a while wince I had a look at stochastic calc so apologies in advance if my math is a bit rusty!
Consider a simple stochastic process with no drift that satisfies the following SDE
Y(t) = X(t)
dX(t) = $\sigma$dB(t) where B(t) is Brownian motion and B(t) ~ N($0$,t).
Solving such a process would give me Y(t) = Y$_0$ + $\sigma$B(t)
I'm currently trying to find out what the resultant stochastic process would be if Y(t) = $\frac{X(t)}{Z}$ where Z is a Normal distribution with mean $\mu_z$ and variance $\sigma_z^2$ i.e Z ~ N($\mu_z$,$\sigma_z^2$).
How would one apply Ito's lemma in such a case?


text:
Q: PRIORVALUE may not be used in this type of formula I try use this formula in SlaesForce, but I am getting this error " PRIORVALUE may not be used in this type of formula"
if(AND(
ISPICKVAL(PRIORVALUE(Status),"Closed"),
ISPICKVAL(PRIORVALUE(Status),"Test"))), test=0

A: PRIORVALUE can only be used on formulas in Workflow rules where the workflow rule is set to "Whenever the object is created or edited."  So if you're trying to use this in a formula field, you won't succeed -- try doing it with a workflow rule and a field update and setting a standard field with the value instead.


text:
Q: Root View Controller Swift I have a function in my app delegate which appends an item to an array in my a file named ViewController.swift, and then I want to reload a tableview in that same file. I attempt to do so like so:
let vc = ViewController()
let navigationController = UINavigationController(rootViewController: vc)
window!.rootViewController = navigationController
println(vc.messages)

//1        vc.messages.append(message.data.message as! String)
//2        vc.MessageTableView?.reloadData()

The lines numbered 1,2 are where I set breakpoints. It appears to break after line numbered 2.
The exact error I get is

fatal error: unexpectedly found nil while unwrapping an Optional value

I believe my problem is that I am setting the root view controller incorrectly.
Edit #1
Window is declared up top.
If i run my code like this:
    let vc = ViewController()
    messages.append(message.data.message as! String)
    vc.MessageTableView?.reloadData()
    println(messages)

Then I can see that the correct data is put into the array (Which i made global for this scenario) but the table does not get updated in the View controller.

A: What is the implementation of your delegate function?
After you put the tableview in the storyboard,You have to connect the tableview to the ViewController.swift.
Control drag from the tableview to the top of the viewcontroller (the yellowcircle) , there will be a black popup , do that two times and for each time click on datasource and delegate.
Then in the viewcontroller.swift file implement the functions they show in this tutorial. You don't have to modify the AppDelegate.swift file!
https://www.weheartswift.com/how-to-make-a-simple-table-view-with-ios-8-and-swift/

A: You have to reload data inside your ViewController
Put the reload inside viewDidAppear() or sth like that
It's an error because you just init a controller, but your views is not ready yet, they are being initialized.
After viewDidLoad, you can call your views, but not before.
So that's why your table is nil
Beside that, why do you need to reload your table even when you don't see it, right ?

A: if you  want you viewcontroller to be the rootviewcontroller al you have to do is click on the viewcontroller in storyboard and then in the utilities-> attributes inspector ->  check the box "is initial view controller"
https://www.dropbox.com/s/qfd9jqeos7ueq1w/Screen%20Shot%202015-06-25%20at%207.40.46%20PM.png?dl=0


text:
Q: C3P0 with hibernate configuration I am using
spring  4.0.3.RELEASE
hibernate 4.3.5.Final
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-c3p0</artifactId>
        <version>4.3.6.Final</version>
    </dependency>
    also spring-orm

My persistence has below configurations:
    <!-- Important -->
        <property name="hibernate.connection.provider_class" value="org.hibernate.connection.C3P0ConnectionProvider" />
        <property name="hibernate.c3p0.max_size" value="10" />
        <property name="hibernate.c3p0.min_size" value="0" />
        <property name="hibernate.c3p0.timeout" value="30"  />

Added these

My application is running on server which has
apache-tomcat-8.0.21
JDK 8 version
Oracle 12c

I have added these
<dependency>
  <groupId>com.mchange</groupId>
   <artifactId>c3p0</artifactId>
    <version>0.9.5.2</version>
</dependency>

But server log is
    Caused by: com.mchange.v2.resourcepool.TimeoutException: A client timed out while waiting to acquire a resource from com.mchange.v2.resourcepool.BasicResourcePool@1677773d -- timeout at awaitAvailable()
        at com.mchange.v2.resourcepool.BasicResourcePool.awaitAvailable(BasicResourcePool.java:1467)
        at com.mchange.v2.resourcepool.BasicResourcePool.prelimCheckoutResource(BasicResourcePool.java:644)
        at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:554)
        at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutAndMarkConnectionInUse(C3P0PooledConnectionPool.java:758)
        at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:685)
        ... 58 more
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
        at java.util.ArrayList.rangeCheck(ArrayList.java:653)
        at java.util.ArrayList.get(ArrayList.java:429)
        at net.divineit.titas.queryBuilders.QueryBuilder.countAll(QueryBuilder.java:395)
        at net.divineit.titas.services.PayrollItemService.list(PayrollItemService.java:69)
        at net.divineit.titas.controllers.EmployeeBenifitsController.getSchema(EmployeeBenifitsController.java:177)
        at sun.reflect.GeneratedMethodAccessor2198.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
        at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
current thread from acl at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)

        at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)2014

        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
*** z closing connection        at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)

        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:721)
        at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:466)
        at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:391)
        at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:318)
        at net.divineit.titas.filter.UrlRoleFilter.doFilter(UrlRoleFilter.java:109)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
        at psiprobe.Tomcat80AgentValve.invoke(Tomcat80AgentValve.java:45)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
        at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
        at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
        at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
14:51:38,332  WARN SqlExceptionHelper:144 - SQL Error: 0, SQLState: null
        at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1517)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1474)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:745)
14:51:38,333  WARN SqlExceptionHelper:144 - SQL Error: 0, SQLState: null
14:51:38,333 ERROR SqlExceptionHelper:146 - An attempt by a client to checkout a Connection has timed out.
current thread from acl
2008
*** z closing connection
14:51:38,333 ERROR SqlExceptionHelper:146 - An attempt by a client to checkout a Connection has timed out.
javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection
        at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1763)
        at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1677)
        at org.hibernate.jpa.spi.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:1771)
        at org.hibernate.jpa.internal.TransactionImpl.begin(TransactionImpl.java:64)
        at net.divineit.titas.queryBuilders.QueryBuilder.countAll(QueryBuilder.java:384)
        at net.divineit.titas.services.PayrollItemService.list(PayrollItemService.java:69)
        at net.divineit.titas.controllers.EmployeeBenifitsController.getSchema(EmployeeBenifitsController.java:177)
        at sun.reflect.GeneratedMethodAccessor2198.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
        at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
        at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:721)
        at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:466)
        at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:391)
        at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:318)
        at net.divineit.titas.filter.UrlRoleFilter.doFilter(UrlRoleFilter.java:109)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
        at psiprobe.Tomcat80AgentValve.invoke(Tomcat80AgentValve.java:45)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
        at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
        at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
        at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
        at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1517)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1474)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:745)
14:51:38,335 DEBUG SQL:109 - select payrollite0_.ID as col_0_0_, payrollite0_.NAME as col_1_0_, payrollite1_.ID as col_2_0_, payrollite0_.AMOUNT as col_3_0_, payrollite0_.CALCULATION_METHOD as col_4_0_, payrollite0_.MAX_VALUE as col_5_0_, payrollite0_.MIN_VALUE as col_6_0_, payrollite0_.PARAMETER as col_7_0_, payrollite0_.IS_TAXABLE as col_8_0_, payrollite0_.CREATED_BY as col_9_0_ from PAYROLL.PAYROLL_ITEMS payrollite0_, PAYROLL.PAYROLL_ITEM_GROUPS payrollite1_ where payrollite0_.PAYROLL_ITEM_GROUP_ID=payrollite1_.ID
Hibernate: select payrollite0_.ID as col_0_0_, payrollite0_.NAME as col_1_0_, payrollite1_.ID as col_2_0_, payrollite0_.AMOUNT as col_3_0_, payrollite0_.CALCULATION_METHOD as col_4_0_, payrollite0_.MAX_VALUE as col_5_0_, payrollite0_.MIN_VALUE as col_6_0_, payrollite0_.PARAMETER as col_7_0_, payrollite0_.IS_TAXABLE as col_8_0_, payrollite0_.CREATED_BY as col_9_0_ from PAYROLL.PAYROLL_ITEMS payrollite0_, PAYROLL.PAYROLL_ITEM_GROUPS payrollite1_ where payrollite0_.PAYROLL_ITEM_GROUP_ID=payrollite1_.ID
Caused by: org.hibernate.exception.GenericJDBCException: Could not open connection
        at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54)
        at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
        at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
        at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:235)
        at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:171)
        at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.doBegin(JdbcTransaction.java:67)
        at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.begin(AbstractTransactionImpl.java:162)
        at org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1435)
        at org.hibernate.jpa.internal.TransactionImpl.begin(TransactionImpl.java:61)
        ... 49 more
Caused by: java.sql.SQLException: An attempt by a client to checkout a Connection has timed out.
        at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:118)
        at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:77)
        at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:690)
        at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection(AbstractPoolBackedDataSource.java:140)
        at org.hibernate.c3p0.internal.C3P0ConnectionProvider.getConnection(C3P0ConnectionProvider.java:89)
        at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:380)
        at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:228)
        ... 54 more
Caused by: com.mchange.v2.resourcepool.TimeoutException: A client timed out while waiting to acquire a resource from com.mchange.v2.resourcepool.BasicResourcePool@1677773d -- timeout at awaitAvailable()
        at com.mchange.v2.resourcepool.BasicResourcePool.awaitAvailable(BasicResourcePool.java:1467)
        at com.mchange.v2.resourcepool.BasicResourcePool.prelimCheckoutResource(BasicResourcePool.java:644)
        at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:554)
        at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutAndMarkConnectionInUse(C3P0PooledConnectionPool.java:758)
        at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:685)
        ... 58 more
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
        at java.util.ArrayList.rangeCheck(ArrayList.java:653)
        at java.util.ArrayList.get(ArrayList.java:429)
        at net.divineit.titas.queryBuilders.QueryBuilder.countAll(QueryBuilder.java:395)
        at net.divineit.titas.services.PayrollItemService.list(PayrollItemService.java:69)
        at net.divineit.titas.controllers.EmployeeBenifitsController.getSchema(EmployeeBenifitsController.java:177)
        at sun.reflect.GeneratedMethodAccessor2198.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
        at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
        at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:721)
        at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:466)
        at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:391)
        at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:318)
        at net.divineit.titas.filter.UrlRoleFilter.doFilter(UrlRoleFilter.java:109)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
        at psiprobe.Tomcat80AgentValve.invoke(Tomcat80AgentValve.java:45)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
        at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
        at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
        at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
        at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1517)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1474)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)

Please help me to find out probable issues.
Thanks you.


text:
Q: Feature Engineering Salary Data using Categorical Column as a condition Need to convert salary amount to annualised salaries considering the Categorical Column :

*

*'M' - monthly

*'Y' - yearly

*'W' - weekly

*'B' - bi weekly

df = pd.DataFrame({'Name':['A','B','C','D','E'],
                  'sal_amt':[4500,50000,2000,3000,5000],
                  'sal_md':['M','Y','W','B','M']})
df.head()

#defined a function for my problem...

def func(row):
    if row['sal_md'] == 'M':
        return (row['sal_amt']*12)
    elif row['sal_md'] =='Y':
        return row['sal_amt']
    elif row['sal_md'] == 'H':
        return (row['sal_amt']*8760)
    elif row['sal_md'] == 'W':
        return (row['sal_amt']*52)
    elif row['sal_md'] == 'B':
        return (row['sal_amt']*26)
    elif row['sal_md'] == 'S':
        return row['sal_amt']
    elif row['sal_md'] == 'A':
        return row['sal_amt']

df['sal_annual'] = df.apply(func,axis=1)

https://i.stack.imgur.com/INXva.png

A: In [1]: import pandas as pd

In [2]: df = pd.DataFrame({'Name':['A','B','C','D','E'],
                      'sal_amt':[4500,50000,2000,3000,5000],
                      'sal_md':['M','Y','W','B','M']})

In [3]: multiplier_dict = {'M':12, 'Y':1, 'W':52, 'B':26}

In [4]: df['sal_multiplier'] = df.sal_md.map(multiplier_dict)

In [5]: df['sal_annual'] = df.sal_amt*df.sal_multiplier

In [6]: df.head()
Out[6]:
  Name  sal_amt sal_md  sal_multiplier  sal_annual
0    A     4500      M              12       54000
1    B    50000      Y               1       50000
2    C     2000      W              52      104000
3    D     3000      B              26       78000
4    E     5000      M              12       60000

Not exactly what you asked about, but exactly solves your problem in an easy and pythonic way.


text:
Q: Is $\frac{\sin |\xi|}{|\xi|}$ in range of Fourier Transform for $n \ge 3$? Does there exist $f \in L^1(\mathbb{R}^n)$ s.t., $\displaystyle \widehat{f}(\xi) =  \frac{\sin |\xi|}{|\xi|}$ in case of dimension $n \ge 3$?
It is known that for $n = 2$, the function $\displaystyle f(x) = \frac{\chi_{\{|x| < 1\}}}{\sqrt{1-|x|^2}}$ curiously has some constant multiple of $\dfrac{\sin |\xi|}{|\xi|}$ as Fourier transform. Or at least is there a way of finding the Fourier transform $\frac{\sin |\xi|}{|\xi|}$ in sense of tempered distributions for $n \ge 3$?

A: Here's a formula  from Duistermaat and Kolk  book Distributions: Theory and Applications, Chapter 17, Eq, (17.13). We denote by $\newcommand{\eF}{\mathscr{F}}$ $\eF$ the Fourier transform. Then $\newcommand{\ii}{\boldsymbol{i}}$ $\newcommand{\ve}{\varepsilon}$
$$
\eF^{-1}\left(\frac{e^{\ii t\Vert \xi\Vert}}{\Vert\xi\Vert}\right)=p_n\lim_{\ve\searrow 0} \Big(\; \Vert x\Vert^2-(t+\ve\ii)^2\;\Big)^{-\frac{n-1}{2}},
$$
where $p_n$ is a certain universal constant,
$$p_n=\frac{\Gamma\big(\frac{n+1}{2}\big)}{(n-1)\pi^{(n+1)/2}}. $$


text:
Q: multiple groupby with pandas I'm trying to make multiple groupby with pandas, but I encounter errors.
I want to use both Date and category column.
What I want to do; to find the average of the returns of different funds in the same category on the same date. For example, On 2019-03 x category mean return is 0.025.
My sample python code:
df['benchmark_mean']= df.groupby(["category","date"])["fund_ret"].mean()

My Sample DataFrame:

date
fund_ticker
category
fund_ret
nav

2019-02
AAA
x
0.05
1000

2019-03
AAA
x
0.03
1030

2019-02
BBB
y
-0.01
...

2019-03
BBB
y
0.07
...

2019-03
CCC
x
0.02
...

A: You probably need to create a new column called benchmark_mean that has the mean per group?, then you could do as below:
df.groupby(["category","date"],as_index=False).agg(
       benchmark_mean = pd.NamedAgg(column = 'fund_ret', aggfunc = 'mean'))

output:
    category       date benchmark_mean
0          x    2019-02          0.050
1          x    2019-03          0.025
2          y    2019-02         -0.010
3          y    2019-03          0.070

If you want a new column in the original dataframe with no change in rows, you can use groupby with transform as below:
df['benchmark_mean'] = df.groupby(['category', 'date'])['fund_ret'].transform('mean')

output of df after :
       date fund_ticker    nav   category   fund_ret    benchmark_mean
0   2019-02         AAA 1000.0         x        0.05             0.050
1   2019-03         AAA 1030.0         x        0.03             0.025
2   2019-02         BBB    NaN         y       -0.01            -0.010
3   2019-03         BBB    NaN         y        0.07             0.070
4   2019-03         CCC    NaN         x        0.02             0.025

Why we cannot use "apply" instead of "transform"?
You can use apply instead of transform definitely and you can get the same result as below:
df_bm = df.groupby(['date', 'category']).apply(lambda x : pd.Series(x['fund_ret'].mean(), ['benchmark_mean'])).reset_index()

df = df.merge(df_bm, on = ['date', 'category'], how = 'left')

You may want to look at this beautiful answer to look at differences between apply and transform.
How to get weighted mean?
I m going to use apply because transform works only on one Series at a time so I cannot use [nav, fund_ret] after groupby. The code will be :
def weighted_average(x):
    x['nav'] = x['nav'].replace(np.nan, 0)
    if x['nav'].nunique() == 1 and x['nav'].iloc[0] == 0:
        return 0
    return np.average(x['fund_ret'], weights=x['nav'])

df1 = df.groupby(['date', 'category'],as_index=False).apply(lambda x: pd.Series(weighted_average(x), ['weighted_mean']))['weighted_mean'].reset_index()
df.merge(df1, on = ['date', 'category'], how = 'left')

Output (after both the applys):
       date fund_ticker    nav category fund_ret    benchmark_mean  weighted_mean
0   2019-02        AAA  1000.0       x      0.05             0.050           0.05
1   2019-03        AAA  1030.0       x      0.03             0.025           0.03
2   2019-02        BBB     NaN       y     -0.01            -0.010            NaN
3   2019-03        BBB     NaN       y      0.07             0.070            NaN
4   2019-03        CCC     NaN       x      0.02             0.025           0.03


text:
Q: NSCollectionView How to scroll to selected item I programmatically select a item in my NSCollectionView. The item is selected as expected but the view doesn't scroll automatically to this item.
[collectionView setSelectionIndexes:[NSIndexSet indexSetWithIndex:compt]];

How to scroll to the selected item ?

A: Find the answer here NSScrollView: Make sure frame is visible
This code worked for me :
NSRect selectionRect = [self.collectionView frameForItemAtIndex:[[self.collectionView selectionIndexes] firstIndex]];
[self.collectionView scrollRectToVisible:selectionRect];

A: Tested on: Swift 4.2. Xcode 10.2. macOS 10.14.5 Beta
if  let indexPath = indexPaths.first {
            if #available(OSX 10.12, *) {
                NSAnimationContext.runAnimationGroup { (context) in
                    context.duration = 0.8
                    context.allowsImplicitAnimation = true
                    collectionView.scrollToItems(at: [indexPath], scrollPosition: NSCollectionView.ScrollPosition.bottom)
                }
            } else {
                collectionView.scrollToItems(at: [indexPath], scrollPosition: NSCollectionView.ScrollPosition.bottom)
            }
        }

A: Since OS X 10.11 in the new NSCollectionView you should use instead:
[self.collectionView scrollToItemsAtIndexPaths:[self.collectionView selectionIndexPaths] scrollPosition:NSCollectionViewScrollPositionCenteredHorizontally];

A: let scrollPositionX: CGFloat = videoThumbCollectionView.visibleRect.origin.x + 150.0
        videoThumbCollectionView.scroll(NSPoint(x: scrollPositionX, y: videoThumbCollectionView.visibleRect.origin.y))

A: For Swift 4
collectionView.scrollToItems(at: [collectionView.selectionIndexPaths.first!], scrollPosition: NSCollectionView.ScrollPosition.centeredHorizontally)

A: If you want to select and scroll with animation at the same time, you can use this (Swift):
 NSAnimationContext.runAnimationGroup { (context) in
     context.allowsImplicitAnimation = true
     collectionView.selectItems(at: [newIndexPath], scrollPosition: .centeredVertically)
 }


text:
Q: Safe struct array as plain byte stream I have given an array of structs:
typedef struct sRawMsg{
    int a;
}sRawMsg;

sRawMsg RawMsg[10];

First the struct array entries are filled with data. Then the data is copied to an output buffer given as a 2D array.
// sending buffer which allocates memory for the array struct
static unsigned char sendingBuffer[10][sizeof(sRawMsg)];

for(int i = 0; i < 10; ++i)
{
    sRawMsg* pMsg = &(RawMsg[i]);
    // data is now stored in the struct array @ pos i
    ...
    // data from the struct entry is now saved in the output sending buffer
    memcopy(&(sendingBuffer[i][0]), pMsg, sizeof(sRawMsg));
}

The obtained output buffer is transmitted as an plain byte array over an wireless connection. Since I am new to C programming I want to ask whether a more efficient / elegant / secure way exist to handle the struct array data.

A: Since you don't have any padding in the structure (one element structures don't have padding with any normal compiler), you could simply pass the
(unsigned char *)&RawMsg[0]

as the argument to your sending function.
If you were converting the data to a fixed format (e.g. network order), or if your structure included a mixture of types with padding between the elements, or if your structure included pointers to strings (or other pointers to data), you'd have to work harder — use serialization analogous to what you are doing.  With pointers to strings, you'd probably need a protocol that knows how to identify the lengths of strings.  One such convention is known as TLV (Type, length, value). Another (vastly more complex) one is ASN.1.  Or you can use a format such as JSON or BSON, or maybe Google's Protocol buffers.


text:
Q: How to simulate foreground service killed by the Android system I want to reproduce a scenario where android system kills the service.
In service class I'm posting foreground service notification from onCreate and returning START_REDELIVER_INTENT from onStartCommand method. Below exception I'm getting for some of devices.
Fatal Exception: android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()

As per code, it shouldn't crash as I am posting foreground service notification from onCreate and cancelling that notification on service onDestroy. The only thing I'm guessing that might possible at some moment android system kills the service and due to that notification get cancelled automatically and service get restarted, and this time onCreate may not get called. But on the other side i'm also not sure whether this time(system kill service) onCreate will get called or not, if that get call then it is impossible to get the above exception.

A: Try to use a "Terminate" button, it placed in the bottom pane in android studio on the "Run" tab, it looks like a red circle with cross.