问:
How to dynamically recognize points via HTTPS ingestion?
We are sending https requests to ingest data. How can the request be formatted so that Elastic dynamically maps the 'geo_point' field as type:point and not text or number? Thank you!</p>
```<code>curl -X POST "https://in-https.URL" -H 'Content-Type: application/json' -d'
{
    "geo_point": -71.34, 41.12
}
'
</code>```

答:
geo_point dynamic mapping is not supported - https://www.elastic.co/guide/en/elasticsearch/reference/current/dynamic-field-mapping.html.

To index a geo_point field, precede you original request with a request to _mapping to add your geo_point field to the index mapping - https://www.elastic.co/guide/en/elasticsearch/reference/current/geo-point.html

Body:
We are sending https requests to ingest data. How can the request be formatted so that Elastic dynamically maps the 'geo_point' field as type:point and not text or number? Thank you!

curl -X POST "https://in-https.URL" -H 'Content-Type: application/json' -d'
{
    "geo_point": -71.34, 41.12
}
'


来源: stackexchange

问:
Limiting size of salt-minion log file
Without obvious cause, the /var/log/salt/minion file on my webserver will sometimes explode in size, quickly filling up my 250GB disk space. Looking at the logs when this happens, it is a process repeatedly complaining that there is no drive space. I can't get back to what happens before the drive space fills up. The end result is that the server is dead. It can't respond to web requests or do anything useful. I'm lucky that I can SSH into the server.

My solution is terrible. I have a cron job that checks the size of the file every 5 minutes. If it is bigger than 1GB, I delete the file. The result is that I really have no way to know what is causing the log file explosion in size. But, this is a production server. I can't let it go down for hours on end while I poke around.

Yes - I do have mirrored servers. All are RHEL7 running HTTPD24. All are truly mirrors of one another. All of them suffer from the random explosion in the size of the /var/log/salt/minion file. So, when one goes down, the load balancer will shuffle traffic to other servers.

What I want is a way to restrict the size of the log file. I've never done anything in the past with salt or minions. I didn't install it. It came with RHEL7. I've been googling for a couple weeks and I see nothing that explains what exactly sends logs to the minion file and how to tell it that I don't really need those logs. So, don't do it. I also can't find anyone else with this problem. So, I assume it is yet another "just me" problem. That is why I'm focusing on the direct solution: don't let the log file explode in size, fill up the drive, and kill the server.

答:
To answer the surface-level question: adjust your logrotate config. Some RHEL-specific guidance.

The fundamental problem, however, is that you have not configured your production systems appropriately. Some common strategies to avoid this issue:

Separate partitions. So filling one does not kill the whole machine. A common arrangement is separate partitions for /, /var, and /var/log, but it depends on your applications.

System monitoring. So you can see your disk usage trends and get alerts before it's too late to do something. e.g. with Elastic, Nagios, Zabbix, etc.

External logging. So you can still look at past logs even if the servers are inaccessible or you deleted them locally. e.g. remote syslog or Elastic, etc.

Application configuration. So only the minimum log levels you need are enabled, and they are using appropriate file locations and outputs to work with the above.

ContentLicense: CC BY-SA 4.0

Title: Limiting size of salt-minion log file


问:
Integration test with Hotchocolate GraphQL and TestServer in C#
I have an ASP.NET Core Api (.NET 6.0) with REST- and GraphQL-endpoints. The GraphQL-endpoints are implemented with Hotchocolate (12.6.0).

For testing the REST endpoints I create a TestServer like this:

```<code>protected static async Task<TestServer> CreateServer()
{
     IHostBuilder webHostBuilder = new HostBuilder();
     webHostBuilder.UseContentRoot(Directory.GetCurrentDirectory());

     webHostBuilder.ConfigureWebHost(webBuilder =>
          {
               webBuilder
                    .UseTestServer()
                    .UseEnvironment("Test")
                    .ConfigureAppConfiguration((_, config) =>
                         config.AddJsonFile("appsettings.Test.json"))
                    .UseStartup<AuthenticatedTestStartup>();
           });

     IHost host = await webHostBuilder.StartAsync();
     return host.GetTestServer();
}
</code>```

AuthenticatedTestStartup derives from Startup and overrides some methods there, e.g. the database configuration.
Using the test server created above I can perform integration tests by using the .CreateClient() method which returns an HttpClient object. With thìs client I am able to call the REST endpoints.
This works very fine.

My question is now: Is there a way to use this test server for integration tests agains the GraphQL endpoints and if yes: how? If not: What are the alternatives to test the GraphQL endpoints programatically against a test database?

答:
As GraphQL is server over HTTP you can test it the same way as an normal REST endpoint.

But if you do not need HTTP for your tests I would recommend to use a in memory server as it is way faster.

// arrange
var executor = await new ServiceCollection()
    .AddGraphQLServer()
    .AddQueryType<Query>()
    .BuildRequestExecutorAsync();

// act
var query = QueryRequestBuilder.New()
  .SetQuery("{ foo }")
  // you can also add a test principal if you want to test authorised
  // resolvers
  .AddProperty(nameof(ClaimsPrincipal), CreatePrincipal())
  .Create()
var result = executor.ExecuteAsync(query);

// assert
// assert here
```

Body:
I have an ASP.NET Core Api (.NET 6.0) with REST- and GraphQL-endpoints. The GraphQL-endpoints are implemented with Hotchocolate (12.6.0).

For testing the REST endpoints I create a TestServer like this:

protected static async Task<TestServer> CreateServer()
{
     IHostBuilder webHostBuilder = new HostBuilder();
     webHostBuilder.UseContentRoot(Directory.GetCurrentDirectory());

     webHostBuilder.ConfigureWebHost(webBuilder =>
          {
               webBuilder
                    .UseTestServer()
                    .UseEnvironment("Test")
                    .ConfigureAppConfiguration((_, config) =>
                         config.AddJsonFile("appsettings.Test.json"))
                    .UseStartup<AuthenticatedTestStartup>();
           });

     IHost host = await webHostBuilder.StartAsync();
     return host.GetTestServer();
}

AuthenticatedTestStartup derives from Startup and overrides some methods there, e.g. the database configuration.
Using the test server created above I can perform integration tests by using the .CreateClient() method which returns an HttpClient object. With thìs client I am able to call the REST endpoints.
This works very fine.

My question is now: Is there a way to use this test server for integration tests agains the GraphQL endpoints and if yes: how? If not: What are the alternatives to test the GraphQL endpoints programatically against a test database?


问:
PHP Session variable not being set, possibly because subdomain on different server?
I've got a newly set up dev server of a site I built. The dev server sits at a completely different Box and IP.

The dev site is a complete copy of the live site minus updates to paths and databases. The address is dev.mysite.com as opposed to just mysite.com.

The live site has a number of subdomains attached to it that change skins based on the subdomain, but nothing else is changed. When I try to log in to the dev site, it won't set the Session variable for the login. Any thoughts on this would be greatly appreciated.

答:
I got a solution for you

— Create a cookie and set it for domain and all subdomain (*)

So you need to insert sessions to database, I suggest you to use Zend Sessions.

Documentation : http://framework.zend.com/manual/en/zend.session.savehandler.dbtable.html

ContentLicense: CC BY-SA 3.0


问:
Flutter url_launcher is not launching url in release mode
I don't know for some reason url_launcher (https://pub.dev/packages/url_launcher) is not working after downloading app from google playstore. In debug mode it is working the way it should be. But after uploading app on playstore and downloading it from there, url launcher is not launching any url. WHY is that?

import 'package:url_launcher/url_launcher.dart';

 onTap: () {
  launchURL("https://www.google.com");
},
..............
  launchURL(String url) async {
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }
```
<p><strong>pubspec.yaml</strong>
<code>url_launcher: ^5.7.6</code></p>
<p>I've also added <code>android.permission.INTERNET</code></p>
<p>I'm not using latest version of <code>url_launcher</code> so may be using latest version will solve the issue BUT problem with it is that latest version of  <code>url_launcher</code> needs latest version of flutter. Is it safe to upgrade flutter version? I can't take a risk of causing any more issues as my app is already in production</p>
<p>This is what I get when I try to upgrade to  <code>url_launcher: ^5.7.10</code> which is the latest version and run <strong>flutter pub get</strong></p>
```[xxxxx] flutter pub get
Running "flutter pub get" in xxxxx...
The current Flutter SDK version is 1.22.0-9.0.pre.

Because url_launcher >=5.7.7 <6.0.0-nullsafety depends on url_launcher_platform_interface >=1.0.9 <2.0.0-nullsafety which requires Flutter SDK version >=1.22.0 <2.0.0, url_launcher >=5.7.7 <6.0.0-nullsafety is forbidden.

So, because xxxxx depends on url_launcher ^5.7.10, version solving failed.
pub get failed (1; So, because storeifie depends on url_launcher ^5.7.10, version solving failed.)
exit code 1
```

答:
add permission  to <AndroidManifest.xml>
under the  <manifest ... package="com.example.app":
Hot restart or you have to uninstall app and install it again</p>

Body:
I don't know for some reason url_launcher (https://pub.dev/packages/url_launcher) is not working after downloading app from google playstore. In debug mode it is working the way it should be. But after uploading app on playstore and downloading it from there, url launcher is not launching any url. WHY is that?

import 'package:url_launcher/url_launcher.dart';

 onTap: () {
  launchURL("https://www.google.com");
},
..............
  launchURL(String url) async {
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }

pubspec.yaml
url_launcher: ^5.7.6

I've also added android.permission.INTERNET

I'm not using latest version of url_launcher so may be using latest version will solve the issue BUT problem with it is that latest version of  url_launcher needs latest version of flutter. Is it safe to upgrade flutter version? I can't take a risk of causing any more issues as my app is already in production

This is what I get when I try to upgrade to  url_launcher: ^5.7.10 which is the latest version and run flutter pub get

[xxxxx] flutter pub get
Running "flutter pub get" in xxxxx...
The current Flutter SDK version is 1.22.0-9.0.pre.

Because url_launcher >=5.7.7 <6.0.0-nullsafety depends on url_launcher_platform_interface >=1.0.9 <2.0.0-nullsafety which requires Flutter SDK version >=1.22.0 <2.0.0, url_launcher >=5.7.7 <6.0.0-nullsafety is forbidden.

So, because xxxxx depends on url_launcher ^5.7.10, version solving failed.
pub get failed (1; So, because storeifie depends on url_launcher ^5.7.10, version solving failed.)
exit code 1


问:
Laravel - create model, controller and migration in single artisan command
I can create a model and resource controller (binded to model) with the following command

```<code>php artisan make:controller TodoController --resource --model=Todo
</code>```

I want to also create a migration with the above command, is it possible?

答:
If you are using Laravel as an only API add --api option:

php artisan make:model Post -a --api
```

Body:
I can create a model and resource controller (binded to model) with the following command

php artisan make:controller TodoController --resource --model=Todo

I want to also create a migration with the above command, is it possible?


问:
jar file doesn't do anything when executed (VSCode)
Here I have a short program, which I would like to export as a .jar file. When I use VSCode's "Export Jar..." option (and select Test as the main class), it creates the jar file without any errors, but when I run it (by double clicking), nothing happens. When I run the code from within VSCode however, it works as expected (the window shows up and says "Hello World").
Here's my code:

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class Test {

    public static void main(String[] args) {
        try {
            SwingUtilities.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    JFrame frame = new JFrame("Test");
                    frame.setSize(600, 400);
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setLocationRelativeTo(null);
                    frame.getContentPane().add(new JLabel("Hello World!"));
                    frame.setVisible(true);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
```

答:
You can run the jar with the following command:</p>
```<code>java -jar jar-file-name.jar
</code>```

Body:
You can run the jar with the following command:

java -jar jar-file-name.jar


问:
how to create non-spa website only using react js?
I have a simple test project using react that shows users of fake API. The parent component is named App and it's my home page. There is a button named panel in the App component. I want it to go to Panel Component when I click it.

```<code>function App() {
const users = useSelector(state => state.users)
 const dispatch = useDispatch();
    const getUsers=()=>{
        // async action using redux-thunk
        return async function(dispatch){
            try{

            dispatch(GetUserRequest())
             const response= await axios.get("https://reqres.in/api/users?page=2")

             dispatch(GetUserSuccess(response.data.data))
            }
            catch(er){
                dispatch(GetUserFail(er))

            }
        }
    }
useEffect(()=>{

    dispatch(getUsers())
 }

  ,[])
  return (<>
 <Provider store={store}>
 <Routes>
<Route path="users" element={<Users Items={users}/>}/>
<Route path="/Panel" element={<Panel/>}/>
</Routes>

 <button className='btn btn-primary' onClick={()=>{
  navigate("/Panel")

}}>Panel</button>
<Users/>

</>
</code>```

It's simple, But I want the Panel component to be a separate page instead of being part of the home page! And I don't want to show other components (in my project User component)

So I tried a trick: using showPages state to determine which page should be shown:

```<code>function App() {
 const users = useSelector(state => state.users)
const[showPages,setShowPages]=useState("users")
  useEffect(()=>{

    setShowPages("users")
    dispatch(getUsers())
  }

  ,[])
 return (<>
<button className='btn btn-primary' onClick={()=>{
 setShowPages("panel")

}}>Panel</button>
 {showPages=="users" && ( <Users/> Items={users})}

     {showPages=="Panel" && <Panel/>}
 </>
</code>```

Now when  I click the Panel button, I can see Panel page as a separate page, But guess what: I missed back button of the browser! I also don't want to use html-based project and use react in it.

Is it possible to create non spa website using pure react? or I should create project without react and use react in it.

答:
I think It would be better to learn Framework those uses React.
Because React is not SEO Friendly. It had not any Server Side Rendering or Static Server Generation. It only provides Client Side Fetching and Rendering.

You can also Try React Router. But At some point, you would feel Hard to Maintain Routes with React Router.

If you want to Learn framework which uses React, You can try RemixJS.

Body:
I have a simple test project using react that shows users of fake API. The parent component is named App and it's my home page. There is a button named panel in the App component. I want it to go to Panel Component when I click it.

function App() {
const users = useSelector(state => state.users)
 const dispatch = useDispatch();
    const getUsers=()=>{
        // async action using redux-thunk
        return async function(dispatch){
            try{

            dispatch(GetUserRequest())
             const response= await axios.get("https://reqres.in/api/users?page=2")

             dispatch(GetUserSuccess(response.data.data))
            }
            catch(er){
                dispatch(GetUserFail(er))

            }
        }
    }
useEffect(()=>{

    dispatch(getUsers())
 }

  ,[])
  return (<>
 <Provider store={store}>
 <Routes>
<Route path="users" element={<Users Items={users}/>}/>
<Route path="/Panel" element={<Panel/>}/>
</Routes>

 <button className='btn btn-primary' onClick={()=>{
  navigate("/Panel")

}}>Panel</button>
<Users/>

</>

It's simple, But I want the Panel component to be a separate page instead of being part of the home page! And I don't want to show other components (in my project User component)

So I tried a trick: using showPages state to determine which page should be shown:

function App() {
 const users = useSelector(state => state.users)
const[showPages,setShowPages]=useState("users")
  useEffect(()=>{

    setShowPages("users")
    dispatch(getUsers())
  }

  ,[])
 return (<>
<button className='btn btn-primary' onClick={()=>{
 setShowPages("panel")

}}>Panel</button>
 {showPages=="users" && ( <Users/> Items={users})}

     {showPages=="Panel" && <Panel/>}
 </>

Now when  I click the Panel button, I can see Panel page as a separate page, But guess what: I missed back button of the browser! I also don't want to use html-based project and use react in it.

Is it possible to create non spa website using pure react? or I should create project without react and use react in it.


问:
How to only load one portion of an AzureML tabular dataset (linked to Azure Blob Storage)
I have a DataSet defined in my AzureML workspace that is linked to an Azure Blob Storage csv file of 1.6Gb.  This file contains timeseries information of around 10000 devices.  So, I could've also created 10000 smaller files (since I use ADF for the transmission pipeline).

My question now is: is it possible to load a part of the AzureML DataSet in my python notebook or script instead of loading the entire file?

The only code I have now load the full file:

dataset = Dataset.get_by_name(workspace, name='devicetelemetry')
df = dataset.to_pandas_dataframe()
```

The only concept of partitions I found with regards to the AzureML datasets was around time series and partitioning of timestamps & dates.  However, here I would love to partition per device, so I can very easily just do a load of all telemetry of a specific device.

Any pointers to docs or any suggestions? (I couldn't find any so far)

Thanks already

答:
TabularDataset has introduced filtering (experimental as of now - Feb'21) upgraded since then.

```<code>ds.filter( ds['patient_id']==my_patient_id ).to_pandas_dataframe()
</code>```

You also find methods like take which give you first n rows, random sample of desired size etc.

Body:
I have a DataSet defined in my AzureML workspace that is linked to an Azure Blob Storage csv file of 1.6Gb.  This file contains timeseries information of around 10000 devices.  So, I could've also created 10000 smaller files (since I use ADF for the transmission pipeline).

My question now is: is it possible to load a part of the AzureML DataSet in my python notebook or script instead of loading the entire file?

The only code I have now load the full file:

dataset = Dataset.get_by_name(workspace, name='devicetelemetry')
df = dataset.to_pandas_dataframe()

The only concept of partitions I found with regards to the AzureML datasets was around time series and partitioning of timestamps & dates.  However, here I would love to partition per device, so I can very easily just do a load of all telemetry of a specific device.

Any pointers to docs or any suggestions? (I couldn't find any so far)

Thanks already

Body:
TabularDataset has introduced filtering (experimental as of now - Feb'21) upgraded since then.

ds.filter( ds['patient_id']==my_patient_id ).to_pandas_dataframe()

You also find methods like take which give you first n rows, random sample of desired size etc.


问:
Call a function in a Class or another fuction Python
I'm not good with Python Classes. I know in this instance using a class would solve the problem of trying to call a function within a function but I'm not sure how to do it. This is a script that opens a website on a set time added in the variable introduced in the beginning. I want to call the openWebsite() function in setTime() function. I'm sure a class would solve my problems but I'm a bit new to Python.

```<code>import webbrowser
import time
</code>```

specify a website, local time and desired time

```<code>page = "https://www.twitter.com"
today = time.strftime('%X %x')
timeToOpen = "09:53:36 02/06/22"
</code>```

a function to open a website and print opened

```<code>def openWebsite():
    webbrowser.open_new(page)
    print("website opened")
    print(today)
</code>```

compares real live time with a specified time in a variable in the beginning

```<code>def setTime():
    while time.strftime('%X %x') != timeToOpen:
        timeNow = time.strftime('%X %x')
        if timeNow >= timeToOpen:
            print("It's A Match")
</code>```

I want to call openWebsite() here

```<code>            break
        print("waiting!")
        print (timeNow + " vs " + timeToOpen)
        time.sleep(3)
</code>```

call a function

```<code>setTime()
</code>```

PS: If you have any other suggestions to improve the code I would be very grateful

Thanks,
Magz

答:
Great question and one that touches on scope and argument passing approaches.

You can pass functions to a metafunction in a number of ways perhaps depending on your use case/coding style/ and PEP8. There are a few related answers with may help:

How do I pass a method as a parameter in Python

Passing functions with arguments to another function in Python?

For all of the  methods below, you will need to put a parameter in your function for e.g 'func_a'(below), the function will then take on the parameter's name within the local/function scope:

def setTime(func_a):
    '''a function that opens website with
      some conditions(...)'''
    while time.strftime('%X %x') != timeToOpen:
        timeNow = time.strftime('%X %x')
        if timeNow >= timeToOpen:
            print("It's A Match")
            #call your function here
            func_a()
            break
    #..... rest of function

```
<ol>
<li>By simply passing the function as an argument without calling ():</li>
</ol>
<pre class="lang-py prettyprint-override"><code>setTime(openWebsite)
</code>```

By wrapping in a tuple if you want/need to compress multiple args:

functions = (openWebsite,some_other_fuction)
#passing like this
setTime(*functions)
```
<p>Writing function parameters like this:</p>
<pre class="lang-py prettyprint-override"><code>def setTime(open_page,open_page_b):
    ''' code '''
</code>```

A dictionary of arguments:

functions = {'func_a':opneWebsite}
#passing like this
setTime(**functions)
```
<p>With 3 you will need to use:</p>
<pre class="lang-py prettyprint-override"><code>def setTime(func_a=None):
    ''' code '''
</code>```

The converse of option 2/3 works using args or kwargs as parameters
prefixed with * or ** respectively, for example:

def setTime(**kwargs):
    ''' code '''
```
<p>Passing like this:</p>
<pre class="lang-py prettyprint-override"><code>setTime(func=openWebsite)
</code>```

with:

def setTime(func_a):
    '''a function that opens website with
      some conditions(...)'''
    while time.strftime('%X %x') != timeToOpen:
        timeNow = time.strftime('%X %x')
        if timeNow >= timeToOpen:
            print("It's A Match")
            #call your function here
            kwargs['func_a']()
            break
    #..... rest of function

```

Hope this helps <^_^>

Body:
I'm not good with Python Classes. I know in this instance using a class would solve the problem of trying to call a function within a function but I'm not sure how to do it. This is a script that opens a website on a set time added in the variable introduced in the beginning. I want to call the openWebsite() function in setTime() function. I'm sure a class would solve my problems but I'm a bit new to Python.

import webbrowser
import time

specify a website, local time and desired time

page = "https://www.twitter.com"
today = time.strftime('%X %x')
timeToOpen = "09:53:36 02/06/22"

a function to open a website and print opened

def openWebsite():
    webbrowser.open_new(page)
    print("website opened")
    print(today)

compares real live time with a specified time in a variable in the beginning

def setTime():
    while time.strftime('%X %x') != timeToOpen:
        timeNow = time.strftime('%X %x')
        if timeNow >= timeToOpen:
            print("It's A Match")

I want to call openWebsite() here

            break
        print("waiting!")
        print (timeNow + " vs " + timeToOpen)
        time.sleep(3)

call a function

setTime()

PS: If you have any other suggestions to improve the code I would be very grateful

Thanks,
Magz

Body:
Great question and one that touches on scope and argument passing approaches.

You can pass functions to a metafunction in a number of ways perhaps depending on your use case/coding style/ and PEP8. There are a few related answers with may help:

How do I pass a method as a parameter in Python

Passing functions with arguments to another function in Python?

For all of the  methods below, you will need to put a parameter in your function for e.g 'func_a'(below), the function will then take on the parameter's name within the local/function scope:

def setTime(func_a):
    '''a function that opens website with
      some conditions(...)'''
    while time.strftime('%X %x') != timeToOpen:
        timeNow = time.strftime('%X %x')
        if timeNow >= timeToOpen:
            print("It's A Match")
            #call your function here
            func_a()
            break
    #..... rest of function

By simply passing the function as an argument without calling ():

setTime(openWebsite)

By wrapping in a tuple if you want/need to compress multiple args:

functions = (openWebsite,some_other_fuction)
#passing like this
setTime(*functions)

Writing function parameters like this:

def setTime(open_page,open_page_b):
    ''' code '''

A dictionary of arguments:

functions = {'func_a':opneWebsite}
#passing like this
setTime(**functions)

With 3 you will need to use:

def setTime(func_a=None):
    ''' code '''

The converse of option 2/3 works using args or kwargs as parameters
prefixed with * or ** respectively, for example:

def setTime(**kwargs):
    ''' code '''

Passing like this:

setTime(func=openWebsite)

with:

def setTime(func_a):
    '''a function that opens website with
      some conditions(...)'''
    while time.strftime('%X %x') != timeToOpen:
        timeNow = time.strftime('%X %x')
        if timeNow >= timeToOpen:
            print("It's A Match")
            #call your function here
            kwargs['func_a']()
            break
    #..... rest of function

Hope this helps <^_^>


问:
Entity Framework + SQL CLR + remote database
I have a project in which I use WCF Data Services to expose access to certain tables in my database (db1).

now, the requirements just changed and I am required to fetch data that used to be from database db1, table teacher from a new database db2, table teacher2, but to keep everything else same.

I am thinking of doing the following :

1- set up the .edmx file of the service to point to a stored procedure (SQL CLR), instead of pointing to table teacher.

2- in SQL CLR, initiate the connection using proprietary API and connect to database db2, and retrieve data from there.

3- send the data retrieved from db2 back to the WCF Data Services client.

Is this possible ? If so, How to do it ? Is there a better way to achieve the same ?

答: You can have more than one edmx per project, and more than one wcf data service. I would make a second one.</p>


问:
I can't access the xpath button location
I need to access it with xpath. I wrote the code but I can't enter it.
enter image description here

```<code>js_click(save_btn)
js_click(xpath('//*[@id="app-content"]/div/div[2]/div/div[4]/div[3]/footer/button[1]'))
</code>```

I tried (btn-primary,button,button1,button[2])

答:
When the Xpath is too long - just avoid using it. A better approach will be to use CSS, you can do something like this:

```<code> "button[class*='Part1-OfTheAtr][class*='Part2-OfTheAtr']"
</code>```

CSS selectors can't find long attributes with spaces, so use *= to look for a string that is part of the class (using string contains and not full match). In your case this will be the code you need:

```<code>"button[class*='btn-primary'][class*='fotter-button']"
</code>```

and if this doesn't work try this:

```<code>"button[class*='btn-primary'][class*='fotter-button'][data-testid*='footer-next']"
</code>```

Body:
I need to access it with xpath. I wrote the code but I can't enter it.
enter image description here

js_click(save_btn)
js_click(xpath('//*[@id="app-content"]/div/div[2]/div/div[4]/div[3]/footer/button[1]'))

I tried (btn-primary,button,button1,button[2])

Body:
When the Xpath is too long - just avoid using it. A better approach will be to use CSS, you can do something like this:

 "button[class*='Part1-OfTheAtr][class*='Part2-OfTheAtr']"

CSS selectors can't find long attributes with spaces, so use *= to look for a string that is part of the class (using string contains and not full match). In your case this will be the code you need:

"button[class*='btn-primary'][class*='fotter-button']"

and if this doesn't work try this:

"button[class*='btn-primary'][class*='fotter-button'][data-testid*='footer-next']"


问:
How to display a table of employee details based on gender selection by the user, by providing the user 3 radio buttons
I've created a table of employees in view, used json array to store the employees details in my component and provided 3 radio buttons named: all, male and female.

What I want is, when I click on all, it should display the table with all the employees. and when I click on male, it should display the table of male employees only and when on clicking female, it should display the table with female candidates only. can anyone help me adding events to the radio buttons with my requirements?

Here is my code:

Component:

  selectedgender = 'all';
  employees: any;

  constructor() {
    this.selectedgender = 'all';
    this.employees=  [
      {"FirstName":"Karthik", "LastName":"Dobbaka", "Age":29, "gender":"Male"},
      {"FirstName":"Yashwanth", "LastName":"Reddy", "Age":28, "gender":"Male"},
      {"FirstName":"Shiva", "LastName":"Kondella", "Age":31, "gender":"Male"},
      {"FirstName":"Arthi", "LastName":"Bharadwaj", "Age":29, "gender":"Female"},
      {"FirstName":"Kavya", "LastName":"Gadadasu", "Age":27, "gender":"Female"},
      {"FirstName":"Kishore", "LastName":"Veldandi", "Age":30, "gender":"Male"},
      {"FirstName":"Shrinivas", "LastName":"Bandi", "Age": 34, "gender":"Male"},
      {"FirstName":"Sowmya", "LastName":"Dasari", "Age":26, "gender":"Female"}
    ];
  }
```
<p>View:</p>
<pre class="lang-html prettyprint-override"><code><form>
  <div>
    <label>Select</label>
    <label>
      <input type="radio" name="gender" value="all"  [(ngModel)]="selectedgender">All
    </label>
    <label>
      <input type="radio" name="gender" value="male" [(ngModel)]="selectedgender">Male
    </label>
    <label>
      <input type="radio" name="gender" value="female" [(ngModel)]="selectedgender">Female
    </label>
  </div>

  <table border="2px">
    <thead>
      <tr>
        <th>FirstName</th>
        <th>LastName</th>
        <th>Age</th>
        <th>gender</th>
      </tr>
    </thead>
    <tr *ngFor=" let emp of employees">
      <td>{{ emp.FirstName }}</td>
      <td>{{ emp.LastName }}</td>
      <td>{{ emp.Age }}</td>
      <td>{{ emp.gender }}</td>
    </tr>
  </table>
</form>
</code>```

答:
You has three aproach

1.-Using an auxiliar variable

Decalre an auxiliar variable

```<code>employeesFiltered=this.employees
</code>```

split the [(ngModel)] in [ngModel] (ngModelChange) to call a function

```<code><input ...
       [ngModel]="selectedgender"
       (ngModelChange)="selectedgender=$event;filter($event)"
>
</code>```

And the function filter like

```<code>  filter(gender:string){
     this.employeesFiltered=gender=='all'?this.employees:
               this.employees.filter(x=>x.gender.toLowerCase()==gender)
  }
</code>```

And iterare over employeesFiltered

```<code><tr *ngFor=" let emp of employeesFiltered">
...
</tr>
</code>```

2.-Using a pipe. A Pipe transform "anything" in other

```<code>@Pipe({
  name: 'filterEmployees'
})
export class FilterEmployeesPipe implements PipeTransform {

  transform(value: any[], args?: any): any {
    console.log(args)
    return args=='all'?value:value.filter(x=>x.gender.toLowerCase()==args);
  }

}
</code>```

And you iterate over employees |filterEmployees:selectedgender

```<code><tr *ngFor=" let emp of employees |filterEmployees:selectedgender">
...
</tr>
</code>```

3.-Using a getter. That's you greate a function

```<code>  get employeesFiltered2()
  {
    return this.selectedgender=='all'?this.employees:
         this.employees.filter(x=>x.gender.toLowerCase()==this.selectedgender)
  }
</code>```

And iterate over employeesFiltered2

```<code><tr *ngFor="let emp of employeesFiltered2">
...
</tr>
</code>```

You can think that the two last options are more "elegant", but be careful. The two options makes that the function (or the pipe) is executed several times along the live of the component. That's are less "efficiency". In this case is not a big problem (no body can detect this lost of efficiency) but you need take account that a pipe or a getter is executed several times.

Well, you can avoid using OnPush change detection but it's require another answer and this is yet a bit large

You has a example of the three aproach in this stackblitz. I put in the stackblitz a "console.log" to allow see how many times is executed each function.

Body:
I've created a table of employees in view, used json array to store the employees details in my component and provided 3 radio buttons named: all, male and female.

What I want is, when I click on all, it should display the table with all the employees. and when I click on male, it should display the table of male employees only and when on clicking female, it should display the table with female candidates only. can anyone help me adding events to the radio buttons with my requirements?

Here is my code:

Component:

  selectedgender = 'all';
  employees: any;

  constructor() {
    this.selectedgender = 'all';
    this.employees=  [
      {"FirstName":"Karthik", "LastName":"Dobbaka", "Age":29, "gender":"Male"},
      {"FirstName":"Yashwanth", "LastName":"Reddy", "Age":28, "gender":"Male"},
      {"FirstName":"Shiva", "LastName":"Kondella", "Age":31, "gender":"Male"},
      {"FirstName":"Arthi", "LastName":"Bharadwaj", "Age":29, "gender":"Female"},
      {"FirstName":"Kavya", "LastName":"Gadadasu", "Age":27, "gender":"Female"},
      {"FirstName":"Kishore", "LastName":"Veldandi", "Age":30, "gender":"Male"},
      {"FirstName":"Shrinivas", "LastName":"Bandi", "Age": 34, "gender":"Male"},
      {"FirstName":"Sowmya", "LastName":"Dasari", "Age":26, "gender":"Female"}
    ];
  }

View:

<form>

    Select

      <input type="radio" name="gender" value="all"  [(ngModel)]="selectedgender">All

      <input type="radio" name="gender" value="male" [(ngModel)]="selectedgender">Male

      <input type="radio" name="gender" value="female" [(ngModel)]="selectedgender">Female

        FirstName
        LastName
        Age
        gender

      {{ emp.FirstName }}
      {{ emp.LastName }}
      {{ emp.Age }}
      {{ emp.gender }}

</form>

Body:
You has three aproach

1.-Using an auxiliar variable

Decalre an auxiliar variable

employeesFiltered=this.employees

split the [(ngModel)] in [ngModel] (ngModelChange) to call a function

<input ...
       [ngModel]="selectedgender"
       (ngModelChange)="selectedgender=$event;filter($event)"
>

And the function filter like

  filter(gender:string){
     this.employeesFiltered=gender=='all'?this.employees:
               this.employees.filter(x=>x.gender.toLowerCase()==gender)
  }

And iterare over employeesFiltered

<tr *ngFor=" let emp of employeesFiltered">
...
</tr>

2.-Using a pipe. A Pipe transform "anything" in other

@Pipe({
  name: 'filterEmployees'
})
export class FilterEmployeesPipe implements PipeTransform {

  transform(value: any[], args?: any): any {
    console.log(args)
    return args=='all'?value:value.filter(x=>x.gender.toLowerCase()==args);
  }

}

And you iterate over employees |filterEmployees:selectedgender

<tr *ngFor=" let emp of employees |filterEmployees:selectedgender">
...
</tr>

3.-Using a getter. That's you greate a function

  get employeesFiltered2()
  {
    return this.selectedgender=='all'?this.employees:
         this.employees.filter(x=>x.gender.toLowerCase()==this.selectedgender)
  }

And iterate over employeesFiltered2

<tr *ngFor="let emp of employeesFiltered2">
...
</tr>

You can think that the two last options are more "elegant", but be careful. The two options makes that the function (or the pipe) is executed several times along the live of the component. That's are less "efficiency". In this case is not a big problem (no body can detect this lost of efficiency) but you need take account that a pipe or a getter is executed several times.

Well, you can avoid using OnPush change detection but it's require another answer and this is yet a bit large

You has a example of the three aproach in this stackblitz. I put in the stackblitz a "console.log" to allow see how many times is executed each function.


问:
How do I check whether a SQLite database file exists using Java?
I get the name of database file from a user, and I want to check if that file already exists. If it does exist, I want to show an error message to user, but I don't know how to check if the file exists. </p>

```<code>public static void databaseConnect(String dbName) throws Exception
{
  if (/*same name exists*/) // How do I check this?
  {
    System.out.print("This database name already exists");
  }
  else
  {
    Class.forName("SQLite.JDBCDriver").newInstance();
    conn = DriverManager.getConnection("jdbc:sqlite:/"+ dbName);
    stat = conn.createStatement();
  }
}
</code>```

答:
Assuming that your dbName parameter indicates the path to the SQLite file ("-wal" and "-shm" companion files notwithstanding), you can use the Java java.io.File class and its exists() predicate:

```<code>final File f = new File(dbName);
if (f.exists())
{
  if (f.isDirectory())
  {
    // Warn about the designated name being a directory.
  }
  else
  {
    // Warn about the designated name already existing as a file.
  }
}
</code>```

Other checks could be warranted too, such as whether the process has the privilege to create the file, though ultimately SQLite will do a better job ensuring that all its requirements can be fulfilled.

Body:
I get the name of database file from a user, and I want to check if that file already exists. If it does exist, I want to show an error message to user, but I don't know how to check if the file exists.

public static void databaseConnect(String dbName) throws Exception
{
  if (/*same name exists*/) // How do I check this?
  {
    System.out.print("This database name already exists");
  }
  else
  {
    Class.forName("SQLite.JDBCDriver").newInstance();
    conn = DriverManager.getConnection("jdbc:sqlite:/"+ dbName);
    stat = conn.createStatement();
  }
}

Body:
Assuming that your dbName parameter indicates the path to the SQLite file ("-wal" and "-shm" companion files notwithstanding), you can use the Java java.io.File class and its exists() predicate:

final File f = new File(dbName);
if (f.exists())
{
  if (f.isDirectory())
  {
    // Warn about the designated name being a directory.
  }
  else
  {
    // Warn about the designated name already existing as a file.
  }
}

Other checks could be warranted too, such as whether the process has the privilege to create the file, though ultimately SQLite will do a better job ensuring that all its requirements can be fulfilled.


问:
Add data in v-tab-item to be active based on v-tab each month
I want add data in v-tab-item from api to active based on v-tab each month.

For example, start_at is January to be show on the January tab, start_at is February to be show on the February tab, etc.

template

```<code><v-tabs v-model="tab" show-arrows >
  <v-tab v-for="item in tabmonth" :key="item.name" > {{ item.name }} </v-tab>
</v-tabs>
<v-tabs-items v-model="tab">
   <v-tab-item v-for="item in tabmonth" :key="item.name">
   <v-row v-for="lesson in lessonCourse" :key="lesson.id">
      <h3 class="courseName">{{lesson.course.title}}</h3>
      <p v-if="lesson.live">{{dateFormat(lesson.live.start_at)}}</p>
      <p v-else>{{dateFormat(lesson.onsite.start_at)}}</p>
   </v-row>
   </v-tab-item>
</v-tabs-items>

<script>
 data() {
  return {
  lessonCourse: [],
  tab: null,
  tabmonth: [
    {id:0, name:'January'},
    {id:1, name:'February'},
    {id:2, name:'March'},
    ...
  ],
 }
 }
 method: {
 async getData () {
  try {
    const request = await Axios.get('v1/courses/onsite-live')
    this.lessonCourse = request.lessons
  } catch (error) {
    console.log(error.message)
  }
}}
</code>```

example data in api
.json

```<code>"lessons": [
    {
        "id": 1,
        "title": "Live1",
        "live": {
            "id": 1,
            "start_at": "2022-01-27 16:00:00",
            "end_at": "2022-01-27 16:20:00",
        },
    },
    {
        "id": 2,
        "title": "OnSite1",
        "onsite": {
            "id": 1,
            "start_at": "2022-02-29 13:00:00",
            "end_at": "2022-02-29 16:00:00",
        }
    },
]
</code>```

答:
You can try with computed property :

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data() {
    return {
      lessonCourse: [
        {"id": 1, "title": "Live1", "live": { "id": 1, "start_at": "2022-01-27 16:00:00", "end_at": "2022-01-27 16:20:00"}},
        {"id": 2, "title": "OnSite1", "onsite": { "id": 1, "start_at": "2022-02-28 13:00:00", "end_at": "2022-02-28 16:00:00"}},
      ],
      tab: null,
      tabmonth: [
        {id:0, name:'January'},
        {id:1, name:'February'},
        {id:2, name:'March'},
      ],
    }
  },
  computed: {
    withMonths() {
      if (this.tab !== null) {
        return this.lessonCourse.map(les => {
          if (les.live) {
            les.month = new Date(les.live.start_at).getMonth()
          } else if (les.onsite) {
            les.month = new Date(les.onsite.start_at).getMonth()
          }
          return {...les}
        }).filter(l => l.month === this.tab)
      }
    }
  },
  methods: {
  // async getData () {
    //try {
      //const request = await Axios.get('v1/courses/onsite-live')
      //this.lessonCourse = request.lessons
    //} catch (error) {
   //   console.log(error.message)
   // }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/font@6.x/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet">
<div id="app">
  <v-app>
    <v-main>
      <v-container>
        <v-tabs v-model="tab" show-arrows >
          <v-tab v-for="item in tabmonth" :key="item.name" >{{ item.name }}</v-tab>
        </v-tabs>
        <v-tabs-items v-model="tab">
           <v-tab-item v-for="item in tabmonth" :key="item.name">
             <v-card mb2 v-for="lesson in withMonths" :key="lesson.id">
                <h3 class="courseName">{{lesson.title}}</h3>
                <p v-if="lesson.live">{{lesson.live.start_at}}</p>
                <p v-else>{{lesson.onsite.start_at}}</p>
             </v-card>
           </v-tab-item>
        </v-tabs-items>
      </v-container>
    </v-main>
  </v-app>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script></code>```

Body:
I want add data in v-tab-item from api to active based on v-tab each month.

For example, start_at is January to be show on the January tab, start_at is February to be show on the February tab, etc.

template

<v-tabs v-model="tab" show-arrows >
  <v-tab v-for="item in tabmonth" :key="item.name" > {{ item.name }} </v-tab>
</v-tabs>
<v-tabs-items v-model="tab">
   <v-tab-item v-for="item in tabmonth" :key="item.name">
   <v-row v-for="lesson in lessonCourse" :key="lesson.id">

{{lesson.course.title}}

{{dateFormat(lesson.live.start_at)}}

{{dateFormat(lesson.onsite.start_at)}}

   </v-row>
   </v-tab-item>
</v-tabs-items>

Body:
You can try with computed property :

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data() {
    return {
      lessonCourse: [
        {"id": 1, "title": "Live1", "live": { "id": 1, "start_at": "2022-01-27 16:00:00", "end_at": "2022-01-27 16:20:00"}},
        {"id": 2, "title": "OnSite1", "onsite": { "id": 1, "start_at": "2022-02-28 13:00:00", "end_at": "2022-02-28 16:00:00"}},
      ],
      tab: null,
      tabmonth: [
        {id:0, name:'January'},
        {id:1, name:'February'},
        {id:2, name:'March'},
      ],
    }
  },
  computed: {
    withMonths() {
      if (this.tab !== null) {
        return this.lessonCourse.map(les => {
          if (les.live) {
            les.month = new Date(les.live.start_at).getMonth()
          } else if (les.onsite) {
            les.month = new Date(les.onsite.start_at).getMonth()
          }
          return {...les}
        }).filter(l => l.month === this.tab)
      }
    }
  },
  methods: {
  // async getData () {
    //try {
      //const request = await Axios.get('v1/courses/onsite-live')
      //this.lessonCourse = request.lessons
    //} catch (error) {
   //   console.log(error.message)
   // }
  }
})

<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/font@6.x/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet">
<div id="app">
  <v-app>
    <v-main>
      <v-container>
        <v-tabs v-model="tab" show-arrows >
          <v-tab v-for="item in tabmonth" :key="item.name" >{{ item.name }}</v-tab>
        </v-tabs>
        <v-tabs-items v-model="tab">
           <v-tab-item v-for="item in tabmonth" :key="item.name">
             <v-card mb2 v-for="lesson in withMonths" :key="lesson.id">
                <h3 class="courseName">{{lesson.title}}</h3>
                <p v-if="lesson.live">{{lesson.live.start_at}}</p>
                <p v-else>{{lesson.onsite.start_at}}</p>
             </v-card>
           </v-tab-item>
        </v-tabs-items>
      </v-container>
    </v-main>
  </v-app>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script>


问:
Fix my querySelector to add a specific class to it in javaScript
I have built the navigation bar in my web page dynamically as shown below

```<code>NavBuilder = () => {
//to loop from section 1 to 4 and add sections to navigation
for (s = 0; s < sections.length; s++) {
    const liElem = document.createElement('li');
    //const divElem = document.createElement("div");
    const Id = sections[s].id;
    const DataNav = sections[s].dataset.nav;
    liElem.innerHTML = `<a class="menu__link" href="#${Id}">${DataNav}</a>`;
    Menu.appendChild(liElem);
}
}
NavBuilder();
</code>```

and when I want to scroll the page I want to add a specific class "your-active-class" to the section which I created in my html page, and also add the class "active" to the liElem so whenever I scroll in the page and stop on a specific section the navbar should highlight the section I stopped on int the navbar it and also highlight the section itself.

the javaScript function I created to add the class active:

```<code>window.addEventListener('scroll', () => {
sections.forEach(s => {
    const topDistance = s.getBoundingClientRect().top;
    // if the distance to the top is between 0-150px
    if (topDistance >= 0 && topDistance < 150) {
        s.classList.add('your-active-class');
        document.querySelector(`<a class="menu__link" href="#${sections[s].id}"></a>`).classList.add("active");

        // otherwise, remove the class
    } else {
        s.classList.remove('your-active-class');
        document.querySelector(`<a class="menu__link" href="#${sections[s].id}"></a>`).classList.remove("active");

    }
});

});
</code>```

I am still caughting this error "Uncaught TypeError: Cannot read property 'id' of undefined" in the line
document.querySelector().classList.add("active");

What is the mistake i am making that prevent me from highlighting my navbar?

the html code:

```<code>    <!DOCTYPE>
<html lang="en">

<head>
</head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Manipulating the DOM</title>
<!-- Load Google Fonts -->
<link href="https://fonts.googleapis.com/css?family=Fira+Sans:900|Merriweather&display=swap" rel="stylesheet">
<!-- Load Styles -->
<link href="css/styles.css" rel="stylesheet">

<body>
  <!-- HTML Follows BEM naming conventions
  IDs are only used for sections to connect menu achors to sections -->
  <header class="page__header">
    <nav class="navbar__menu">
      <!-- Navigation starts as empty UL that will be populated with JS -->
      <ul id="navbar__list"></ul>
    </nav>
  </header>
  <main>
    <header class="main__hero">
      <h1>Landing Page </h1>
    </header>
    <!-- Each Section has an ID (used for the anchor) and
    a data attribute that will populate the li node.
    Adding more sections will automatically populate nav.
    The first section is set to active class by default -->
    <section id="section1" data-nav="Section 1">
      <div class="landing__container">
        <h2>Section 1</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi fermentum metus faucibus lectus pharetra
          dapibus. Suspendisse potenti. Aenean aliquam elementum mi, ac euismod augue. Donec eget lacinia ex. Phasellus
          imperdiet porta orci eget mollis. Sed convallis sollicitudin mauris ac tincidunt. Donec bibendum, nulla eget
          bibendum consectetur, sem nisi aliquam leo, ut pulvinar quam nunc eu augue. Pellentesque maximus imperdiet
          elit a pharetra. Duis lectus mi, aliquam in mi quis, aliquam porttitor lacus. Morbi a tincidunt felis. Sed leo
          nunc, pharetra et elementum non, faucibus vitae elit. Integer nec libero venenatis libero ultricies molestie
          semper in tellus. Sed congue et odio sed euismod.</p>

        <p>Aliquam a convallis justo. Vivamus venenatis, erat eget pulvinar gravida, ipsum lacus aliquet velit, vel
          luctus diam ipsum a diam. Cras eu tincidunt arcu, vitae rhoncus purus. Vestibulum fermentum consectetur
          porttitor. Suspendisse imperdiet porttitor tortor, eget elementum tortor mollis non.</p>
      </div>
    </section>
    <section id="section2" data-nav="Section 2">
      <div class="landing__container">
        <h2>Section 2</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi fermentum metus faucibus lectus pharetra
          dapibus. Suspendisse potenti. Aenean aliquam elementum mi, ac euismod augue. Donec eget lacinia ex. Phasellus
          imperdiet porta orci eget mollis. Sed convallis sollicitudin mauris ac tincidunt. Donec bibendum, nulla eget
          bibendum consectetur, sem nisi aliquam leo, ut pulvinar quam nunc eu augue. Pellentesque maximus imperdiet
          elit a pharetra. Duis lectus mi, aliquam in mi quis, aliquam porttitor lacus. Morbi a tincidunt felis. Sed leo
          nunc, pharetra et elementum non, faucibus vitae elit. Integer nec libero venenatis libero ultricies molestie
          semper in tellus. Sed congue et odio sed euismod.</p>

        <p>Aliquam a convallis justo. Vivamus venenatis, erat eget pulvinar gravida, ipsum lacus aliquet velit, vel
          luctus diam ipsum a diam. Cras eu tincidunt arcu, vitae rhoncus purus. Vestibulum fermentum consectetur
          porttitor. Suspendisse imperdiet porttitor tortor, eget elementum tortor mollis non.</p>
      </div>
    </section>
    </main>
  <footer class="page__footer">
    <p>&copy Udacity</p>
  </footer>
  <script src="js/app.js"></script>
</body>

</html>
</code>```

and the active class and your-active-class

```<code>.active {
padding: 25px;
background-color: black;
color: white;
</code>```

}

```<code>section.your-active-class {
background: rgb(0, 0, 0);
background: linear-gradient(0deg, rgba(211, 39, 39, 0.356) 0%, rgba(223, 10, 10, 0.548) 100%);
</code>```

}

答:
querySelector expects that you pass a valid CSS selector to it, which you aren't doing. You need to change it a little bit and select by the href's value.

In a queryselector you cannot use the -syntax.

```<code>document.querySelector(`a[href="#${sections[s].id}"]`)
</code>```

Body:
I have built the navigation bar in my web page dynamically as shown below

NavBuilder = () => {
//to loop from section 1 to 4 and add sections to navigation
for (s = 0; s < sections.length; s++) {
    const liElem = document.createElement('li');
    //const divElem = document.createElement("div");
    const Id = sections[s].id;
    const DataNav = sections[s].dataset.nav;
    liElem.innerHTML = `<a class="menu__link" href="#${Id}">${DataNav}</a>`;
    Menu.appendChild(liElem);
}
}
NavBuilder();

and when I want to scroll the page I want to add a specific class "your-active-class" to the section which I created in my html page, and also add the class "active" to the liElem so whenever I scroll in the page and stop on a specific section the navbar should highlight the section I stopped on int the navbar it and also highlight the section itself.

the javaScript function I created to add the class active:

window.addEventListener('scroll', () => {
sections.forEach(s => {
    const topDistance = s.getBoundingClientRect().top;
    // if the distance to the top is between 0-150px
    if (topDistance >= 0 && topDistance < 150) {
        s.classList.add('your-active-class');
        document.querySelector(`<a class="menu__link" href="#${sections[s].id}"></a>`).classList.add("active");

        // otherwise, remove the class
    } else {
        s.classList.remove('your-active-class');
        document.querySelector(`<a class="menu__link" href="#${sections[s].id}"></a>`).classList.remove("active");

    }
});

});

I am still caughting this error "Uncaught TypeError: Cannot read property 'id' of undefined" in the line
document.querySelector().classList.add("active");

What is the mistake i am making that prevent me from highlighting my navbar?

the html code:

    <!DOCTYPE>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Manipulating the DOM</title>

<link href="https://fonts.googleapis.com/css?family=Fira+Sans:900|Merriweather&display=swap" rel="stylesheet">

<link href="css/styles.css" rel="stylesheet">

Landing Page

Section 1

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi fermentum metus faucibus lectus pharetra
          dapibus. Suspendisse potenti. Aenean aliquam elementum mi, ac euismod augue. Donec eget lacinia ex. Phasellus
          imperdiet porta orci eget mollis. Sed convallis sollicitudin mauris ac tincidunt. Donec bibendum, nulla eget
          bibendum consectetur, sem nisi aliquam leo, ut pulvinar quam nunc eu augue. Pellentesque maximus imperdiet
          elit a pharetra. Duis lectus mi, aliquam in mi quis, aliquam porttitor lacus. Morbi a tincidunt felis. Sed leo
          nunc, pharetra et elementum non, faucibus vitae elit. Integer nec libero venenatis libero ultricies molestie
          semper in tellus. Sed congue et odio sed euismod.

Aliquam a convallis justo. Vivamus venenatis, erat eget pulvinar gravida, ipsum lacus aliquet velit, vel
          luctus diam ipsum a diam. Cras eu tincidunt arcu, vitae rhoncus purus. Vestibulum fermentum consectetur
          porttitor. Suspendisse imperdiet porttitor tortor, eget elementum tortor mollis non.

Section 2

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi fermentum metus faucibus lectus pharetra
          dapibus. Suspendisse potenti. Aenean aliquam elementum mi, ac euismod augue. Donec eget lacinia ex. Phasellus
          imperdiet porta orci eget mollis. Sed convallis sollicitudin mauris ac tincidunt. Donec bibendum, nulla eget
          bibendum consectetur, sem nisi aliquam leo, ut pulvinar quam nunc eu augue. Pellentesque maximus imperdiet
          elit a pharetra. Duis lectus mi, aliquam in mi quis, aliquam porttitor lacus. Morbi a tincidunt felis. Sed leo
          nunc, pharetra et elementum non, faucibus vitae elit. Integer nec libero venenatis libero ultricies molestie
          semper in tellus. Sed congue et odio sed euismod.

Aliquam a convallis justo. Vivamus venenatis, erat eget pulvinar gravida, ipsum lacus aliquet velit, vel
          luctus diam ipsum a diam. Cras eu tincidunt arcu, vitae rhoncus purus. Vestibulum fermentum consectetur
          porttitor. Suspendisse imperdiet porttitor tortor, eget elementum tortor mollis non.

&copy Udacity

and the active class and your-active-class

.active {
padding: 25px;
background-color: black;
color: white;

}

section.your-active-class {
background: rgb(0, 0, 0);
background: linear-gradient(0deg, rgba(211, 39, 39, 0.356) 0%, rgba(223, 10, 10, 0.548) 100%);

}

Body:
querySelector expects that you pass a valid CSS selector to it, which you aren't doing. You need to change it a little bit and select by the href's value.

In a queryselector you cannot use the <a>-syntax.

document.querySelector(`a[href="#${sections[s].id}"]`)


问:
How to fix the "Android MPAndroidChart Could not find method dependencyResolutionManagement() for arguments error in gradle"?
well Im trying to use MPAndroidChart library in Android studio
my gradle version was 7.0.2 but it didnt work well.
so i changed gradle Version to 6.7.1, and Android Gradle Plugin Version to 4.2.2
i also changed the version of sdk to Android 11.0(R)
my Target SDK version is 30

--build.gradle(project)

```<code>// Top-level build file where you can add configuration options common to all sub-

projects/modules.
buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.2.2"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects{
    repositories{
        google()
        mavenCentral()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

--build.gradle(Module)

```<code>plugins {
    id 'com.android.application'
}

android {
    compileSdk 31
    BuildToolsVersion '30.0.3'

    defaultConfig {
        applicationId "com.example.myapplication"
        minSdkVersion 23
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}
repositories{
    maven { url 'https://jitpack.io' }
}
dependencies {

    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'
}
</code>```

--setting.gradle

```<code>dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
        jcenter() // Warning: this repository is going to shut down soon
    }
}
rootProject.name = "My Application"
include ':app'
</code>```

--capture of the bug
enter image description here

--bug code
Settings file 'C:\Users\kimta\AndroidStudioProjects\MyApplication\settings.gradle' line: 1

A problem occurred evaluating settings 'MyApplication'.

Could not find method dependencyResolutionManagement() for arguments [settings_5pc4jcjs87c9dkfx5manehm0u$_run_closure1@69c68d91] on settings 'MyApplication' of type org.gradle.initialization.DefaultSettings.

gradle problem is too difficult for novice like me. Is there any solution ?

答:
You try to add this line in your settings.gradle:

```<code>maven { url 'https://jitpack.io' }
</code>```

--setting.gradle

```<code>dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
        jcenter() // Warning: this repository is going to shut down soon
        maven { url 'https://jitpack.io' }  //Add this line in your settings.gradle
    }
}
rootProject.name = "My Application"
include ':app'
</code>```

--build.gradle(project)

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:7.0.4"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.10"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

--build.gradle(Module)

```<code>plugins {
    id 'com.android.application'
    id 'kotlin-android'
}

android {
    compileSdk 31

    defaultConfig {
        applicationId "com.example.myapplication"
        minSdk 21
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    // MPAndroidChart
    implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'
}
</code>```

Body:
well Im trying to use MPAndroidChart library in Android studio
my gradle version was 7.0.2 but it didnt work well.
so i changed gradle Version to 6.7.1, and Android Gradle Plugin Version to 4.2.2
i also changed the version of sdk to Android 11.0(R)
my Target SDK version is 30

--build.gradle(project)

// Top-level build file where you can add configuration options common to all sub-

projects/modules.
buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.2.2"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects{
    repositories{
        google()
        mavenCentral()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

--build.gradle(Module)

plugins {
    id 'com.android.application'
}

android {
    compileSdk 31
    BuildToolsVersion '30.0.3'

    defaultConfig {
        applicationId "com.example.myapplication"
        minSdkVersion 23
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}
repositories{
    maven { url 'https://jitpack.io' }
}
dependencies {

    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'
}

--setting.gradle

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
        jcenter() // Warning: this repository is going to shut down soon
    }
}
rootProject.name = "My Application"
include ':app'

--capture of the bug
enter image description here

--bug code
Settings file 'C:\Users\kimta\AndroidStudioProjects\MyApplication\settings.gradle' line: 1

A problem occurred evaluating settings 'MyApplication'.

Could not find method dependencyResolutionManagement() for arguments [settings_5pc4jcjs87c9dkfx5manehm0u$_run_closure1@69c68d91] on settings 'MyApplication' of type org.gradle.initialization.DefaultSettings.

gradle problem is too difficult for novice like me. Is there any solution ?

Body:
You try to add this line in your settings.gradle:

maven { url 'https://jitpack.io' }

--setting.gradle

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
        jcenter() // Warning: this repository is going to shut down soon
        maven { url 'https://jitpack.io' }  //Add this line in your settings.gradle
    }
}
rootProject.name = "My Application"
include ':app'

--build.gradle(project)

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:7.0.4"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.10"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

--build.gradle(Module)

plugins {
    id 'com.android.application'
    id 'kotlin-android'
}

android {
    compileSdk 31

    defaultConfig {
        applicationId "com.example.myapplication"
        minSdk 21
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    // MPAndroidChart
    implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'
}


问:
How to put Arraylist<object> as parameter in HashMap in Java?
I am doing a Java project - Budget manager, which shows how I spend my money.
For that purpose, I used Hashmap to store the type of purchase with parameters of  String(enum), and Arraylist<Product>. Product is a new class where name and price are to be passed.

How can I put multiple values from ArrayList to the same key in HashMap?

```<code>switch (choice) {
    case 1:
        mapProducts.put(Product.Type.FOOD.name(),//add array);
        break;
    case 2:
        mapProducts.put(Product.Type.CLOTHES.name(), );
        break;
    case 3:
        mapProducts.put(Product.Type.ENTERTAINMENT.name(), );
        break;
    case 4:
        mapProducts.put(Product.Type.OTHER.name(), );
        break;
}
</code>```

import java.util.*;

public class Account {
    private ArrayList<String> listOfPurchases;
    private ArrayList<Double> itemPrice;
    private ArrayList<Product> products;
    private double balance;
    private Scanner input = new Scanner(System.in);
    private Map<String, ArrayList<Product>> mapProducts = new HashMap<>();

    public Account() {
        this.listOfPurchases = new ArrayList<>();
        this.itemPrice = new ArrayList<>();
        this.balance = 0.00d;
    }

    public void mainMenuPrint() {
        System.out.println(
                "Choose your action:\n" +
                        "1) Add income\n" +
                        "2) Add purchase\n" +
                        "3) Show list of purchases\n" +
                        "4) Balance\n" +
                        "0) Exit");
    }

    public void startMenu() {
        Scanner input = new Scanner(System.in);
        boolean isOn = true;
        while (isOn) {
            mainMenuPrint();
            int choice = input.nextInt();
            switch (choice) {
                case 0:
                    System.out.println("Bye!");
                    isOn = false;
                    break;
                case 1:
                    addIncome();
                    break;
                case 2:
                    addPurchase();
                    break;
                case 3:
                    showPurchases();
                    break;
                case 4:
                    showBalance();
                    break;
            }
        }
    }

    public void addIncome() {
        double addMoney = 0.00d;
        System.out.println("Enter income:");
        addMoney = input.nextDouble();
        setBalance(addMoney);
        System.out.println("Income was added!");
        System.out.println("");
    }

    public void addPurchase() {
        System.out.println(
                "Choose the type of purchase\n" +
                        "1) Food\n" +
                        "2) Clothes\n" +
                        "3) Entertainment\n" +
                        "4) Other\n" +
                        "5) Back\n");

        int choice = input.nextInt();
        double price = 0.0d;
        if (choice == 5) {
            startMenu();
        } else {
            System.out.println("Enter purchase name:");
            String item = input.next();
            setListOfPurchases(item);
            System.out.println("Enter its price:");
            try {
                price = input.nextDouble();
                setItemPrice(price);
                balanceSubtractFromPurchasePrice(price);
            } catch (
                InputMismatchException e) {
                System.out.println("Wrong input");
            }
            switch (choice) {
                case 1:
                    mapProducts.put(Product.Type.FOOD.name(),//add array);
                    break;
                case 2:
                    mapProducts.put(Product.Type.CLOTHES.name(), );
                    break;
                case 3:
                    mapProducts.put(Product.Type.ENTERTAINMENT.name(), );
                    break;
                case 4:
                    mapProducts.put(Product.Type.OTHER.name(), );
                    break;
            }
            System.out.println("");
        }
    }

    public void showPurchases() {
        double sum = 0.0d;
        if (mapProducts.size() == 0) {
            System.out.println("The purchase list is empty");
        } else {
            System.out.println(
                    "Choose the type of purchase\n" +
                            "1) Food\n" +
                            "2) Clothes\n" +
                            "3) Entertainment\n" +
                            "4) Other\n" +
                            "5) All\n" +
                            "6) Back\n");

            int choice = input.nextInt();
            for (Map.Entry<String, ArrayList<Product>> entry : mapProducts.entrySet()) {
                System.out.println(entry.getKey());
                System.out.println(mapProducts.get("FOOD").get(0));
            }
            for (int i = 0; i < listOfPurchases.size(); i++) {
                sum += itemPrice.get(i);
            }
            System.out.println("Total sum: $" + sum);
        }
        System.out.println("");
    }

    public void showBalance() {
        System.out.printf("Balance: $%.2f", getBalance());
        System.out.println("");
        System.out.println("");
    }

    public void setBalance(double balanceAmount) {
        this.balance += balanceAmount;
    }

    public void balanceSubtractFromPurchasePrice(double purchasePrice) {
        this.balance -= purchasePrice;
    }

    public double getBalance() {
        if (balance < 0) {
            System.out.println("Balance is negative ");
        }
        return this.balance;
    }

    public void setListOfPurchases(String item) {
        this.listOfPurchases.add(item);
    }

    public ArrayList<String> getListOfPurchases() {
        return listOfPurchases;
    }

    public ArrayList<Double> getItemPrice() {
        return itemPrice;
    }

    public void setItemPrice(double itemPrice) {
        this.itemPrice.add(itemPrice);
    }
}
```
<hr />
```public class Product {
    enum Type {
        FOOD, CLOTHES, ENTERTAINMENT, OTHER;
    }

    private String name;
    private double price;
    private Scanner input = new Scanner(System.in);

    public Product(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }
}
```

Thanks for the help!

答:
Instead of saving name and price in two separate list just create a product and place it directly into the map using computeIfAbsent.

```<code>System.out.println("Enter purchase name:");
String item = input.next();
System.out.println("Enter its price:");
try {
    price = input.nextDouble();
    balanceSubtractFromPurchasePrice(price);
    // Lazy replacement for complicated switch case.
   if(choice >= 1 && choice <= 4) {
       Product.Type productType = Product.Type.values()[choice - 1];
       Product product = new Product(item, price);
       List<Product> products = mapProducts.computeIfAbsent(productType, k -> new ArrayList<>());
       products.add(product);
    } else {
        System.out.println("Wrong input");
    }
    } catch (InputMismatchException  e) {
        System.out.println("Wrong input");
    }
    System.out.println("");
}
</code>```

Body:
I am doing a Java project - Budget manager, which shows how I spend my money.
For that purpose, I used Hashmap to store the type of purchase with parameters of  String(enum), and Arraylist<Product>. Product is a new class where name and price are to be passed.

How can I put multiple values from ArrayList to the same key in HashMap?

switch (choice) {
    case 1:
        mapProducts.put(Product.Type.FOOD.name(),//add array);
        break;
    case 2:
        mapProducts.put(Product.Type.CLOTHES.name(), );
        break;
    case 3:
        mapProducts.put(Product.Type.ENTERTAINMENT.name(), );
        break;
    case 4:
        mapProducts.put(Product.Type.OTHER.name(), );
        break;
}

import java.util.*;

public class Account {
    private ArrayList<String> listOfPurchases;
    private ArrayList<Double> itemPrice;
    private ArrayList<Product> products;
    private double balance;
    private Scanner input = new Scanner(System.in);
    private Map<String, ArrayList<Product>> mapProducts = new HashMap<>();

    public Account() {
        this.listOfPurchases = new ArrayList<>();
        this.itemPrice = new ArrayList<>();
        this.balance = 0.00d;
    }

    public void mainMenuPrint() {
        System.out.println(
                "Choose your action:\n" +
                        "1) Add income\n" +
                        "2) Add purchase\n" +
                        "3) Show list of purchases\n" +
                        "4) Balance\n" +
                        "0) Exit");
    }

    public void startMenu() {
        Scanner input = new Scanner(System.in);
        boolean isOn = true;
        while (isOn) {
            mainMenuPrint();
            int choice = input.nextInt();
            switch (choice) {
                case 0:
                    System.out.println("Bye!");
                    isOn = false;
                    break;
                case 1:
                    addIncome();
                    break;
                case 2:
                    addPurchase();
                    break;
                case 3:
                    showPurchases();
                    break;
                case 4:
                    showBalance();
                    break;
            }
        }
    }

    public void addIncome() {
        double addMoney = 0.00d;
        System.out.println("Enter income:");
        addMoney = input.nextDouble();
        setBalance(addMoney);
        System.out.println("Income was added!");
        System.out.println("");
    }

    public void addPurchase() {
        System.out.println(
                "Choose the type of purchase\n" +
                        "1) Food\n" +
                        "2) Clothes\n" +
                        "3) Entertainment\n" +
                        "4) Other\n" +
                        "5) Back\n");

        int choice = input.nextInt();
        double price = 0.0d;
        if (choice == 5) {
            startMenu();
        } else {
            System.out.println("Enter purchase name:");
            String item = input.next();
            setListOfPurchases(item);
            System.out.println("Enter its price:");
            try {
                price = input.nextDouble();
                setItemPrice(price);
                balanceSubtractFromPurchasePrice(price);
            } catch (
                InputMismatchException e) {
                System.out.println("Wrong input");
            }
            switch (choice) {
                case 1:
                    mapProducts.put(Product.Type.FOOD.name(),//add array);
                    break;
                case 2:
                    mapProducts.put(Product.Type.CLOTHES.name(), );
                    break;
                case 3:
                    mapProducts.put(Product.Type.ENTERTAINMENT.name(), );
                    break;
                case 4:
                    mapProducts.put(Product.Type.OTHER.name(), );
                    break;
            }
            System.out.println("");
        }
    }

    public void showPurchases() {
        double sum = 0.0d;
        if (mapProducts.size() == 0) {
            System.out.println("The purchase list is empty");
        } else {
            System.out.println(
                    "Choose the type of purchase\n" +
                            "1) Food\n" +
                            "2) Clothes\n" +
                            "3) Entertainment\n" +
                            "4) Other\n" +
                            "5) All\n" +
                            "6) Back\n");

            int choice = input.nextInt();
            for (Map.Entry<String, ArrayList<Product>> entry : mapProducts.entrySet()) {
                System.out.println(entry.getKey());
                System.out.println(mapProducts.get("FOOD").get(0));
            }
            for (int i = 0; i < listOfPurchases.size(); i++) {
                sum += itemPrice.get(i);
            }
            System.out.println("Total sum: $" + sum);
        }
        System.out.println("");
    }

    public void showBalance() {
        System.out.printf("Balance: $%.2f", getBalance());
        System.out.println("");
        System.out.println("");
    }

    public void setBalance(double balanceAmount) {
        this.balance += balanceAmount;
    }

    public void balanceSubtractFromPurchasePrice(double purchasePrice) {
        this.balance -= purchasePrice;
    }

    public double getBalance() {
        if (balance < 0) {
            System.out.println("Balance is negative ");
        }
        return this.balance;
    }

    public void setListOfPurchases(String item) {
        this.listOfPurchases.add(item);
    }

    public ArrayList<String> getListOfPurchases() {
        return listOfPurchases;
    }

    public ArrayList<Double> getItemPrice() {
        return itemPrice;
    }

    public void setItemPrice(double itemPrice) {
        this.itemPrice.add(itemPrice);
    }
}

public class Product {
    enum Type {
        FOOD, CLOTHES, ENTERTAINMENT, OTHER;
    }

    private String name;
    private double price;
    private Scanner input = new Scanner(System.in);

    public Product(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }
}

Thanks for the help!

Body:
Instead of saving name and price in two separate list just create a product and place it directly into the map using computeIfAbsent.

System.out.println("Enter purchase name:");
String item = input.next();
System.out.println("Enter its price:");
try {
    price = input.nextDouble();
    balanceSubtractFromPurchasePrice(price);
    // Lazy replacement for complicated switch case.
   if(choice >= 1 && choice <= 4) {
       Product.Type productType = Product.Type.values()[choice - 1];
       Product product = new Product(item, price);
       List<Product> products = mapProducts.computeIfAbsent(productType, k -> new ArrayList<>());
       products.add(product);
    } else {
        System.out.println("Wrong input");
    }
    } catch (InputMismatchException  e) {
        System.out.println("Wrong input");
    }
    System.out.println("");
}


问:
Issue accessing member property of a class that is a property of another class
Here's the first class:

```<code>@interface ClassA : NSObject {

NSMutableArray* array1;
NSArray* array2;

}

@property (nonatomic, assign)NSMutableArray* array1;
@property (nonatomic, assign)NSArray* array2;

-(id) initWithData:(NSString*)string1 andWords:(NSString*)string2;

@end

@implementation ClassA

@synthesize array1;
@synthesize array2;

-(id) initWithData:(NSString*)string1 andWords:(NSString*)string2
{
if ((self = [super init]))
{
    array1 = [[NSMutableArray alloc] initWithCapacity:[string1 length]];
    for (int i=0; i < [array1 length]; i++)
        [array1 addObject:[NSString stringWithFormat:@"%c", [string1 characterAtIndex:i]]];

    array2 = [string2 componentsSeparatedByString:@";"];

    NSLog(@"array1 = %@", array1);
    NSLog(@"array2 = %@", array2);
}
return self;
}

- (void) dealloc
{
[array1 release];
[array2 release];

[super dealloc];
}

@end
</code>```

Here's 2nd Class:

```<code>@interface ClassB : NSObject {

ClassA* classA;
}

@property (nonatomic, assign)ClassA* classA;
</code>```

Im having issues gaining access to the properties of ClassA, that are stored in ClassB.

For instance, I want to do something like:

```<code>// print out the arrays stored in Class B
NSLog(@"%@",[[classB classA] array1]);
NSLog(@"%@",[[classB classA] array2]);
</code>```

array1 prints out okay, but array2 throws and EXC_BAD_ACCESS error.  I'm guessing because

```<code>array2 = [string2 componentsSeparatedByString:@";"];
</code>```

is not allocating properly.

答:
I resolved this issue by first calling alloc:</p>

```<code>array2 = [NSArray alloc];
array2 = [string2 componentsSeparatedByString:@";"];
</code>```

Body:
Here's the first class:

@interface ClassA : NSObject {

NSMutableArray* array1;
NSArray* array2;

}

@property (nonatomic, assign)NSMutableArray* array1;
@property (nonatomic, assign)NSArray* array2;

-(id) initWithData:(NSString*)string1 andWords:(NSString*)string2;

@end

@implementation ClassA

@synthesize array1;
@synthesize array2;

-(id) initWithData:(NSString*)string1 andWords:(NSString*)string2
{
if ((self = [super init]))
{
    array1 = [[NSMutableArray alloc] initWithCapacity:[string1 length]];
    for (int i=0; i < [array1 length]; i++)
        [array1 addObject:[NSString stringWithFormat:@"%c", [string1 characterAtIndex:i]]];

    array2 = [string2 componentsSeparatedByString:@";"];

    NSLog(@"array1 = %@", array1);
    NSLog(@"array2 = %@", array2);
}
return self;
}

- (void) dealloc
{
[array1 release];
[array2 release];

[super dealloc];
}

@end

Here's 2nd Class:

@interface ClassB : NSObject {

ClassA* classA;
}

@property (nonatomic, assign)ClassA* classA;

Im having issues gaining access to the properties of ClassA, that are stored in ClassB.

For instance, I want to do something like:

// print out the arrays stored in Class B
NSLog(@"%@",[[classB classA] array1]);
NSLog(@"%@",[[classB classA] array2]);

array1 prints out okay, but array2 throws and EXC_BAD_ACCESS error.  I'm guessing because

array2 = [string2 componentsSeparatedByString:@";"];

is not allocating properly.

Body:
I resolved this issue by first calling alloc:

array2 = [NSArray alloc];
array2 = [string2 componentsSeparatedByString:@";"];


问:
Is there a way to improve this SparkSQL query logic to improve performance?
I'm trying to make a select between 2 tables which I cannot join directly ( they don't have the same values ).

My 2 input table look something like this:

Table1:

Col4      |   Col3  |   Col2     |  Col1
ZO123     |   ZH10  |  Spark111  | 000567
VS561     |   JK14  |  Dmi563    | 009123
```
<p><code>Table2</code> ( here is the main problem, as we have concatenated values inside the cells):</p>
<pre class="lang-none prettyprint-override"><code>    Col7         |     Col6      |    Col5    |  Col8
000567,009123    |   567,9123    |  ZH10,JK14 | Spark111
00657,00896      |   657,896     |  PK15,NU85 | Dmi563
</code>```

Table1 is a temp view as well with 410 million rows. Table2 is a temp view with 221 rows.
Both are temp views built on top of some parquet files.

The query that I currently test and it's taking like 2 hours is:

CREATE OR REPLACE TEMP VIEW Table3 AS SELECT w.Col1 AS Col1
w.Col2 AS Col2
w.Col3 AS Col3
w.Col4 AS Col4
m.Col5 AS Col5,
m.Col6 AS Col6,
m.Col7 AS Col7
m.Col8 AS Col8 FROM Table1 w,Table2 m
WHERE exists (SELECT * FROM Table2 WHERE exists(split(Table2.Col5, ','), x -> x = w.Col3) AND Table2.Col5 = m.Col5 AND exists(split(Table2.Col6, ','), x -> x = udf_function_to_remove_zeros(w.Col1)) and Table2.Col6 = m.Col6 AND exists(split(Table2.Col8, ','), x -> x = w.Col2) AND Table2.Col8 = m.Col8)
```

The main idea is that I'm trying to retrieve rows from Table1 where the values from rows can be found in the splited values from Table2. Also, all the conditions should be passed with AND.

答:
You are facing performance issues probably because you're:

unnecessarily doing a cartesian product FROM Table1 w,Table2 m

using UDF to remove leading zeros while you can do the same using builtin functions

You can actually write the same query using inner join like this:

SELECT
  w.Col1 AS Col1,
  w.Col2 AS Col2,
  w.Col3 AS Col3,
  w.Col4 AS Col4,
  m.Col5 AS Col5,
  m.Col6 AS Col6,
  m.Col7 AS Col7,
  m.Col8 AS Col8
FROM
  Table1 w
JOIN (
  SELECT
    Col7,
    Col8,
    INLINE(ARRAYS_ZIP(SPLIT(Col6, ','), SPLIT(Col5, ','))) AS (Col6, Col5)
  FROM
    Table2
) m
ON
  w.Col3 = m.Col5
  AND TRIM(LEADING '0' FROM w.Col1) = m.Col6
  AND w.Col2 = m.Col8
```
<p>Applied to your input example:</p>
<pre class="lang-py prettyprint-override"><code>spark.createDataFrame([
    ("ZO123", "ZH10", "Spark111", "000567"), ("VS561", "JK14", "Dmi563", "009123")
], ["Col4", "Col3", "Col2", "Col1"]).createOrReplaceTempView("Table1")

spark.createDataFrame([
    ("000567,009123", "567,9123", "ZH10,JK14", "Spark111"), ("00657,00896", "657,896", "PK15,NU85", "Dmi563")
], ["Col7", "Col6", "Col5", "Col8"]).createOrReplaceTempView("Table2")

spark.sql(above_query).show()

#+------+--------+----+-----+----+----+-------------+--------+
#|  Col1|    Col2|Col3| Col4|Col5|Col6|         Col7|    Col8|
#+------+--------+----+-----+----+----+-------------+--------+
#|000567|Spark111|ZH10|ZO123|ZH10| 567|000567,009123|Spark111|
#+------+--------+----+-----+----+----+-------------+--------+
</code>```

Body:
I'm trying to make a select between 2 tables which I cannot join directly ( they don't have the same values ).

My 2 input table look something like this:

Table1:

Col4      |   Col3  |   Col2     |  Col1
ZO123     |   ZH10  |  Spark111  | 000567
VS561     |   JK14  |  Dmi563    | 009123

Table2 ( here is the main problem, as we have concatenated values inside the cells):

    Col7         |     Col6      |    Col5    |  Col8
000567,009123    |   567,9123    |  ZH10,JK14 | Spark111
00657,00896      |   657,896     |  PK15,NU85 | Dmi563

Table1 is a temp view as well with 410 million rows. Table2 is a temp view with 221 rows.
Both are temp views built on top of some parquet files.

The query that I currently test and it's taking like 2 hours is:

CREATE OR REPLACE TEMP VIEW Table3 AS SELECT w.Col1 AS Col1
w.Col2 AS Col2
w.Col3 AS Col3
w.Col4 AS Col4
m.Col5 AS Col5,
m.Col6 AS Col6,
m.Col7 AS Col7
m.Col8 AS Col8 FROM Table1 w,Table2 m
WHERE exists (SELECT * FROM Table2 WHERE exists(split(Table2.Col5, ','), x -> x = w.Col3) AND Table2.Col5 = m.Col5 AND exists(split(Table2.Col6, ','), x -> x = udf_function_to_remove_zeros(w.Col1)) and Table2.Col6 = m.Col6 AND exists(split(Table2.Col8, ','), x -> x = w.Col2) AND Table2.Col8 = m.Col8)

The main idea is that I'm trying to retrieve rows from Table1 where the values from rows can be found in the splited values from Table2. Also, all the conditions should be passed with AND.

Body:
You are facing performance issues probably because you're:

unnecessarily doing a cartesian product FROM Table1 w,Table2 m

using UDF to remove leading zeros while you can do the same using builtin functions

You can actually write the same query using inner join like this:

SELECT
  w.Col1 AS Col1,
  w.Col2 AS Col2,
  w.Col3 AS Col3,
  w.Col4 AS Col4,
  m.Col5 AS Col5,
  m.Col6 AS Col6,
  m.Col7 AS Col7,
  m.Col8 AS Col8
FROM
  Table1 w
JOIN (
  SELECT
    Col7,
    Col8,
    INLINE(ARRAYS_ZIP(SPLIT(Col6, ','), SPLIT(Col5, ','))) AS (Col6, Col5)
  FROM
    Table2
) m
ON
  w.Col3 = m.Col5
  AND TRIM(LEADING '0' FROM w.Col1) = m.Col6
  AND w.Col2 = m.Col8

Applied to your input example:

spark.createDataFrame([
    ("ZO123", "ZH10", "Spark111", "000567"), ("VS561", "JK14", "Dmi563", "009123")
], ["Col4", "Col3", "Col2", "Col1"]).createOrReplaceTempView("Table1")

spark.createDataFrame([
    ("000567,009123", "567,9123", "ZH10,JK14", "Spark111"), ("00657,00896", "657,896", "PK15,NU85", "Dmi563")
], ["Col7", "Col6", "Col5", "Col8"]).createOrReplaceTempView("Table2")

spark.sql(above_query).show()

#+------+--------+----+-----+----+----+-------------+--------+
#|  Col1|    Col2|Col3| Col4|Col5|Col6|         Col7|    Col8|
#+------+--------+----+-----+----+----+-------------+--------+
#|000567|Spark111|ZH10|ZO123|ZH10| 567|000567,009123|Spark111|
#+------+--------+----+-----+----+----+-------------+--------+


问:
how to fetch from db with laravel using CONCAT and COUNT
In database I have table Users like this:

```<code>// id // name  // street  // house
--------------------------
// 1 // name1  // street1 // 1
// 2 // name2  // street1 // 1
// 3 // name3  // street1 // 1
// 4 // name4  // street2 // 2
// 5 // name5  // street3 // 3
// 6 // name6  // street4 // 4
// 7 // name7  // street5 // 5

</code>```

I need to make a selection where I will get the full address and the number of records with that address in descending order for Users in users_ids array. The result should look like this:

```<code> address     number
'street1 1'   3
'street2 2'   1
'street3 3'   1
'street4 4'   1
'street5 5'   1
</code>```

in laravel i use query:

```<code>        $recordsByAddresses = DB::table('users')
            ->whereIn('id', $users_ids)
            ->select(DB::raw("CONCAT(street, ' ', house) AS address"), DB::raw("COUNT(CONCAT(street, ' ', house)) AS number"))
            ->orderBy('number', 'desc')
            ->get();
</code>```

As a result I get only one first address and the number of all addresses:

```<code> address     number
'street1 1'   7
</code>```

答:
It's untested but this might work:</p>
```<code>$recordsByAddresses = DB::table('users')
    ->whereIn('id', $userIds)
    ->select(
        DB::raw('CONCAT(street, " ", house) AS address'),
        DB::raw('count(*) as total')
    )
    ->groupBy('address')
    ->orderBy('total', 'desc')
    ->get();
</code>```

Body:
In database I have table Users like this:

// id // name  // street  // house
--------------------------
// 1 // name1  // street1 // 1
// 2 // name2  // street1 // 1
// 3 // name3  // street1 // 1
// 4 // name4  // street2 // 2
// 5 // name5  // street3 // 3
// 6 // name6  // street4 // 4
// 7 // name7  // street5 // 5

I need to make a selection where I will get the full address and the number of records with that address in descending order for Users in users_ids array. The result should look like this:

 address     number
'street1 1'   3
'street2 2'   1
'street3 3'   1
'street4 4'   1
'street5 5'   1

in laravel i use query:

        $recordsByAddresses = DB::table('users')
            ->whereIn('id', $users_ids)
            ->select(DB::raw("CONCAT(street, ' ', house) AS address"), DB::raw("COUNT(CONCAT(street, ' ', house)) AS number"))
            ->orderBy('number', 'desc')
            ->get();

As a result I get only one first address and the number of all addresses:

 address     number
'street1 1'   7

Body:
It's untested but this might work:

$recordsByAddresses = DB::table('users')
    ->whereIn('id', $userIds)
    ->select(
        DB::raw('CONCAT(street, " ", house) AS address'),
        DB::raw('count(*) as total')
    )
    ->groupBy('address')
    ->orderBy('total', 'desc')
    ->get();