text:
Q: The query with OR statement is too slow this is my query
$select = (new yii\db\Query())
                ->select('autori.IDAutore, autori.IParte, autori.IIParte, autori.Prefisso, autori.Qualificazione, count(autori.IDAutore) AS qta')
                ->from('autori')
                ->innerJoin('bibliografie b', '
                b.RIDAutorePrinc1 = autori.IDAutore OR
                b.RIDAutorePrinc2 = autori.IDAutore OR
                b.RIDAutorePrinc3 = autori.IDAutore OR
                b.RIDAutorePrinc4 = autori.IDAutore OR
                b.RIDAutorePrinc5 = autori.IDAutore OR
                b.RIDAltroAutore1 = autori.IDAutore OR
                b.RIDAltroAutore2 = autori.IDAutore OR
                b.RIDAltroAutore3 = autori.IDAutore OR
                b.RIDAltroAutore4 = autori.IDAutore OR
                b.RIDAltroAutore5 = autori.IDAutore
            ')->limit(20)->orderby('COUNT(*) DESC');
$autoreList = $select->groupby('autori.IDAutore')->limit(20)->all();

The problem is that the loading page is too slow if the result have more than 2000 items. It take 20-30 seconds.
Any suggestion for optimize the query?
Thank you

A: I think based on your query that you should change db design , why you use so many columns ? Maybe i am wrong but you need to optimise this part , b.RIDAutorePrinc1 , b.RIDAutorePrinc2 ....... b.RIDAutorePrincN where you can have only one colum b.RIDAutorePrinc and put all values in this column and you dont have to put in a join so many or conditions .
Firstly join in sql always cost you some time and added here also so many or conditions the time goes up . If you put everything in b.RIDAutorePrinc you would have a shorter query like below and saving some appreciated time:
$select = (new yii\db\Query())
              ->select('autori.IDAutore, autori.IParte, autori.IIParte, autori.Prefisso, autori.Qualificazione, count(autori.IDAutore) AS qta')
              ->from('autori')
              ->innerJoin('bibliografie b', 'b.RIDAutorePrinc = autori.IDAutore')
              ->limit(20)
              ->orderby('COUNT(*) DESC');

$autoreList = $select->groupby('autori.IDAutore')->limit(20)->all();


text:
Q: ELASTICSEARCH - Recommendations to modify cluster size in ElastiCloud I have this error in Elastic CLoud:
elasticsearch.exceptions.RequestError: RequestError(400, 'illegal_argument_exception', 'Validation Failed: 1: this action would add [6] total shards, but this cluster currently has [2000]/[2000] maximum shards open;')

It is posible to modify the settings cluster in cluster.max_shards_per_node. in Elastic Cloud?
Do you recommend other solutions than modifying the size of the cluster?

A: you had the max shards configuration set as 2000 and looks like you are creating the new index which will have total 6 shards(including primary and replica) shards.
You can increase the total number of shards in a cluster if you have resources to handle it, the default is 1000 shards per cluster.
Another option is, if you have an unused index, you can delete them and free some shards in your cluster.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Software Updater crashes on Xfce only TL;DR: The only clue I could find in the logs is that on a working system /var/log/syslog reports AptDaemon's transactions like this: queuing - simulating - processing - finished. On my system it stops on 'simulating'.
Long version
The problem manifested after the upgrade from 18.04 that had Xfce 4.12 to 20.04 with its Xfce 4.14. Since 20.04 also had Software Updater remade to include snaps, I can't attribute the issue to Xfce only.
Software Updater works fine with the standard Gnome 3 on Xorg, Gnome 3 on Wayland, Gnome Flashback - all on the same Ubuntu installation. On Xfce, the following happens:

*

*The list of packages to install and remove is displayed correctly.

*After I click 'Install', the words "waiting for auth..." (can't read the rest this fast, but the idea is clear) appear for a split second and Software Updater closes.

Tried reinstalling this and that as suggested by Google; no dice. Of course, I can dance around it with the console. Would prefer to fix it, though.
ETA
Fixed by installing policykit-1-gnome. I'm still curious about the root cause.


text:
Q: Listview for my records if I appear in any child records Suppose we have an A SObject, A has a user child SObject. Now we want to build a list view to show my A records if I am one of the child users linking to the A record. And this needs to be done using listview instead of LWC.
When we come to this scenario, we don't think there is any out-of-box way resolving this. So we thought about using a trigger to populate the ids of the users into one custom field in A. Then we can filter. This can be a solution. But wondering if there is any better way resolving this.


text:
Q: Where are the username and password stored in a PHP program when you are using HTTP authentication? Where are the username and password stored in a PHP program when you are
using HTTP authentication?

A: $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW']
Source: https://secure.php.net/manual/en/features.http-auth.php


text:
Q: Weakly dominance in Zero Sum game With the following game matrix in Zero sum games:
  a  b
A -1  2

As b dominates over a - does this still prove there is Nash Equilibrium using minimax theorem ?

A: According to usual interpretation, Column minimizes so actually $a$ dominates $b$. Regardless, the minimax outcome for this game (following the usual interpretation) is $(A,a)$.


text:
Q: Line integral using Green's Extended Theorem. Let $C$ be parametrization $\mathbf{r}=\space5\cos(t) \mathbf{i}+\space4\sin(t) \mathbf{j}\space, t \in [0, 2\pi]$. Calculate $\oint_C \mathbf{F}\cdot d \mathbf{r}$ where $F$ is vector field
$$F(x,y)= \frac{-4x^3y}{(x^4+y^4)^2} \mathbf{i}+\frac{x^4-3y^4}{(x^4+y^4)^2} \mathbf{j}$$
Using Green's theorem:
\begin{align}
&\oint_C \bigg(\frac{-4x^3y}{(x^4+y^4)^2} \mathbf{i}+\frac{x^4-3y^4}{(x^4+y^4)^2} \mathbf{j} \bigg) \cdot d \mathbf{r} \\\\
&= \iint_R \bigg[\frac{\partial}{\partial x} \bigg(\frac{x^4-3y^4}{(x^4+y^4)^2 } \bigg)- \frac{\partial}{\partial y} \bigg(\frac{-4x^3y}{(x^4+y^4)^2} \bigg)\bigg] dA
\end{align}
But the vector field presents a singularity on $(0,0)$ so I cannot directly apply Green's. I use Extended Green's Theorem instead.
$$\oint_CF-\oint_LF=\iint_R  (\nabla×F) ·k\space dA = 0$$
$$\oint_CF=\oint_LF$$
Which $L$ will let me calculate the line integral in the easiest way possible?
PD: I've already tried with a square $(|x|=1\space |y|=1)$ but it just gives me more problems.

A: I don't know what problems the square gave you. It works excellently:
Define $$\mathbf r(t) = \begin{cases}(t+3)\mathbf{i} - \mathbf{j}& t \in [-4,-2)\\
(\mathbf{i} + (t+1)\mathbf{j}& t\in [-2, 0)\\
(1 - t)\mathbf{i} + \mathbf{j}& t \in [0,2)\\
-\mathbf{i} + (3-t)\mathbf{j}& t\in [2, 4)\end{cases}$$
Then
$$\dot{\mathbf r}(t) = \begin{cases}\mathbf{i}& t \in [-4,-2)\\
\mathbf{j}& t\in [-2, 0)\\
-\mathbf{i}& t \in [0,2)\\
-\mathbf{j}& t\in [2, 4)\end{cases}$$
So
$$\begin{align}\oint_LF\cdot d\mathbf r = &\int_{-4}^{-2} \frac{4(t+3)^3}{((t+3)^4+1)^2} dt\\
&+\int_{-2}^{0}\frac{1-3(t+1)^4}{(1+(t+1)^4)^2}dt\\
&+\int_{0}^{2} \frac{4(1-t)^3}{((1-t)^4+1)^2} dt\\
&+\int_{2}^{4}\frac{3(3-t)^4-1}{(1+(3-t)^4)^2}dt\\=&\int_{-1}^{1} \frac{4t^3}{(t^4+1)^2} dt\\
&+\int_{-1}^{1}\frac{1-3t^4}{(1+t^4)^2}dt\\
&+\int_{-1}^{1} \frac{4t^3}{(t^4+1)^2} dt\\
&+\int_{-1}^{1}\frac{3t^4-1}{(1+t^4)^2}dt\end{align}$$
For the first and third integrals, the integrand is odd, so the integrals are $0$. The second and fourth integrals are opposites, so their sum is $0$.


text:
Q: How to disable flipping of the "up" button on the action bar? Background
I've made an "app manager" alternative app, and I wish to add translation for RTL (right to left) languages.
Since I know that as of certain Android version, things got flipped to let words and sentences align correctly, I decided to first switch to such a language and then continue with the translation
The problem
After switching to an RTL language (Hebrew in my case), I've found out that the action bar's up button has the "<" image flipped horizontally:

So now it shows ">" instead.
The question
How do I fix it? It doesn't make sense to see it this way...

A: What worked for me was to let the system use the default theme, and not specify Holo. If you can live with that, the Up button will be oriented correctly. Unfortunately this cannot be done if you use AppCompat of course.
To make this even more annoying: the flipping of the up button is device specific. It occurs on Samsung devices but not on Google's. The supportsRtl flag is only for API 17 and above, so older Samsung phones cannot be fixed.
The issue is apparently the Holo implementation on Samsung devices. Be careful with flipping the icon since on Google phones it will be flipped wrong.
See this: https://code.google.com/p/android/issues/detail?id=68476

A: Well, you can access that ActionBar "up" affordance by calling Resources.getIdentifier and View.findViewById. After that you could rotate it.
    final int upId = getResources().getIdentifier("up", "id", "android");
    final View up = findViewById(upId);
    // Call this to just rotate the icon 180°
    if (getResources().getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_RTL) {
        up.setRotation(180f);
    }


text:
Q: Function for estimating Generalized Pareto Distribution parameters in R not working In this paper https://www.jstor.org/stable/27867255?seq=1#metadata_info_tab_contents they provide a method of estimation for the GPD, based on the profile likelihood function and the empirical Bayesian method. The code they provide is the following:
# x is the sample data from the GPD
f <- function(x) {
  n <- length(x)
  x <- sort(x)
  lx <- function(b,x) {
    k <- -mean(log(1-b*x))
    if (b==0) {
      k-1-log(mean(x))
    } else {
      k-1+log(b/k)
    }
    }
  p <- (3:9)/10
  xp <- x[round(n*(1-p)+.5)]
  m <- 20+round(n^.5)
  xq <- x[round(n*(1-p*p)+.5)]
  k <-  log(xq/xp-1,p)
  a <- k*xp/(1-p^k)
  a[k==0] <- (-xp/log(p))[k==0]
  k <- -1
  b <- w <- L <- (n-1)/(n+1)/n[n]-(1-((1:m-.5)/m)^k)/k/median(a)/2
  for (i in 1:m) L[i] <- n*lx(b[i],x)
  for (i in 1:m) w[i] <- 1/sum(exp(L-L[i]))
  b <- sum(b*w)
  k <- -mean(log(1-b*x))
  list(sigma=k/b,k=k)
}

I simulated a vector of x values with size n = 100 from a GPD with shape parameter equals to 1 and scale parameter equals to -1. Then I get the error:
Error in if (condition) { : missing value where TRUE/FALSE needed

According to this question Error in if/while (condition) {: missing Value where TRUE/FALSE needed the error can be attributed to the NA values in the b vector, but I don't understand why this happens.
My x vector:
x
  [1]   0.24264350   0.71418670   0.90929131   1.31011008   1.26467953   0.66491141  40.16132902
  [8]   0.24815930   0.83783287   1.18879459   1.87167421   0.00396890   1.58125086   0.32042532
 [15]   0.01330135   0.80800732   0.67832942   0.32623323  10.87447448   0.64779973   0.16550198
 [22]   1.03595024   0.08463867   6.17820208  15.07862358   0.19188437   0.14925543   2.20031552
 [29]   1.14093185   2.92184174   0.79279984   0.14736789   0.32954571  24.41728358   5.64925376
 [36]   1.31141081   1.62897827   0.01491289   0.86641233   0.82289179   0.12105522   1.66701079
 [43]   4.65817711  53.08764134   8.87696704   0.61560327   0.77817268   0.65148331   2.33976096
 [50]   2.96629395   0.43783850   3.11005777   0.44923740   0.27073261   2.98854135   1.85962571
 [57]   0.67065561   1.09661475   1.55934896   1.65683579   0.62373160  27.04125805   0.16137916
 [64]   0.32925148   0.40487288   1.41714764   0.48798225   0.07624247   2.32993211   2.13228723
 [71]   6.74938943   2.10121108   0.56772145   2.84504482   1.67119601   1.68640938  23.65633183
 [78]   7.78195561   0.21317910   0.33639542   1.14508402   6.61466064   2.03818446   2.28166528
 [85]   0.28095778  30.93008603   0.16512528   1.21974281   0.32121843 103.90277963   0.09672460
 [92]   1.04882224   1.68444513  29.93956683   0.43961534   2.60623811   0.25039076   0.76208631
 [99] 568.46662349   1.66133511

A: I think you have some transcription errors in your function (to be fair, the code is not well formatted in the paper). I think this should be what you're looking for:
f <- function(x) {
  n <- length(x)
  x <- sort(x)
 lx <- function(b, x) {
   k <- -mean(log(1 - b * x))
   if (b == 0) k - 1 - log(mean(x)) else k - 1 + log(b/k)
 }
 p <- (3:9)/10
 xp <- x[round(n*(1 - p)+ 0.5)]
 m <- 20 + round(n^0.5)
 xq <- x[round(n*(1 - p * p) + .5)]
 k <- log(xq / xp - 1, p)
 a <- k*xp/(1 - p^k)
 a[k == 0] <- (-xp/log(p))[k == 0]
 k <- -1
 b <- w <- L <- (n-1)/(n+1)/x[n] -(1-((1:m-.5)/m)^k)/k/median(a)/2
 for (i in 1:m) L[i] <- n*lx(b[i],x)
 for (i in 1:m) w[i] <- 1/sum(exp(L-L[i]))
 b <- sum(b * w)
 k <- -mean(log(1 - b * x))
 list(sigma = k / b, k = k)
}

Which gives, on your data:
f(x)
#> $sigma
#> [1] 1.050348
#>
#> $k
#> [1] -1.070265

data
x <- c(0.2426435, 0.7141867, 0.90929131, 1.31011008, 1.26467953, 0.66491141,
40.16132902, 0.2481593, 0.83783287, 1.18879459, 1.87167421, 0.0039689,
1.58125086, 0.32042532, 0.01330135, 0.80800732, 0.67832942, 0.32623323,
10.87447448, 0.64779973, 0.16550198, 1.03595024, 0.08463867,
6.17820208, 15.07862358, 0.19188437, 0.14925543, 2.20031552,
1.14093185, 2.92184174, 0.79279984, 0.14736789, 0.32954571, 24.41728358,
5.64925376, 1.31141081, 1.62897827, 0.01491289, 0.86641233, 0.82289179,
0.12105522, 1.66701079, 4.65817711, 53.08764134, 8.87696704,
0.61560327, 0.77817268, 0.65148331, 2.33976096, 2.96629395, 0.4378385,
3.11005777, 0.4492374, 0.27073261, 2.98854135, 1.85962571, 0.67065561,
1.09661475, 1.55934896, 1.65683579, 0.6237316, 27.04125805, 0.16137916,
0.32925148, 0.40487288, 1.41714764, 0.48798225, 0.07624247, 2.32993211,
2.13228723, 6.74938943, 2.10121108, 0.56772145, 2.84504482, 1.67119601,
1.68640938, 23.65633183, 7.78195561, 0.2131791, 0.33639542, 1.14508402,
6.61466064, 2.03818446, 2.28166528, 0.28095778, 30.93008603,
0.16512528, 1.21974281, 0.32121843, 103.90277963, 0.0967246,
1.04882224, 1.68444513, 29.93956683, 0.43961534, 2.60623811,
0.25039076, 0.76208631, 568.46662349, 1.66133511)


text:
Q: Included xml layout_width/height not found I have a standard header layout that I want to include in all my activity layouts.  It is very simple:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="@dimen/medium_margin"
android:background="@drawable/header_bg" >

<Button
    android:id="@+id/new_client_button"
    android:layout_width="@dimen/client_btn_width"
    android:layout_height="@dimen/client_btn_height"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"
    android:background="@drawable/search_btn_bg"
    android:text="@string/find_client" />

<ImageView
    android:id="@+id/header_logo"
    android:layout_width="@dimen/header_logo_width"
    android:layout_height="@dimen/header_logo_height"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:contentDescription="@string/OK"
    android:src="@drawable/negev_logo" />

</RelativeLayout>

I have included it in several activities, and everything is OK. However, in the following declaration, I get complaints from Eclipse saying '"client_header" does not set the required layout_width attribute:'
This is the declaration, I can't see anything here that doesn't exist in other, successful layouts:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/back"
android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true"
tools:context=".ClientActivity" >

<include
    android:id="@+id/client_header"
    layout="@layout/header_layout" />
... etc

I also get a runtime exception with the same error when I try to inflate the layout. Any thoughts?

A: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" />

<include
    android:id="@+id/client_header"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignRight="@+id/textView1"
    android:layout_below="@+id/textView1"
    android:layout_marginRight="25dp"
    android:layout_marginTop="94dp"
    layout="@layout/layout_name" />
</RelativeLayout>

This layout worked for me.

A: Remove the padding from the parent layout.Because its a base view If you need padding either use Margin for child views or use other wrapper layout within that to hold textView and ImageView and set padding for that.

A: It turns out that this was a side effect of a malformed layout further down in the file.  That layout was not flagged, but somehow it affected the XML code above it. The moral of the story: don't assume that the bug is at the place that Eclipse's lint thinks it is. Just like any other bug, simplify until you have isolated the problem.


text:
Q: Load docker image using docker engine api I want to load an image using docker engine api. I have an image tar that was created using: docker save -o <path-for-generated-tar/filename> <image name>
How can I load it using docker api? I am looking into POST /images/load endpoint on the documentation. The documentation dictates that an image tarball is needed.
Is this same as what we get with docker save command?
I am trying to create an endpoint in postman which would do this but I cant seem to find how to pass the image tarball.
Kindly help me out with this. Thanks.

A: Here is how I got it done:
curl -X POST 'http://<ip>:<port>/v1.24/images/load' -H 'Content-Type: application/x-tar'  --data-binary "@image.tar"
@ here is important. The image tar filename must be given with an @ at the start.


text:
Q: C# Dynamic Linq Where Clause is there a way to dynamically build a Where clause in LINQ?
Example... today I query my sql db, and only ServerGroup A has issues.  I return the fault codes for that group.  Works. However, tomorrow, ServerGroup A & B have issues. I do not want to manually change my LINQ query, but have it dynamically add the new ServerGroup to the WHERE clause.  Is this possible with LINQ?  I've done it with a Sql query.
Greatly appreciate the assistance.
        var query = referenceDt.AsEnumerable()
            .Where(results => results.Field<string>("ServerGroup") == "A" ||
                             results.Field<string>("SeverGroup") == "B")
            .GroupBy(results => new
                {
                    FaultCode = results.Field<int>("FaultCode")
                })
            .OrderByDescending(newFaultCodes => newFaultCodes.Key.FaultCode)
            .Select(newFaultCodes => new
            {
                FaultCode = newFaultCodes.Key.FaultCode,
                Count = newFaultCodes.Count()
            });

A: This is a perfect use case for .Contains()
var serverGroups = new string []{ "A", "B" }.ToList();

var query = referenceDt.AsEnumerable()
        .Where(results => serverGroups.Contains(results.Field<string>("ServerGroup")))
        .GroupBy(results => new
            {
                FaultCode = results.Field<int>("FaultCode")
            })
        .OrderByDescending(newFaultCodes => newFaultCodes.Key.FaultCode)
        .Select(newFaultCodes => new
        {
            FaultCode = newFaultCodes.Key.FaultCode,
            Count = newFaultCodes.Count()
        });

where serverGroups would be dynamically generated.

A: You can use  Contains in Linq query for SQL equivalent of IN.


text:
Q: Returning JSON object using jquery as a string (XSS)
*

*I'm using jquery to display a returned JSON file, however, I want to
display the returned object as a string to mitigate XSS, so the value is displayed as plain text and is iterated through. This is part of the statement which displays the values. escape inputs "%20" between
strings. What is the best practice to do this?
if (myObj.value === undefined || myObj.value === null){
    extrahtml += '' + "" + '	';
} else {
    extrahtml += '' + escape(myObj.value) + '	';
}


text:
Q: Tomcat Remote Address Filter is not working - Tomcat 9.0.X I'm trying to restrict the some of my application endpoints for public internet. For this I tried tomcat's Remote Address Filter. I added the filter to my application's web.xml (D:\apache-tomcat-9.0.22\webapps\myApp\WEB-INF). but it does not effect at all. I tried both <param-name>allow</param-name>  <param-name>deny</param-name> and specific IP addresses of my team member, but still it is we all can access.  Each time of this change, I've restarted the tomcat.
<filter>
    <filter-name>Remote Address Filter</filter-name>
    <filter-class>org.apache.catalina.filters.RemoteAddrFilter</filter-class>
    <init-param>
      <param-name>deny</param-name> <!-- Tried to block my team mate's IP -->
      <param-value>10\.142\.16\.1</param-value>  <!-- My team mates IP address -->

      <!-- param-value>127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1</param-value -->

    </init-param>
 </filter>

 <filter-mapping>
    <filter-name>Remote Address Filter</filter-name>
    <url-pattern>/myApp/context/* </url-pattern>
 </filter-mapping>

Also I tried as in documentation  <param-value>127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1</param-value> but still my team mate and myself can access the pages without any problem.
My environment details>>
I've used a standalone Tomcat. Servlet engine: [Apache Tomcat/9.0.22]
Running with Spring Boot v2.1.3.RELEASE, Spring v5.1.5.RELEASE

Where could be the problem?  Is there a way to find whether the web.xml changes are really reflecting?

A: I found the problem. The problem was with the url-pattern. We shouldn't add the application context to the url-pattern.
Now this works with below settings.
<url-pattern>/actuator/health </url-pattern>

A: One possible solution is to add restrictions in application/META-INF/context.xml. this would result in 403 for entire application. you could see the implementation in webapps\manager\META-INF of your tomcat.
<?xml version="1.0" encoding="UTF-8"?>
<Context antiResourceLocking="false" privileged="true" >
  <Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />
</Context>


text:
Q: Wordpress how to check if a post is the first post I am using the get_previous_post() to check if the first custom post type so I can add a condition. It works if it's not equal to 0 (the first post), to make it work I need to parse the output.
The following didn't work, I get the error Argument ($str) must be of type string
$checkFirst = get_previous_post();
<?php !(wp_parse_str(strlen($checkFirst)) == 0) ? 'something' : '';?>

I have also tried :
wp_parse_str(strlen($checkFirst), $output)
<?php !($output[strlen($checkFirst)] == 0) ? 'something' : '';?>

A: Why do you think you need to parse it?
According to the get_previous_postDocs, it returns:

*

*Null if global $post is not set.

*Empty string if no corresponding post exists.

*Post object if the current post is not the first one.

So you could check its value like this:
$checkFirst = get_previous_post();

echo $checkFirst
               ? 'There is a previous post'
               : 'No, this is the first post';

You don't need to use strlen or wp_parse_str.


text:
Q: ASP.NET / SQL Server - Timeout expired while searching We have a table called Purchases:
| PRSNumber   | ... | ... | ProjectCode |
| PRJCD-00001 |     |     | PRJCD       |
| PRJCD-00002 |     |     | PRJCD       |
| PRJCD-00003 |     |     | PRJCD       |
| PRJX2-00003 |     |     | PRJX2       |
| PRJX2-00003 |     |     | PRJX2       |

Note: ProjectCode is the prefix of PRSNumber.
Before, when there is no ProjectCode field in the table, our former developers use this query to search for purchases with specific supplier:
select * from Purchases where left(PRSNumber,5) = @ProjectCode

Yes, they concatenate the PRSNumber in order to obtain and compare the ProjectCode. Although, the code above works fine regardless of the table design.
But when I added a new field, the ProjectCode, and use this query:
select * from Purchases where ProjectCode = @ProjectCode

I receive this exception:

Timeout expired. The timeout period elapsed prior to completion
  of the operation or the server is not responding.

I can't believe, that the first query, which needs concatenation before the compare, is faster than the second one which has to do nothing but compare. Can you please tell me why is this happening?
Some information which might be helpful:

*

*PRSNumber is varchar(11) and is the primary key

*ProjectCode is nvarchar(10)

*Both query works fine in SQL Server Management Studio

*First query works in ASP.NET website, but the second does not

*ProjectCode is indexed

*The table has 32k rows

Update

*

*ProjectCode is now indexed, still no luck

A: First thing I would do is check the index on PRSNumber, I assume there is an index on that field and the table is very large.
Adding an index to your new field will likely fix the problem (if that is the case).
The code to add an index:
CREATE INDEX IX_Purchases_ProjectCode
ON dbo.Purchases (ProjectCode);

Update:
I would also try adding the field as a varchar to eliminate the datatype change from the equation.

A: I set the CommandTimeout property of my SqlCommand higher instead of making the query faster. It didn't solve the speed but solved the timeout issue.


text:
Q: clearTimeout() is not working properly Here is a JSFiddle example of the problem.
When I click the button everything fades as expected and returns in 3 seconds or until cliked. However, if I do not wait the 3 seconds but click it early and then quickly click the button it returns in less than 3 seconds.
EDIT: a better explanation of the problem:
 In the JSFiddle, click the green button, click the open space to stop the fade, and then click the green button again (this all has to be done quickly). The elements fade back in way too quickly.
Thanks Katana314
var waiting;

function startNext() {
  $(document).off('click');
  window.clearTimeout(waiting);
  $('#correctT, #correctP').fadeOut('fast', function() {
    $('#button1, #button2, #button3, #button4, #title, #image, #ame').fadeIn('slow');

  })

}
$('#button1, #button2, #button3, #button4').click(function(e) {

  $('#button1, #button2, #button3, #button4, #title, #image, #ame').fadeOut('fast', function() {

    $('#button1, #button2, #button3, #button4, #title, #image, #ame').hide();
    $('#correctT, #correctP').fadeIn('fast');

    $(document).click(startNext);

    waiting = setTimeout(startNext, 2500);
  });
});

A: The root of your problem is here:
$('#button1, #button2, #button3, #button4, #title, #image, #ame').fadeOut('fast', function() {

    $('#button1, #button2, #button3, #button4, #title, #image, #ame').hide();
    $('#correctT, #correctP').fadeIn('fast');

    $(document).click(startNext);

    waiting = setTimeout(startNext, 2500);
    console.log("started timer:" + waiting );
});

If you run this and look at your console what do you see? You see that you are starting not one, but 7 timers. Your fadeOut handler will be called for each of your elements. So you start 7 timers, but waiting only has the id of the last timer started. So the other 6 are still running. Robert's answer above avoids that problem by not starting another timer if one is already set and that works. A cleaner solution would be to wait for all the animations to be done. For example, see here:
jQuery wait till all page animations are done
So something like this ought to work:
$('#button1, #button2, #button3, #button4, #title, #image, #ame').fadeOut('fast').promise().done(function() {

    $('#button1, #button2, #button3, #button4, #title, #image, #ame').hide();
    $('#correctT, #correctP').fadeIn('fast');

    $(document).click(startNext);

    waiting = setTimeout(startNext, 2500);
    console.log("started timer:" + waiting);
});

A: https://jsfiddle.net/1dmjvon3/3/
take care of your timeout ids...
if(waiting!==null){
    window.clearTimeout(waiting);
    waiting = null;
}

also
if(waiting===null) waiting = setTimeout(startNext, 2500);

A more appropriate solution is to assign a class name to each of the elements in your selector and use the classname as the selector so the function doesn't fire seven times.
Here's another fiddle: https://jsfiddle.net/1dmjvon3/


text:
Q: c# Windows Azure Mobile Services insert/read data I'm creating a Windows 8 Store App (c#) using Windows Azure Mobile Services to store my data.
I can successfully add data to the Table (ToDoItem) but got problems with reading it.
To add Data:
public class TodoItem
{
    public int Id { get; set; }

    [DataMember(Name = "text")]
    public string Text { get; set; }

    [DataMember(Name = "Private")]
    public bool Private { get; set; }

    [DataMember(Name = "FirstTeam")]
    public string Team1 { get; set; }

    [DataMember(Name = "SecondTeam")]
    public string Team2 { get; set; }
}

public sealed partial class ViewItems : Page
{

    private ObservableCollection<TodoItem> items;
    private IMobileServiceTable<TodoItem> todoTable = App.MobileService.GetTable<TodoItem>();

    private async void InsertTodoItem(TodoItem todoItem)
    {
        await todoTable.InsertAsync(todoItem);
    }

    private void ButtonSave_Click(object sender, RoutedEventArgs e)
    {
        var todoItem = new TodoItem { Text = Ploeg1.Text, Team1 = Ploeg1.Text, Team2 = Ploeg2.Text};
        InsertTodoItem(todoItem);
    }
}

So this piece of code works! Now the problem: I want to read the data from the Mobile Service in another blank page:
public class TodoItem
{
    public int Id { get; set; }

    [DataMember(Name = "text")]
    public string Text { get; set; }

    [DataMember(Name = "Private")]
    public bool Private { get; set; }

    [DataMember(Name = "FirstTeam")]
    public string Team1 { get; set; }

    [DataMember(Name = "SecondTeam")]
    public string Team2 { get; set; }
}

public sealed partial class gamestore : Page
{
    private ObservableCollection<TodoItem> items;
    private IMobileServiceTable<TodoItem> todoTable = App.MobileService.GetTable<TodoItem>();

    private void ButtonRefresh_Click(object sender, RoutedEventArgs e)
    {
       RefreshTodoItems();
    }

    private async void RefreshTodoItems()
    {
        var results = await todoTable2
            .Where(todoItem => todoItem.Private == false)
            .ToListAsync();

        items = new ObservableCollection<TodoItem>(results);
        ListItems.ItemsSource = items;
    }
}

I have some Ambiguity errors with this. I know I'm using the same names but those are my column names. How can I make this work so it would be able to read the saved data on another page??

A: Fixed the problem! Changed a few names


text:
Q: Java crash during garbage collection I have the following problem: Java application without using JNI regularly crashes during garbage collection:
A fatal error has been detected by the Java Runtime Environment:
EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x0000000000000000, pid=3032, tid=0x0000000000000500

JRE version: Java(TM) SE Runtime Environment (8.0_211-b12) (build 1.8.0_211-b12)
Java VM: Java HotSpot(TM) 64-Bit Server VM (25.211-b12 mixed mode windows-amd64 compressed oops)
Problematic frame:
C  0x0000000000000000
---------------  T H R E A D  ---------------
Current thread (0x000000000323f000):  GCTaskThread [stack: 0x0000000017af0000,0x0000000017bf0000] [id=1280]

I don't override the finalize method.
What could cause such crashes?
If gc crash during validation of pointers to objects, probably, we can see what gc collecting before the crash?
I have tried many versions of jdk8, the error is the same everywhere.

A: My bet is that you are running out of memory.


text:
Q: API Key implementation in Apache Shiro I have Java web application which implemented Apache shiro Authentication & Authorization.
Now i need to implement API Key to the existing project (which has apache shiro).
Please help me on implementation part. Even i could not find any documentation
PS:: We have already implemented 3 different types of Custom Realm(jdbc,ldap,Pac4jRealm) but now struggling to implement the API key concept with Apache Shiro.

A: I resolved the above issue by extending the JDBCRealm,see the below example code
public class APIRealm extends JdbcRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        SimpleAuthorizationInfo info = null;
        AuthAPIInfo authInfo = null;
        try {
        String apiKey= (String) principals.getPrimaryPrincipal();
        authInfo=fetchAPIKeyInfo(apiName);

        // Do all the other stuff like checking for Authorization and setting it to token

        } catch (Exception e) {
            insertAPILogActivity(authInfo, "User not authorized");
        }
        return info;

    }

private AuthAPIInfo fetchAPIKeyInfo(String apiKeyName) {
    //Connect to Database using JDBC connection and validate the API Key and return the AuthAPIInfo
}

}

Add the above realm in shiro.ini
apiRealm=com.example.APIRealm
securityManager.realms=$apiRealm


text:
Q: Scraping Google Front Page Results with php i can with php code Scraping title and url from google search results now how to get descriptions
$url  = 'http://www.google.com/search?hl=en&safe=active&tbo=d&site=&source=hp&q=Beautiful+Bangladesh&oq=Beautiful+Bangladesh';
$html = file_get_html($url);

$linkObjs = $html->find('h3.r a');
foreach ($linkObjs as $linkObj) {
    $title = trim($linkObj->plaintext);
    $link  = trim($linkObj->href);

    // if it is not a direct link but url reference found inside it, then extract
    if (!preg_match('/^https?/', $link) && preg_match('/q=(.+)&sa=/U', $link, $matches) && preg_match('/^https?/', $matches[1])) {
        $link = $matches[1];
    } else if (!preg_match('/^https?/', $link)) { // skip if it is not a valid link
        continue;
    }

    echo '
Title: ' . $title . '
';
    echo 'Link: ' . $link . '
';
}

The above code gives the following output
Title: Natural Beauties - Bangladesh Photo Gallery
Link: http://www.photo.com.bd/Beauties/

Now I want the following output
Title: Natural Beauties - Bangladesh Photo Gallery
Link: http://www.photo.com.bd/Beauties/
description : photo.com.bd is a website for creative photographers from Bangladesh, mainly for amateur ... Natural-Beauty-of-Bangladesh_Flower · fishing on ... BEAUTY-4.

A: include("simple_html_dom.php");

$in = "Beautiful Bangladesh";
$in = str_replace(' ','+',$in); // space is a +
$url  = 'http://www.google.com/search?hl=en&tbo=d&site=&source=hp&q='.$in.'&oq='.$in.'';

print $url."
";

$html = file_get_html($url);

$i=0;
$linkObjs = $html->find('h3.r a');
foreach ($linkObjs as $linkObj) {
    $title = trim($linkObj->plaintext);
    $link  = trim($linkObj->href);

    // if it is not a direct link but url reference found inside it, then extract
    if (!preg_match('/^https?/', $link) && preg_match('/q=(.+)&sa=/U', $link, $matches) && preg_match('/^https?/', $matches[1])) {
        $link = $matches[1];
    } else if (!preg_match('/^https?/', $link)) { // skip if it is not a valid link
        continue;
    }

    $descr = $html->find('span.st',$i); // description is not a child element of H3 thereforce we use a counter and recheck.
    $i++;
    echo '
Title: ' . $title . '
';
    echo 'Link: ' . $link . '
';
    echo 'Description: ' . $descr . '
';
}


text:
Q: How to create Account while creating New Contact from the Contact lookup on Lead On Lead, I have a lookup to Contact. When I attempt to create a new contact from this lookup field, the new Contact dialog box appears, but within here, I cannot create a new Account from the Account lookup field. On the other hand, when I create a new Contact from the Contacts tab, I am able to create a new Account from the Account lookup field. Is there a way I can create a new account, while creating a new Contact from the Contact lookup field ?

A: I assume that you are on classic because right now it is unavailable to disable quick create option on lookup fields on forms in lightning - if you have create permission on the lookup item.
https://success.salesforce.com/ideaView?id=0873A000000TvUBQA0

Are you sure that you have checked the OWD permissions on the object?
The answer above mine reflects correctly on your question, you cannot use this feature over multiple dialog/relations per 1 item creation. Try to use some kind of guided flow to achive your real needs.

A: You can only go one object away in creating a new record from a lookup field. You cannot create a new object, while creating a new object, while creating a new object.


text:
Q: Yii profiler get methods names My goal is know all steps what my app execute. Example:
Method1() -> Method2() -> Method3()

How can I achieve this ? I logging everythin: my log looks like:
    'routes' => [
        [
            'class' => 'CFileLogRoute',
            'levels' => 'error, warning, trace, info, profile',
            'categories' => 'system.*',

        ],

Bet all still not have methods names in log.

A: To improve profiling exist issue to increse trace level to:
define('YII_TRACE_LEVEL',3);

That will allow to get file line numbers where method call. In logs you will some thins like:
UserController.php 78 line 'SELECT * FROM `users`'


text:
Q: Confused with function-object usage in Python Am currently learning python using "Think Python" in which i came through a certain piece of code like below and am being a beginner programmer i don't understand how it works, explain me the code below and also the various concepts behind it.
excercise: A function object is a value you can assign to a variable or pass as an argument. For
example, do_twice is a function that takes a function object as an argument and calls it twice:
def do_twice(f):
    f()
    f()

# Here's an example that uses do_twice to call a function named print_spam twice.

def print_spam():
    print 'spam'

do_twice(print_spam)

this code gives o/p as
spam
spam
i dont know how and i want deeper explanation with this concept

A: Python functions are first-class objects. Just like other objects, they can be assigned to variables and passed around.
>>> def print_spam():
...     print 'spam'
...
>>> print_spam
<function print_spam at 0x105722ed8>
>>> type(print_spam)
<type 'function'>
>>> another_name = print_spam
>>> another_name
<function print_spam at 0x105722ed8>
>>> another_name is print_spam
True
>>> another_name()
spam

In the above example session I play around with the print_spam function object, assigning it to another_name, then invoking it via that other variable.
All that the code you quoted from Think Python does is pass print_spam as a parameter to the function do_twice, which calls it's parameter f twice.


text:
Q: BackgroundWorkerThread access in a thread I use BackgroundWorker most of the time in the win form apps to show progress as I'm getting data. I was under impression that Work_completed is guaranteed to be executed on Main UI thread but it's not. If we create a thread and call the worker.RunWorkerAsync within it, it breaks if we try to update any gui control. Here is an example
private void StartButton_Click(object sender, EventArgs e)
{
    Thread thread1 = new Thread(new ThreadStart(PerformWorkerTask));
    _worker = new BackgroundWorker();
    thread1.Start();
}

public void PerformWorkerTask()
{
    _worker.DoWork += delegate
    {
        for (int i = 0; i < 10; i++)
        {
            Thread.Sleep(100);
        }
    };

    _worker.RunWorkerCompleted += delegate
    {
        // this throws exception
        MessageLabel.Text = "Completed";
    };
    _worker.RunWorkerAsync();

 }

How can we make backgroundworker work in this case?

A: From your example it's hard to see what good the Thread (thread1) is, but if you really do need this thread1 then I think your only option is to use MainForm.Invoke() to execute RunWorkerAsync() (or a small method around it) on the main thread.
Added: You can use something like this:
Action a = new Action(_worker.RunWorkerAsync);
this.Invoke(a);

A: RunWorkerAsync does its thread-synchronization magic by getting the  SynchronizationContext from the thread that it is called on.  It then guarantees that the events will be executed on the correct thread according to the semantics of the SynchronizationContext it got.  In the case of the WindowsFormsSynchronizationContext, which is what is automatically used if you're using WinForms, the events are synchronized by posting to the message queue of the thread that started the operation.  Of course, this is all transparent to you until it breaks.
EDIT: You MUST call RunWorkerAsync from the UI thread for this to work.  If you can't do it any other way, your best bet is to invoke the beginning of the operation on a control so that the worker is started on the UI thread:
private void RunWorker()
{
    _worker = new BackgroundWorker();

    _worker.DoWork += delegate
    {
        // do work
    };

    _worker.RunWorkerCompleted += delegate
    {
        MessageLabel.Text = "Completed";
    };

    _worker.RunWorkerAsync();
}

// ... some code that's executing on a non-UI thread ...
{
    MessageLabel.Invoke(new Action(RunWorker));
}

A: It sounds like the issue is just that you want to make a change to a GUI component and you aren't actually sure if you're on the GUI thread.  Dan posted a valid method of setting a GUI component property safely, but I find the following shortcut method the simplest:
            MessageLabel.Invoke(
                (MethodInvoker)delegate
                {
                    MessageLabel.Text = "Hello World";
                });

If there are any issues with this approach, I'd like to know about them!

A: In the code you have presented here, you're adding the delegates for the BackgroundWorker events in a separate thread from the UI thread.
Try adding the event handlers in the main UI thread, and you should be okay.

A: I believe BackgroundWorker is designed to automatically utilize a new thread. Therefore creating a new thread just to call RunWorkerAsync is redundant. You are creating a thread just to create yet another thread. What's probably happening is this:

*

*You create a new thread from thread 1 (the GUI thread); call this thread 2.

*From thread 2, you launch RunWorkerAsync which itself creates yet another thread; call this thread 3.

*The code for RunWorkerCompleted runs on thread 2, which is the thread that called RunWorkerAsync.

*Since thread 2 is not the same as the GUI thread (thread 1), you get an illegal cross-thread call exception.

(The below suggestion uses VB instead of C# since that's what I'm more familiar with; I'm guessing you can figure out how to write the appropriate C# code to do the same thing.)
Get rid of the extraneous new thread; just declare _worker WithEvents, add handlers to _worker.DoWork and _worker.RunWorkerCompleted, and then call _worker.RunWorkerAsync instead of defining a custom PerformWorkerTask function.
EDIT: To update GUI controls in a thread-safe manner, use code like the following (more or less copied from this article from MSDN):
delegate void SetTextCallback(System.Windows.Forms.Control c, string t);

private void SafeSetText(System.Windows.Forms.Control c, string t)
{
  if (c.InvokeRequired)
  {
    SetTextCallback d = new SetTextCallback(SafeSetText);
    d.Invoke(d, new object[] { c, t });
  }

  else
  {
    c.Text = t;
  }
}

A: You could probably make your existing code work by doing:
this.Dispatcher.BeginInvoke(() => MessageLabel.Text = "Completed")

instead of
MessageLabel.Text = "Completed"

You're probably having cross-thread data access issues, so you have to ensure that you access properties of MessageLabel on your UI thread.  This is one way to do that.  Some of the other suggestions are valid too.  The question to ask yourself is: why are you creating a thread that does nothing other than create a BackgroundWorker thread?  If there's a reason, then fine, but from what you've shown here there's no reason you couldn't create and start the BackgroundWorker thread from your event handler, in which case there would be no cross-thread access issue because the RunWorkerCompleted event handler will call its delegates on the UI thread.

A: The best way to deal with these generic problems is to deal it once. Here I'm posting a small class that wraps the backgroupdworker thread and makes sure that the workcompleted always gets executed on the UI thread.

using System.Windows.Forms;
namespace UI.Windows.Forms.Utilities.DataManagment
{
    public class DataLoader
    {
        private BackgroundWorker _worker;
        private DoWorkEventHandler _workDelegate;
        private RunWorkerCompletedEventHandler _workCompleted;
        private ExceptionHandlerDelegate _exceptionHandler;
        public static readonly Control ControlInvoker = new Control();

     public DoWorkEventHandler WorkDelegate
    {
        get { return _workDelegate; }
        set { _workDelegate = value; }
    }

    public RunWorkerCompletedEventHandler WorkCompleted
    {
        get { return _workCompleted; }
        set { _workCompleted = value; }
    }

    public ExceptionHandlerDelegate ExceptionHandler
    {
        get { return _exceptionHandler; }
        set { _exceptionHandler = value; }
    }

    public void Execute()
    {
        if (WorkDelegate == null)
        {
            throw new Exception(
                "WorkDelegage is not assinged any method to execute. Use WorkDelegate Property to assing the method to execute");
        }
        if (WorkCompleted == null)
        {
            throw new Exception(
                "WorkCompleted is not assinged any method to execute. Use WorkCompleted Property to assing the method to execute");
        }

        SetupWorkerThread();
        _worker.RunWorkerAsync();
    }

    private void SetupWorkerThread()
    {
        _worker = new BackgroundWorker();
        _worker.WorkerSupportsCancellation = true;
        _worker.DoWork += WorkDelegate;
        _worker.RunWorkerCompleted += worker_RunWorkerCompleted;

    }

    void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if(e.Error !=null && ExceptionHandler != null)
        {
            ExceptionHandler(e.Error);
            return;
        }
        ControlInvoker.Invoke(WorkCompleted, this, e);
    }
}

}

And here is the usage. One thing to note is that it exposes a static property ControlInvoker that needs to be set only once (you should do it at the beginning of the app load)

Let's take the same example that I posted in question and re write it

DataLoader loader = new DataLoader();
loader.ControlInvoker.Parent = this; // needed to be set only once

private void StartButton_Click(object sender, EventArgs e)
{

Thread thread1 = new Thread(new ThreadStart(PerformWorkerTask));
_worker = new BackgroundWorker();
thread1.Start();

}

public void PerformWorkerTask()
{

        loader.WorkDelegate = delegate {
                                         // get any data you want
                                         for (int i = 0; i < 10; i++)
                                        {
                                            Thread.Sleep(100);
                                        }

                                       };
        loader.WorkCompleted = delegate
                                   {
                                       // access any control you want
                                       MessageLabel.Text = "Completed";

                                   };
        loader.Execute();

}
Cheers


text:
Q: Distribution function of Sum of IID Exponentiation Variables of Variable amount So I'm trying to determine the distribution function of a random variable, S, give:

*$N \sim Geo(\frac{1}{1+\lambda}) $

*$S_i \sim Exp(\mu), \forall i\in [0,N]$

*$S = \Sigma^{N}_{i=0}S_i$

*$S = 0$ if $N=0$

Taking the approach of first evaluating $P(S>x)$, I know that the sum of n exponentiation distributions is a Gamma distribution and by the Law of Total Probability:

*$P(S>x)=\Sigma^{\infty}_{i=0}P(S>x|N=n)\times P(N=n)$

*$=\Sigma^{\infty}_{n=0}[[(\frac{1}{1+\lambda})(\frac{\lambda}{1+\lambda})^n][e^{-\mu x}\Sigma^{n-1}_{r=0}\frac{(\mu x)^r}{r!}]]$ (I think)

But I'm completely stuck at that ... if it's even correct.


text:
Q: How to clear the text in the address bar? I am creating a custom new tab page, and I want links to localhost and my router.  It seems if I want to link to one of these it just appends it to the existing text in my address bar, instead of clearing it like it does for http:// links.
$('#router').on('click', function() {
    window.open("192.168.1.1");
});

This is the address it opens:
file:///C:/Users/brennan/development/new_tab/192.168.1.1
instead of just:
192.168.1.1

A: It is using relative paths
Try
window.open("http://192.168.1.1");

A: Add http:// in the front.
 $('#router').on('click', function() {
    window.open("http://192.168.1.1");
 });

A: try window.open("http://192.168.1.1"). Because otherwise code reacts as if you are looking for a local file named 192.168.1.1


text:
Q: How to access typescpirt empty object properties my code is like this
type.js
export interface User {
  name: string;
  age: number;
}

I am using react
Coponent.tsx
const [state,setState] = useState<User|{}>({});

const isValid = () =>{
 const clone = { ...state};

 const name:string = clone.name //<= error

}

i tried this
 const name:string = clone?.name

Any good solutions?

A: User | {} does not mean 'a possibly empty User object.' It means this type is either an object of type User or an empty object. In your React code, you've set the state variable to be an empty object, which will never have the name or age properties.
From the code you've shared, it's hard to deduce what you're trying to accomplish. But depending on what you're trying to do, you could try something like this:
const Component = () => {
  // forget an empty object, use null or undefined (the below expression will set state to undefined)
  const [state, setState] = useState<User | undefined>();

  const isValid = (): boolean => {
    if (!state) {
      return false;
    }
    // now that we know state is not null or undefined, we know it's of type `User`! We can now clone our state for whatever we're trying to do
    const clone = { ...state};

    const name:string = clone.name //<= should no longer error
    return true;
  }
}

A:   const [state, setState] = useState<User | undefined>();

  const isValid = () => {
    if (!state) {
      return false;
    }

    // do validate
    const clone = { ...state };
    const name: string = clone.name;
  };

A: Please try with this.

const {name} = clone;


text:
Q: ffmpeg - Stream webcam - RTP h264 + audio I am trying to create a rtp stream using ffmpeg. I am taking input from my logitech C920 which has built in h264 encoding support and also has a microphone. I wanted to send both video(h264 either with the built in encoder or ffmpeg's encoder) and audio(any encoding) through RTP and then play the stream using ffplay.
So far I am able to send only the video with the following command:
ffmpeg -i /dev/video0 -r 24 -video_size 320x240 -c:v libx264 -f  rtp rtp://127.0.0.1:9999

and also the audio separately using the command:
ffmpeg  -f alsa -i plughw:CARD=C920,DEV=0 -acodec libmp3lame -t 20 -f  rtp rtp://127.0.0.1:9998

and play the sdp file with:
 ffplay -i -protocol_whitelist file,udp,rtp test3.sdp
 ffplay -i -protocol_whitelist file,udp,rtp test4.sdp

I'm on Ubuntu 14.04
How can I play the two streams with a single ffplay command as ffplay cannot take two inputs and I can't send two streams using a single RTP stream(or can I?).
Also, how can I use the built in h264 encoder of my webcam?
Thank you!


text:
Q: Super class checking for respondsToSelector fails I did the following code, to check, if super implement the method (using respondsToSelector)
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if ([super respondsToSelector:@selector(scrollViewWillBeginDragging:)]) {
        [super scrollViewWillBeginDragging:scrollView];
    }

    self.scrolling = YES;
}

but it evaluates to YES and than it breaks on unrecognized selector
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[InputFormViewController scrollViewWillBeginDragging:]: unrecognized selector sent to instance 0x17da8670'

Is this the desired (faulty) behavior, or am i doing smth. wrong?
Note: super class is
@interface FormBaseViewController : UIViewController<UITableViewDataSource, UITableViewDelegate>

that doesnt implement (scrollViewWillBeginDragging:)

A: [super respondsToSelector: @selector(someSelector)] doesn't test whether the superclass implements someSelector. It tests whether the current object (i.e. self) responds to someSelector, but it does it using the superclass's implementation of respondsToSelector:. In other words, unless you have overridden respondsToSelector:, the code [super respondsToSelector: @selector(someSelector)] is exactly the same as [self respondsToSelector: @selector(someSelector)], because you were already using the inherited version.
What you want is [[[self class] superclass] instancesRespondToSelector: @selector(someSelector)].
Though I am not sure why you'd do this, since dynamic superclasses are not really supported by the language.


text:
Q: Can I use / mention a third party payment provider in my app After reading several threads on Stackoverflow / Reddit it's still quite confusing what is allowed on Android / iOS regarding payments.
I have a an app available for iOS and Android and a web app dashboard. The iOS / Android / Web app uses a API where your profile and statistics are stored.
To cover the costs of the server I want to add a premium membership feature.
Users can subscribe on a monthly / yearly base.
This allows the user to get more statistics available in the app (iOS, Android and Webapp).
The idea is the same as Spotify (free account / paid account) with the difference that you get music
without ads with Spotify and here you will get access to more statistics data / more filter options in the API.

A: If you are using subscription method you need to use apple In-App purchase which you are using.
Regarding mentioning the payment provider, you can write in the description about how your app let users use the in-app purchase feature and list out the plans for more clarifications.


text:
Q: test equality of 2 string on python error from optparse import OptionParser
usage = "usage: %prog [options]"
parser = OptionParser(usage=usage)
import sys
print("Please choose the type of agent")
line = sys.stdin.readline()

i have put random and when i test what line looks like it give me random
parser.add_option("-p","--player1",dest="player1",
                  default=str(line),help="Choose type of first player")

i want to  test if the value in entry are equal but it returns nothing why the default parameter can't learn the value str(line) i try also for line withour str
if str(opts.player1)=='random':
    print ('true')

A: The return value of sys.stdin.readline() retains the newline, so the value of line is 'random\n', not 'random'. You need to strip it first:
parser.add_option(..., default=str(line.strip()), ...)


text:
Q: Cannot read eslintrc config file, stripComments is not found Im struggling with an npm run build (webpack) step. Locally on my machine its building fine. But on the remote build im getting an error when it tries to build the eslint module.
The error is as follows:
ERROR in ./app/app.module.js
Module build failed: TypeError: Cannot read config file: D:\a\1\s\.eslintrc.json
Error: stripComments is not a function
From digging into it. I have a feeling its some dependency that I have installed locally but the remote build doesnt have it. Ive tried clearing the npm cache, deleting my local npm modules. But I cant seem to repro on my local machine.That function seems to come from strip-json-comments lib, I added it as a dependency but still no dice.
Any ideas? Help to get this error solved? Thanks!
Heres my package.json..
{
  "name": "My Dummy App",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "start": "node server.js",
    "build": "webpack",
    "watch": "webpack --watch"
  },
  "dependencies": {
    "Some Private Package": "^1.3.23",
    "request": "^2.87.0",
    "dotenv": "^6.0.0"
  },
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-env": "^1.6.0",
    "eslint": "^4.15.0",
    "eslint-config-google": "^0.9.1",
    "eslint-loader": "^1.9.0",
    "eslint-plugin-import": "^2.8.0",
    "babel-plugin-angularjs-annotate": "^0.9.0",
    "node-sass": "^4.7.2",
    "webpack": "^3.5.5"
  }
}


text:
Q: Validación del nombre de los headers al importar excel Hola estoy utilizando laravel excel para importar un excel a mi app. Pero me encuentro con un problema y es que necesito validar el nombre de las cabeceras de las filas y validar que se importe el archivo con el formato correcto.
Intente hacer la validación, pero no esta funcionando. Es como si no se estuviera ejecutando la validación.
Así lo tengo en mi import.
public function model(array $row)
{

    return new Factura([
        'documento'         => $row['rnc_cedula'],
        'tipo_documento'    => $row['tipo_de_identificacion'],
        'ncf'               => $row['ncf'],
    )]
}

Esta es la validacion de las cabeceras:
public function rules(): array
{
    return [
        // Fila.columna
        '0.0'   => 'in:rnc_cedula',
        '0.1'   => 'in:tipo_de_identificacion',
        '0.2'   => 'in:ncf',
    ];
}

En el controlador estoy intentando atrapar el error:
try{
            Excel::import($import, $request->archivo );
        }
        catch (\Maatwebsite\Excel\Validators\ValidationException $e) {
            $failures = $e->failures();

            foreach ($failures as $failure) {
                $failure->row(); // row that went wrong
                $failure->attribute(); // either heading key (if using heading row concern) or column index
                $failure->errors(); // Actual error messages from Laravel validator
                $failure->values(); // The values of the row that has failed.
            }
        }

Y si trato de importar un archivo que no tiene este formato me sale este error:


text:
Q: Enable 'Run as an Administrator' for Windows 7/Vista application (VS2012/InstallShield2013) I'm using VS2012 & InstallShield2013 to generate installer file.
Some of the installed user couldn't run this application on WIn 7 OS. But they can get into the installed directory
and right click 'Run as an Administrator' it works.
The icon on the desktop, when i right right click there is no option like 'Run as an Administrator'.
I checked in the InstallShield directory C:\Program Files\InstallShield\2013LE\Support\
There are three files:
SetupExe.Admin.manifest,
SetupExe.Highest.manifest,
SetupExe.Invoker.manifest
So I followed this article : http://helpnet.flexerasoftware.com/installshield20helplib/Content/helplibrary/SpecifyingRequiredExecution.htm
and selected Required Execution Level  'Invoker' and Include MSI Engine:yes in the 'Release Setup /Single Image'
How can i enable the option to right click 'Run as an Administrator'?
It's important for me to fix this problem, for the users of Win 7 32/64 & Win Vista.
I'm totally confused about these files. Please help me.

A: The settings you reference in InstallShield will not affect how your application itself runs; instead they only change the privileges setup.exe requires when launched.
As for your application, there are a number of potential moving pieces that can affect whether the "Run as administrator" option shows up in the context menu in Explorer:

*

*If the exe referenced by the shortcut has a manifest that requires administrative access, it will always run elevated, and the Run as administrator option will not appear

*If the exe referenced is detected as an installer, Windows may choose to act as though it has a manifest requiring administrative access, and thus the Run as administrator option may not appear

*If the Program Compatability Assistant (PCA) has decided the program needs administrative access, ditto

*If the shortcut's compatibility settings have been modified to select "Run this program as an administrator", ditto

*If UAC is disabled, Explorer may choose not to show Run as administrator

Some of these scenarios may persist across uninstallation and reinstallation; Windows can be very aggressive in its attempts to improve the end-user experience. However in all these cases, the end result is that your application would launch as an administrator.
If you always require administrative access in your application, you are strongly advised to implement the first of these: embed a manifest that includes the requiresAdministrator setting. This is equivalent to what the settings you reference change for setup.exe, but must be done in your application's executable.


text:
Q: Excel 2010 SUMPRODUCT with multiple conditions I have three columns A=Date, B=Region, C=Qty. I need to identify the Qty in the GR region between two dates.
I have tried this formula with no success:
$B$3=Beginning date,
$C$3=Ending date

=SUMPRODUCT(($A$6:$A$5000>=$B$3) * ($A$6:$A$5000 < $C$3) * ($B$6:$B$5000="GR"),$C$6:$C$5000)

Output is 0.


text:
Q: J2ME InvalidRecordIDException Nokia 2700 I have an RMS having 512 records as retrieved from
rs.getNumRecords();

But when I try to read the records using getRecordId(i) or even if using
rs.enumerateRecords( null, null, false );

I get InvalidRecordIDException, for records from 1 to 180, and I am able to read the records from 181 index to onwords.
I am not deleting the records anywhere in my application.
There have been instances of exiting the application in between while processing (reading this RMS), and overwriting the application.
I am closing the RMS at the end of my try block while reading the records.
Are there any possible reasons, of getting RMS corrupted or the particular indexes getting corrupted??
Code for reading the RMS  using getRecord is
 try {
        RecordStore rs = RecordStore.openRecordStore(getTableName(), true);
        ByteArrayInputStream inputStream = null;
        DataInputStream inputDataStream = null;

       int nor = rs.getNumRecords();

      for(int i=1;i<=nor;i++)
      {
         System.out.println("i : "+i);

        _recordByteArr =  rs.getRecord(i);

        inputStream = new ByteArrayInputStream(_recordByteArr);
        inputDataStream = new DataInputStream(inputStream);

        System.out.println("val at " + i + " ::" + new String(_recordByteArr));

        //used inputDataStream.readUTF() here
      }
      if (inputDataStream != null) {
            inputDataStream.close();
      }
      if (inputStream != null) {
            inputStream.close();
      }

      rs.closeRecordStore();

    } catch (Exception e) {
        System.out.println("exp in read fieldtxn :" + e);
    }

A: According to documentation on enumerateRecords method "This is the most efficient way to traverse all of the records in a record store."
I always use rs.enumerateRecords(null /*filter*/, null /*comparator*/, false /*keepUpdated*/) because I believe it is safer.
It is very odd that you are getting an InvalidRecordIDException from a RecordEnumeration traversal. Be sure to use it like this
RecordEnumeration re = rs.enumerateRecords( null, null, false );
while (re.hasNextElement()) {
    int i = re.nextRecordId();
    System.out.println("i : "+i);
    _recordByteArr =  rs.getRecord(i);
    // ...
}

A: When you store records in RMS, it automatically creates a new ID for each the record getting store. This ID remains unique for each record. Suppose you have added 10 Records. Now if you delete 5th Records and add a new Record to RMS then this newly added record will get ID = 11.
While you are fetching the records using getRecords(int recNumber) method, when the recNumber value will be 5, it will return the Exception as InvalidRecordIDException as the 5th record is deleted.
I have created an RMS Library class. There is a method called getRecords() which is going to return the String Array as the records. You can use that String array to fetch the record you are looking for. It will be easy for you.


text:
Q: Autodesk Forge Error trying to access the API online I have a problem loading a 3D model on an online server, the error shown is related to accessing the Forge API, locally works smoothly however when mounted on the server or a website is made marks the following error "Failed to load resource: the server responded with a status of 404 (Not Found)", then "onDocumentLoadFailure() - errorCode:7".
As I comment, what I find stranger is that, locally, it works. Attached the segment of the code where it displays the error.
 function getAccessToken() {
    var xmlHttp = null;
    xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET", '/api/forge/toke', false); //Address not found
    xmlHttp.send(null);
    return xmlHttp.responseText;
}

Thank you very much in advance.

A: Are you sure the code you're running locally and the code you've deployed are really the same?
The getAccessToken function doesn't seem to be correct, for several reasons:

*

*First of all, there seems to be a typo in the URL - shouldn't it be /api/forge/token instead of /api/forge/toke?

*More importantly, the HTTP request is asynchronous, meaning that it cannot return the response immediately after calling xmlHttp.send(). You can find more details about the usage of XMLHttpRequest in https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest.

*And finally, assuming that the function is passed to Autodesk.Viewing.Initializer options, it should return the token using a callback parameter passed to it (as shown in https://forge.autodesk.com/en/docs/viewer/v7/developers_guide/viewer_basics/initialization/#example).

With that, your getAccessToken should probably look more like this (using the more modern fetch and async/await):
async function getAccessToken(callback) {
  const resp = await fetch('/api/forge/token');
  const json = await resp.json();
  callback(json.access_token, json.expires_in);
}

A: I've already found the issue. When I make the deploy I have to change the url where the request is made for the public or the name of the domain. For example: mywebsite.com/aplication-name/api/forge/token.


text:
Q: How to suppress display of escape sequences in diff When I run git diff to see what was changed in a modified file, diff displays many highlighted escape sequences. For example:
ESC[1mindex a7671ab..c228e2c 100644ESC[m
ESC[1m--- a/core/bp-nav-horizontal.phpESC[m
ESC[1m+++ b/core/bp-nav-horizontal.phpESC[m
ESC[36m@@ -77,7 +77,7 @@ESC[m
 ESC[m

ESC[m

ESC[m

How can I suppress these ESC[xxx characters. They make it very hard to read the text.
Amended 15 Aug 2014
This is not really about git diff. Displays of git log also show the ESC... characters. This seems like a configuration problem, but I don't know where it is. Where should I look?

A: You might have set color.ui=always (or auto and the terminal detection does not work). You can turn it off with never (if it is always try auto first).
You can configure all commands with config.ui or specific for git-diff with color.diff.
git config --global color.ui never

Use
git config --local -l
git config --global -l
git config --system -l

To list the current settings for the project, user and machine. To switch it temporarily on/off you can use the --color=always argument at each command. For example:
git log --color=never

See also: http://git-scm.com/book/en/Customizing-Git-Git-Configuration

A: The problem is with the pager used by GIT to print diffs and logs. Adding -R to the configuration for less solved the problem for me. I used
git config --global core.pager "less -R"

A: Git 2.14.x/2.15 (Q3 2017) will finally respect git config color.ui never.
See commit 11b087a, commit 18fb7ff, commit d75dfb1, commit d8b6868, commit 136c8c8, commit ab7ded3, commit 29ef53c, commit aa8a5d1, commit 18a2565, commit bf285ae, commit 4a68e36, commit 51331aa, commit 097b681, commit 5d3d068, commit 2eda010 (13 Jul 2017) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 15595ce, 11 Aug 2017)

"%C(color name)" in the pretty print format always produced ANSI
  color escape codes, which was an early design mistake.
  They now honor the configuration (e.g. "color.ui = never") and also tty-ness
  of the output medium.

A: I am on a system that does not have 'less' installed by default.
I use:

*

*git config --global core.pager "/usr/bin/more -v"

You could also choose:

*

*git config --system core.pager "/usr/bin/more -v"

The key point is that it is not 'git', but the (default) configuration of the pager you use.


text:
Q: How does SAML work in relation to an application that is not a service provider? So I'm struggling a bit with the basics of the flow of SAML.  Here's the scenario I find confusing.
I have a java web application.  The user is logged in.  I know they want to order cookies from a 3rd party because they've clicked on the "I want chocolate chip cookies" link.  I also know that "Mrs. Pillsbury Cookies Co." is a "Service Provider" because she sent me her meta-data and I've registered her with my Gluu Server (IdP).  I've also sent her my IdP meta-data so we've done the whole hand-shaking thing.
My question is...how do I now send the SAMLResponse to Mrs. Pillsbury?  She's given me a SOAP endpoint that is waiting for a SAMLResponse.  How do I tell my Java application to get some XML from my gluu server as a SAMLReponse that I can then pass to the Pillsbury SOAP endpoint?  That's the part where I'm stuck...I don't know how to get a response to forward.  I can see in the metadata that there are lots of SSO endpoints
    <SingleSignOnService Binding="urn:mace:shibboleth:2.0:profiles:AuthnRequest" Location="https://idp.myjavaapp.com/idp/profile/SAML2/Unsolicited/SSO"/>
    <SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="https://idp.myjavaapp.com/idp/profile/SAML2/POST/SSO"/>
    <SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST-SimpleSign" Location="https://idp.myjavaapp.com/idp/profile/SAML2/POST-SimpleSign/SSO

Am I supposed to hit one of those SSO endpoints and it'll generate a response that I can then forward on to Pillsbury?  Can one of you SAML experts out there get me straigtened out?  Thanks in advance.

A: There are a few ways SAML Requests/Responses can be generated.
IdP initiated:
This is a SAML Response generated w/o a SAML request. This requires the user to login/be logged into the idP and the idP will generate a SAML Response based off the SP setup in the idp.
SP initiated:
This is usually an HTTP Redirect but can be a POST as well. This is a SAML Request Redirect/POST that gets sent to the idP based of some link or button on the SP's website.

A: As I understand it you have the following relationship:
Your App
        \
         3rd Party ordering
        /
IdP Server

Your app needs to make a request to the 3rd party, but also need it to authenticate against the IdP. Yes?
Normally the process works such that the 3rd party requests the token itself. Your app shouldn't have the token intended for the 3rd party -- it should only have the token for its own app.
Usually you send whatever your app-specific request is to the 3rd party first. When they receive that bit of information they hold onto it and then make a SP-Initiated authentication request to your IdP. They will attach a bit of information as part of the auth request called relay state. This bit of information is used to reconstitute the session after the IdP responds.
Once the IdP receives the request it does whatever it needs to do to authenticate the user, and sends the token back to the 3rd party. As part of that response they also send the relay state. The 3rd party then verifies the token and sets the session as necessary, then reads the relay state and sets whatever internal state is necessary to continue the order.

A: You're on the right track. As the previous answers have explained, it can be done one of two ways: the SP site (Pillsbury) sends you an authentication request, or you can direct your IDP/Gluu server to send an SAML message to the SP without them prompting: "unsolicited".
In the case of the first "SP-Initiated", you just create a link to the SP site for the user's browser to follow. The user's browser hits the SP site, the SP site realizes that it needs to authenticate the user: so it creates a SAML Authentication Request to your IDP endpoint, directing the user's browser there.  Then your IDP server will respond according to the metadata/relationship that you've set up with the SP site. Just as one of the other answers explained, this Authentication Request can include a RelayState parameter which will be sent back to the SP to tell them where to send the user after the SAML message had been consumed & validated.  I haven't used Gluu but I believe the SP would use the second endpoint you showed in your question to do this.
In the case of the second "IDP-initiated", you need to direct the user's browser to one of the Gluu server endpoints to generate a SAML assertion, which will be POST'd back to the SP site without the SP site's prompting. This one is less used because every time the user is directed to the SP site from your site, they will be forced through the AuthN process among other reasons.  I believe this is the first listed endpoint that you showed in your question.
Here's a really good explanation of IDP-initiated from Shibboleth, that should help clear this up for you: https://wiki.shibboleth.net/confluence/display/SHIB2/IdPUnsolicitedSSO
Best of luck!


text:
Q: if condition on array if i have
int win[][] ={{1,2,3},{4,5,6},{7,8,9},{1,4,7},{2,5,8},{3,6,9},{1,5,9},{3,5,7}};

Can I put condition in this way?
if(((win[0][0]) && (win[0][1]) && (win[0][2]))||

            ((win[1][0]) && (win[1][1]) && (win[1][2]))||

            ((win[2][0]) && (win[2][1]) && (win[2][2]))||

            ((win[3][0]) && (win[3][1]) && (win[3][2]))||

            ((win[4][0]) && (win[4][1]) && (win[4][2]))||

            ((win[5][0]) && (win[5][1]) && (win[5][2]))||

            ((win[6][0]) && (win[6][1]) && (win[6][2]))||

            ((win[7][0]) && (win[7][1]) && (win[7][2]))||

            ((win[8][0]) && (win[8][1]) && win[8][2])))

A: Your array is 8x3, means last element will be win[7][2]. So calling win[8][0] will throw an ArrayIndexOutOfBounds exception. If you correct this error, your code will work. Hope this helps.

A: For a clearer version of this, why not try:
for(int i = 0; i < 8; i++) {
    if(win[i][0] && win[i][1] && win[i][2]) {
        doStuff();
        break;
    }
}

A: If your aim is completely confuse the reader - you can


text:
Q: Debugging a System.IO.Package out that won't open in Excel, possibly content_type.xml issue? I'm trying to create a 2007+ Excel document (.xlsx), using nothing but VB.net and .net4.0 built-in classes. So I can't use any third party libraries, including Open XML SDK. The code already works fine for basic workbooks, multiple sheets, styles, etc. The resulting files open fine in Excel and calc etc.
Now I am trying to add pivotTables. They are a bit weird, as they are spread out in multiple files. I have created the Cache and Table in their proper "folders", added the pointer from workbook to the cache and the various related _rels entries... everything seems OK but Excel always reports "... found unreadable content in..."
The only obvious issue I can see is that the content_types.xml file in the resulting Package does not have an Override for the pivotTable. It does have one for the Cache, which I do not do in code, so I'm assuming Packaging has noticed the Cache and added a line here. I'm not clear on why the pivotTable didn't show up.
So looking for experts in Packaging that might point me in the right direction: is a missing line in content_types fatal to opening the file, and if so, how can I force the pivotTable to appear?


text:
Q: Pandas Resampling error: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex When using pandas' resample function on a DataFrame in order to convert tick data to OHLCV, a resampling error is encountered.
How should we solve the error?

# Resample data into 30min bins
bars = data.Price.resample('30min', how='ohlc')
volumes = data.Volume.resample('30min', how='sum')

This gives the error:
TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Int64Index'

A: Convert the integer timestamps in the index to a DatetimeIndex:
data.index = pd.to_datetime(data.index, unit='s')

This interprets the integers as seconds since the Epoch.

For example, given
data = pd.DataFrame(
    {'Timestamp':[1313331280, 1313334917, 1313334917, 1313340309, 1313340309],
     'Price': [10.4]*3 + [10.5]*2, 'Volume': [0.779, 0.101, 0.316, 0.150, 1.8]})
data = data.set_index(['Timestamp'])
#             Price  Volume
# Timestamp
# 1313331280   10.4   0.779
# 1313334917   10.4   0.101
# 1313334917   10.4   0.316
# 1313340309   10.5   0.150
# 1313340309   10.5   1.800

data.index = pd.to_datetime(data.index, unit='s')

yields
                     Price  Volume
2011-08-14 14:14:40   10.4   0.779
2011-08-14 15:15:17   10.4   0.101
2011-08-14 15:15:17   10.4   0.316
2011-08-14 16:45:09   10.5   0.150
2011-08-14 16:45:09   10.5   1.800

Then
ticks = data.ix[:, ['Price', 'Volume']]
bars = ticks.Price.resample('30min').ohlc()
volumes = ticks.Volume.resample('30min').sum()

can be computed:
In [368]: bars
Out[368]:
                     open  high   low  close
2011-08-14 14:00:00  10.4  10.4  10.4   10.4
2011-08-14 14:30:00   NaN   NaN   NaN    NaN
2011-08-14 15:00:00  10.4  10.4  10.4   10.4
2011-08-14 15:30:00   NaN   NaN   NaN    NaN
2011-08-14 16:00:00   NaN   NaN   NaN    NaN
2011-08-14 16:30:00  10.5  10.5  10.5   10.5

In [369]: volumes
Out[369]:
2011-08-14 14:00:00    0.779
2011-08-14 14:30:00      NaN
2011-08-14 15:00:00    0.417
2011-08-14 15:30:00      NaN
2011-08-14 16:00:00      NaN
2011-08-14 16:30:00    1.950
Freq: 30T, Name: Volume, dtype: float64

A: Because it is designed for time-series data, as the error says, resample() works only if the index is datetime, timedelta or period. The following are a few common ways this error may show up.
However, you can also use the on= parameter to use a column as grouper, without having a datetime index.
df['Timestamp'] = pd.to_datetime(df['Timestamp'], unit='s')
bars = df.resample('30min', on='Timestamp')['Price'].ohlc()
volumes = df.resample('30min', on='Timestamp')['Volume'].sum()

If you have a MultiIndex dataframe where one of the index is datetime, then you can use level= to select that level as the grouper.
volumes = df.resample('30min', level='Timestamp')['Volume'].sum()

You can also use resample.agg to pass multiple methods.
resampled = df.resample('30min', on='Timestamp').agg({'Price': 'ohlc', 'Volume': 'sum'})


text:
Q: Deployment failure: Failed opening required '/var/app/ondeck/vendor/autoload.php' I've come across a problem that I really don't understand. I've developed a local composer package for my Laravel app (based on an existing one that didn't do exactly what I needed it to), and now I can no longer successfully deploy my app to my AWS Elastic Beanstalk instance.
I believe my new local composer package was created correctly: I took the original composer package, moved it to a new folder called "packages" in my Laravel app root. I added a repositories entry to my composer.json that pointed to it:
"repositories": [
    {
        "type": "path",
        "url": "packages/konsulting/justgiving-api-sdk"
    }
]

I then ran composer require konsulting/justgiving-api-sdk @dev and the local package was installed successfully. It works locally with no issues.
But now deploy to EB, I get the following error:

Activity execution failed, because: PHP Warning:
  require(/var/app/ondeck/vendor/autoload.php): failed to open stream:
  No such file or directory in /var/app/ondeck/artisan on line 18   PHP
  Fatal error:  require(): Failed opening required
  '/var/app/ondeck/vendor/autoload.php'
  (include_path='.:/usr/share/pear7:/usr/share/php') in
  /var/app/ondeck/artisan on line 18
  (ElasticBeanstalk::ExternalInvocationError)

What could be causing this issue? Literally nothing but this composer package (which works locally) is different.
I've tried composer dumpautoload and composer update.

A: The problem was simple, but confusing. I just needed to disable symlinking in repositories {}.
"options": {
    "symlink": false
}

Works fine now!


text:
Q: How to generate a random number, then display it on screen? Ok, im fairly new to android but i have managed to teach myself the basics, i am making an app where you press a button , and a new screen opens and it shows a randomly generated number, the only problem is i dont know how to generate and display the random number, i have been searching the web for ages and have only found little snippets of information , that dosent really make sense to me. :/
If someone could help me , or even give me just a little bit of info that should guide me in the right direction it would be great
EDIT: (for the comment below)
    super.onCreate(savedInstanceState);
    TextView tv = new TextView(this);
    tv.setText("Random Number : " + Math.random());
    int random = (int)Math.ceil(Math.random()*100);
    setContentView(tv);

Thats the code i have , where have i gone wrong ^^^^ :/

A: Android's documentation is excellent. Here's a hello world app:
http://developer.android.com/guide/tutorials/hello-world.html
Just change
tv.setText("Hello, Android");

to
tv.setText("Random Number: " + Math.random());

and make sure to import the Math library (if you're using eclipse, hit Ctrl+Shift+O).

A: below code return a value in Integer:-
    public static int randomBox() {

    Random rand = new Random();
    int pickedNumber = rand.nextInt(100);
    return pickedNumber;

}

A: Random rand = new Random();
String randomInt = list.get(rand.nextInt(list.size()));

it may be help for you

A:     Random r = new Random();

    StringBuffer temp = new StringBuffer("Random numbers:");
    for (int i = 0; i < 10; i++) {
        int i1 = r.nextInt(100 - 0) + 0;
        temp.append(String.valueOf(i1));
        temp.append(String.valueOf(" "));
    }
    return temp.toString();

A: Actually, you could easily use :
yourVariable = Math.random();

Should work in Android. Gives you a number between 0 and 1. Then you give yourVariable to a TextView with the method .setText(yourVariable) for instance...

A: Here is your documentation for Random. Beyond that I'm not sure if you want to launch an Activity or update a TextView or what have you. However, I strongly recommend reading the documentation for Activity as well as common tasks in android and User Interface. These should help you understand what you are trying to do.

A: int number = (new Random().nextInt(100));

a random number will be assigned to variable number, each time it is used

A: If you are willing to devloper your own algorithms to generate random number, pick any algo and implement in any language of preference. https://en.wikipedia.org/wiki/List_of_random_number_generators

A: Different way, but simple:)
    Calendar c = Calendar.getInstance();
    final int seconds = c.get(Calendar.SECOND);

    Random r = new Random();
    final int n = r.nextInt(80 - 65) + 65;

    Toast.makeText(getApplicationContext(), ""+ n + seconds, Toast.LENGTH_SHORT).show();

A:         Random r = new Random();
        rendomNumber = r.nextInt(80- 65) + 65;
        System.out.print(""+rendomNumber )


text:
Q: .net clear IBM mq programatically Is there anyway to clear the IBM Queue programatically? I want to clear all messages for some queues at a certain time everyday.

A: You can write a simple program to consume all messages on the queue.  If the IPPROCS and OPPROCS are both zero then you can write a program to issue the PCF ClearQ command or the runmqsc ClearQ command.  I've written about how to do it and so have other MQ users.  Try doing an internet search.

A: you can find some good options for your question here => Automatically clear messages from queue in IBM MQ
the easiest way would be to schedule the 'amqsget' sample program and just consume messages from queue and don't store them on disk (it's called a destructive MQGET).


text:
Q: Função Javascript não executa PageMethod Estou chamando um PageMethod em uma função Javascript, porém ele passa direto para o final não entrando na minha função C#. Segue o código abaixo:

<form name="frm" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True">
    </asp:ScriptManager>

            CPF/CNPJ:

                <asp:TextBox ID="CPF" runat="server" onblur='return valida();' MaxLength="14" Width="130px">

                <asp:Button ID="btnEnviar" runat="server" Text="Enviar" CssClass="btn btn-default" OnClick="btnEnviar_Click" OnClientClick="enviar();" />

</form>

[WebMethod]
    [ScriptMethod]
    public static string VerificaCaixa(string cart)
    {
        CPesquisa pesquisa = new CPesquisa();

        string parametros = "";
        parametros = pesquisa.VerificaCaixa(cart);

        return parametros;
    }

A: Na pagina do MSDN você consegue um exemplo.
<asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true">

</asp:ScriptManager>

Seu método tem que conter [WebMethod] para ficar exposto.
No arquivo myPageMethods.js, você faria algo assim.
function example(){
    myPageMethods.method();
}

Caso de algum problema, você pode consumir seu metodo via ajax tambem.
function method(){
    $.ajax({
        type: "POST",
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        url: "myPage.aspx/metodo",
        data:JSON.stringify({}), // parametros de entrada do metodo
        success: function (dt) { alert(dt);}, //sucesso
        error: function () { alert('error'); } // error
    });
}


text:
Q: Downgradind from rails 3.1 to 3.0.9 For reasons of compatibility with another project i'd like to downgrade rails 3.1 to 3.0.9 but i'm scared to lose some functionality! At the same time i would change the adapter of migration.yml from sqlite3 to mysql.
Right now is the standard one:
development:
 adapter: sqlite3
 database: db/development.sqlite3

I would change it in something like:
development:
 adapter: mysql
 encoding: utf8
 database: myapp_dev
 host: localhost
 username: username
 password: pass

Any ideas?
Edit
I started working to a project with rails 3.1.0, then i downloaded and developed another project made using rails 3.0.9. Now when i came back to the first project, loading home page, i get back
undefined method `clear_active_connections!' for ActiveRecord::Base:Class

and if i type something like:
rake db:migrate

application claims one gem located in Gemefile.lock of the other application!

A: I believe that only changing the database.yml for mysql it works, but I do not know about the update, keep a backup and make tests before you make it through.


text:
Q: Integral of $\frac{x^\alpha}{(1 + x^2)^2}$ from 0 to $\infty$ using contour integration for $-1 < \alpha <3$ I have tried to evaluate $\int_0^\infty \dfrac{x^\alpha}{(x^2 + 1)^2}\ dx$ for $-1 < \alpha < 3$ using the keyhole contour, but am not sure about my working, especially in defining the analytic branch of log $z$ when we consider the function $f(z) = \dfrac{z^\alpha}{(z^2 + 1)^2}$ where $z^\alpha  = e^{\alpha\text{log}\ z}$. Below is my working:
Using the keyhole contour $K_{\varepsilon,M}$ and considering the complex function $\dfrac{z^\alpha}{(z^2 + 1)^2}$, we inspect the integral of the function over each part of the contour (namely $C_{\varepsilon},C_M, I_1$ and $I_2$) in the limit $\varepsilon \to 0,\ M \to \infty$. For $C_{\varepsilon}$, we have $|z^2 +1|$ to be the modulus of points lying on a circle of radius $\varepsilon^2$ centered at $z = 1$ and hence $|z^2 + 1| > 1/2$ for $\varepsilon$ small enough (e.g. $\varepsilon^2 < 1/2$). We thus have:
\begin{align*}
\int_{C_{\varepsilon}} \dfrac{z^\alpha}{(z^2 + 1)^2}\ dz \ll \pi\varepsilon\ \text{max}_{C_\varepsilon}\bigg|\dfrac{z^\alpha}{(z^2 + 1)^2}\bigg| \ll 4\pi\varepsilon^{\alpha + 1} \Rightarrow \lim_{\varepsilon \to 0}\int_{C_{\varepsilon}} \dfrac{z^\alpha}{(z^2 + 1)^2}\ dz = 0
\end{align*} For any $z \in C_M$, we have $|z^2 + 1| \geq |z^2| = M^2$ for $M$ big enough. We thus have:
\begin{align*}
\int_{C_M} \dfrac{z^\alpha}{(z^2 + 1)^2}\ dz \ll 2\pi M \ \text{max}_{C_M}\bigg|\dfrac{z^\alpha}{(z^2 + 1)^2}\bigg| \ll 2\pi M^{\alpha - 3} \Rightarrow \lim_{M \to \infty}\int_{C_M} \dfrac{z^\alpha}{(z^2 + 1)^2}\ dz = 0
\end{align*}
For $I_1$, we have $\begin{aligned} = \lim_{\varepsilon \to 0,\  M \to \infty}\int_{I_1}\dfrac{z^\alpha}{(z^2 + 1)^2}\ dz = \int_0^\infty \dfrac{x^\alpha}{(x^2 + 1)^2}\ dx \end{aligned}$. As for $I_2$, we have $z^\alpha = e^{\alpha(\text{ln}x + 2\pi i)} = x^{\alpha}e^{2\pi i\alpha}$, and hence we have $\begin{aligned} = \lim_{\varepsilon \to 0,\  M \to \infty}\int_{I_2}\dfrac{z^\alpha}{(z^2 + 1)^2}\ dz = -e^{2\pi i\alpha}\int_0^\infty \dfrac{x^\alpha}{(x^2 + 1)^2}\ dx \end{aligned}$. Then, by the Residue Theorem, we have:
\begin{align*}
\int_0^\infty \dfrac{x^\alpha}{(x^2 + 1)^2}\ dx &= \frac{2\pi i}{1 - e^{2\pi i\alpha}}\sum_k \text{Res}\bigg(\dfrac{z^\alpha}{(z^2 + 1)^2}; z_k\bigg) \\
&= \frac{2\pi i}{1 - e^{2\pi i\alpha}}\bigg(\lim_{z \to i} \frac{d}{dz}\bigg(\dfrac{z^\alpha}{(z + i)^2}\bigg) + \lim_{z \to -i} \frac{d}{dz}\bigg(\dfrac{z^\alpha}{(z - i)^2}\bigg)\bigg) \\
&= \frac{2\pi i}{1 - e^{2\pi i\alpha}}\bigg(\frac{\alpha -1}{4}i^{\alpha -3} + \frac{\alpha -1}{4}(-i)^{\alpha -3}\bigg) \\
&= \frac{\pi i(\alpha -1)\text{cos}(\pi(\alpha - 3)/2)}{1 - e^{2\pi i\alpha}}
\end{align*}
where the keyhole contour is given as !Keyhole Contour 1
Any help in correcting my working or giving hints or posting your solution is appreciated.

A: Complex Analysis Approach
Consider the function
$$f(z) = \frac{z^{\alpha}}{(z^2+1)^2}$$
Note that $z^{\alpha} = e^{\alpha \log(z)}$ and choose the branch cut on the imaginary axis where $$\log(z) = \log|z|+ i\theta ,  \,\,\,\theta \in (-3\pi/2,3\pi/2)$$
Consider the following contour
$$\int^{-r}_{-R}f(z) \,dz +\int^{R}_{r}f(z) \,dz+ \int_{C_R}f(z)\,dz+\int_{c_r}f(z)\,dz =2\pi i \mathrm{Res}(f,i)$$
As you showed the integrals on the semi-circles go to zero as $r \to 0, R \to \infty$ hence
$$\int^{0}_{-\infty}\frac{e^{\alpha(\log|x|+i\pi)}}{(x^2+1)^2}\,dx+\int_{0}^{\infty}\frac{e^{\alpha(\log|x|)}}{(x^2+1)^2}\,dx = 2\pi i \mathrm{Res}(f,i)$$
$$(1+e^{\alpha \pi i})\int_{0}^{\infty}\frac{x^{\alpha}}{(x^2+1)^2}\,dx = 2\pi i \mathrm{Res}(f,i)$$
Note that
$$\mathrm{Res}(f,i) = \lim_{z \to i}\frac{d}{dz} \frac{e^{\alpha \log(z)}}{(z+i)^2} = \lim_{z \to i} \frac{\alpha z^{\alpha-1}(z+i)-2z^{\alpha}}{(z+i)^3} = \frac{2e^{i\alpha \pi/2}(\alpha-1)}{-8 i }$$
$$\int_{0}^{\infty}\frac{x^{\alpha}}{(x^2+1)^2}\,dx=\frac{\pi  e^{i\alpha \pi/2}(1-\alpha)}{2(1+e^{\alpha \pi i}) } = \frac{\pi (1-\alpha)}{4\cos\left( \frac{\pi}{2}\alpha\right)}$$

Real Analysis Approach
$$\int_{0}^{\infty}\frac{x^{\alpha}}{(x^2+1)^2}\,dx$$
Let $x^2 = t$
\begin{align}\frac{1}{2}\int_{0}^{\infty}\frac{t^{(\alpha-1)/2}}{(t+1)^2}\,dt &= \frac{1}{2}\Gamma \left(\frac{\alpha +1}{2} \right)\Gamma \left(2-\frac{\alpha +1}{2}\right)
\tag{1}\\ & = \frac{(1-\alpha)}{4}\Gamma \left(\frac{\alpha +1}{2} \right)\Gamma \left(1-\frac{\alpha +1}{2}\right)
\tag{2}\\ & = \frac{\pi (1-\alpha)}{4 \sin\left((1-\alpha)\pi/2 \right)}
\tag{3}\\ & = \frac{\pi (1-\alpha)}{4\cos\left( \frac{\pi}{2}\alpha\right) }\tag{4}\end{align}

(1). $$\int^\infty_0 \frac{t^{x-1}}{(1+t)^{x+y}}\,dt = B(x,y)$$
 (2). $$\Gamma(x+1) = x \Gamma(x)$$
 (3). $$\Gamma(x) \Gamma(1-x) = \frac{\pi}{\sin(\pi x)}$$


text:
Q: Aligning multiple axes on MATLAB? I need to plot a bunch of unit vectors and histograms corresponding to both axes (as a simple way to visualize clustering).
This is what I want: http://imgur.com/SBO34t8.

*

*The axes for the histogram are aligned with the unit vector plot.

This is what I am getting: http://imgur.com/Q4hcPOy

*

*The axes are misaligned

=
x = randn(100,1);
y = randn(100,1);
data = [x y];

normData = rowfun(@(n) n./norm(n,2),table(data));

xData = normData{:,:}(:,1);
yData = normData{:,:}(:,2);

blankFigure([-1 1 -1 1]);  hold on;
cellfun(@(x,y) plot([0 x], [0 y],'LineWidth',3),num2cell(xData),num2cell(yData))

ax1 = gca;
ax1Pos = get(ax1,'Position');
ax2Pos = ax1Pos;
ax2Pos(2) = ax1Pos(2)-.05;
ax2 = axes('Position',ax2Pos);
edges = [-1:.1:1];
histogram(xData,edges,'Normalization','pdf','Orientation','vertical');
set(ax2,'XLim',get(ax1,'XLim'));
set(ax2,'YLim',[0 8]);
set(ax2,'Visible','off');

ax3Pos = ax1Pos;
ax3Pos(1) = ax1Pos(1)-.05;
ax3 = axes('Position',ax3Pos);
histogram(yData,edges,'Normalization','pdf','Orientation','horizontal')
set(ax3,'YLim',get(ax1,'YLim'));
set(ax3,'XLim',[0 8]);
set(ax3,'Visible','off')

set(ax1,'Visible','on');


text:
Q: How to delete node on AgensGraph? I try to delete node on agens graph and failed.
lee=# match (n:v{id:1}) delete n;
ERROR:  vertex 4 in "v" has edge(s)

How to delete node?

A: Add detach before delete token.
assam=# match (n:v{id:1}) detach delete n;
GRAPH WRITE (DELETE VERTEX 1, DELETE EDGE 1)


text:
Q: Teradata SQL query to find sum of fields with same column values I really stuck with one task.
I have a table like this
Departure | Arrival    | SUM
 AAA      | ZZZ        | 100
 ZZZ      | AAA        | 50
 AAA      | CCC        | 60

I want get the sum of the same routes and  condition here is that I should treat AAA-ZZZ and ZZZ-AAA route as one route. The route ZZZ-AAA it's just route back from the original destination.
I'm trying to obtain the result like this:
Departure | Arrival    | SUM
 AAA      | ZZZ        | 150
 AAA      | CCC        | 60

Any suggestions, ideas please on how can I write my sql query to achieve that ?
Regards,
Jack

A: If you need to preserve to order of columns (i.e. a,b but no b,a must return the existing combination) you must expand Gordon's solution and add an indicator for the original order.
SELECT
    -- MIN(flag) = 1 -> departure < arrival
    --           = 2 -> arrival > departure or both exist
   CASE WHEN Min(flag)=1 THEN #1 ELSE #2 END AS departure,
   CASE WHEN Min(flag)=2 THEN #1 ELSE #2 END AS arrival,
   Sum(sumcol)
FROM
 (
  SELECT
    Least(Departure, Arrival) AS #1,
    Greatest(Departure, Arrival) AS #2,
    sumcol, -- seems this is already result of an aggregation?
    CASE WHEN departure < arrival THEN 1 ELSE 2 END AS flag
  FROM nodupes
 ) t
GROUP BY #1,#2;

This could be further simplified without Derived Table, but then it's really hard to understand and it's the same Explain anyway.

A: Just use least() and greatest():
select least(Departure, Arrival) as Departure,
       greatest(Departure, Arrival) as Arrival,
       sum(al)
from t
group by least(Departure, Arrival),
         greatest(Departure, Arrival);


text:
Q: URLComponents adds cryptic characters when adding path I have a problem when adding a path to an URLComponents object. Please have a look at following code:
func urlWith(path: String, andParameters parameters: [String:String]) -> URL? {
        let urlString = "https://some.nice.url/path/to"

        guard var urlComponents = URLComponents(string: urlString) else {
            return nil
        }

        let optionalURLQueryItems = parameters.map {
            return URLQueryItem(name: $0, value: $1)
        }
        let queryItems = optionalURLQueryItems

        urlComponents.path += path

        urlComponents.queryItems = queryItems

        return urlComponents.url
    }

When I pass a (valid) String to this method for a path, for example "/somewhere", the url looks like this:
https://some.nice.url/path/to%E2%80%8B/somewhere

The weird thing is, when I change the appending path method to this:
urlComponents.path += "/somewhere"

The URL looks like this:
https://some.nice.url/path/to/somewhere

So the question is, why is URLComponents adding %E2%80%8B to the URL and how to solve this issue?
Any help is much appreciated!
UPDATE
After checking the answers and the comments, I copied over the whole method to blank playground. There it works as expected. I have no idea why it does not work in Xcode. Then I just restarted Xcode and guess what, it worked. So I took the advice with the paths as suggested and here we go. But the remaining question is: When I type everything letter by letter (url and path), why does it work in playground but not in Xcode? Why does a restart solve the issue?

A: You have a left-to-right mark at the start of your path parameter. It's either because it's being localized, or because you've copy-and-pasted it from somewhere that includes it.

A: I recommend to create the URL from the base URL and concatenate the path
func urlWith(path: String, andParameters parameters: [String:String]) -> URL? {
    let urlString = "https://some.nice.url"

    guard var urlComponents = URLComponents(string: urlString) else {
        return nil
    }
    let optionalURLQueryItems = parameters.map {
        return URLQueryItem(name: $0, value: $1)
    }
    let queryItems = optionalURLQueryItems
    urlComponents.path = "/path/to/" + (path.hasPrefix("/") ? String(path.dropFirst()) : path)
    urlComponents.queryItems = queryItems
    return urlComponents.url
}