问:
Android: Sugar ORM No Such Table Exception
I am getting the No Such table exception when i am Using Sugar ORM with GPU image Android Library. I am using Gradle and Android Studio. Once i remove GPU image this issue is solved. So i don't know whats causing this exception. Details about this exception are also being discussed in this git issue
and it seems a lot of people are still facing it.

My crash log is posted below

```<code>> 10-09 11:30:21.511 4326-4831/com.example.app E/SQLiteLog: (10) Failed
> to do file read, got: 0, amt: 100, last Errno: 2 10-09 11:30:26.506
> 4326-4831/com.example.app E/SQLiteLog: (1) no such table: IMAGE 10-09
> 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime: FATAL
> EXCEPTION: AsyncTask #1 10-09 11:30:26.516 4326-4831/com.example.app
> E/AndroidRuntime: java.lang.RuntimeException: An error occured while
> executing doInBackground() 10-09 11:30:26.516
> 4326-4831/com.example.app E/AndroidRuntime:     at
> android.os.AsyncTask$3.done(AsyncTask.java:299) 10-09 11:30:26.516
> 4326-4831/com.example.app E/AndroidRuntime:     at
> java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> java.util.concurrent.FutureTask.setException(FutureTask.java:219)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> java.util.concurrent.FutureTask.run(FutureTask.java:239) 10-09
> 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 10-09
> 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> java.lang.Thread.run(Thread.java:838) 10-09 11:30:26.516
> 4326-4831/com.example.app E/AndroidRuntime:  Caused by:
> android.database.sqlite.SQLiteException: no such table: IMAGE (code
> 1): , while compiling: SELECT * FROM IMAGE 10-09 11:30:26.516
> 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native
> Method) 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:
> at
> android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:886)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:497)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37) 10-09
> 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1161)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1032)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1238)
</code>```

答:
Please check this property

```<code>    <`meta-data android:name="DOMAIN_PACKAGE_NAME" android:value="trending.hashtags.pojo" />`
</code>```

This should be exactly where your POJO class is not the package name only.

Body:
I am getting the No Such table exception when i am Using Sugar ORM with GPU image Android Library. I am using Gradle and Android Studio. Once i remove GPU image this issue is solved. So i don't know whats causing this exception. Details about this exception are also being discussed in this git issue
and it seems a lot of people are still facing it.

My crash log is posted below

> 10-09 11:30:21.511 4326-4831/com.example.app E/SQLiteLog: (10) Failed
> to do file read, got: 0, amt: 100, last Errno: 2 10-09 11:30:26.506
> 4326-4831/com.example.app E/SQLiteLog: (1) no such table: IMAGE 10-09
> 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime: FATAL
> EXCEPTION: AsyncTask #1 10-09 11:30:26.516 4326-4831/com.example.app
> E/AndroidRuntime: java.lang.RuntimeException: An error occured while
> executing doInBackground() 10-09 11:30:26.516
> 4326-4831/com.example.app E/AndroidRuntime:     at
> android.os.AsyncTask$3.done(AsyncTask.java:299) 10-09 11:30:26.516
> 4326-4831/com.example.app E/AndroidRuntime:     at
> java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> java.util.concurrent.FutureTask.setException(FutureTask.java:219)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> java.util.concurrent.FutureTask.run(FutureTask.java:239) 10-09
> 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 10-09
> 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> java.lang.Thread.run(Thread.java:838) 10-09 11:30:26.516
> 4326-4831/com.example.app E/AndroidRuntime:  Caused by:
> android.database.sqlite.SQLiteException: no such table: IMAGE (code
> 1): , while compiling: SELECT * FROM IMAGE 10-09 11:30:26.516
> 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native
> Method) 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:
> at
> android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:886)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:497)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37) 10-09
> 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1161)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1032)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1238)

Body:
Please check this property

    <`meta-data android:name="DOMAIN_PACKAGE_NAME" android:value="trending.hashtags.pojo" />`

This should be exactly where your POJO class is not the package name only.


来源: stackexchange

问:
Unassigned variable in Unity
I've just started learning Unity 2D with the "How to make a 2D game" course from Brackeys on YouTube about 3 hrs ago. I'm using Unity 2018.4.1f1 on Ubuntu 18.04, and because JS is not supported in my version so I have to use C# instead. But I've encountered this error on the third video: The variable mainCam of GameSetup has not been assigned. This is my code in C#:

GameSetup.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameSetup : MonoBehaviour
{
    public Camera mainCam;

    public BoxCollider2D topWall, bottomWall, leftWall, rightWall;

    public Transform Player1, Player2;

    // Start is called before the first frame update
    void Start()
    {
        // topWall = GetComponent<BoxCollider2D>();
        // mainCam = GetComponent<Camera>();
        // If I uncomment this, there would be a new error: There is no 'Camera' attached to '_GM' game object, but a script is trying to access it.
    }

    // Update is called once per frame
    void Update()
    {
        // Move each wall to its edge location
        topWall.size = new Vector2(mainCam.ScreenToWorldPoint(new Vector3(Screen.width * 2.0f, 0f)).x, 1.0f);
        topWall.offset = new Vector2(0f, mainCam.ScreenToWorldPoint(new Vector3(0f, Screen.width, 0f)).y + 0.5f);
    }
}

```

<p>With the help of Google, I've add <code>rb2d.GetComponent<Rigibody2D>()</code> in <code>Start()</code> from the script of the second video under and prevent the error (there are no <code>Start()</code> in the video)</p>

<p>PlayerControls.cs</p>

<pre class="lang-cs prettyprint-override"><code>
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerControls : MonoBehaviour
{

    public KeyCode moveUp, moveDown;

    public float speed = 10;

    private Rigidbody2D rb2d = new Rigidbody2D();
    // Start is called before the first frame update
    void Start()
    {
        rb2d = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(moveUp))
        {
            Vector3 v = rb2d.velocity;
            v.y = speed;
            rb2d.velocity = v;
            // rb2d.velocity.y = speed;
        }
        else if (Input.GetKey(moveDown))
        {
            Vector3 v = rb2d.velocity;
            v.y = speed * (-1);
            rb2d.velocity = v;
        }
        else
        {
            Vector3 v = rb2d.velocity;
            v.y = 0;
            rb2d.velocity = v;
        }
    }
}
</code>```

How can I fix the bug in GameSetup.cs ? I've done exactly what said in the video, but only changed the language from JS to C#

答:
Either assign it null:

```<code>public Camera mainCam = null;
</code>```

But you are most likely missing to attach a camera object to it in the Unity3D editor. Check your inspector and make sure that whatever object that is using this script(GameSetup.cs) has a camera object assigned to its public variable.

Should look something like this. You have to drag and drop a camera object to the Gameobject.

ContentLicense: CC BY-SA 4.0

Title: Unassigned variable in Unity

Body:
I've just started learning Unity 2D with the "How to make a 2D game" course from Brackeys on YouTube about 3 hrs ago. I'm using Unity 2018.4.1f1 on Ubuntu 18.04, and because JS is not supported in my version so I have to use C# instead. But I've encountered this error on the third video: The variable mainCam of GameSetup has not been assigned. This is my code in C#:

GameSetup.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameSetup : MonoBehaviour
{
    public Camera mainCam;

    public BoxCollider2D topWall, bottomWall, leftWall, rightWall;

    public Transform Player1, Player2;

    // Start is called before the first frame update
    void Start()
    {
        // topWall = GetComponent<BoxCollider2D>();
        // mainCam = GetComponent<Camera>();
        // If I uncomment this, there would be a new error: There is no 'Camera' attached to '_GM' game object, but a script is trying to access it.
    }

    // Update is called once per frame
    void Update()
    {
        // Move each wall to its edge location
        topWall.size = new Vector2(mainCam.ScreenToWorldPoint(new Vector3(Screen.width * 2.0f, 0f)).x, 1.0f);
        topWall.offset = new Vector2(0f, mainCam.ScreenToWorldPoint(new Vector3(0f, Screen.width, 0f)).y + 0.5f);
    }
}

With the help of Google, I've add rb2d.GetComponent<Rigibody2D>() in Start() from the script of the second video under and prevent the error (there are no Start() in the video)

PlayerControls.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerControls : MonoBehaviour
{

    public KeyCode moveUp, moveDown;

    public float speed = 10;

    private Rigidbody2D rb2d = new Rigidbody2D();
    // Start is called before the first frame update
    void Start()
    {
        rb2d = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(moveUp))
        {
            Vector3 v = rb2d.velocity;
            v.y = speed;
            rb2d.velocity = v;
            // rb2d.velocity.y = speed;
        }
        else if (Input.GetKey(moveDown))
        {
            Vector3 v = rb2d.velocity;
            v.y = speed * (-1);
            rb2d.velocity = v;
        }
        else
        {
            Vector3 v = rb2d.velocity;
            v.y = 0;
            rb2d.velocity = v;
        }
    }
}

How can I fix the bug in GameSetup.cs ? I've done exactly what said in the video, but only changed the language from JS to C#

Body:
Either assign it null:

public Camera mainCam = null;

But you are most likely missing to attach a camera object to it in the Unity3D editor. Check your inspector and make sure that whatever object that is using this script(GameSetup.cs) has a camera object assigned to its public variable.

Should look something like this. You have to drag and drop a camera object to the Gameobject.


问:
Pasting values from one Excel Workbook to others
I want to copy the same values from one workbook to 30 other workbooks.

I found a macro that open and copies all the values of the files of the first workbook.

It doesn't copy any value, even when I use this simple code:

```<code>Range("B2:B5").Select
Selection.Copy
Sheets("Hoja2").Select
Range("B2").Select
ActiveSheet.Paste
</code>```

Also I don't know how to put the name of the workbook that I want to paste because there are a lot of names.

This would be the problem, I think. "reports.xlms" is only one name of the files, there are other files with other names.

Is there a way to copy and paste the values without specifying the name of the worksheets? maybe only saying the number, for example, worksheet(1), like this:

Workbooks("Reports.xlsm").Worksheets("Data").Range("A2:D9").PasteSpecial

Here is my code:

```<code>Sub AbrirArchivos()
 Dim Archivos As String

 'Paso 2: Especificar una carpeta y el tipo de archivo que buscamos
 'en este caso la carpeta se llama "temporal" y el tipo de dato es "xlsx"

 Archivos = Dir("C:\Users\fernandofernandez\Desktop\Prueba\*.xlsx")
 Do While Archivos <> “”

 'Paso 3: Abrir los libros uno por uno
 Workbooks.Open "C:\Users\fernandofernandez\Desktop\Prueba\" & Archivos

'code:

  ***Workbooks("New Data.xlsx").Worksheets("Export").Range("A2:D9").Copy

  Workbooks("Reports.xlsm").Worksheets("Data").Range("A2:D9").PasteSpecial Paste:=xlPasteValues***

 'Paso 5: Cuadro de mensaje, cerrar y guardar cambios

 MsgBox ActiveWorkbook.Name

 ActiveWorkbook.Close SaveChanges:=True

'Paso 6: buscar más archivos en la carpeta para volver seguir la secuencia

 Archivos = Dir
 Loop

End Sub
</code>```

答:
There's few cases where I would every use copy PasteValues. Sometimes there's a case for formatting or formulas, but for values, I would always recommend using the approach of just setting the Value. See example:

Workbooks("Reports.xlsm").Worksheets("Data").Range("A2:D9").Value = _
Workbooks("New Data.xlsx").Worksheets("Export").Range("A2:D9").Value

Body:
I want to copy the same values from one workbook to 30 other workbooks.

I found a macro that open and copies all the values of the files of the first workbook.

It doesn't copy any value, even when I use this simple code:

Range("B2:B5").Select
Selection.Copy
Sheets("Hoja2").Select
Range("B2").Select
ActiveSheet.Paste

Also I don't know how to put the name of the workbook that I want to paste because there are a lot of names.

This would be the problem, I think. "reports.xlms" is only one name of the files, there are other files with other names.

Is there a way to copy and paste the values without specifying the name of the worksheets? maybe only saying the number, for example, worksheet(1), like this:

Workbooks("Reports.xlsm").Worksheets("Data").Range("A2:D9").PasteSpecial

Here is my code:

Sub AbrirArchivos()
 Dim Archivos As String

 'Paso 2: Especificar una carpeta y el tipo de archivo que buscamos
 'en este caso la carpeta se llama "temporal" y el tipo de dato es "xlsx"

 Archivos = Dir("C:\Users\fernandofernandez\Desktop\Prueba\*.xlsx")
 Do While Archivos <> “”

 'Paso 3: Abrir los libros uno por uno
 Workbooks.Open "C:\Users\fernandofernandez\Desktop\Prueba\" & Archivos

'code:

  ***Workbooks("New Data.xlsx").Worksheets("Export").Range("A2:D9").Copy

  Workbooks("Reports.xlsm").Worksheets("Data").Range("A2:D9").PasteSpecial Paste:=xlPasteValues***

 'Paso 5: Cuadro de mensaje, cerrar y guardar cambios

 MsgBox ActiveWorkbook.Name

 ActiveWorkbook.Close SaveChanges:=True

'Paso 6: buscar más archivos en la carpeta para volver seguir la secuencia

 Archivos = Dir
 Loop

End Sub


问:
Is there a possibility to retrieve liquipedia page content in json?
I got this page - https://liquipedia.net/dota2/Players_(all) which I want to get in JSON format, is there any open liquipedia (which is actually wikipedia based site) api's I can use? Or maybe there are approaches to convert html to json?</p>

答: There appears to be a python API that would do what your looking for at https://github.com/c00kie17/liquipediapy#dota_get_players</p>


问:
SQL query to get max of a column and display with every row
Here's my scenario...
Multiple Items with multiple item types which have multiple prices.
Want to select Items with all types showing the MAX price. Can't figure out how to get the max?

Input:

```<code>ProductId   ProductType Description     Price
</code>```

1           A           BAKED BEANS     1.29

1           B           BAKED BEANS     1.98

Output:

```<code>ProductId   ProductType Description     Price
</code>```

1           A           BAKED BEANS     1.98

1           B           BAKED BEANS     1.98

Any suggestions?

答:
Another way:</p>

```<code>SELECT ProductId
     , ProductType
     , Description
     , ( SELECT MAX(price)
         FROM Product pg
         WHERE pg.Description = p.Description
       ) AS MaxPrice
  FROM Product p
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here's my scenario...
Multiple Items with multiple item types which have multiple prices.
Want to select Items with all types showing the MAX price. Can't figure out how to get the max?

Input:

ProductId   ProductType Description     Price

1           A           BAKED BEANS     1.29

1           B           BAKED BEANS     1.98

Output:

ProductId   ProductType Description     Price

1           A           BAKED BEANS     1.98

1           B           BAKED BEANS     1.98

Any suggestions?

Body:
Another way:

SELECT ProductId
     , ProductType
     , Description
     , ( SELECT MAX(price)
         FROM Product pg
         WHERE pg.Description = p.Description
       ) AS MaxPrice
  FROM Product p


问:
How @SentTo sends the message to related topic?
I am using ReplyingKafkaTemplate in my Rest controller to return the synchronous response. I am also setting header REPLY_TOPIC. For listener microservice part,

```<code>
 @KafkaListener(topics = "${kafka.topic.request-topic}")
 @SendTo
 public Model listen(Model<SumModel,SumResp> request) throws InterruptedException {

   SumModel model = request.getRequest();
   int sum = model.getNumber1() + model.getNumber2();

   SumResp resp = new SumResp(sum);
   request.setReply(resp);

   request.setAdditionalProperty("sum", sum);
   return request;
 }
</code>```

My question is, How @sentTo annotation manage to publish the message to the topic provided in the header. There should be a KafkaTemplate bean or it does not need it? As we are just returning the message without using any KafkaTemplate or ReplyingKafkaTemplate bean.

Without any kafka template does it work or does it require KafkaTemplate or ReplyingKafkaTemplate beans?

Thanks

答:
Yes, a template is used to send the reply...

```<code>Assert.state(replyTopic == null || this.replyTemplate != null,
        "a KafkaTemplate is required to support replies");
</code>```

Spring Boot automatically wires a template into the listener container factory if there is exactly one in the application context.

```<code>map.from(this.replyTemplate).to(factory::setReplyTemplate);
</code>```

Boot also auto configures a template if there is not one already in the context.

Body:
I am using ReplyingKafkaTemplate in my Rest controller to return the synchronous response. I am also setting header REPLY_TOPIC. For listener microservice part,

 @KafkaListener(topics = "${kafka.topic.request-topic}")
 @SendTo
 public Model listen(Model<SumModel,SumResp> request) throws InterruptedException {

   SumModel model = request.getRequest();
   int sum = model.getNumber1() + model.getNumber2();

   SumResp resp = new SumResp(sum);
   request.setReply(resp);

   request.setAdditionalProperty("sum", sum);
   return request;
 }

My question is, How @sentTo annotation manage to publish the message to the topic provided in the header. There should be a KafkaTemplate bean or it does not need it? As we are just returning the message without using any KafkaTemplate or ReplyingKafkaTemplate bean.

Without any kafka template does it work or does it require KafkaTemplate or ReplyingKafkaTemplate beans?

Thanks

Body:
Yes, a template is used to send the reply...

Assert.state(replyTopic == null || this.replyTemplate != null,
        "a KafkaTemplate is required to support replies");

Spring Boot automatically wires a template into the listener container factory if there is exactly one in the application context.

map.from(this.replyTemplate).to(factory::setReplyTemplate);

Boot also auto configures a template if there is not one already in the context.


问:
Compare files on double click in Pending Changes view
Is there a way in visual studio to change the behavior when I double click a file in the 'Pending Changes' view.

The default behavior is, that Visual Studio opens the file in code editor, but I want that it opens the 'Compare'-Dialog with the latest version. (same behavior as in TortoiseSVN)

答:
VS 2019 And Beyond (hopefully)

Building on Tereza's answer using powershell

Run powershell as adminstrator and close Visual Studio.
(you might have to wait a couple of seconds for VS to release some files)
(if you copy paste make sure to send the last command, or else VS won't start)

$instanceId = $(& "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -latest -property instanceId).Trim()
$versionMajor = $(& "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -latest -property installationVersion).Trim().Substring(0,2)
$year = $(& "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -latest -property catalog_productLineVersion).Trim()
reg.exe load HKLM\VS$yearPrivateRegistry $env:LOCALAPPDATA\Microsoft\VisualStudio\$versionMajor.0_$instanceId\privateregistry.bin
reg.exe add HKLM\VS$yearPrivateRegistry\Software\Microsoft\VisualStudio\$versionMajor.0_$instanceId\TeamFoundation\SourceControl\Behavior /v DoubleClickOnChange /t REG_DWORD /d 1 /f
reg.exe unload HKLM\VS$yearPrivateRegistry
```

This attempts to determine the major version as well.

Body:
VS 2019 And Beyond (hopefully)

Building on Tereza's answer using powershell

Run powershell as adminstrator and close Visual Studio.
(you might have to wait a couple of seconds for VS to release some files)
(if you copy paste make sure to send the last command, or else VS won't start)

$instanceId = $(& "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -latest -property instanceId).Trim()
$versionMajor = $(& "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -latest -property installationVersion).Trim().Substring(0,2)
$year = $(& "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -latest -property catalog_productLineVersion).Trim()
reg.exe load HKLM\VS$yearPrivateRegistry $env:LOCALAPPDATA\Microsoft\VisualStudio\$versionMajor.0_$instanceId\privateregistry.bin
reg.exe add HKLM\VS$yearPrivateRegistry\Software\Microsoft\VisualStudio\$versionMajor.0_$instanceId\TeamFoundation\SourceControl\Behavior /v DoubleClickOnChange /t REG_DWORD /d 1 /f
reg.exe unload HKLM\VS$yearPrivateRegistry

This attempts to determine the major version as well.


Title: Join dataframe to multiple lists

Body:
I have the following list:

$df1
  x   y          z
1 a 145 2010-01-01
2 b  22 2010-02-01
3 c  33 2010-03-01

$df2
  x   y          z
1 d  45 2010-01-01
2 e  35 2010-02-01
3 f 633 2010-03-01

I also have a data frame which looks like the following:

    x   y          z
1 aty 451 2010-01-01
2 b43 452 2010-02-01
3 crf 343 2010-03-01

I am trying to join the dataframe by date of column z to each of the lists so the expected output would be something like:

$df1
  x   y          z  x.1 y.1
1 a 145 2010-01-01  aty 451
2 b  22 2010-02-01  b43 452
3 c  33 2010-03-01  crf 343

$df2
  x   y          z  x.1 y.1
1 d  45 2010-01-01  aty 451
2 e  35 2010-02-01  b43 452
3 f 633 2010-03-01  crf 343

Data:

foo <- list(df1 = data.frame(x=c('a', 'b', 'c'),y = c(145,22,33), z=c("2010-01-01", "2010-02-01", "2010-03-01")),
            df2 = data.frame(x=c('d', 'e', 'f'),y = c(45,35,633), z=c("2010-01-01", "2010-02-01", "2010-03-01")))

foo2 <- data.frame(x = c('aty', 'b43', 'crf'), y= c(451,452,343), z=c("2010-01-01", "2010-02-01", "2010-03-01"))

Body:
We can use tidyverse

library(tidyverse)
map(foo, inner_join, foo2, by = 'z')
#$df1
#  x.x y.x          z x.y y.y
#1   a 145 2010-01-01 aty 451
#2   b  22 2010-02-01 b43 452
#3   c  33 2010-03-01 crf 343

#$df2
#  x.x y.x          z x.y y.y
#1   d  45 2010-01-01 aty 451
#2   e  35 2010-02-01 b43 452
#3   f 633 2010-03-01 crf 343

Or using base R

lapply(foo, merge, foo2, by = 'z')
#$df1
#           z x.x y.x x.y y.y
#1 2010-01-01   a 145 aty 451
#2 2010-02-01   b  22 b43 452
#3 2010-03-01   c  33 crf 343

#$df2
#           z x.x y.x x.y y.y
#1 2010-01-01   d  45 aty 451
#2 2010-02-01   e  35 b43 452
#3 2010-03-01   f 633 crf 343


问:
Display dictionary in print statement
Is there a way to print the contents of a dictionary without have to iterate over the dictionary? In javascript you can console.log to view the contents of the object. Is there something similar in python?

I've tried print statement as well as object.keys() and object.values(). However, I would like to see the entire dictionary via print statement.

```<code>print(dictionary)
</code>```

I expect {a: 1} instead of object at 0x7efd79610278>

答:
I don't think the variable dictionary is what you think it is.
Here's a small example in the Python3 REPL (Read. Evaluate. Print. Loop) that shows the printing a dictionary with the expected behavior.

```<code>$ python3
Python 3.7.3 (default, Apr  3 2019, 05:39:12)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a = {}
>>> a[0] = '0'
>>> a
{0: '0'}
>>> print(a)
{0: '0'}
</code>```

To answer your question the default __str__ method pronounced (dunder str) should be sufficient. However if it is not you could do something the following and provide your own implementation.

```<code>>>> import json
>>> class MyDict(dict):
...     def __str__(self):
...             return json.dumps(self)
...
>>> d = MyDict()
>>> d['key'] = 'value'
>>> print(d)
{"key": "value"}
</code>```

Title: Display dictionary in print statement

Body:
Is there a way to print the contents of a dictionary without have to iterate over the dictionary? In javascript you can console.log to view the contents of the object. Is there something similar in python?

I've tried print statement as well as object.keys() and object.values(). However, I would like to see the entire dictionary via print statement.

print(dictionary)

I expect {a: 1} instead of object at 0x7efd79610278>

Body:
I don't think the variable dictionary is what you think it is.
Here's a small example in the Python3 REPL (Read. Evaluate. Print. Loop) that shows the printing a dictionary with the expected behavior.

$ python3
Python 3.7.3 (default, Apr  3 2019, 05:39:12)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a = {}
>>> a[0] = '0'
>>> a
{0: '0'}
>>> print(a)
{0: '0'}

To answer your question the default __str__ method pronounced (dunder str) should be sufficient. However if it is not you could do something the following and provide your own implementation.

>>> import json
>>> class MyDict(dict):
...     def __str__(self):
...             return json.dumps(self)
...
>>> d = MyDict()
>>> d['key'] = 'value'
>>> print(d)
{"key": "value"}


问:
Why does the mongo shell work without mongod server being explicitly run?
Running MongoDB Shell v-3.2.8

I've noticed that articles and tutorials always mention to run the mongod server before running the mongo shell.

However, when I skip the first step and simply type mongo into my terminal, the mongo shell works without any errors / interruptions.

```<code>MacBook:Desktop user$ mongo
MongoDB shell version: 3.2.8
connecting to: test
</code>```

Why does this work? Does mongo call mongod?

答: I noticed the same. I think mongoose is doing some smart things there, which I'm not sure how it works. But I have noticed such things before, like mongoose will automatically add an "s" to your database's name when you declare it, which is a very thoughtful act =)).</p>

Body:
Running MongoDB Shell v-3.2.8

I've noticed that articles and tutorials always mention to run the mongod server before running the mongo shell.

However, when I skip the first step and simply type mongo into my terminal, the mongo shell works without any errors / interruptions.

MacBook:Desktop user$ mongo
MongoDB shell version: 3.2.8
connecting to: test

Why does this work? Does mongo call mongod?


问:
Array length is not changing
I think i am making a mistake in pushing api response data into array. it is not reflecting. The length of the array remains 1.

When i get a response from watson api. I am pushing that response into an array. Then I call fetchLogs function again to get next page and push it in the same array. But I am seeing first response only.

I am writing it in a text file when no logs left. I only see first response.

Could any one please guide me. Why value is not being pushed.

```<code>let nxt_url = '';
const logs = [];

const fetchLogs = async () => {
   let newurl = checkUrl();
   try {
    let response = await axios.get(newurl, {
      withCredentials: true,
      headers: {
        "Accept": "application/json",
        "Content-Type": "application/json"
      },
      auth: {
        username: "abc123"
        password: "xyz123"
      }
    });
    if(!isEmpty(response.data.pagination)) {
      nxt_url = response.data.pagination.next_url;
      logs.push(response.data) // here I am pushing
      await fetchLogs();
    } else {
      console.log("No More Logs");
      fs.writeFile("temp.txt", JSON.stringify(logs, null, 2), err => {
          if (err) console.log(err);
          console.log("log saved in an array !");
      });
    }
   } catch (error) {
     console.log(error.message);
   }
}

</code>```

答:
```<code>  if (response.data.pagination.next_url) {
      nxt_url = response.data.pagination.next_url;
      logs.push(response.data); // here I am pushing
      return fetchLogs();
    } else {
      logs.push(response.data);
      console.log(logs.length);
      console.log('No More Logs');
      fs.writeFile('temp.txt', JSON.stringify(logs, null, 2), err => {
        if (err) console.log(err);
        console.log('log saved in an array !');
      });
    }
</code>```

Title: Array length is not changing

Body:
I think i am making a mistake in pushing api response data into array. it is not reflecting. The length of the array remains 1.

When i get a response from watson api. I am pushing that response into an array. Then I call fetchLogs function again to get next page and push it in the same array. But I am seeing first response only.

I am writing it in a text file when no logs left. I only see first response.

Could any one please guide me. Why value is not being pushed.

let nxt_url = '';
const logs = [];

const fetchLogs = async () => {
   let newurl = checkUrl();
   try {
    let response = await axios.get(newurl, {
      withCredentials: true,
      headers: {
        "Accept": "application/json",
        "Content-Type": "application/json"
      },
      auth: {
        username: "abc123"
        password: "xyz123"
      }
    });
    if(!isEmpty(response.data.pagination)) {
      nxt_url = response.data.pagination.next_url;
      logs.push(response.data) // here I am pushing
      await fetchLogs();
    } else {
      console.log("No More Logs");
      fs.writeFile("temp.txt", JSON.stringify(logs, null, 2), err => {
          if (err) console.log(err);
          console.log("log saved in an array !");
      });
    }
   } catch (error) {
     console.log(error.message);
   }
}


问:
Given an array of objects, how do I replace the key name with another whilst keeping the value from the original key?
I'm trying to take an array of objects and, without mutating the original array, rename a specific key in each object.

I've created a new variable and assigned it to the result of using 'map' on my original array (to avoid mutation).
Within the 'map' method, I've tried to deconstruct the 'keyToChange' parameter and spread the rest of the values to the 'newKey'.

```<code>const renameKeys = (array, keyToChange, newKey) => {
  const spreadArray = array.map(({keyToChange: newKey, ...rest}) => ({newKey, ...rest}));
    return spreadArray;
   };
</code>```

The above code returns
'newKey: [undefined]' followed by the original array of objects.

Any help would be greatly appreciated.

答:
Use square brackets notation if you want to use dynamic value as key.  https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors
*/</p>

```<code> const spreadArray = array.map(({ [keyToChange]: newKey, ...rest}) => ({newKey, ...rest}));
</code>```

Body:
I'm trying to take an array of objects and, without mutating the original array, rename a specific key in each object.

I've created a new variable and assigned it to the result of using 'map' on my original array (to avoid mutation).
Within the 'map' method, I've tried to deconstruct the 'keyToChange' parameter and spread the rest of the values to the 'newKey'.

const renameKeys = (array, keyToChange, newKey) => {
  const spreadArray = array.map(({keyToChange: newKey, ...rest}) => ({newKey, ...rest}));
    return spreadArray;
   };

The above code returns
'newKey: [undefined]' followed by the original array of objects.

Any help would be greatly appreciated.

Body:
Use square brackets notation if you want to use dynamic value as key.  https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors
*/

 const spreadArray = array.map(({ [keyToChange]: newKey, ...rest}) => ({newKey, ...rest}));


问:
How to use GROUP BY method in php-mysql
I’m trying to use "group by" instead of "DISTINCT" in my php file to select some rows that all of them have an specific column value and it’s "idchat".
And I want to get more than one columns
please help me!

I’ve checked every pages but I didn’t understand enything

```<code> <?php

$connection = mysqli_connect("localhost","---","pass","---");
    $id = $_GET["id"];
    $mobile = $_GET["mobile"];
    $idchat = $_GET["idchat"];

    if (strpos($mobile, '9') !== false) {

$query = "SELECT DISTINCT a,b,c,d,idchat  FROM database where mobile = '$mobile' ORDER BY id DESC";
$result = mysqli_query($connection,$query);
while ($row = mysqli_fetch_assoc($result)) {

    $array[] = $row;
}
header('Content-Type:Application/json');
echo json_encode($array);
    }
    mysqli_close($connection);?>
</code>```

and this code gives me this error:

Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in /home/---/test.php on line 12

答:
"Could you correct my codes please?": Ok, but untested:

```<code><?php

$connection = mysqli_connect("localhost","---","pass","---");
    $id = $_GET["id"];
    $mobile = $_GET["mobile"];
    $idchat = $_GET["idchat"];

    if (strpos($mobile, '9') !== false) {

$query = "SELECT DISTINCT a,b,c,d,idchat,id  FROM `database` where mobile = '$mobile' ORDER BY id DESC";
$result = mysqli_query($connection,$query);
if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {

        $array[] = $row;
    }
    header('Content-Type:Application/json');
    echo json_encode($array);
}
else {
  echo mysqli_error($connection);
}
mysqli_close($connection);?>
}
</code>```

I also did add id to the query because of comment from @Raymond

Title: How to use GROUP BY method in php-mysql

Body:
I’m trying to use "group by" instead of "DISTINCT" in my php file to select some rows that all of them have an specific column value and it’s "idchat".
And I want to get more than one columns
please help me!

I’ve checked every pages but I didn’t understand enything

 <?php

$connection = mysqli_connect("localhost","---","pass","---");
    $id = $_GET["id"];
    $mobile = $_GET["mobile"];
    $idchat = $_GET["idchat"];

    if (strpos($mobile, '9') !== false) {

$query = "SELECT DISTINCT a,b,c,d,idchat  FROM database where mobile = '$mobile' ORDER BY id DESC";
$result = mysqli_query($connection,$query);
while ($row = mysqli_fetch_assoc($result)) {

    $array[] = $row;
}
header('Content-Type:Application/json');
echo json_encode($array);
    }
    mysqli_close($connection);?>

and this code gives me this error:

Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in /home/---/test.php on line 12

Body:
"Could you correct my codes please?": Ok, but untested:

<?php

$connection = mysqli_connect("localhost","---","pass","---");
    $id = $_GET["id"];
    $mobile = $_GET["mobile"];
    $idchat = $_GET["idchat"];

    if (strpos($mobile, '9') !== false) {

$query = "SELECT DISTINCT a,b,c,d,idchat,id  FROM `database` where mobile = '$mobile' ORDER BY id DESC";
$result = mysqli_query($connection,$query);
if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {

        $array[] = $row;
    }
    header('Content-Type:Application/json');
    echo json_encode($array);
}
else {
  echo mysqli_error($connection);
}
mysqli_close($connection);?>
}

I also did add id to the query because of comment from @Raymond


问:
What is the purpose of anchor transaction file in Hyperledger Fabric?
In BYFN documentation after the channel.tx file, it generates ORG1MSPanchors.tx

Next, we will define the anchor peer for Org1 on the channel that we
  are constructing.

```<code>../bin/configtxgen -profile TwoOrgsChannel -outputAnchorPeersUpdate ./channel-artifacts/Org1MSPanchors.tx -channelID $CHANNEL_NAME -asOrg Org1MSP
</code>```

I understood the purpose of creating the transaction file, but where it is utilizing?

genesis.block - used for creating the channel

channel.tx - use for creating the channel

ORG1MSPanchors.tx -- Where does it used?

答:
The channel configuration is the main component of any fabric network. If any changes made in the network like a new organization in the network or making existing peer as an anchor peer, the channel is unaware of these changes. So, to make these changes as part of the channel we have to update the channel configuration.

In case of making a peer as an anchor peer, we have to create a new anchorpeer.tx file using  configtxgen tool and -outputAnchorPeersUpdate flag.

Now, with this generated tx file channel configuration needs to be updated. This will inform the channel that a particular peer is now an anchor peer.

To check how to update this, please follow the Alexander Yammine answer to this question.

Body:
In BYFN documentation after the channel.tx file, it generates ORG1MSPanchors.tx

Next, we will define the anchor peer for Org1 on the channel that we
  are constructing.

../bin/configtxgen -profile TwoOrgsChannel -outputAnchorPeersUpdate ./channel-artifacts/Org1MSPanchors.tx -channelID $CHANNEL_NAME -asOrg Org1MSP

I understood the purpose of creating the transaction file, but where it is utilizing?

genesis.block - used for creating the channel

channel.tx - use for creating the channel

ORG1MSPanchors.tx -- Where does it used?


问:
UIApplication not launching to make phone call
I have this code:

```<code>NSString *telURL = [NSString stringWithFormat:@"tel:1-%@",((UIButton*) sender).titleLabel.text];
telURL = [telURL stringByReplacingOccurrencesOfString:@"\n" withString:@""];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:telURL]];
</code>```

But it does not launch the dialer application to make a phone call.

I've checked the string telURL and its contents are : "tel:[REDACTED]", which to my understanding is what it needs to be.

Any ideas?

EDIT:
In the event that it matters I've just been running this on the simulator. I won't have a physical device for a few days. (And from the answers  below apparently it does matter)

答: You answered your own question. The tel: URL does NOT work on the iPhone simulator AND the iPod Touch (and iPad, of course).  It ONLY works on the iPhone.</p>

Body:
I have this code:

NSString *telURL = [NSString stringWithFormat:@"tel:1-%@",((UIButton*) sender).titleLabel.text];
telURL = [telURL stringByReplacingOccurrencesOfString:@"\n" withString:@""];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:telURL]];

But it does not launch the dialer application to make a phone call.

I've checked the string telURL and its contents are : "tel:[REDACTED]", which to my understanding is what it needs to be.

Any ideas?

EDIT:
In the event that it matters I've just been running this on the simulator. I won't have a physical device for a few days. (And from the answers  below apparently it does matter)


问:
Why my font-awesome icons are being displayed big at first and then updated to the right size?
Every time I refresh the page the font-awesome icons are being displayed big. Seems like the css in being loaded before applying the proper size because right after the refresh it shows big, and then goes to the right size.

I tried some solutions I found online but none of them worked.

Right now I'm back to square one where I have these:

```<code>import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faFacebook } from '@fortawesome/free-brands-svg-icons'
import { faTwitter } from '@fortawesome/free-brands-svg-icons'
import { faLinkedin } from '@fortawesome/free-brands-svg-icons'
import { faEnvelope } from '@fortawesome/free-solid-svg-icons'
import { faMapMarkerAlt } from '@fortawesome/free-solid-svg-icons'
</code>```

and then use them like this:

```<code><FontAwesomeIcon icon={faFacebook} color="white" size="2x"/>
</code>```

I didn't need to import any css but I did install following this link:

https://www.npmjs.com/package/@fortawesome/react-fontawesome

Basically I installed those:

```<code>$ npm i --save @fortawesome/fontawesome-svg-core
$ npm i --save @fortawesome/free-solid-svg-icons
$ npm i --save @fortawesome/react-fontawesome
</code>```

If someone could give me a direction on what to look for it would be great.

My project is hosted at Github (https://github.com/palomaschkrab/keto-ui)
And you can run it with "npm run dev" and go to localhost:3000/about_us if you want to see it happening.

答:
I've seen this before when browsing some pages, most notably www.getbootstrap.com
Only happened with Firefox and I found that Ctrl+F5 would fix the problem. As soon as I opened another URL on the same site, that effect returned. Never found out what was causing it, as I then decided to go to Chrome.</p>

Body:
Every time I refresh the page the font-awesome icons are being displayed big. Seems like the css in being loaded before applying the proper size because right after the refresh it shows big, and then goes to the right size.

I tried some solutions I found online but none of them worked.

Right now I'm back to square one where I have these:

import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faFacebook } from '@fortawesome/free-brands-svg-icons'
import { faTwitter } from '@fortawesome/free-brands-svg-icons'
import { faLinkedin } from '@fortawesome/free-brands-svg-icons'
import { faEnvelope } from '@fortawesome/free-solid-svg-icons'
import { faMapMarkerAlt } from '@fortawesome/free-solid-svg-icons'

and then use them like this:

<FontAwesomeIcon icon={faFacebook} color="white" size="2x"/>

I didn't need to import any css but I did install following this link:

https://www.npmjs.com/package/@fortawesome/react-fontawesome

Basically I installed those:

$ npm i --save @fortawesome/fontawesome-svg-core
$ npm i --save @fortawesome/free-solid-svg-icons
$ npm i --save @fortawesome/react-fontawesome

If someone could give me a direction on what to look for it would be great.

My project is hosted at Github (https://github.com/palomaschkrab/keto-ui)
And you can run it with "npm run dev" and go to localhost:3000/about_us if you want to see it happening.


问:
How add where condition in fillAll method in spring boot using hibernate
I am using Spring boot framework with hibernate. I want to show all data from database only certain conditions. Here is my query

```<code>SELECT * FROM `client_master` WHERE CLIENT_GROUP='S'
</code>```

I want to get data which CLIENT_GROUP data has only S. I have used bellow cod for spring boot..

Model  I have used bellow code..

```<code> @Entity
@Table(name = "client_master")
public class ClientMasterModel {
  @Id
  @GeneratedValue(strategy = GenerationType.SEQUENCE)
  @Column(name= "ID")
  private int ID;

  @Column(name= "NAME")
  private String name;

  //getter or setter
 }
</code>```

My repository is bellow

```<code>  public interface Staff_Add_Repository extends JpaRepository<ClientMasterModel, Long> {

}
</code>```

In service, I have used bellow code..

```<code>  @Autowired
Staff_Add_Repository add_Repository;

 public List<ClientMasterModel> findAll(){
   return add_Repository.findAll();
 }
</code>```

Above method returns all data. I want to get only specific data .
How to do it? Please help me..

答:
Try</p>

```<code>List<ClientMasterModel> findByClientGroup(String clientGroup);
</code>```

Body:
I am using Spring boot framework with hibernate. I want to show all data from database only certain conditions. Here is my query

SELECT * FROM `client_master` WHERE CLIENT_GROUP='S'

I want to get data which CLIENT_GROUP data has only S. I have used bellow cod for spring boot..

Model  I have used bellow code..

 @Entity
@Table(name = "client_master")
public class ClientMasterModel {
  @Id
  @GeneratedValue(strategy = GenerationType.SEQUENCE)
  @Column(name= "ID")
  private int ID;

  @Column(name= "NAME")
  private String name;

  //getter or setter
 }

My repository is bellow

  public interface Staff_Add_Repository extends JpaRepository<ClientMasterModel, Long> {

}

In service, I have used bellow code..

  @Autowired
Staff_Add_Repository add_Repository;

 public List<ClientMasterModel> findAll(){
   return add_Repository.findAll();
 }

Above method returns all data. I want to get only specific data .
How to do it? Please help me..

Body:
Try

List<ClientMasterModel> findByClientGroup(String clientGroup);


问:
How do you do a function in terms of the Y axis instead of the X axis with Sympy in Python?
I´m trying to code a Game Theory method to find optimal mixed strategies of a game of 2x2 order.

Anyway, to do that I require to define two functions, one which is in terms of the x axis and another which is in terms of the y axis (yes, the classic axes required to work in the two dimensional plane), so later a can obtain the intersection points.

For example;

suppose I have the next functions obtained from the 2x2 game:

L(y)= y+1

L(x)= x-2

where:

```<code>   if L(y)> 0, i.e., y+1>0, then x=1 (this is if y>-1 then x=1)
   if L(y)< 0, then x=0  (this is if y<-1 then x=0)
   if L(y)= 0, then x∈[0,1] (this is if y=-1 then x∈[0,1])
</code>```

and

```<code>   if L(x) >0 then  y=1 (this is: if x>2 then y=1)
   if L(x) <0 then  y=0 (this is: if x<2 then y=0)
   if L(x) =0 then  y∈[0,1] (this is: if x=2 then y∈[0,1]
</code>```

https://imgur.com/a/eXeTVF0

I was searching for a Python library that could do this, and I found that with sympy one can create piecewise functions like what I´m trying to do. I was doing something like this:

```<code>    from sympy import symbols, Piecewise
    x,y = symbols('x,y')

    p = Piecewise((1, x > 2), (0, x <2))
    q = Piecewise((1, y>-1), (0,y<-1))
</code>```

and then find the intersection points from it. The problem is that Python doesn't care about the "name" of the variable and it treats them both as if they where in the same X axis.

Also I have trouble plotting them both at the same time and of course finding the intersection point in it. Is that even possible for Python?
What should I do, or what other way I could approach this problem.
Greetings.

答:
If you mean by "intersection of p and q" that you want to know the conditions for when they are the same, you can "fold" Tuple(p, q) to show you:</p>

```<code>>>> piecewise_fold(Tuple(p, q))
Piecewise(
  ((1, 1), (x > 2) & (y > -1)),
  ((1, 0), x > 2),
  ((0, 1), y > -1),
  ((0, 0), True))
</code>```

Body:
I´m trying to code a Game Theory method to find optimal mixed strategies of a game of 2x2 order.

Anyway, to do that I require to define two functions, one which is in terms of the x axis and another which is in terms of the y axis (yes, the classic axes required to work in the two dimensional plane), so later a can obtain the intersection points.

For example;

suppose I have the next functions obtained from the 2x2 game:

L(y)= y+1

L(x)= x-2

where:

   if L(y)> 0, i.e., y+1>0, then x=1 (this is if y>-1 then x=1)
   if L(y)< 0, then x=0  (this is if y<-1 then x=0)
   if L(y)= 0, then x∈[0,1] (this is if y=-1 then x∈[0,1])

and

   if L(x) >0 then  y=1 (this is: if x>2 then y=1)
   if L(x) <0 then  y=0 (this is: if x<2 then y=0)
   if L(x) =0 then  y∈[0,1] (this is: if x=2 then y∈[0,1]

https://imgur.com/a/eXeTVF0

I was searching for a Python library that could do this, and I found that with sympy one can create piecewise functions like what I´m trying to do. I was doing something like this:

    from sympy import symbols, Piecewise
    x,y = symbols('x,y')

    p = Piecewise((1, x > 2), (0, x <2))
    q = Piecewise((1, y>-1), (0,y<-1))

and then find the intersection points from it. The problem is that Python doesn't care about the "name" of the variable and it treats them both as if they where in the same X axis.

Also I have trouble plotting them both at the same time and of course finding the intersection point in it. Is that even possible for Python?
What should I do, or what other way I could approach this problem.
Greetings.

Body:
If you mean by "intersection of p and q" that you want to know the conditions for when they are the same, you can "fold" Tuple(p, q) to show you:

>>> piecewise_fold(Tuple(p, q))
Piecewise(
  ((1, 1), (x > 2) & (y > -1)),
  ((1, 0), x > 2),
  ((0, 1), y > -1),
  ((0, 0), True))


答:
Assuming you have a field named clientGroup in your ClientMasterModel you just need a correctly named method and possibly - if you wish - a default wrapper method in your repository as following:

```<code>public interface Staff_Add_Repository
            extends JpaRepository<ClientMasterModel, Long> {

    List<ClientMasterModel> findByClientGroup(String clientGroup);

    default List<ClientMasterModel> findWhereClientGroupIsS() {
        return findByClientGroup("S");
    }

}
</code>```

Also the findAllBy is a synonym to findBy. See this question

Title: How add where condition in fillAll method in spring boot using hibernate

Body:
Assuming you have a field named clientGroup in your ClientMasterModel you just need a correctly named method and possibly - if you wish - a default wrapper method in your repository as following:

public interface Staff_Add_Repository
            extends JpaRepository<ClientMasterModel, Long> {

    List<ClientMasterModel> findByClientGroup(String clientGroup);

    default List<ClientMasterModel> findWhereClientGroupIsS() {
        return findByClientGroup("S");
    }

}

Also the findAllBy is a synonym to findBy. See this question


问:
How to change a thread's Runnable target during runtime
I want to build my own ExecutorService in Java which is able to 'submit(Callable task)' a given task.
I intended to use a thread pool comprising several 'Threads(Runnable target)'.
The idea is to create a fixed number of threads which dequeue FutureTask objects from a list that has been filled by the 'submit' method. The FutureTask objects have been created within the submit method as well.
My problem is that I can only hand over a Runnable object(here: FutureTask) to a thread when the thread is created (via constructor), but obviously FutureTasks need to be assigned to a thread dynamically (when the item is removed from the list).
Is there any way to do this?</p>

```<code>// content of submit, parameter: myTask
FutureTask<V> newFutureTask = new FutureTask<V>(myTask);
taskQueue = new BlockingQueue<FutureTask<V>>();
try {
    taskQueue.put(newFutureTask);
} catch (InterruptedException ex) { }
return newFutureTask;

// remove item from list and hand it over to thread
// method within MyThread extends Thread (thread pool) class
void exec() {
    FutureTask<V> task;
    try {
        task = taskQueue.take();
        // TODO: run task somehow????
        } catch(InterruptedException ex) { }
}
</code>```

答:
First, FutureTask is Runnable and so you can just task.run(); in the line whith // TODO.

Second, you need not taskQueue = new BlockingQueue<FutureTask<V>>(); at all. Make your implementation of ExecutorService as an addition to an existing Executor:

```<code>class MyExecutorService implements ExecutorService {

   private final Executor executor;

   public MyExecutorService(Executor executor) {
       this.executor=executor;
   }

   public Future<?> submit(Runnable task) {
       FutureTask task = new FutureTask(task);
       executor.exec(task);
       return task;
   }
}
</code>```

Body:
I want to build my own ExecutorService in Java which is able to 'submit(Callable task)' a given task.
I intended to use a thread pool comprising several 'Threads(Runnable target)'.
The idea is to create a fixed number of threads which dequeue FutureTask objects from a list that has been filled by the 'submit' method. The FutureTask objects have been created within the submit method as well.
My problem is that I can only hand over a Runnable object(here: FutureTask) to a thread when the thread is created (via constructor), but obviously FutureTasks need to be assigned to a thread dynamically (when the item is removed from the list).
Is there any way to do this?

// content of submit, parameter: myTask
FutureTask<V> newFutureTask = new FutureTask<V>(myTask);
taskQueue = new BlockingQueue<FutureTask<V>>();
try {
    taskQueue.put(newFutureTask);
} catch (InterruptedException ex) { }
return newFutureTask;

// remove item from list and hand it over to thread
// method within MyThread extends Thread (thread pool) class
void exec() {
    FutureTask<V> task;
    try {
        task = taskQueue.take();
        // TODO: run task somehow????
        } catch(InterruptedException ex) { }
}

Body:
First, FutureTask is Runnable and so you can just task.run(); in the line whith // TODO.

Second, you need not taskQueue = new BlockingQueue<FutureTask<V>>(); at all. Make your implementation of ExecutorService as an addition to an existing Executor:

class MyExecutorService implements ExecutorService {

   private final Executor executor;

   public MyExecutorService(Executor executor) {
       this.executor=executor;
   }

   public Future<?> submit(Runnable task) {
       FutureTask task = new FutureTask(task);
       executor.exec(task);
       return task;
   }
}


问:
Can I convert a null pointer of int to a long type by reinterpret_cast
int *pt = 0;

long i = reinterpret_cast<long>(pt);

Is i guaranteed to be 0? Is this well defined or implementation-defined?
I checked the c++ standard, but it only states that

A pointer to a data object or to a function (but not a pointer to member) can be converted to any integer type large enough to contain it.

In this case, pt doesn't point to any data object. Does the rule apply to this case?

答:
Yes, it does not matter where it points at runtime; the only thing that matters is the type of the pointer. "to a data object or to a function" just means that both "regular" object pointers as well as function pointers (i.e. pointers to object code) can be recast into numeric types.

I think the code you have above safely stores 0 to 'i' on all known common platforms.


问:
Change key of entries in PHP array
I'm currently trying to build a complex function to re-order the positions of some sections (div's) which are defined in a PHP array.

So for example I've this array here:

```<code>$sections = array(
    0 => 'section_one',
    1 => 'section_two',
    2 => 'section_three',
    3 => 'section_four',
    4 => 'section_five',
    5 => 'section_six',
    6 => 'section_seven'
);
</code>```

Which turns out like this:

```<code>array(7) { [0]=> string(11) "section_one" [1]=> string(11) "section_two" [2]=> string(13) "section_three" [3]=> string(12) "section_four" [4]=> string(12) "section_five" [5]=> string(11) "section_six" [6]=> string(13) "section_seven" }
</code>```

When the user moves now the section six before section two on my website, I need to change the key of section six to 1 and move every key one number up after the moved section. So section_two becomes the key 2 and so on...

Any idea how I can do this? I know that I can replace keys this way:

```<code>$arr[ $newkey ] = $arr[ $oldkey ];
unset( $arr[ $oldkey ] );
</code>```

When the user finished a move of an element, I know the name like section_six and the new position of the element.

After re-ordering / re-placing the keys, the array must look like this:

```<code>$sections_a = array(
    0 => 'section_one',
    1 => 'section_six',
    2 => 'section_two',
    3 => 'section_three',
    4 => 'section_four',
    5 => 'section_five',
    6 => 'section_seven'
);
</code>```

答:
I see @Eddie has given a better solution than mine thanks Eddie,
but here is the custom function I made for this if it helps anyone.</p>

```<code>// This function returns the new array
function reindexArray($array,       // Array
                      $index,       // Index of the value that you to change the index of
                      $indexToMove) // Index that you want to move that value
{
    // Store the value to be reindex in a variable
    $reIndexedValue = $array[$index];
    // Remove that value from the array
    unset($array[$index]);
    // Reorder the original array
    $oldArrayInOrder = array_values($array);
    // Create a new array
    $newArray = array();
    // Now reindex all the value into the new array in the proper order
    for ($j=0, $i=0; $i < count($oldArrayInOrder)+1; $i++) {
        if($i == $indexToMove)
        {
            $newArray[$i]=$reIndexedValue;
            continue;
        }
        else
        {
            $newArray[$i] = $oldArrayInOrder[$j];
            $j++;
        }
    }
    return($newArray);
}
</code>```

Title: Change key of entries in PHP array

Body:
I'm currently trying to build a complex function to re-order the positions of some sections (div's) which are defined in a PHP array.

So for example I've this array here:

$sections = array(
    0 => 'section_one',
    1 => 'section_two',
    2 => 'section_three',
    3 => 'section_four',
    4 => 'section_five',
    5 => 'section_six',
    6 => 'section_seven'
);

Which turns out like this:

array(7) { [0]=> string(11) "section_one" [1]=> string(11) "section_two" [2]=> string(13) "section_three" [3]=> string(12) "section_four" [4]=> string(12) "section_five" [5]=> string(11) "section_six" [6]=> string(13) "section_seven" }

When the user moves now the section six before section two on my website, I need to change the key of section six to 1 and move every key one number up after the moved section. So section_two becomes the key 2 and so on...

Any idea how I can do this? I know that I can replace keys this way:

$arr[ $newkey ] = $arr[ $oldkey ];
unset( $arr[ $oldkey ] );

When the user finished a move of an element, I know the name like section_six and the new position of the element.

After re-ordering / re-placing the keys, the array must look like this:

$sections_a = array(
    0 => 'section_one',
    1 => 'section_six',
    2 => 'section_two',
    3 => 'section_three',
    4 => 'section_four',
    5 => 'section_five',
    6 => 'section_seven'
);

Body:
I see @Eddie has given a better solution than mine thanks Eddie,
but here is the custom function I made for this if it helps anyone.

// This function returns the new array
function reindexArray($array,       // Array
                      $index,       // Index of the value that you to change the index of
                      $indexToMove) // Index that you want to move that value
{
    // Store the value to be reindex in a variable
    $reIndexedValue = $array[$index];
    // Remove that value from the array
    unset($array[$index]);
    // Reorder the original array
    $oldArrayInOrder = array_values($array);
    // Create a new array
    $newArray = array();
    // Now reindex all the value into the new array in the proper order
    for ($j=0, $i=0; $i < count($oldArrayInOrder)+1; $i++) {
        if($i == $indexToMove)
        {
            $newArray[$i]=$reIndexedValue;
            continue;
        }
        else
        {
            $newArray[$i] = $oldArrayInOrder[$j];
            $j++;
        }
    }
    return($newArray);
}


问:
Subtract month/year to get years
```<code>data = data.frame("start"= c("1/2000","8/2004","99/9999"),
                  "stop"=c("1/2001","2/2007","09/2010"),
                  "WANTYEARS"= c(1,2.5,NA))
</code>```

I have date in month/year format and want to subtract to get the years.

My attempt of simple data$stop - data$start did not yield the desired results. THank you.

答:
One option is to use difftime from base R. Add "01" to stop and start date to create an actual Date object and subtract those dates using difftime with unit as "weeks" and divide it by number of weeks in year to get time difference in year,

```<code>round(difftime(as.Date(paste0("01/", data$stop), "%d/%m/%Y"),
      as.Date(paste0("01/", data$start), "%d/%m/%Y"), units = "weeks")/52.2857, 2)

#[1] 1.0 2.5  NA
</code>```

We can do the same using any other unit component of difftime as well if we know the equivalent year conversion ratio like for example with "days"

```<code>round(difftime(as.Date(paste0("01/", data$stop), "%d/%m/%Y"),
      as.Date(paste0("01/", data$start), "%d/%m/%Y"), units = "days")/365.25, 2)
#[1] 1.0 2.5  NA
</code>```

Title: Subtract month/year to get years

Body:
data = data.frame("start"= c("1/2000","8/2004","99/9999"),
                  "stop"=c("1/2001","2/2007","09/2010"),
                  "WANTYEARS"= c(1,2.5,NA))

I have date in month/year format and want to subtract to get the years.

My attempt of simple data$stop - data$start did not yield the desired results. THank you.

Body:
One option is to use difftime from base R. Add "01" to stop and start date to create an actual Date object and subtract those dates using difftime with unit as "weeks" and divide it by number of weeks in year to get time difference in year,

round(difftime(as.Date(paste0("01/", data$stop), "%d/%m/%Y"),
      as.Date(paste0("01/", data$start), "%d/%m/%Y"), units = "weeks")/52.2857, 2)

#[1] 1.0 2.5  NA

We can do the same using any other unit component of difftime as well if we know the equivalent year conversion ratio like for example with "days"

round(difftime(as.Date(paste0("01/", data$stop), "%d/%m/%Y"),
      as.Date(paste0("01/", data$start), "%d/%m/%Y"), units = "days")/365.25, 2)
#[1] 1.0 2.5  NA


问:
Why can't I use var in this instance?
I am using the code below and for some reason I can't use var to declare my variable. I am brand new to asp/c# so please go easy on me. I've had a look around and I can't find the correct way of doing this:

```<code>var brandslist = from brand in brandDB.brands
                         join brand_family in brandDB.brand_family on brand.brand_family_id equals brand_family.bf_id
                         orderby brand_family.brand_family_name
                         orderby brand.priority
                         orderby brand.genre_id
                         select brand_family.brand_family_name, priority, roll_image;
</code>```

Thanks to anyone who can tell me the correct method of making this work.

答:
Fixed :D</p>

```<code>var brandslist = from brand in brandDB.brands
                 join brand_family in brandDB.brand_family on brand.brand_family_id equals brand_family.bf_id
                 orderby brand_family.brand_family_name,
                         brand.priority,
                         brand.genre_id
                 select new {brand_family.brand_family_name, brand.priority, brand.roll_image};
</code>```

Title: Why can't I use var in this instance?

Body:
I am using the code below and for some reason I can't use var to declare my variable. I am brand new to asp/c# so please go easy on me. I've had a look around and I can't find the correct way of doing this:

var brandslist = from brand in brandDB.brands
                         join brand_family in brandDB.brand_family on brand.brand_family_id equals brand_family.bf_id
                         orderby brand_family.brand_family_name
                         orderby brand.priority
                         orderby brand.genre_id
                         select brand_family.brand_family_name, priority, roll_image;

Thanks to anyone who can tell me the correct method of making this work.

Body:
Fixed :D

var brandslist = from brand in brandDB.brands
                 join brand_family in brandDB.brand_family on brand.brand_family_id equals brand_family.bf_id
                 orderby brand_family.brand_family_name,
                         brand.priority,
                         brand.genre_id
                 select new {brand_family.brand_family_name, brand.priority, brand.roll_image};


答:
Introduce a new column, start_period:

```<code>df['start_period'] = (df['discount_weeks'].diff().ne(1)).astype(int)
</code>```

Then, for each book_id, you can define discount_periods as the cumulative sum of start_period:

```<code>df['discount_periods'] = df.groupby(['book_id'])['start_period'].cumsum()
</code>```

```<code>import pandas as pd

df = pd.DataFrame({
    'book_id': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1,1, 1, 1, 1, 1, 1, 1, 1, 1,1,1,1, 2, 2, 2],
    'week_id': [199, 200, 201, 202, 203, 204, 205, 206, 208, 209,211, 212, 213,214,216,
                217,218,219,220,222,223,224,225,226,228]})

df['discount_weeks']=df.groupby(['book_id', df['week_id'].diff().ne(1).cumsum()]).cumcount()+1
df['total'] = df['discount_weeks'].diff().ne(1).cumsum()

# df['start_period'] = (df['discount_weeks'] == 1).astype(int)  # also works, if every period starts with discount_weeks equal to 1
df['start_period'] = (df['discount_weeks'].diff().ne(1)).astype(int)
df['discount_periods'] = df.groupby(['book_id'])['start_period'].cumsum()

print(df)
</code>```

yields

```<code>    book_id  week_id  discount_weeks  discount_periods  total
0         1      199               1                 1      1
1         1      200               2                 1      1
2         1      201               3                 1      1
3         1      202               4                 1      1
4         1      203               5                 1      1
5         1      204               6                 1      1
6         1      205               7                 1      1
7         1      206               8                 1      1
8         1      208               1                 2      2
9         1      209               2                 2      2
10        1      211               1                 3      3
11        1      212               2                 3      3
12        1      213               3                 3      3
13        1      214               4                 3      3
14        1      216               1                 4      4
15        1      217               2                 4      4
16        1      218               3                 4      4
17        1      219               4                 4      4
18        1      220               5                 4      4
19        1      222               1                 5      5
20        1      223               2                 5      5
21        1      224               3                 5      5
22        2      225               1                 1      6
23        2      226               2                 1      6
24        2      228               1                 2      7
</code>```

Title: How to create periods in dataFrame using pandas?

Body:
I'm trying to create periods with using cumsum() and cumcount(). How to create periods for each book?

Period - continuous weekly sequence.
For example If (week) - (previous week) > 1 => new period.

I've tried

df = pd.DataFrame({'book_id': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1,1, 1, 1, 1, 1, 1, 1, 1, 1,1,1,1, 2, 2, 2],
                   'week_id': [199, 200, 201, 202, 203, 204, 205, 206, 208, 209,211, 212, 213,214,216,217,218,219,220,222,223,224,225,226,228]})

df['discount_weeks']=df.groupby(['book_id', df['week_id'].diff().ne(1).cumsum()]).cumcount()+1

df['discount_periods'] = df.groupby(['book_id','discount_weeks']).cumcount()+1

df['total'] = df['discount_weeks'].diff().ne(1).cumsum()
print(df)

    book_id  week_id  discount_weeks  discount_periods  total
0         1      199               1                 1      1
1         1      200               2                 1      1
2         1      201               3                 1      1
3         1      202               4                 1      1
4         1      203               5                 1      1
5         1      204               6                 1      1
6         1      205               7                 1      1
7         1      206               8                 1      1
8         1      208               1                 2      2
9         1      209               2                 2      2
10        1      211               1                 3      3
11        1      212               2                 3      3
12        1      213               3                 2      3
13        1      214               4                 2      3
14        1      216               1                 4      4
15        1      217               2                 4      4
16        1      218               3                 3      4
17        1      219               4                 3      4
18        1      220               5                 2      4
19        1      222               1                 5      5
20        1      223               2                 5      5
21        1      224               3                 4      5
22        2      225               1                 1      6
23        2      226               2                 1      6
24        2      228               1                 2      7

but 'discount_periods' works incorrectly in some places (12,13,16,17,18 ...)

Final result should be:

    book_id  week_id  discount_weeks  discount_periods  total
0         1      199               1                 1      1
1         1      200               2                 1      1
2         1      201               3                 1      1
3         1      202               4                 1      1
4         1      203               5                 1      1
5         1      204               6                 1      1
6         1      205               7                 1      1
7         1      206               8                 1      1
8         1      208               1                 2      2
9         1      209               2                 2      2
10        1      211               1                 3      3
11        1      212               2                 3      3
12        1      213               3                 3      3
13        1      214               4                 3      3
14        1      216               1                 4      4
15        1      217               2                 4      4
16        1      218               3                 4      4
17        1      219               4                 4      4
18        1      220               5                 4      4
19        1      222               1                 5      5
20        1      223               2                 5      5
21        1      224               3                 5      5
22        2      225               1                 1      6
23        2      226               2                 1      6
24        2      228               1                 2      7

Maybe other methods will work better here than cumsum(), cumcount()?

Body:
Introduce a new column, start_period:

df['start_period'] = (df['discount_weeks'].diff().ne(1)).astype(int)

Then, for each book_id, you can define discount_periods as the cumulative sum of start_period:

df['discount_periods'] = df.groupby(['book_id'])['start_period'].cumsum()

import pandas as pd

df = pd.DataFrame({
    'book_id': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1,1, 1, 1, 1, 1, 1, 1, 1, 1,1,1,1, 2, 2, 2],
    'week_id': [199, 200, 201, 202, 203, 204, 205, 206, 208, 209,211, 212, 213,214,216,
                217,218,219,220,222,223,224,225,226,228]})

df['discount_weeks']=df.groupby(['book_id', df['week_id'].diff().ne(1).cumsum()]).cumcount()+1
df['total'] = df['discount_weeks'].diff().ne(1).cumsum()

# df['start_period'] = (df['discount_weeks'] == 1).astype(int)  # also works, if every period starts with discount_weeks equal to 1
df['start_period'] = (df['discount_weeks'].diff().ne(1)).astype(int)
df['discount_periods'] = df.groupby(['book_id'])['start_period'].cumsum()

print(df)

yields

    book_id  week_id  discount_weeks  discount_periods  total
0         1      199               1                 1      1
1         1      200               2                 1      1
2         1      201               3                 1      1
3         1      202               4                 1      1
4         1      203               5                 1      1
5         1      204               6                 1      1
6         1      205               7                 1      1
7         1      206               8                 1      1
8         1      208               1                 2      2
9         1      209               2                 2      2
10        1      211               1                 3      3
11        1      212               2                 3      3
12        1      213               3                 3      3
13        1      214               4                 3      3
14        1      216               1                 4      4
15        1      217               2                 4      4
16        1      218               3                 4      4
17        1      219               4                 4      4
18        1      220               5                 4      4
19        1      222               1                 5      5
20        1      223               2                 5      5
21        1      224               3                 5      5
22        2      225               1                 1      6
23        2      226               2                 1      6
24        2      228               1                 2      7


问:
Tkinter GUI disappears when file selection dialog appears
Background:
I am building a GUI for a PDF app. This app requires that the user select the location of the file and provide some additional information so that a cover page can be generated and then appended to a PDF. I have chosen Tkinter to create the GUI for this app. I developing on Mac OS.

Problem:
I am able to generate a file selection dialog upon pressing the form's button, however, the GUI disappears immediately after the file selection dialog appears. Does someone know what is causing this?

```<code>from tkinter import *
from tkinter import filedialog

root = Tk()
Label(root, text='Submittal No. ').grid(row=0)
Label(root, text='Project Name ').grid(row=1)
Label(root, text='Product Name ').grid(row=2)
e1 = Entry(root)
e2 = Entry(root)
e3 = Entry(root)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
e3.grid(row=2, column=1)

def fileSelector():
    root.withdraw()
    root.fileName = filedialog.askopenfilename()
    print(root.fileName)

Button(root, text='Select PDF file ', command=fileSelector).grid(row=3)

if __name__ == "__main__":
    mainloop()
</code>```

答:
The reason your GUI disappears is because of the statement

```<code> root.withdraw()
</code>```

Delete this statement and your GUI remains visible.

Body:
Background:
I am building a GUI for a PDF app. This app requires that the user select the location of the file and provide some additional information so that a cover page can be generated and then appended to a PDF. I have chosen Tkinter to create the GUI for this app. I developing on Mac OS.

Problem:
I am able to generate a file selection dialog upon pressing the form's button, however, the GUI disappears immediately after the file selection dialog appears. Does someone know what is causing this?

from tkinter import *
from tkinter import filedialog

root = Tk()
Label(root, text='Submittal No. ').grid(row=0)
Label(root, text='Project Name ').grid(row=1)
Label(root, text='Product Name ').grid(row=2)
e1 = Entry(root)
e2 = Entry(root)
e3 = Entry(root)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
e3.grid(row=2, column=1)

def fileSelector():
    root.withdraw()
    root.fileName = filedialog.askopenfilename()
    print(root.fileName)

Button(root, text='Select PDF file ', command=fileSelector).grid(row=3)

if __name__ == "__main__":
    mainloop()

Body:
The reason your GUI disappears is because of the statement

 root.withdraw()

Delete this statement and your GUI remains visible.


问:
get the database Name , Creation Date when Database is UNmounted Oracle 11g
Is it possible to get the database name , Creation Date
when the database is on Startup but NOT mounted ?

when it is mounted we can use this statement :

```<code>select NAME,CREATED from V$DATABASE ;
</code>```

Any help please?

答: No.  When unmounted, the only file that has been opened is the parameter file - init or spfile.  The only information there is that which is needed properly allocate memory for the instance, where to write critical logs, and where to find the control file(s).</p>

Body:
Is it possible to get the database name , Creation Date
when the database is on Startup but NOT mounted ?

when it is mounted we can use this statement :

select NAME,CREATED from V$DATABASE ;

Any help please?


问:
Elasticsearch query to return all records
I have a small database in Elasticsearch and for testing purposes would like to pull all records back.  I am attempting to use a URL of the form...

```<code>http://localhost:9200/foo/_search?pretty=true&q={'matchAll':{''}}
</code>```

Can someone give me the URL you would use to accomplish this, please?

答:
this is the query to accomplish what you want,
(I am suggesting to use Kibana, as it helps to understand queries better)

```<code>GET my_index_name/my_type_name/_search
{
   "query":{
      "match_all":{}
   },
   size : 20,
   from : 3
}
</code>```

to get all records you have to use "match_all" query.

size is the no of records you want to fetch (kind of limit).
by default, ES will only return 10 records

from is like skip, skip first 3 records.

If you want to fetch exactly all the records, just use the value from the "total" field
from the result once you hit this query from Kibana and the use it with "size".

Body:
I have a small database in Elasticsearch and for testing purposes would like to pull all records back.  I am attempting to use a URL of the form...

http://localhost:9200/foo/_search?pretty=true&q={'matchAll':{''}}

Can someone give me the URL you would use to accomplish this, please?

Body:
this is the query to accomplish what you want,
(I am suggesting to use Kibana, as it helps to understand queries better)

GET my_index_name/my_type_name/_search
{
   "query":{
      "match_all":{}
   },
   size : 20,
   from : 3
}

to get all records you have to use "match_all" query.

size is the no of records you want to fetch (kind of limit).
by default, ES will only return 10 records

from is like skip, skip first 3 records.

If you want to fetch exactly all the records, just use the value from the "total" field
from the result once you hit this query from Kibana and the use it with "size".