text:
Q: If there is one perfect square in an arithmetic progression, then there are infinitely many Consider the following positive integers:
$$a,a+d,a+2d,\dots$$
Suppose there is a perfect square in the above list of numbers. Then prove that there are infinitely many perfect square in the above list. How can I do this?
At first I started in this way:
Let the $n$th term is perfect square. Therefore,
$$t_n=a+(n-1)d=m^2.$$
Then I think that I will put values at the position of $n$. But I failed to find anything from this level. Can somebody help me?

A: Let $n^2$ be the known square.
Then $n^2+kd=m^2$ is equivalent to $kd=(m-n)(m+n)$. You can take $m-n$ to be any multiple of $d$, and $k$ follows.

A: Note that $$(m+d)^2=m^2+(2m+d)\cdot d$$

A: Starting from where you left, suppose the $k$th term is a perfect square such that $$a_k = a_1 + (k-1)d = p^2$$
Now add $2pmd + m^2d^2 $ to both sides where $m$ is a natural number giving us, $$\Rightarrow a_1 + (k-1)d + 2pmd + m^2d^2 = p^2 + 2pmd + m^2d^2 $$ $$\Rightarrow a_1 + [(k-1)+2pm+m^2]d = (p+md)^2$$
The RHS is a perfect square, and the left side
is the $(k-1+2pm+m^2)$th term for infinitely many values of $m $. Hope it helps.

A: Suppose that given $a_n = a+n*d = x_n^2$ there is theoretically another value $a_n' = a+n'*d = x_n'^2$ where all numbers are whole.
Taking the difference between these number yields:
$$
a_n' - a_n = a_n'- a_n\\
(a+n'*d) - (a+n*d) = x_n'^2 - x_n^2\\
(n' - n)d = (x_n' - x_n)(x_n' + x_n)
$$
Setting the outer expressions equal to each other, and the inner expressions equal to each other yields:
$$x_n' - x_n = d
\\x_n' = d + x_n$$
and
$$n' - n = x_n'+x_n\\n' = n + x_n'+x_n\\n' = n + d + 2 x_n$$

Therefore: If $a_n = a + n*d = x_n^2$ is a square, you can use theses values to generate a new larger square within the sequence where: $a_n' = a + n'd = a + (n+d+2*x_n)*d$.  This will be: $x_n'^2 = (d+x_n)^2$.


text:
Q: Django date filter failing to execute right after midnight or 12am I have a django project that allows a user to only create 8 objects per day and its filtering using __day but it seems between oo:oo and 01:59 the programs is allowing users to create unlimited objects.
today = datetime.today()
day = today.day

task_limit_enabler = False
task_limit = MyRate.objects.filter(user = request.user, date_created__day = day).count()

    if task_limit < 8:
        task_limit_enabler = True

redpajama_set_name: RedPajamaStackExchange


text:
Q: Date Slicer to filter data from other table I created Date table to get Date. I used Date table(Date) as Slicer to filter data from other table where data exists. Applied relation between Date table and other table where data exists. When I used date(date table) slicer to filter data from other table it is showing empty data. When I have taken Date slicer from table where data exists it showing data.
slicer should filter data with date from Date table.


text:
Q: Sharing data from a VueJS component I have a VueJS address lookup component.
Vue.component('address-lookup',
{
    template: '#address-lookup-template',
    data: function()
    {
        return {
            address: {'name': '', 'town:': '', 'postcode': ''},
            errors: {'name': false, 'town': false, 'postcode': false},
            states: {'busy': false, 'found': false},
            result: {}
        }
    },
    methods:
    {
        findAddress: function(event)
        {
            if( typeof event === 'object' && typeof event.target === 'object' )
            {
                event.target.blur();
            }

            $.ajax(
            {
                context: this,
                url: '/lookup',
                data:
                {
                    'name':     this.address.name,
                    'town':     this.address.town,
                    'postcode': this.address.postcode
                },
                success: function(data)
                {
                    this.states.busy = false;
                    this.states.found = true;
                    this.address.name = data.name;
                    this.result = data;
                }
            });
        },
        reset: function()
        {
            this.states.found = false;
            this.result = {};
        }
    }
});

Inside my template I've then bound the result like so:
<p>{{ result.formatted_address }}</p>

There is some extra data returned within the result (like a twitter handle) that isn't part of the address lookup template, and occurs on a separate part of the form. For reasons relating to how my form is structured I can't include these inputs within the same template.
I found a way to bind those inputs, although it felt somewhat 'hacky'.
<input type="text" name="twitter" v-model="$refs.lookupResult._data.result.twitter">

That all works fine.
My problem is that the form is included as part of a larger template sometimes in the context of creating a new record, sometimes in the context of editing. When editing a record, the lookup component is removed (using an if server-side, so the template is no longer loaded at all) and when that happens I get this error.
$refs.lookupResult._data.result.twitter": TypeError: Cannot read property '_data' of undefined

This makes sense. lookupResult is defined when I include the template, and when editing I am removing this line:
<address-lookup v-ref:lookup-result></address-lookup>

I've worked around it by including a version of each extra input without the v-model attribute, again using a server-side if. But there are quite a few of these and it's getting a bit messy.
Is there a cleaner approach I could be using to better achieve this?

A: So I don't know the hierarchy of your layout, it isn't indicated above, but assuming that address-lookup component is a child of your parent, and you in fact need the results of address lookup in that parent, eg:
<parent-component> <!-- where you need the data -->
  <address-lookup></address-lookup> <!-- where you lookup the data -->
</parent-component>

then you can simply pass the data props, either top-down only (default) or bidirectionally by defining 'address' for example on your parent's vue data hook:
// parent's data() function
data = function () {
  return {
    address: {}
  }
}

// parent template, passed address with .sync modifier (to make it bi-directional)
<parent-component>
  <address-lookup :address.sync='address'></address-lookup>
</parent-component>

// have the props accepted in the address look up component
var addressComponent = Vue.extend({
  props: ['address']
})

Now in your $.ajax success function, simply set the props you need on this.address. Of course you can do this with all the props you need: errors, results, state etc. Even better, if you can nest them into a single key on the parent, you can pass the single key for the object containing all four elements instead of all four separately.


text:
Q: Committing every x rows in table insert I'm writing a huge number of rows (~20 million) to a table from a JDBC connection to a static Oracle 12c database. I want to commit every 10,000 rows to prevent rollback and so that I can effectively restart the insert command from the last commit if there is an error.
What is the most efficient (time and resources) way that I can do this using JDBC?
Note that this will be an INSERT INTO SELECT statement from a big underlying table join. As such, cursors will slow down the insert statement considerably - are they truly the best solution here?

A: A single insert into ... select ... in general would be the most efficient (if you system will handle it).
If you really want to split it up you could use a scheme such as
while <rows still need inserting>
    insert into x
    select from y where (y is not x) and rownum < 10000;
    commit

where (y is not in x) is a not in() , a NOT EXISTS() or other such mechanism on only select rows not yet inserted.


text:
Q: Y coordinate being rounded to tenth I'm having an issue where the Y coordinate in a UTM is being rounded to the nearest 10th, and I don't know why.
I have a SQL Server Database with a view that is using columns from a table in another database through a linked server.  This view has an extra SHAPE column in which I computer the POINT from the X and Y columns in table. I'm using this formula to create the Geometry,
geometry::STPointFromText('POINT(' + CAST(X_UTM_NAD83Z14_D AS VARCHAR(20))
                      + ' ' + CAST(Y_UTM_NAD83Z14_D AS VARCHAR(20)) + ')', 26914) AS SHAPE

The columns X_UTM_NAD83Z14_D and Y_UTM_NAD83Z14_D are float datatype
The problem was noticed when it was compared to original points and a temporary layer was made directly from the source table.  The X direction was fine, but the Y direction was being rounded to the nearest tenth and thus shifting all the points north or south a maximum of 5 meters.
Original Coordinate: 335688.2, 6067867.1
PointFromText Coordinate: 335688.2, 6067870.0
Could someone help me figure this out?  I don't understand where the error is coming from.

A: I am not sure why, but this behaviour is documented on the official documentation:
Cast may truncate your results:
From https://msdn.microsoft.com/en-us/library/ms187928.aspx:

Conversions to char, varchar, nchar, nvarchar, binary, and varbinary
  are truncated, except for the conversions shown in the following
  table.

The function STR is designed for converting float expressions: https://msdn.microsoft.com/en-us/library/ms189527.aspx
STR ( float_expression [ , length [ , decimal ] ] )

From that article, it seems there are other options as well. I did not test them.
http://www.connectsql.com/2011/04/normal-0-microsoftinternetexplorer4.html


text:
Q: Page Curl on iOS I look around for similar posts but didn't find a solution. I'm looking for a simple page turn animation (without finger tracking) like this: http://www.youtube.com/watch?v=_vOYvaNhSHw
Is it possible to create or license it?
Many thanks for your help.

A: Yes, that's possible.
Read the following blog tutorial.
http://oleb.net/blog/2010/06/app-store-safe-page-curl-animations/
http://blog.steventroughtonsmith.com/2010/02/apples-ibooks-dynamic-page-curl.html
http://wdnuon.blogspot.com/2010/05/implementing-ibooks-page-curling-using.html

A: This fragment of code do the trick:
[UIView beginAnimations:@"Flip" context:nil];
[UIView setAnimationDuration:1.0];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.base.view cache:YES];

[user.view removeFromSuperview];
[base.view addSubview:home.view];

[UIView commitAnimations];

In this example the "user" viewcontroller is removed, and the "home" viewcontroller is added, with a pageflip like transition

A: It's an old and closed question but if someone is looking for a working implementation look at this:
Newer:
iOS-PageCurl-OpenGL
Older:
XBPageCurl project

A: Use UIViewAnimationTransitionCurlDown. Example shown in this question:
curl down transition for adding an UIView to a superview

A: As I was looking for something similar I have found out that for some people (like me itself) UIPageViewController did the trick with transition style UIPageViewControllerTransitionStylePageCurl ideally. If you want to see what you can achieve using this component take a look at iBooks app and try to turn the page. Very simple to use, great effect.
Page cant be rotated programatically and by a pan gesture which gives very page rotation/turning like feel.


text:
Q: How to redirect the user to another page after login using JavaScript Fetch API? Using the following JavaScript code, I make a request to obtain the firebase token, and then a POST request to my FastAPI backend, using the JavaScript fetch() method, in order to login the user. Then, in the backend, as can be seen below, I check whether or not the token is valid, and if so, return a redirect (i.e., RedirectResponse). The problem is that the redirect in the browser does not work, and the previous page remains.
function loginGoogle() {
        var provider = new firebase.auth.GoogleAuthProvider();
        firebase.auth()
            //.currentUser.getToken(provider)
            .signInWithPopup(provider)
            .then((result) => {
                /** @type {firebase.auth.OAuthCredential} */
                var credential = result.credential;

                // This gives you a Google Access Token. You can use it to access the Google API.
                var token = credential.idToken;

                // The signed-in user info.
                var user = result.user;

                // ...
            })
            .catch((error) => {
                // Handle Errors here.
                var errorCode = error.code;
                var errorMessage = error.message;
                // The email of the user's account used.
                var email = error.email;
                // The firebase.auth.AuthCredential type that was used.
                var credential = error.credential;
                // ...

                });

        firebase.auth().currentUser.getIdToken(true).then(function(idToken) {
            console.log(idToken)

            const token = idToken;
            const headers = new Headers({
                    'x-auth-token': token
            });
            const request = new Request('http://localhost:8000/login', {
                    method: 'POST',
                    headers: headers
            });
            fetch(request)
            .then(response => response.json())
            .then(data => console.log(data))
            .catch(error => console.error(error));

        })

The endpoint in the backend that returns the login page that contains the HTML code with the button and the loginGoogle function:
@router.get("/entrar")
def login(request: Request):
    return templates.TemplateResponse("login.html", {"request": request})

I call this POST endpoint and then a redirect to /1 which is a GET route, and with status_code being 303, which is how @tiangolo specifies it in the doc to redirect from a POST to a GET route.
@router.post("/login")
async def login(x_auth_token: str = Header(None)):
    valid_token = auth.verify_id_token(x_auth_token)

    if valid_token:
        print("token validado")
        return RedirectResponse(url="/1", status_code=status.HTTP_303_SEE_OTHER)
    else:
        return {"msg": "Token no recibido"}

This is the GET endpoint to which the user should be redirected, but it doesn't:
@app.get("/1")
def get_landing(request: Request):
    return templates.TemplateResponse("landing.html", {"request": request})

Swagger screenshot of testing the /login endpoint:

A: The main "Problem" that I see that might cause this to not work is the fast that you're doing it form a Post request to a Get request.
After some search online I've stumble across this [BUG] RedirectResponse from a POST request route to GET request route if you'll read this bug you'll see they specify that sometimes you may need a 307 instead you can read about the 307 response here 307 Temporary Redirect.
According to this the following should help:
import starlette.status as status
from fastapi.responses import RedirectResponse

@router.post("/login")
async def login(x_auth_token: str = Header(None))
    # Implementation details ...
    return RedirectResponse('/1', status_code=status.HTTP_302_FOUND)

@app.get("/1")
def get_landing(request: Request):
    return templates.TemplateResponse("landing.html", {"request": request})

From what I've seen the solution here was to use status_code=status.HTTP_302_FOUND you can learn more about it here: What Is a 302 Status Code?
You can also refer to the following links for more:

*

*fastapi (starlette) RedirectResponse redirect to post instead get method

*How to do a Post/Redirect/Get (PRG) in FastAPI?

*[QUESTION] How to post/redirect/get

*RedirectResponse
According to @Chris in the comments, you also have the following:

*

*How to redirect the user back to the home page using FastAPI, after submitting an HTML form?

*FastAPI's RedirectResponse doesn't work as expected in Swagger UI

*How to send RedirectResponse from a POST to a GET route in FastAPI?

A: Option 1 - Returning RedirectResponse
When using fetch() to make an HTTP request to a server that responds with a RedirectResponse, the redirect response will be automatically followed on client side (as explained here), as the redirect mode is set to follow by default in fetch() method. This means that the user won't be redirected to the new URL, but rather fetch() will follow that redirect behind the scenes and return the response from the redirect URL. You might expected that setting redirect to manual instead would allow you to get the redirect URL (contained in the Location response header) and manually navigate to the new page, but this is not the case, as described here.
However, you could still use the default redirect value in the fetch() request, i.e., follow (no need to manually specify it, as it is already set by default—in the example below, it is manually defined only for clarity purposes), and then use Response.redirected to check whether or not the response is the result of a request that you made which was redirected. If so, you can use Response.url, which will return the "final URL obtained after any redirects", and using JavaScript's window.location.href, you can redirect the user to the target URL (i.e., the redirect page).
Instead of window.location.href, one can also use window.location.replace(). The difference from setting the href property value is that when using the location.replace() method, after navigating to the given URL, the current page will not be saved in session history—meaning the user won't be able to use the back button to navigate to it.
Working Example
app.py
from fastapi import FastAPI, Request, status, Depends
from fastapi.templating import Jinja2Templates
from fastapi.responses import RedirectResponse
from fastapi.security import OAuth2PasswordRequestForm

app = FastAPI()
templates = Jinja2Templates(directory='templates')

@app.get('/')
async def index(request: Request):
    return templates.TemplateResponse('index.html', {'request': request})

@app.post('/login')
async def login(data: OAuth2PasswordRequestForm = Depends()):
    # perform some validation, using data.username and data.password
    credentials_valid = True

    if credentials_valid:
        return RedirectResponse(url='/welcome',status_code=status.HTTP_302_FOUND)
    else:
        return 'Validation failed'

@app.get('/welcome')
async def welcome():
    return 'You have been successfully redirected'

templates/index.html
<!DOCTYPE html>

      <form id="myForm">
         Username:

         <input type="text" id="username" name="username" value="user@mail.com">

         Password:

         <input type="password" id="password" name="password" value="pa55w0rd">

         <input type="submit" value="Submit" class="submit">
      </form>

Option 2 - Returning JSON response containing the redirect URL
Instead of returning a RedirectResponse from the server, you could have the server returning a normal JSON response with the URL included in the JSON object. On client side, you could check whether the JSON object returned from the server—as a result of the fetch() request—includes the url key, and if so, retrieve its value and redirect the user to the target URL, using JavaScript's window.location.href or window.location.replace().
Alternatively, one could add the redirect URL to a custom response header on server side (see examples here and here on how to set a response header in FastAPI), and access it on client side, after posting the request using fetch(), as shown here (Note that if you were doing a cross-origin request, you would have to set the Access-Control-Expose-Headers response header on server side (see examples here and here, as well as FastAPI's CORSMiddleware documentation on how to use the expose_headers argument), indicating that your custom response header—that includes the redirect URL—should be made available to JS scripts running in the browser, as only the CORS-safelisted response headers are exposed by default).
Working Example
app.py
from fastapi import FastAPI, Request, status, Depends
from fastapi.templating import Jinja2Templates
from fastapi.security import OAuth2PasswordRequestForm

app = FastAPI()
templates = Jinja2Templates(directory='templates')

@app.get('/')
async def index(request: Request):
    return templates.TemplateResponse('index.html', {'request': request})

@app.post('/login')
async def login(data: OAuth2PasswordRequestForm = Depends()):
    # perform some validation, using data.username and data.password
    credentials_valid = True

    if credentials_valid:
        return {'url': '/welcome'}
    else:
        return 'Validation failed'

@app.get('/welcome')
async def welcome():
    return 'You have been successfully redirected'

templates/index.html
<!DOCTYPE html>

      <form id="myForm">
         Username:

         <input type="text" id="username" name="username" value="user@mail.com">

         Password:

         <input type="password" id="password" name="password" value="pa55w0rd">

         <input type="submit" value="Submit" class="submit">
      </form>

Option 3 - Using HTML <form> in the frontend
If using a fetch() request is not a requirement for your project, you could instead use a normal HTML <form> and have the user click on the submit button to send the POST request to the server. In this way, using a RedirectResponse on server side (as demonstrated in Option 1) would result in having the user on client side automatically be redirected to the target URL, without any further action.
Working examples can be found in this answer, as well as this answer and this answer.


text:
Q: CSS was ignored due to mime type mismatch I am working on client side web part using JavaScript and CSS for customization.
I have added custom css and JS into the page and I am getting the message on console of the browser i.e.
CSS was ignored due to mime type mismatch
I checked the paths of the CSS files and all of them are correct. I searched over the internet for the same issue and applied following paths, but none of them worked.

*

*Installed the Core update in SharePoint available here.

*Installed the Language Update Pack available here

*Checked the Static Content feature is installed in the machine

*Mime Type is available in IIS

*Checked the Registry for the CSS and it has proper file type mentioned i.e. text/css.
The above solutions did not work.
The interesting part is: when I am loading the same css from SharePoint Hive (15) it is loading properly.
Can someone please help me out for solving the issue.
Environment: SP2019 Windows Server 2019 Standard Evaluation
TIA.

A: for anyone facing this problem, the solution is to go to

*

*Open Server Manager

*Add roles and features Role-based or
feature-based installation

Click Web Server (IIS) -> Management Tools
-> check IIS 6 Management Compatibility


text:
Q: Liquibase: best way to check whether a table in a different database exists in  I have 2 databases: db 1 and db 2
I need to take different action on db 1 based on whether a table in db 2 exists or not, and I am using liquibase to record my action.
here is my solution so far
<preconditions onFail="CONTINUE">
    <sqlcheck expectedResult="1">
          IF EXISTS (SELECT 1 FROM DB2.INFORMATION_SCHEMA.TABLES
                  WHERE TABLE_NAME = 'MY_TABLE')
                  SELECT 1 ELSE SELECT 0
    </sqlCheck>
</precondition>

The problem is: This is mssql syntax, if I try to use a different db, I need to change to use a different syntax, so what is the best way to do such thing?

A: Have you tried <tableExists> precondition http://www.liquibase.org/documentation/preconditions.html?
Also you can implement any logic as <customPrecondition> in Java.


text:
Q: Continuous extension of analytic functions Is it possible to prove the following statement or is there a counter-example:
Let $H=\{y>0\}$ be the upper half plane in the complex plane. If $f$ is an analytic function on $H$ and its real part is continuously extendable on the closure of $H$, which is $\overline H$, then $f$ is continuously extendable on $\overline H$.

A: Here's the idea:
Let $\mathbb H$ denote the upper half plane.
Let $U=H\setminus i\cdot[0,1]$ and $f\colon U\to i\mathbb H$ given by the Riemann mapping theorem.
It should be not too difficult to write down $f$ explicitly. Via a suitable automorphism of $\mathbb H$, we may assume that that $f$ is "symmetric" and then one sees that $f^{-1}$ extends to the boundary.
This implies that $\Re f(z)\to 0$ if $z\to a\in\mathbb R$, but $\lim_{z\to0}f(z)$ does not exist.

Here's something more explicit:
$g(z)=iz+\frac iz$ maps $S^1\to[-2i,2i]$ and $i\mathbb R\cup\{\infty\}\to \mathbb R\cup\{\infty\}$.
For the regions it constitutes among others a biholomorphic map
$$-i\mathbb H\setminus \overline{ \mathbb D}\longrightarrow \mathbb H\setminus (0,2i]$$
that extends continuously to the boundary - but for the inverse the continuation to the boundary fails.
We find that the inverse
$$ \mathbb H\setminus (0,2i]\longrightarrow -i\mathbb H\setminus \overline{ \mathbb D}$$
is given by
$$ g^{-1}(z) = \frac{-iz+\sqrt{-z^2-4}}{2} $$
where we take the square root with positive real part (which exists because $z$ is neither real nor in $(0,2i]$).
If $a\in\mathbb R$ then $$\Re g^{-1}(z)= \frac{\Im z+\Re\sqrt{-z^2-4}}{2}\to 0 $$
as $z\to a$.
However, as $t\to 0^+$ we have
$$ g^{-1}((\pm1+i)t)=\frac{t\mp t+\sqrt{\pm2it^2-4}}{2} \to\pm i,$$
whence $f:=g^{-1}$ is a counter-example as asked for.

Remark: Taking the problem statement literally (I implicitly assumed above that $U$ should be a region and not just an open set), a simpler counterexample can be given:
Let $U=(-1,0)\times(0,i)\cup (0,1)\times(0,i)$, $I=(-1,1)$, $f(z)=0$ if $\Re z<0$ and $f(z)=i$ if $\Re(z)>0$.
EDIT: After reformulation of the question, this answer no longer applies.
(It is an example of

$U\subseteq \mathbb H$, $\mathbb R\subseteq \partial U$, $f\colon U\to \mathbb C$ analytic, $g\colon U\cup \mathbb R\to \mathbb R$ continuous, $g|_U=\Re f$ and there is no continuous extension of $f$ to $U\cup\mathbb R$.

whereas the edited problem statement asks

$f\colon \mathbb H\to \mathbb C$ analytic, $g\colon \mathbb H\cup \mathbb R\to \mathbb R$ continuous, $g|_{\mathbb H}=\Re f$. Is there always a continuous extension of $f$ to $\mathbb H\cup\mathbb R$?

)

A: Define
$$ g(z)= \int_0^{2\pi}\frac{1}{1-e^{-it}z}\,\mathrm dt$$
on the unit disk. It is obtained by computing the Cauchy integral to achieve $g(z)=i$ for $z\in S^1$ with positive imaginary part and $g(z)=0$ for $z\in S^1$ with negative imaginary part.
Tranfering this via a bihomomorphic map $\mathbb H\to \mathbb D$ to the upper half plane, i.e. letting
$$ f(z)=g\left(\frac{iz + 1}{z+i}\right)$$
then should do the trick.

A: A correct answer has not been given yet. Unfortunately I cannot take the bounty back. :(


text:
Q: Can I use localhost URL as notify_url in paypal IPN? Can I give my localhost url in paypal IPN to send the message back to notify and process it?
OR...
Do I need live server URL to process (I guess this is right) because paypal knows live url when sending the message, but it never knows localhost url to send message.
Can anyone please tell me, do I need live server url or can I use localhost because I am not sure.
If I need live URL, how can I debug and develop my functionality (to send mail etc) in visual studio?
Does anyone have a small example or some useful links??

A: You may try it locally. Use https://ngrok.com/ to access localhost from internet.
ngrok is a command line tool and ngrok 80 command will assign a domain name in the following format :
http://s1ab334.ngrok.com and the https:// version is also the same.
Now, you can use the url in ipn simulator.

A: No, notify_url must be directly accessible via the internet,  because PayPal will POST the data to it.
In addition, it must run on port 80 or 443. Other ports are not allowed.


text:
Q: RestAssured groovy.json.JsonException I am trying to create a test to validate the response of a JSON Post is as expected.
I am trying to test the POST of a JSON message body to a URL which is turn then sends a text message and if successful it sends a response that it was successful again in JSON format.
My test is as follows
public void simpleTest() {

        JSONObject jsonObj = new JSONObject();
        jsonObj.put("phoneNumber","353837986524");
        jsonObj.put("messageContent","test");

        given()
                .port(31111) // port number
                .contentType("application/json")
                .body(jsonObj.toString())
                .when()
                .post("/testing/services/text/send")
                .then()
                .assertThat()
                .body("message", equalTo("{\"resultMessage\":\"Message accepted\", \"messageID\":\"0123456\"}"));
    }

but i'm getting the following exception
groovy.json.JsonException: Lexing failed on line: 1, column: 1, while reading 'R', no possible valid JSON value or punctuation could be recognized.

    at groovy.json.JsonLexer.nextToken(JsonLexer.java:85)
    at groovy.json.JsonLexer$nextToken.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:117)
    at com.jayway.restassured.internal.path.json.ConfigurableJsonSlurper.parse(ConfigurableJsonSlurper.groovy:96)
    at com.jayway.restassured.internal.path.json.ConfigurableJsonSlurper$parse$0.callCurrent(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:52)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:154)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:166)
    at com.jayway.restassured.internal.path.json.ConfigurableJsonSlurper.parseText(ConfigurableJsonSlurper.groovy:82)
    at com.jayway.restassured.internal.path.json.ConfigurableJsonSlurper$parseText.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
    at com.jayway.restassured.internal.ContentParser.parse(ContentParser.groovy:41)
    at com.jayway.restassured.internal.ContentParser$parse.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:149)
    at com.jayway.restassured.internal.ResponseSpecificationImpl$HamcrestAssertionClosure.validate(ResponseSpecificationImpl.groovy:583)
    at com.jayway.restassured.internal.ResponseSpecificationImpl$HamcrestAssertionClosure$validate$1.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
    at com.jayway.restassured.internal.ResponseSpecificationImpl.validateResponseIfRequired(ResponseSpecificationImpl.groovy:760)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:210)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:59)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:52)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:154)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:166)
    at com.jayway.restassured.internal.ResponseSpecificationImpl.content(ResponseSpecificationImpl.groovy:251)
    at com.jayway.restassured.specification.ResponseSpecification$content$0.callCurrent(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:52)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:154)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:190)
    at com.jayway.restassured.internal.ResponseSpecificationImpl.body(ResponseSpecificationImpl.groovy:234)
    at com.jayway.restassured.internal.ValidatableResponseOptionsImpl.body(ValidatableResponseOptionsImpl.java:264)
    at ie.david.text.flow.Test1.simpleTest(NoNumberSpecifiedTest.java:22)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

Which is weird because the first character is not "R"
I originally didn't use JSONObject and had the code as
String myJson = "{\"phoneNumber\":\"353837986524\", \"messageContent\":\"test\", \"clientApp\":\"30711\", \"transactionId\":\"20100101-DL123-353875213464\"}";
But was still getting the same exception

A: Based on the error code, it looks like that your JSON is corrupt, use a JSON validator to check it. If not, it is likely a Restassured issue. What happens if you just use .body(jsonObj) instead of the .toString()? I think it will solve the issue, but I am not sure.


text:
Q: How do I use the nth-child selector with jquery's child selector? This works fine:

$("#element").find("> tr > td > i > a")

But I'm trying to use the nth-child selector to say that I want a specific numbered child. For example, I want:

$("#element").find("> tr > td > i > a:nth-child(3)")

I'm not getting any results. Does anyone have any ideas on how I could select all the nth numbered children? Thanks in advance!

A: Firstly, this unless there's a great need to do direct descendant (the >) selectors, I don't see the need of including them, you can appropriately shorten your CSS selector too:
//Select 3rd  tag, within the context of #element td
$('a:nth-child(3)', '#element td');
   //or
$('#element td a:nth-child(3)')

Fiddle: http://jsfiddle.net/KGWuK/
Although, currently your selector provided with the question will only work if your HTML structure is:

         One
         Two
         Three

Which isn't a very advisable style of markup. That's because the original selector is selecting  tags of those that a direct child of the

A: I would recommend not using find as its not needed:
$("#element > tr > td > i > a:nth-child(3)")

This will find the  tag located within the  tag located within the table cell within a table row located within the element.
JSFiddle

A: Seeing that you have only 1 a with no sibling, i guess you are for the fourth element of your stack.
There is a jQuery method for that : .eq() :
$("#element").find("> tr > td > i > a:eq(3)");

or faster :
$("#element").find("> tr > td > i > a").eq(3);


text:
Q: Why does compiling a swig binary only produce a `pyd` file when using cmake when manual commands also produce a `py` file? Building a swig module (C++ to Python) manually using the procedure in the docs produces two files, one pyd and one py:
/* File: example.h */
int fact(int n);

// example.c
#include "example.h"
#include <stdio.h>

int fact(int n) {
  if (n < 0) { /* This should probably return an error, but this is simpler */
    return 0;
  }
  if (n == 0) {
    return 1;
  } else {
    /* testing for overflow would be a good idea here */
    return n * fact(n-1);
  }
}

// example.i
/* File: example.i */
%module example

%{
#define SWIG_FILE_WITH_INIT
#include "example.h"
%}

/**
 * @brief compute n factorial
 * @param n number
 */
int fact(int n);

Then
D:\swigwin-4.0.2\swig.exe -python .\example.i

produces example_wrap.c and example.py. Users then use a setup.py for building the final binary, a pyd file.
However, I need to build my swig module using cmake within a larger project. Using the UseSWIG module:
set(Python_ROOT_DIR "C:/Miniconda3")
find_package(Python COMPONENTS Interpreter Development NumPy)
        message("Python_EXECUTABLE ${Python_EXECUTABLE}")

find_package(SWIG 4.0.0 REQUIRED
        COMPONENTS python
        )
include(UseSWIG)

swig_add_module(example python example.i example)

target_include_directories(example PUBLIC
        ${Python_INCLUDE_DIRS}
        ${CMAKE_CURRENT_SOURCE_DIR}
        )
target_link_libraries(example PUBLIC ${Python_LIBRARIES})

This procedure produces one single file called _example.pyd. So why does cmake only produce a pyd file while with manual commands you also get a py file?

A: It turns out that my problem had nothing to do with swig not generating the py file but with cmake not installing it.
A call like:
install(TARGETS Swiggity DESTINATION SwigOut)

Only installs the binary produced by swig, aka the pyd file. The py file is still burried somewhere in the binary tree.


text:
Q: С помощью regexp_substr получить число из строки Есть строки вида:
Time 555.55
Time .55
Time 55

Надо с помощью regexp_substr хочу получить подстроки в виде
555.55
.55
55

Пробую такое выражение [[:digit:]]*[\.][[:digit:]]*
Однако последний вариант не цепляется(цифра без точки)
Если пробую [[:digit:]]*[\.]?[[:digit:]]* то вообще ничего не получаю.
Что я делаю не так?
Пример запроса:
with n as (
select 'Time 555.55' s from dual
union all
select 'Time .55' from dual
union all
select 'Time 55' from dual
)
select s, regexp_substr(s, '[[:digit:]]*[\.]?[[:digit:]]*'),  regexp_substr(s, '[[:digit:]]*[\.][[:digit:]]*') from n;

A: В данном случае следует использовать квантификатор + вместо *, указывая обязательное наличие хотя бы одной цифры.
'[[:digit:]]*\.?[[:digit:]]+'


text:
Q: GNU makefile syntax for loop in windows I have a GNU makefile written for linux operating system. I want to compile it on windows but there are some syntax changes for windows. I have done some changes but I am getting an error on for loop syntax.
Make file code is already written and I have to modify it for running on windows OS. Original code is attached and the changes i made are also given
Original code:
This is the original code:
@for i in $(subdirs); do \ (cd $$i && $(MAKE) $@) || break; \ done

After changes:
# pass make directives to subdirectories
SHELL = sh
%:
    for f in $$(subdirs); \
    do \
      (cd $$i && $(MAKE) $@) || break; \
    done

# eof

I am getting the error on line 16 which is first line of for loop
GNUmakefile(16) : fatal error U1035: syntax error : expected ':' or '=' separator

A: I made certain changes after reading nmake syntax. Now the problem is resolved.
The %: is not needed and @for does not work. So we need to turn off echo using @echo off: and then for loop will work with simple 'for' keyword instead of @for.
Working code is here:
SHELL = sh
# %:
@echo off :
    for i in $(subdirs) ; \
    do \
    (cd $$i && $(MAKE) $@) || break; \
    done

# eof


text:
Q: Sky force reloaded planes So I have all but two planes. The ones I have are:

*

*Model 2004.

*Ambulance.

*???

*Enforcer.

*Iron clad.

*Swift justice.

*Limp berserker.

*Ace of spades.

*???

Anyone have any others and if so how did you get them? Was it random or was it in some level or by doing something specific?


text:
Q: The remote server returned an error: (500) Internal Server Error on website I have a problem with running website via http://datalan.aspone.cz/ where data in a red table were still not available and as result is returned error message below
"Error close
 The remote server returned an error: (500)
 Internal Server Error."
Also website is already running on a localhost and there is no trouble.
I don't know where I made mistake but I would greatly appreciate it if someone helps solve these case.
I attach the code below:
public List<Data> Generate()
    {
        List<Data> data = new List<Data>();

        WebRequest request = WebRequest.Create("http://192.168.1.100/st0.xml");

        request.Credentials = new System.Net.NetworkCredential("admin", "admin");

        WebResponse response;
        Stream ReceiveStream;
        XmlTextReader reader = null;

        try
        {
            response = request.GetResponse();
            ReceiveStream = response.GetResponseStream();
            reader = new XmlTextReader(ReceiveStream);
        }
        catch (WebException ex)
        {
            response = ex.Response;
            ReceiveStream = response.GetResponseStream();
        }

        List<Tuple<string, string, int>> values = new List<Tuple<string, string, int>>();

        while (reader.Read())
        {
            if (reader.NodeType == XmlNodeType.Element)
            {
                switch (reader.Name)
                {
                    case "ia0":
                        double temp = Convert.ToDouble(reader.ReadString()) / 10;
                        values.Add(new Tuple<string, string, int>(String.Format(temp.ToString() + " °C"), "Temperature", 0));
                        break;
                    case "ia1":
                        double vol = Convert.ToDouble(reader.ReadString()) / 10;
                        values.Add(new Tuple<string, string, int>(String.Format(vol.ToString() + "V"), "Voltage", 1));
                        break;
                    case "di0":
                        values.Add(new Tuple<string, string, int>(reader.ReadString(), "INPD0", 2));
                        break;
                    case "di1":
                        values.Add(new Tuple<string, string, int>(reader.ReadString(), "INPD1", 3));
                        break;
                    case "di2":
                        values.Add(new Tuple<string, string, int>(reader.ReadString(), "INPD2", 4));
                        break;
                    case "di3":
                        values.Add(new Tuple<string, string, int>(reader.ReadString(), "INPD3", 5));
                        break;
                    case "out0":
                        values.Add(new Tuple<string, string, int>(reader.ReadString(), "OUT0", 6));
                        break;
                    case "out1":
                        values.Add(new Tuple<string, string, int>(reader.ReadString(), "OUT1", 7));
                        break;
                    case "out2":
                        values.Add(new Tuple<string, string, int>(reader.ReadString(), "OUT2", 8));
                        break;
                    case "out3":
                        values.Add(new Tuple<string, string, int>(reader.ReadString(), "OUT3", 9));
                        break;
                }
            }
        }

        for (int i = 0; i < values.Count; i++)
        {
            for (int j = 0; j < values.Count; j++)
            {
                if (i == values[j].Item3)
                {
                    data.AddRange(new List<Data> { new Data { Type = values[j].Item2, Value = values[j].Item1 } });
                }
            }
        }

        return data;
    }

A: It most likely has something to do with this code:
WebRequest request = WebRequest.Create("http://192.168.1.100/st0.xml");

You are making a call to a local IP address and if it's on shared hosting especially, it probably won't like this request.

A: I already have solved these problem.
After finding a solution I edited code in Web.config by these steps:
<location path="." inheritInChildApplications="false">
<system.web>
...
...
...
</system.web>
</location>

In the next time it could help someone.


text:
Q: MySQL count group by I have 3 tables, orders(orders_id, date, ...), products (product_id, product_name, product_price) and order_products (product_id, orders_id, product_id, products_quantity) and I need to group the products so that they are displayed by product and total quantity per product to make it easier for the eshop manager to know how many items per product have been ordered.
I'm having a little bot of trouble thinking of the correct sql syntax, I keep bumping into group by issues and i'd like some help.
This is what I've done so far
select *, op.products_quantity as pquant, count(*) as `count`
from orders o
left join orders_products op on o.orders_id = op.orders_id
left join products p on op.products_id = p.products_id
group by op.orders_products_id
order by op.products_id desc;

A: Looking at what you have, you're counting orders, not summing the quantity of the orders..
So
if you had
orders
monday 5 potatoes
tuesday 2 carrots
wednesday 3 potatoes

You wanted
potatoes 8
carrots 2

in which case you'd want to do
select sum(quantity),item from orders group by item

I didnt quite see what the differende between orders_products and orders was.
Maybe a bit of sample data would help?

A: Select p.Product_name,sum(prodcuts_quantity) as OrderedQuantity from
Order_products op join
Products p on p.Product_id = op.product_id
group by p.Product_name

A: If you need Total quantity and total orders per product than you can do that in following way
SELECT p.*,op.total_order,op.total_quantity FROM PRODUCT LEFT JOIN (SELECT COUNT(*) AS total_order, SUM(quantity) AS total_quantity FROM orders_products GROUP BY product_id) AS op ON p.id = op.product_id

A: This should work, use SUM, not COUNT:
SELECT
    *,
    SUM(op.products_quantity)
FROM
    orders AS o
    LEFT JOIN orders_products AS op ON o.orders_id  = op.orders_id
    LEFT JOIN products AS p ON op.products_id = p.products_id
GROUP BY p.products_id
ORDER BY p.products_id  DESC


text: Q: What are the topics of string theory that are comprehensible with only a mathematical background on Manifolds and Algebraic Topology? What are the topics of string theory that are comprehensible with only a mathematical background on manifolds and algebraic topology? Also, I have read only the first four chapters in Peskin & Schroder. And I have studied QM.


text:
Q: DBMS_LOB.APPEND File is getting cut because of concatenation I have the below block. I want to replace that concatenation and also have a records from the cursor in new line.
For small data set it works,but when the number of rows returned by the cursor is 600+ it cuts the file. I think its because of conversion of CLOB to Varchar2 when || is used.
How do I resolve it?
DECLARE
CURSOR cur IS
    SELECT  ID, CA_ID, STATUS,S_DATE, E_DATE FROM TEST; -- Here I have a big query
    v_MESG                  CLOB := EMPTY_CLOB();
    v_Interim               CLOB := EMPTY_CLOB();
    v_col                   VARCHAR2(500);
    CRLF                    VARCHAR2(2) := CHR(13)||CHR(10);
    v_fileHandler           UTL_FILE.FILE_TYPE;
BEGIN
    v_col:= '"ID","CA_ID","Status","S_Date","E_Date"'||CRLF;

    dbms_lob.createtemporary(v_MESG, TRUE);

    FOR v_cur IN cur LOOP
        BEGIN
        v_Interim := NULL;
        v_Interim:= v_col||v_cur.ID||',"'||
                    v_cur.CA_ID||'","'||
                    v_cur.Status||'","'||
                    v_cur.S_Date||'","'||
                    v_cur.E_DATE||'"'||CRLF
            ;
        DBMS_LOB.APPEND(v_mesg, v_Interim);
        v_col := NULL;
        END;
    END LOOP;
     v_fileHandler := UTL_FILE.FOPEN('XML_PROCESS_TEST',v_file_name , 'w');
         UTL_FILE.PUT(v_fileHandler, v_MESG);
         UTL_FILE.FCLOSE(v_fileHandler);
END;


text:
Q: how can i eliminate whitespace between navbar and main background div? hoping you can help. It's been a long time since I've coded without frameworks and such so I am purposely using vanilla html and css as a refresher.
I have begun building a quick website prototype, and I cannot for the life of me figure out why there is whitespace underneath the navbar element and my background section, despite creating css rules specifically for a full viewport background. I want the background section to start directly after the navbar.
Note: In testing, it appears the styling issue is tied to the html and body element rules. I could set the color to match with my background section, but somehow I feel that might cause other problems later..or at least it feels like cheating. Is there another possible solution? Most importantly, WHY is this happening given the css rules I have set? Everything appears to be in order, and inspecting elements has not helped, unless I have overlooked something important.
I can get everything else functioning fine, but I prefer to build in chunks, so the example below will look messy.
Apologies for any sloppiness in my coding. I am primarily a graphic designer.
html, body {
  margin:0px;
  padding:0px;
  border:0px;
  background-color:white;
}

Full Codepen here:http://codepen.io/J_Davis/pen/RGLVPv
Thanks!

A: Add to your wrapper this props:
display: flex;
flex-direction: column;

It should look like this:
#wrapper {
  display: flex;
  flex-direction: column;
  margin:0px;
  padding:0px;
  border:0px;
}

Here you have it working
Happy new year!!!

A: You can also set the margin-top of class bigBG to -20px;
like this:
.bigBG {
  background:#FF5733;
  min-height:100vh;
  margin-top:-20px;
  padding:0px;
}

Happy coding!


text:
Q: BufferQueue has been abandoned: When playing video with TextureView Every time I pause my activity (actually Fragment) to go to another app, upon returning with onResume I try to resume the video playing but it does not play: I get a blank screen. Upon investigation, I see the following in the Logcat
E/BufferQueueProducer: [unnamed-23827-0] queueBuffer: BufferQueue has been abandoned
E/MediaPlayer: error (1, -38)
E/MediaPlayer: error (1, -38)
E/MediaPlayer: error (1, -38)
E/MediaPlayer: error (1, -38)
E/BufferQueueProducer: [unnamed-23827-0] connect(P): BufferQueue has been abandoned

Here is the code I call inside on resume
player.seekTo(mVideoSeekPosition);
player.start();

FYI: I have been trying to apply this answer to my case, but I can't: What can I do when the BufferQueue has been abandoned?
UPDATE
I struggled to go it alone, but I am still crashing. So I am posting the whole code for help
private void setupVideoPlayingSystem(View root) {
  textureView = (TextureView) root.findViewById(R.id.textureView);

  textureView.setSurfaceTextureListener(this);
}

@Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
  Log.d(TAG, "onSurfaceTextureAvailable");
  if (null == surface) {
    Log.d(TAG, "new surface");
    surface = new Surface(surfaceTexture);
    mediaPlayer = new MediaPlayer();
    mediaPlayer.setSurface(surface);
    mediaPlayer.setLooping(false);
  }

  /*

  outstandingVideoRequest is IOU for orentation change (verifed: onResume before onSurfaceTextureAvailable)
  but for cold startup, must check mVideoUrl
  */

  if (outstandingVideoRequest && null != mVideoUrl) {

    outstandingVideoRequest = false;

        playNewVideo(mVideoUrl);
  }

}

@Override

public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {

  Log.d(TAG, "onSurfaceTextureSizeChanged");

    }

@Override

    public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {

  Log.d(TAG, "onSurfaceTextureDestroyed");
  return false;//leave destruction for onDestroy

}

@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
        }

    private void playNewVideo(String url) {

      if (null == mediaPlayer || null == surface) {

        Log.d(TAG, "playNewVideo not ready");

            synchronized (outstandingVideoRequest) {

              Log.d(TAG, "playNewVideo outstandingVideoRequest");

               outstandingVideoRequest = true;
        }

      } else {

        try {

          mediaPlayer.reset();

          mediaPlayer.setDataSource(getContext(), Uri.parse(url));

          mediaPlayer.setLooping(false);

          mediaPlayer.prepareAsync();

          mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

            @Override

            public void onPrepared(MediaPlayer player) {

              Log.d(TAG, "onPrepared changeMediaPlayerDatasource");

              onReadyToPlay(player);
            }

          });

       } catch (Exception e) {//IOException && IllegalStateException

         Log.d(TAG, "textureview playNewVideo ERORR");

         e.printStackTrace();

       }

     }

    }

  private void resumeVideoUponReturningFromAnotherActivity() {

            if (null == mediaPlayer || null == surface) {

                Log.d(TAG, "resumeVideoUponReturningFromAnotherActivity outstandingVideoRequest");

                outstandingVideoRequest = true;

        } else {

//            playNewVideo(mVideoUrl);

                Log.d(TAG, "resumeVideoUponReturningFromAnotherActivity go NOW");

                mediaPlayer.setSurface(surface);

            onReadyToPlay(mediaPlayer);

            }

    }

    private void onReadyToPlay(MediaPlayer player) {

        //play video

        mProgressCircle.setVisibility(View.GONE);

            showVideoOverlayChildren();

        if (0 == mVideoSeekPosition) {

            Log.d(TAG, "onReadyToPlay start");

                player.start();

            } else {

            Log.d(TAG, "onReadyToPlay seek");

                player.seekTo(mVideoSeekPosition);

           player.start();

            }

        mHandler.postDelayed(new Runnable() {

                @Override

                public void run() {

                    Log.d(TAG, "postDelayed resumeVideo");

                hideVideoOverlayChildren();

                }

        }, Constant.BEFORE_VIDEO_OVERLAY_DISAPPEAR);

        }

        private void destroyMediaPlayer() {

            if (null != mediaPlayer) {//move to video todo

            mediaPlayer.stop();

                mediaPlayer.release();

            mediaPlayer = null;

            }

        if (null != surface) {

                surface.release();

                surface = null;

        }

    }

    private void pauseVideo() {

            if (null != mediaPlayer) {

                Log.d(TAG, "pause");

            mediaPlayer.pause();

                mVideoSeekPosition = mediaPlayer.getCurrentPosition();

            }

    }

        private void stopVideo(){

        if (null != mediaPlayer) {

                Log.d(TAG, "stop video");

                mediaPlayer.pause();

                mVideoSeekPosition = mediaPlayer.getCurrentPosition();

                mediaPlayer.stop();

            }

    }

@Override
    public void onResume() {

        super.onResume();

        Log.d(TAG, "onResume");

    mLocalBroadcastManager.registerReceiver(mVideoSelectionReceiver, mVideoSelectedIntentFilter);

    resumeVideoUponReturningFromAnotherActivity();

    }

A: I find setSurface(null) is useful.
If you use a TextureView to display something, when TextureView.SurfaceTextureListener callback onSurfaceTextureDestroyed was called, you must stop use SurfaceTexture/new Surface(SurfaceTexture) binded by camera2, MediaCodec or MediaPlayer.
Like this
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
   mediaPlayer.setDisplayer(null);
   return false;//do not return true if you reuse it.
}

A: I had the same problem when switched between activities and also had MediaPlayer(1971): Error (100,0). Solved it by adding these lines inside onSurfaceTextureDestroyed
    @Override
    public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        return true;
    }

A: It seems there is a bug in your code:
in SurfaceTextureDestroyed() you did not reset surface or mediaPlayer. When resume, neither mediaPlayer nor surface is null, so in resumeVideoUponReturningFromAnotherActivity() set the surface and call start to play, but surface already become invalid because of previous SurfaceTextureDestroyed. That's why you get error.
To fix it, you should reset surface in callback SurfaceTextureDestroyed. When resume, rebuild surface in callback SurfaceTextureAvailable, set it to mediaPlayer and call start to play. The codes go like this:
public void onResume() {
   if (mSurface == null) {
      mResumeRequested = true;
      return;
   }
   mMediaPlayer.start();
}

@Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
   mSurface = new Surface(surface);
   if (mMediaPlayer != null) {
      mMediaPlayer.setSurface(mSurface);
      if (mResumeRequested) {
         mMediaPlayer.start();
         mResumeRequested = false;
      }
   }
}

@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
   mSurface = null;
   return false;
}

And you do not have to reset media player at all. If you reset, you have to re-instantiate it and re-buffering, which causes delay, this harms user experience because no delaying pause/resume is more desired.


text:
Q: Get indices of elements that are greater than a threshold in 2D numpy array I have a 2D numpy array:
x = [[  1.92043482e-04   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   2.41005634e-03   0.00000000e+00
    7.19330120e-04   0.00000000e+00   0.00000000e+00   1.42886875e-04
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   9.79279411e-05   7.88888657e-04   0.00000000e+00
    0.00000000e+00   1.40425916e-01   0.00000000e+00   1.13955893e-02
    7.36868947e-03   3.67091988e-04   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   1.72037105e-03   1.72377961e-03
    0.00000000e+00   0.00000000e+00   1.19532061e-01   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   3.37249481e-04
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   1.75111492e-03   0.00000000e+00
    0.00000000e+00   1.12639313e-02]
 [  0.00000000e+00   0.00000000e+00   1.10271735e-04   5.98736562e-04
    6.77961628e-04   7.49569659e-04   0.00000000e+00   0.00000000e+00
    2.91697850e-03   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   3.30257021e-04   2.46629275e-04
    0.00000000e+00   1.87586441e-02   6.49103144e-04   0.00000000e+00
    1.19046355e-04   0.00000000e+00   0.00000000e+00   2.69499898e-03
    1.48525386e-02   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   1.18803119e-03
    3.93100829e-04   0.00000000e+00   3.76245304e-04   2.79537738e-02
    0.00000000e+00   1.20738457e-03   9.74669064e-06   7.18680093e-04
    1.61546793e-02   3.49360861e-04   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00]]

How do I get indices of the elements that are greater than 0.01?
Right now, I'm doing t = np.argmax(x, axis=1) to get the index of the maximum value from each and the result of it is: [21 35]. How do I achieve the above?

A: You can use np.argwhere to return the indices of all the entries in an array matching a boolean condition:
>>> x = np.array([[0,0.2,0.5],[0.05,0.01,0]])

>>> np.argwhere(x > 0.01)
array([[0, 1],
       [0, 2],
       [1, 0]])


text:
Q: A question on counting I'm having difficulty answering (Qb iii)
Question:
(a) Write an expression for the number of sets S which contain 10 elements, each of which is
an integer between 1 and 20.
A: There are ${20 \choose 10}$ ways of selecting 10 integers from 1 to 20 where repetition is not allowed and order doesn't matter. If we consider each of these ways a set then the number of set which contain 10 element, each of which is an integer between 1 and 20 is ${20 \choose 10}$.
(b) Let S be a set with the properties described in (a).
(i) How many ways are there to order the members of S?
A: There are 10! ways to order the members of S.
(ii) How many subsets of S have size two?
A: There are ${10 \choose 2}$ subsets of size 2.
(iii) For a non-empty subset X ⊆ S, let t(X) denote the sum of the members of X. Prove
that there must be distinct subsets A,B ⊆ S, each of size two, such that t(A) = t(B).
(Hint: what are the possible values of t(A) and t(B)?)
Where I am at so far
I realised the following:
Consider 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20.
I realised that if you pick any two number say 5 and 13 then
5 + 13 = 18,
6 + 12 = 18,
7 + 11 = 18 etc.
But that's really all I've realised.

A: Even more explicit hint... the smallest possible value of $t(A)$ would happen when the subset is $\{1,2\}$ since this is the set using the two smallest available elements while the largest possible value of $t(A)$ would happen when the subset is $\{19,20\}$ since this is the set using the two largest available elements.

 The possible outcomes of $t(A)$ are then $3,4,5,\dots,37,38,39$

You correctly noted however that there are $\binom{10}{2}=45$ distinct two-element subsets of $S$ however

 And if we compare the number of possible two-element subsets of $S$ to the number of possible values of $t(A)$ we see that one is larger than the other which means...

A: New proof:
Observe that {1, 2} will have the smallest sum which is 3 and {19, 20} will have the largest sum which is 39.
Now any 2-subset of S will be greater than or equal to 3 and less than or equal to 39. Since we have 45 2-subsets of S and only 37 possible sums they will be mapped to, by the Pigeonhole Principle there will be at least two subsets with the same sum.
End of proof.


text:
Q: What happens when a MySQL table gets REALLY big? I'm working on a project and I'm concerned about size limitations of a table.
If a table gets too big for the max file size of the OS. Windows is 2GB per file.
Does MySQL split the data from the table into two files?
I was looking at the data from my WAMP installation and right now each table is a single file:
user.frm and user.ibd (this one is the one storing all the data according to the file size)
Basically if I'm looking at data in the size of 10-50GB stored in one table can the MySQL database handle it?
EDIT: Also I'm eventually moving my project to a Linux server with the same file size limitations I'm assuming MySQL works the same way on Linux and Windows.

A: According to Limits on Table Size, the table size is limited by the maximum file size, but the maximum file size depends on the file system.
Make sure you put your data on a modern file system, such as NTFS, and you wont have any problems.


text:
Q: firebase addvalueeventlistener not being triggered in one device I'm having a problem with one specific device (my main device which is galaxy s7)
as described here :
Firebase addValueEventListener not being triggered
the addvalueeventlistener won't trigger and as suggested i checked if i have connection using this :
https://firebase.google.com/docs/database/android/offline-capabilities#section-connection-state
and i'm actually not connected
the problem is that one the developing device it's working great and on other it's not.
what am i missing here ?
this is the code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
localCountryDB = ((GlobalState) this.getApplication()).getCountry();
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference().child(localCountryDB);
FirebaseUser user = mAuth.getCurrentUser();
if (mAuth.getCurrentUser()!=null)
userID = user.getUid();

DatabaseReference connectedRef = FirebaseDatabase.getInstance().getReference(".info/connected");
connectedRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
boolean connected = snapshot.getValue(Boolean.class);
if (connected) {
System.out.println("connected");
} else {
System.out.println("not connected");
}
}

@Override
public void onCancelled(DatabaseError error) {
System.err.println("Listener was cancelled");
}
});

valueEventListener = myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
getUserData(dataSnapshot);
}

@Override
public void onCancelled(DatabaseError databaseError) {

String Hello;
Hello="a";
}
});

A: I found the problem
The problem is that :
mAuth.getCurrentUser()

actually returned a user, an old user which was already deleted from the authentication data so i had to
mAuth.signout()

once i did it the connection was "connected" again and the ValueEventListener triggers
The problem is that i don't know how to catch this bug since trigger doesn't fire.

A: Try this

*

*Add the internet permission to the manifest

*Set the firebase database security rules read to true


text:
Q: Storing CSV data into Dynamic paths using Athena Query (Start Query Execution) I am trying to store JSON data that has been dumped into an input S3 bucket and convert the file into CSV in another S3 output bucket location using Athena's Start Query Execution.

*

*I am using a large Query that would be inserted into a temp table (using INSERT INTO).

*That table is partitioned into year, month, day and hour.

*Using AWS Glue I was able to set up storage.location.template  for the query table  (See screen scrape)
s3://prod-cog-kahala-test-output/data/landing/olo/baja/year=${year}/month=${month}/day=${day}/hour=${hour}

*I am also using projection year, hour, month, and day using AWS Gue on this table. (See screen scrape)

This output patch is dynamically created based on the date and time when the event has fired. It will store CSV files from JSON that were created during that event time the Athena's query. The output path should look like the following screen scrape:

I am using python lambda to extract the event record's eventDate value and then using an Athena query, output the csv files to  the dynamic output path

Note: I have only been able to run this successfully using a static S3 path  but not a dynamic S3 path which is a requirement .

When I ingest/extract an input JSON file in the input S3 bucklet, I get the following error when Athena runs the query using dynamic S3 path:

(<class 'botocore.errorfactory.InvalidRequestException'>, InvalidRequestException("An error occurred (InvalidRequestException) when calling the StartQueryExecution operation: line 45:64: mismatched input '{'. Expecting: '*', <expression>, <identifier>"), <traceback object at 0x7fac83b93300>).

Please help me determine what I am doing that is incorrect. Thanks much

Here is the table property

Here is the lambda code:

def lambda_handler(event, context):
try:
    print('<< IN Handler >>')
    print(event)
    print("File size is", event['Records'][0]['s3']['object']['size'])
    if(event['Records'][0]['s3']['object']['size'] > 0):
        file_path = event['Records'][0]['s3']['object']['key']
        print('<<FILEPATH >>'+file_path)
        bucket_name = os.environ['BUCKETBAJA']
        file_name = file_path.split("/")[-1]
        print(file_name)
        #process the  input file time stamp to extrac tthe year,month,day
        parse_filename = file_name.split(today_year)
        #Get date and hour
        parse_date = event['Records'][0]['eventTime']
        #print(parse_date)
        dateStr = parse_date.split("-")
        print('<< PROCESS DATE >>'+dateStr[2])
        fyear= dateStr[0]
        fmonth= dateStr[1]
        fday =  dateStr[2].split("T")
        #print('REST OF STRING '+fday[1])
        parse_more = fday
        #print(parse_more)
        hour = fday[1].split(":")
        #print(hour)
        fhour = hour[0]
        fday = fday[0]
        print('<< DAY >>'+fday)
        print('<< HOUR >>'+fhour)
        print('<< MONTH >>'+fmonth)
        process_date = fyear+'-'+fmonth+'-'+fday
        start_date = fyear+'-'+fmonth+'-'+fday
        end_date = fyear+'-'+fmonth+'-'+fday
        output_prefix= "all_dates/year=/"+fyear+"/month="+fmonth+'/day='+fday+'/hour='+fhour
        print('<< OUT_PREFIX  >>'+output_prefix)
        clients3 = boto3.client('s3')
        result = clients3.list_objects(Bucket=bucket_name, Prefix=output_prefix )
        exists=False
        athena_out_path = 's3://'+bucket_name+'/all-dates/year='+fyear+'/month='+fmonth+'/day='+fday+'/hour='+fhour
        print('<<< INSIDE BAJA TABLE DUMP NEXT ...  >>>>')
        #list_tables = table_queries_v1
        if 'coldstone' in file_name:
            query = kahala_coldstone
            bucket_name = os.environ['BUCKETCOLDSTONE']
            athena_out_path = 's3://athena-'+bucket_name+'/all-dates/year='+fyear+'/month='+fmonth+'/day='+fday+'/hour='+fhour
        else:
            query = kahala_baja
            print('<<QUERY  >>')
            response = athena_client.start_query_execution(
                QueryString=query,
                QueryExecutionContext={
                  'Database': database
                },
                ResultConfiguration={
                    'OutputLocation': athena_out_path,
                }
            )

    else:
        print("Empty File, exiting")
except:
    print("Unknown Error")
    print(sys.exc_info())

Here is the Query code:

    """insert into olo_baja_insert_to_csv
    select cast(first_name as varchar) first_name,
    cast(contact_number as varchar) contact_number,
    cast(membership_number as varchar) membership_number,
    cast(olo_customer_id as varchar) olo_customer_id,
    cast(login_providers as varchar) login_providers,
    cast(external_reference as varchar) external_reference,
    cast(olo_email_address as varchar) olo_email_address,
    cast(last_name as varchar) last_name,
    cast(loyalty_scheme as varchar) loyalty_scheme,
    cast(product_id as varchar) product_id,
    cast(modifier_detail['modifierid'] as varchar) modifier_detail_modifier_id,
    cast(modifier_detail['description'] as varchar) modifier_detail_description,
    cast(modifier_detail['vendorspecificmodifierid'] as varchar) modifier_detail_vendor_specific_modifier_id,
    cast(modifier_detail['modifiers'] as varchar) modifier_detail_modifiers,
    cast(modifier_detail['modifierquantity'] as varchar)
modifier_detail_modifier_quantity,
    cast(modifier_detail['customfields'] as varchar)  modifier_detail_custom_fields,
    cast(modifier_quantity as varchar) modifier_quantity,
   cast(modifier_custom_fields as varchar) modifier_custom_fields,
    cast(delivery as varchar) delivery,
    cast(total as varchar) total,
    cast(subtotal as varchar) subtotal,
    cast(discount as varchar) discount,
    cast(tip as varchar) tip,
    cast(sales_tax as varchar) sales_tax,
    cast(customer_delivery as varchar) customer_delivery,
    cast(payment_amount as varchar) payment_amount,
    cast(payment_description as varchar) payment_description,
    cast(payment_type as varchar) payment_type,
    cast(location_lat as varchar) location_lat,
    cast(location_long as varchar) location_long,
    cast(location_name as varchar) location_name,
    cast(location_logo as varchar) location_logo,
    cast(ordering_provider_name as varchar) ordering_provider_name,
    cast(ordering_provider_slug as varchar) ordering_provider_slug,year,month,day, hour
    from(
    select cast(first_name as varchar) first_name,
    cast(contact_number as varchar) contact_number,
    cast(membership_number as varchar) membership_number,
    cast(olo_customer_id as varchar) olo_customer_id,
    cast(login_providers as varchar) login_providers,
    cast(external_reference as varchar) external_reference,
    cast(olo_email_address as varchar) olo_email_address,
    cast(last_name as varchar) last_name,
    cast(loyalty_scheme as varchar) loyalty_scheme,
    cast(product_id as varchar) product_id,
    cast(special_instructions as varchar) special_instructions,
    cast(quantity as varchar) quantity,
    cast(recipient_name as varchar) recipient_name,
    cast(custom_values as varchar) custom_values,
    cast(item_description as varchar) item_description,
    cast(item_selling_price as varchar) item_selling_price,
    cast(modifier['sellingprice'] as varchar) pre_modifier_selling_price,
    cast(modifier['modifierid'] as varchar) modifier_id,
    cast(modifier['description'] as varchar) modifier_description,
    cast(modifier['vendorspecificmodifierid'] as varchar) vendor_specific_modifierid,
    cast(modifier['modifiers'] as varchar) modifier_details,
    cast(modifier['modifierquantity'] as varchar) modifier_quantity,
    cast(modifier['customfields'] as varchar) modifier_custom_fields,
    cast(delivery as varchar),cast(total as varchar),cast(subtotal as varchar),
    cast(discount as varchar),cast(tip as varchar),cast(sales_tax as varvchar),cast(customer_delivery as varchar), cast(payment_amount as varchar), cast(payment_description as varchar),
    cast(payment_type as varchar),cast(location_lat as varchar),cast(location_long as varchar), cast(location_name as varchar),
    cast(location_logo as varchar),
    cast(ordering_provider_name as varchar), cast(ordering_provider_slug as varchar), year,month,day,hour
    from(
    select
    cast(json_extract(customer, '$.firstname') as varchar) as first_name,
    cast(json_extract(customer, '$.contactnumber') as varchar) as contact_number,
    cast(json_extract(customer, '$.membershipnumber') as varchar) as membership_number,
    cast(json_extract(customer, '$.customerid') as varchar) as olo_customer_id,
    cast(json_extract(customer, '$.loginproviders') as array<map<varchar,varchar>>) as login_providers,
    cast(json_extract(customer, '$.externalreference') as varchar) as external_reference,
    cast(json_extract(customer, '$.email') as varchar) as olo_email_address,
    cast(json_extract(customer, '$.lastname') as varchar) as last_name,
    cast(json_extract(customer, '$.loyaltyscheme') as varchar) as loyalty_scheme,
    try_cast(json_extract("item", '$.productid') as varchar) product_id,
    try_cast(json_extract("item", '$.specialinstructions') as varchar) special_instructions,
    try_cast(json_extract("item", '$.quantity') as varchar) quantity,
    try_cast(json_extract("item", '$.recipientname') as varchar) recipient_name,
    try_cast(json_extract("item", '$.customvalues') as varchar) custom_values,
    try_cast(json_extract("item", '$.description') as varchar) item_description,
    try_cast(json_extract("item", '$.sellingprice') as varchar) item_selling_price,
    cast(json_extract("item", '$.modifiers') as array<map<varchar,json>>) modifiers,
    cast(json_extract(totals, '$.delivery') as varchar) delivery,
    cast(json_extract(totals, '$.total') as varchar) total,
    cast(json_extract(totals, '$.subtotal') as varchar) subtotal,
    cast(json_extract(totals, '$.discount') as varchar) discount,
    cast(json_extract(totals, '$.tip') as varchar) tip,
    cast(json_extract(totals, '$.salestax') as varchar) sales_tax,
    cast(json_extract(totals, '$.customerdelivery') as varchar) customer_delivery,
    payment['amount'] payment_amount,
    payment['description'] payment_description,
    payment['type'] payment_type,
    cast(json_extract("location", '$.latitude') as varchar) location_lat,
    cast(json_extract("location", '$.longitude') as varchar) location_long,
    cast(json_extract("location", '$.name') as varchar) location_name,
    cast(json_extract("location", '$.logo') as varchar) location_logo,
    cast(json_extract("orderingprovider", '$.name') as varchar) ordering_provider_name,
    cast(json_extract("orderingprovider", '$.slug') as varchar) ordering_provider_slug,hour
    from sandbox_twilliams.olo_baja_raw_john_testing
    cross join unnest (payments, "items") as t (payment, item)
    --cross join unnest ("items") as t (item)
    --cross join unnest (payments) as t (payment)
    where year = {fyear}
    and month = {fmonth}
    and day = {fday}
    and hour = {fhour}
    ).format(year={fyear},month={fmonth},day={fday}, hour={fhour})
    CROSS JOIN UNNEST (modifiers) as t (modifier)
    )
    CROSS JOIN UNNEST (cast(modifier_details as array<map<varchar,json>>)) as t (modifier_detail)
    group by 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45;"""

A: There is a syntax error in your query, but you don't include the query in the question so it's hard to figure out what's going wrong. It looks like you print the query SQL in your logging so I suggest taking that SQL and running it manually in the Athena console and see if you can figure out from the error message what's wrong.
On another note, converting to CSV is best done through UNLOAD. Athena's query results are CSV, but Athena also writes a binary metadata file along with the CSV file, which can mess things up if you expect the output directory to only contain CSV data.

A: As I had commented to @Theo , It was an absolute mess attempting to get the insert into statement -  on that query  - functional. Some tweaks to the query had to be made and now the csv files are getting generated.  The following tweaks were:

This format() functions tatement was omitted from the query just before assigning its value to the Athena client for the Start Execute Query : query = kahala_coldstone.format(fyear=fyear,fmonth=fmonth,fday=fday,fhour=fhour)
Another reason  the query wasn't running was due to a {month} binding that
should have been {fmonth} (fmonth is a variable  used to store the
month value from the event date time stamp) . The majority of the time
was spent trying to get the insert to work, but it does not seem
possible to do that insert from a JSON SerDe to a CSV SerDe. I wonder why this would be the case?

Other than this, the motto for this fix to start wit is "omit the INSERT INTO statement before the beginning of the query string".


text:
Q: SonarQube gradle plugin failing with ArrayIndexOutOfBounds exception I am trying to run the sonar gradle plugin and after running the tests I get the following:
Execution failed for task ':sonarqube'.

String index out of range: -1

For what its worth I'm on OS X 10.10 with sonar qube gradle plugin version 2.2.1
EDIT: Here is what I see in the log:
    :sonarqube
    Class not found: javax.annotation.Nullable
    Class not found: javax.annotation.CheckReturnValue
    Class not found: org.apache.http.annotation.NotThreadSafe
    Class not found: org.apache.http.annotation.Immutable
    Class not found: org.apache.http.annotation.ThreadSafe
    Class not found: org.apache.http.annotation.Immutable
    Class not found: org.apache.http.annotation.NotThreadSafe
    Class not found: org.apache.http.annotation.ThreadSafe
    (list goes on, there are some, but not all of my classes in here as well)
:sonarqube FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':sonarqube'.
> String index out of range: -1

When I run sonarqube with stack trace enabled I get the following stack trace:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':sonarqube'.
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:84)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:55)
        at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:62)
        at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
        at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:88)
        at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:46)
        at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:51)
        at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
        at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
        at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.execute(DefaultTaskGraphExecuter.java:236)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.execute(DefaultTaskGraphExecuter.java:228)
        at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:61)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:228)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:215)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:77)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:58)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:32)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:113)
        at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
        at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
        at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
        at org.gradle.initialization.DefaultGradleLauncher$RunTasksAction.execute(DefaultGradleLauncher.java:256)
        at org.gradle.initialization.DefaultGradleLauncher$RunTasksAction.execute(DefaultGradleLauncher.java:253)
        at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:56)
        at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:175)
        at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:119)
        at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:102)
        at org.gradle.launcher.exec.GradleBuildController.run(GradleBuildController.java:71)
        at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
        at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:75)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:49)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:49)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:31)
        at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:47)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
        at org.gradle.util.Swapper.swap(Swapper.java:38)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:60)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:72)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
        at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
        at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:46)
Caused by: java.lang.StringIndexOutOfBoundsException: String index out of range: -1
        at org.sonar.plugins.surefire.data.SurefireStaxHandler.getClassname(SurefireStaxHandler.java:69)
        at org.sonar.plugins.surefire.data.SurefireStaxHandler.stream(SurefireStaxHandler.java:57)
        at org.sonar.api.utils.StaxParser.parse(StaxParser.java:115)
        at org.sonar.api.utils.StaxParser.parse(StaxParser.java:95)
        at org.sonar.api.utils.StaxParser.parse(StaxParser.java:85)
        at org.sonar.plugins.surefire.SurefireJavaParser.parseFiles(SurefireJavaParser.java:109)
        at org.sonar.plugins.surefire.SurefireJavaParser.parseFiles(SurefireJavaParser.java:99)
        at org.sonar.plugins.surefire.SurefireJavaParser.collect(SurefireJavaParser.java:64)
        at org.sonar.plugins.surefire.SurefireSensor.collect(SurefireSensor.java:65)
        at org.sonar.plugins.surefire.SurefireSensor.analyse(SurefireSensor.java:60)
        at org.sonar.batch.phases.SensorsExecutor.executeSensor(SensorsExecutor.java:58)
        at org.sonar.batch.phases.SensorsExecutor.execute(SensorsExecutor.java:50)
        at org.sonar.batch.phases.AbstractPhaseExecutor.execute(AbstractPhaseExecutor.java:83)
        at org.sonar.batch.scan.ModuleScanContainer.doAfterStart(ModuleScanContainer.java:192)
        at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:142)
        at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:127)
        at org.sonar.batch.scan.ProjectScanContainer.scan(ProjectScanContainer.java:241)
        at org.sonar.batch.scan.ProjectScanContainer.scanRecursively(ProjectScanContainer.java:236)
        at org.sonar.batch.scan.ProjectScanContainer.doAfterStart(ProjectScanContainer.java:226)
        at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:142)
        at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:127)
        at org.sonar.batch.task.ScanTask.execute(ScanTask.java:47)
        at org.sonar.batch.task.TaskContainer.doAfterStart(TaskContainer.java:86)
        at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:142)
        at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:127)
        at org.sonar.batch.bootstrap.GlobalContainer.executeTask(GlobalContainer.java:106)
        at org.sonar.batch.bootstrapper.Batch.executeTask(Batch.java:119)
        at org.sonarsource.scanner.api.internal.batch.BatchIsolatedLauncher.execute(BatchIsolatedLauncher.java:62)
        at org.sonarsource.scanner.api.internal.IsolatedLauncherProxy.invoke(IsolatedLauncherProxy.java:60)
        at com.sun.proxy.$Proxy179.execute(Unknown Source)
        at org.sonarsource.scanner.api.EmbeddedScanner.doExecute(EmbeddedScanner.java:233)
        at org.sonarsource.scanner.api.EmbeddedScanner.runAnalysis(EmbeddedScanner.java:151)
        at org.sonarqube.gradle.SonarQubeTask.run(SonarQubeTask.java:93)
        at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.doExecute(DefaultTaskClassInfoStore.java:141)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:134)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:123)
        at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:632)
        at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:615)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:95)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:76)
        ... 70 more

EDIT:Turns out the cause is the Sonar Surefire library, more specifically the fact that it is not designed to handle unbalanced parentheses in test class names and I accidentally left unbalanced parentheses in one of my cucumber scenario names

A: Summarizing the solution from the comments, this problem is caused by unbalanced parentheses in scenario names. It is best to avoid parentheses in feature and scenario names.
In my specific case, I had a Feature called Feedback (bounce and confirmation), and this caused cucumber to generate per scenario reports with the name ).Email successfully sent( instead of the usual Feedback (bounce and confirmation).Email successfully sent. And apparently, the sonarqube plugin doesn't like that.
Changing the feature name to Bounce and confirmation feedback solved the issue.


text:
Q: NuGet Push Failure in TFS build Preface: I am running NuGet Server (2.11.3) on Windows 2012 R2 / IIS 8.5. The NuGet Server manages its packages folder in separated file server (shared folder).
Additionally I am running TFS build machine (agent from TFS 2015) that uses this nuget server for both restore and push activities. Naturally,  each build, initially, reads the target solution >>> projects >>> packages.config files and restores the configured packages from the nuget server. On late step, the agent generates the required *.nupkg files and pushes them to the nuget endpoint of the same nuget server. Those are dependencies of other solutions.
Problem: the majority of the solutions running properly without any special issues. There are couple of solutions that only 1-3 projects within them, fail the TFS build with the following message:
Response status code does not indicate success: 500 (Internal Server Error).
Unexpected exit code 1 returned from tool NuGet.exe

The IIS logs on nuget server looks like the following:
2017-03-27 16:47:26 192.168.2.116 PUT /MainRepository/nuget/ - 80 - 192.168.1.30 NuGet+Command+Line/3.5.0+(Microsoft+Windows+NT+6.2.9200.0) - 500 0 0 15
2017-03-27 16:47:26 192.168.2.116 PUT /MainRepository/nuget/ - 80 - 192.168.1.30 NuGet+Command+Line/3.5.0+(Microsoft+Windows+NT+6.2.9200.0) - 500 0 0 15
2017-03-27 16:47:26 192.168.2.116 PUT /MainRepository/nuget/ - 80 - 192.168.1.30 NuGet+Command+Line/3.5.0+(Microsoft+Windows+NT+6.2.9200.0) - 500 0 0 31

The following event is logged (shown in the event viewer) in the nuget server:
Event code: 3005
Event message: An unhandled exception has occurred.
Event time: 27/03/2017 10:40:17
Event time (UTC): 27/03/2017 07:40:17
Event ID: cb897ce6dc2f4e40a07c71a9160718f2
Event sequence: 2073
Event occurrence: 4
Event detail code: 0

Application information:
    Application domain: /LM/W3SVC/1/ROOT/MainRepository-1-131350724531418170
    Trust level: Full
    Application Virtual Path: /MainRepository
    Application Path: C:\inetpub\wwwroot\NugetServerInternal\
    Machine name: NUGET-SRV

Process information:
    Process ID: 2512
    Process name: w3wp.exe
    Account name: some.domain/some.user

Exception information:
    Exception type: IndexOutOfRangeException
    Exception message: Index was outside the bounds of the array.
   at System.Web.HttpRawUploadedContent.get_Item(Int32 index)
   at System.Web.HttpMultipartContentTemplateParser.GetNextLine()
   at System.Web.HttpMultipartContentTemplateParser.ParseIntoElementList()
   at System.Web.HttpMultipartContentTemplateParser.Parse(HttpRawUploadedContent data, Int32 length, Byte[] boundary, Encoding encoding)
   at System.Web.HttpRequest.GetMultipartContent()
   at System.Web.HttpRequest.FillInFilesCollection()
   at System.Web.HttpRequest.EnsureFiles()
   at System.Web.HttpRequest.get_Files()
   at System.Web.HttpRequestWrapper.get_Files()
   at NuGet.Server.Publishing.PackageService.CreatePackage(HttpContextBase context)
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

Request information:
    Request URL: http://nuget-srv/MainRepository/nuget/
    Request path: /MainRepository/nuget/
    User host address: 192.168.1.30
    User:
    Is authenticated: False
    Authentication Type:
    Thread account name: some.domain/some.user

Thread information:
    Thread ID: 19
    Thread account name: some.domain/some.user
    Is impersonating: False
    Stack trace:    at System.Web.HttpRawUploadedContent.get_Item(Int32 index)
   at System.Web.HttpMultipartContentTemplateParser.GetNextLine()
   at System.Web.HttpMultipartContentTemplateParser.ParseIntoElementList()
   at System.Web.HttpMultipartContentTemplateParser.Parse(HttpRawUploadedContent data, Int32 length, Byte[] boundary, Encoding encoding)
   at System.Web.HttpRequest.GetMultipartContent()
   at System.Web.HttpRequest.FillInFilesCollection()
   at System.Web.HttpRequest.EnsureFiles()
   at System.Web.HttpRequest.get_Files()
   at System.Web.HttpRequestWrapper.get_Files()
   at NuGet.Server.Publishing.PackageService.CreatePackage(HttpContextBase context)
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

NOTE: per my checking sometime the package is created in the packages folder and sometime is not.
NOTE: I am pretty sure that all configuration is in place (including API key etc..). Of course, will be glad to know what is missing though.
Will appreciate any advice on this one.
Many thanks in advance,
Ofer

A: Poor answer though, but still one that might help any potential issues you guys encounter :-).
I've realized that my "problematic" push requests had worked against newly created NuGet server. The new one was Windows Server 2012 R2 too. I've just raised it clean and added ONLY the necessary windows features to support the IIS/web operations against the Nuget server.
If I am not mistaken it was only ASP.NET 4.5.
Best regards,
Ofer