问:
Choosing OData or REST ? Detailed Analysis
Below is the Analysis from various web-sites about Odata.

Background about Odata

```<code>1. open standard and web protocol. protocol to expose data over the internet
2. developed by Microsoft, managed by Oasis Org
3. open data protocol - allow creation and consumption of query-able and inter-operable RESTFUL APIs
4. best way to REST
5. used by mobile and web app widely
6. all info about odata - odata.org
7. odata reference services - https://www.odata.org/odata-services/
8. querying and updating data
9. built on http and sends data using Json/Atom
10. support various advanced query language. example
    a. filtering and ordering data - http://../api/Orders?$filter=Total gt 1000$orderby=shippedat
       desc
    b. navigating through relationship - http://../api/Orders(451)/Lines(4)/Product/Name
    c. client side paging - http://../api/Orders?$top=10&$skip=10 and ~/Products/$skip=70&$top=10
11. Asynchronous queries
12. Odata protocol allows the publisher to tag and label the data with domain specific vocabularies.
13. Access data from any platform or device
14. OData shares some similarities with JDBC and with ODBC; like ODBC, OData is not limited to
   relational databases.
</code>```

What problem Odata solves?

```<code>Data Api's frequently create more problem than solutions. many web-sites exposes data via apis
(ex: facebook, twitter)

Ex: facebook: what fields will i get when you read a post? time, user name
    twitter api: list of user's following me and unfollow someone (ex: post
    https://api.twitter.com/1.1/friendships/destroy.json with id)

Usual problem: how to developers know ? they need to go through the documents. if API is changed,
               then the request will be changed. uniformity increases the time needed to learn the
               API.

Reduces the amount of time to design an API.
</code>```

Rest Issues?

```<code>a. URL structure i.e how do you want your URL looks
b. search
c. how do you use the method consistenly
d. how do you create a new resource
</code>```

Difference between OData vs REST

```<code>OData prescribes conventions that REST doesn't

   a. Representation formats
   b. Precise verb meaning
   c. URL conventions for filtering, paging etc.,
</code>```

Other differences

```<code>1. The problem is that ODBC allows clients to initiate transactions across multiple requests. REST
   does not allow this as it would violate the stateless constraint.
2. OData is a specific protocol where as REST is architecture style and design pattern
3. All OData is REST, but NOT all REST is OData.
</code>```

Negatives or Drawbacks of Odata

```<code>1. anti-pattern - provides both a weak contract and leaky abstraction. development and API practices
   by providing a black-box framework to enforce a generic repository pattern.
2. An API should be designed with a specific intent in mind rather than providing a generic set of
   methods that are automatically generated. OData tends to give rise to very noisy method outputs
   with a metadata approach that feels more like a WSDL than REST. This doesn’t exactly foster
   simplicity and usability.
3. allows remote clients to execute database queries remotely over HTTP which can only give rise to
   complex and fragile integrations that break under the weight of edge case problems.
4. OData stems from an era (the 2000’s) where everything had to be XML (and SOAP ugh!). That era has
   luckily passed and the open web has moved on to other simpler & more efficient formats & protocols
   like JSON or protobuf etc.
</code>```

Reference Links

```<code>1. http://pragmatiqa.com/xodata/ for non-developer to play with Odata
2. https://www.odata.org/odata-services/ - Odata Services
3. https://en.wikipedia.org/wiki/Open_Data_Protocol
</code>```

What is needed?

Looking for a detailed feedback/comments to know whether to go with Odata v4 or choose REST. Some says
Odata is outdated and doesn't fit for new generation or next generation app. Not sure.

Sample working Odata app and database to play with or work with to understand Odata better.

Best way to quickly learn or get upto speed on Odata.

答:
Lets be honest, the reason that there was no response to this earlier is that this topic and the way the question was asked is too broad to be properly on-topic for SO. I'll draft this here and find somewhere else to publish it later ;).

OData IS the best way to REST

An open protocol to allow the creation and consumption of queryable and interoperable RESTful APIs in a simple and standard way.

OData Protocol Overview

The OData Protocol is different from other REST-based web service approaches in that it provides a uniform way to describe both the data and the data model. This improves semantic interoperability between systems and allows an ecosystem to emerge

Many of your arguments both for and against are outdated or unfounded, so I don't want to address each of them individually, but the reason that OData was created in the first place was to address the sprawl of unique interpretations of what a REST API means by creating a standard for these aspects of APIs:

Describing the resources and capabilities of an API (CSDL)

URL Routing conventions

Response Formats and Structures

Aggregated Queries across Resources

While anyone can say their API is REST based on the fact that it uses HTTP requests, is uniform within itself and might be stateless, a Rest API that is OData Compliant  is a specific implementation that follows the guidelines described in the OData protocol and specifically constrains the definitions of what a resource is and how different resources can be related to each other.

Fundamental to the OData protocol is to the idea that the standards should keep API development simple for both developers and consumers. The common standard has facilitated the evolution of libraries and frameworks that significantly reduce the common boilerplate logic that each API requires to conform to these standards.

Another key factor that OData addresses is that APIs often provide more data and metadata than many clients require, which leads to unnecessary bandwidth consumption. Some APIs address this by creating multiple endpoints that serve different structures or views for the same resource, OData provides a Query language that allows clients to specify how much detail they require from a request, but importantly there is limited scope to modify the resource, you can only reduce the schema that is returned by omission of the properties that you do no want transmitted. In this way the structure of responses will remain consistent, which is especially important for some client-side implementations.

in OData 4.01 it is now possible for us to make additive changes to the schema as well via the $compute operator.

PATCH

Reducing the bytes over the wire also comes into play with the partial update via HTTP PATCH. From a pure REST point of view, PUT should be used to update an existing resource, it is guaranteed to be idempotent. Thta means a real REST architecture should respect any and ALL content provided via  PUT request and subsequent calls to GET the same resource should return the same content. This is problematic in Application Design, especially in a scenario where 2 users update a different fields in the same resource at a similar time.

User John executes a GET on the resource X (which represents a Prospect)

John is from Sales, he is updating the status of a lead that includes some lengthy notes on a new proposal before calling , so it will take a few minutes before they submit the PUT

User Jane executes a GET on the resource X

Jane is from Admin and is processing a request to change the contact number for the Prospect

Unless each client application is tracking changes and executes a new GET immediately before submitting a PUT to ensure that they have data that is up to date, or you try to do something similar on the service side, then one of the following scenarios will occur:

John submits first, then Jane submits. Jane's submission didn't have any of the data that John has entered, Jane's PUT will overwrite Johns. We will lose all of Johns changes, including new contract arrangements or offers

Jane submits first, then John. John's submission overwrites Janes, so the new contact number is lost and the record retains the previous value.

In both cases, there are not likely to be any errors raised, at the point in time of the submission in both cases, the API will override the stored content without question, that is what REST tells us to do.

There are workaround for this, like comparing the ETag first before processing a PUT request, but then the client would need to know how to handle potential failures which will result in either a poor user experience or a lot of code to maintain.

OData actually introduces a new issue with PUT, if it is possible to query only a single property from a resource via $select, then if you were to pass that same value back in a PUT then now the entire resource is nulled out except for the single property that was PUT back into that resource.

PATCH allows us to send a differential structure (AKA Delta) that only contains the properties that you wish to change. In this way the previous John vs Jane scenario is avoided as long as both John and Jane are not trying to edit the same fields. This is a more advanced optimistic concurrency scenario, but due to $select it is really important to avoid the client accidentally nulling out properties that the client may not have even been aware they existed.

In an OData implementation it is a good idea to disable PUT altogether.

The last comment "properties that the client may not have even been aware they existed" is more important than it sounds at first. Over time, it is likely that the Schema of your API is likely to change, and your clients are not likely to change as fast or at all in some cases. This can cause significant issues when PUT
is used and it can be hard to identify when it becomes a problem. If the client code uses serialization techniques that do not retain the original JSON schema, for instance if you deserialize into a strongly typed interface, then it is common for additional fields that do not match the interface contract to be excluded. Then on a subsequent PUT the original state of the missing fields, even though the client code didn't make any changes to it, would effectively be deleted.

PATCH when implemented correctly has an enormous impact on the integrity of data as well as performance, most CRUD data operations will only be modifying specific fields, not every property on the resource. PATCH reduces bandwidth consumption and reduces to data merge conflicts that might still occur to just those specific fields that are entered by the different operators at the same time.

Why Choose OData

OData is commonly chosen as part of a Rapid Application Development (RAD) SDLC process, I only have anecdotal evidence to support that, but the features of OData correlate very closely with RAD priorities. The idea that we can quickly expose the bulk business application framework and start prototyping the client implementation is very tempting on its own, but hyper important in a RAD process, the front end devs need the API to start coding against, often before the API guys have fully defined all of the behaviours and operations available.

OData fits the throw away prototype culture of RAD development because the client developers can use the rich query capabilities to access data in ways the API designers hadn't yet considered. Through the feedback from the each cycle of the development process, Functions, Actions and new Aggregates will be added to the Business Model to create efficiencies and enhance the next iteration of client side development.

Fundamentally the underlying Business Resources are not likely to change throughout this process, a change to the Business Model is after all a change to the Business. Complex queries from the client, however inefficient will do the job, hoever any complex logic from the client should be transitioned through to the API layer to reduce the logic on the client

What are the Cons to OData, why wouldn't you use it?

Most of the critisms against OData are against specific implementations and the lazy or relaxed patterns implemented in many APIs. For instance the latest version of .Net (6) comes with support for exposing an entire database via conventions through a single coded controller in less than 40 lines of code. Implementations like this that just expose everything are considered an anti-pattern because all they are doing is exposing a query mechanism through an abstraction layer, presumably the assumption is that there is no Business Logic implementation.

40 lines of code to get a server operating might sound appealing to some teams but this would be a very rudimentary API and it is generally expected that you would take more care to expose a rich set of Business Entities, Views (Functions) and Operations (Actions) outside of the standard CRUD capabilities.

In fact a well designed OData API will explicitly filter the available operations, routes and query options based on the security and business context needs, just as you would with and other REST based API.

OData is NOT designed to be a simple database query engine. It can be used to do this, and is really good at it, if that is your intention, but that is NOT the point of it.

OData allows your Business Domain Model to be queried, NOT specifically the database. If you choose to design your database schema following DDD principals, then it might be entirely appropriate to expose the database schema almost in its entirety through the OData protocol. But that is an implementation decision that sits purely with the author of that API, there is no requirement to expose a database at all.

All OData implementations require you to define the model via the CSDL, it is part of what makes OData stand out from other protocols, you must describe the model. This is also part of the reason why it is harder to implement an OData API, you are forced to describe things adequately and in a way that conforms to the protocol.

I said I wouldn't but lets address each of the drawbacks that were listed, noting that the primary source was an an article on Ben Morris.com about Netflix failing to deliver a robust API in 2013 for their business use case. - sorry that's a bit critical...

anti-pattern - provides both a weak contract and leaky abstraction. development and API practices by providing a black-box framework to enforce a generic repository pattern.

So all APIs could be considered "black box" and really should be, that is the point of the API to abstract away the internal implementation so consumers only see the business implementation. OData at least defines the input and output structure at a protocol level, a protocol cannot really offer much else other than the general expectation on how CRUD operations will be accepted.

As with all applications, the success of the product is usually less about the protocols used, and more about the business implementation and accessibility to the consumers. I am not familiar with the specific use cases that caused contention at Netflix, but it sounds like the structure of the data was not conducive to consumers and user adoption, it sounds very much like a DDD was NOT implemented very well. In this case OData is only to blame because of the ease of which they were able to publish the data schema and that they chose to use a very relaxed set of conventions to base their business model on.

An API should be designed with a specific intent in mind rather than providing a generic set of methods that are automatically generated. OData tends to give rise to very noisy method outputs with a metadata approach that feels more like a WSDL than REST. This doesn’t exactly foster simplicity and usability

Um... OData forces you to explicitly define the intent, that is precisely what makes OData different. There is a single metadata document that describes the intent and structure of the entire schema if you wish to read it, if developers wish to provide that level of documentation. WSDL (SOAP) and XSD are the only other standard protocols that I am aware of that are highly specific to inputs and outputs, OData is a lot less prescriptive and focuses on data types, enums and nullability.

The fundamental difference with OData is the heavy focus on resource items and collections. It takes some effort to design your business model around this resource concept, especially if your database schema is no inline with this.

It doesn't matter what the protocol is, an API should be designed with specific intent in mind, OData is no different. Just because OData allows the client to control the content through a rich query language is no less indicative of intent, but it des allow the client callers some flexibility capability

The same article is critical that OData is like WSDL as if that is a negative thing, but then crusifies OData from not being prescriptive enough, so I think this point is moot.

Most of us agree that from a programming point of view WSDL is too specific and therefore prohibitive, and that REST on it's own is too ambiguous. OData attempts to create a middle ground, the descriptive language is specifically designed to convey all the information that youneed to generate the necessary request and response structures in the client implemenation, which matches the same information that would be intrinsically available if the API was a simple code reference that was included in your client-side project.

allows remote clients to execute database queries remotely over HTTP which can only give rise to complex and fragile integrations that break under the weight of edge case problems.

As explained above, many OData APIs might expose direct database queries, but that is an implementation detail, there is no requirement to do this, the queries are against the Business Domain Model, if the author maps that directly to their database then that is precisely what they wanted to do and would likely do the same thing if forced to use another implementation.

OData stems from an era (the 2000’s) where everything had to be XML (and SOAP ugh!). That era has luckily passed and the open web has moved on to other simpler & more efficient formats & protocols like JSON or protobuf etc.

I have no words, this again is the negative reference to SOAP, but OData is the very embodyment of moving on from SOAP and XML. Yes the $metadata document is expressed in XML, but that is very deliberate and no apologies are made for this, JSON does not have the necessary semantics to fully express all that needs to be documented in the CSDL without an accompanying schema document.

Overall the main criticisms of OData revolve around the perception of too much flexibility for the client to do what they want, but the reality is that in many projects we don't always know what the client wants in advance, so this flexibility becomes the main deciding reason to use OData, it is not always a negative concept.

Many devs leave OData APIs wide open, but the same due diligence should be taken in reviewing the cpabilities of endpoints in all APIs before releasing them to the public domain. The main difference is what is normally off or prevented in other APIs may be enabled in OData.

What else is there:

In researching for this post I found a lot of negative content about OData, mostly in the GraphQL vs OData, this article I found to be quite balanced, REST API Industry Debate: OData vs GraphQL vs ORDS. (I had never even heard of ORDS) The closing argument sums things up very well, The concept of OData is really good, the implementation even using all the available tools still takes a lot of work to make your implementation fully OData compliant.

You mention ODBC... Lets call that about as close to directly accessing the database as you can get. The problem with ODBC / OLE DB / ADO is that you are exposing the raw database implementation and that there is little room for encapsulation of Business Domain logic and structures, you would be required to manage all of that into the database layer directly.

Thats an oversimplification, but in general ODBC is reserved for high trust environments, so generally internal facing interface, or when the caller manages most of the business logic.

ODBC / OLE DB / ADO are Data Access protocols that your API uses to talk to the databases, the API is essentially an abstraction around these concepts that encapsulates your Business Domain Logic.

If we talk about just different protocols, then GraphQL is really the only other protocol that competes with OData at a protocol level. To choose to go with a simple REST or JSON API is really like saying you will make your own standards in terms of routing, responses and behaviours. Which you are very welcome to do, there are many different libraries that will provide there own implementation standards but to do a proper Pro/Con analysis would require comparison against specific implementations, it isn't fair to say that in general they are any better or worse that OData/GraphQL, they would simply be different and it is up to you what sort of interface you want to expose to your consumers.

The reason to go with a standard implementation is to offload the knowledge on how to consume your API, with OData it is customary in documentation to firstly refer consumers to the version of the protocol that your API conforms to, and the supported vocabularies (because we don't bother implementing 100% of the specification every time). This covers the technical requirements, then you only need to describe specific features of your business domain that are not part of the OData protocol itself.

From a practical sense, implementing OData or GraphQL on your own from scratch can be a lot of work, your chosen language, development environment, deployment environment and skill level may dictate what frameworks would be practical for you to use, the structure of your database or internal services that you are exposing through the API will also factor into the level of effort that might be required for different protocol implementations.

A very simple OData vs GraphQL:

GraphQL is great for aggregating multiple services or repository based APIs or microservices where different resources are sourced from different or multiple internal endpoints. If your resources are all centrally located, especially if they are in the same DB then an OData API will be far simpler to implement and manage.

GraphQL is IMO the best solution for creating an abstraction layer exposing multiple existing services or data sources through a common API

OData is great when there is a single or highly coupled data source where there are very clear relationships between the resources.

OData is IMO the best solution for exposing a business schema for CRUD interoperability with a client application or for integrations.

Other than that they generally attempt to solve similar problems in different ways.

Body:
Below is the Analysis from various web-sites about Odata.

Background about Odata

1. open standard and web protocol. protocol to expose data over the internet
2. developed by Microsoft, managed by Oasis Org
3. open data protocol - allow creation and consumption of query-able and inter-operable RESTFUL APIs
4. best way to REST
5. used by mobile and web app widely
6. all info about odata - odata.org
7. odata reference services - https://www.odata.org/odata-services/
8. querying and updating data
9. built on http and sends data using Json/Atom
10. support various advanced query language. example
    a. filtering and ordering data - http://../api/Orders?$filter=Total gt 1000$orderby=shippedat
       desc
    b. navigating through relationship - http://../api/Orders(451)/Lines(4)/Product/Name
    c. client side paging - http://../api/Orders?$top=10&$skip=10 and ~/Products/$skip=70&$top=10
11. Asynchronous queries
12. Odata protocol allows the publisher to tag and label the data with domain specific vocabularies.
13. Access data from any platform or device
14. OData shares some similarities with JDBC and with ODBC; like ODBC, OData is not limited to
   relational databases.

What problem Odata solves?

Data Api's frequently create more problem than solutions. many web-sites exposes data via apis
(ex: facebook, twitter)

Ex: facebook: what fields will i get when you read a post? time, user name
    twitter api: list of user's following me and unfollow someone (ex: post
    https://api.twitter.com/1.1/friendships/destroy.json with id)

Usual problem: how to developers know ? they need to go through the documents. if API is changed,
               then the request will be changed. uniformity increases the time needed to learn the
               API.

Reduces the amount of time to design an API.

Rest Issues?

a. URL structure i.e how do you want your URL looks
b. search
c. how do you use the method consistenly
d. how do you create a new resource

Difference between OData vs REST

OData prescribes conventions that REST doesn't

   a. Representation formats
   b. Precise verb meaning
   c. URL conventions for filtering, paging etc.,

Other differences

1. The problem is that ODBC allows clients to initiate transactions across multiple requests. REST
   does not allow this as it would violate the stateless constraint.
2. OData is a specific protocol where as REST is architecture style and design pattern
3. All OData is REST, but NOT all REST is OData.

Negatives or Drawbacks of Odata

1. anti-pattern - provides both a weak contract and leaky abstraction. development and API practices
   by providing a black-box framework to enforce a generic repository pattern.
2. An API should be designed with a specific intent in mind rather than providing a generic set of
   methods that are automatically generated. OData tends to give rise to very noisy method outputs
   with a metadata approach that feels more like a WSDL than REST. This doesn’t exactly foster
   simplicity and usability.
3. allows remote clients to execute database queries remotely over HTTP which can only give rise to
   complex and fragile integrations that break under the weight of edge case problems.
4. OData stems from an era (the 2000’s) where everything had to be XML (and SOAP ugh!). That era has
   luckily passed and the open web has moved on to other simpler & more efficient formats & protocols
   like JSON or protobuf etc.

Reference Links

1. http://pragmatiqa.com/xodata/ for non-developer to play with Odata
2. https://www.odata.org/odata-services/ - Odata Services
3. https://en.wikipedia.org/wiki/Open_Data_Protocol

What is needed?

Looking for a detailed feedback/comments to know whether to go with Odata v4 or choose REST. Some says
Odata is outdated and doesn't fit for new generation or next generation app. Not sure.

Sample working Odata app and database to play with or work with to understand Odata better.

Best way to quickly learn or get upto speed on Odata.


来源: stackexchange

问:
How to properly store and extract AZURE_TENANT_ID, AZURE_CLIENT_ID and AZURE_CLIENT_SECRET?
I have this azure key vault in which I have stored an api key.
I have via Visual studio added the azure key vault as an connected service to the project.

I try to get my keyvalue stored in akv via this code

```<code>    HttpClient client = new HttpClient();
    string keyVaultName = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("web-kv")) ? Environment.GetEnvironmentVariable("web-kv") : throw new ArgumentNullException("web-kv");
    string kvUri = "https://" + keyVaultName + ".vault.azure.net";
    bool success = Uri.TryCreate(kvUri, UriKind.Absolute, out Uri uri);
    if(!success)
    {
        throw new Exception(kvUri);
    }
        var akvClient = new SecretClient(new Uri(kvUri), new DefaultAzureCredential());
        var apiKey = akvClient.GetSecret("LicenseApiKey");
</code>```

Which returns this exception

```<code>Azure.Identity.AuthenticationFailedException: The DefaultAzureCredential failed to retrieve a token from the included credentials.
  EnvironmentCredential is unavailable Environment variables not fully configured. AZURE_TENANT_ID and AZURE_CLIENT_ID must be set, along with either AZURE_CLIENT_SECRET or AZURE_USERNAME and AZURE_PASSWORD. Currently set variables [  ].
  ManagedIdentityCredential is unavailable No managed identity endpoint found..
  SharedTokenCacheCredential is unavailable No accounts were discovered in the shared token cache. To fix, authenticate through tooling supporting azure developer sign on..
</code>```

the application is not registerd as an APP in azure, and for some reason it does not detect that the environment variable is set?

答:
On development environment you need to use SecretManager as described here.

Here you can find a deep dive with a working sample.

ContentLicense: CC BY-SA 4.0

Body:
I have this azure key vault in which I have stored an api key.
I have via Visual studio added the azure key vault as an connected service to the project.

I try to get my keyvalue stored in akv via this code

    HttpClient client = new HttpClient();
    string keyVaultName = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("web-kv")) ? Environment.GetEnvironmentVariable("web-kv") : throw new ArgumentNullException("web-kv");
    string kvUri = "https://" + keyVaultName + ".vault.azure.net";
    bool success = Uri.TryCreate(kvUri, UriKind.Absolute, out Uri uri);
    if(!success)
    {
        throw new Exception(kvUri);
    }
        var akvClient = new SecretClient(new Uri(kvUri), new DefaultAzureCredential());
        var apiKey = akvClient.GetSecret("LicenseApiKey");

Which returns this exception

Azure.Identity.AuthenticationFailedException: The DefaultAzureCredential failed to retrieve a token from the included credentials.
  EnvironmentCredential is unavailable Environment variables not fully configured. AZURE_TENANT_ID and AZURE_CLIENT_ID must be set, along with either AZURE_CLIENT_SECRET or AZURE_USERNAME and AZURE_PASSWORD. Currently set variables [  ].
  ManagedIdentityCredential is unavailable No managed identity endpoint found..
  SharedTokenCacheCredential is unavailable No accounts were discovered in the shared token cache. To fix, authenticate through tooling supporting azure developer sign on..

the application is not registerd as an APP in azure, and for some reason it does not detect that the environment variable is set?


问:
How do I configure Intellij to allow node import assertions?
I have the following code...

It compiles and functions just fine with the --experimental-json-modules flag but it still shows the following error on the red tilda...

I am already configured to use ECMAScript6+ so what else do I need?

答: Import assertions proposal is supported since version 2021.3, see WEB-52552; please consider upgrading IDEA to the most recent version</p>


问:
Java Logger usage
I made a custom logger for my project by using java.util.logging:

public class SpotifyLogger {
    private static final Logger LOGGER = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
    public SpotifyLogger(String loggerFilePath) throws IOException {
        Logger myLogger = Logger.getLogger("");
        // suppress console messaging
        Handler[] handlers = myLogger.getHandlers();
        if (handlers[0] instanceof ConsoleHandler) { //exception occurs here
            myLogger.removeHandler(handlers[0]);
        }
        // set level
        LOGGER.setLevel(Level.SEVERE);
        // create a txt handler
        FileHandler textFileHandler = new FileHandler(loggerFilePath);
        SimpleFormatter simpleFormatter = new SimpleFormatter();
        textFileHandler.setFormatter(simpleFormatter);
        LOGGER.addHandler(textFileHandler);
    }
    public void log(String user, Exception e) {
        LOGGER.log(Level.SEVERE, user, e);
    }
}
```
<p>For the client and the server parts of my program, I create two separate Logger objects:</p>
<pre class="lang-java prettyprint-override"><code>// class member initialized as null, because of exception handling
private SpotifyLogger logger = null;
//...
//in constructor:
this.logger = new SpotifyLogger(LOGGER_FILE_NAME); // the LOGGER_FILE_NAME is different for the client and the server
</code>```

When I test my program manually, the loggers seem to work (the two log files contain exceptions that I have caused). Then, I wrote automatic tests. For each class that I am testing (a total of 5), I create a separate logger object with a different destination path. The tests (for whichever class comes first) work correctly. All other tests fail because I get an ArrayIndexOutOfBoundsException, when I initialize the logger for that particular class. The reason is that I am trying to access handlers[0], when handlers has 0 length. From what I understood after searching the web, this is because the logger is using parent handlers. I tried this:

public SpotifyLogger(String loggerFilePath) throws IOException {
    Logger myLogger = Logger.getLogger("");
    // suppress console messaging
    myLogger.setUseParentHandlers(false);
    Handler[] handlers = myLogger.getHandlers();
    if (handlers.length > 0) {
        if (handlers[0] instanceof ConsoleHandler) {
            myLogger.removeHandler(handlers[0]);
        }
    }
    //etc
}
```

I don't get an exception anymore but the logging doesn't work. What am I doing wrong?

答:
This doesn't make much sense to me

Logger myLogger = Logger.getLogger("")

Reference: Oracle java docs

Title: Java Logger usage

Body:
I made a custom logger for my project by using java.util.logging:

public class SpotifyLogger {
    private static final Logger LOGGER = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
    public SpotifyLogger(String loggerFilePath) throws IOException {
        Logger myLogger = Logger.getLogger("");
        // suppress console messaging
        Handler[] handlers = myLogger.getHandlers();
        if (handlers[0] instanceof ConsoleHandler) { //exception occurs here
            myLogger.removeHandler(handlers[0]);
        }
        // set level
        LOGGER.setLevel(Level.SEVERE);
        // create a txt handler
        FileHandler textFileHandler = new FileHandler(loggerFilePath);
        SimpleFormatter simpleFormatter = new SimpleFormatter();
        textFileHandler.setFormatter(simpleFormatter);
        LOGGER.addHandler(textFileHandler);
    }
    public void log(String user, Exception e) {
        LOGGER.log(Level.SEVERE, user, e);
    }
}

For the client and the server parts of my program, I create two separate Logger objects:

// class member initialized as null, because of exception handling
private SpotifyLogger logger = null;
//...
//in constructor:
this.logger = new SpotifyLogger(LOGGER_FILE_NAME); // the LOGGER_FILE_NAME is different for the client and the server

When I test my program manually, the loggers seem to work (the two log files contain exceptions that I have caused). Then, I wrote automatic tests. For each class that I am testing (a total of 5), I create a separate logger object with a different destination path. The tests (for whichever class comes first) work correctly. All other tests fail because I get an ArrayIndexOutOfBoundsException, when I initialize the logger for that particular class. The reason is that I am trying to access handlers[0], when handlers has 0 length. From what I understood after searching the web, this is because the logger is using parent handlers. I tried this:

public SpotifyLogger(String loggerFilePath) throws IOException {
    Logger myLogger = Logger.getLogger("");
    // suppress console messaging
    myLogger.setUseParentHandlers(false);
    Handler[] handlers = myLogger.getHandlers();
    if (handlers.length > 0) {
        if (handlers[0] instanceof ConsoleHandler) {
            myLogger.removeHandler(handlers[0]);
        }
    }
    //etc
}

I don't get an exception anymore but the logging doesn't work. What am I doing wrong?


问:
How to use lower-case() function in XSLT 2.0?
In a small XML conversion project I am working on, I am able to use the XSLT 1.0 translate() function to convert to lowercase or uppercase as suggested in posts like this one, so that something like the following works fine:

```<code><xsl:variable name="lowercase" select="'abcdefghijklmnopqrstuvwxyz'" />
<xsl:variable name="uppercase" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'" />
<xsl:value-of select="translate(@value, $uppercase, $lowercase)" />
</code>```

But really, I would prefer to use XSLT 2.0's lower-case() function, but for the following:

```<code><xsl:value-of select="lower-case(@value)" />
</code>```

...Chrome outputs nothing, and Firefox gets "unknown" error 0x8060000e, which maybe suggests that the lower-case() function isn't recognized. Perhaps my problem is something with the XML declaration line?:

```<code><xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
</code>```

...or is there something else I'm missing?

答: Neither Chrome nor Firefox support XSLT2, in spite of its being a 4-year old standard.  See for example this Firefox bug, languishing since 2008.</p>

ContentLicense: CC BY-SA 3.0

Body:
In a small XML conversion project I am working on, I am able to use the XSLT 1.0 translate() function to convert to lowercase or uppercase as suggested in posts like this one, so that something like the following works fine:

<xsl:variable name="lowercase" select="'abcdefghijklmnopqrstuvwxyz'" />
<xsl:variable name="uppercase" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'" />
<xsl:value-of select="translate(@value, $uppercase, $lowercase)" />

But really, I would prefer to use XSLT 2.0's lower-case() function, but for the following:

<xsl:value-of select="lower-case(@value)" />

...Chrome outputs nothing, and Firefox gets "unknown" error 0x8060000e, which maybe suggests that the lower-case() function isn't recognized. Perhaps my problem is something with the XML declaration line?:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

...or is there something else I'm missing?


问:
Chart.js core.js:6162 ERROR Error: "line" is not a registered controller

 const gainContext = this.gainRef.nativeElement.getContext('2d')
  gainContext.canvas.height = '300px'

  new Chart(gainContext, createChartConfig(gainConfig))

function createChartConfig({type, labels, data, label, color}: ChartConfig): ChartConfiguration<"line">{

  console.log('3 Chart.defaults', Chart.defaults)

  return {
type: "line",
data: {
  labels,
  datasets: [
    {
      label,
      data,
      borderColor: color,
      stepped: false,
      fill: false
    }
  ]
}
  }```

This is not working: It not recognize the type property as it must in official documentation.

let myChart = new Chart(gainContext, {
type: 'line',

What I do wrong?

答:
please upgrade npm package, its worked for me</p>
```<code>npm i chart.js@2.9.4
</code>```

Body:
 const gainContext = this.gainRef.nativeElement.getContext('2d')
  gainContext.canvas.height = '300px'

  new Chart(gainContext, createChartConfig(gainConfig))

function createChartConfig({type, labels, data, label, color}: ChartConfig): ChartConfiguration<"line">{

  console.log('3 Chart.defaults', Chart.defaults)

  return {
type: "line",
data: {
  labels,
  datasets: [
    {
      label,
      data,
      borderColor: color,
      stepped: false,
      fill: false
    }
  ]
}
  }

This is not working: It not recognize the type property as it must in official documentation.

let myChart = new Chart(gainContext, {
type: 'line',

What I do wrong?

Body:
please upgrade npm package, its worked for me

npm i chart.js@2.9.4


问:
How to Submit a Form With Action Page in a Different Folder?
I am not been able to submit a form if its action is on a page in a  different folder. I tried the following code:</p>
```<code><form action="model/insert_resident.php" onsubmit="return formvalidate()" method="POST">

    <label for="name">Name:</label><span id="err_name" style="color:red; display: none;">Enter Name</span>
      <input type="text" class="form-control" id="name" name="name" placeholder="Name">

    <label for="flatid">Flat Id:</label>
      <input type="text" class="form-control" id="flatid" name="flatid">

    <label for="email">Email:</label>
      <input type="text" class="form-control" id="email" name="email">

    <label for="phone">Phone:</label>
      <input type="number" id="phone" class="form-control"  name="phone">
      <input type="hidden" id="date" class="form-control" name="date" value="<?php echo date("Y-m-d"); ?>">

     <p id="chk"> </p>

     <input class="btn btn-primary" type="submit"  onClick="formvalidate()" name="insert" value="Add">

   </form>
</code>```

答:
As you have given us following in the form tag:

```<code>action="model/insert_resident.php
</code>```

we assume that your file called insert_resident.php is in the sub-directory model. Have you tried opening this page with the direct URL in the browser?
You should also try to prefix with a / or ./ to mean current directory.

```<code>action="./model/insert_resident.php
</code>```

Body:
I am not been able to submit a form if its action is on a page in a  different folder. I tried the following code:

<form action="model/insert_resident.php" onsubmit="return formvalidate()" method="POST">

    Name:Enter Name
      <input type="text" class="form-control" id="name" name="name" placeholder="Name">

    Flat Id:
      <input type="text" class="form-control" id="flatid" name="flatid">

    Email:
      <input type="text" class="form-control" id="email" name="email">

    Phone:
      <input type="number" id="phone" class="form-control"  name="phone">
      <input type="hidden" id="date" class="form-control" name="date" value="<?php echo date("Y-m-d"); ?>">

     <input class="btn btn-primary" type="submit"  onClick="formvalidate()" name="insert" value="Add">

   </form>

Body:
As you have given us following in the form tag:

action="model/insert_resident.php

we assume that your file called insert_resident.php is in the sub-directory model. Have you tried opening this page with the direct URL in the browser?
You should also try to prefix with a / or ./ to mean current directory.

action="./model/insert_resident.php


问:
Regex to get length of group of character classes
I have a workaround for this, but was hoping to find a purely regex solution.

The requirements are:

has one required character

only pulls from a pool of approved characters

minimum length of 4

single word, no whitespace

e.g.

required character: m

pool of characters: [a,b,e,l]

Possible matches:

mabel

abemal

labeam

won't match:

a mael

ama

label

So far I have this expression, but putting a {4,} after it thinks I'm talking about multiplying word matches by 4.

^\b(?:[abel]*[m]+[abel]*)\b

答:
You can use

```<code>^(?=.*[m])[abelm]{4,}$
</code>```

^ start of a line or string

Positive Lookahead (?=.*[m])

Asserts that the string contains at least 1 m character

[abelm]{4,} matches characters in the list abelm

between 4 and unlimited times, as many times as possible.

(greedy) (case sensitive)

$ end of a line or string

Body:
You can use

^(?=.*[m])[abelm]{4,}$

^ start of a line or string

Positive Lookahead (?=.*[m])

Asserts that the string contains at least 1 m character

[abelm]{4,} matches characters in the list abelm

between 4 and unlimited times, as many times as possible.

(greedy) (case sensitive)

$ end of a line or string


问:
TCP/IP basics: Destination port relevance
Ok this is kind of embarassing but I just have a rather "noob" question.

In a client server TCP communications, where my system is a client accessing a remote server at say Port XX, isnt the client opening a random port YY in its system to talk to remote port XX?
So when we code we do specify the destination port XX right?

For the client, the port YY itself is chosen when the socket is created, isnt it?

Is there anyway I could monitor/restrict/control any client talking to a particular server?(like say clients talking to servers at specific serving ports??)

Is there any IPTABLE rule or some firewall rule restricting the client?
Can this be done at all??

Are destination ports saved in the socket structures? If so where??

Thanks!

答: Yes you can create a firewall rule to prevent outbound TCP connections to port XX. For example, some organizations prevent outbound TCP port 25, to prevent spam being sent from network PCs to remote SMTP servers.</p>


问:
Is it wrong to periodically refresh a div in html?
I own a small messaging platform and I'm trying to make it live, so everything needs to work without any refresh. Messages are sent with Ajax and the procedure is refresh-free. I'm also trying to make sure that when Alice sends a message to Bob, Bob receives it (almost) immediately. For this reason, I'm refreshing the div containing all of the messages every second with this script:

```<code>      <script>
         $(document).ready(function() {
         var pageRefresh = 1000;
             setInterval(function() {
                 refresh();
             }, pageRefresh);
         });

         function refresh() {
             $("#messagesframe").load(" #messagesframe > *");
         }
      </script>

      <div id="messagesframe">
      <!-- messages displayed here! -->
      </div>
</code>```

This makes sure that every second the new messages are shown. I have a doubt, however, that this may slow down the application. I am asking you, thus, whether this doubt is well-founded or if this procedure is harmless. Any help is appreciated.

Note: I'm using PHP.

答: this kind of code is not Optimal, best way for real time applications is using socket technology</p>

Body:
I own a small messaging platform and I'm trying to make it live, so everything needs to work without any refresh. Messages are sent with Ajax and the procedure is refresh-free. I'm also trying to make sure that when Alice sends a message to Bob, Bob receives it (almost) immediately. For this reason, I'm refreshing the div containing all of the messages every second with this script:

This makes sure that every second the new messages are shown. I have a doubt, however, that this may slow down the application. I am asking you, thus, whether this doubt is well-founded or if this procedure is harmless. Any help is appreciated.

Note: I'm using PHP.


问:
How to validate canvas text in python?
I want to restrict the text box to characters only and Incase of error it should show messagebox

Also text box should show alternate characters but its showing only A

This is the function I used but it's not working

```<code>  def check():
    sel = T.get()

    if not sel.isalpha():
        messagebox.showerror('Only letters','Only letters are allowed!')
</code>```

below is my code:

```<code>from tkinter import *
root = Tk()
root.geometry("1600x890")

def check():
    sel = T.get("1")
    l = T1.get("1")

    if sel != 0 & l !=0:
    messagebox.showerror('Only letters','Only letters are allowed!')
    else:
        root.destroy()
        import mpr02

bg = PhotoImage(file="C:\\New folder (2)\\Pictures\python proj\\1.png")

canvas1 = Canvas(root, width=400, height=400)

canvas1.pack(fill="both", expand=True)

canvas1.create_image(0, 0, image=bg, anchor="nw")

canvas1.create_text(760, 60, text="WELCOME TO THE NARWANI ATLANTA", font=('Times New Roman', '24', 'bold'))
label2 = Label(root, text="USERNAME", fg="blue", bg="cyan")
label1 = Label(root, text="PASSWORD", fg="blue", bg="cyan")
T1 = Text(root, height=2.4, width=20)
button1 = Button(root, text="LOGIN", bg="magenta", fg="cyan", command=check)

button1_canvas = canvas1.create_window(744, 600, window=button1, width=90, height=38)
T = Text(root, height=2.4, width=20)
h="Adca"
T1 = Entry(root,show=h);
T_canvas = canvas1.create_window(850, 358, window=T)
label2_canvas = canvas1.create_window(624, 355, window=label2, width=138, height=37)
label1_canvas = canvas1.create_window(624, 455, window=label1, width=138, height=37)
T1_canvas = canvas1.create_window(850, 458, window=T1)
root.mainloop()
</code>```

答:
You're not calling Text widget get() method with the proper arguments — see Methods on Text widgets. You can snatch its entire contents from beginning to end using the text indices shown in the snippet below:

```<code>from tkinter import *
from tkinter import messagebox
root = Tk()
root.geometry("1600x890")

def check():
    sel = T.get('1.0', END)
    if not sel.isalpha():
        messagebox.showerror('Only letters','Only letters are allowed!')

bg = PhotoImage(file="8-ball.png")

canvas1 = Canvas(root, width=400, height=400)
canvas1.pack(fill="both", expand=True)

canvas1.create_image(0, 0, image=bg, anchor="nw")
canvas1.create_text(760, 60, text="Welcome to the Narwani Atlanta",
                    font=('Times New Roman', '24', 'bold'))

label2 = Label(root, text="USERNAME", fg="blue", bg="cyan")
label2_canvas = canvas1.create_window(624, 355, window=label2, width=138, height=37)

label1 = Label(root, text="PASSWORD", fg="blue", bg="cyan")
label1_canvas = canvas1.create_window(624, 455, window=label1, width=138, height=37)

button1 = Button(root, text="LOGIN", bg="magenta", fg="cyan", command=check)
button1_canvas = canvas1.create_window(744, 600, window=button1, width=90, height=38)

T = Text(root, height=2.4, width=20)
T_canvas = canvas1.create_window(850, 358, window=T)

T1 = Entry(root, show="*");
T1_canvas = canvas1.create_window(850, 458, window=T1)

root.mainloop()

</code>```

Title: How to validate canvas text in python?

Body:
I want to restrict the text box to characters only and Incase of error it should show messagebox

Also text box should show alternate characters but its showing only A

This is the function I used but it's not working

  def check():
    sel = T.get()

    if not sel.isalpha():
        messagebox.showerror('Only letters','Only letters are allowed!')

below is my code:

from tkinter import *
root = Tk()
root.geometry("1600x890")

def check():
    sel = T.get("1")
    l = T1.get("1")

    if sel != 0 & l !=0:
    messagebox.showerror('Only letters','Only letters are allowed!')
    else:
        root.destroy()
        import mpr02

bg = PhotoImage(file="C:\\New folder (2)\\Pictures\python proj\\1.png")

canvas1 = Canvas(root, width=400, height=400)

canvas1.pack(fill="both", expand=True)

canvas1.create_image(0, 0, image=bg, anchor="nw")

canvas1.create_text(760, 60, text="WELCOME TO THE NARWANI ATLANTA", font=('Times New Roman', '24', 'bold'))
label2 = Label(root, text="USERNAME", fg="blue", bg="cyan")
label1 = Label(root, text="PASSWORD", fg="blue", bg="cyan")
T1 = Text(root, height=2.4, width=20)
button1 = Button(root, text="LOGIN", bg="magenta", fg="cyan", command=check)

button1_canvas = canvas1.create_window(744, 600, window=button1, width=90, height=38)
T = Text(root, height=2.4, width=20)
h="Adca"
T1 = Entry(root,show=h);
T_canvas = canvas1.create_window(850, 358, window=T)
label2_canvas = canvas1.create_window(624, 355, window=label2, width=138, height=37)
label1_canvas = canvas1.create_window(624, 455, window=label1, width=138, height=37)
T1_canvas = canvas1.create_window(850, 458, window=T1)
root.mainloop()

Body:
You're not calling Text widget get() method with the proper arguments — see Methods on Text widgets. You can snatch its entire contents from beginning to end using the text indices shown in the snippet below:

from tkinter import *
from tkinter import messagebox
root = Tk()
root.geometry("1600x890")

def check():
    sel = T.get('1.0', END)
    if not sel.isalpha():
        messagebox.showerror('Only letters','Only letters are allowed!')

bg = PhotoImage(file="8-ball.png")

canvas1 = Canvas(root, width=400, height=400)
canvas1.pack(fill="both", expand=True)

canvas1.create_image(0, 0, image=bg, anchor="nw")
canvas1.create_text(760, 60, text="Welcome to the Narwani Atlanta",
                    font=('Times New Roman', '24', 'bold'))

label2 = Label(root, text="USERNAME", fg="blue", bg="cyan")
label2_canvas = canvas1.create_window(624, 355, window=label2, width=138, height=37)

label1 = Label(root, text="PASSWORD", fg="blue", bg="cyan")
label1_canvas = canvas1.create_window(624, 455, window=label1, width=138, height=37)

button1 = Button(root, text="LOGIN", bg="magenta", fg="cyan", command=check)
button1_canvas = canvas1.create_window(744, 600, window=button1, width=90, height=38)

T = Text(root, height=2.4, width=20)
T_canvas = canvas1.create_window(850, 358, window=T)

T1 = Entry(root, show="*");
T1_canvas = canvas1.create_window(850, 458, window=T1)

root.mainloop()


问:
How can I make a notification in a C# Windows app with a custom image and onclick function?
My ultimate goal is to have a Windows 10 app in C#.NET that displays a notification to the user. The notification should have a title, description, at least one image, and when clicked, it should open a webpage. It should also be stored in notification manager (or whatever that place in Windows that lists notifications is called) if the user doesn't click on it. So that's the goal.

I've tried a bunch of different ways of doing this, and cannot get any of them to work properly.

My current code uses the Microsoft.Toolkit.Uwp.Notifications NuGet package and is primarily taken from this sample:
https://learn.microsoft.com/en-us/windows/uwp/design/shell/tiles-and-notifications/adaptive-interactive-toasts?tabs=builder-syntax

The following code works great, as far as it goes:

```<code>using System;
using System.Windows;
using Microsoft.Toolkit.Uwp.Notifications;

namespace PushClient
{
    public partial class App : System.Windows.Application
    {
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            new ToastContentBuilder()
            .AddText("My Title")
            .AddText("My Description")
            .Show();
        }
    }
}
</code>```

Here is the notification it produces...

FIRST PROBLEM

The first problem is that I cannot add a custom image, even though there are supposedly three different methods through which an image can be added. I first tried this:

```<code>new ToastContentBuilder()
.AddText("My Title")
.AddText("My Description")
.AddAppLogoOverride((new Uri("https://picsum.photos/48?image=883")), ToastGenericAppLogoCrop.Circle)
.Show();
</code>```

That successfully removes the default icon at the left of the notification and adds the name of the app at the bottom (since the idea is that the logo has been gotten rid of, so the app has to be identified through some other method). However, there is no new image in place of the old. Just blank space.

I also attempted this:

```<code>new ToastContentBuilder()
.AddText("My Title")
.AddText("My Description")
.AddHeroImage(new Uri("https://picsum.photos/364/180?image=1043"))
.Show();
</code>```

But that changed literally nothing from the first version as far as I could tell.

Finally I tried this:

```<code>new ToastContentBuilder()
.AddText("My Title")
.AddText("My Description")
.AddInlineImage(new Uri("https://picsum.photos/360/202?image=1043"))
.Show();
</code>```

That seems to have added some blank space beneath the description, but no image.

SECOND PROBLEM

Another problem is that I cannot figure out how to add a full onclick action through this process. I would be perfectly happy with either a button that needs to be clicked, or a click action on the notification itself. But however it works, it ultimately needs to open a specified URL in the user's default browser.

OTHER ATTEMPTS

I have also played with other processes of sending notifications, like the ShowBalloonTip process. This seems to have no option at all for a custom image, which is what I want. However, I can select an image from a specified list of images, including a "warning" icon, which I've chosen in this code, and the onclick action is simple to add:

```<code>using System;
using System.Threading;
using System.Windows;
using System.Windows.Forms;

namespace PushClient
{
    public partial class App : System.Windows.Application
    {
        private NotifyIcon _notifyIcon = new NotifyIcon();

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            try
            {
                _notifyIcon = new NotifyIcon();
                _notifyIcon.Icon = PushClient.Properties.Resources.accountable2you;
                _notifyIcon.Visible = true;
                _notifyIcon.ContextMenuStrip = new System.Windows.Forms.ContextMenuStrip();

                Thread t = new Thread(() => LaunchBalloonNotification(_notifyIcon, "My Title", "My Description"));
                t.Start();
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
        private static void notifyIcon_BalloonTipClicked(object sender, EventArgs e)
        {
            Console.WriteLine("Action clicked");
        }
        private static void LaunchBalloonNotification(NotifyIcon ico, String title, String msg)
        {
            ico.ShowBalloonTip(
                10000,
                title,
                msg,
                ToolTipIcon.Warning
            );
            ico.BalloonTipClicked += new EventHandler(notifyIcon_BalloonTipClicked);
        }
    }
}
</code>```

I have also tried working with ToastNotificationManager, but the results I get with that are identical to the results I get with Microsoft.Toolkit.Uwp.Notifications... except that ToastNotificationManager requires an AppID to work, and I've had difficulty figuring out how I'm properly supposed to create such a thing for my little Visual Studio test app.

Anyway, if you can point me in the right direction to help me achieve my goal here (preferably with a minimal, reproducible example!), it would be much appreciated!

答:
maybe a bit late, but I had the same issue with the toast, if the user turned off the notification, not sure it's helpful.

To show toast like, I tried this with success : Tulpep.NotificationWindow

Works great, you add a control and access all the parameters, and able to show an image (and to resize).

Here's the link to an example : https://www.c-sharpcorner.com/article/working-with-popup-notification-in-windows-forms/

Body:
My ultimate goal is to have a Windows 10 app in C#.NET that displays a notification to the user. The notification should have a title, description, at least one image, and when clicked, it should open a webpage. It should also be stored in notification manager (or whatever that place in Windows that lists notifications is called) if the user doesn't click on it. So that's the goal.

I've tried a bunch of different ways of doing this, and cannot get any of them to work properly.

My current code uses the Microsoft.Toolkit.Uwp.Notifications NuGet package and is primarily taken from this sample:
https://learn.microsoft.com/en-us/windows/uwp/design/shell/tiles-and-notifications/adaptive-interactive-toasts?tabs=builder-syntax

The following code works great, as far as it goes:

using System;
using System.Windows;
using Microsoft.Toolkit.Uwp.Notifications;

namespace PushClient
{
    public partial class App : System.Windows.Application
    {
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            new ToastContentBuilder()
            .AddText("My Title")
            .AddText("My Description")
            .Show();
        }
    }
}

Here is the notification it produces...

FIRST PROBLEM

The first problem is that I cannot add a custom image, even though there are supposedly three different methods through which an image can be added. I first tried this:

new ToastContentBuilder()
.AddText("My Title")
.AddText("My Description")
.AddAppLogoOverride((new Uri("https://picsum.photos/48?image=883")), ToastGenericAppLogoCrop.Circle)
.Show();

That successfully removes the default icon at the left of the notification and adds the name of the app at the bottom (since the idea is that the logo has been gotten rid of, so the app has to be identified through some other method). However, there is no new image in place of the old. Just blank space.

I also attempted this:

new ToastContentBuilder()
.AddText("My Title")
.AddText("My Description")
.AddHeroImage(new Uri("https://picsum.photos/364/180?image=1043"))
.Show();

But that changed literally nothing from the first version as far as I could tell.

Finally I tried this:

new ToastContentBuilder()
.AddText("My Title")
.AddText("My Description")
.AddInlineImage(new Uri("https://picsum.photos/360/202?image=1043"))
.Show();

That seems to have added some blank space beneath the description, but no image.

SECOND PROBLEM

Another problem is that I cannot figure out how to add a full onclick action through this process. I would be perfectly happy with either a button that needs to be clicked, or a click action on the notification itself. But however it works, it ultimately needs to open a specified URL in the user's default browser.

OTHER ATTEMPTS

I have also played with other processes of sending notifications, like the ShowBalloonTip process. This seems to have no option at all for a custom image, which is what I want. However, I can select an image from a specified list of images, including a "warning" icon, which I've chosen in this code, and the onclick action is simple to add:

using System;
using System.Threading;
using System.Windows;
using System.Windows.Forms;

namespace PushClient
{
    public partial class App : System.Windows.Application
    {
        private NotifyIcon _notifyIcon = new NotifyIcon();

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            try
            {
                _notifyIcon = new NotifyIcon();
                _notifyIcon.Icon = PushClient.Properties.Resources.accountable2you;
                _notifyIcon.Visible = true;
                _notifyIcon.ContextMenuStrip = new System.Windows.Forms.ContextMenuStrip();

                Thread t = new Thread(() => LaunchBalloonNotification(_notifyIcon, "My Title", "My Description"));
                t.Start();
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
        private static void notifyIcon_BalloonTipClicked(object sender, EventArgs e)
        {
            Console.WriteLine("Action clicked");
        }
        private static void LaunchBalloonNotification(NotifyIcon ico, String title, String msg)
        {
            ico.ShowBalloonTip(
                10000,
                title,
                msg,
                ToolTipIcon.Warning
            );
            ico.BalloonTipClicked += new EventHandler(notifyIcon_BalloonTipClicked);
        }
    }
}

I have also tried working with ToastNotificationManager, but the results I get with that are identical to the results I get with Microsoft.Toolkit.Uwp.Notifications... except that ToastNotificationManager requires an AppID to work, and I've had difficulty figuring out how I'm properly supposed to create such a thing for my little Visual Studio test app.

Anyway, if you can point me in the right direction to help me achieve my goal here (preferably with a minimal, reproducible example!), it would be much appreciated!


问:
Check to see if elements in a list have an SRC from a variable and then run code - jQuery / Javascript
So I wish to check a variable called SRC against the source of images in a list from my HTML and if it returns true then run a certain function.

It seems that it is not currently running properly, please see the link for a live example.

http://jsbin.com/exigop/4/edit

答:
Attribute selectors need quotes around the attribute value.  You probably also want to check the count, not just the return value from the jQuery function:</p>

```<code>if ($('ul li img[src="' + src + '"]').length > 0) {
</code>```

Body:
Attribute selectors need quotes around the attribute value.  You probably also want to check the count, not just the return value from the jQuery function:

if ($('ul li img[src="' + src + '"]').length > 0) {


问:
How to convert UTC offset written like this "UTC+02:00" to timestamp format?
How to convert UTC offset like this for example "UTC+02:00" to timestamp format (offset written in milliseconds)? I need to read the offset written in such way in the json file and then convert it to minutes</p>

答:
You can extract the values with a regular expression

```<code>/UTC([+-]\d{2}):(\d{2})/
</code>```

and calculate the offset in milliseconds with

```<code>milliseconds = ((hours * 60 + minutes) * 60) * 1000
</code>```

Example:

const [hours, minutes] = 'UTC-05:45'.match(/UTC([+-]\d{2}):(\d{2})/).slice(1).map(Number);

const milliseconds = Math.sign(hours) * ((Math.abs(hours) * 60 + minutes) * 60) * 1000

console.log(milliseconds);```

Body:
You can extract the values with a regular expression

/UTC([+-]\d{2}):(\d{2})/

and calculate the offset in milliseconds with

milliseconds = ((hours * 60 + minutes) * 60) * 1000

Example:

const [hours, minutes] = 'UTC-05:45'.match(/UTC([+-]\d{2}):(\d{2})/).slice(1).map(Number);

const milliseconds = Math.sign(hours) * ((Math.abs(hours) * 60 + minutes) * 60) * 1000

console.log(milliseconds);


问:
What assert do in dart?
I just want to know what's the use of assert in a Dart. I was tried to figure it out by myself but I'm not able to do that. It would be great if someone explains to me the use of assert.

答: As a programmer, it is very necessary to make an errorless code, and finding errors is very difficult and time taking. Dart provides a solution in the form of assert to validate your code and to make sure the code will work fine without any error. The assert is useful in debugging and it uses a boolean condition in its syntax. If the boolean expression in assert statement is true then the code continues to execute, but if it returns false then the code ends with Assertion Error.

Title: What assert do in dart?


问:
How to return multiple ID’s from a function
I need to return ID’s of a table from a function based on input.

Create or replace function f(v_input nvarchar)
Return v_table
Is
  Select id bulk collect into v_table from table1 where user=v_input ;
  Return v_table
End;
```
<p>And this function will be called in sql queries like</p>
```Select * from table2 where id in (f(abc));
```

This is the concept.

How can we do this programmatically in oracle? How to return multiple record id’s from a function?

Body:
I need to return ID’s of a table from a function based on input.

Create or replace function f(v_input nvarchar)
Return v_table
Is
  Select id bulk collect into v_table from table1 where user=v_input ;
  Return v_table
End;

And this function will be called in sql queries like

Select * from table2 where id in (f(abc));

This is the concept.

How can we do this programmatically in oracle? How to return multiple record id’s from a function?

Body:
In Oracle 19c, version 19.7 and above you may use SQL_MACRO concept for this purpose, which is a parameterized query.

As you may see, it is merged within the main query.

create function f_get_ids(p_user in varchar2)
return varchar2
sql_macro(table)
as
begin
  return q'[select id from table1 where user_name = p_user]';
end;
/

select *
from table2
where id in (select id from f_get_ids('User 1'))

ID | DATA_
-: | :----
 1 | 001

select *
from dbms_xplan.display_cursor(format => 'TYPICAL')

| PLAN_TABLE_OUTPUT                                                             |
| :---------------------------------------------------------------------------- |
| SQL_ID  9ns9x68zjtvhy, child number 0                                         |
| -------------------------------------                                         |
| select * from table2 where id in (select id from f_get_ids('User 1'))         |
|                                                                               |
| Plan hash value: 2946371633                                                   |
|                                                                               |
| ----------------------------------------------------------------------------- |
| | Id  | Operation          | Name   | Rows  | Bytes | Cost (%CPU)| Time     | |
| ----------------------------------------------------------------------------- |
| |   0 | SELECT STATEMENT   |        |       |       |     6 (100)|          | |
| |*  1 |  HASH JOIN SEMI    |        |     1 |    17 |     6   (0)| 00:00:01 | |
| |   2 |   TABLE ACCESS FULL| TABLE2 |     4 |    28 |     3   (0)| 00:00:01 | |
| |*  3 |   TABLE ACCESS FULL| TABLE1 |     1 |    10 |     3   (0)| 00:00:01 | |
| ----------------------------------------------------------------------------- |
|                                                                               |
| Predicate Information (identified by operation id):                           |
| ---------------------------------------------------                           |
|                                                                               |
|    1 - access("ID"="ID")                                                      |
|    3 - filter("USER_NAME"='User 1')                                           |
|                                                                               |

db<>fiddle here


问:
how to fix "Method Illuminate\Database\Schema\Blueprint::class does not exist."
When I use php artisan migrate I receive this message.
Can someone help me with this?
I searched on the Internet but I didn't find anything that helped me.
(I am new in laravel)

my table:

```<code><?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateServiceTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('service', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->string('description');
            $table->string('icon');
            $table->class('class');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('service');
    }
}
</code>```

答:
I ran into the same problem. Check the naming of your columns.

for me:

$table->**name**("name") instead of the right syntax which is

$table->**string**("name")

Into context: the above was because the referral was $table->**class**("class") instead of the right syntax $table->**string**("class")

Body:
When I use php artisan migrate I receive this message.
Can someone help me with this?
I searched on the Internet but I didn't find anything that helped me.
(I am new in laravel)

my table:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateServiceTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('service', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->string('description');
            $table->string('icon');
            $table->class('class');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('service');
    }
}


问:
sessions not being set in all pages on php5
I am using session_start(); at the top of my login page. After a user logs in, a message is displayed on screen which shows that the session is being set. But, I cannot carry sessions from page to page or can I echo out SID. It is a blank value. I would be grateful if someone could show me where I am going wrong. Thanks</p>

```<code><?php

  $userpost = mysql_real_escape_string($_POST['user']);

  if (!isset($_SESSION['user'])) {
   session_start();
   $_SESSION['user'] = $userpost;
}

   echo $_SESSION['user'] .' '. 'Just logged in' .  SID;
   // Or maybe pass along the session id, if needed

?>
</code>```

答:
You have to have session_start(); on the very top of your code, after <?php. Since you are checking if the session is set without starting the sessions, your code will fail.

Is has to be like this:

```<code><?php
 session_start();
 $userpost = mysql_real_escape_string($_POST['user']);

 if (!isset($_SESSION['user'])) {
   $_SESSION['user'] = $userpost;
 }

 echo $_SESSION['user'] .' '. 'Just logged in' .  SID;
 // Or maybe pass along the session id, if needed

?>
</code>```

Body:
I am using session_start(); at the top of my login page. After a user logs in, a message is displayed on screen which shows that the session is being set. But, I cannot carry sessions from page to page or can I echo out SID. It is a blank value. I would be grateful if someone could show me where I am going wrong. Thanks

<?php

  $userpost = mysql_real_escape_string($_POST['user']);

  if (!isset($_SESSION['user'])) {
   session_start();
   $_SESSION['user'] = $userpost;
}

   echo $_SESSION['user'] .' '. 'Just logged in' .  SID;
   // Or maybe pass along the session id, if needed

?>

Body:
You have to have session_start(); on the very top of your code, after <?php. Since you are checking if the session is set without starting the sessions, your code will fail.

Is has to be like this:

<?php
 session_start();
 $userpost = mysql_real_escape_string($_POST['user']);

 if (!isset($_SESSION['user'])) {
   $_SESSION['user'] = $userpost;
 }

 echo $_SESSION['user'] .' '. 'Just logged in' .  SID;
 // Or maybe pass along the session id, if needed

?>


问:
My set of custom objects accepts duplicates (Kotlin)
I have a quick question about Sets and custom objects in Kotlin. I have a simple 3D Point class and I would like to have a set of these.

```<code>class Point3D(val x: Int, val y: Int, val z: Int){

    override fun equals(other: Any?): Boolean {
        if (other == null) return false
        if (other is Point3D && (this.x != other.x || this.y != other.y || this.z != other.z)) return false
        return true
    }

    override fun toString(): String {
        return "Point(${this.x}, ${this.y}, ${this.z})"
    }
}
</code>```

When I make a set, I can add several Points with identical coordinates. I tried to override the equality operator but that still doesn't seem to fix it.
How can I avoid duplicate objects being added to sets?

答: Thanks guys, both reimplementing hashCode() and declaring data class worked</p>

Body:
I have a quick question about Sets and custom objects in Kotlin. I have a simple 3D Point class and I would like to have a set of these.

class Point3D(val x: Int, val y: Int, val z: Int){

    override fun equals(other: Any?): Boolean {
        if (other == null) return false
        if (other is Point3D && (this.x != other.x || this.y != other.y || this.z != other.z)) return false
        return true
    }

    override fun toString(): String {
        return "Point(${this.x}, ${this.y}, ${this.z})"
    }
}

When I make a set, I can add several Points with identical coordinates. I tried to override the equality operator but that still doesn't seem to fix it.
How can I avoid duplicate objects being added to sets?


问:
How to initialize python-vlc without VLC installed on the machine (portable VLC intance)
I am currently making some kind of a program that can control PCs using a remote control, and one of the features is music playing (In the background, the player will not be visible). I know that there are other options for that in python, but the only lightweight one is playsound, which cant pause and stop the music.

All the other packages increase the executable file size dramatically, so I decided to use VLC as a downloadable extension. Now, I don't want users to install VLC, just to download portable VLC libraries and use them to get VLC playing features. Any way to use python VLC bindings with potable version of VLC? (Without installing, that's the whole point)

Thank you!

答:
This is a cheeky solution. So what you want to do is install vlc on your PC then read bytes using

```<code>with open('vlc.exe', 'rb') as fa:
    fa.read()
</code>```

You have to do this with all dependencies. Then in your existing code. Add

```<code>with open('vlc.exe', 'wb') as g:
    g.write('your existing bytes')
</code>```

Then running the script on another pc will recreate vlc but they don't have to install and internet cost will not incur. Note that wb mode creates a new file but if it exists it will override it.

Body:
This is a cheeky solution. So what you want to do is install vlc on your PC then read bytes using

with open('vlc.exe', 'rb') as fa:
    fa.read()

You have to do this with all dependencies. Then in your existing code. Add

with open('vlc.exe', 'wb') as g:
    g.write('your existing bytes')

Then running the script on another pc will recreate vlc but they don't have to install and internet cost will not incur. Note that wb mode creates a new file but if it exists it will override it.


问:
Comparing a specific string in two csv files and making third csv based on those strings
I have this csv file:

```<code>OU                                   Mailfile
CORP:Jenny Smith:                    mail/246802.nsf
"CORP:John Smith:,John Smith:"       mail/123456.nsf
STORE:Mary Poppins:                  mail/789012.nsf
STORE:Tony Stark:                    mail/345678.nsf
STORE:Carmen Sandiego:               mail/901234.nsf
NEWS:Peter Parker:                   mail/567890.nsf
NEWS:Clark Kent:                     mail/654321.nsf
STORES:store123                      mail/369121.nsf
NEWS:CORPmanager                     mail/137112.nsf
NEWS:STOREmanager                    mail/083561.nsf
</code>```

Then file2.csv:

```<code>OU
CORP
STORE
NEWS
</code>```

For every line in file2.csv that has 'CORP', 'STORE', or 'NEWS', I want to search through file1.csv and create a file, such as STOREall.csv, CORPall.csv, and NEWSall.csv.

Such as NEWSall.csv

```<code>OU                                   Mailfile

NEWS:Peter Parker:                   mail/567890.nsf
NEWS:Clark Kent:                     mail/654321.nsf
NEWS:CORPmanager                     mail/137112.nsf
NEWS:STOREmanager                    mail/083561.nsf
</code>```

But I'm getting this output instead:

In CORPall.csv

```<code>OU                                   Mailfile
CORP:Jenny Smith:                    mail/246802.nsf
CORP:John Smith:,John Smith:         mail/123456.nsf
NEWS:CORPmanager                     mail/137112.nsf
</code>```

Then NEWSall.csv

```<code>OU                                   Mailfile
NEWS:Peter Parker:                   mail/567890.nsf
NEWS:Clark Kent:                     mail/654321.nsf
</code>```

Since CORP is also in news, it appears in the CORPall.csv. I don't want that. If it says NEWS before the : then that should be in NEWSall.csv, etc.

I used this snippet that someone showed me on here:

```<code>for dept in OUList['OU']:
    df[df['OU'].str.contains(dept)]
    df_dept['OU'].to_csv(f'{dept}all.csv', index=False)
</code>```

It works great. But it only looks for what's in the whole file. So I need a way to search before the : (mind there's two in some cases)

答:
You can use str.startswith to filter the dataframe by checking if the start of each string element matches the pattern in the OUList.

for dept in OUList['OU']:
    df_dept = df[df['OU'].str.startswith(f'{dept}:')]
    df_dept.to_csv(f'{dept}all.csv', index=False)
```

Body:
I have this csv file:

OU                                   Mailfile
CORP:Jenny Smith:                    mail/246802.nsf
"CORP:John Smith:,John Smith:"       mail/123456.nsf
STORE:Mary Poppins:                  mail/789012.nsf
STORE:Tony Stark:                    mail/345678.nsf
STORE:Carmen Sandiego:               mail/901234.nsf
NEWS:Peter Parker:                   mail/567890.nsf
NEWS:Clark Kent:                     mail/654321.nsf
STORES:store123                      mail/369121.nsf
NEWS:CORPmanager                     mail/137112.nsf
NEWS:STOREmanager                    mail/083561.nsf

Then file2.csv:

OU
CORP
STORE
NEWS

For every line in file2.csv that has 'CORP', 'STORE', or 'NEWS', I want to search through file1.csv and create a file, such as STOREall.csv, CORPall.csv, and NEWSall.csv.

Such as NEWSall.csv

OU                                   Mailfile

NEWS:Peter Parker:                   mail/567890.nsf
NEWS:Clark Kent:                     mail/654321.nsf
NEWS:CORPmanager                     mail/137112.nsf
NEWS:STOREmanager                    mail/083561.nsf

But I'm getting this output instead:

In CORPall.csv

OU                                   Mailfile
CORP:Jenny Smith:                    mail/246802.nsf
CORP:John Smith:,John Smith:         mail/123456.nsf
NEWS:CORPmanager                     mail/137112.nsf

Then NEWSall.csv

OU                                   Mailfile
NEWS:Peter Parker:                   mail/567890.nsf
NEWS:Clark Kent:                     mail/654321.nsf

Since CORP is also in news, it appears in the CORPall.csv. I don't want that. If it says NEWS before the : then that should be in NEWSall.csv, etc.

I used this snippet that someone showed me on here:

for dept in OUList['OU']:
    df[df['OU'].str.contains(dept)]
    df_dept['OU'].to_csv(f'{dept}all.csv', index=False)

It works great. But it only looks for what's in the whole file. So I need a way to search before the : (mind there's two in some cases)


问:
How do I exclude all instances of a transitive dependency when using Gradle?
My gradle project uses the application plugin to build a jar file. As part of the runtime transitive dependencies, I end up pulling in org.slf4j:slf4j-log4j12. (It's referenced as a sub-transitive dependency in at least 5 or 6 other transitive dependencies - this project is using spring and hadoop, so everything but the kitchen sink is getting pulled in... no wait... that's there too :) ).

I want to globally exclude the slf4j-log4j12 jar from my built jar. So I've tried this:

```<code>configurations {
  runtime.exclude group: "org.slf4j", name: "slf4j-log4j12"
}
</code>```

However, this seems to exclude all org.slf4j artifacts including slf4j-api. When running under debug mode I see lines such as:

```<code>org.slf4j#slf4j-api is excluded from com.pivotal.gfxd:gfxd-demo-mapreduce:1.0(runtime).
org.slf4j#slf4j-simple is excluded from com.pivotal.gfxd:gfxd-demo-mapreduce:1.0(runtime).
org.slf4j#slf4j-log4j12 is excluded from org.apache.hadoop:hadoop-common:2.2.0(runtime).
</code>```

I do not want to have to look up the source of each slf4j-log4j12 transitive dependency and then have individual compile foo { exclude slf4j... } statements in my dependencies block.

Update:

I did also try this:

```<code>configurations {
  runtime.exclude name: "slf4j-log4j12"
}
</code>```

Which ends up excluding everything from the build! As though I specified group: "*".

Update 2:

I'm using Gradle version 1.10 for this.

答:
This is for Kotlin DSL (build.gradle.kts) which prevents you from using wrong properties.

Exclude the library from all configrations (implementation, runtimeOnly, etc.):

configurations.all {
    exclude(group = "ir.mahozad.android", module = "pie-chart")
    // OR exclude("ir.mahozad.android", "pie-chart")
}

// Another notation:
// configurations {
//     all {
//         exclude(group = "ir.mahozad.android", module = "pie-chart")
//     }
// }
```
<p>Exclude the library from a single configuration (like <code>implementation</code>):</p>
<pre class="lang-kotlin prettyprint-override"><code>configurations.implementation {
    exclude(group = "ir.mahozad.android", module = "pie-chart")
}

// Another notation:
// configurations {
//     implementation {
//         exclude(group = "ir.mahozad.android", module = "pie-chart")
//     }
// }
</code>```

Exclude the library for a single dependency:

dependencies {
    // ...
    implementation("ir.mahozad.android:charts:1.2.3") {
        exclude(group = "ir.mahozad.android", module = "pie-chart")
    }
}
```

Body:
My gradle project uses the application plugin to build a jar file. As part of the runtime transitive dependencies, I end up pulling in org.slf4j:slf4j-log4j12. (It's referenced as a sub-transitive dependency in at least 5 or 6 other transitive dependencies - this project is using spring and hadoop, so everything but the kitchen sink is getting pulled in... no wait... that's there too :) ).

I want to globally exclude the slf4j-log4j12 jar from my built jar. So I've tried this:

configurations {
  runtime.exclude group: "org.slf4j", name: "slf4j-log4j12"
}

However, this seems to exclude all org.slf4j artifacts including slf4j-api. When running under debug mode I see lines such as:

org.slf4j#slf4j-api is excluded from com.pivotal.gfxd:gfxd-demo-mapreduce:1.0(runtime).
org.slf4j#slf4j-simple is excluded from com.pivotal.gfxd:gfxd-demo-mapreduce:1.0(runtime).
org.slf4j#slf4j-log4j12 is excluded from org.apache.hadoop:hadoop-common:2.2.0(runtime).

I do not want to have to look up the source of each slf4j-log4j12 transitive dependency and then have individual compile foo { exclude slf4j... } statements in my dependencies block.

Update:

I did also try this:

configurations {
  runtime.exclude name: "slf4j-log4j12"
}

Which ends up excluding everything from the build! As though I specified group: "*".

Update 2:

I'm using Gradle version 1.10 for this.

Body:
This is for Kotlin DSL (build.gradle.kts) which prevents you from using wrong properties.

Exclude the library from all configrations (implementation, runtimeOnly, etc.):

configurations.all {
    exclude(group = "ir.mahozad.android", module = "pie-chart")
    // OR exclude("ir.mahozad.android", "pie-chart")
}

// Another notation:
// configurations {
//     all {
//         exclude(group = "ir.mahozad.android", module = "pie-chart")
//     }
// }

Exclude the library from a single configuration (like implementation):

configurations.implementation {
    exclude(group = "ir.mahozad.android", module = "pie-chart")
}

// Another notation:
// configurations {
//     implementation {
//         exclude(group = "ir.mahozad.android", module = "pie-chart")
//     }
// }

Exclude the library for a single dependency:

dependencies {
    // ...
    implementation("ir.mahozad.android:charts:1.2.3") {
        exclude(group = "ir.mahozad.android", module = "pie-chart")
    }
}


问:
How to add a string in an array which is in an object which is in a state array
Now siizeVariant is a string Array and I want to add Strings to it with an onClick event. findIndex works fine. It's just the concat section. I guess it's wrong to use it there but I have no idea what to do else :/

const [selectedP, setSelectedP] = useState([
    {
      name: "Uomo - Valentino",
      productId: "H114",
      sizeVariants: []
    },
    {
      name: "Uomo - Valentino",
      productId: "H243",
      sizeVariants: []
    }
  ])

setSelectedP((prev as any[]) => {
      const index = selectedP.findIndex((sP: any) => sP.productId === productId);

      return [
        ...prev.slice(0, index),
        {
          ...prev[index],
          sizeVariants: prev.sizeVariants.concat(string),
        },
        ...prev.slice(index + 1),
      ];
    })
  }
```

This is the error I get:
prev.sizeVariant is undefined

答:
in place of using findIndex and slice method, use array.map for updating the array.
And instead of using any type define a type and use it.</p>
```<code>type product = {
    productId: number;
    sizeVariants: string[];
}
setSelecteP((prev: product[]) => prev.map(obj => {
    if (obj.productId === productId) {
        return {
            ...obj,
            sizeVariants: obj.sizeVariants.concat(newSizeVariant),
        };
    };
    return obj;
}))
</code>```

Body:
Now siizeVariant is a string Array and I want to add Strings to it with an onClick event. findIndex works fine. It's just the concat section. I guess it's wrong to use it there but I have no idea what to do else :/

const [selectedP, setSelectedP] = useState([
    {
      name: "Uomo - Valentino",
      productId: "H114",
      sizeVariants: []
    },
    {
      name: "Uomo - Valentino",
      productId: "H243",
      sizeVariants: []
    }
  ])

setSelectedP((prev as any[]) => {
      const index = selectedP.findIndex((sP: any) => sP.productId === productId);

      return [
        ...prev.slice(0, index),
        {
          ...prev[index],
          sizeVariants: prev.sizeVariants.concat(string),
        },
        ...prev.slice(index + 1),
      ];
    })
  }

This is the error I get:
prev.sizeVariant is undefined

Body:
in place of using findIndex and slice method, use array.map for updating the array.
And instead of using any type define a type and use it.

type product = {
    productId: number;
    sizeVariants: string[];
}
setSelecteP((prev: product[]) => prev.map(obj => {
    if (obj.productId === productId) {
        return {
            ...obj,
            sizeVariants: obj.sizeVariants.concat(newSizeVariant),
        };
    };
    return obj;
}))


问:
Android 11 su get global access with inherited namespace
I have a root app that should change some files in another app. My phone is rooted (Samsung Galaxy S21+ 5G) and I use the following code to execute a ls as test, but I only get the own app directory as long as I have set Mount Namespace Mode to "inherit the requester's namespace". I only see all directories with Global Namespace. The thing I'm not understanding is why I can see all apps using Termux app (su; ls /data/user/0/) even with inherit namespace.

Is there a way to make it work with default namespace setting in Magisk (inherit namespace)?

```<code>Process p = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(p.getOutputStream());
os.writeBytes("ls /data/user/0/\n");
os.writeBytes("exit\n");
os.flush();
os.close();
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
while (true) {
  int read = reader.read(buffer);
  int read2 = read;
  if (read <= 0) {
      System.out.println(output.toString());
  }
  output.append(buffer, 0, read2);
}
</code>```

答:
If you are using magisk su, there is a parameter:

--mount-master                force run in the global mount namespace

So you change change the command to su --mount-master

Body:
I have a root app that should change some files in another app. My phone is rooted (Samsung Galaxy S21+ 5G) and I use the following code to execute a ls as test, but I only get the own app directory as long as I have set Mount Namespace Mode to "inherit the requester's namespace". I only see all directories with Global Namespace. The thing I'm not understanding is why I can see all apps using Termux app (su; ls /data/user/0/) even with inherit namespace.

Is there a way to make it work with default namespace setting in Magisk (inherit namespace)?

Process p = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(p.getOutputStream());
os.writeBytes("ls /data/user/0/\n");
os.writeBytes("exit\n");
os.flush();
os.close();
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
while (true) {
  int read = reader.read(buffer);
  int read2 = read;
  if (read <= 0) {
      System.out.println(output.toString());
  }
  output.append(buffer, 0, read2);
}