text:
Q: Progress Dialog not showing during a asynctask call Ok so I am trying to get a progress dialog to show when data is being downloaded from the internet and being applied to the UI. My asynctask is working fine and it runs though all the steps, but it never shows the dialog ever. I don't know what I have done wrong here and I pretty much hit the wall. I even tried to put the async task into the new runnable thread and run it like that, that also did not show the dialog. I am calling the async task like this
    new runningMan().execute();

Here is the code that I am trying to run.
private class runningMan extends AsyncTask<Void, Void, Integer>
{

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        Log.d("Runningman: ", "Started running");
        //this method will be running on UI thread
        progress = ProgressDialog.show(PromotionMain.this, "Loading", "PleaseWait", true);

    }
    @Override
    protected Integer doInBackground(Void... params) {
        //parse the JSON string
        JSONParser jp = new JSONParser();
        try {
            Log.d(username , password);
            jp.parsesData(promos, myJson, pictureArray, pathArray, labelArray);
            Log.d("Runningman: ", "Finished parsing");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return 1;
    }
    @Override
    protected void onPostExecute(Integer result) {
        super.onPostExecute(result);
        ArrayList<ListItem> listData = getListData();
        fillListView(listData);
        Log.d("Runningman: ", "Finished runing");
        //this method will be running on UI thread
        progress.dismiss();
    }

}

Thank you for any help with this.

A: Call "super.onPreExecute();" and "super.onPostExecute(result);" after your code for progress dialog. Or better, get rid of them (if you don't have reasons for calling them).
Use the following code:
private class runningMan extends AsyncTask<Void, Void, Integer>
{

    @Override
    protected void onPreExecute() {

        Log.d("Runningman: ", "Started running");
        //this method will be running on UI thread
        progress = ProgressDialog.show(PromotionMain.this, "Loading", "PleaseWait", true);
        super.onPreExecute();

    }
    @Override
    protected Integer doInBackground(Void... params) {
        //parse the JSON string
        JSONParser jp = new JSONParser();
        try {
            Log.d(username , password);
            jp.parsesData(promos, myJson, pictureArray, pathArray, labelArray);
            Log.d("Runningman: ", "Finished parsing");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return 1;
    }
    @Override
    protected void onPostExecute(Integer result) {
        ArrayList<ListItem> listData = getListData();
        fillListView(listData);
        Log.d("Runningman: ", "Finished runing");
        //this method will be running on UI thread
        progress.dismiss();
        super.onPostExecute(result);
    }

}


text:
Q: extracting access token out of string in javascript I have a string which and I need to get the access token out of this string .However we also need to confirm if access token is there or not .
The string is as followed .
      ?utm_source=xyz&utm_medium=xyza&utm_campaign=xyzb&access_token=abybsjw16373vdgw

I need to get the access token out of this using javascript.
I would like to understand as how people approach such problems .

A: we can also do this like

let str="?utm_source=xyz&utm_medium=xyza&utm_campaign=xyzb&access_token=abybsjw16373vdgw"

       let tokenIsPresent=str.search("access_token")
       if(tokenIsPresent !=-1){
       let token= str.slice(tokenIsPresent+13)
        console.log(token)}
        else{console.log("token is not present")}

we can find access_token by string.search which will return starting position of our search string ie "50" here
and then we have to add the length of our search ie "access_token=" which is 13
then we have to slice it by 50+13

A: You can try:
const str = "?utm_source=xyz&utm_medium=xyza&utm_campaign=xyzb&access_token=abybsjw16373vdgw "
const accessParts = str.match('access_token=.*$')[0].split("=")

console.log(accessParts) // ["access_token", "abybsjw16373vdgw "]

A: let token='';
if(window.location.href.split('access_token').length>0){
    token=window.location.href.split('access_token')[1].split('&').join('');
}
if(!token){
    console.log('token is missing');
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Restore Windows From Data Backup? So I managed to break my partition table, but I was able to recover my entire C: drive and copy every file and folder to an external drive. My question now becomes, is there anyway to, when I reinstall Windows, to restore from that backup (since it's just a data backup of files and folders, not a system image)?
Would booting into linux (so that partition isn't in use by Windows) and simply copy-past-overwriting the old files effectively give me my system back?

A: Using another OS, like a linux live cd, or a different install of Windows, you can simply restore all of the files, yes.. at least assuming you did actually back them all up.  If you did the backup while running windows, then it won't let you backup files that are in use, such as the registry hives.


text:
Q: Generate method that calls class private field method by just forwarding parameters? Is it possible in Visual Studio or ReSharper to generate a method that just forwards parameters to a private field's method?
class Inner
{
 public void Test(String a, String b){}
}
class Outer
{
  private Inner _inner;
  public Outer(Inner inner)
  {_inner = inner;}
  /*
  //I want to generate this:
  public void Test(String a, String b)
  {
    _inner.Test(a, b);
  }
  */
}

A: The Resharper feature you are looking for is called "Generating delegating members" and is described here:

To generate delegating members

*

*In the editor, set the caret on the type name or within a type at the line where you want to insert delegating members. If the caret is on the type name, the generated code will be added in the beginning of the type declaration.

*Press Alt+Insert or choose ReSharper | Edit | Generate Code… from the main menu. Alternatively, you can press Ctrl+Shift+A, start typing the command name in the pop-up, and then choose it there.

*In the Generate pop-up menu, select Delegating Members.

*In the Generate dialog that appears, you will see a list of private properties and fields in the current type. You can expand these items to see the members of their types. Select some or all of these type members, and ReSharper will generate wrappers in the current type that delegate execution to selected type members.

*Click Finish to complete the wizard.
  You can also click Options to review or modify common code generation preferences on the Code Editing | Members Generation page of ReSharper options.


text:
Q: WorkingDays between Two days (Culture dependent?) I need the workingday-difference between two dates.
It is easy, to

*

*get the difference between two dates

*get the difference of weekdays between two dates

*get the workingday difference between two dates for a culture where you know the federal holidays.

But I'm wondering, if there is a method to get this difference in a generic way for any culture?
i.e. in the US, the 4th of july is a federal holiday. So - for Users from the US, the following calculation should apply:
//Assuming:
// 3rd July = Monday
// 4th July = Tuesday
// 5th July = Wednesday

workingDayDiff("03 July", "05 July", Locale.US) //2
workingDayDiff("03 July", "05 July", Locale.Germany) //3

While, around a german federal holidy, i.e. the 3th october:
//Assuming:
// 3rd Oct = Monday
// 4th Oct = Tuesday
// 5th Oct = Wednesday

workingDayDiff("03 Oct", "05 Oct", Locale.US) //3
workingDayDiff("03 Oct", "05 Oct", Locale.Germany) //2

If you know any libraries that work, I'm open for it. (I cannot lookup federal holidays for every possible country and store them somewhere...)
it wouldn't matter if start / Enddate is in- or exclusive, as this can be easily changed by using "+/- 1 day" on the dates.


text:
Q: Not understand this recursive function that inverts digits of a number I found this code
#include <stdio.h>
#include <math.h>

int rev(int num)
{
    if(num < 10)
        return num;
    else
        return (num % 10) * pow(10, (int)log10(num)) + rev(num/10);
}

int main(void)
{
    printf("%d\n", rev(12345));

    return 0;
}

And I set out to analyzing it, but now I have one doubt it is the following, to return to the starting point what values are obtained with (num % 10) according to my understanding should be (1,2,3,4,5) but when trying do the calculation manually I do not get the expected value.
What happens here, if someone explains to me this, or I missed out something?

A: int rev(int num) // num = 12345
{
    if(num < 10) // false
        return num;
    else
        return (num % 10) * pow(10, (int)log10(num)) + rev(num/10);
        //     (12345 % 10) * 10 ^ (log 12345) + rev(12345/10);
        //     5 * 10 ^ (4) + rev (1234)
        //     50000 + rev(1234)
}

Based on this, we can assume that:
rev(12345) = 50000 + rev(1234)
rev(1234) = 4000 + rev(123)
rev(123) = 300 + rev(12)
rev(12) = 20 + rev(1)
rev(1) = 1

So, the end result is:
rev(12345) = 50000 + 4000 + 300 + 20 + 1 = 54321

It is a simple math, the only non trivial rule is (int)log10(num), but it was explained by @QuestionC in his comment.


text:
Q: If I change my current display name, will my old questions have a changed name? I would like to change the name I display to the community. Would my old questions from before the change get modified to display my new name please?
I was unable to find it in the FAQ. This question "If I change my display name, will the change reflect in comments?" is about comments but may be related.
Would it be difficult to implement it so that you can look at a user's name history and related questions?

A: If you change your display name, all of your old questions and answers will use your new display name. However, if anyone has @replied you in comments, the @replies will still use your old display name because they are part of the actual text of the comments.
The old display name will also continue to appear on Community Wiki posts and chat transcripts.
It's important to keep in mind that your old display name will always be visible from websites that scrape and archive old content, like the Wayback Machine.
There is a "Recent Names" section on your profile that keeps a log of your recent display names, but it is visible to only you and moderators.
For the most part, the transition from one display name to another is relatively seamless, but there are a couple of downsides, the first being the lingering display names mentioned above, which can make discussions/edit histories confusing for future visitors.
Another is that you lose any to all reputation (not the points, actual reputation) associated with you by other users. To put it more simply: people won't know who you are, so you lose all association and trust associated with your display name.
Of course, your name now is user237730, which doesn't carry much, so changing it can't hurt, but it's something to keep in mind for later if you change it to something more substantial.


text:
Q: Eliminar dos o mas espacios en blanco expresion regular Necesito de su ayuda debido a que tengo una expresion regular para eliminar dos o más espacios en blanco, pero he intentado de varias maneras y no logro obtener el resultado esperado, me pueden orientar por favor.
Caso No. 1
String texto = "  95716 B VO  21513836                        269     60 S          50.40          3024.00          SI          DCBO040818BLA";
texto = texto.replaceAll("\\s+"," ");

Caso No. 2
String texto = "  95716 B VO  21513836                        269     60 S          50.40          3024.00          SI          DCBO040818BLA";
texto = texto.replaceAll("\\s"," ");

Caso No. 3
String texto = "  95716 B VO  21513836                        269     60 S          50.40          3024.00          SI          DCBO040818BLA";
texto = texto.replaceAll(" +"," ");

Caso No. 4
String texto = "  95716 B VO  21513836                        269     60 S          50.40          3024.00          SI          DCBO040818BLA";
texto = texto.replaceAll("\\s+"," ").trim();

Caso No. 5
String texto = "  95716 B VO  21513836                        269     60 S          50.40          3024.00          SI          DCBO040818BLA";
texto = texto.replaceAll("\\s+"," ").replaceAll("^\\s*","").replaceAll("\\s*$","");

Caso No. 6
String texto = "  95716 B VO  21513836                        269     60 S          50.40          3024.00          SI          DCBO040818BLA";
texto = texto.replace("  "," ");

Resultado Esperado
String texto = "95716 B VO 21513836 269 60 S 50.40 3024.00 SI DCBO040818BLA";

A: prueba esto:
String texto = " Esto  es una     prueba    ";
        texto=texto.trim();
        texto=texto.replaceAll("\\s{2,}", " ");
        System.out.println(texto);

La funcion "trim" te quitara los espacios en blanco que existan al principio y al final de tu cadena.
Y esta linea de código:
texto=texto.replaceAll("\\s{2,}", " ");

Se interpreta asi, reemplaza 2 o mas espacios en blanco por un solo espacio.
Saludos.

A: Amigo espero y esto te sirva :).
Primera Opción.

var texto = "  95716 B VO  21513836                        269     60 S          50.40          3024.00          SI          DCBO040818BLA";
texto_2 = texto.replace(/^\s+|\s+$|\s+(?=\s)/g, "");
console.log(texto_2);

Segunda Opción:

var string="  95716 B VO  21513836                        269     60 S          50.40          3024.00          SI          DCBO040818BLA";

string3= string.trim().replace(/\s\s+/g, ' ');

 console.log(string3);


text:
Q: Using modular arithmetic show that in $<ℤ_p, +, *> , a = a^{-1}$ if and only if $a ∈ {1, p-1}$. (a) Show that in $<ℤ_p, +, *> , a = a^{-1}$ if and only if $a \in \{1, p-1\}$.
(b) Using (a), prove that for any prime p, we have $(p - 2)! =  1 \ $ mod $ \ p$.
(c) Let p be a prime number greater than five. Prove that
$\underbrace{111...1}_{p-1 \ \text{ digits}}=0! \ $ mod $\ p$

A: For part (a) observe the following chain of biconditionals.
$a=a^{-1}\iff a^2\equiv 1\mod p\ \iff a^2-1\equiv0\mod p\ \iff (a-1)(a+1)\equiv 0\mod p\ \iff a-1\equiv0\mod p\ \text{or}\ a+1\equiv 0\mod p\ \iff a\in\{1,p-1\}$
Let $p$ be a prime. Then $\mathbf{Z}_p$ is a field and therefore each member of $\mathbf{Z}_p$ is invertible. By part (a) we know that $1$ is its own inverse and $p-1$ is its own inverse. And $1,p-1$ are the only such members of $\mathbf{Z}_p$. So for any $a\in \{2,3,\cdots,p-2\}$ there is $b\in \{2,3,\cdots,p-2\}\setminus \{a\}$ such that $ab=1$. Hence the product $2\times3\times\cdots\times (p-2)\equiv 1\mod p$ or rather $(p-2)!\equiv 1\mod p$.


text:
Q: Why does this batch script terminate unexpectedly? This batch script terminates when %CHECKCONTINUE% is given a null value by not inputting anything on line 13 (SET /p CHECKCONTINUE=Okay to continue? (y/n):), why is this?
@ECHO OFF
SETLOCAL
TITLE Registry restore script
REM Restores registry settings and disables the cloud

SET %CHECKCONTINUE%=

:listaction
ECHO I'm about to...
ECHO 1.) Remove the registry data that specifies settings for TF2
ECHO 2.) Forcibly disable Steam Cloud.
ECHO.
SET /p CHECKCONTINUE=Okay to continue? (y/n):

REM No?
IF %CHECKCONTINUE%==n GOTO exit
IF %CHECKCONTINUE%==no GOTO exit

REM Yes?
IF %CHECKCONTINUE%==y GOTO start
IF %CHECKCONTINUE%==yes GOTO start

REM Did they put something else?
IF DEFINED %CHECKCONTINUE% GOTO loop-notvalid

REM Did they not put anything at all?
IF NOT DEFINED %CHECKCONTINUE% GOTO loop-noreply

:start
REM Delete application specific data
REG DELETE HKEY_CURRENT_USER\Software\Valve\Source\tf\Settings /f
REG DELETE HKEY_CURRENT_USER\Software\Valve\Steam\Apps\440 /f

REM Disable Steam Cloud for TF2
REG ADD HKEY_CURRENT_USER\Software\Valve\Steam\Apps\440 /v Cloud /t REG_DWORD /d "0x0" /f

:exit
ENDLOCAL
EXIT

:loop-notvalid
ECHO.
ECHO That's not a valid reply. Try again.
ECHO.
SET %CHECKCONTINUE%=
GOTO listaction

:loop-noreply
ECHO.
ECHO You must enter a reply.
ECHO.
SET %CHECKCONTINUE%=
GOTO listaction

A: First, on multiple lines you have:
SET %CHECKCONTINUE%=

This doesn't modify CHECKCONTINUE but uses its value as the variable name.
Change it to:
SET CHECKCONTINUE=

It would also be better if you moved it immediately above set /p ... -- this way you would only need it once.

if defined also only takes a variable name, so instead of
IF DEFINED %CHECKCONTINUE% GOTO loop-notvalid

you should use:
IF DEFINED CHECKCONTINUE GOTO loop-notvalid

Same applies to this line:
IF NOT DEFINED %CHECKCONTINUE% GOTO loop-noreply

However, it can be shortened to:
GOTO loop-noreply

If the variable were defined, the execution would never reach this line anyway (if defined ... above)

This is how I would have written it:
@echo off & setlocal
title Registry restore script
:: Restores registry settings and disables the Cloud

:menu
echo I'm about to...
echo 1) Remove the registry data that specifies settings for TF2
echo 2) Forcibly disable Steam Cloud.
echo.
set check=
set /p check=Okay to continue? (y/n)
:: /i means case-insensitive comparison
if /i %check%==y goto :start
if /i %check%==yes goto :start
if /i %check%==n goto :EOF
if /i %check%==no goto :EOF
:: On empty response, pick the safest option as default
if not defined check goto :EOF

goto :loop-invalid

:start
:: Delete application specific data
reg delete HKCU\Software\Valve\Source\tf\Settings /f
reg delete HKCU\Software\Valve\Steam\Apps\440 /f

:: Disable Steam Cloud for TF2
reg add HKCU\Software\Valve\Steam\Apps\440 /v Cloud /t REG_DWORD /d "0x0" /f

:loop-invalid
echo.
echo Not a valid answer.
goto :menu

A: Expanding on grawity's great answer:
First, to answer your question:
Why does the batch script terminate when %CHECKCONTINUE% is given a null value?
The problem is, in line 16, you do this:
if %CHECKCONTINUE%==n GOTO exit

Since CHECKCONTINUE is "undefined", it evaluates to an "empty" string, so the statement on line 16 is actually doing:
if ==n GOTO exit

This is an invalid statement because there is nothing on the left hand side of the "==". So, the batch script terminates when it tries to execute an improperly formatted statement:
C:\>script.cmd
I'm about to...
1.) Remove the registry data that specifies settings for TF2
2.) Forcibly disable Steam Cloud.

Okay to continue? (y/n): <ENTER key pressed>
GOTO was unexpected at this time.

C:\>

You would have a similar problem if someone types something that contains a space in it:
C:\>script.cmd
I'm about to...
1.) Remove the registry data that specifies settings for TF2
2.) Forcibly disable Steam Cloud.

Okay to continue? (y/n): Yes please
please==n was unexpected at this time.

C:\>

To fix this, you should use double quotes around the terms like this:
if "%CHECKCONTINUE%"=="n" GOTO :exit

This is necessary if the variables used could be "empty" or if they could have embedded whitespace, but it's just a good idea to always use double quotes when evaluating with "==".
Note: Some errors (like the one above with "if" and "==" are "fatal" errors which will cause execution of the batch script to immediately stop. Other errors (like the one below with "set"), are "non-fatal" errors. For "non-fatal" errors, the statement with the error is NOT executed, an error message is shown, and the batch script continues to run starting with the next statement
Next, as grawity pointed out about this line:
set %CHECKCONTINUE%=

This doesn't modify CHECKCONTINUE but uses its value as the variable name.
Again, if CHECKCONTINUE was "undefined", it would evaluate to an "empty" string, so the statement is actually doing:
set =

This is also an invalid statement because there is nothing on the left hand side of the "=".
And these lines:
if defined %CHECKCONTINUE% GOTO loop-notvalid
if not defined %CHECKCONTINUE% GOTO loop-noreply

"if defined" (and "if not defined") expects a variable name, not the value of a variable. If CHECKCONTINUE was undefined, %CHECKCONTINUE% would evaluate to an empty string, and these statements would actually be:
if defined  GOTO loop-notvalid
if not defined  GOTO loop-noreply

Here, "if defined" (and "if not defined") is going to check if a variable named GOTO is defined or not.
Also, for these 3 lines, if CHECKCONTINUE was actually defined, "set" and "if defined" would operate on the "value" of the variable, rather than the "name" of the variable itself. So, if CHECKCONTINUE already had a value of "y", then:
set %CHECKCONTINUE%=
if defined %CHECKCONTINUE% goto loop-notvalid
if not defined %CHECKCONTINUE% goto loop-noreply

would actually be seen as:
set y=
if defined y goto loop-notvalid
if not defined y goto loop-noreply

Example "script.cmd":
@set "CHECKCONTINUE="

@rem ## CHECKCONTINUE="%CHECKCONTINUE%" (undefined/empty).
@rem ## 05: set %CHECKCONTINUE%=
set %CHECKCONTINUE%=

@echo This doesn't set the value of of the variable named "CHECKCONTINUE".
@echo Since no variable name is actually specified, it is an error.

@set "CHECKCONTINUE=yes"
@set "yes=something"

@rem ## CHECKCONTINUE="%CHECKCONTINUE%" and the value of the variable named "yes"="%yes%"
@rem ## 17: set %CHECKCONTINUE%=
set %CHECKCONTINUE%=

@echo This doesn't set the value of the variable named "CHECKCONTINUE".
@echo Since CHECKCONTINUE="%CHECKCONTINUE%", it sets the value of the variable named
@echo "%CHECKCONTINUE%". No error is shown because the statement is valid.
@echo It could have been a problem (well, at least a big annoyance) if
@echo CHECKCONTINUE had the value: "path". The statement
@echo should be: set "CHECKCONTINUE="

@rem ## 27: echo CHECKCONTINUE still has the value: "%CHECKCONTINUE%"
@echo CHECKCONTINUE still has the value: "%CHECKCONTINUE%"

@rem ## 30: echo and the variable named "%CHECKCONTINUE%" is now empty="%yes%"
@echo and the variable named "%CHECKCONTINUE%" is now empty="%yes%"

@set "yes="
@set "CHECKCONTINUE="
@set "echo=something"

@rem ## CHECKCONTINUE="%CHECKCONTINUE%" (undefined) and the value of the variable
@rem ## named "echo"="%echo%".
@rem ## 41: if defined %CHECKCONTINUE% echo Variable is defined.
if defined %CHECKCONTINUE% echo Variable is defined.

@echo This doesn't check if the variable named "CHECKCONTINUE" is defined.
@echo Since it's "empty", it is skipped (well, there is nothing there to
@echo "skip") and "if defined" is checking the next word (which is "echo").
@echo What's left is: if defined echo Variable is defined.
@echo So, it checks if a variable named "echo" is defined (which it is).
@echo Since "if defined" has checked a variable named "echo", it then tries
@echo to execute the rest of the line starting with the word "Variable",
@echo as a command. This fails and is an error. The statement
@echo should be: if defined CHECKCONTINUE echo Variable is defined.

@set "echo="

@rem ## CHECKCONTINUE="%CHECKCONTINUE%" (undefined) and "echo"="%echo%" (undefined).
@rem ## 59: if not defined %CHECKCONTINUE% echo The-variable-is-not-defined.
if not defined %CHECKCONTINUE% echo The-variable-is-not-defined.

@echo Similar: Since "if not defined" has checked a variable named "echo"
@echo (which is "undefined"), it then tries to execute the rest of the
@echo line: "The-variable-is-not-defined." as a command. This fails and is
@echo an error. The statement
@echo should be: if not defined CHECKCONTINUE echo The-variable-is-not-defined.

@set "echo=something"

@rem ## CHECKCONTINUE="%CHECKCONTINUE%" (undefined) and "echo"="%echo%".
@rem ## 73: if defined %CHECKCONTINUE% echo Verify this.
if defined %CHECKCONTINUE% echo Verify this.

@echo Again, similar: Since "if defined" has checked a variable named
@echo "echo", it then tries to execute the rest of the line starting with
@echo the word: "Verify" as a command. This happens to be a valid command
@echo but it also fails because of an incorrect parameter for the command.
@echo The statement should be: if defined CHECKCONTINUE echo Verify this.

@set "echo="

@set "CHECKCONTINUE=yes"
@set "yes="

@rem ## CHECKCONTINUE="%CHECKCONTINUE%" and the variable named "yes"="%yes%" (undefined).
@rem ## 90: if not defined %CHECKCONTINUE% echo CHECKCONTINUE is not defined.
if not defined %CHECKCONTINUE% echo CHECKCONTINUE is not defined.

@echo Here "CHECKCONTINUE" is defined, but "if not defined" still doesn't
@echo check if the variable named "CHECKCONTINUE" is defined. Since
@echo CHECKCONTINUE has a value of "%CHECKCONTINUE%", "if not defined" is
@echo checking if a variable named "%CHECKCONTINUE%" is defined (which it isn't).
@echo This causes "if not defined" to proceed and echo the message when
@echo that's probably not what was intended. The statement
@echo should be: if not defined CHECKCONTINUE echo CHECKCONTINUE is not defined.

Running "script.cmd" you would get:
## CHECKCONTINUE="" (undefined/empty).
## 05: set %CHECKCONTINUE%=

    C:\>set =
    The syntax of the command is incorrect.

This doesn't set the value of of the variable named "CHECKCONTINUE".
Since no variable name is actually specified, it is an error.

## CHECKCONTINUE="yes" and the value of the variable named "yes"="something"
## 17: set %CHECKCONTINUE%=

    C:\>set yes=

This doesn't set the value of the variable named "CHECKCONTINUE".
Since CHECKCONTINUE="yes", it sets the value of the variable named
"yes". No error is shown because the statement is valid.
It could have been a problem (well, at least a big annoyance) if
CHECKCONTINUE had the value: "path". The statement
should be: set "CHECKCONTINUE="

## 27: echo CHECKCONTINUE still has the value: "%CHECKCONTINUE%"

    CHECKCONTINUE still has the value: "yes"

## 30: echo and the variable named "yes" is now empty="%yes%"

    and the variable named "yes" is now empty=""

## CHECKCONTINUE="" (undefined) and the value of the variable
## named "echo"="something".
## 41: if defined %CHECKCONTINUE% echo Variable is defined.

    C:\>if defined echo Variable is defined.
    'Variable' is not recognized as an internal or external command,
    operable program or batch file.

This doesn't check if the variable named "CHECKCONTINUE" is defined.
Since it's "empty", it is skipped (well, there is nothing there to
"skip") and "if defined" is checking the next word (which is "echo").
What's left is: if defined echo Variable is defined.
So, it checks if a variable named "echo" is defined (which it is).
Since "if defined" has checked a variable named "echo", it then tries
to execute the rest of the line starting with the word "Variable",
as a command. This fails and is an error. The statement
should be: if defined CHECKCONTINUE echo Variable is defined.

## CHECKCONTINUE="" (undefined) and "echo"="" (undefined).
## 59: if not defined %CHECKCONTINUE% echo The-variable-is-not-defined.

    C:\>if not defined echo The-variable-is-not-defined.
    'The-variable-is-not-defined.' is not recognized as an internal or external command,
    operable program or batch file.

Similar: Since "if not defined" has checked a variable named "echo"
(which is "undefined"), it then tries to execute the rest of the
line: "The-variable-is-not-defined." as a command. This fails and is
an error. The statement
should be: if not defined CHECKCONTINUE echo The-variable-is-not-defined.

## CHECKCONTINUE="" (undefined) and "echo"="something".
## 73: if defined %CHECKCONTINUE% echo Verify this.

    C:\>if defined echo Verify this.
    An incorrect parameter was
    entered for the command.

Again, similar: Since "if defined" has checked a variable named
"echo", it then tries to execute the rest of the line starting with
the word: "Verify" as a command. This happens to be a valid command
but it also fails because of an incorrect parameter for the command.
The statement should be: if defined CHECKCONTINUE echo Verify this.

## CHECKCONTINUE="yes" and the variable named "yes"="" (undefined).
## 90: if not defined %CHECKCONTINUE% echo CHECKCONTINUE is not defined.

    C:\>if not defined yes echo CHECKCONTINUE is not defined.
    CHECKCONTINUE is not defined.

Here "CHECKCONTINUE" is defined, but "if not defined" still doesn't
check if the variable named "CHECKCONTINUE" is defined. Since
CHECKCONTINUE has a value of "yes", "if not defined" is
checking if a variable named "yes" is defined (which it isn't).
This causes "if not defined" to proceed and echo the message when
that's probably not what was intended. The statement
should be: if not defined CHECKCONTINUE echo CHECKCONTINUE is not defined.

Also, as an alternative to "set /p", you could use "choice":
@echo off
title Registry restore script
rem Restores registry settings and disables the cloud

rem "quotes" around variable name and value for set visibly shows what
rem the variable is being set to and prevents accidentally including
rem trailing whitespace in the variable's value.
    set "CHECKCONTINUE="

:listaction
echo I'm about to...
echo 1.) Remove the registry data that specifies settings for TF2
echo 2.) Forcibly disable Steam Cloud.
echo.
choice /c yn /M "Okay to continue"

set "CHECKCONTINUE=%errorlevel%"
if %CHECKCONTINUE% EQU 1 @echo Pressed Y && goto :start
if %CHECKCONTINUE% EQU 2 @echo Pressed N && goto :exit
if %CHECKCONTINUE% EQU 0 @echo Pressed Ctrl-C+n
@echo.

@echo Terminate batch job cancelled. You must enter a reply. Press n to exit.
@echo.
goto :listaction

rem The remainder of your code goes here ...

Note: the code at label: "loop-notvalid" is not necessary because "choice" won't accept undefined responses (y/n).
Also, the only way to get an "empty" response from the "choice" commnad, is if the user presses "Ctrl-C" to terminate batch job, and then enters N (No) to the "Terminate batch job (Y/N)?" prompt, indicating they DON'T want to exit. The code above catches that and prints a message then jumps (goto) to the ":listaction" label to re-prompt the user, so you don't need the code at the "loop-noreply" label either.
There is no need to "reset" errorlevel since the choice command takes care of that. And, it's not necessary to clear the CHECKCONTINUE variable because it is always set equal to %errorlevel% before the value of CHECKCONTINUE is examined.
By default, choice is "case-insensitive", so pressing "Y" or "N" is the same as pressing "y" or "n". This behavior can be changed by specifying /cs on the choice command line.


text:
Q: Eclipse - "Error moving resource" I am creating a web service client to consume a WCF service in eclipse and when I enter in the url for my WSDL, the setup wizard begins generating classes, then abruptly stops and spits out a nasy error message specifically targeting one of my classes.
IWAB0523E Error moving resource: Could not read from source when writing file 'C:\Documents and Settings\sam.bengtson\My Documents\Java Files\WebServiceProject\src\org\datacontract\schemas\_2004\_07\InmateCanteenService\CallStatus.java'

The thing is, this class is automatically generated by the .Net connector for MySql.  This also used to work without any problems and I have not recently changed my WCF service either.  Has anybody else seen this error message before?  Any sort of help would be appreciated.  Thanks

A: Try refreshing your project and then cleaning it.

A: Eclipse has no idea about file modification that has taken place outside of it. The problem could simply be that you need to refresh the project which would involve selecting the project name and hitting F5 or right-click and select Refresh.


text:
Q: Terraform how to remove key from resource when variable is empty? I have a Terraform resource definition as such:
variable "NUM_NODES" {
   type = number
}

resource "aws_resource" {
   num_nodes = var.NUM_NODES
}

There is a restriction on the resource for num_nodes, if present, to not be empty. Is there a way for terraform to ignore keys without values on the "aws_resource"? So the key num_nodes is not included at all?
If this isn't possible what is the best option? Can anyone help me?
I've tried to set the default of NUM_NODES to null
variable "NUM_NODES" {
  type = number
  default = null
}

but continue to see errors regarding 'invalid value for input variable', instead of it being ignored

A: When defining the arguments in a resource block that are declared by the provider itself, setting an argument to null is exactly the same as not setting it at all.
It should therefore work to declare a variable as optional by setting its default to null, and then assign the value directly to the argument:
# NOTE: It's conventional to name Terraform variables in lowercase
variable "node_count" {
  type    = number
  default = null
}

resource "example" "example" {
  num_nodes = var.node_count
}

There is no way for a provider to distinguish between an argument being unset completely vs. being set to null because the two are represented identically in the protocol that Terraform uses to talk to providers.
If you try this and see validation errors for the argument in question then there must be something else going on that isn't reflected in this example. For example, if you actually set node_count in the calling module block then the default value of null won't be used and so it'll be up to the calling module to provide a valid value for this argument, or to explicitly set it to null.


text:
Q: How to display nodejs mysql results on html page? I am learning Nodejs as an alternative to PHP which I am familiar with. Typically I would use Ajax to call PHP scripts to return json data and work from there. It is pretty simple to show it on a website.
Now I am trying to us Nodejs to load data from a MySQL database on page load and show it on the html page. The following is my app.js script.
I have two ideas listed below #1 using socket.io and #2 just loading it, they are not running concurrently, just different attempts.
const express = require('express');
const mysql = require('mysql');

const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);

const port = process.env.PORT || 3000;

app.use(express.static(__dirname + '/public'));

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});

//mysql

var connection = mysql.createConnection({
    host: '...',
    user: '...',
    password: '...',
    database: '...'
});

io.on('connection', (socket) => {
    socket.on('chat message', (msg) => {
        io.emit('chat message', msg);
    });
    socket.on('typing', (data) => {
        socket.broadcast.emit('typing', data);
    });
    socket.on('typing_clear', (data) => {
        socket.broadcast.emit('typing_clear', data);
    });

    // #1 - This is one attempt but crashes the app if loaded from a second page... It works but then if I open a second browser and load the url it crashes the app. I just want this to load once each time a user goes to the URL to load historical data from the database.

    socket.on('get_posts', (data) => {
        connection.connect();

        connection.query('SELECT `status` FROM `training`', function (error, results) {
            if (error) {
                console.log(error);
            }
            var string = JSON.stringify(results);
            // console.log(string);
            io.emit('get_posts', string);

        });

        connection.end();

    });

});

// #2 - This is another attempt. It grabs the data and successfully console log the data. I don't know what do from there. How can I get it to the client side JS page to use json parse and display it.

connection.connect();

connection.query('SELECT `status` FROM `training`', function (error, results) {
    if (error) {
        console.log(error);
    }
    var string = JSON.stringify(results);
    console.log(string);

});

connection.end();

http.listen(port, () => {
    console.log(`Socket.IO server running at http://localhost:${port}/`);
});

I have a second JS script on the client side that does front end stuff with socket.io and others.
Am I going about this wrong?

Edit:
Here is the relevant part of the client side JS script.
load();
function load() {
    socket.emit('get_posts', "none");
}

socket.on('get_posts', function (data) {

    var results = JSON.parse(data);

    jQuery.each(results, function (index, item) {

        var status = item.status;
        var sticky = '
' + status + '
';
        $("#messages").append(sticky);
    });

    var x = '
END
';
    $("#messages").append(x);
});

Error for #2:
I am doing this on local host to test. I do nodemon app.js and go to localhost:3000.
Looks great, loads the data and displays as expected. Then I open a second browser window to see how another person may see it. It loads the html but does not load the data and in the server console (VS Code) I get:
Socket.IO server running at http://localhost:3000/
events.js:292
      throw er; // Unhandled 'error' event
      ^

Error: Cannot enqueue Handshake after invoking quit.
    at Protocol._validateEnqueue (/Users/username_hidden/node/node_modules/mysql/lib/protocol/Protocol.js:215:16)
    at Protocol._enqueue (/Users/username_hidden/node/node_modules/mysql/lib/protocol/Protocol.js:138:13)
    at Protocol.handshake (/Users/username_hidden/node/node_modules/mysql/lib/protocol/Protocol.js:51:23)
    at Connection.connect (/Users/username_hidden/node/node_modules/mysql/lib/Connection.js:116:18)
    at Socket.<anonymous> (/Users/username_hidden/node/app.js:36:20)
    at Socket.emit (events.js:315:20)
    at Socket.emitUntyped (/Users/username_hidden/node/node_modules/socket.io/dist/typed-events.js:69:22)
    at /Users/username_hidden/node/node_modules/socket.io/dist/socket.js:428:39
    at processTicksAndRejections (internal/process/task_queues.js:75:11)
Emitted 'error' event on Connection instance at:
    at Connection._handleProtocolError (/Users/username_hidden/node/node_modules/mysql/lib/Connection.js:423:8)
    at Protocol.emit (events.js:315:20)
    at Protocol._delegateError (/Users/username_hidden/node/node_modules/mysql/lib/protocol/Protocol.js:398:10)
    at Handshake.<anonymous> (/Users/username_hidden/node/node_modules/mysql/lib/protocol/Protocol.js:232:10)
    at Handshake.emit (events.js:315:20)
    at Handshake.Sequence.end (/Users/username_hidden/node/node_modules/mysql/lib/protocol/sequences/Sequence.js:78:12)
    at /Users/username_hidden/node/node_modules/mysql/lib/protocol/Protocol.js:236:14
    at processTicksAndRejections (internal/process/task_queues.js:75:11) {
  code: 'PROTOCOL_ENQUEUE_AFTER_QUIT',
  fatal: false
}
[nodemon] app crashed - waiting for file changes before starting...

Found another post noting you do not need connection.connect(); and connection.end() if already connected. Seemed to have fixes it so far... Testing in progress.

A: Replce your second code with a REST api like below
const connection = mysql.createConnection({
  host: dbConfig.HOST,
  user: dbConfig.USER,
  password: dbConfig.PASSWORD,
  database: dbConfig.DB
});

// open the MySQL connection
connection.connect(error => {
  if (error) throw error;
  console.log("Successfully connected to the database.");
});
app.get('/get-status', (req, res) => {
     connection.query('SELECT `status` FROM `training`', function (error, results) {
         if (error) {
             console.log(error);
         }
         res.send(results);
     });
  });

Now from your front end you could just use ajax to get the REST data using jquery
jQuery.get( "/get-status", function( data ) {
    jQuery.each(data , function (index, item) {
        var status = item.status;
        var sticky = '
' + status + '
';
        $("#messages").append(sticky);
    });
    var x = '
END
';
    $("#messages").append(x);
});

Now what i have suggested abave is a REST api solution that is for your second case. If you like to use sockets on the first go it will be little bit tough to understand try understanding how websockets work then it will be easy.


text:
Q: SwipeRefreshLayout block android.wiget.swith from dragging I have an activity and 10 fragments which I draw on activity. All fragments on activity need to have "drag to refresh". I add Swipe Refresh Layout to create it. Now when I click on the switch, all is fine; but when I try to drag it from one stage to another, swipe to refresh appears, and the switch is just staying in the same position. So how can I block the refreshing of the swipe refresh layout on time when the user drags the switch from one position to another?
I tried to make it like this:
    onOffSwitchSettings.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            ((MainActivity) getActivity()).swipeContainer.setRefreshing(false);
            return false;
        }
    });

But how can I turn it on after?

A: According to SwipeRefreshLayout reference:

The SwipeRefreshLayout will notify the listener each and every time
  the gesture is completed again; the listener is responsible for
  correctly determining when to actually initiate a refresh of its
  content. If the listener determines there should not be a refresh, it
  must call setRefreshing(false) to cancel any visual indication of a
  refresh. If an activity wishes to show just the progress animation, it
  should call setRefreshing(true). To disable the gesture and progress
  animation, call setEnabled(false) on the view.

You've forgotten to use ((MainActivity)getActivity()).swipeContainer.setEnabled(false) method.
Another problem is that using above you're going to disable SRL permanently, so you need to enable it again when the action is right, I mean there's no more dragging.
Hope it will help


text:
Q: What is fastest in reading data: dict, array np-array I created three versions to store, but more important to read data in python3:

*

*1st: a dict with 970200 key - value pairs

*2nd: an 3-D np-array with dimension 100 and the same 907200 entries

*3rd: an array same as the np-array

Reading times for 500.000 reading operations are as followed:
(for testing I read 500.000 times the same value, entry)

*

*1st: 0..07379

*2nd:  0.3007

*3rd:  0.0987

I expected the np-array could be the fastest, but surprisingly it`s the slowest.
More details:
The 3d array could be seen as 3-D coordinates of points - nearly each point has a value assigned. This value is between [0, 3200]. In the 3-D array the 3 dimension are the position of the point, the entry is the value a[222][333][444]=1111.
Access-Version from  Tadhg McDonald-Jensen (a[222, 333, 444] for the np-array) takes: 0.129
The dict has key-value pairs like "[222, 333, 444]":1111
After creating these structures:
Assigning a value from the dict, the array or the np-array to a variable for 500.000 times results in above running times.
Update:
The data gets read from a file into the structure - in the program I want to access individual values from the structure (dict, np-array or array) in the memory. I`m timing the access in the memory only (after structure is already filled with data)
Question:
Could my results be correct from a theoretical point of view - could an np-array be the slowest option to read data?
Thank you for your help! ATramp

A: NumPy is fast for numerical calculations on (large) arrays. You are measuring the access time for one element from Python code. Take this example:
import numpy as np

n = 10
a = np.arange(n)
d = dict.fromkeys(range(n))

The access to the dictionary is faster:
%timeit d[0]
10000000 loops, best of 3: 85.4 ns per loop

than the one to the NumPy array:
%timeit a[0]
10000000 loops, best of 3: 177 ns per loop

Note this time is independent form the size of the structure.
Conclusion: NumPy is fast for vectorized operations on arrays. Doing a lot of pure Python operations on NumPy arrays can be slower than staying with built-in Python datatypes.

Question: Could my results be correct from a theoretical point of view
  - could an np-array be the slowest option to read data?

Yes, this possible when accessing data in NumPy arrays from Python code is all you do with these arrays.


text:
Q: sequence of tenses (optional and obligatory back shifting ) Consider a sentence:

1) The president learned that the earthquake has caused havoc all across the country.

Here present perfect tense is used. First tell me is it correct to use 'has caused' ?
I read once in a grammar book that if the verb in the main clause is in the past tense the the verb in the subordinate clause will also be in the past tense.
So according to this rule it should be 'had caused' instead of 'has caused'.
But at the same time some of them say that if the emphasis is laid on the subordinate clause then present perfect tense can be used. While some say if the emphasis is laid on 'noticing' then past perfect tense to be used. So by this logic one can use present perfect tense as well.
I'm confused.
P.S. -- I'm aware that past perfect tense can be used in every situation but I have no idea when to use present perfect tense in the cases when the verb in the main clause is in the past tense. Help me out.

A: The use of present perfect has caused indicates that the event happened in the recent past and its effects are still current.
Imagine a meeting within the first hour of the earthquake:

We held a meeting in Washington.
  The president learned that the earthquake has caused havoc all across the country.
  The National Guard was mobilised.

All of those simple verbs describe a particular event which happened instantaneously (held, learned, mobilised). The present perfect indicates that havoc was caused and is still ongoing. Compare to the simple past again:

The president learned that the earthquake caused havoc all across the country.

That sentence indicates an instantaneous event (it caused havoc), but it's not explicit that it's still going on: the havoc may well have been countered by the time that sentence was said.


text:
Q: Scaling issues with Unity I am trying to get the starting paddle (I am creating pong) to be at the left most of the screen at all times. I am having trouble coming up with a good formula for doing this. My camera size is 5, it is centered at (0,0). The paddle should be at approximately -6.5 for the x-coordinate. Here, in the script for the paddle, is how I am trying to do this
    //renderer is the SpriteRenderer
    xPos = -Camera.main.orthographicSize -
        (renderer.sprite.textureRect.width/ renderer.sprite.pixelsPerUnit);

However this results in this (the left paddle is here the code is being applied):

So, the right paddle is essential being placed at the very left - the width of the image. However, some of the paddle image is cut off. I can't seem to figure out why and I have checked everywhere. Any help would be extremely appreciated and noticed.

A: I think your problem is related to the calculation of the width of the screen.
Unity uses Camera.main.orthographicSize to calculate the screen's height and then calculates the width depending on the screen proportions. Try to calcule the width in this way:
width= Camera.main.orthographicSize * Camera.main.aspect;


text:
Q: Как устанавливать Ubuntu автоматически? Для Windows есть вариант установки (unattended install), когда все опции, которые нужно выбирать вручную во время самого процесса установки в разных меню, можно задать в виде ключей командной строки или в виде файла настроек.Поскольку Ubuntu сейчас достаточно широко используется и на серверах, наверняка реализован подобный подход к установке и для нее. Как это делается?
A: Посмотрите здесь: automating the installation using preseeding.

Автоматизация обеспечивает способ выбора ответов на вопросы, задаваемые во время процесса установки, без необходимости вручную вводить ответы в то время, как установка работает. Это дает возможность автоматизации наиболее типичных установок, а также предоставляет дополнительные возможности, которые недоступны во время обычной установки.

А также автоматическая преднастроенная установка Ubuntu: isolinux и preseed.
Еще для Windows есть установщик wubi. Подробная информация доступна по ссылке.


text:
Q: How to check if a Scanner is a specific String + any positive integer [Java]  I need to check if a Scanner is holding this: "add (any integer here)"
Here's the code:
import java.util.Scanner;
public class BottleGame {
    void startGame() {
        System.out.println("Welcome to the bottle game! Please type \"help\" to learn about the game.");
        System.out.println("If you already know how the game works, feel free to start!");
        Scanner scanner = new Scanner(System.in);
        commands(scanner);
    }
    void commands(Scanner myScanner) {
        boolean again = false;
        do {
            String response = myScanner.next();
            if (response.equals("help")) {
                System.out.println("+------------------------+");
                System.out.println("help - brings up this menu");
                System.out.println("add X - makes X bottles");
                System.out.println("remove X - deletes X bottles");
                System.out.println("flip - flips a bottle");
                System.out.println("+------------------------+");
                again = true;
            }
            //Need to check if response equals "add" + any integer here
        }
        while(again == true);
    }
}

I commented the spot where I need this, please look for it in the code. Any help would be appreciated. Thanks in advance!

A: You could use a regular expression for this, something like "add\\s+\\d+" which will match the word add followed by one or more white space and then one or more digits with String.matches(String)
} else if (response.matches("add\\s+\\d+")) {
    System.out.println("Add");
}

to then parse that value out, you could group the digits and invoke String.replaceAll(String, String) and then use Integer.parseInt(String) like
} else if (response.matches("add\\s+\\d+")) {
    int v = Integer.parseInt(response.replaceAll("add\\s+(\\d+)", "$1"));
    System.out.println(v);
}


text:
Q: Override Conditional Formatting with Worksheet_SelectionChange I have some code in a worksheet to highlight the row of a selected cell. However, this sheet has conditional formatting which colours some of the rows. The highlighting macro does not work on the rows where the formatting condition is being met (in the sense that the colour of the highlight is not overriding the colour of the conditional formatting).
Private Sub Worksheet_SelectionChange(ByVal Target As Range)

   Cells.Interior.ColorIndex = xlColorIndexNone
    ActiveCell.EntireRow.Interior.ColorIndex = 19 'Highlight row
End Sub

Does anyone know a way around this without removing the conditional formatting?
Eg. can I temporarily disable it for a selected row and re-enable it when the row is unselected?
The formatting is one rule applied to all cells. I figure in theory I could create an independent rule for every row (~500 of them) and then turn that off completely and later reapply it but that seems a little overboard.

A: There is no need to use ActiveCell in your Worksheet_SelectionChange event macro. That is what Target is/does.
Modify your Worksheet_SelectionChange to be closer to the following.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Target.Name = "mySelection"
    Cells.Interior.Pattern = xlNone
    Target.EntireRow.Interior.ColorIndex = 19
End Sub

Now you will be constantly redefining a named range for each new selection of cells.
You didn't disclose what the CF rule actually was so I'm going to assume that is highlights cell that are not blank. Modify the existing CF rule to be of the Use a formula to determine which cells to format variety and adjust the following to suit your own CF rule then put it in the Format values where this formula is true: text box.
=AND(A1<>"", ROW(A1)<>ROW(mySelection))

By adding a boolean criteria within an AND function and constantly redefining the mySelection range to the current selection you can override the CF rule's formatting.


text:
Q: command "ipython" conflict with anaconda and /usr/bin I created an anaconda virtual environment and installed packages related to jupyter and ipython.
But when I type command "ipython" or "jupyter notebook", ipython or jupyter notebook get started from '/usr/bin/', not from my conda environment '/opt/conda/envs/pytorch/bin/' where they're supposed to be from.
How can I start them from conda environment instead of /usr/bin ?

A: You need to activate your environment first:
conda activate pytorch

see the conda user guide here:
https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html#activating-an-environment


text:
Q: Using a dictionary instead of a list to manage a collection I am trying to use a dictionary to manage a collection instead of a list. The use case is for a program that manages a card collection. I have functional code for using a list, but I am seeking assistance with updating the functions to use a dictionary instead. When attempting to use a dictionary, I am getting a TypeError: 'int' object is not subscriptable message in reference to the print('ID: {0}'.format(target['ID'])) line.
In this case, I am trying to get the display_cards function to work and I would appreciate assistance with troubleshooting. I believe the load_card_collection_file function needs to be updated, and particularly the card_collection[card_collection_item["ID"]] = card_collection_item line.
    def load_card_collections():

    sports_card_collection, max_sport_id = load_collection("sportscards.csv")
    pokemon_cards_collection, max_poke_id = load_collection("pokecards.csv")

    if sports_card_collection_collection is None or pokemon_cards_collection_collection is None:
        return None, None

    return {"sports": sports_card_collection, "pokemon": pokemon_cards_collection}, max(max_sport_id, max_poke_id)

def load_card_collection_file(file_name):
    max_id = -1
    try:
        card_collection = {} # This would be changed to a list in the functioning code

        card_collection_file = open(file_name, "r")
        field_names = card_collection_file.readline().rstrip().split(",")

        for item in card_collection_file:
            field_values = item.rstrip().split(",")
            card_collection_item = {}
            for index in range(len(field_values)):
                if (field_names[index] == "Available") or (field_names[index] == "Copies") or (field_names[index] == "ID"):
                    collection_item[field_names[index]] = int(field_values[index])
                else:
                    collection_item[field_names[index]] = field_values[index]
            card_collection[card_collection_item["ID"]] = card_collection_item

            max_id = max(max_id, card_collection_item["ID"])

        card_collection_file.close()

    except FileNotFoundError:
        print("File not found when attempting to read", file_name)
        return None
    except IOError:
        print("Error in data file when reading", file_name)
        return None

    return card_collection, max_id

def menu_prompts():
    print("Command      Function")
    print("  cci        Check in an card")
    print("  cco        Check out an card")
    print("  asc        Add a new sports card")
    print("  apc        Add a new pokemon card")
    print("  dsc        Display sports cards")
    print("  dpc        Display pokemon cards")
    print("  qsc        Query for sports cards")
    print("  qpc        Query for pokemon cards")
    print("  x          Exit")
    return input("Enter a command: ")

def main():

    card_library_collections, max_existing_id = load_card_collections()

    if card_library_collections is None:
        print("The collections did not load.")
        return
    else:
        print("The collections were loaded.")

    operation = menu_prompts()
    while operation != "x":
    # The function calls would need to be updated in this list
        if operation == "cci":
            check_in(card_library_collections)
        elif operation == "cco":
            check_out(card_library_collections)
        elif operation == "asc":
            max_existing_id = add_sports_card(library_collections["sports"], max_existing_id)
        elif operation == "apc":
            max_existing_id = add_pokemon_card(library_collections["pokemon"], max_existing_id)
        elif operation == "dsc":
            display_cards(card_library_collections["sports"])
        elif operation == "dpc":
            display_cards(card_library_collections["pokemon"])
        elif operation == "qsc":
            query_cards(card_library_collections["sports"])
        elif operation == "qpc":
            query_cards(card_library_collections["pokemon"])
        else:
            print("Invalid command")

        operation = menu_prompts()

def check_in(card_library_collections):

    card_id = int(input('Enter the ID for the card: '))
    library = card_library_collections['sports'] + card_library_collections['pokemon']

    for idx, item in enumerate(library):
        if item['ID'] != card_id:
            continue
        elif item['Available'] < item['Copies']:
            library[idx]['Available'] += 1
            print('Your check in has succeeded.')
            display_cards([library[idx]], sports_or_pokemon(library, idx))
            return
        elif item['Available'] == item['Copies']:
            print('All copies are already available, so this card cannot be checked in.')
            return
        else:
            print('Your card ID is invalid')

def check_out(card_library_collections):

    card_id = int(input('Enter the ID for the card you wish to check out: '))
    library = card_library_collections['sports'] + card_library_collections['pokemon']

    for idx, item in enumerate(library):
        if item['ID'] != card_id:
            continue
        elif item['Available'] > 0:
            library[idx]['Available'] -= 1
            print('Your check out has succeeded.')
            display_cards([library[idx]], sports_or_pokemon(library, idx))
            return
        elif item['Available'] == 0:
            print('No copies of the card are available for check out.')
            return
        else:
            print('Your card ID is invalid,')

def sports_or_pokemon(library, idx):

    return 'Sport' in library[idx]

def query_cards(card_collection, sports_or_pokemon_query):

    query_str = input('Enter a query string to use for the search: ')

    if len(query_str) == 0:
        print('Invalid query string.')
        return

    card_list = []
    query_str = query_str.lower()
    for idx, item in enumerate(card_collection):
        if (sports_or_pokemon_query and (query_str in item['Name'].lower() or query_str in item['Sport'].lower() or query_str in item['Publisher'].lower())):
            card_list.append(item)
        elif (not sports_or_pokemon_query and (query_str in item['Title'].lower() or query_str in item['Edition'].lower() or query_str in item['Generation'].lower())):
            card_list.append(item)

    display_cards(res, sports_or_pokemon_query)

def add_sports_card(card_library_collections, max_existing_id):

    print('Please enter the following attributes for the new sports card.')
    card_collection_list = {}

    max_existing_id += 1
    card_collection_list['ID'] = max_existing_id
    card_collection_list['Name'] = input('Name: ')
    card_collection_list['Sport'] = input('Sport: ')
    card_collection_list['Publisher'] = input('Publisher: ')
    card_collection_list['Series'] = input('Series: ')
    card_collection_list['Year'] = int(input('Year: '))
    card_collection_list['Copies'] = int(input('Copies: '))
    card_collection_list['Available'] = card_collection_list['Copies']

    print('You have entered the following details:')
    display_cards([card_collection_list], True)

    cancel_prompt = input("Press enter to add this item to the collection. Enter 'x' to cancel.")
    if(not cancel_prompt):
        card_library_collectionslibrary_collections['sports'].append(card_collection_item)
        return max_existing_id
    elif(cancel_prompt == 'x'):
        return max_existing_id - 1

def add_pokemon_card(card_library_collections, max_existing_id):
    print('Please enter the following attributes for the new card.')
    card_collection_list = {}

    max_existing_id += 1
    card_collection_list['ID'] = max_existing_id
    card_collection_list['Name'] = input('Name: ')
    card_collection_list['Edition'] = input('Edition: ')
    card_collection_list['Rarity'] = input('Rarity: ')
    card_collection_list['Generation'] = input('Generation: ')
    card_collection_list['Year'] = int(input('Year: '))
    card_collection_list['Copies'] = int(input('Copies: '))
    card_collection_list['Available'] = card_collection_list['Copies']

    print('You have entered the following data:')
    display_cards([card_collection_item], False)

    cancel_prompt = input("Press enter to add this item to the collection. Enter 'x' to cancel.")
    if(not cancel_prompt):
        card_library_collections['pokemon'].append(card_collection_item)
        return max_existing_id
    elif(cancel_prompt == 'x'):
        return max_existing_id - 1

def display_cards(items, sports_or_pokemon):

    if len(items) == 0 and sports_or_pokemon:
        print('No related sports cards are found.')
    elif len(items) == 0 and not sports_or_pokemon:
        print('No related pokemon cards are found.')
    else:
        for target in items:
            print('ID: {0}'.format(target['ID']))
            print('Name: {0}'.format(target['Name']))
            print('Year: {0}'.format(target['Year']))
            print('Copies: {0}'.format(target['Copies']))
            print('Available: {0}'.format(target['Available']))

            if(sports_or_pokemon):
                print('Sport: {0}'.format(target['Sport']))
                print('Publisher: {0}'.format(target['Publisher']))
                print('Series: {0}'.format(target['Series']))
            else:
                print('Edition: {0}'.format(target['Edition']))
                print('Rarity: {0}'.format(target['Rarity']))
                print('Generation: {0}'.format(target['Generation']))
            print('')

main()


text:
Q: How do I prevent the render function from outputting a file with Jquery functions I have an R script that calls the render function and outputs an HTML file. The HTML file opens and runs properly when manually opening it on my machine, but I'm also trying to use the HTML file in a subsequent function when I use it as the body of an email to be sent. This emailing function doesn't work, I think because the HTML file is too big - it has these huge Jquery functions.
I'm able to programmatically send an email using the HTML file after I've removed the Jquery functions, so that's why I think it's the length of the file that is the issue. I would copy the functions here, but they're long, more than 30,000 characters long.
I'm not familiar enough with Jquery or HTML to understand what the functions are doing. I looked through the documentation for render and tried playing around with the various parameters to try to remove these huge jquery functions but without any luck. Here's a small snippet of the functions:
<script>/*! jQuery v1.11.3 | (c) 2005, 2015 jQuery Foundation, Inc. | jquery.org/license */
!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.doc

Is there anything I can do to try to remove these? Any way to supress these? Where are they exactly generated from?


text:
Q: Angular2: Update all color assignments in CSS dynamically I have an angular 2 application in which I'd like to implement the ability for a user to choose their color theme from a list of predetermined color palettes. When they select  a theme, ALL relevant instances of color, background-color, etc will be changed to the corresponding new color from the theme palette. Is there any way to implement this from an Angular controller?
I know that you can conditionally add classes to specific elements using [class.className] or [ngClass] but obviously it is not practical to have to change the styles individually on every single attribute in a large application.
Specific use case: (click) listener attached to an "Update Theme" button is handled by a controller function used to change the css color values in .css file.
Has anyone implemented dynamic/user controlled themes/colors in Angular2? Any suggestions for how to approach this?

A: bro the angular material team has worked in a very cool feature.
https://github.com/angular/material2/blob/master/guides/theming.md
if you want to see a working example https://material.angular.io/ has a theme picker in the navbar.


text:
Q: Convert HDF4 MODIS to TIF I need to convert an hdf4 file by MODIS, the MOD13A3 v006 (NDVI Index). In particular, I'm interested in the block "h18v04", which is north-west Europe. You can download the example file I'm using in this question here (16 MB).
What I've done, taking inspiration by this already asked question, is the following python script:
import os

filename = "MOD13A3.A2019001.h18v04.006.2019038102530.hdf"
subdataset = 'HDF4_EOS:EOS_GRID:"MOD13A3.A2019001.h18v04.006.2019038102530.hdf"://MOD_Grid_monthly_1km_VI:"1 km monthly NDVI"'
f_out = "prova.tif"

s_srs = "+proj=sinu +R=6371007.181 +nadgrids=@null +wktext"
t_srs = "+proj=longlat +datum=WGS84 +no_defs"

command = 'gdalwarp -of GTiff -s_srs "' + s_srs + '" -r cubic -t_srs "' + t_srs + '" ' + subdataset + ' ' + f_out
os.system(command)

But it returns to me the following error:

Warning 1: Unknown type -1
ERROR 1: Input file
HDF4_EOS:EOS_GRID:MOD13A3.A2019001.h18v04.006.2019038102530.hdf://MOD_Grid_monthly_1km_VI:1
km monthly NDVI has no raster bands.

Giving gdalinfo, I get
gdalinfo HDF4_EOS:EOS_GRID:"MOD13A3.A2019001.h18v04.006.2019038102530.hdf"://MOD_Grid_monthly_1km_VI:"1 km monthly NDVI"

Warning 1: Unknown type -1

Driver: HDF4Image/HDF4 Dataset

Files: MOD13A3.A2019001.h18v04.006.2019038102530.hdf

       MOD13A3.A2019001.h18v04.006.2019038102530.hdf.aux.xml

Size is 0, 1

Metadata:

  ALGORITHMPACKAGEACCEPTANCEDATE=102004

  ALGORITHMPACKAGEMATURITYCODE=Normal

  ALGORITHMPACKAGENAME=MOD_PR13A3

  ALGORITHMPACKAGEVERSION=5

  ASSOCIATEDINSTRUMENTSHORTNAME.1=MODIS

  ASSOCIATEDPLATFORMSHORTNAME.1=Terra

  ASSOCIATEDSENSORSHORTNAME.1=MODIS

  AUTOMATICQUALITYFLAG.1=Passed

  AUTOMATICQUALITYFLAG.10=Passed

  AUTOMATICQUALITYFLAG.11=Passed

  AUTOMATICQUALITYFLAG.2=Passed

  AUTOMATICQUALITYFLAG.3=Passed

  AUTOMATICQUALITYFLAG.4=Passed

  AUTOMATICQUALITYFLAG.5=Passed

  AUTOMATICQUALITYFLAG.6=Passed

  AUTOMATICQUALITYFLAG.7=Passed

  AUTOMATICQUALITYFLAG.8=Passed

  AUTOMATICQUALITYFLAG.9=Passed

  AUTOMATICQUALITYFLAGEXPLANATION.1=No automatic quality assessment is
performed in the PGE

  AUTOMATICQUALITYFLAGEXPLANATION.10=No automatic quality assessment
is performed in the PGE

  AUTOMATICQUALITYFLAGEXPLANATION.11=No automatic quality assessment
is performed in the PGE

  AUTOMATICQUALITYFLAGEXPLANATION.2=No automatic quality assessment is
performed in the PGE

  AUTOMATICQUALITYFLAGEXPLANATION.3=No automatic quality assessment is
performed in the PGE

  AUTOMATICQUALITYFLAGEXPLANATION.4=No automatic quality assessment is
performed in the PGE

  AUTOMATICQUALITYFLAGEXPLANATION.5=No automatic quality assessment is
performed in the PGE

  AUTOMATICQUALITYFLAGEXPLANATION.6=No automatic quality assessment is
performed in the PGE

  AUTOMATICQUALITYFLAGEXPLANATION.7=No automatic quality assessment is
performed in the PGE

  AUTOMATICQUALITYFLAGEXPLANATION.8=No automatic quality assessment is
performed in the PGE

  AUTOMATICQUALITYFLAGEXPLANATION.9=No automatic quality assessment is
performed in the PGE

  CHARACTERISTICBINANGULARSIZE=30.0

  CHARACTERISTICBINSIZE=926.625433055556

  COMPOSITEMONTHNAME=January

  DATACOLUMNS=1200

  DATAROWS=1200

  DAYNIGHTFLAG=Both

  DAYSOFYEAR=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, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1

  DAYSPROCESSED=2019001, 2019002, 2019003, 2019004, 2019005, 2019006,
2019007, 2019008, 2019009, 2019010, 2019011, 2019012, 2019013,
2019014, 2019015, 2019016, 2019017, 2019018, 2019019, 2019020,
2019021, 2019022, 2019023, 2019024, 2019025, 2019026, 2019027,
2019028, 2019029, 2019030, 2019031, 2019032, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1

  DESCRREVISION=6.0

  EASTBOUNDINGCOORDINATE=15.5702026309755

  EVI1KMMONTHQCLASSPERCENTAGE=0

  EXCLUSIONGRINGFLAG.1=N

  GEOANYABNORMAL=False

  GEOESTMAXRMSERROR=50.0

  GLOBALGRIDCOLUMNS=43200

  GLOBALGRIDROWS=21600

  GRINGPOINTLATITUDE.1=39.8197706210566, 50.0069689864989,
49.9989721995752, 39.8144150819193

  GRINGPOINTLONGITUDE.1=0.000131401253181314, -0.00867479214979005,
15.5723926647109, 13.0379032886097

  GRINGPOINTSEQUENCENO.1=1, 2, 3, 4

  HDFEOSVersion=HDFEOS_V2.19

  HORIZONTALTILENUMBER=18

  identifier_product_doi=10.5067/MODIS/MOD13A3.006

  identifier_product_doi=10.5067/MODIS/MOD13A3.006

  identifier_product_doi_authority=http://dx.doi.org

  identifier_product_doi_authority=http://dx.doi.org

  INPUTFILENAME=MOD13A2.A2019001.h18v04.006.2019024152607.hdf,
MOD13A2.A2019017.h18v04.006.2019037160749.hdf

  INPUTPOINTER=MOD13A2.A2019001.h18v04.006.2019024152607.hdf,
MOD13A2.A2019017.h18v04.006.2019037160749.hdf

  INSTRUMENTNAME=Moderate-Resolution Imaging SpectroRadiometer

  LOCALGRANULEID=MOD13A3.A2019001.h18v04.006.2019038102530.hdf

  LOCALVERSIONID=5.2.2

  LONGNAME=MODIS/Terra Vegetation Indices Monthly L3 Global 1km SIN
Grid

  NDVI1KMMONTHQCLASSPERCENTAGE=0

  NORTHBOUNDINGCOORDINATE=49.9999999955098

  NUMBEROF16DAYPERIODS=2

  NUMBEROFDAYS=31

  PARAMETERNAME.1=1 km monthly NDVI

  PARAMETERNAME.10=1 km monthly relative azimuth angle

  PARAMETERNAME.11=1 km monthly pixel reliability

  PARAMETERNAME.2=1 km monthly EVI

  PARAMETERNAME.3=1 km monthly VI Quality

  PARAMETERNAME.4=1 km monthly red reflectance

  PARAMETERNAME.5=1 km monthly NIR reflectance

  PARAMETERNAME.6=1 km monthly blue reflectance

  PARAMETERNAME.7=1 km monthly MIR reflectance

  PARAMETERNAME.8=1 km monthly view zenith angle

  PARAMETERNAME.9=1 km monthly sun zenith angle

  PERCENTLAND=73

  PGEVERSION=6.0.3

  PROCESSINGCENTER=MODAPS

  PROCESSINGENVIRONMENT=Linux minion7032 3.10.0-957.5.1.el7.x86_64 #1
SMP Fri Feb 1 14:54:57 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux

  PRODUCTIONDATETIME=2019-02-07T15:25:30.000Z

  QAPERCENTCLOUDCOVER.1=11

  QAPERCENTCLOUDCOVER.10=11

  QAPERCENTCLOUDCOVER.11=11

  QAPERCENTCLOUDCOVER.2=11

  QAPERCENTCLOUDCOVER.3=11

  QAPERCENTCLOUDCOVER.4=11

  QAPERCENTCLOUDCOVER.5=11

  QAPERCENTCLOUDCOVER.6=11

  QAPERCENTCLOUDCOVER.7=11

  QAPERCENTCLOUDCOVER.8=11

  QAPERCENTCLOUDCOVER.9=11

  QAPERCENTGOODQUALITY=50

  QAPERCENTINTERPOLATEDDATA.1=100

  QAPERCENTINTERPOLATEDDATA.10=100

  QAPERCENTINTERPOLATEDDATA.11=100

  QAPERCENTINTERPOLATEDDATA.2=100

  QAPERCENTINTERPOLATEDDATA.3=100

  QAPERCENTINTERPOLATEDDATA.4=100

  QAPERCENTINTERPOLATEDDATA.5=100

  QAPERCENTINTERPOLATEDDATA.6=100

  QAPERCENTINTERPOLATEDDATA.7=100

  QAPERCENTINTERPOLATEDDATA.8=100

  QAPERCENTINTERPOLATEDDATA.9=100

  QAPERCENTMISSINGDATA.1=0

  QAPERCENTMISSINGDATA.10=0

  QAPERCENTMISSINGDATA.11=0

  QAPERCENTMISSINGDATA.2=0

  QAPERCENTMISSINGDATA.3=0

  QAPERCENTMISSINGDATA.4=0

  QAPERCENTMISSINGDATA.5=0

  QAPERCENTMISSINGDATA.6=0

  QAPERCENTMISSINGDATA.7=0

  QAPERCENTMISSINGDATA.8=0

  QAPERCENTMISSINGDATA.9=0

  QAPERCENTNOTPRODUCEDCLOUD=0

  QAPERCENTNOTPRODUCEDOTHER=0

  QAPERCENTOTHERQUALITY=50

  QAPERCENTOUTOFBOUNDSDATA.1=0

  QAPERCENTOUTOFBOUNDSDATA.10=0

  QAPERCENTOUTOFBOUNDSDATA.11=0

  QAPERCENTOUTOFBOUNDSDATA.2=0

  QAPERCENTOUTOFBOUNDSDATA.3=0

  QAPERCENTOUTOFBOUNDSDATA.4=0

  QAPERCENTOUTOFBOUNDSDATA.5=0

  QAPERCENTOUTOFBOUNDSDATA.6=0

  QAPERCENTOUTOFBOUNDSDATA.7=0

  QAPERCENTOUTOFBOUNDSDATA.8=0

  QAPERCENTOUTOFBOUNDSDATA.9=0

  QAPERCENTPOORQ1KMMONTHEVI=0, 47, 15, 6, 10, 11, 5, 4, 2, 0, 0, 0, 0,
0, 0, 0

  QAPERCENTPOORQ1KMMONTHNDVI=0, 47, 15, 6, 10, 11, 5, 4, 2, 0, 0, 0,
0, 0, 0, 0

  QA_STRUCTURE_STYLE=C5 or later

  RANGEBEGINNINGDATE=2019-01-01

  RANGEBEGINNINGTIME=00:00:00

  RANGEENDINGDATE=2019-01-31

  RANGEENDINGTIME=23:59:59

  REPROCESSINGACTUAL=reprocessed

  REPROCESSINGPLANNED=further update is anticipated

  SCIENCEQUALITYFLAG.1=Not Investigated

  SCIENCEQUALITYFLAG.10=Not Investigated

  SCIENCEQUALITYFLAG.11=Not Investigated

  SCIENCEQUALITYFLAG.2=Not Investigated

  SCIENCEQUALITYFLAG.3=Not Investigated

  SCIENCEQUALITYFLAG.4=Not Investigated

  SCIENCEQUALITYFLAG.5=Not Investigated

  SCIENCEQUALITYFLAG.6=Not Investigated

  SCIENCEQUALITYFLAG.7=Not Investigated

  SCIENCEQUALITYFLAG.8=Not Investigated

  SCIENCEQUALITYFLAG.9=Not Investigated

  SCIENCEQUALITYFLAGEXPLANATION.1=See
http://landweb.nascom.nasa.gov/cgi-bin/QA_WWW/qaFlagPage.cgi?sat=terra
for the product Science Quality status.

  SCIENCEQUALITYFLAGEXPLANATION.10=See
http://landweb.nascom.nasa.gov/cgi-bin/QA_WWW/qaFlagPage.cgi?sat=terra
for the product Science Quality status.

  SCIENCEQUALITYFLAGEXPLANATION.11=See
http://landweb.nascom.nasa.gov/cgi-bin/QA_WWW/qaFlagPage.cgi?sat=terra
for the product Science Quality status.

  SCIENCEQUALITYFLAGEXPLANATION.2=See
http://landweb.nascom.nasa.gov/cgi-bin/QA_WWW/qaFlagPage.cgi?sat=terra
for the product Science Quality status.

  SCIENCEQUALITYFLAGEXPLANATION.3=See
http://landweb.nascom.nasa.gov/cgi-bin/QA_WWW/qaFlagPage.cgi?sat=terra
for the product Science Quality status.

  SCIENCEQUALITYFLAGEXPLANATION.4=See
http://landweb.nascom.nasa.gov/cgi-bin/QA_WWW/qaFlagPage.cgi?sat=terra
for the product Science Quality status.

  SCIENCEQUALITYFLAGEXPLANATION.5=See
http://landweb.nascom.nasa.gov/cgi-bin/QA_WWW/qaFlagPage.cgi?sat=terra
for the product Science Quality status.

  SCIENCEQUALITYFLAGEXPLANATION.6=See
http://landweb.nascom.nasa.gov/cgi-bin/QA_WWW/qaFlagPage.cgi?sat=terra
for the product Science Quality status.

  SCIENCEQUALITYFLAGEXPLANATION.7=See
http://landweb.nascom.nasa.gov/cgi-bin/QA_WWW/qaFlagPage.cgi?sat=terra
for the product Science Quality status.

  SCIENCEQUALITYFLAGEXPLANATION.8=See
http://landweb.nascom.nasa.gov/cgi-bin/QA_WWW/qaFlagPage.cgi?sat=terra
for the product Science Quality status.

  SCIENCEQUALITYFLAGEXPLANATION.9=See
http://landweb.nascom.nasa.gov/cgi-bin/QA_WWW/qaFlagPage.cgi?sat=terra
for the product Science Quality status.

  SEAPROCESSED=Yes

  SHORTNAME=MOD13A3

  SOUTHBOUNDINGCOORDINATE=39.9999999964079

  SPSOPARAMETERS=2749, 4334, 2749a, 4334a

  TileID=51018004

  VERSIONID=6

  VERTICALTILENUMBER=04

  WESTBOUNDINGCOORDINATE=0.0

Can you help me?


text:
Q: Can I set the default order on the Table class on cakephp3 In CakePHP 2.x there was a property $order in Models. So I used this property to order my data globally. So for example assuming that I need to show a select box with countries on a view in my Country model used to add the line:
$order = 'Country.country DESC';

and then when I fetched the countries from any controller the data where ordered by the country name and not by the id or any other field. This was very helpful specially for the select boxes. On CakePHP 3.x I can't seem to find any similar reference at the documentation.
Is there anything that I can do to have my data sorted globally when I fetch them and not use the order option in each find?

A: Just add your beloved property back and use the beforeFind() callback in the Table object to add the value from the property to the query.
Or just create a custom finder:
public function findOrdered(Query $query, $options) {
    return $query->order([
        $this->alias() . '.name' => 'ASC'
    ]);
}

And use it
$this->find('list')->find('ordered')->all();

Or create an ordered list find that returns the whole ordered list.
public function findOrderedList(Query $query, $options) {
    return $this->findList($query, $options)
    ->order([
        $this->alias() . '.name' => 'ASC'
    ]);
}

Or overload the findList() method directly and call the parent.
Or if your find() gets called via a relationship, you can set the default order for the relationship by using the sort option.
$this->hasMany('AuditLogs', [
    'sort' => [
        'AuditLogs.timestamp' => 'desc',
    ],
]);

A: You can override findAll method in your table class.
public function findAll(Query $query, array $options)
{
    return $query->order(['Country.country' => 'DESC']);
}

A: CakePHP3.x:
If you would like to sort the data in your model for every query related to this model, you can simple order the query in the model file via beforeFind:
public function beforeFind(Event $event, Query $query, $options, $primary) {

    $query->order(['Model.field' => 'ASC']);
    return $query;

}

A: According to the official docs, see cakephp book, you can add a public variable to the controller object in order to set the default sort order:
class InvoicesController extends AppController
{
    public $paginate = [
        'order' => [
                'Invoices.id' => 'desc'
        ]
    ];

....

A: In CakePHP 3.x, if you want so set default order for every query of a model, then you can place following code in your table:
public function beforeFind ($event, $query, $options, $primary)
{
    $order = $query->clause('order');
    if ($order === null || !count($order)) {
        $query->order( [$this->alias() . '.sort_field_name' => 'sort_order'] );
    }
}

If any order set from outside, it skip the default order. Otherwise, it will always sort by sort_field_name according sort_order.


text:
Q: generic method to handle a number of specific classes I need to write method that can create an object based on the return type. The return type will be one one of small number of types known at compile time (although I'll happily accept a run time solution).
If it matters, the types are numeric but not primitive types, e.g. a half precision float, and won't all inherit from Number (or similar). (Can I create a base type that delineates a specific set of subtypes?)
I need to something like
object Thing {
   def apply[T](size: Int): Thing[T] = {

     // The call to makeBuffer[T] is inside another generic.
     // I know there are only a limited number types that T can be
     // so I can implement them individually but the compiler does
     // not know this so it fails to compile
     val buffer = makeBuffer[T](size)

     // more stuff including calling 3rd party generic APIs
     // that depend on T
   }

   private def [T]makeBuffer(size: Int): Buffer[T] = {
      // What do I put here to build and return the correct Buffer?
   }

   abstract class Buffer[T](size: Int) {
    def doStuff
   }

   // I can implement the small number of concrete classes that I need
   class FloatBuffer(size: Int) extends Buffer[T](size) {
    override def doStuff = // Allocate a buffer with size bytes
   }
}

I don't know how to

*

*explain to the compiler that I know what types T will be.

*return the appropriate implementation

Runtime solutions I've seen, based on TypeTags or using match, need an input argument to carry the type information which I don't have in this case.

A: First of all, Thing is an object, and so your return type for apply cannot be Thing.
Also, Thing does not take generic parameters, so you can't return a Thing[T].
    case class Thing[T](buffer: Thing.Buffer[T])

    object Thing {

        def apply[T](size: Int, clazz: Class[T]): Thing[T] = {

            // The call to makeBuffer[T] is inside another generic.
            // I know there are only a limited number types that T can be
            // so I can implement them individually but the compiler does
            // not know this so it fails to compile
            val result = Thing(makeBuffer(size, clazz))

            // more stuff including calling 3rd party generic APIs
            // that depend on T

            return result
        }

        private def makeBuffer[T](size: Int, clazz: Class[T]): U forSome {type U <: Buffer[T]} = {
            //limited number of classes, so this is probably possible:
            val float = classOf[Float]
            clazz match {
                case `float` => new FloatBuffer(10).asInstanceOf
                //and other types too
            }
        }

        abstract class Buffer[T](size: Int) {
            def doStuff
        }

        // I can implement the small number of concrete classes that I need
        class FloatBuffer(size: Int) extends Buffer[Float](size) {
            override def doStuff = apply(size, classOf[Float])// Allocate a buffer with size bytes
        }
    }

If you have an actual instance of whatever type you want to store in the buffer and all of your limited types share a method, then you can use structural typing. Your example isn't clear, though.

A: I think it is just asking to much for the compiler to understand what the generic types will be. I've found the following run time solution:
import scala.reflect.runtime.universe._

object StupidTypes {

  private abstract class LoadableBuffer(size: Int) {
    type T
    // actual code omitted for brevity
  }

  private class LoadableFloatBuffer(size: Int) extends LoadableBuffer(size) {
    type T = Float
    // actual code omitted for brevity
  }

  private class LoadableDoubleBuffer(size: Int) extends LoadableBuffer(size) {
    type T = Double
    // actual code omitted for brevity
  }

  def main(args: Array[String]): Unit = {
    makeBuffer[Float](1)
    makeBuffer[Double](1)
    makeBuffer[Int](1)
  }

  private def makeBuffer[T: TypeTag](size: Int): LoadableBuffer = {
    typeOf[T] match {
      case t if t =:= typeOf[Float] => new LoadableFloatBuffer(size)
      case t if t =:= typeOf[Double] => new LoadableDoubleBuffer(size)
      case _ => throw new Exception("no can do")
    }
  }
}


text:
Q: Don't show "my review history" link or change it to "full review history" if I'm already on it We have question about similar issue for users with rep < 10k (those members can't see full history, so there is no sense to show them "my review history"  link at all): Don't show the 'my review history' link if that's all I can see
But also currently I can see this button even if I'm already on it.
So:

*

*Don't show it if member don't have access to the full revision history (<10r rep).

*Change the link to "full review history" if currently I'm on "my reviews" page.


text:
Q: Grails, ORM, Quartz, Jobs, I'm working with Grails 3.0.12, I'm using Quartz to execute a job, what I try to do now is to send an email every time (In this case every 5 seconds). I have email Service in my Services folder. This is my code:
class EnviaCorreosJob{
NotifierService notificar
Integer diasParaCorreo = 30

static triggers =
{
    cron name: 'myTrigger', cronExpression: "*/5 * * * * ?"
}
def group = "MyGroup"
def description = "Example job with Cron Trigger"
def fechaHoy = new Date()

def execute()
{
    println "------------------ Running every 5 seconds -------------------"

    def queryAgenda = Agenda.where
    {
        inicio_cita <= (fechaHoy + diasParaCorreo)
    }
    def listaAgenda = queryAgenda.list()
    println "----------------------Dates list : " + listaAgenda

    log.info "listaAgenda: " + listaAgenda
    log.info "listaAgendaTamaño: " + listaAgenda.size()

    listaAgenda.each
    {
        agenda ->

        println "it's inside"

        mailService.sendMail
        {
            to "xxxxxx@gmail.com"
            subject "hello"
            body "hello"
        }
    }
}
}

I tried to make an instance of Service class to call mailService.sendMail but didn't work.
Thanks so much for your help. :)

A: It looks like you are trying to use the mail plugin in your job but you haven't injected the mail service into your Job.
Add:
def mailService

To your class and it will be injected and useable. More on service injection can be found here https://grails.github.io/grails-doc/latest/guide/single.html#dependencyInjectionServices
More info on configuring and using the mail plugin is here - https://grails.org/plugins.html#plugin/mail

A: Here is how I have done something similar, sending emails from files within a directory using the @Scheduled annotation.
EmailService emailService

static boolean lazyInit = false
@Scheduled(fixedDelay = 3000L, initialDelay = 2000L)
void executeEveryFourtyFive() {

dire = new File(configfilepath)
dire.eachFileRecurse (FileType.FILES) { fileEmail ->
listEmail << fileEmail
}

listEmail.each {
filepath = it.path
sourceFolder = new File(filepath)

   if (sourceFolder.exists()){
    String fileContents = new File(filepath).text
       def emailaddress = emailaddress

    def emailmessage = message
    def emailtitle = title

    def emailsubject = subject
    def emailfrom = emailfrom
 emailService.send(emailaddress,emailmessage,emailsubject...)
   }
 }
 }catch(Exception exc){
      exc.printStackTrace()
    }
  }else{
   println "++++++++++email service off++++++++++"
 }
 }

And then I have my emailService to do the rest. Hope it helps someone.


text:
Q: The meaning of "did not immediately respond to requests for comment" This expression is included in many news stories but to me, it's frustratingly vague.
I see these as "weasel words" - some journalist leaves a voice mail for someone, waits 10 seconds for a callback then goes to press saying there was no immediate response.
From a journalistic perspective, what is the true meaning of this expression? Is the meaning deliberately vague to sensationalize the news?

A: No, it is not meant in a pejorative sense.
Journalists report on events as they occur. It is always helpful to get additional input from parties involved, e.g. family, employer, public relations representative, attorney, or experts. Sometimes that isn't possible, because the event just occurred, and has been confirmed by authorities. If the event or situation is newsworthy, journalists must report on it, rather than waiting until they get a response from whomever they contacted for additional information.
These are not "weasel words". In fact, good news media reports often republish the story with one or more updates, as responses to comment requests are received. Reuters is particularly good about doing that, occasionally multiple times for a news story! Both Thomson Reuters and the BBC have guidelines on requests for comment.
Via Reuters Handbook of Journalism excerpt, "Vetting"

Give the other side every opportunity to comment. If you don't elicit
  a comment in an initial contact, call again. Record all the times you
  tried to contact them. If they decline to comment, note that down.

and excerpt, "Legal":

When a key subject, company or institution declines to comment,
  provide its point of view. Preferably, this would come from a
  credible, on-the-record source; at the very least, provide contextual
  information that may put things in a more neutral light.

Via BBC Editorial Guidelines - Right of Reply excerpt:

Providing a fair opportunity to reply to allegations requires
  providing enough time to make a response. The amount of time that is
  fair will change according to circumstances, including... whether
  there is a pressing need to broadcast in the public interest; the
  nature of the subject and their resources...a large corporation with a
  sizable PR operation may be expected to respond quicker than a small
  business with just a few employees or an individual.

A: It sounds to me like coded language, indicating that the writer believes that the party concerned has no available comment.
Journalism is full of code. One of the most notorious clichés is found in such as the following:
'The body of the murdered schoolteacher was found at an address in east London. A 45-year-old woman is helping police with their inquiries'.
Invariably it means that the police have got their suspect but because he or she is yet to be formally charged they, the newspaper, cannot legally provide the name or the fact that they are a suspect.


text:
Q: Terraform Kubernetes - Remove annotation I'm trying to configure AWS EKS & Fargate. By default, the CoreDNS add-on is configured to run on EC2 nodes hence I have to remove it (annotation) so that Fargate (worker node) can pick it up, this step is officially stated here. This whole thing should be automated using Terraform. The said step can be achieved using Terraform's Kubernetes provider. However, I can't find any article/doc saying how to target certain values in ignore_annotations.
On the EKS & Fargate doc, it says I have to run the ff command to remove annotation:
kubectl patch deployment coredns \
    -n kube-system \
    --type json \
    -p='[{"op": "remove", "path": "/spec/template/metadata/annotations/eks.amazonaws.com~1compute-type"}]'

and in the Terraform Kubernetes provider doc, the configuration should look like the ff:
provider "kubernetes" {
  ignore_annotations = [
    "^service\\.beta\\.kubernetes\\.io\\/aws-load-balancer.*",
  ]
}

I tried the ff configuration but it didn't work (annotation is not removed):
provider "kubernetes" {
  host                   = module.eks.cluster_endpoint
  cluster_ca_certificate = module.eks.cluster_certificate_authority_data
  exec {
    api_version = "client.authentication.k8s.io/v1alpha1"
    args        = ["eks", "get-token", "--cluster-name", module.eks.cluster_id]
    command     = "aws"
  }

  ignore_annotations = [
    "eks\\.amazonaws\\.com\\/compute-type",
  ]
}

perhaps I have the ignore_annotations value wrong?


text:
Q: Unwanted DB2 timeout when using command chaining I am using the IBM DB2 driver for .NET with command chaining.
I first open a DB2Connection and start a transaction. Then I call DB2Connection.BeginChain on my connection to start a bulk insert. I execute a bunch of prepared statements with 0 as the DB2Command.CommandTimeout. Last, I call DB2Connection.EndChain and commit the transaction.
I expect some of the inserts to fail due to duplicate key errors. I trap this by catching a DB2Exception and inspecting the DB2Exception.Errors collection. I know which row failed because I can look at the DB2Error.RowNumber inside the Errors collection.
The problem is that sometimes I trap a DB2Exception when I call DB2Connection.EndChain and the affected row number is negative.
[IBM][DB2] SQL0952N  Processing was cancelled due to an interrupt.  SQLSTATE=57014
Searching the DB2 documentation for this error seems to indicate that a query has timed out. I didn't see any information how this relates to chaining. Did the entire chain process time out or was it a problem with an individual query? If the later, then why didn't I get a valid row number? Why am I timing out at all if my DB2Connection.ConnectionTimeout is 0 and my DB2Command.CommandTimeout is 0?


text:
Q: EF RemoveRange throws exception when given an empty list I'm calling RemoveRange on an EF6 context but if the argument happens to be an empty enumeration it throws the following.
"Adding a relationship with an entity which is in the Deleted state is not allowed."
It seems very odd to me. Any ideas as to what is going on?


text:
Q: Mass Update in Oracle via stored procedre I have to do a mass update. So I have wriiten a procedure.
CREATE OR REPLACE PROCEDURE or_doh_rcause_sm_wip_upd_sp (
   p_rcause_cd   VARCHAR2,
   p_doh_sa           clob
)
IS
v_plant_cd              VARCHAR2 (8);
v_doh_sa                NUMBER          := 0;
v_ins_upd               CHAR(1);
Begin
for i in (select regexp_substr( p_doh_sa, '[^;]+', 1, rownum) result
          from dual
         connect by level <= length(regexp_replace( p_doh_sa, '[^;]+')) + 1)
   LOOP
    v_doh_sa     := TO_NUMBER(substr( i.result||',', 1, instr(i.result,',')-1 ),'9999999999999999999') ;
    v_ins_upd    := substr(i.result, instr(i.result,',',1)+1,1);
    v_plant_cd   := substr( i.result,instr(i.result,',',1,2)+1 );

IF v_ins_upd = 'U' THEN

           update OR_DOH_PM_SM_ROOT_CAUSE_T set ROOT_CAUSE_SA = p_rcause_cd
           where DOH_SA = v_doh_sa
           AND   Plant_cd = v_plant_cd;
END IF;
END LOOP;
END;

Eg:p_doh_sa:'942168,I,FV52;942167,I,FV52;';
Like this i will have more than 500 sets. When from the front end if they run
getting error ORA-01460: unimplemented or unreasonable conversion requested
Please let me know how to solve this.

A: REGEXP_SUBSTR on a CLOB will return a CLOB. SUBSTR on a CLOB will also return a CLOB. But TO_NUMBER will not work on a CLOB . So you should add a TO_CHAR which always return a VARCHAR2 and that should do the trick.


text:
Q: Multivariate hierarchical linear model via nlme I'm running a multivarialte repeated measures hierarchical linear model in r's nlme package. I have three dependent variables D1, D2, and D3.
My variable structure is such that a time point is nested within a participant, which is nested within their respective group.
A snapshot of my data is below:

In order to bring this to a multivariate space, I've dummy coded my three dependent variables, as per this tutorial
However, I'm having trouble conceptualizing the model with three nests, rather than 2. I've come up with two possible solutions and could use someone's help in determining which one is implementing the correct structure (i.e., group/id/time)
Thus, my possible equations are:
model <- lme(value ~ 0 + D1:Time + D2:Time + D3:Time, random = ~0 + D1:Time + D2:Time + D3:Time | Group/ID , data = Fixed_Data)

or
model <- lme(value ~ 0 + D1 + D2 + D3, random = ~0 + D1 + D2 + D3| Group/ID/Time , data = Fixed_Data)

Am I on the right track for either of these solutions?
Thanks for the help?


text:
Q: Laravel Airlock Token Introduction/Background
I'm looking to enable token authentication for multiple microservices and users. Both applications and users are $user objects.
I need to be able to authenticate once (hence token) using an auth server on a subdomain. I then need to be able to pass around a token that can be managed (revoked/refreshed whatever) by the Auth server.
The microservices are Laravel based, so using Airlock makes sense. Airlock generates tokens easily using:

*

*$token = $user->createToken(now())
However, I see no method to manually check the validity of these tokens... So I assumed they are available in the database.
Airlock suggests that the token be returned as follows:

*

*$token->plainTextToken
This produces a token, as expected. To my understanding, this is a public facing token. It does not match the token in the personal_access_tokens table.
Lets call these PublicToken and PrivateToken.
The private token is actually located in:

*

*$token->accessToken->token
I want to be able to manually switch between a PublicToken. I assume Airlock is doing some security here.. and I want to invoke these secure methods required to check a PublicToken against the PrivateToken.
Please do not say "it's in middleware" ... The point is that I have multiple microservices and usertypes sharing a database. I have an auth server that will end up on secure architecture, and some of the other microservices wont be.... fundamentally I need to do a manual authentication because normal plug and play wont work. Using Airlock as the foundation is great. But I need to be able to know how to convert between public and private tokens.
Essentially I'm looking for the real version of the following psuedocode:

*

*if( someTranslationFunction($public_token) == $private_token ) ...
TLDR: The problem
How do I validate a $token->plainText value against a $token manually?


text:
Q: send parameter to 2 webparts on the page, preferably with Ajax? In SharePoint Server 2010, We have a List with items and their details.  User profiles have an  indexed field that contains items matching the list titles.
I want to display a dataview with just the item titles- When the user clicks the title I want to send the selected row to a connected webpart that will display all the details for the selected item AND ALSO to send the title of the selected row to a PeopleSearch Results webpart on the page and perform the search.  Preferably all this would be done with AJAX/without a postback.
I can connect the titles to the details, but I don't know how to ALSO update the search results.
I want to do this w/o any custom webparts.  I'm OK with using javascript/jquery.
Any suggestions?
Thanks

A: I'd definitely go with jQuery if you don't want a postback. You won't be able to do anything with Web Part Connections without that postback, but you can call the Lists and Query Web Services and probably accomplish what you describe. Take a look at SPServices for this: http://spservices.codeplex.com


text:
Q: How do i optimise my python code which reads Battery Staus Basically i was trying to make a Py script what runs in background to notify the user when to plug in the charger and when to disconnect
the problem which i am facing is with the performance,The script uses more CPU time(May be because i used while loop)
Tell me if there is any better method to handle such a scenario.
I have already tried using sleep time but that did not work.
class Battery_code:

    def __init__(self, c_var):
        self.c_var = c_var

    def mbox(self, title, text, style):
        return Custom.windll.user32.MessageBoxW(0, text, title, style)

    while 1:
        battery = Reader.sensors_battery()
        plugged = battery.power_plugged
        percent = str(battery.percent)
        if plugged is False and int(percent) in range(40, 80, 1) and c_var == 0:
            speak.Speak("Charger is Disconnected Now")
            c_var += 1
            time.sleep(2)
        if plugged is True and int(percent) in range(40, 80, 1) and c_var == 0:
            speak.Speak("Charger is Connected Now")
            c_var += 1
            time.sleep(2)
        if plugged is True and int(percent) > 80:
            mbox('',
                 'Battery is at [' + percent + '%] and Still Plugged Please Unplug ', 0)
            speak.Speak("Please Unplug the charger to increase battery life")
            c_var = 0
        if plugged is False and int(percent) < 40:
            mbox('',
                 'Battery is at [' + percent + '%] Please Connect Charger  ', 0)
            speak.Speak("Please Connect charger to increase battery life")
            c_var = 0
    time.sleep(3)

A: use "battery.secsleft" to figure out how much time the user has left.
Then with some simple math you can figure out when to give the alert and sleep until then.
Of course, this can vary by usage, so you can use some extra padding for the time.
Also, in cases:
if plugged is True and int(percent) > 80:
and
if plugged is False and int(percent) < 40:
you forgot to use sleep.