问:
Media Queries are not working. How do I solve this
So I built a website resembling a template that I found. The website has two grids in it and I want to change the number of columns and rows with media queries to make the website responsive. However, the media queries just refuse to work properly. There are 2 problems: 1) It does what I want but not WHEN I want, 2) It doesn't do anything at all.

```<code>   @media screen and (max-width:760px) {
   body{
        background-color: green;
       }
   }
</code>```

this, for example, will work, but the color changes only when the screen is at least 600px wide

```<code>  @media only screen and (max-width: 760px) {
  #grid {
      grid-template-columns: 1fr 1fr ;
      grid-template-rows: 2fr 2fr 2fr 2fr;
  }
 }
</code>```

This one won't work at all.
Please help, this is so frustrating, I feel dumb

答:
Since you're building upon an existing template you might have an issue with specificity.

Try to override it by putting !important at the end of the declarations which aren't working.

For example:

```<code>@media screen and (max-width:760px) {
   body{
        background-color: green !important;
       }
   }
</code>```

A better way to do this is to use your browser's inspector to find the declaration which is overriding yours and then edit it (if you have access to that code). But the !important is a quick solution for now.

Body:
So I built a website resembling a template that I found. The website has two grids in it and I want to change the number of columns and rows with media queries to make the website responsive. However, the media queries just refuse to work properly. There are 2 problems: 1) It does what I want but not WHEN I want, 2) It doesn't do anything at all.

   @media screen and (max-width:760px) {
   body{
        background-color: green;
       }
   }

this, for example, will work, but the color changes only when the screen is at least 600px wide

  @media only screen and (max-width: 760px) {
  #grid {
      grid-template-columns: 1fr 1fr ;
      grid-template-rows: 2fr 2fr 2fr 2fr;
  }
 }

This one won't work at all.
Please help, this is so frustrating, I feel dumb

Body:
Since you're building upon an existing template you might have an issue with specificity.

Try to override it by putting !important at the end of the declarations which aren't working.

For example:

@media screen and (max-width:760px) {
   body{
        background-color: green !important;
       }
   }

A better way to do this is to use your browser's inspector to find the declaration which is overriding yours and then edit it (if you have access to that code). But the !important is a quick solution for now.


来源: stackexchange

问:
Why am I getting .clear() is not a function while clearing a datatable?
I'm getting the error below:

getdata.js:96 Uncaught TypeError: $(...).dataTable(...).clear is not a function

When I use the following code:

```<code>$("#dynamic-table").dataTable().clear();
</code>```

Although the function works fine and clears the datatable but I get an error in console

答:
dataTable() and DataTable() both functions are different. If you want to clear your data-table then use this code.

$('#myTable').DataTable().clear().draw();

ContentLicense: CC BY-SA 3.0

Body:
I'm getting the error below:

getdata.js:96 Uncaught TypeError: $(...).dataTable(...).clear is not a function

When I use the following code:

$("#dynamic-table").dataTable().clear();

Although the function works fine and clears the datatable but I get an error in console

ContentLicense: CC BY-SA 4.0


问:
Laravel and VueJs: Cannot set property 'cats' of undefined
I'm having this code in the blade:

```<code><list-categories-component></list-categories-component>
</code>```

and this template with vue code

```<code><template>
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">Example Component</div>
                <div class="card-body">
                    <ul>
                    <li v-for="cat in cats" :key="cat.cat_id">{{cat.cat_en_title}}</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>
</template>

<script>
export default {
    data(){
        return{
            cats:[],
        };
    },
    created() {
        this.fetchTaskList();
    },
    methods:{
        fetchTaskList(){
            axios.get('/api/listCats')
                .then(function (response) {
                    console.log(response.data.cats);
                    this.cats = response.data.cats;

                })
                .catch(function (error) {
                    // handle error
                    console.log(error);
                });
        }

    }
}
</script>
</code>```

and here's the axios response

and here's the log

but data can't be rendered successfully as it find an error here

this.cats = response.data.cats;
```

I changed this.cats = response.data.cats to this.cats = response.data to catch the array itself but still getting the same error.

I'm running npm run watch so what's the problem here and how to fix it?

答:
Change your functions inside then and catch to arrow functions, in order to read this as the vue component:

methods:{
        fetchTaskList(){
            axios.get('/api/listCats')
                .then(response => {
                    console.log(response.data.cats);
                    this.cats = response.data.cats;

                })
                .catch( error => {
                    // handle error
                    console.log(error);
                });
        }

}
```

Body:
I'm having this code in the blade:

<list-categories-component></list-categories-component>

and this template with vue code

<template>

Example Component

{{cat.cat_en_title}}

</template>

and here's the axios response

and here's the log

but data can't be rendered successfully as it find an error here

this.cats = response.data.cats;

I changed this.cats = response.data.cats to this.cats = response.data to catch the array itself but still getting the same error.

I'm running npm run watch so what's the problem here and how to fix it?


问:
Can you run a rails console or rake command in the elastic beanstalk environment?
I have set up a RoR environement on AWS' elastic beanstalk.  I am able to ssh into my EC2 instance.
My home directory is /home/ec2-user, which is effectively empty.
If I move up a directory, there is also a /home/webapp directory that i do not have access to.

Is there a way to run a rake command or rails console on my elastic beanstalk instance?

If I type rails console I get Usage: rails new APP_PATH [options]
If I type RAILS_ENV=production bundle exec rails console, I get "Could not locate Gemfile"

答:
For the latest ruby version, please use the following command:

BUNDLE_PATH=/opt/rubies/ruby-2.6.3/lib/ruby/gems/2.6.0/ bundle exec rails c production

Running it with sudo is not needed.


问:
How to restrict edit script to run in specific column _google sheets
I am running a script in sheets to allow multiple selection. The script works but when i go to edit a cell somewhere else on the sheet the information disappears. I need to run this script only for column 5, so if something is documented elsewhere, it wont keep disappearing. </p>

```<code>function onEdit(e) {
    var oldValue;
    var newValue;
    var ss=SpreadsheetApp.getActiveSpreadsheet();
    var activeCell = ss.getActiveCell();
    if(activeCell.getColumn() == 5 && ss.getActiveSheet().getName()=="TRACKER- Relaunch")
        newValue=e.value;
    oldValue=e.oldValue;
    if(!e.value) {
        activeCell.setValue("");
    }
    else {
        if (!e.oldValue) {
            activeCell.setValue(newValue);
        }
        else {
            if(oldValue.indexOf(newValue) <0) {
                activeCell.setValue(oldValue+','+newValue);
            }
            else {
                activeCell.setValue(oldValue);
            }
        }
    }
}
</code>```

答:
Wrap your function in an if statement which checks that the changed cell is in the 5th columns and that you are in the correct sheet.

```<code>function onEdit( event ){
  const columnOfCell = event.columnStart;
  const currentSheetName = SpreadsheetApp.getActiveSheet().getName();
  const targetSheetName = "TRACKER- Relaunch";

  if( columnOfCell === 5 && currentSheetName === targetSheetName){
    // work your magic here
  }
}
</code>```

Body:
I am running a script in sheets to allow multiple selection. The script works but when i go to edit a cell somewhere else on the sheet the information disappears. I need to run this script only for column 5, so if something is documented elsewhere, it wont keep disappearing.

function onEdit(e) {
    var oldValue;
    var newValue;
    var ss=SpreadsheetApp.getActiveSpreadsheet();
    var activeCell = ss.getActiveCell();
    if(activeCell.getColumn() == 5 && ss.getActiveSheet().getName()=="TRACKER- Relaunch")
        newValue=e.value;
    oldValue=e.oldValue;
    if(!e.value) {
        activeCell.setValue("");
    }
    else {
        if (!e.oldValue) {
            activeCell.setValue(newValue);
        }
        else {
            if(oldValue.indexOf(newValue) <0) {
                activeCell.setValue(oldValue+','+newValue);
            }
            else {
                activeCell.setValue(oldValue);
            }
        }
    }
}

Body:
Wrap your function in an if statement which checks that the changed cell is in the 5th columns and that you are in the correct sheet.

function onEdit( event ){
  const columnOfCell = event.columnStart;
  const currentSheetName = SpreadsheetApp.getActiveSheet().getName();
  const targetSheetName = "TRACKER- Relaunch";

  if( columnOfCell === 5 && currentSheetName === targetSheetName){
    // work your magic here
  }
}


问:
Get list of all controllers and action in laravel 5
I am new to laravel and would like to fetch list of all controllers and list of action in that controller.
Just want to know if there is a way to get a list of all Controllers as well as all their Methods by code?

Thanks,
DJ

答:
That worked for me.

Extracting all controllers (App\Http\Controllers)

```<code>
$controllers = require_once base_path('vendor/composer/autoload_classmap.php');
$controllers = array_keys($controllers);
$controllers = array_filter($controllers, function ($controller) {
    return strpos($controller, 'App\Http\Controllers') !== false;
});

$controllers = array_map(function ($controller) {

    return str_replace('App\Http\Controllers\\', '', $controller);
}, $controllers);

dd($controllers);
</code>```

Extracting all methods in a specific controller using ReflectionClass

```<code>$namespace = "App\Http\Controllers";
$controller = "TestController";
$controller_class = new ReflectionClass($namespace.'\\'.$controller);
$controller_methods = $controller_class->getMethods(ReflectionMethod::IS_PUBLIC);
dd($controller_methods);
</code>```

One catch though. You may need to run composer dump-autoload after creating a controller.

Body:
That worked for me.

Extracting all controllers (App\Http\Controllers)

$controllers = require_once base_path('vendor/composer/autoload_classmap.php');
$controllers = array_keys($controllers);
$controllers = array_filter($controllers, function ($controller) {
    return strpos($controller, 'App\Http\Controllers') !== false;
});

$controllers = array_map(function ($controller) {

    return str_replace('App\Http\Controllers\\', '', $controller);
}, $controllers);

dd($controllers);

Extracting all methods in a specific controller using ReflectionClass

$namespace = "App\Http\Controllers";
$controller = "TestController";
$controller_class = new ReflectionClass($namespace.'\\'.$controller);
$controller_methods = $controller_class->getMethods(ReflectionMethod::IS_PUBLIC);
dd($controller_methods);

One catch though. You may need to run composer dump-autoload after creating a controller.


问:
React Native Make PDF file
I want to make a pdf file into android phone. So far i just found https://www.npmjs.com/package/react-native-html-to-pdf allow me to make a pdf file but it used html. Is there any others packages other than react-native-html-to-pdf able to make a pdf file?

答:
Yes,there is: react-native-pdf-lib

here is the link: https://www.npmjs.com/package/react-native-pdf-lib

Title: React Native Make PDF file


问:
AjaxControlToolkit ModalPopup in Asp.net MVC
I have a DashBoard view.
On clicking on Assign button a ModalPopup Opens like :

Code for opening PopUp

```<code>$create(AjaxControlToolkit.ModalPopupBehavior,
    {
        "BackgroundCssClass": "modalBackground",
        "DropShadow": false,
        "OkControlID":
        "OkButton",
        "OnOkScript": "onOk()",
        "PopupControlID": "div_to_popup",
        "id": "PopUpBox"
    }, null, null, $get("day"+a));

function onOk(){
  // what to write here to save data on server
}
</code>```

答:
You could probably do this with a jQuery plugin of your choice.

I would advise against using the Ajax Control Toolkit with ASP.NET MVC at all, since it is both old and kind of hacky to begin with, and (more importantly) heavily targeted against WebForms development.

Body:
I have a DashBoard view.
On clicking on Assign button a ModalPopup Opens like :

Code for opening PopUp

$create(AjaxControlToolkit.ModalPopupBehavior,
    {
        "BackgroundCssClass": "modalBackground",
        "DropShadow": false,
        "OkControlID":
        "OkButton",
        "OnOkScript": "onOk()",
        "PopupControlID": "div_to_popup",
        "id": "PopUpBox"
    }, null, null, $get("day"+a));

function onOk(){
  // what to write here to save data on server
}


问:
How to model a simple Workout app (Class diagram)
I've developed a simple Workout Android app without uml class diagram in mind. Now I want to refactor it.

How the app works

On the home screen, there's just a button to start an workout session. By clicking on it, a countdown of 10 seconds is fired, waiting for the person to get ready.

Then, the app will display several exercises, one at a time, with a break interval between them. Each exercise takes 30 seconds; and each break interval, 10 seconds. On each exercise/break, the app shows the following information:

A countdown timer of the current exercise/break;

The name of the current exercise or, in the case of a break interval, the name of the next exercise;

An image that illustrates the current (or the next) exercise;

A pause button.

Finally, when the workout session finishes, the app shows a GIF as a celebration. On this last screen there's also a "Go home" button.

The UML class diagram

I've made the following UML class diagram to model this app:

My doubts

However, I'm not so sure if this is the proper way to model the scenario described. I'd appreciate if I could get some feedback/review about it.

One of the main things that I'm in doubt of has to deal with the WorkoutActivity class. It has no attributes in the diagram because I couldn't think of any attribute for it in the way that I'm modeling this problem. And because it's empty, it's a little weird to me. I thought about using a list class (e.g. ExercisesList) to model the set of exercises, but I'm kind of stuck with this diagram.

Another issue is about the buttons, should I include them in the diagram?

答:
It all depends on what you want to represent.

If your model is meant for the domain of workouts, keep it simple: the buttons (the user interface objects) and the timer (execution context) would not be needed.

In the narrative you mentioned a "workout session". I assume that this is what the WorkoutActivity is about. So better be consistent with the naming.

You can think easily of attributes: it’s the date and time (and user account?) of the session: this could allow the user to follow his/her regularity in the training.

A more general approach would be to have a WorkoutSession composed of several abstract WorkoutActivity (caution: different meaning than in your current diagram). Each WorkoutActivity would be a specialisation: either an Exercise, a BreakInterval or a InfoActivity (e.g. FinalActivity, but why not also a StartActivity activity to encourage new users, and other occasional activities such as tips&tricks, or advertisement). Something like:

The constraint of having one break after each exercise does not need to be structural: it can be a constraint that you enforce when the session is composed or generated. This gives you more flexibility, if in the future you’d line to have a break every 2 or 3 exercises (e.g.:advanced users).


问:
dotnet is not recognized as the name of a cmdlet (MacOS)
This is a really weird thing that happens to me now and then. When using visual studio on mac and I use the Nuget Package manager console, sometimes it looses access to dotnet. Then I start pocking around and somehow it fixes again (it can take a lot of time).

The weird thing is that dotnet is installed, never was moved and I can run it in Terminal without any location. So, it is added to the Path.

Has anybody suffered from this problem? Is there any way to fix that?

答:
I had the same issue. It happens randomly. Lost a couple of hours from my life until I found a workaround that solves the issue.

I am using:

NuGet Package Manager Console (NuGet 5.6.0.5)

in Visual Studio for Mac COMMUNITY Version 8.6.1

and use it for Entity Framework commands

Example command:

```<code>PM> Update-Database
Build started...
Build succeeded.
The running command stopped because the preference variable "ErrorActionPreference" or common parameter is set to Stop: The term 'dotnet' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
</code>```

A couple of minutes ago realized that by cleaning the project the issue goes away.

```<code>Visual Studio -> Build -> Clean All
</code>```

Then when running again the command in NuGet PM it is executed without any issue.

```<code>PM>  Update-Database
Build started...
Build succeeded.
No migrations were applied. The database is already up to date.
Done.
</code>```

The issue was also posted to the developer community web page, but was soon closed without any resolution:
https://developercommunity.visualstudio.com/content/problem/913964/dotnet-the-term-dotnet-is-not-recognized-as-the-na.html
I am about to reconsider this issue. Hope they will come up with a fix.

Body:
I had the same issue. It happens randomly. Lost a couple of hours from my life until I found a workaround that solves the issue.

I am using:

NuGet Package Manager Console (NuGet 5.6.0.5)

in Visual Studio for Mac COMMUNITY Version 8.6.1

and use it for Entity Framework commands

Example command:

PM> Update-Database
Build started...
Build succeeded.
The running command stopped because the preference variable "ErrorActionPreference" or common parameter is set to Stop: The term 'dotnet' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

A couple of minutes ago realized that by cleaning the project the issue goes away.

Visual Studio -> Build -> Clean All

Then when running again the command in NuGet PM it is executed without any issue.

PM>  Update-Database
Build started...
Build succeeded.
No migrations were applied. The database is already up to date.
Done.

The issue was also posted to the developer community web page, but was soon closed without any resolution:
https://developercommunity.visualstudio.com/content/problem/913964/dotnet-the-term-dotnet-is-not-recognized-as-the-na.html
I am about to reconsider this issue. Hope they will come up with a fix.


问:
Why does this code not achieve the objective of restoring a Derby database from a backup copy of the database?
I have a JavaFXML application that accesses an embedded Derby database. The database is stored in this file subsystem:

The directory db contains the usual Derby files and directories:

The Backups directory in fig 1 are copies of db that a user can create from the applications GUI. For example:

What I want to achieve is to be able to select one of the backup files from the GUI and replace the current database contained in db. I have verified the integrity of these backups by manually deleting db and replacing it with a backup.

The code to try and achieve the objective is:

```<code>public class NdBkp
{
  private static Connection conn = null;
  public final static String SETUP_FILE_PATH = "/AppData/Local/NewdawnTest_old/";
  public static final String CONNECTION_URL = "jdbc:derby:" + "C:/Users/" + System.getenv("USERNAME") + SETUP_FILE_PATH + "db";
  public static final String BACKUP_FILE_PATH = "C:/Users/" + System.getenv("USERNAME") + SETUP_FILE_PATH + "Backups";

  public static void connect() {
    try {
//      conn = DriverManager.getConnection(CONNECTION_URL  + ";create=true");
      conn = DriverManager.getConnection(CONNECTION_URL);
    }
    catch (SQLException e) {
      e.printStackTrace();
    }
  }

  public static void commit(){
    try {
      conn.commit();
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }

  public static boolean isConnected() {
    try{
      System.out.println("");
      return (!(conn.isClosed()));
    }
    catch (SQLException | NullPointerException e){
      e.printStackTrace();
      return false;
    }
  }

  public static void disconnect() {
    try {
      if (conn != null) {
        conn.close();
        conn = null;
      }
    } catch (SQLException e) {
       e.printStackTrace();
    }
  }

  public static void backUpDatabase(String dirname) {
    try {
      CallableStatement cs = conn.prepareCall("CALL SYSCS_UTIL.SYSCS_BACKUP_DATABASE(?)");
      cs.setString(1, BACKUP_FILE_PATH + "/" + dirname);
      cs.execute();
      cs.close();
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }

  public static void restoreDatabase(String backupdirpath) {
    System.out.println("Restoring " + CONNECTION_URL + " from + " + backupdirpath);
    try {
      DriverManager.getConnection(CONNECTION_URL + ";restoreFrom=backupdirpath");
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }

  public static void main (String [] args)
  {
    String backupdirpath = "C:/Users/Administrator/AppData/Local/NewdawnTest_old/Backups/20200515_bkp_02";
    connect();
    restoreDatabase(backupdirpath);
    System.out.println("Is connected is " + isConnected());
    disconnect();
    System.out.println("Is connected is " + isConnected());
 }
}
</code>```

When I compile and run this code, everything appears to work. There is no error dump or any indication that the requested operation defined in the restoreDatabase method has not worked. But when I look in the file system, nothing has in fact happened and the current version of db has remained unaffected. I cannot figure out why this is and don't know what is missing, so I would appreciate some assistance.

答:
Might the problem be, that you're just appending the word "backupdirpath" where you should be appending a value of variable referenced by this name?</p>

```<code>  public static void restoreDatabase(String backupdirpath) {
    System.out.println("Restoring " + CONNECTION_URL + " from + " + backupdirpath);
    try {
      // I think this:
      DriverManager.getConnection(CONNECTION_URL + ";restoreFrom=backupdirpath");
      // should be this:
      //DriverManager.getConnection(CONNECTION_URL + ";restoreFrom=" + backupdirpath);
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
</code>```

Body:
I have a JavaFXML application that accesses an embedded Derby database. The database is stored in this file subsystem:

The directory db contains the usual Derby files and directories:

The Backups directory in fig 1 are copies of db that a user can create from the applications GUI. For example:

What I want to achieve is to be able to select one of the backup files from the GUI and replace the current database contained in db. I have verified the integrity of these backups by manually deleting db and replacing it with a backup.

The code to try and achieve the objective is:

public class NdBkp
{
  private static Connection conn = null;
  public final static String SETUP_FILE_PATH = "/AppData/Local/NewdawnTest_old/";
  public static final String CONNECTION_URL = "jdbc:derby:" + "C:/Users/" + System.getenv("USERNAME") + SETUP_FILE_PATH + "db";
  public static final String BACKUP_FILE_PATH = "C:/Users/" + System.getenv("USERNAME") + SETUP_FILE_PATH + "Backups";

  public static void connect() {
    try {
//      conn = DriverManager.getConnection(CONNECTION_URL  + ";create=true");
      conn = DriverManager.getConnection(CONNECTION_URL);
    }
    catch (SQLException e) {
      e.printStackTrace();
    }
  }

  public static void commit(){
    try {
      conn.commit();
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }

  public static boolean isConnected() {
    try{
      System.out.println("");
      return (!(conn.isClosed()));
    }
    catch (SQLException | NullPointerException e){
      e.printStackTrace();
      return false;
    }
  }

  public static void disconnect() {
    try {
      if (conn != null) {
        conn.close();
        conn = null;
      }
    } catch (SQLException e) {
       e.printStackTrace();
    }
  }

  public static void backUpDatabase(String dirname) {
    try {
      CallableStatement cs = conn.prepareCall("CALL SYSCS_UTIL.SYSCS_BACKUP_DATABASE(?)");
      cs.setString(1, BACKUP_FILE_PATH + "/" + dirname);
      cs.execute();
      cs.close();
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }

  public static void restoreDatabase(String backupdirpath) {
    System.out.println("Restoring " + CONNECTION_URL + " from + " + backupdirpath);
    try {
      DriverManager.getConnection(CONNECTION_URL + ";restoreFrom=backupdirpath");
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }

  public static void main (String [] args)
  {
    String backupdirpath = "C:/Users/Administrator/AppData/Local/NewdawnTest_old/Backups/20200515_bkp_02";
    connect();
    restoreDatabase(backupdirpath);
    System.out.println("Is connected is " + isConnected());
    disconnect();
    System.out.println("Is connected is " + isConnected());
 }
}

When I compile and run this code, everything appears to work. There is no error dump or any indication that the requested operation defined in the restoreDatabase method has not worked. But when I look in the file system, nothing has in fact happened and the current version of db has remained unaffected. I cannot figure out why this is and don't know what is missing, so I would appreciate some assistance.

Body:
Might the problem be, that you're just appending the word "backupdirpath" where you should be appending a value of variable referenced by this name?

  public static void restoreDatabase(String backupdirpath) {
    System.out.println("Restoring " + CONNECTION_URL + " from + " + backupdirpath);
    try {
      // I think this:
      DriverManager.getConnection(CONNECTION_URL + ";restoreFrom=backupdirpath");
      // should be this:
      //DriverManager.getConnection(CONNECTION_URL + ";restoreFrom=" + backupdirpath);
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }


问:
Reading and writing to Java file at the same time?
I'm trying to read the contents of a java file in json format and update the file. My initial  plan was to create a new json object with the updated data i need and delete the old one and append the updated stuff to the file. I'm however having problems reading and writing the file at the same time. I've searched all over and haven't had any luck. Kindly take a look below. What I'm dong here is searching the file line by line for the username and then getting the value of the key "balance" and adding the new deposit to it. I however can't seem to find a way to write to the file.</p>

```<code>public static void depositAmount(){
    // Searching for user data
    String searchUser;
    Scanner sc = new Scanner(System.in);
    System.out.println("Please enter your username: ");
    searchUser = sc.nextLine();
    int deposit;
    StringBuilder sb = new StringBuilder();
    //Searching data for username and getting the deposit
    try
    {
        FileInputStream file = new FileInputStream("/Users/baidench/Documents/Github/Banking/banking.txt");
        Scanner scan = new Scanner(file);
        while(scan.hasNextLine())
        {
            final String line = scan.nextLine();
            if(line.contains(searchUser)){
                JSONObject customer = new JSONObject(line);
                int balance =  customer.getInt("balance");
                String name = customer.getString("fullName");
                System.out.println(name + ", your current balance is: " + balance);
                System.out.println("How much do you want to deposit? : ");
                deposit = sc.nextInt();
                customer.remove("balance");
                customer.put("balance", balance + deposit);
                JSONObject newCustomerData = customer;
                //sb.append(newCustomer);
                System.out.println(newCustomerData);

                //scan.close();

                //FileWriter filetoWrite = new FileWriter("/Users/baidench/Documents/Github/Banking/data.txt", true);
                //filetoWrite.write(sb + System.lineSeparator());
            }
        }
        scan.close();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}
</code>```

答:
You don't close the FileInputStream always must close your Input before create your Output.

```<code>//More Code
  customer.remove("balance");
                customer.put("balance", balance + deposit);
                JSONObject newCustomerData = customer;

                //sb.append(newCustomer);

                System.out.println(newCustomerData);

                scan.close();

               //This.
                file.close();

                FileWriter filetoWrite = new FileWriter("/Users/baidench/Documents/Github/Banking/data.txt", true);
                filetoWrite.write(sb + System.lineSeparator());

//More code....
...

</code>```

Body:
I'm trying to read the contents of a java file in json format and update the file. My initial  plan was to create a new json object with the updated data i need and delete the old one and append the updated stuff to the file. I'm however having problems reading and writing the file at the same time. I've searched all over and haven't had any luck. Kindly take a look below. What I'm dong here is searching the file line by line for the username and then getting the value of the key "balance" and adding the new deposit to it. I however can't seem to find a way to write to the file.

public static void depositAmount(){
    // Searching for user data
    String searchUser;
    Scanner sc = new Scanner(System.in);
    System.out.println("Please enter your username: ");
    searchUser = sc.nextLine();
    int deposit;
    StringBuilder sb = new StringBuilder();
    //Searching data for username and getting the deposit
    try
    {
        FileInputStream file = new FileInputStream("/Users/baidench/Documents/Github/Banking/banking.txt");
        Scanner scan = new Scanner(file);
        while(scan.hasNextLine())
        {
            final String line = scan.nextLine();
            if(line.contains(searchUser)){
                JSONObject customer = new JSONObject(line);
                int balance =  customer.getInt("balance");
                String name = customer.getString("fullName");
                System.out.println(name + ", your current balance is: " + balance);
                System.out.println("How much do you want to deposit? : ");
                deposit = sc.nextInt();
                customer.remove("balance");
                customer.put("balance", balance + deposit);
                JSONObject newCustomerData = customer;
                //sb.append(newCustomer);
                System.out.println(newCustomerData);

                //scan.close();

                //FileWriter filetoWrite = new FileWriter("/Users/baidench/Documents/Github/Banking/data.txt", true);
                //filetoWrite.write(sb + System.lineSeparator());
            }
        }
        scan.close();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}

Body:
You don't close the FileInputStream always must close your Input before create your Output.

//More Code
  customer.remove("balance");
                customer.put("balance", balance + deposit);
                JSONObject newCustomerData = customer;

                //sb.append(newCustomer);

                System.out.println(newCustomerData);

                scan.close();

               //This.
                file.close();

                FileWriter filetoWrite = new FileWriter("/Users/baidench/Documents/Github/Banking/data.txt", true);
                filetoWrite.write(sb + System.lineSeparator());

//More code....
...


问:
Jquery replacing text inside html
Is there a more elegant way replacing a text inside an html element than :</p>

```<code>$el = $("#myDiv");
$el.html( $el.html().replace("something", "something new") );
</code>```

答:
there is nothing more elegant than the example you wrote!
Check this exmple http://blog.chapagain.com.np/jquery-how-to-replace-string-div-content-and-image-src/</p>

Title: Jquery replacing text inside html

Body:
Is there a more elegant way replacing a text inside an html element than :

$el = $("#myDiv");
$el.html( $el.html().replace("something", "something new") );


问:
How to resize text for cv2.putText according to the image size in OpenCV, Python?

fontScale = 1
fontThickness = 1

# make sure font thickness is an integer, if not, the OpenCV functions that use this may crash
fontThickness = int(fontThickness)

upperLeftTextOriginX = int(imageWidth * 0.05)
upperLeftTextOriginY = int(imageHeight * 0.05)

textSize, baseline = cv2.getTextSize(resultText, fontFace, fontScale, fontThickness)
textSizeWidth, textSizeHeight = textSize

# calculate the lower left origin of the text area based on the text area center, width, and height
lowerLeftTextOriginX = upperLeftTextOriginX
lowerLeftTextOriginY = upperLeftTextOriginY + textSizeHeight

# write the text on the image
cv2.putText(openCVImage, resultText, (lowerLeftTextOriginX, lowerLeftTextOriginY), fontFace, fontScale, Color,
            fontThickness)
```

It seems fontScale does not scale text according to the image width and height because the text is almost in the same size for different sized images. So how can I resize the text according to the image size so that all the text could fit in the image?

答:
Here is the solution that will fit the text inside your rectangle. If your rectangles are of variable width, then you can get the font scale by looping through the potential scales and measuring how much width (in pixels) would your text take. Once you drop below your rectangle width you can retrieve the scale and use it to actually putText:

```<code>def get_optimal_font_scale(text, width):
    for scale in reversed(range(0, 60, 1)):
        textSize = cv.getTextSize(text, fontFace=cv.FONT_HERSHEY_DUPLEX, fontScale=scale/10, thickness=1)
        new_width = textSize[0][0]
        if (new_width <= width):
            print(new_width)
            return scale/10
    return 1
</code>```

Body:
fontScale = 1
fontThickness = 1

# make sure font thickness is an integer, if not, the OpenCV functions that use this may crash
fontThickness = int(fontThickness)

upperLeftTextOriginX = int(imageWidth * 0.05)
upperLeftTextOriginY = int(imageHeight * 0.05)

textSize, baseline = cv2.getTextSize(resultText, fontFace, fontScale, fontThickness)
textSizeWidth, textSizeHeight = textSize

# calculate the lower left origin of the text area based on the text area center, width, and height
lowerLeftTextOriginX = upperLeftTextOriginX
lowerLeftTextOriginY = upperLeftTextOriginY + textSizeHeight

# write the text on the image
cv2.putText(openCVImage, resultText, (lowerLeftTextOriginX, lowerLeftTextOriginY), fontFace, fontScale, Color,
            fontThickness)

It seems fontScale does not scale text according to the image width and height because the text is almost in the same size for different sized images. So how can I resize the text according to the image size so that all the text could fit in the image?

Body:
Here is the solution that will fit the text inside your rectangle. If your rectangles are of variable width, then you can get the font scale by looping through the potential scales and measuring how much width (in pixels) would your text take. Once you drop below your rectangle width you can retrieve the scale and use it to actually putText:

def get_optimal_font_scale(text, width):
    for scale in reversed(range(0, 60, 1)):
        textSize = cv.getTextSize(text, fontFace=cv.FONT_HERSHEY_DUPLEX, fontScale=scale/10, thickness=1)
        new_width = textSize[0][0]
        if (new_width <= width):
            print(new_width)
            return scale/10
    return 1


问:
How to split array in chunks of set size by value in javascript?
I've been trying to get my head around this but I've had no luck at all. I've tried various ways, one of it being the forEach array method but I'm not able to get the output I need.

Idea is, MEAL DEAL: $2.99 - must be a combination of 1x Sandwich, 1x drink and 1x quick bite.

If it's just 1x each of the items in array, it works but when there are more than 1 of each item in array, I cant get it to work

I have the following array but it may vary:

[
  { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2 },
  { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.5 },
  { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5 },
  { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 3.5 },
  { "CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3 }
]
```

<p>I need to split that into parts like below:</p>

<pre class="lang-js prettyprint-override"><code>IN MEAL DEAL
[
  { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2 },
  { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5 },
  { "CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3 }
]

NOT IN MEAL DEAL (IF SANDWICH IS ADDED, IT BECOMES MEAL DEAL)
[
  { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.5 },
  { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 3.5 }
]
</code>```

Sorry, if the explanation is not too good.

Idea is, each chunk must have all 3 element with following values.
1x COLD DRINK
1x SANDWICH
1x QUICK BITES

What I've tried:

```<code>var ITM ="";
var PER_CATEGORY_SET = [];
var value = [
      { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2 },
      { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.5 },
      { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5 },
      { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 3.5 },
      { "CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3 },
      { "CAT": "SANDWICHES", "QTY": 1, "PRICE": 7.5 }
    ]

value.forEach(function (my_item){
var xx = value.length;

while (xx > 0) {
   if(ITM !=  my_item.CAT ){
   ITM = my_item.CAT;PER_CATEGORY_SET.push({'CAT':my_item.CAT,'QTY':my_item.QTY,'PRICE':my_item.PRICE});
   value.splice(0, 1);
 }
   xx--;
  }
});
</code>```

Output I get is below, it work to create only initial array than it don't do anything:

```<code> [
      { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2 },
      { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5 },
      { "CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3 }
 ]
</code>```

答:
I hope it helps you

let arr = [
 {"CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2},
 {"CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.5},
 {"CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5},
 {"CAT": "QUICK BITES", "QTY": 1, "PRICE": 3.5},
 {"CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3},
 {"CAT": "SANDWICHES", "QTY": 1, "PRICE": 7.5}
]

let arr1 = [], arr2 = []

for (let i = 0; i < arr.length; i++ ){
  if(i%2==0) {
  arr1.push(arr[i])
  } else {
  arr2.push(arr[i])
  }
}

console.log(arr1,arr2)```

Body:
I've been trying to get my head around this but I've had no luck at all. I've tried various ways, one of it being the forEach array method but I'm not able to get the output I need.

Idea is, MEAL DEAL: $2.99 - must be a combination of 1x Sandwich, 1x drink and 1x quick bite.

If it's just 1x each of the items in array, it works but when there are more than 1 of each item in array, I cant get it to work

I have the following array but it may vary:

[
  { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2 },
  { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.5 },
  { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5 },
  { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 3.5 },
  { "CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3 }
]

I need to split that into parts like below:

IN MEAL DEAL
[
  { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2 },
  { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5 },
  { "CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3 }
]

NOT IN MEAL DEAL (IF SANDWICH IS ADDED, IT BECOMES MEAL DEAL)
[
  { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.5 },
  { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 3.5 }
]

Sorry, if the explanation is not too good.

Idea is, each chunk must have all 3 element with following values.
1x COLD DRINK
1x SANDWICH
1x QUICK BITES

What I've tried:

var ITM ="";
var PER_CATEGORY_SET = [];
var value = [
      { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2 },
      { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.5 },
      { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5 },
      { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 3.5 },
      { "CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3 },
      { "CAT": "SANDWICHES", "QTY": 1, "PRICE": 7.5 }
    ]

value.forEach(function (my_item){
var xx = value.length;

while (xx > 0) {
   if(ITM !=  my_item.CAT ){
   ITM = my_item.CAT;PER_CATEGORY_SET.push({'CAT':my_item.CAT,'QTY':my_item.QTY,'PRICE':my_item.PRICE});
   value.splice(0, 1);
 }
   xx--;
  }
});

Output I get is below, it work to create only initial array than it don't do anything:

 [
      { "CAT": "COLD DRINKS", "QTY": 1, "PRICE": 1.2 },
      { "CAT": "QUICK BITES", "QTY": 1, "PRICE": 2.5 },
      { "CAT": "SANDWICHES", "QTY": 1, "PRICE": 5.3 }
 ]


问:
Laravel 6 API RESTful with many to many relationship filtered
I'm developing a Multilanguage API with laravel 6 and I've got this situation in my database:

```<code>Categories
id
other not relevants fields

Languages:
id
name
code

Category_Language
id
language_id
category_id
name --> this is the name of the category in the specific language.
</code>```

Now I've 2 models, the first for Category

```<code>class Category extends Model
{
    public function languages()
    {
        return $this->belongsToMany('App\Models\v1\Language')->withTimestamps()->withPivot('name');
    }
}
</code>```

and the second Model

```<code>class Language extends Model
{
    protected $fillable = ['code', 'name', 'image_id', 'enabled'];

    public function categories() {
        return $this->belongsToMany('App\Models\v1\Category')->withTimestamps()->withPivot('name');
    }
}
</code>```

In my logic (I'm using Service Pattern) I've used this approach on create Category, every time I Pass a JSON object like this:

```<code>{
  "names": [
    {
      "languageId": 1,
      "name": "Hello"
    },
    {
      "languageId": 2,
      "name": "Hola"
    }
  ]
}
</code>```

First of all I create a category (validate if the id of the language is really stored in database) and then with many to many laravel power I attach the language and the name in the category model like this:

```<code> foreach($request->names as $name) {
    $category->languages()->attach($name['languageId'], ['name' => $name['name']]);
 }
</code>```

Now this seems to work perfectly and it's good to retrieve all the category without filtering languages using API Resource like this:

```<code>public function toArray($request)
{
    $category = [];
    $category['id'] = $this->id;
    $category['languages'] = [];

    $category['languages'] = $this->languages->map(function ($language) {
        return [
            'languageId' => $language->id,
            'languageCode' => $language->code,
            'languageName' => $language->name,
            'categoryName' => $language->pivot->name,
        ];
    });

    return $category;
}
</code>```

and this is the output for 3 categories with 3 languages (faker data):

```<code>array:3 [
  "data" => array:3 [
    0 => array:4 [
      "id" => 1
      "languages" => array:3 [
        0 => array:4 [
          "languageId" => 1
          "languageCode" => "pa"
          "languageName" => "Kacey Trantow"
          "categoryName" => "quasi"
        ]
        1 => array:4 [
          "languageId" => 2
          "languageCode" => "ne"
          "languageName" => "Mr. Alexandre Heathcote"
          "categoryName" => "perferendis"
        ]
        2 => array:4 [
          "languageId" => 3
          "languageCode" => "kj"
          "languageName" => "Mr. Misael Robel"
          "categoryName" => "repudiandae"
        ]
      ]
      "imageUrl" => null
      "enabled" => true
    ]
    1 => array:4 [
      "id" => 2
      "languages" => array:3 [
        0 => array:4 [
          "languageId" => 1
          "languageCode" => "pa"
          "languageName" => "Kacey Trantow"
          "categoryName" => "non"
        ]
        1 => array:4 [
          "languageId" => 2
          "languageCode" => "ne"
          "languageName" => "Mr. Alexandre Heathcote"
          "categoryName" => "vitae"
        ]
        2 => array:4 [
          "languageId" => 3
          "languageCode" => "kj"
          "languageName" => "Mr. Misael Robel"
          "categoryName" => "suscipit"
        ]
      ]
      "imageUrl" => null
      "enabled" => true
    ]
    2 => array:4 [
      "id" => 3
      "languages" => array:3 [
        0 => array:4 [
          "languageId" => 1
          "languageCode" => "pa"
          "languageName" => "Kacey Trantow"
          "categoryName" => "molestiae"
        ]
        1 => array:4 [
          "languageId" => 2
          "languageCode" => "ne"
          "languageName" => "Mr. Alexandre Heathcote"
          "categoryName" => "esse"
        ]
        2 => array:4 [
          "languageId" => 3
          "languageCode" => "kj"
          "languageName" => "Mr. Misael Robel"
          "categoryName" => "beatae"
        ]
      ]
      "imageUrl" => null
      "enabled" => true
    ]
  ]
</code>```

now, the problem is when I want to FILTER the categories passing ONLY 1 specific Language, a classical use case when a user use ONLY 1 language during navigations so, If I want ONLY 1 language (and 1 name in pivot relations of category) what kind of operation I need?

I've organized the service with specific filters and ordering for any collections but this kind of need seems to make me crazy!

So this is my final getCategories method that build filter, ordering and include dinamically:

-

imaging so to have a query string like this:

http://localhost:8000/api/v1/categories?orderBy=id:asc&include=language&language.code=EN

and I want a response like this:

```<code>array:3 [
      "data" => array:3 [
        0 => array:4 [
          "id" => 1
          "languages" => array:3 [
            0 => array:4 [
              "languageId" => 1
              "languageCode" => "EN"
              "languageName" => "English"
              "categoryName" => "quasi"
            ]
          ]
        ]
        1 => array:4 [
          "id" => 2
          "languages" => array:3 [
            0 => array:4 [
              "languageId" => 1
              "languageCode" => "EN"
              "languageName" => "English"
              "categoryName" => "non"
            ]
          ]
        ]
        2 => array:4 [
          "id" => 3
          "languages" => array:3 [
            0 => array:4 [
              "languageId" => 1
              "languageCode" => "EN"
              "languageName" => "English"
              "categoryName" => "molestiae"
            ]
          ]
        ]
      ]
</code>```

I need something like this but GENERALLY, because we have others entities that use the same logic for multilanguage system.

To clarify what I want is like a join query like this:

```<code>SELECT *
FROM categories ca INNER JOIN category_language cl ON ca.id =cl.category_id
                 INNER JOIN languages lan ON lan.id = cl.language_id
WHERE lan.code = 'EN';
</code>```

You will retrieve a list of categories only in ENGLISH languages...

Thanks for any suggestion and help!

答:
I don't think this is exactly the most elegant way of doing this but, I've solved with a little workaround.

First of all, I don't pass language code in query string but, in Header paramas using X-localization params, like explained in this tutorial for laravel with multilanguages.

Second, I always return query->paginate() in service method when retrieve all the resources:

```<code>public function getCategories(Request $request)
{
    $sort = $this->buildSort($request->sort ?? '', 'id', 'asc');
    $where = $this->buildWhere($request->where ?? '');
    $includes = $this->buildWith($request->include ?? '');
    $query = Category::orderBy($sort[0], $sort[1]);

    if (!empty($include)) {
        $query = $query->with($includes);
    }

    if (!empty($where)) {
        $query = $query->where($where);
    }

    return $query->paginate();

}
</code>```

Finally, I intercept the request header into the Category API Resource and if is setted the X-localization param, I filter in the map the languages array like this:

```<code>public function toArray($request)
{
    $languageCode = $request->header('X-localization') ?? null;

    $category = [];
    $category['id'] = $this->id;
    $category['languages'] = [];

    $languages = $this->languages;

    if ($languageCode) {
        $languages = $languages->where('code', '=', $languageCode);
    }

    $languages = $languages->map(function ($language) use ($languageCode, $category) {
        return [
            'languageId' => $language->id,
            'languageCode' => $language->code,
            'languageName' => $language->name,
            'categoryName' => $language->pivot->name,
        ];
    });

    $category['languages'] = $languages;

    return $category;

}
</code>```

The result is exactly what I want without using pure SQL in my project (fake data):

```<code>array:3 [
  "data" => array:3 [
    0 => array:4 [
      "id" => 1
      "languages" => array:1 [
        0 => array:4 [
          "languageId" => 1
          "languageCode" => "ho"
          "languageName" => "Dott. Orfeo Sartori"
          "categoryName" => "rem"
        ]
      ]
      "imageUrl" => null
      "enabled" => true
    ]
    1 => array:4 [
      "id" => 2
      "languages" => array:1 [
        0 => array:4 [
          "languageId" => 1
          "languageCode" => "ho"
          "languageName" => "Dott. Orfeo Sartori"
          "categoryName" => "accusamus"
        ]
      ]
      "imageUrl" => null
      "enabled" => true
    ]
    2 => array:4 [
      "id" => 3
      "languages" => array:1 [
        0 => array:4 [
          "languageId" => 1
          "languageCode" => "ho"
          "languageName" => "Dott. Orfeo Sartori"
          "categoryName" => "totam"
        ]
      ]
      "imageUrl" => null
      "enabled" => true
    ]
  ]
  "links" => array:4 [
    "first" => "http://localhost/api/v1/categories?page=1"
    "last" => "http://localhost/api/v1/categories?page=1"
    "prev" => null
    "next" => null
  ]
  "meta" => array:7 [
    "current_page" => 1
    "from" => 1
    "last_page" => 1
    "path" => "http://localhost/api/v1/categories"
    "per_page" => 15
    "to" => 3
    "total" => 3
  ]
]
</code>```

Process finished with exit code 1

Body:
I'm developing a Multilanguage API with laravel 6 and I've got this situation in my database:

Categories
id
other not relevants fields

Languages:
id
name
code

Category_Language
id
language_id
category_id
name --> this is the name of the category in the specific language.

Now I've 2 models, the first for Category

class Category extends Model
{
    public function languages()
    {
        return $this->belongsToMany('App\Models\v1\Language')->withTimestamps()->withPivot('name');
    }
}

and the second Model

class Language extends Model
{
    protected $fillable = ['code', 'name', 'image_id', 'enabled'];

    public function categories() {
        return $this->belongsToMany('App\Models\v1\Category')->withTimestamps()->withPivot('name');
    }
}

In my logic (I'm using Service Pattern) I've used this approach on create Category, every time I Pass a JSON object like this:

{
  "names": [
    {
      "languageId": 1,
      "name": "Hello"
    },
    {
      "languageId": 2,
      "name": "Hola"
    }
  ]
}

First of all I create a category (validate if the id of the language is really stored in database) and then with many to many laravel power I attach the language and the name in the category model like this:

 foreach($request->names as $name) {
    $category->languages()->attach($name['languageId'], ['name' => $name['name']]);
 }

Now this seems to work perfectly and it's good to retrieve all the category without filtering languages using API Resource like this:

public function toArray($request)
{
    $category = [];
    $category['id'] = $this->id;
    $category['languages'] = [];

    $category['languages'] = $this->languages->map(function ($language) {
        return [
            'languageId' => $language->id,
            'languageCode' => $language->code,
            'languageName' => $language->name,
            'categoryName' => $language->pivot->name,
        ];
    });

    return $category;
}

and this is the output for 3 categories with 3 languages (faker data):

array:3 [
  "data" => array:3 [
    0 => array:4 [
      "id" => 1
      "languages" => array:3 [
        0 => array:4 [
          "languageId" => 1
          "languageCode" => "pa"
          "languageName" => "Kacey Trantow"
          "categoryName" => "quasi"
        ]
        1 => array:4 [
          "languageId" => 2
          "languageCode" => "ne"
          "languageName" => "Mr. Alexandre Heathcote"
          "categoryName" => "perferendis"
        ]
        2 => array:4 [
          "languageId" => 3
          "languageCode" => "kj"
          "languageName" => "Mr. Misael Robel"
          "categoryName" => "repudiandae"
        ]
      ]
      "imageUrl" => null
      "enabled" => true
    ]
    1 => array:4 [
      "id" => 2
      "languages" => array:3 [
        0 => array:4 [
          "languageId" => 1
          "languageCode" => "pa"
          "languageName" => "Kacey Trantow"
          "categoryName" => "non"
        ]
        1 => array:4 [
          "languageId" => 2
          "languageCode" => "ne"
          "languageName" => "Mr. Alexandre Heathcote"
          "categoryName" => "vitae"
        ]
        2 => array:4 [
          "languageId" => 3
          "languageCode" => "kj"
          "languageName" => "Mr. Misael Robel"
          "categoryName" => "suscipit"
        ]
      ]
      "imageUrl" => null
      "enabled" => true
    ]
    2 => array:4 [
      "id" => 3
      "languages" => array:3 [
        0 => array:4 [
          "languageId" => 1
          "languageCode" => "pa"
          "languageName" => "Kacey Trantow"
          "categoryName" => "molestiae"
        ]
        1 => array:4 [
          "languageId" => 2
          "languageCode" => "ne"
          "languageName" => "Mr. Alexandre Heathcote"
          "categoryName" => "esse"
        ]
        2 => array:4 [
          "languageId" => 3
          "languageCode" => "kj"
          "languageName" => "Mr. Misael Robel"
          "categoryName" => "beatae"
        ]
      ]
      "imageUrl" => null
      "enabled" => true
    ]
  ]

now, the problem is when I want to FILTER the categories passing ONLY 1 specific Language, a classical use case when a user use ONLY 1 language during navigations so, If I want ONLY 1 language (and 1 name in pivot relations of category) what kind of operation I need?

I've organized the service with specific filters and ordering for any collections but this kind of need seems to make me crazy!

So this is my final getCategories method that build filter, ordering and include dinamically:

-

imaging so to have a query string like this:

http://localhost:8000/api/v1/categories?orderBy=id:asc&include=language&language.code=EN

and I want a response like this:

array:3 [
      "data" => array:3 [
        0 => array:4 [
          "id" => 1
          "languages" => array:3 [
            0 => array:4 [
              "languageId" => 1
              "languageCode" => "EN"
              "languageName" => "English"
              "categoryName" => "quasi"
            ]
          ]
        ]
        1 => array:4 [
          "id" => 2
          "languages" => array:3 [
            0 => array:4 [
              "languageId" => 1
              "languageCode" => "EN"
              "languageName" => "English"
              "categoryName" => "non"
            ]
          ]
        ]
        2 => array:4 [
          "id" => 3
          "languages" => array:3 [
            0 => array:4 [
              "languageId" => 1
              "languageCode" => "EN"
              "languageName" => "English"
              "categoryName" => "molestiae"
            ]
          ]
        ]
      ]

I need something like this but GENERALLY, because we have others entities that use the same logic for multilanguage system.

To clarify what I want is like a join query like this:

SELECT *
FROM categories ca INNER JOIN category_language cl ON ca.id =cl.category_id
                 INNER JOIN languages lan ON lan.id = cl.language_id
WHERE lan.code = 'EN';

You will retrieve a list of categories only in ENGLISH languages...

Thanks for any suggestion and help!

Body:
I don't think this is exactly the most elegant way of doing this but, I've solved with a little workaround.

First of all, I don't pass language code in query string but, in Header paramas using X-localization params, like explained in this tutorial for laravel with multilanguages.

Second, I always return query->paginate() in service method when retrieve all the resources:

public function getCategories(Request $request)
{
    $sort = $this->buildSort($request->sort ?? '', 'id', 'asc');
    $where = $this->buildWhere($request->where ?? '');
    $includes = $this->buildWith($request->include ?? '');
    $query = Category::orderBy($sort[0], $sort[1]);

    if (!empty($include)) {
        $query = $query->with($includes);
    }

    if (!empty($where)) {
        $query = $query->where($where);
    }

    return $query->paginate();

}

Finally, I intercept the request header into the Category API Resource and if is setted the X-localization param, I filter in the map the languages array like this:

public function toArray($request)
{
    $languageCode = $request->header('X-localization') ?? null;

    $category = [];
    $category['id'] = $this->id;
    $category['languages'] = [];

    $languages = $this->languages;

    if ($languageCode) {
        $languages = $languages->where('code', '=', $languageCode);
    }

    $languages = $languages->map(function ($language) use ($languageCode, $category) {
        return [
            'languageId' => $language->id,
            'languageCode' => $language->code,
            'languageName' => $language->name,
            'categoryName' => $language->pivot->name,
        ];
    });

    $category['languages'] = $languages;

    return $category;

}

The result is exactly what I want without using pure SQL in my project (fake data):

array:3 [
  "data" => array:3 [
    0 => array:4 [
      "id" => 1
      "languages" => array:1 [
        0 => array:4 [
          "languageId" => 1
          "languageCode" => "ho"
          "languageName" => "Dott. Orfeo Sartori"
          "categoryName" => "rem"
        ]
      ]
      "imageUrl" => null
      "enabled" => true
    ]
    1 => array:4 [
      "id" => 2
      "languages" => array:1 [
        0 => array:4 [
          "languageId" => 1
          "languageCode" => "ho"
          "languageName" => "Dott. Orfeo Sartori"
          "categoryName" => "accusamus"
        ]
      ]
      "imageUrl" => null
      "enabled" => true
    ]
    2 => array:4 [
      "id" => 3
      "languages" => array:1 [
        0 => array:4 [
          "languageId" => 1
          "languageCode" => "ho"
          "languageName" => "Dott. Orfeo Sartori"
          "categoryName" => "totam"
        ]
      ]
      "imageUrl" => null
      "enabled" => true
    ]
  ]
  "links" => array:4 [
    "first" => "http://localhost/api/v1/categories?page=1"
    "last" => "http://localhost/api/v1/categories?page=1"
    "prev" => null
    "next" => null
  ]
  "meta" => array:7 [
    "current_page" => 1
    "from" => 1
    "last_page" => 1
    "path" => "http://localhost/api/v1/categories"
    "per_page" => 15
    "to" => 3
    "total" => 3
  ]
]

Process finished with exit code 1


问:
Getting a number of digits
I've been searching for a way in python to get only 4 digits on the right of the comma of a decimal number, but i couldn't find. Took a look on this post,---> Rounding decimals with new Python format function
,but the function written there...

```<code>    >>> n = 4
    >>> p = math.pi
    >>> '{0:.{1}f}'.format(p, n)
    '3.1416'
</code>```

...seems not to work in my case.

I imported the modules "math" and "decimal", but maybe i'm missing some others to import, but i don't know which of them to import.

Thanks everyone, and sorry if this issue has already been posted.

Peixe

答:
If you only want the remainder of a float you could convert to a string and split on '.':

```<code>>>> str(math.pi).split('.')[1][:4]
<<< '1415'
</code>```

or decimal.Decimal:

```<code>>>> Decimal(math.pi).as_tuple()[1][1:5]
<<< (1, 4, 1, 5)
</code>```

Title: Getting a number of digits

Body:
I've been searching for a way in python to get only 4 digits on the right of the comma of a decimal number, but i couldn't find. Took a look on this post,---> Rounding decimals with new Python format function
,but the function written there...

    >>> n = 4
    >>> p = math.pi
    >>> '{0:.{1}f}'.format(p, n)
    '3.1416'

...seems not to work in my case.

I imported the modules "math" and "decimal", but maybe i'm missing some others to import, but i don't know which of them to import.

Thanks everyone, and sorry if this issue has already been posted.

Peixe

Body:
If you only want the remainder of a float you could convert to a string and split on '.':

>>> str(math.pi).split('.')[1][:4]
<<< '1415'

or decimal.Decimal:

>>> Decimal(math.pi).as_tuple()[1][1:5]
<<< (1, 4, 1, 5)


问:
Should I be saving my data in a .csv file?
I am writing a small .py file that contains some classes to be imported later repetitively into other work. The mentioned .py file uses some small database (in order of KB) in the form of tables. Do you think it is better to store this data in the same .py file or is it better to keep it in a separate .csv file? What are the differences in terms of performance and convenience for later use? A point that I might have to mention is that this data is numerical and is not prone to any possible change in the future.
Single items are to be accessed from this data at a time.

答:
I would rather not hard-code the data into the py file. If you keep it separate the py file is more versatile and easily transferable to other data. A separate file would also make it easier to replace the dataset ("data not prone to change" may mean only that individual values are constant, not the whole set).

The resources required for the import may vary depending on the libraries used and the type of object created (see here for more details). This however may be negligible, depending on the size of the data.

Consider creating a function that imports the data once, pickles (serializes) it and loads the serialized form (as long as the data is unchanged, or according to user input). This is especially useful for large datasets and some other cases which do not seem to apply to you.


问:
How to incorporate a variable into a URI?
Basically I'm trying to put a result of a query into a file path, into the image source.

Updated code. Now I actually get the string I want but I still have trouble with interpolating it into the Uri constructor.

```<code> Random rand = new Random();
            var nrand = rand.Next(1, 4);

            using (var db = new DungeonContext())
            {
                var query = db.Rooms.Where(b => b.RoomId == nrand).Select(b => b.RoomName);
                foreach(string name in query)
                {
                    nameOfRoom = name;
                }
            }
</code>```

Somehow I have trouble setting images dir as Resources since I'm missing advancent properties for this folder.

```<code>roomScreen.Source = new BitmapImage(new Uri($"/images/{nameOfRoom}.png", UriKind.Relative));
</code>```

Making Uri relative seemed to stop throwing exceptions, but the intended effect does not happen.

答: Apparently all I needed to do was add UriKInd.RelativeOrAbsolute to the constructor.</p>

Body:
Basically I'm trying to put a result of a query into a file path, into the image source.

Updated code. Now I actually get the string I want but I still have trouble with interpolating it into the Uri constructor.

 Random rand = new Random();
            var nrand = rand.Next(1, 4);

            using (var db = new DungeonContext())
            {
                var query = db.Rooms.Where(b => b.RoomId == nrand).Select(b => b.RoomName);
                foreach(string name in query)
                {
                    nameOfRoom = name;
                }
            }

Somehow I have trouble setting images dir as Resources since I'm missing advancent properties for this folder.

roomScreen.Source = new BitmapImage(new Uri($"/images/{nameOfRoom}.png", UriKind.Relative));

Making Uri relative seemed to stop throwing exceptions, but the intended effect does not happen.


问:
Navigate sheets in an order
i have sheets names Day1,Day2,Day3,

copy 2 cell value from Day1 and paste it in another workbook Monday,

copy 2 cell value from Day2 and paste it in another workbook Tuesday,

copy 2 cell value from Day3 and paste it in another workbook Wednesday.

I am looking for a VBA code to activate sheet in a order Day1 copy information and paste it, then come back to Day2 copy information and paste it.
Request your help on this pls

答:
To activate a sheet you must use the method Activate:

```<code>Worksheets("Day1").Activate
</code>```

However, you don't need to activate a sheet to copy content from it, or to paste to it. You can do this copy and paste by referring to the worksheets and using the argument of the Copy method:

```<code>Worksheets("Day1").Range("origin_range").Copy Worksheets("Monday").Range("target_range")
</code>```

Title: Navigate sheets in an order

Body:
To activate a sheet you must use the method Activate:

Worksheets("Day1").Activate

However, you don't need to activate a sheet to copy content from it, or to paste to it. You can do this copy and paste by referring to the worksheets and using the argument of the Copy method:

Worksheets("Day1").Range("origin_range").Copy Worksheets("Monday").Range("target_range")


问:
Issue in addPlugInSingleRowFunction upgrading Esper version from 5.3 to 8.3
In our existing application we are using Esper Version 5.3.
We have added few addPlugInSingleRowFunction() to use it in EPL as below --

final Configuration cepConfiguration = new Configuration();
cepConfiguration.addPlugInSingleRowFunction("toNumber", Double.class.getName(), "parseDouble");
cepConfiguration.addPlugInSingleRowFunction("toBoolean", Boolean.class.getName(), "parseBoolean");

This was working fine in 5.3 version.

Post upgrading to 8.3 above code changed as per Esper documentation --

cepConfiguration.getCompiler().addPlugInSingleRowFunction("toNumber", Double.class.getName(), "parseDouble");
cepConfiguration.getCompiler().addPlugInSingleRowFunction("toBoolean", Boolean.class.getName(), "parseBoolean");

But once the sendEventBean() method is called to send a Event to runtime we are seeing below exception every time.

Surprisingly events are getting matched as per the statements present in runtime even if below exception are coming. Though we are not sure whether some events are not matching or not.

Can someone please help on this?

applog.cls=com.espertech.esper.common.internal.epl.expression.dot.core.ExprDotNodeForgeStaticMethodEval,applog.mthd=staticMethodEvalHandleInvocationException,applog.line=228,applog.msg=Invocation exception when invoking method 'parseDouble' of class 'java.lang.Double' passing parameters [null] for statement 'stmt-0': NullPointerException : null,exc.stack=java.lang.NullPointerException\n\tat sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1838)\n\tat sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)\n\tat java.lang.Double.parseDouble(Double.java:538)\n\tat generated.StatementAIFactoryProvider_a4bd241445010f45474e4598e34521ca1b2836db_stmt450.m8(StatementAIFactoryProvider_a4bd241445010f45474e4598e34521ca1b2836db_stmt450.java:161)\n\tat generated.StatementAIFactoryProvider_a4bd241445010f45474e4598e34521ca1b2836db_stmt450$2.get(ANONYMOUS.java:148)\n\tat com.espertech.esper.runtime.internal.filtersvcimpl.FilterParamIndexEquals.matchEvent(FilterParamIndexEquals.java:32)\n\tat com.espertech.esper.runtime.internal.filtersvcimpl.FilterHandleSetNode.matchEvent(FilterHandleSetNode.java:100)\n\tat com.espertech.esper.runtime.internal.filtersvcimpl.EventTypeIndex.matchType(EventTypeIndex.java:178)\n\tat com.espertech.esper.runtime.internal.filtersvcimpl.EventTypeIndex.matchEvent(EventTypeIndex.java:124)\n\tat com.espertech.esper.runtime.internal.filtersvcimpl.FilterServiceBase.retryableMatchEvent(FilterServiceBase.java:179)\n\tat com.espertech.esper.runtime.internal.filtersvcimpl.FilterServiceBase.evaluateInternal(FilterServiceBase.java:96)\n\tat com.espertech.esper.runtime.internal.filtersvcimpl.FilterServiceLockCoarse.evaluate(FilterServiceLockCoarse.java:52)\n\tat com.espertech.esper.runtime.internal.kernel.service.EPEventServiceImpl.processMatches(EPEventServiceImpl.java:610)\n\tat com.espertech.esper.runtime.internal.kernel.service.EPEventServiceImpl.processWrappedEvent(EPEventServiceImpl.java:450)\n\tat com.espertech.esper.runtime.internal.kernel.thread.InboundUnitSendEvent.run(InboundUnitSendEvent.java:43)\n\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)\n\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)\n\tat java.lang.Thread.run(Thread.java:748)

答: You could turn on compiler logging (config.getCompiler().getLogging().setEnableCode(true);) and make sure you have INFO level logging. You can inspect "StatementAIFactoryProvider_a4bd241445010f45474e4598e34521ca1b2836db_stmt450.m8" at line 161 to see what the problem is. Sounds like a null value gets passed to Double.parseDouble. But since I don't have the complete code its hard to say.  </p>


问:
Update map rotation with angles with orthographic projection
I try to rotate a map using angles with orthographic projection. My aim is to center a map on a particular place without using drag'n drop or mouse move.

My map is created like that:

```<code>var projection = d3.geo.orthographic()
     .scale(248)
     .clipAngle(90);

var svg = d3.select(element[0]).append('svg')
    .attr('preserveAspectRatio', 'xMidYMid')
    .attr('viewBox', '0 0 ' + width + ' ' + height)
    .attr('width', mWidth)
    .attr('height', mWidth * height / width);

svg.append('rect')
   .attr('class', 'background')
   .attr('width', width)
   .attr('height', height);

var g = svg.append('g').attr('id', 'myid');

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

I saw this interesting article on the subject: http://www.jasondavies.com/maps/rotate/. But this shows you how to using events.

How to do the same things using angle values?

Thanks for your help!
Thierry

答:
To center a map to a specific location under orthographic projection, you can use:

```<code>projection.rotate([-longitude, -latitude])
</code>```

There is also interactive documentation about the rotation:
https://www.d3indepth.com/geographic/#rotate

Body:
I try to rotate a map using angles with orthographic projection. My aim is to center a map on a particular place without using drag'n drop or mouse move.

My map is created like that:

var projection = d3.geo.orthographic()
     .scale(248)
     .clipAngle(90);

var svg = d3.select(element[0]).append('svg')
    .attr('preserveAspectRatio', 'xMidYMid')
    .attr('viewBox', '0 0 ' + width + ' ' + height)
    .attr('width', mWidth)
    .attr('height', mWidth * height / width);

svg.append('rect')
   .attr('class', 'background')
   .attr('width', width)
   .attr('height', height);

var g = svg.append('g').attr('id', 'myid');

(...)

I saw this interesting article on the subject: http://www.jasondavies.com/maps/rotate/. But this shows you how to using events.

How to do the same things using angle values?

Thanks for your help!
Thierry

Body:
To center a map to a specific location under orthographic projection, you can use:

projection.rotate([-longitude, -latitude])

There is also interactive documentation about the rotation:
https://www.d3indepth.com/geographic/#rotate


问:
JTextArea with line wrap reports incorrect preferred size to JDialog pack?
I am using multiple JTextAreas to display variable sized amounts of text, with LineWrap and WrapStyleWord both true. One application of this is displaying a JDialog with multiple of these text areas inside a JScrollPane. The panel that contains all of these text areas implements Scrollable (as explained here) allowing the JDialog to have a maximum size, but still shrink. The JDialog has a set horizontal size, however. The horizontal scroll bar is forced to never appear, and the vertical scrollbar should not appear unless the dialog reaches its maximum size. However, in cases where the JTextArea wraps its lines, the vertical scroll bar appears while the JDialog's height is smaller than its maximum. The issue seems to be that the JTextArea reports a preferred height of one row when the JDialog is packed, causing the height of the dialog to be smaller than the height of the panel as the text area takes up more than one row.

It seems to be a catch-22, as to get the proper height of the text area it needs to be added to a panel with the desired width to calculate line wrap, which would allow the actual lines to be counted (using a method found here). But the JDialog requires a preferred size before pack is called (from what I understand), causing the issue. To demonstrate the problem:

```<code>import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Rectangle;
import javax.swing.BoxLayout;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.Scrollable;

public class DisplayPopup extends JDialog {

    public DisplayPopup() {

        JPanel actual = new JPanel();
        actual.setLayout(new BoxLayout(actual, BoxLayout.Y_AXIS));
        actual.setOpaque(false);

        JTextArea jta = new JTextArea();
        jta.setText("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ac dictum magna. Nam sed mattis sem. Donec tortor felis, finibus in lectus fringilla, semper finibus turpis. ");
        jta.setFont(new java.awt.Font("Arial", 0, 18));
        jta.setForeground(new java.awt.Color(204, 204, 204));
        jta.setLineWrap(true);
        jta.setWrapStyleWord(true);
        jta.setEditable(false);
        jta.setBackground(new Color(45,45,45));
        jta.setHighlighter(null);
        actual.add(jta);

        PopupScroll ps = new PopupScroll(actual);

        JScrollPane scroll = new JScrollPane();
        scroll.getViewport().add(ps);

        setModalityType(java.awt.Dialog.ModalityType.MODELESS);
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);
        setLocationRelativeTo(null);
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(scroll);

        pack();
    }

    public static void launch() {
        DisplayPopup dp = new DisplayPopup();
        dp.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(DisplayPopup::launch);
    }

    private class PopupScroll extends JPanel implements Scrollable {

        public PopupScroll(JPanel jp) {
            setBackground(Color.PINK);
            setLayout(new BorderLayout());
            add(jp);
        }

        @Override
        public Dimension getPreferredScrollableViewportSize() {
            return new Dimension(500,Math.min((int)getPreferredSize().getHeight(),700));
        }

        @Override
        public int getScrollableUnitIncrement(Rectangle arg0, int arg1, int arg2) {
            return 1;
        }

        @Override
        public int getScrollableBlockIncrement(Rectangle arg0, int arg1, int arg2) {
            return 1;
        }

        @Override
        public boolean getScrollableTracksViewportWidth() {
            return true;
        }

        @Override
        public boolean getScrollableTracksViewportHeight() {
            return false;
        }

    }

}
</code>```

The dialog does not size to include all lines of text. Unlike this solution to a similar issue, calling pack does not solve the problem. I have a few guesses about the solution, maybe using something besides a JTextArea (because I am only trying to display text...?), but I don't know what that would be. I've tried putting a hierarchy listener on the vertical scroll bar so I could detect when it is active without making the dialog visible, but that did not work. Is this a hard problem or am I missing something obvious?

答:
Made a couple of changes and I see the text displayed on 3 lines:

```<code>pack();
pack();
</code>```

Yes that is correct I added a second pack(). First pack seems to recognize the width and the second pack causes the text to be wrapped.

However, I also had to change:

```<code>//actual.setLayout(new BoxLayout(actual, BoxLayout.Y_AXIS));
actual.setLayout(new BorderLayout());
</code>```

I know you don't really want to use a BorderLayout (since you want multiple components aligned vertically), but somehow its preferred size calculation seems to work.

Instead of the BoxLayout, you might be able to use a GridBagLayout. It allows you to specify the "fill" constraints. I would guess you would try with just the horizontal fill.

Or another option is to use the Relative Layout. I would be easier than the GridBagLayout since you don't need to worry about any constraint. The code to use it would be:

```<code>//actual.setLayout(new BoxLayout(actual, BoxLayout.Y_AXIS));
RelativeLayout rl = new RelativeLayout(RelativeLayout.Y_AXIS);
rl.setFill( true );
actual.setLayout( rl );
</code>```

Body:
I am using multiple JTextAreas to display variable sized amounts of text, with LineWrap and WrapStyleWord both true. One application of this is displaying a JDialog with multiple of these text areas inside a JScrollPane. The panel that contains all of these text areas implements Scrollable (as explained here) allowing the JDialog to have a maximum size, but still shrink. The JDialog has a set horizontal size, however. The horizontal scroll bar is forced to never appear, and the vertical scrollbar should not appear unless the dialog reaches its maximum size. However, in cases where the JTextArea wraps its lines, the vertical scroll bar appears while the JDialog's height is smaller than its maximum. The issue seems to be that the JTextArea reports a preferred height of one row when the JDialog is packed, causing the height of the dialog to be smaller than the height of the panel as the text area takes up more than one row.

It seems to be a catch-22, as to get the proper height of the text area it needs to be added to a panel with the desired width to calculate line wrap, which would allow the actual lines to be counted (using a method found here). But the JDialog requires a preferred size before pack is called (from what I understand), causing the issue. To demonstrate the problem:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Rectangle;
import javax.swing.BoxLayout;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.Scrollable;

public class DisplayPopup extends JDialog {

    public DisplayPopup() {

        JPanel actual = new JPanel();
        actual.setLayout(new BoxLayout(actual, BoxLayout.Y_AXIS));
        actual.setOpaque(false);

        JTextArea jta = new JTextArea();
        jta.setText("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ac dictum magna. Nam sed mattis sem. Donec tortor felis, finibus in lectus fringilla, semper finibus turpis. ");
        jta.setFont(new java.awt.Font("Arial", 0, 18));
        jta.setForeground(new java.awt.Color(204, 204, 204));
        jta.setLineWrap(true);
        jta.setWrapStyleWord(true);
        jta.setEditable(false);
        jta.setBackground(new Color(45,45,45));
        jta.setHighlighter(null);
        actual.add(jta);

        PopupScroll ps = new PopupScroll(actual);

        JScrollPane scroll = new JScrollPane();
        scroll.getViewport().add(ps);

        setModalityType(java.awt.Dialog.ModalityType.MODELESS);
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);
        setLocationRelativeTo(null);
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(scroll);

        pack();
    }

    public static void launch() {
        DisplayPopup dp = new DisplayPopup();
        dp.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(DisplayPopup::launch);
    }

    private class PopupScroll extends JPanel implements Scrollable {

        public PopupScroll(JPanel jp) {
            setBackground(Color.PINK);
            setLayout(new BorderLayout());
            add(jp);
        }

        @Override
        public Dimension getPreferredScrollableViewportSize() {
            return new Dimension(500,Math.min((int)getPreferredSize().getHeight(),700));
        }

        @Override
        public int getScrollableUnitIncrement(Rectangle arg0, int arg1, int arg2) {
            return 1;
        }

        @Override
        public int getScrollableBlockIncrement(Rectangle arg0, int arg1, int arg2) {
            return 1;
        }

        @Override
        public boolean getScrollableTracksViewportWidth() {
            return true;
        }

        @Override
        public boolean getScrollableTracksViewportHeight() {
            return false;
        }

    }

}

The dialog does not size to include all lines of text. Unlike this solution to a similar issue, calling pack does not solve the problem. I have a few guesses about the solution, maybe using something besides a JTextArea (because I am only trying to display text...?), but I don't know what that would be. I've tried putting a hierarchy listener on the vertical scroll bar so I could detect when it is active without making the dialog visible, but that did not work. Is this a hard problem or am I missing something obvious?

Body:
Made a couple of changes and I see the text displayed on 3 lines:

pack();
pack();

Yes that is correct I added a second pack(). First pack seems to recognize the width and the second pack causes the text to be wrapped.

However, I also had to change:

//actual.setLayout(new BoxLayout(actual, BoxLayout.Y_AXIS));
actual.setLayout(new BorderLayout());

I know you don't really want to use a BorderLayout (since you want multiple components aligned vertically), but somehow its preferred size calculation seems to work.

Instead of the BoxLayout, you might be able to use a GridBagLayout. It allows you to specify the "fill" constraints. I would guess you would try with just the horizontal fill.

Or another option is to use the Relative Layout. I would be easier than the GridBagLayout since you don't need to worry about any constraint. The code to use it would be:

//actual.setLayout(new BoxLayout(actual, BoxLayout.Y_AXIS));
RelativeLayout rl = new RelativeLayout(RelativeLayout.Y_AXIS);
rl.setFill( true );
actual.setLayout( rl );


问:
SQL query, three tables
So let's same I'm trying to find actors who are in two movies together (for the purpose of a degrees of separation page). I have databases as such (this is just some made up data):

actors

```<code>id     first_name     last_name    gender
17     brad           pitt         m
2      kevin          bacon        m
</code>```

movies

```<code>id     name               year
20     benjamin button    2008
</code>```

roles

```<code>a_id    m_id     role
17      20       Mr. Benjamin Button
</code>```

So I want to return the names of the movies which both actors are in. I have the first and last names of two actors.

I'm having a lot of trouble getting this to work. What I'm having trouble with, specifically, is the SELECT part

```<code>SELECT name FROM movies JOIN . . .
</code>```

I'm starting with first_name and last_name values for each

答:
You must join twice:

```<code>SELECT m.name movie_name
FROM movies m join roles r1 on
   r1.m_id = m.id join actors a1 on
   r1.a_id = a1.id join roles r2 on
   r2.m_id = m.id join actors a2 on
   r2.a_id = a2.id
WHERE
  a1.first_name = 'brad' and a1.last_name = 'pitt' and
  a2.first_name = 'kevin' and a2.last_name = 'bacon'
</code>```

Show all actor combinations per film:

```<code>SELECT m.name movie_name, a1.id actor1, a2.id actor2
FROM movies m join roles r1 on
   r1.m_id = m.id join actors a1 on
   r1.a_id = a1.id join roles r2 on
   r2.m_id = m.id join actors a2 on
   r2.a_id = a2.id
WHERE
  a1.id < a2.id
</code>```

The < ensures that each combination is only reported once.

Title: SQL query, three tables

Body:
So let's same I'm trying to find actors who are in two movies together (for the purpose of a degrees of separation page). I have databases as such (this is just some made up data):

actors

id     first_name     last_name    gender
17     brad           pitt         m
2      kevin          bacon        m

movies

id     name               year
20     benjamin button    2008

roles

a_id    m_id     role
17      20       Mr. Benjamin Button

So I want to return the names of the movies which both actors are in. I have the first and last names of two actors.

I'm having a lot of trouble getting this to work. What I'm having trouble with, specifically, is the SELECT part

SELECT name FROM movies JOIN . . .

I'm starting with first_name and last_name values for each

Body:
You must join twice:

SELECT m.name movie_name
FROM movies m join roles r1 on
   r1.m_id = m.id join actors a1 on
   r1.a_id = a1.id join roles r2 on
   r2.m_id = m.id join actors a2 on
   r2.a_id = a2.id
WHERE
  a1.first_name = 'brad' and a1.last_name = 'pitt' and
  a2.first_name = 'kevin' and a2.last_name = 'bacon'

Show all actor combinations per film:

SELECT m.name movie_name, a1.id actor1, a2.id actor2
FROM movies m join roles r1 on
   r1.m_id = m.id join actors a1 on
   r1.a_id = a1.id join roles r2 on
   r2.m_id = m.id join actors a2 on
   r2.a_id = a2.id
WHERE
  a1.id < a2.id

The < ensures that each combination is only reported once.


问:
integrate() gives totally wrong number
integrate() gives horribly wrong answer:

```<code>integrate(function (x) dnorm(x, -5, 0.07), -Inf, Inf, subdivisions = 10000L)
# 2.127372e-23 with absolute error < 3.8e-23
</code>```

The return value should obviously be 1 (normal distrubution integrates to 1), but integrate() returns ridiculously small number, with wrong error reporting, and no warning...

Any ideas?

This seems the default integrate() is horribly buggy... and I just found this by chance! Is there any reliable R package to compute numerical integration?

EDIT: I tried package pracma and I see the same problem! :

```<code>require(pracma)
integral(function (x) dnorm(x, -5, 0.07), -Inf, Inf)
# For infinite domains Gauss integration is applied!
# [1] 0
</code>```

EDIT: Hmm... digging deeper, it seems that he has trouble to find the very narrow domain for the function which is numerically > 0. When I set the limits  to certain (very close to 0, 1) quantiles, it starts to work:

```<code>integral(function (x) dnorm(x, -5, 0.07), qnorm(1e-10, -5, 0.07), qnorm(1 - 1e-10, -5, 0.07))
</code>```

But anyway, this is quite horrible gotcha... wonder if there is any remedy for this.

答:
Interesting workaround: not too surprisingly, integrate does well when the values sampled (on (-Inf,Inf), no less) are closer to the "center" of the data. You can reduce this by using your function but hinting at a center:

Without adjustment:

t(sapply(-10:10, function(i) integrate(function (x) dnorm(x, i, 0.07), -Inf, Inf, subdivisions = 10000L)))
#       value        abs.error    subdivisions message call
#  [1,] 0            0            1            "OK"    Expression
#  [2,] 1            4.611403e-05 10           "OK"    Expression
#  [3,] 6.619713e-19 1.212066e-18 2            "OK"    Expression
#  [4,] 7.344551e-71 0            2            "OK"    Expression
#  [5,] 3.389557e-06 6.086176e-06 3            "OK"    Expression
#  [6,] 2.127372e-23 3.849798e-23 2            "OK"    Expression
#  [7,] 1            3.483439e-05 8            "OK"    Expression
#  [8,] 1            6.338078e-07 11           "OK"    Expression
#  [9,] 1            3.408389e-06 7            "OK"    Expression
# [10,] 1            6.414833e-07 8            "OK"    Expression
# [11,] 1            7.578907e-06 3            "OK"    Expression
# [12,] 1            6.414833e-07 8            "OK"    Expression
# [13,] 1            3.408389e-06 7            "OK"    Expression
# [14,] 1            6.338078e-07 11           "OK"    Expression
# [15,] 1            3.483439e-05 8            "OK"    Expression
# [16,] 2.127372e-23 3.849798e-23 2            "OK"    Expression
# [17,] 3.389557e-06 6.086176e-06 3            "OK"    Expression
# [18,] 7.344551e-71 0            2            "OK"    Expression
# [19,] 6.619713e-19 1.212066e-18 2            "OK"    Expression
# [20,] 1            4.611403e-05 10           "OK"    Expression
# [21,] 0            0            1            "OK"    Expression
```

<p>If we add a "centering" hint, though, we get more consistent results:</p>

<pre class="lang-r prettyprint-override"><code>t(sapply(-10:10, function(i) integrate(function (x, offset) dnorm(x + offset, i, 0.07), -Inf, Inf, subdivisions = 10000L, offset = i)))
#       value abs.error    subdivisions message call
#  [1,] 1     7.578907e-06 3            "OK"    Expression
#  [2,] 1     7.578907e-06 3            "OK"    Expression
#  [3,] 1     7.578907e-06 3            "OK"    Expression
#  [4,] 1     7.578907e-06 3            "OK"    Expression
#  [5,] 1     7.578907e-06 3            "OK"    Expression
#  [6,] 1     7.578907e-06 3            "OK"    Expression
#  [7,] 1     7.578907e-06 3            "OK"    Expression
#  [8,] 1     7.578907e-06 3            "OK"    Expression
#  [9,] 1     7.578907e-06 3            "OK"    Expression
# [10,] 1     7.578907e-06 3            "OK"    Expression
# [11,] 1     7.578907e-06 3            "OK"    Expression
# [12,] 1     7.578907e-06 3            "OK"    Expression
# [13,] 1     7.578907e-06 3            "OK"    Expression
# [14,] 1     7.578907e-06 3            "OK"    Expression
# [15,] 1     7.578907e-06 3            "OK"    Expression
# [16,] 1     7.578907e-06 3            "OK"    Expression
# [17,] 1     7.578907e-06 3            "OK"    Expression
# [18,] 1     7.578907e-06 3            "OK"    Expression
# [19,] 1     7.578907e-06 3            "OK"    Expression
# [20,] 1     7.578907e-06 3            "OK"    Expression
# [21,] 1     7.578907e-06 3            "OK"    Expression
</code>```

I recognize this is mitigation for heuristics, presumes knowing something about your distribution before integration, and is not a perfect "generic" solution. Just offering another perspective.

Title: integrate() gives totally wrong number

Body:
integrate() gives horribly wrong answer:

integrate(function (x) dnorm(x, -5, 0.07), -Inf, Inf, subdivisions = 10000L)
# 2.127372e-23 with absolute error < 3.8e-23

The return value should obviously be 1 (normal distrubution integrates to 1), but integrate() returns ridiculously small number, with wrong error reporting, and no warning...

Any ideas?

This seems the default integrate() is horribly buggy... and I just found this by chance! Is there any reliable R package to compute numerical integration?

EDIT: I tried package pracma and I see the same problem! :

require(pracma)
integral(function (x) dnorm(x, -5, 0.07), -Inf, Inf)
# For infinite domains Gauss integration is applied!
# [1] 0

EDIT: Hmm... digging deeper, it seems that he has trouble to find the very narrow domain for the function which is numerically > 0. When I set the limits  to certain (very close to 0, 1) quantiles, it starts to work:

integral(function (x) dnorm(x, -5, 0.07), qnorm(1e-10, -5, 0.07), qnorm(1 - 1e-10, -5, 0.07))

But anyway, this is quite horrible gotcha... wonder if there is any remedy for this.

Body:
Interesting workaround: not too surprisingly, integrate does well when the values sampled (on (-Inf,Inf), no less) are closer to the "center" of the data. You can reduce this by using your function but hinting at a center:

Without adjustment:

t(sapply(-10:10, function(i) integrate(function (x) dnorm(x, i, 0.07), -Inf, Inf, subdivisions = 10000L)))
#       value        abs.error    subdivisions message call
#  [1,] 0            0            1            "OK"    Expression
#  [2,] 1            4.611403e-05 10           "OK"    Expression
#  [3,] 6.619713e-19 1.212066e-18 2            "OK"    Expression
#  [4,] 7.344551e-71 0            2            "OK"    Expression
#  [5,] 3.389557e-06 6.086176e-06 3            "OK"    Expression
#  [6,] 2.127372e-23 3.849798e-23 2            "OK"    Expression
#  [7,] 1            3.483439e-05 8            "OK"    Expression
#  [8,] 1            6.338078e-07 11           "OK"    Expression
#  [9,] 1            3.408389e-06 7            "OK"    Expression
# [10,] 1            6.414833e-07 8            "OK"    Expression
# [11,] 1            7.578907e-06 3            "OK"    Expression
# [12,] 1            6.414833e-07 8            "OK"    Expression
# [13,] 1            3.408389e-06 7            "OK"    Expression
# [14,] 1            6.338078e-07 11           "OK"    Expression
# [15,] 1            3.483439e-05 8            "OK"    Expression
# [16,] 2.127372e-23 3.849798e-23 2            "OK"    Expression
# [17,] 3.389557e-06 6.086176e-06 3            "OK"    Expression
# [18,] 7.344551e-71 0            2            "OK"    Expression
# [19,] 6.619713e-19 1.212066e-18 2            "OK"    Expression
# [20,] 1            4.611403e-05 10           "OK"    Expression
# [21,] 0            0            1            "OK"    Expression

If we add a "centering" hint, though, we get more consistent results:

t(sapply(-10:10, function(i) integrate(function (x, offset) dnorm(x + offset, i, 0.07), -Inf, Inf, subdivisions = 10000L, offset = i)))
#       value abs.error    subdivisions message call
#  [1,] 1     7.578907e-06 3            "OK"    Expression
#  [2,] 1     7.578907e-06 3            "OK"    Expression
#  [3,] 1     7.578907e-06 3            "OK"    Expression
#  [4,] 1     7.578907e-06 3            "OK"    Expression
#  [5,] 1     7.578907e-06 3            "OK"    Expression
#  [6,] 1     7.578907e-06 3            "OK"    Expression
#  [7,] 1     7.578907e-06 3            "OK"    Expression
#  [8,] 1     7.578907e-06 3            "OK"    Expression
#  [9,] 1     7.578907e-06 3            "OK"    Expression
# [10,] 1     7.578907e-06 3            "OK"    Expression
# [11,] 1     7.578907e-06 3            "OK"    Expression
# [12,] 1     7.578907e-06 3            "OK"    Expression
# [13,] 1     7.578907e-06 3            "OK"    Expression
# [14,] 1     7.578907e-06 3            "OK"    Expression
# [15,] 1     7.578907e-06 3            "OK"    Expression
# [16,] 1     7.578907e-06 3            "OK"    Expression
# [17,] 1     7.578907e-06 3            "OK"    Expression
# [18,] 1     7.578907e-06 3            "OK"    Expression
# [19,] 1     7.578907e-06 3            "OK"    Expression
# [20,] 1     7.578907e-06 3            "OK"    Expression
# [21,] 1     7.578907e-06 3            "OK"    Expression

I recognize this is mitigation for heuristics, presumes knowing something about your distribution before integration, and is not a perfect "generic" solution. Just offering another perspective.


问:
How run a script with variable in the name under PowerShell in GitHub workflow / actions
I'm implementing a GitHub workflow and I need to run a batch (*.bat) script under PowerShell with a variable part. This doesn't seem to work. A simple batch script is running fine. But when I try to insert a variable into its name it doesn't

I've tried these  with no success:

```<code>run: |
  $i=2
  call "myscript_$i.bat"
</code>```

```<code>run: |
  $i=2
  .\myscript_$i.bat
</code>```

```<code>run: |
  $i=2
  .\myscript_${env:i}.bat
</code>```

Is there any Obi-Wan who can help on this? )

答:
Well, after some experimenting this solution works:</p>

```<code>run |
  $i=2
  Invoke-Expression ".\myscript_$i.bat"
</code>```

Body:
I'm implementing a GitHub workflow and I need to run a batch (*.bat) script under PowerShell with a variable part. This doesn't seem to work. A simple batch script is running fine. But when I try to insert a variable into its name it doesn't

I've tried these  with no success:

run: |
  $i=2
  call "myscript_$i.bat"

run: |
  $i=2
  .\myscript_$i.bat

run: |
  $i=2
  .\myscript_${env:i}.bat

Is there any Obi-Wan who can help on this? )

Body:
Well, after some experimenting this solution works:

run |
  $i=2
  Invoke-Expression ".\myscript_$i.bat"