问:
Now able to load html page in web view when trying to load it from internal storage of device
I have created an index.html inside a directory, named as "TestingPurpose", of my internal storage of device.

I was trying to load the html page which is inside internal storage of device, but not able to load it

```<code>String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/TestingPurpose/index.html";
webView.loadUrl(path);
</code>```

But working if I try to load from assets directory

```<code>String path = "file:///android_asset/index.html";
webView.loadUrl(path);
</code>```

How I can make the URL load in web view from the file which is inside the internal storage of device?

答:
Try this:</p>
```<code>String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/TestingPurpose/index.html";
String url = "file://" + path;
webView.loadUrl(url);
</code>```

Body:
I have created an index.html inside a directory, named as "TestingPurpose", of my internal storage of device.

I was trying to load the html page which is inside internal storage of device, but not able to load it

String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/TestingPurpose/index.html";
webView.loadUrl(path);

But working if I try to load from assets directory

String path = "file:///android_asset/index.html";
webView.loadUrl(path);

How I can make the URL load in web view from the file which is inside the internal storage of device?

Body:
Try this:

String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/TestingPurpose/index.html";
String url = "file://" + path;
webView.loadUrl(url);


来源: stackexchange

问:
Spring with Redis: cache manager, resolver and key generator
Spring provides a caching abstraction package spring-boot-starter-cache which basically provides method level annotations to cache data with @Cacheable, @Cacheput and other annotations. I feel there are limitations to this: Caching a collection of POJO against a property (for example: Person.getId() as the key from List<Person> as a return type). And the other limitation is searching. How do I query and search data in the cache provider?

I'm assuming I'd need to use CacheManager, CacheResolver and KeyGenerator along with RedisCacheManager to cache a collection of objects and also to lookup caches. So far the documentation hasn't been helpful at all. And most of the articles don't even touch up on these items. Can someone please explain how to use these or direct me towards some documentation.

答:
The core Spring Framework's Cache Abstraction is much more than a collection of annotations for caching, and specifically, Look-Aside, or Cache-Aside, caching as it's commonly referred. The Cache-Aside pattern is the pattern of caching on which Spring's Cache Abstraction is based.

Spring's Cache Abstraction is a general purpose caching framework (and facade) with an API allowing users to plugin different "caching provider" implementations (e.g. Redis, or Apache Geode using the following bits). For all intents and purposes, it is a proper Service Provider Interface (SPI) with implementations adhering to the interfaces defined by the SPI.

The 2 main interfaces in Spring's Cache Abstraction include the CacheManager and Cache.

These are the primary interfaces and APIs that must be implemented when adding support for a new caching provider that can be used to apply caching to Spring managed application services (components, or beans declared in the Spring container). Under-the-hood, Spring's Cache Abstraction is implemented with Spring AOP.

You can either use the APIs from the CacheManager and Cache interfaces directly in your Spring managed application components (beans), or you can more commonly use the caching annotations (e.g. @Cacheable), which are less invasive, and easier to disable, if applicable (e.g. simply remove the @EnableCaching annotation, or in Spring Boot's case, set the spring.cache.type property to none; see here).

The Cache interface (Javadoc) only provides basic and essential data access operations (e.g. querying) that are relevant for caching. It does not provide "low-level" data access operations that are possibly provided by the underlying caching provider (e.g. Redis).

This is primarily due to the fact that not all caching providers are equal. Some caching providers far exceed others in terms of functionality and capabilities, functionality and capabilities that fall outside of the "general concern of caching". In fact, things like querying or distributed compute, replication, eviction/expiration policies (hence this), consistency guarantees, etc, all vary from 1 caching provider to the next.  The caching provider is often chosen based on your application use case and requirements.

However, Spring does not prevent you from getting access to the low-level functionality if you need it, even from the Cache Abstraction.

For instance, the Cache.getNativeCache() method returns the underlying implementation of the Cache interface for your caching provider implementation.  In Spring for Apache Geode, that is a cache Region.  In Spring for Redis, that is a HASH, I believe (?).

Regarding the "limitations", as you say, for example, "Caching a collection of POJO...", this is not entirely true.

Indeed Spring's Cache Abstraction is intentionally and deliberately designed for general purpose caching, which involves "lookup", not querying or handling complex object hierarchies, or even arrays/collections of objects.

While Spring does not handle these type of concerns out of the box, it does not mean they are not possible. Spring is designed to the Open/Closed principle, being "closed" for modification, but "open" to extension.

It is possible to extend Spring's Cache Abstraction to, for example, cache the individual elements in an array or Collection (e.g. List) returned by a @Cacheable service method.

See my answer (2nd, or bottom one) to this StackOverflow question. Specifically, see this SO post.

The thing is, while Spring may not have an immediate answer out-of-the-box, there is usually always an answer, but might involve a bit of work (code).

If you understand the underlying design principles, then you can begin to plugin and customize all aspects of the caching behavior as needed, such as how Caches are resolved (from a provider), key generation, or conditional caching. Spring provides "default" behavior (for example), but nearly every aspect can be customized in some way.

Still, somethings will be very provider specific (like "Expiration") and so you are not completely void from having to understand your underlying provider.  No technology can completely shield from having to understand the underlying infrastructure, for example not even JPA for databases, especially when you need to create indexes.

Hope this makes sense.

ContentLicense: CC BY-SA 4.0


问:
How to customize React native track player notification bar
I am using react-native-track-player to create a music app. Can I customize the notification area, and lock screen player?

What I need to do is changing the background color and add custom theming to the notification area and lock screen play options. Can someone please let me know how to do it please?

Following is the code I have used to enable track player options. How can I modified it to do above tasks? Or is there any other method to perform customization. Thank you so much.

const setUpTrackPlayer = async () => {
  try {
    await TrackPlayer.setupPlayer();
    await TrackPlayer.add(audioClipsArray);
    await TrackPlayer.updateOptions({
      stopWithApp: true,
      capabilities: [
        Capability.Play,
        Capability.Pause,
        Capability.SkipToNext,
        Capability.SkipToPrevious,
        Capability.Stop,
      ],
      compactCapabilities: [
        Capability.Play,
        Capability.Pause,
        Capability.SkipToNext,
        Capability.SkipToPrevious,
      ],
      notificationCapabilities: [
        Capability.Play,
        Capability.Pause,
        Capability.SkipToNext,
        Capability.SkipToPrevious,
      ],
    });
  } catch (e) {
    console.log(e);
  }
};```

答: You cannot do it from javascript at least for now, because this module is not providing any methods to customize that. To do that you need to change native files in order to get make it customized. You can also take a look at https://github.com/invertase/notifee and see if you can make it work together with track player.</p>


问:
Determine how similar two arrays are in PostgreSQL
I'm aware you can compare two arrays in PostgreSQL to see if the elements in one are contained in the elements of another like so,

```<code>SELECT ARRAY[1,2] <@ ARRAY[1,2,3] --> true
</code>```

Is there any way to get # of matches or say "if matches 2 of 3" ??

```<code>SELECT ARRAY[1,2] ?? ARRAY[1,2,3] --> 2/3 or 66.6666%
</code>```

I'm open to interesting solutions.. I want to take an array and ultimately say it must match 2 of 3 elements from another array in an inline query.. or >= 66% or something of that nature.

Ideally like this..

```<code>SELECT * FROM SOMETABLE WHERE ARRAY[1,2] ?? ARRAY[1,2,3] >= 66.66666666666667
</code>```

Thanks in advance.

答:
You could create a function for that:</p>
```<code>CREATE FUNCTION array_similarity(anyarray, anyarray)
   RETURNS double precision
   LANGUAGE sql
   IMMUTABLE STRICT AS
$$SELECT 100.0 * count(*) / cardinality($2)
FROM unnest($1) AS a1(e1)
WHERE ARRAY[e1] <@ $2$$;
</code>```

Body:
I'm aware you can compare two arrays in PostgreSQL to see if the elements in one are contained in the elements of another like so,

SELECT ARRAY[1,2] <@ ARRAY[1,2,3] --> true

Is there any way to get # of matches or say "if matches 2 of 3" ??

SELECT ARRAY[1,2] ?? ARRAY[1,2,3] --> 2/3 or 66.6666%

I'm open to interesting solutions.. I want to take an array and ultimately say it must match 2 of 3 elements from another array in an inline query.. or >= 66% or something of that nature.

Ideally like this..

SELECT * FROM SOMETABLE WHERE ARRAY[1,2] ?? ARRAY[1,2,3] >= 66.66666666666667

Thanks in advance.

Body:
You could create a function for that:

CREATE FUNCTION array_similarity(anyarray, anyarray)
   RETURNS double precision
   LANGUAGE sql
   IMMUTABLE STRICT AS
$$SELECT 100.0 * count(*) / cardinality($2)
FROM unnest($1) AS a1(e1)
WHERE ARRAY[e1] <@ $2$$;


问:
GOLANG bufio Scanner handling 10000 characters
I want to input 10000 length of string from os.stdin
but bufio.NewScanner can only read 4096 of characters
How can I read more than 4096 characters?

Here is my code

```<code>package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    sc := bufio.NewScanner(os.Stdin)
    buf := make([]byte, 2048*2048)
    sc.Buffer(buf, 2048*2048)

    sc.Scan()
    s := sc.Bytes()
    fmt.Println(len(s)) // 9998; must be 10000

    str := make([]byte, len(s) + 1)
    for i := 1; i < len(s) + 1; i++ {
        str[i] = s[i-1]
    }
}
</code>```

if I input 10000 characters

panic: runtime error: index out of range [9998] with length 9998

答:
Just a hunch, but I suspect that the missing two characters are the CR+LF pair used by windows as a line terminator.

This works for me. I'm using a text file ("pp1.txt") that contains the text of Jane Austin's Pride and Prejudice broken up into 10,000-character lines — making each line (on my MacOS system) actually 10,001 characters (10,000 characters of text, followed by a LF line delimiter). It reads the entire line, discarding the line terminator and giving me 10,000 characters.

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {

    file, err := os.Open("./pp1.txt")
    if err != nil {
        panic(err)
    }

    one_megabyte := 1024 * 1024
    buf := make([]byte, one_megabyte)
    sc := bufio.NewScanner(file)

    sc.Buffer(buf, one_megabyte)

    sc.Scan()
    s := sc.Bytes()
    fmt.Println(len(s)) // 9998; must be 10000

    str := make([]byte, len(s)+1)
    for i := 1; i < len(s)+1; i++ {
        str[i] = s[i-1]
    }

}
```
<p>I'm a little confused by this, though:</p>
<blockquote>
```str := make([]byte, len(s)+1)
for i := 1; i < len(s)+1; i++ {
  str[i] = s[i-1]
}
```

If you trying to convert the bytes from the scanner into a string, why wouldn't you just use sc.Text() instead of sc.Bytes().

Body:
I want to input 10000 length of string from os.stdin
but bufio.NewScanner can only read 4096 of characters
How can I read more than 4096 characters?

Here is my code

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    sc := bufio.NewScanner(os.Stdin)
    buf := make([]byte, 2048*2048)
    sc.Buffer(buf, 2048*2048)

    sc.Scan()
    s := sc.Bytes()
    fmt.Println(len(s)) // 9998; must be 10000

    str := make([]byte, len(s) + 1)
    for i := 1; i < len(s) + 1; i++ {
        str[i] = s[i-1]
    }
}

if I input 10000 characters

panic: runtime error: index out of range [9998] with length 9998

Body:
Just a hunch, but I suspect that the missing two characters are the CR+LF pair used by windows as a line terminator.

This works for me. I'm using a text file ("pp1.txt") that contains the text of Jane Austin's Pride and Prejudice broken up into 10,000-character lines — making each line (on my MacOS system) actually 10,001 characters (10,000 characters of text, followed by a LF line delimiter). It reads the entire line, discarding the line terminator and giving me 10,000 characters.

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {

    file, err := os.Open("./pp1.txt")
    if err != nil {
        panic(err)
    }

    one_megabyte := 1024 * 1024
    buf := make([]byte, one_megabyte)
    sc := bufio.NewScanner(file)

    sc.Buffer(buf, one_megabyte)

    sc.Scan()
    s := sc.Bytes()
    fmt.Println(len(s)) // 9998; must be 10000

    str := make([]byte, len(s)+1)
    for i := 1; i < len(s)+1; i++ {
        str[i] = s[i-1]
    }

}

I'm a little confused by this, though:

str := make([]byte, len(s)+1)
for i := 1; i < len(s)+1; i++ {
  str[i] = s[i-1]
}

If you trying to convert the bytes from the scanner into a string, why wouldn't you just use sc.Text() instead of sc.Bytes().


问:
How to scale up Kubernetes cluster with Terraform avoiding downtime?
Here's the scenario: we have some applications running on a Kubernetes cluster on Azure. Currently our production cluster has one Nodepool with 3 nodes which are fairly low on resources because we still don't have that many active users/requests simultaneously.

Our backend APIs app is running on three pods, one on each node. I was told I will have need to increase resources soon (I'm thinking more memory or even replacing the VMs of the nodes with better ones).

We structured everything Kubernetes related using Terraform and I know that replacing VMs in a node is a destructive action, meaning the cluster will have to be replaces, new config and all deployments, services and etc will have to be reapplied.

I am fairly new to the Kubernetes and Terraform world, meaning I can do the basics to get an application up and running but I would like to learn what is the best practice when it comes to scaling and performance. How can I perform such increase in resources without having any downtime of our services?

I'm wondering if having an extra Nodepool would help while I replace the VM's of the other one (I might be absolutely wrong here)

If there's any link, course, tutorial you can point me to it's highly appreciated.

答:
(Moved from comments)

In Azure, when you're performing cluster upgrade, there's a parameter called "max surge count" which is equal to 1 by default. What it means is when you update your cluster or node configuration, it will first create one extra node with the updated configuration - and only then it will safely drain and remove one of old ones. More on this here: Azure - Node Surge Upgrade


问:
Indy 9 to Indy 10 App: Connection refused
I'm porting and old Delphi 2009 app with Indy 9 to Delphi 11 with Indy 10:

```<code>// *************** Indy Version 9:
IdTCPClient1.Host := '123.456.789.012';
IdTCPClient1.Port := 123;
IdTCPClient1.Connect;
IdTCPClient1.OpenWriteBuffer;
IdTCPClient1.Write(Data);
i :=  IdTCPClient1.ReadInteger(True);
x := IdTCPClient1.ReadLn('</root>', 20000, 1500);
// Works OK

// *************** Indy Version 10
XMLStream := TMemoryStream.Create;
XMLDoc1.XML.SaveToStream(XMLStream);
IdTCPClient1.Host := '123.456.789.012';
IdTCPClient1.Port := 123;
IdTCPClient1.Connect;
IdTCPClient1.Socket.Open;
IdTCPClient1.Socket.WriteBufferOpen;
IdTCPClient1.Socket.Write(XMLStream, XMLStream.Size);
i := IdTCPClient1.Socket.ReadInt32(True);
x := IdTCPClient1.Socket.ReadLn('</root>', 20000, 1500);
// Socket Error # 10061 Connection refused.
</code>```

Both versions are executing in the same PC/User...
Any help will be appreciated.
Francisco

```<code>    //Still receiving Socket Error # 10061: Connection Refused
    IdTCPClient1.Host := '123.456.789.0';
    IdTCPClient1.Port := 55065;
    IdTCPClient1.Connect;
    IdTCPClient1.Socket.WriteBufferOpen;
    IdTCPClient1.Socket.Write(XMLStream, XMLStream.Size);
    i := IdTCPClient1.Socket.ReadInt32(True);
    sResp := IdTCPClient1.Socket.ReadLn('</root>', 20000, 1500);
    IdTCPClient1.Socket.WriteBufferFlush;
    IdTCPClient1.Socket.Close;
    IdTCPClient1.Disconnect;
    // I omitted some code like try, except
</code>```

答:
Your translation to Indy 10 is not quite correct.  You should not be calling Socket.Open() at all, as Connect() already handles that internally, and that Open() call is what actually creates the socket and establishes the TCP connection.  So, you are trying to open a 2nd connection, which won't work.  Get rid of that call completely:

IdTCPClient1.Connect;
// IdTCPClient1.Socket.Open; // <-- get rid of this!
```
<p>Also, in both of your codes, you are opening Indy's internal write buffer, but where are you flushing/closing it? As long as the buffer is open, any writes you perform will store their bytes in the buffer only and not transmit them over the socket (unless you assign a buffer threshold value, which your example is not).</p>
<pre class="lang-pascal prettyprint-override"><code>// *************** Indy Version 9
IdTCPClient1.Connect;
IdTCPClient1.OpenWriteBuffer;
IdTCPClient1.Write(Data);
...
// where is the call to (Flush/Close/Cancel)WriteBuffer?
</code>```

// *************** Indy Version 10
IdTCPClient1.Connect;
IdTCPClient1.Socket.WriteBufferOpen;
IdTCPClient1.Socket.Write(XMLStream, XMLStream.Size);
...
// where is the call to WriteBuffer(Flush/Close/Cancel)?
```

In general, you don't need to use Indy's write buffer unless you are sending LOTS of data and would benefit from the performance boost that the buffering might offer you.  TCP already does a decent job of buffering data in the socket's own internal buffer by default, so you typically don't need to use Indy's write buffering on top of that, too.

Body:
I'm porting and old Delphi 2009 app with Indy 9 to Delphi 11 with Indy 10:

// *************** Indy Version 9:
IdTCPClient1.Host := '123.456.789.012';
IdTCPClient1.Port := 123;
IdTCPClient1.Connect;
IdTCPClient1.OpenWriteBuffer;
IdTCPClient1.Write(Data);
i :=  IdTCPClient1.ReadInteger(True);
x := IdTCPClient1.ReadLn('</root>', 20000, 1500);
// Works OK

// *************** Indy Version 10
XMLStream := TMemoryStream.Create;
XMLDoc1.XML.SaveToStream(XMLStream);
IdTCPClient1.Host := '123.456.789.012';
IdTCPClient1.Port := 123;
IdTCPClient1.Connect;
IdTCPClient1.Socket.Open;
IdTCPClient1.Socket.WriteBufferOpen;
IdTCPClient1.Socket.Write(XMLStream, XMLStream.Size);
i := IdTCPClient1.Socket.ReadInt32(True);
x := IdTCPClient1.Socket.ReadLn('</root>', 20000, 1500);
// Socket Error # 10061 Connection refused.

Both versions are executing in the same PC/User...
Any help will be appreciated.
Francisco

    //Still receiving Socket Error # 10061: Connection Refused
    IdTCPClient1.Host := '123.456.789.0';
    IdTCPClient1.Port := 55065;
    IdTCPClient1.Connect;
    IdTCPClient1.Socket.WriteBufferOpen;
    IdTCPClient1.Socket.Write(XMLStream, XMLStream.Size);
    i := IdTCPClient1.Socket.ReadInt32(True);
    sResp := IdTCPClient1.Socket.ReadLn('</root>', 20000, 1500);
    IdTCPClient1.Socket.WriteBufferFlush;
    IdTCPClient1.Socket.Close;
    IdTCPClient1.Disconnect;
    // I omitted some code like try, except

Body:
Your translation to Indy 10 is not quite correct.  You should not be calling Socket.Open() at all, as Connect() already handles that internally, and that Open() call is what actually creates the socket and establishes the TCP connection.  So, you are trying to open a 2nd connection, which won't work.  Get rid of that call completely:

IdTCPClient1.Connect;
// IdTCPClient1.Socket.Open; // <-- get rid of this!

Also, in both of your codes, you are opening Indy's internal write buffer, but where are you flushing/closing it? As long as the buffer is open, any writes you perform will store their bytes in the buffer only and not transmit them over the socket (unless you assign a buffer threshold value, which your example is not).

// *************** Indy Version 9
IdTCPClient1.Connect;
IdTCPClient1.OpenWriteBuffer;
IdTCPClient1.Write(Data);
...
// where is the call to (Flush/Close/Cancel)WriteBuffer?

// *************** Indy Version 10
IdTCPClient1.Connect;
IdTCPClient1.Socket.WriteBufferOpen;
IdTCPClient1.Socket.Write(XMLStream, XMLStream.Size);
...
// where is the call to WriteBuffer(Flush/Close/Cancel)?

In general, you don't need to use Indy's write buffer unless you are sending LOTS of data and would benefit from the performance boost that the buffering might offer you.  TCP already does a decent job of buffering data in the socket's own internal buffer by default, so you typically don't need to use Indy's write buffering on top of that, too.


问:
.gitignore negation not working
I'm using msysgit 1.9.4.

My .gitignore file, at the root of the repo, looks like this:

```<code>build/
a/b/
!a/c/d/e/**/build/
</code>```

My intent is that, all build/ directories are ignored, unless they are subdirs (any depth) of a/c/d/e/.
But a/c/d/e/f/build/ is still getting ignored by Git.

What am I missing here?

答:
The general rule of gitignore is simple:

It is not possible to re-include a file if a parent directory of that file is excluded.

To exclude files (or all files) from a subfolder of an ignored folder build, you need to exclude the folder first, then the files:

I have tested:

```<code>**/build/
a/b/
!a/c/d/e/**/build/     <== whitelist folder first
!a/c/d/e/**/build/**   <== then the files
</code>```

ContentLicense: CC BY-SA 3.0

Title: .gitignore negation not working

Body:
I'm using msysgit 1.9.4.

My .gitignore file, at the root of the repo, looks like this:

build/
a/b/
!a/c/d/e/**/build/

My intent is that, all build/ directories are ignored, unless they are subdirs (any depth) of a/c/d/e/.
But a/c/d/e/f/build/ is still getting ignored by Git.

What am I missing here?

Body:
The general rule of gitignore is simple:

It is not possible to re-include a file if a parent directory of that file is excluded.

To exclude files (or all files) from a subfolder of an ignored folder build, you need to exclude the folder first, then the files:

I have tested:

**/build/
a/b/
!a/c/d/e/**/build/     <== whitelist folder first
!a/c/d/e/**/build/**   <== then the files


问:
ExtJS Controllers Interraction
apologies if it's not termed correctly, development isn't my first language :)

I'm trying to add functionality to an extjs web application called Traccar (a web based tracking platform).

For anyone familiar with the application, what I'm trying to do is add a "quick report" button to the devices section, so that you can click a device, click the button and it will expand the reports section and pre-select the report type as trips, device as the selected device and click show.

From a technical perspective, I've achived some of this. I believe that there are two view controllers that I need to be concerned about  - "DevicesController.js" (https://github.com/traccar/traccar-web/blob/9e1c0b44189136ec6abf05720c698027a689fa08/web/app/view/edit/DevicesController.js) and "ReportsController.js" (https://github.com/traccar/traccar-web/blob/9e1c0b44189136ec6abf05720c698027a689fa08/web/app/view/ReportController.js)

I've worked out how to expand the reports section at the bottom of the screen (that was fairly easy):

onQuickReportClick: function() {

  Ext.getCmp('reportViewPanel').expand(true);

},```
</div>
</div>
</p>
<p>I've been trying to call across to the reports controller to interact with it, but I can't seem to get my head round how to do it (if you even can)
I've been trying things like -
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>    var reportController = Traccar.app.getController("Traccar.view.ReportController");
    reportController.test();</code>```

But, I get an error like this

```<code>```    Uncaught TypeError: controller.doInit is not a function
```    at constructor.getController (ext-all-debug.js:95199:28)
```    at constructor.onQuickReportClick (DevicesController.js:109:38)
```    at Object.callback (ext-all-debug.js:8705:32)
```    at constructor.fireHandler (ext-all-debug.js:144259:17)
```    at constructor.onClick (ext-all-debug.js:144241:16)
```    at constructor.fire (ext-all-debug.js:20731:42)
```    at constructor.fire (ext-all-debug.js:34336:27)
```    at constructor.publish (ext-all-debug.js:34296:28)
```    at constructor.publishDelegatedDomEvent (ext-all-debug.js:34318:14)
```    at constructor.doDelegatedEvent (ext-all-debug.js:34361:16)
```
<p>The test method is very simple at the moment, just to prove I'm getting there -
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>test: function () {
    showToast("test - succsfully in report controller", "test");
},</code>```

Any pointers / guidance / advice would be greatly appreciated

答:
Advice

It is a NoGo to call a controller from another controller.

The controller is a viewController, created when the view is created to react to userinput from that view. Worstcase: the other view does not exist and therefore the viewController has not been created.

If you really have to

You want to follow Peters comment and  run:

```<code>Ext.first('reportView').getController()
// or faster and prefered
// add an id to the view => reportViewId
Ext.getCmp('reportViewId').getController()
</code>```

Way better

Make use of Events or setup your own Eventbus

Setup EventBus

after your app started call

```<code>Traccar.Bus = new Ext.util.Observable();
</code>```

With that in place you can fire an event in one viewController:

```<code>/**
 * @param {string} eventName
 * @param {object} args
 */
Traccar.Bus.fireEvent(eventName, args);
</code>```

In the receiving viewController you previously set a listener

```<code>onOtherViewControllerFire: function(args) {...}
init: function() {
    Traccar.Bus.on(eventName, this.onOtherViewControllerFire);
}
</code>```

Title: ExtJS Controllers Interraction

Body:
apologies if it's not termed correctly, development isn't my first language :)

I'm trying to add functionality to an extjs web application called Traccar (a web based tracking platform).

For anyone familiar with the application, what I'm trying to do is add a "quick report" button to the devices section, so that you can click a device, click the button and it will expand the reports section and pre-select the report type as trips, device as the selected device and click show.

From a technical perspective, I've achived some of this. I believe that there are two view controllers that I need to be concerned about  - "DevicesController.js" (https://github.com/traccar/traccar-web/blob/9e1c0b44189136ec6abf05720c698027a689fa08/web/app/view/edit/DevicesController.js) and "ReportsController.js" (https://github.com/traccar/traccar-web/blob/9e1c0b44189136ec6abf05720c698027a689fa08/web/app/view/ReportController.js)

I've worked out how to expand the reports section at the bottom of the screen (that was fairly easy):

onQuickReportClick: function() {

  Ext.getCmp('reportViewPanel').expand(true);

},

I've been trying to call across to the reports controller to interact with it, but I can't seem to get my head round how to do it (if you even can)
I've been trying things like -

    var reportController = Traccar.app.getController("Traccar.view.ReportController");
    reportController.test();

But, I get an error like this

```    Uncaught TypeError: controller.doInit is not a function
```    at constructor.getController (ext-all-debug.js:95199:28)
```    at constructor.onQuickReportClick (DevicesController.js:109:38)
```    at Object.callback (ext-all-debug.js:8705:32)
```    at constructor.fireHandler (ext-all-debug.js:144259:17)
```    at constructor.onClick (ext-all-debug.js:144241:16)
```    at constructor.fire (ext-all-debug.js:20731:42)
```    at constructor.fire (ext-all-debug.js:34336:27)
```    at constructor.publish (ext-all-debug.js:34296:28)
```    at constructor.publishDelegatedDomEvent (ext-all-debug.js:34318:14)
```    at constructor.doDelegatedEvent (ext-all-debug.js:34361:16)

The test method is very simple at the moment, just to prove I'm getting there -

test: function () {
    showToast("test - succsfully in report controller", "test");
},

Any pointers / guidance / advice would be greatly appreciated

Body:
Advice

It is a NoGo to call a controller from another controller.

The controller is a viewController, created when the view is created to react to userinput from that view. Worstcase: the other view does not exist and therefore the viewController has not been created.

If you really have to

You want to follow Peters comment and  run:

Ext.first('reportView').getController()
// or faster and prefered
// add an id to the view => reportViewId
Ext.getCmp('reportViewId').getController()

Way better

Make use of Events or setup your own Eventbus

Setup EventBus

after your app started call

Traccar.Bus = new Ext.util.Observable();

With that in place you can fire an event in one viewController:

/**
 * @param {string} eventName
 * @param {object} args
 */
Traccar.Bus.fireEvent(eventName, args);

In the receiving viewController you previously set a listener

onOtherViewControllerFire: function(args) {...}
init: function() {
    Traccar.Bus.on(eventName, this.onOtherViewControllerFire);
}


问:
How to disable auto-detected JPA in Quarkus?
I'm building a quarkus project with 3 modules: api (jax-rs), web (vaadin) and model (shared). The model module contains entity classes annotated with JPA @Entity.

The api module can compile and use the classes sucessfully, however, the web module fails to start as it can't find the default datasource:

```<code>Model classes are defined for the default persistence unit, but no default datasource was found.
</code>```

How can a web application use the shared entity class definition, for example in rest client, wihtout triggering JPA detection by Quarkus (just ignore the annotations and use it as a plain object)?

答: You don't want @Entity to be picked up ? don't add Hibernate/JPA extension to the project would be the easiest.</p>

Body:
I'm building a quarkus project with 3 modules: api (jax-rs), web (vaadin) and model (shared). The model module contains entity classes annotated with JPA @Entity.

The api module can compile and use the classes sucessfully, however, the web module fails to start as it can't find the default datasource:

Model classes are defined for the default persistence unit, but no default datasource was found.

How can a web application use the shared entity class definition, for example in rest client, wihtout triggering JPA detection by Quarkus (just ignore the annotations and use it as a plain object)?


问:
Why are my nfs4 mounts not working with ansible?
With Ansible, I cannot mount nfs4.

I have nfs4 exports configured on the server, and I can mount both nfs4 and nfs using a bash shell.

I can also get nfs to work in ansible, just not nfs4.

so I'm wondering how I can mount a share like /pool1/volume1 on the server to the same style path on the client-
/pool1/volume1

tried switching to standard nfs which worked, and I can mount nfs4 in a bash shell, but not with ansible

This works-

```<code>  - name: mount softnas NFS volume
    become: yes
    mount:
      fstype: nfs
      path: "/pool1/volume1"
      opts: rsize=8192,wsize=8192,timeo=14,intr,_netdev
      src: "10.0.11.11:/pool1/volume1"
      state: mounted
</code>```

But this doesn't

```<code>  - name: mount softnas NFS volume
    become: yes
    mount:
      fstype: nfs4
      path: "/pool1/volume1"
      opts: rsize=8192,wsize=8192,timeo=14,intr,_netdev
      src: "10.0.11.11:/pool1/volume1"
      state: mounted
</code>```

and if i use this command from a shell, this works fine in mounting the paths into test.
sudo mount -t nfs4 10.0.11.11:/ /test
although its not quite right, because id like /pool1/volume1 and /pool2/volume2 to not appear under /test

my exports file on the server is this-

```<code>/ *(ro,fsid=0)
# These mounts are managed in ansible playbook softnas-ebs-disk-update-exports.yaml
# BEGIN ANSIBLE MANAGED BLOCK /pool1/volume1/
/pool1/volume1/ *(async,insecure,no_subtree_check,no_root_squash,rw,nohide)
# END ANSIBLE MANAGED BLOCK /pool1/volume1/
# BEGIN ANSIBLE MANAGED BLOCK /pool2/volume2/
/pool2/volume2/ *(async,insecure,no_subtree_check,no_root_squash,rw,nohide)
# END ANSIBLE MANAGED BLOCK /pool2/volume2/
</code>```

when I try to switch to nfs4, i get this error with ansible

Error mounting /pool1/volume1/: mount.nfs4: mounting 10.0.11.11:/pool1/volume1/ failed, reason given by server: No such file or directory

答:
Came across this same issue, using Ansible 2.11.5 the above answer didn't work for me.  Ansible was complaining about the fstype "nfs4" and quoting was needed for the "opts" equal signs.  Here is what I used:

```<code>- name: mount AWS EFS Volume
  mount:
    fstype: nfs
    path: "/mnt/efs"
    opts: "nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport"
    src: "{{ efs_share_address[env] }}:/"
    state: mounted
</code>```

From the roles var file:

```<code>efs_share_address:
  qa: 10.2.2.2
  stage: 10.3.3.3
  production: 10.4.4.4
</code>```

Body:
With Ansible, I cannot mount nfs4.

I have nfs4 exports configured on the server, and I can mount both nfs4 and nfs using a bash shell.

I can also get nfs to work in ansible, just not nfs4.

so I'm wondering how I can mount a share like /pool1/volume1 on the server to the same style path on the client-
/pool1/volume1

tried switching to standard nfs which worked, and I can mount nfs4 in a bash shell, but not with ansible

This works-

  - name: mount softnas NFS volume
    become: yes
    mount:
      fstype: nfs
      path: "/pool1/volume1"
      opts: rsize=8192,wsize=8192,timeo=14,intr,_netdev
      src: "10.0.11.11:/pool1/volume1"
      state: mounted

But this doesn't

  - name: mount softnas NFS volume
    become: yes
    mount:
      fstype: nfs4
      path: "/pool1/volume1"
      opts: rsize=8192,wsize=8192,timeo=14,intr,_netdev
      src: "10.0.11.11:/pool1/volume1"
      state: mounted

and if i use this command from a shell, this works fine in mounting the paths into test.
sudo mount -t nfs4 10.0.11.11:/ /test
although its not quite right, because id like /pool1/volume1 and /pool2/volume2 to not appear under /test

my exports file on the server is this-

/ *(ro,fsid=0)
# These mounts are managed in ansible playbook softnas-ebs-disk-update-exports.yaml
# BEGIN ANSIBLE MANAGED BLOCK /pool1/volume1/
/pool1/volume1/ *(async,insecure,no_subtree_check,no_root_squash,rw,nohide)
# END ANSIBLE MANAGED BLOCK /pool1/volume1/
# BEGIN ANSIBLE MANAGED BLOCK /pool2/volume2/
/pool2/volume2/ *(async,insecure,no_subtree_check,no_root_squash,rw,nohide)
# END ANSIBLE MANAGED BLOCK /pool2/volume2/

when I try to switch to nfs4, i get this error with ansible

Error mounting /pool1/volume1/: mount.nfs4: mounting 10.0.11.11:/pool1/volume1/ failed, reason given by server: No such file or directory

Body:
Came across this same issue, using Ansible 2.11.5 the above answer didn't work for me.  Ansible was complaining about the fstype "nfs4" and quoting was needed for the "opts" equal signs.  Here is what I used:

- name: mount AWS EFS Volume
  mount:
    fstype: nfs
    path: "/mnt/efs"
    opts: "nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport"
    src: "{{ efs_share_address[env] }}:/"
    state: mounted

From the roles var file:

efs_share_address:
  qa: 10.2.2.2
  stage: 10.3.3.3
  production: 10.4.4.4


问:
Click inside Loop issue - Remove dynamically created elements
The following code takes all the links onto the page that contains "https" and not "google.com" and turns them into iFrames. While that works, the close button that each is iFrame is supposed to be paired with does not work. When you click close, it only closes the last iFrame element on the page. I prefer to be able to do this in vanilla JavaScript, as opposed to jQuery.

total = []
var links = document.querySelectorAll("a");
for (var i = 0; i < links.length; i++) {
  var link = links[i];
  if (link.href.indexOf("https") != -1 &&
 link.href.indexOf("google.com") == -1) {
    var hey = (links[i].href);
    console.log(link.href);
    total.push(links[i].href);
    var iframe = document.createElement('iframe');
    iframe.src = hey;
    document.body.appendChild(iframe);
    var close = document.createElement('button');
    document.body.appendChild(close);
    close.innerHTML = "close";
    close.addEventListener('click',function(){
      console.log("click");
      document.body.removeChild(iframe);
      document.body.removeChild(close);
    })
  }
}
```

答:
```<code>for (var i = 0; i < links.length; i++)
</code>```

Change var to let.

OR

Use forEach instead of for loop.

The reason of this is scoping. var is function-scoped. Because above loop runs inside one function, var remains common for all loop iteration. On the other side, let or const are block-scoped. Because for loop creates individual blocks, each of the blocks created by the loop will work with an individual variable. forEach also creates individual scope. All variables will have values independent from each scope

Body:
for (var i = 0; i < links.length; i++)

Change var to let.

OR

Use forEach instead of for loop.

The reason of this is scoping. var is function-scoped. Because above loop runs inside one function, var remains common for all loop iteration. On the other side, let or const are block-scoped. Because for loop creates individual blocks, each of the blocks created by the loop will work with an individual variable. forEach also creates individual scope. All variables will have values independent from each scope


问:
How can I print a grep result with the matched word?
I have two files, "file A":

```<code>Adygei
Albanian
Armenia_C
Armenia_Caucasus
Armenia_EBA
Armenia_LBA
Armenia_MBA
Armenian.DG
Austria_EN_HG_LBK
Austria_EN_LBK
</code>```

And "fileB":

```<code>HG01880.SG Aygei_o1.SG
HG01988.SG Adygei_o2.SG
HG02419.SG Albanian_o2.SG
HG01879.SG Albanian.SG
HG01882.SG Armenia_C.SG
HG01883.SG Armenia_C.SG
HG01885.SG Armenia_EBA.SG
HG01886.SG Armenia_EBA.SG
HG01889.SG Armenia_LBA.SG
HG01890.SG Armenia_MBA.SG
</code>```

What I want at the end is create a new columne (doesn't matter the position of the column) with the grep word with the word that matched. Like This:

```<code>HG01880.SG Aygei_o1.SG Adygei
HG01988.SG Adygei_o2.SG Adygei
HG02419.SG Albanian_o2.SG Albanian
HG01879.SG Albanian.SG Albanian
HG01882.SG Armenia_C.SG Armenia_C
HG01883.SG Armenia_C.SG Armenia_C
HG01885.SG Armenia_EBA.SG Armenia_EBA
HG01886.SG Armenia_EBA.SG Armenia_EBA
HG01889.SG Armenia_LBA.SG Armenia_LBA
HG01890.SG Armenia_MBA.SG Armenia_MBA
</code>```

What I used to match both files in bash is grep -wFf fileA fileB > newfileA_B.txt. This can be both in python or bash

答:
Perform the grep search once more but this time adding the flag -o which only lists the matching words. Then use paste to add it as column (define the delimiter using the -d flag).

paste -d ' ' <(grep -wFf fileA fileB) <(grep -woFf fileA fileB)
```

Body:
I have two files, "file A":

Adygei
Albanian
Armenia_C
Armenia_Caucasus
Armenia_EBA
Armenia_LBA
Armenia_MBA
Armenian.DG
Austria_EN_HG_LBK
Austria_EN_LBK

And "fileB":

HG01880.SG Aygei_o1.SG
HG01988.SG Adygei_o2.SG
HG02419.SG Albanian_o2.SG
HG01879.SG Albanian.SG
HG01882.SG Armenia_C.SG
HG01883.SG Armenia_C.SG
HG01885.SG Armenia_EBA.SG
HG01886.SG Armenia_EBA.SG
HG01889.SG Armenia_LBA.SG
HG01890.SG Armenia_MBA.SG

What I want at the end is create a new columne (doesn't matter the position of the column) with the grep word with the word that matched. Like This:

HG01880.SG Aygei_o1.SG Adygei
HG01988.SG Adygei_o2.SG Adygei
HG02419.SG Albanian_o2.SG Albanian
HG01879.SG Albanian.SG Albanian
HG01882.SG Armenia_C.SG Armenia_C
HG01883.SG Armenia_C.SG Armenia_C
HG01885.SG Armenia_EBA.SG Armenia_EBA
HG01886.SG Armenia_EBA.SG Armenia_EBA
HG01889.SG Armenia_LBA.SG Armenia_LBA
HG01890.SG Armenia_MBA.SG Armenia_MBA

What I used to match both files in bash is grep -wFf fileA fileB > newfileA_B.txt. This can be both in python or bash


问:
Finding palindrome in C
A palindrome is a word that reads the same from left to right and from right to left.
I wrote a program that finds palindromes from a console.

```<code>#include <stdio.h>
#include <ctype.h>
#include <string.h>

#define SIZE 100

int main() {
    int i = 0, c;
    int left, right;
    char string[SIZE];

    while (EOF != (c = getchar()) || (c = getchar()) != '\n') {
        if (isspace(c) != 0) {
            if (i > 0) {
                left = 0;
                right = i - 1;
                while (right > left) {
                    if (string[left] != string[right]) {
                        i = 0;
                        break;
                    }
                    ++left;
                    --right;
                }
                if (left >= right) {
                    while (i > 0)
                        printf("%c", string[--i]);
                    printf("%c", c);
                }
                i = 0;
            }
            if (c == '\n')
                break;
        }
        else {
            string[i++] = c;
        }
    }
}
</code>```

For example, we enter the words: dad sad mum. She outputs: dad mum. But if we write dad sad or dad mum sad. The output will be: dad mum.
That is, an extra space is printed when the last word we read is not a palindrome. How can you get around this situation?

答:
Code is convoluted

First read input properly and form a string.

```<code>for (i = 0; i < SIZE - 1; i++) [
  int ch = getchar();
  if (ch == EOF || ch == '\n') {
    break;
  }
  string[i++] = (char) ch;
}
string[i] = 0;
</code>```

Then process the string in string[].  Only print spaces when needed.

```<code>const char *separator = "";
int i = 0;
while (string[i]) {
  // Beginning of a word?
  if (!isspace(string[i])) {
    int start = i;
    int end = i;
    while (!isspace(string[end+1]) && string[end+1]) {
      end++;
    }
    // At this point, start indexes the 1st char of the word
    // and end indexes the last char of the word
    // Now find if a palindrome

    while (start <= end && string[start] == string[end]) {
      start++;
      end--;
    }

    // Found a palindrome?
    if (start > end) {
      fputs(separator, stdout);
      separator = " ";  // print a space _next_ time
      while (!isspace(string[i]) && string[i]) {
        fputc(string[i++], stdout);
      }
    } else {
      i = end + 1;
    }
  } else {
    i++;
  }
}
fputc('\n', stdout);
</code>```

Title: Finding palindrome in C

Body:
A palindrome is a word that reads the same from left to right and from right to left.
I wrote a program that finds palindromes from a console.

#include <stdio.h>
#include <ctype.h>
#include <string.h>

#define SIZE 100

int main() {
    int i = 0, c;
    int left, right;
    char string[SIZE];

    while (EOF != (c = getchar()) || (c = getchar()) != '\n') {
        if (isspace(c) != 0) {
            if (i > 0) {
                left = 0;
                right = i - 1;
                while (right > left) {
                    if (string[left] != string[right]) {
                        i = 0;
                        break;
                    }
                    ++left;
                    --right;
                }
                if (left >= right) {
                    while (i > 0)
                        printf("%c", string[--i]);
                    printf("%c", c);
                }
                i = 0;
            }
            if (c == '\n')
                break;
        }
        else {
            string[i++] = c;
        }
    }
}

For example, we enter the words: dad sad mum. She outputs: dad mum. But if we write dad sad or dad mum sad. The output will be: dad mum.
That is, an extra space is printed when the last word we read is not a palindrome. How can you get around this situation?

Body:
Code is convoluted

First read input properly and form a string.

for (i = 0; i < SIZE - 1; i++) [
  int ch = getchar();
  if (ch == EOF || ch == '\n') {
    break;
  }
  string[i++] = (char) ch;
}
string[i] = 0;

Then process the string in string[].  Only print spaces when needed.

const char *separator = "";
int i = 0;
while (string[i]) {
  // Beginning of a word?
  if (!isspace(string[i])) {
    int start = i;
    int end = i;
    while (!isspace(string[end+1]) && string[end+1]) {
      end++;
    }
    // At this point, start indexes the 1st char of the word
    // and end indexes the last char of the word
    // Now find if a palindrome

    while (start <= end && string[start] == string[end]) {
      start++;
      end--;
    }

    // Found a palindrome?
    if (start > end) {
      fputs(separator, stdout);
      separator = " ";  // print a space _next_ time
      while (!isspace(string[i]) && string[i]) {
        fputc(string[i++], stdout);
      }
    } else {
      i = end + 1;
    }
  } else {
    i++;
  }
}
fputc('\n', stdout);


问:
difference between data mining and machine learning
I am new to this area.

In my image,

Data mining means to retrieve useful information from data with respect to a data model.
Machine learning seeks to identify behavior patterns in data, and them build various models based on observed patterns.

答:
Also, Data Mining is often considered a sub-field of Machine Learning.

Data Mining usually goes only as far as interpreting the data (e.g. categorizing newspaper articles based on their theme, or books according to the suitable age of readers). It is a part of Machine Learning that is given raw data, and then, using Machine Learning methods, extracts some meaningful information about it.

Machine Learning in general can have more steps than just interpreting the data. Programs developed Machine Learning techniques can also act upon the knowledge "learned" from the data, e.g. a program that is given a bunch of examples of Checkers games and based on that is able to play the game (well), has "learned" from the examples -- the data, and can now interpret new (similar data) and act upon that.


问:
Why won't my image align to the right? CSS
I am stuck on this simple issue. How the heck do I align my image to the right border of the box? I tried float:right, align-self: end, margin: -4em, I tried most things I found online but nothing.
As you can see I put the image through CSS as a background image for a div. I am stuck.

how it should look

how it is

  body{
    background-color: hsl(233, 47%, 7%);
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 6em;
  }
  .all{
    background-color: hsl(244, 38%, 16%);
    width: 80em;
    height: 28em;
    border-radius: 0.725em;
    overflow: hidden;
    display: flex;
  }
  .bella{
    background-image: url(images/image-header-desktop.jpg);
    height: 30em;
    width: 30em;
    background-repeat: no-repeat;
    contain: content;
    display: inline-block;
    background-position: right;
    align-self: flex-end;
    clear: left;
    float: right;
  }
  .writings{
    font-family: 'Inter';
    display: flex;
    flex-direction: column;
    max-width: 30em ;
    margin: 6em;
  }
  .writings h1{
    font-weight: 700;
    color: white;
  }
  #viola{
    color: hsl(277, 64%, 61%);
  }
  .writings p{
    color: hsla(0, 0%, 100%, 0.75);
    font-weight: 400;
  }
  .figures{
    display: flex;
  }
  .figures h2{
    font-weight: 700;
    color: white;
    font-family: 'Inter';
  }
  .figures h5{
    color: hsla(0, 0%, 100%, 0.6);
    text-transform: uppercase;
    font-family: 'Lexend Deca';
    letter-spacing: 2px;
  }
  .fig1{
    padding-right: 5em;
  }
HTML```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="tutto"></div>
    <div class="all">
      <div class="writings">
          <h1>Get <span id="viola">insights</span> that help your business grow.</h1>
          <p> Discover the benefits of data analytics and make better decisions regarding revenue, customer
            experience, and overall efficiency.</p>
          <div class="figures">
            <div class="fig1"><h2>10k+</h2><h5> companies</h5></div>
            <div class="fig1"><h2>1314</h2><h5> templates</h5></div>
            <div class="fig1"><h2>12M+</h2><h5> queries</h5></div>
          </div>
      </div>
      <div class="bella"></div>
    </div>
  </div>
</body>
</html></code>```

答: First, I would try to set the height to 100%. Then consider to make both sides equally wide, if you want it to look exactly like the "how it should look" version. Additionally, your picture has to have the right nativ width and height so that it is as big as the left side of your div.</p>

Body:
I am stuck on this simple issue. How the heck do I align my image to the right border of the box? I tried float:right, align-self: end, margin: -4em, I tried most things I found online but nothing.
As you can see I put the image through CSS as a background image for a div. I am stuck.

how it should look

how it is

  body{
    background-color: hsl(233, 47%, 7%);
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 6em;
  }
  .all{
    background-color: hsl(244, 38%, 16%);
    width: 80em;
    height: 28em;
    border-radius: 0.725em;
    overflow: hidden;
    display: flex;
  }
  .bella{
    background-image: url(images/image-header-desktop.jpg);
    height: 30em;
    width: 30em;
    background-repeat: no-repeat;
    contain: content;
    display: inline-block;
    background-position: right;
    align-self: flex-end;
    clear: left;
    float: right;
  }
  .writings{
    font-family: 'Inter';
    display: flex;
    flex-direction: column;
    max-width: 30em ;
    margin: 6em;
  }
  .writings h1{
    font-weight: 700;
    color: white;
  }
  #viola{
    color: hsl(277, 64%, 61%);
  }
  .writings p{
    color: hsla(0, 0%, 100%, 0.75);
    font-weight: 400;
  }
  .figures{
    display: flex;
  }
  .figures h2{
    font-weight: 700;
    color: white;
    font-family: 'Inter';
  }
  .figures h5{
    color: hsla(0, 0%, 100%, 0.6);
    text-transform: uppercase;
    font-family: 'Lexend Deca';
    letter-spacing: 2px;
  }
  .fig1{
    padding-right: 5em;
  }
HTML

Get insights that help your business grow.

 Discover the benefits of data analytics and make better decisions regarding revenue, customer
            experience, and overall efficiency.

10k+

 companies

1314

 templates

12M+

 queries


问:
how can I set background to react native animated view

Issue Description

I want to change background color right after rendering component but interpolate but actual output is Error: Style property 'backgroundColor' is not supported by native animated module

Codes

```<code>import React, {useEffect, useRef} from 'react';
import {Animated} from 'react-native';

export default function Welcome(props) {
  const translation = useRef(new Animated.Value(0)).current;
  useEffect(() => {
    Animated.timing(translation, {
      toValue: 0,
      duration: 1000,
      useNativeDriver: true,
    }).start();
  }, []);
  const styles = {
    flex: 1,
    backgroundColor: translation.interpolate({
      inputRange: [0, 100],
      outputRange: ['orange', 'blue'],
    }),
    opacity: translation.interpolate({
      inputRange: [25, 50, 100],
      outputRange: [0, 1, 0],
      extrapolate: 'clamp',
    }),
    transform: [
      {translateX: translation},
      {
        rotate: translation.interpolate({
          inputRange: [0, 100],
          outputRange: ['0deg', '360deg'],
        }),
      },
    ],
  };
  return (
    <Animated.View style={styles}>
      <Animated.Text style={{color:'tomato'}}>Credex</Animated.Text>
    </Animated.View>
  );
}
</code>```

答: React native 0.68-rc added support for interpolating colors but you can also use reanimated to do these things and it's much easier. For this case, please set useNativeDriver to false.

Body:
Issue Description

I want to change background color right after rendering component but interpolate but actual output is Error: Style property 'backgroundColor' is not supported by native animated module

Codes

import React, {useEffect, useRef} from 'react';
import {Animated} from 'react-native';

export default function Welcome(props) {
  const translation = useRef(new Animated.Value(0)).current;
  useEffect(() => {
    Animated.timing(translation, {
      toValue: 0,
      duration: 1000,
      useNativeDriver: true,
    }).start();
  }, []);
  const styles = {
    flex: 1,
    backgroundColor: translation.interpolate({
      inputRange: [0, 100],
      outputRange: ['orange', 'blue'],
    }),
    opacity: translation.interpolate({
      inputRange: [25, 50, 100],
      outputRange: [0, 1, 0],
      extrapolate: 'clamp',
    }),
    transform: [
      {translateX: translation},
      {
        rotate: translation.interpolate({
          inputRange: [0, 100],
          outputRange: ['0deg', '360deg'],
        }),
      },
    ],
  };
  return (
    <Animated.View style={styles}>
      <Animated.Text style={{color:'tomato'}}>Credex</Animated.Text>
    </Animated.View>
  );
}


问:
Is there a way to make this query formula work? it was working before but I had to add more sheets and then it broke
Formula that combines all the sheets in my project and removes any empty cells

答:
yes, change this:

```<code>;},
</code>```

to this:

```<code>},
</code>```

Body:
yes, change this:

;},

to this:

},


问:
webpack-dev-server not reloading on html or sass change
My project has this structure:

```<code>\root
   \webpack.config.js
   \public
     \ index.html
     \ ...
     \ css
     \ directives
     \ views
     \ dist (webpack output)
       \app.js
       \ index.html
       \ app.js.map
       \ style.css
       \ style.css.map
</code>```

when i use webpack-dev-server I launch it from /root and it loads the app. But, when i change a sass file or html file it does not reload.   What is wrong with the webpack config?

Command to launch webpack:

```<code>$ cd root
$ webpack-dev-server
</code>```

Webpack.config.js

```<code>const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');

const webConfig = {
  entry: path.join(__dirname, 'public', 'js', 'app'),
  output: {
    path: path.join(__dirname, 'public', 'dist'),
    filename: 'app.js'
  },
  resolve: {
    modules: [__dirname, 'node_modules'],
    extensions: ['.js'],
    enforceExtension: false,
  },
  devtool: 'source-map',
  devServer:{
    contentBase: 'public/',
    publicPath: 'public/'
  },
  module: {
    loaders: [
      {
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract({
          loader: 'css-loader?modules,localIdentName=[name]__[local]--[hash:base64:5]!sass-loader'
        }),
        exclude: /node_modules/
      },
      {
        test: /\.html$/,
        loader: "raw-loader" // loaders: ['raw-loader'] is also perfectly acceptable.
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin({filename: 'style.css', allChunks: true}),
    new HtmlWebpackPlugin({
      template: './public/index.html'
    })
  ]
};

module.exports = webConfig;
</code>```

答: if you have HtmlWebpackPlugin, try to remove it, weback-dev-server/webpack serve can pick the html file under ./public automatically.

Body:
My project has this structure:

\root
   \webpack.config.js
   \public
     \ index.html
     \ ...
     \ css
     \ directives
     \ views
     \ dist (webpack output)
       \app.js
       \ index.html
       \ app.js.map
       \ style.css
       \ style.css.map

when i use webpack-dev-server I launch it from /root and it loads the app. But, when i change a sass file or html file it does not reload.   What is wrong with the webpack config?

Command to launch webpack:

$ cd root
$ webpack-dev-server

Webpack.config.js

const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');

const webConfig = {
  entry: path.join(__dirname, 'public', 'js', 'app'),
  output: {
    path: path.join(__dirname, 'public', 'dist'),
    filename: 'app.js'
  },
  resolve: {
    modules: [__dirname, 'node_modules'],
    extensions: ['.js'],
    enforceExtension: false,
  },
  devtool: 'source-map',
  devServer:{
    contentBase: 'public/',
    publicPath: 'public/'
  },
  module: {
    loaders: [
      {
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract({
          loader: 'css-loader?modules,localIdentName=[name]__[local]--[hash:base64:5]!sass-loader'
        }),
        exclude: /node_modules/
      },
      {
        test: /\.html$/,
        loader: "raw-loader" // loaders: ['raw-loader'] is also perfectly acceptable.
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin({filename: 'style.css', allChunks: true}),
    new HtmlWebpackPlugin({
      template: './public/index.html'
    })
  ]
};

module.exports = webConfig;


问:
Store slope, intercept, and R2 for multiple regressions in one batch calculation in R
I have a data frame that has a long list of data:

```<code>Well.ID | Year | Ave.GWE
1       | 2005 | 525
1       | 2006 | 524
1       | 2004 | 523
2       | 2005 | 552
2       | 2006 | 551
2       | 2007 | 550
.
.
.
10       | 2005 | 582
10       | 2006 | 581
10       | 2007 | 580

</code>```

I've been able to make a batch plot of the linear regression of Years vs GWE for each Well.ID using ggplot, facet_rep_wrap, geom_smooth, and stat_regline_equation. Now i'd like to create a data frame with the following for each regression:

```<code>
Well.ID | m (slope) | b (intercept) | R2

</code>```

Does anyone know if i can run the lm function through a forloop and store all this information automatically?

Thanks

答:
We need a bit more data to demonstrate. The following should match approximately your structure:

set.seed(1)

df <- data.frame(Well.ID = rep(1:5, each = 5),
                 Year = rep(2005:2009, 5),
                 Ave.GWE = round(runif(25, 400, 500)))
head(df)
#>   Well.ID Year Ave.GWE
#> 1       1 2005     427
#> 2       1 2006     437
#> 3       1 2007     457
#> 4       1 2008     491
#> 5       1 2009     420
#> 6       2 2005     490
```
<p>We can get your result by doing</p>
```do.call(rbind, lapply(unique(df$Well.ID), function(d) {
  model <- lm(Ave.GWE ~ Year, data = df[df$Well.ID == d,])
  data.frame(Well.ID = d, Intercept = coef(model)[1],
             Slope = coef(model)[2], r_squared = summary(model)$r.squared,
             row.names = NULL)
}))
#>   Well.ID Intercept Slope  r_squared
#> 1       1   -7581.6   4.0 0.04903163
#> 2       2   40403.1 -19.9 0.80086151
#> 3       3  -26047.8  13.2 0.59000406
#> 4       4   -3948.0   2.2 0.02105080
#> 5       5   28541.8 -14.0 0.42416898
```

Created on 2022-02-09 by the reprex package (v2.0.1)

Body:
I have a data frame that has a long list of data:

Well.ID | Year | Ave.GWE
1       | 2005 | 525
1       | 2006 | 524
1       | 2004 | 523
2       | 2005 | 552
2       | 2006 | 551
2       | 2007 | 550
.
.
.
10       | 2005 | 582
10       | 2006 | 581
10       | 2007 | 580

I've been able to make a batch plot of the linear regression of Years vs GWE for each Well.ID using ggplot, facet_rep_wrap, geom_smooth, and stat_regline_equation. Now i'd like to create a data frame with the following for each regression:

Well.ID | m (slope) | b (intercept) | R2

Does anyone know if i can run the lm function through a forloop and store all this information automatically?

Thanks

Body:
We need a bit more data to demonstrate. The following should match approximately your structure:

set.seed(1)

df <- data.frame(Well.ID = rep(1:5, each = 5),
                 Year = rep(2005:2009, 5),
                 Ave.GWE = round(runif(25, 400, 500)))
head(df)
#>   Well.ID Year Ave.GWE
#> 1       1 2005     427
#> 2       1 2006     437
#> 3       1 2007     457
#> 4       1 2008     491
#> 5       1 2009     420
#> 6       2 2005     490

We can get your result by doing

do.call(rbind, lapply(unique(df$Well.ID), function(d) {
  model <- lm(Ave.GWE ~ Year, data = df[df$Well.ID == d,])
  data.frame(Well.ID = d, Intercept = coef(model)[1],
             Slope = coef(model)[2], r_squared = summary(model)$r.squared,
             row.names = NULL)
}))
#>   Well.ID Intercept Slope  r_squared
#> 1       1   -7581.6   4.0 0.04903163
#> 2       2   40403.1 -19.9 0.80086151
#> 3       3  -26047.8  13.2 0.59000406
#> 4       4   -3948.0   2.2 0.02105080
#> 5       5   28541.8 -14.0 0.42416898

Created on 2022-02-09 by the reprex package (v2.0.1)


问:
Issue with libphonenumber-js library not formatting international numbers
I'm trying to get international phone numbers to format properly but it doesn't seem to be adding the spaces within the number, only for the country code.

```<code>let phoneNumber = parsePhoneNumber('+3802342342345', 'UA');
return phoneNumber.formatInternational();
</code>```

So the result I would expect to see is:

```<code>+380 234 234 2345
</code>```

but instead I get

```<code>+380 2342342345
</code>```

without the spaces in the actual phone number.

答:
Seems like your number is invalid. Some of the number formats I found here

let phoneNumber = libphonenumber.parsePhoneNumber('+3802342342345', 'UA').formatInternational();;
console.log(phoneNumber)
console.log(libphonenumber.isValidNumber(phoneNumber))

//+380 44 xxx-xx-xx  (international call to Kyiv)
let a = libphonenumber.parsePhoneNumber('+380444234245', 'UA').formatInternational();
console.log(a)
console.log(libphonenumber.isValidNumber(a))

//+380 45 94x-xx-xx  (international call to Brovary)
let b = libphonenumber.parsePhoneNumber('+380459434245', 'UA').formatInternational();
console.log(b)
console.log(libphonenumber.isValidNumber(b))

//+380 48 xxx-xx-xx  (international call to Odessa)
let c = libphonenumber.parsePhoneNumber('+380489434245', 'UA').formatInternational();
console.log(c)
console.log(libphonenumber.isValidNumber(c))

//+380 48 2xx-xx-xx  (international call to 6-digit numbers in Odessa)
let d = libphonenumber.parsePhoneNumber('+380482434245', 'UA').formatInternational();
console.log(d)
console.log(libphonenumber.isValidNumber(d))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/libphonenumber-js/1.9.48/libphonenumber-js.min.js"></script></code>```

The library seems to take the default digits together

Body:
I'm trying to get international phone numbers to format properly but it doesn't seem to be adding the spaces within the number, only for the country code.

let phoneNumber = parsePhoneNumber('+3802342342345', 'UA');
return phoneNumber.formatInternational();

So the result I would expect to see is:

+380 234 234 2345

but instead I get

+380 2342342345

without the spaces in the actual phone number.

Body:
Seems like your number is invalid. Some of the number formats I found here

let phoneNumber = libphonenumber.parsePhoneNumber('+3802342342345', 'UA').formatInternational();;
console.log(phoneNumber)
console.log(libphonenumber.isValidNumber(phoneNumber))

//+380 44 xxx-xx-xx  (international call to Kyiv)
let a = libphonenumber.parsePhoneNumber('+380444234245', 'UA').formatInternational();
console.log(a)
console.log(libphonenumber.isValidNumber(a))

//+380 45 94x-xx-xx  (international call to Brovary)
let b = libphonenumber.parsePhoneNumber('+380459434245', 'UA').formatInternational();
console.log(b)
console.log(libphonenumber.isValidNumber(b))

//+380 48 xxx-xx-xx  (international call to Odessa)
let c = libphonenumber.parsePhoneNumber('+380489434245', 'UA').formatInternational();
console.log(c)
console.log(libphonenumber.isValidNumber(c))

//+380 48 2xx-xx-xx  (international call to 6-digit numbers in Odessa)
let d = libphonenumber.parsePhoneNumber('+380482434245', 'UA').formatInternational();
console.log(d)
console.log(libphonenumber.isValidNumber(d))

<script src="https://cdnjs.cloudflare.com/ajax/libs/libphonenumber-js/1.9.48/libphonenumber-js.min.js"></script>

The library seems to take the default digits together


问:
Extract json key/value pairs with postgresql/snowflake, where value is not null/blank
I have a field called "filter" with json array like:

[
   {
      "after":"2021-10-14T00:00:00",
      "column":"createddate",
      "from":null,
      "gt":null,
      "gte":null,
      "id":"928d57b0",
      "lt":null,
      "lte":null,
      "not":null,
      "prior":null,
      "to":null,
      "value":null
   },
   {
      "after":null,
      "column":"last_coach_date",
      "from":"",
      "gt":null,
      "gte":null,
      "id":"01704cdd",
      "lt":null,
      "lte":null,
      "not":null,
      "prior":null,
      "to":"",
      "value":null
   }
]
```

I'm trying to extract key/value pairs where value is not null/blank and create another field for it.

Maybe to something like this or one long string:

 { "after": "2021-10-14T00:00:00", "column": "createddate", "id": "928d57b0"}, {"column": "last_coach_date","id": "01704cdd"} AS filter_value

答:
Using FLATTEN and OBJECT_AGG:

```<code>CREATE OR REPLACE TABLE t(col VARIANT)
AS
SELECT PARSE_JSON('[ { "after": "2021-10-14T00:00:00", "column": "createddate", "from": null, "gt": null, "gte": null, "id": "928d57b0", "lt": null, "lte": null, "not": null, "prior": null, "to": null, "value": null }, { "after": null, "column": "last_coach_date", "from": "", "gt": null, "gte": null, "id": "01704cdd", "lt": null, "lte": null, "not": null, "prior": null, "to": "", "value": null }]'
                );
</code>```

Query:

```<code>SELECT s.index, OBJECT_AGG(s2.key, s2.value) AS output
FROM t
,LATERAL FLATTEN(input => col) s
,LATERAL FLATTEN(input =>  s.value) s2
WHERE NOT IS_NULL_VALUE(s2.value)  AND s2.value::TEXT != ''
GROUP BY s.INDEX;
</code>```

Output:

Body:
I have a field called "filter" with json array like:

[
   {
      "after":"2021-10-14T00:00:00",
      "column":"createddate",
      "from":null,
      "gt":null,
      "gte":null,
      "id":"928d57b0",
      "lt":null,
      "lte":null,
      "not":null,
      "prior":null,
      "to":null,
      "value":null
   },
   {
      "after":null,
      "column":"last_coach_date",
      "from":"",
      "gt":null,
      "gte":null,
      "id":"01704cdd",
      "lt":null,
      "lte":null,
      "not":null,
      "prior":null,
      "to":"",
      "value":null
   }
]

I'm trying to extract key/value pairs where value is not null/blank and create another field for it.

Maybe to something like this or one long string:

 { "after": "2021-10-14T00:00:00", "column": "createddate", "id": "928d57b0"}, {"column": "last_coach_date","id": "01704cdd"} AS filter_value

Body:
Using FLATTEN and OBJECT_AGG:

CREATE OR REPLACE TABLE t(col VARIANT)
AS
SELECT PARSE_JSON('[ { "after": "2021-10-14T00:00:00", "column": "createddate", "from": null, "gt": null, "gte": null, "id": "928d57b0", "lt": null, "lte": null, "not": null, "prior": null, "to": null, "value": null }, { "after": null, "column": "last_coach_date", "from": "", "gt": null, "gte": null, "id": "01704cdd", "lt": null, "lte": null, "not": null, "prior": null, "to": "", "value": null }]'
                );

Query:

SELECT s.index, OBJECT_AGG(s2.key, s2.value) AS output
FROM t
,LATERAL FLATTEN(input => col) s
,LATERAL FLATTEN(input =>  s.value) s2
WHERE NOT IS_NULL_VALUE(s2.value)  AND s2.value::TEXT != ''
GROUP BY s.INDEX;

Output:


答:
Remove the float you had set on the div with the background image. This is not needed with flex. Then set your height and width to 100%. I added a dummy image for demonstration purposes. See below.

body {
  background-color: hsl(233, 47%, 7%);
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 6em;
}

.all {
  background-color: hsl(244, 38%, 16%);
  width: 80em;
  height: 28em;
  border-radius: 0.725em;
  overflow: hidden;
  display: flex;
}

.bella {
  background-image: url(https://dummyimage.com/600x400/000/fff);
  height: 100%;
  width: 100%;
  /* background-repeat: no-repeat; */
  contain: content;
  display: inline-block;
  background-position: right;
  /* align-self: flex-end; */
  /* clear: left; */
  /* float: right; */
}

.writings {
  font-family: 'Inter';
  display: flex;
  flex-direction: column;
  max-width: 30em;
  margin: 6em;
}

.writings h1 {
  font-weight: 700;
  color: white;
}

#viola {
  color: hsl(277, 64%, 61%);
}

.writings p {
  color: hsla(0, 0%, 100%, 0.75);
  font-weight: 400;
}

.figures {
  display: flex;
}

.figures h2 {
  font-weight: 700;
  color: white;
  font-family: 'Inter';
}

.figures h5 {
  color: hsla(0, 0%, 100%, 0.6);
  text-transform: uppercase;
  font-family: 'Lexend Deca';
  letter-spacing: 2px;
}

.fig1 {
  padding-right: 5em;
}

HTML```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="tutto"></div>
  <div class="all">
    <div class="writings">
      <h1>Get <span id="viola">insights</span> that help your business grow.</h1>
      <p> Discover the benefits of data analytics and make better decisions regarding revenue, customer experience, and overall efficiency.</p>
      <div class="figures">
        <div class="fig1">
          <h2>10k+</h2>
          <h5> companies</h5>
        </div>
        <div class="fig1">
          <h2>1314</h2>
          <h5> templates</h5>
        </div>
        <div class="fig1">
          <h2>12M+</h2>
          <h5> queries</h5>
        </div>
      </div>
    </div>
    <div class="bella"></div>
  </div>
  </div>
</body></code>```

Title: Why won't my image align to the right? CSS

Body:
Remove the float you had set on the div with the background image. This is not needed with flex. Then set your height and width to 100%. I added a dummy image for demonstration purposes. See below.

body {
  background-color: hsl(233, 47%, 7%);
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 6em;
}

.all {
  background-color: hsl(244, 38%, 16%);
  width: 80em;
  height: 28em;
  border-radius: 0.725em;
  overflow: hidden;
  display: flex;
}

.bella {
  background-image: url(https://dummyimage.com/600x400/000/fff);
  height: 100%;
  width: 100%;
  /* background-repeat: no-repeat; */
  contain: content;
  display: inline-block;
  background-position: right;
  /* align-self: flex-end; */
  /* clear: left; */
  /* float: right; */
}

.writings {
  font-family: 'Inter';
  display: flex;
  flex-direction: column;
  max-width: 30em;
  margin: 6em;
}

.writings h1 {
  font-weight: 700;
  color: white;
}

#viola {
  color: hsl(277, 64%, 61%);
}

.writings p {
  color: hsla(0, 0%, 100%, 0.75);
  font-weight: 400;
}

.figures {
  display: flex;
}

.figures h2 {
  font-weight: 700;
  color: white;
  font-family: 'Inter';
}

.figures h5 {
  color: hsla(0, 0%, 100%, 0.6);
  text-transform: uppercase;
  font-family: 'Lexend Deca';
  letter-spacing: 2px;
}

.fig1 {
  padding-right: 5em;
}

HTML

<body>
  <div class="tutto"></div>
  <div class="all">
    <div class="writings">
      <h1>Get <span id="viola">insights</span> that help your business grow.</h1>
      <p> Discover the benefits of data analytics and make better decisions regarding revenue, customer experience, and overall efficiency.</p>
      <div class="figures">
        <div class="fig1">
          <h2>10k+</h2>
          <h5> companies</h5>
        </div>
        <div class="fig1">
          <h2>1314</h2>
          <h5> templates</h5>
        </div>
        <div class="fig1">
          <h2>12M+</h2>
          <h5> queries</h5>
        </div>
      </div>
    </div>
    <div class="bella"></div>
  </div>
  </div>
</body>


问:
How can I conditionally return different navbars/headers in app.js based on the route?
I couldn't find any clear answers on this so I thought I'd ask. I am trying to render 2 different headers for two different routes. So ideally, if we're on the '/home', we return my decked out <HeaderHome />, and if we are in '/projects' route, then render a more simple header in <HeaderProjects />. Below is my code structure.

```<code>function App() {
  return (
    <>
      <div className={styles.container}>
        <main className={styles.main}>
          {(path == "/home") ? <HeaderHome /> : <HeaderProjects />}
          <Routes>
              <Route path="/home" element={< Home />} />
              {/* <Route path="/about" element={< About />} />
              <Route path="/resume" element={<Resume />} /> */}
              <Route path="/projects" element={<Projects />} />
              {/* <Route path="/contact" element={<Contact />} />     */}
          </Routes>
          <Footer />
        </main>
      </div>
    </>
  )
}
</code>```

Thank you for taking a look.

答:
You can use layout components that render the specific header component you want and an Outlet for nested routes.

Example:

```<code>import { Outlet } from 'react-router-dom';

const HomeLayout = () => (
  <>
    <HeaderHome />
    <Outlet />
  </>
);

const ProjectsLayout = () => (
  <>
    <HeaderProjects />
    <Outlet />
  </>
);

function App() {
  return (
    <div className={styles.container}>
      <main className={styles.main}>
        <Routes>
          <Route element={<HomeLayout />}>
            <Route path="/home" element={<Home />} />
          </Route>

          <Route element={<ProjectsLayout />}>
            <Route path="/projects" element={<Projects />} />
          </Route>

          <Route path="/about" element={<About />} />
          <Route path="/resume" element={<Resume />} />
          <Route path="/contact" element={<Contact />} />
        </Routes>
        <Footer />
      </main>
    </div>
  );
}
</code>```

Body:
I couldn't find any clear answers on this so I thought I'd ask. I am trying to render 2 different headers for two different routes. So ideally, if we're on the '/home', we return my decked out <HeaderHome />, and if we are in '/projects' route, then render a more simple header in <HeaderProjects />. Below is my code structure.

function App() {
  return (
    <>

          {(path == "/home") ? <HeaderHome /> : <HeaderProjects />}
          <Routes>
              <Route path="/home" element={< Home />} />
              {/* <Route path="/about" element={< About />} />
              <Route path="/resume" element={<Resume />} /> */}
              <Route path="/projects" element={<Projects />} />
              {/* <Route path="/contact" element={<Contact />} />     */}
          </Routes>

    </>
  )
}

Thank you for taking a look.

Body:
You can use layout components that render the specific header component you want and an Outlet for nested routes.

Example:

import { Outlet } from 'react-router-dom';

const HomeLayout = () => (
  <>
    <HeaderHome />
    <Outlet />
  </>
);

const ProjectsLayout = () => (
  <>
    <HeaderProjects />
    <Outlet />
  </>
);

function App() {
  return (
    <div className={styles.container}>
      <main className={styles.main}>
        <Routes>
          <Route element={<HomeLayout />}>
            <Route path="/home" element={<Home />} />
          </Route>

          <Route element={<ProjectsLayout />}>
            <Route path="/projects" element={<Projects />} />
          </Route>

          <Route path="/about" element={<About />} />
          <Route path="/resume" element={<Resume />} />
          <Route path="/contact" element={<Contact />} />
        </Routes>
        <Footer />
      </main>
    </div>
  );
}


问:
react not showing from images from props on cards
Sorry am a newbie to ReactJS. Am trying to load images from MainContent to Cards from PROPS to but unsuccessful for couple of days

MainContent.js

```<code>import react from "react";
import reactDom from "react-dom";
import '../css/styles.css'
import Cards from './Cards'

export default function MainContent(){

return(
     <div>
        <Cards ximg= "/images/stays/1.jpg"  alt="Enthralling Escapes Manali" xhead="Windflower Condo Manali"/>
        <Cards ximg= './images/stays/Enthralling-Escapes-Manali.jpg' alt="Enthralling Escapes Manali" xhead="Windflower Condo Manali" />
        <Cards ximg= "../images/stays/Lonchenpa-Manali.jpg" alt="Lonchenpa-Manali" xhead="Lonchenpa Manali" />
        <Cards ximg= "../images/stays/The-Abode-Shobla-Pine-Chalet.jpg" alt="The-Abode-Shobla-Pine-Chalet" xhead="The Abode Shobla Pine Chalet" />
        <Cards ximg= "../images/stays/The-Warehouse-Gadherni-Himachal-Pradesh.jpg" alt="The-Warehouse-Gadherni-Himachal-Pradesh" xhead="The Warehouse Gadherni Himachal Pradesh" />
        <Cards ximg= "../images/stays/Windflower-Condo-Manali.jpg" alt="Windflower-Condo-Manali" xhead="Windflower Condo Manali" />
    </div>
    )
}
</code>```

here is my --- Cards.js

```<code>import React, {Component} from 'react';
import reactDom from "react-dom";

export default function Cards(props){
const url = 'http://localhost:3000/images/stays/';
return(
    <section>
        <div className='xcards'>
            <h3>{props.xhead}</h3>
            <img src={props.ximg} alt={props.alt} />
        </div>
    </section>
    )
}
</code>```

The other data like ALT and XHEAD are visible but only images are not showing up

thank you in advance to everyone reading my question

答: the image paths are not valid inside Card component, use absolute or relative path or just send the image name as prop and create the path inside Card

Body:
Sorry am a newbie to ReactJS. Am trying to load images from MainContent to Cards from PROPS to but unsuccessful for couple of days

MainContent.js

import react from "react";
import reactDom from "react-dom";
import '../css/styles.css'
import Cards from './Cards'

export default function MainContent(){

return(

        <Cards ximg= "/images/stays/1.jpg"  alt="Enthralling Escapes Manali" xhead="Windflower Condo Manali"/>
        <Cards ximg= './images/stays/Enthralling-Escapes-Manali.jpg' alt="Enthralling Escapes Manali" xhead="Windflower Condo Manali" />
        <Cards ximg= "../images/stays/Lonchenpa-Manali.jpg" alt="Lonchenpa-Manali" xhead="Lonchenpa Manali" />
        <Cards ximg= "../images/stays/The-Abode-Shobla-Pine-Chalet.jpg" alt="The-Abode-Shobla-Pine-Chalet" xhead="The Abode Shobla Pine Chalet" />
        <Cards ximg= "../images/stays/The-Warehouse-Gadherni-Himachal-Pradesh.jpg" alt="The-Warehouse-Gadherni-Himachal-Pradesh" xhead="The Warehouse Gadherni Himachal Pradesh" />
        <Cards ximg= "../images/stays/Windflower-Condo-Manali.jpg" alt="Windflower-Condo-Manali" xhead="Windflower Condo Manali" />

    )
}

here is my --- Cards.js

import React, {Component} from 'react';
import reactDom from "react-dom";

export default function Cards(props){
const url = 'http://localhost:3000/images/stays/';
return(

{props.xhead}

    )
}

The other data like ALT and XHEAD are visible but only images are not showing up

thank you in advance to everyone reading my question


问:
Replace, Insert, Delete operations on IEnumerable
I have a library that only accepts a proprietary immutable collection type. I would like to have a function that accepts one of these collections and performs some changes to this collection by returning a new collection that contains the changes made.

I would like to use a LINQ syntax instead of copying this collection to a List and back.

Add operations is easy for me: concat the enumerable with another one.
But what about Replace (at the given index, return the value given instead of that IEnumerable's value), Insert (at given index, return the given value and then continue iterating over the IEnumerable) or Delete (at given index, skip the IEnumerable's value)?

Are there functions like this available in the .NET framework or in another library? If not, how would I go about implementing these functions?

答:
For a functional, more LINQ-ey feeling solution, inspired by Arturo's answer:

```<code>public static IEnumerable<T> Replace<T>(this IEnumerable<T> enumerable, Func<T, bool> selector, T value)
{
    foreach (var item in enumerable)
    {
        yield return selector(item) ? value : item;
    }
}
</code>```

Used like this: var newEnumerable = oldEnumerable.Replace(x => x.Id == 1, newItem)

Body:
For a functional, more LINQ-ey feeling solution, inspired by Arturo's answer:

public static IEnumerable<T> Replace<T>(this IEnumerable<T> enumerable, Func<T, bool> selector, T value)
{
    foreach (var item in enumerable)
    {
        yield return selector(item) ? value : item;
    }
}

Used like this: var newEnumerable = oldEnumerable.Replace(x => x.Id == 1, newItem)


问:
page.getHtmlElementById("tsf") wont work: com.gargoylesoftware.htmlunit.ElementNotFoundException:tsf
I am trying to run the tutorial on here. The code looks like this:

public class Test {

    public static void main(String[] args) throws FailingHttpStatusCodeException, MalformedURLException, IOException {
        WebClient client = new WebClient(BrowserVersion.FIREFOX);
        HtmlPage page = client.getPage("https://google.com/");

        // Getting Form from google home page. tsf is the form name
        HtmlForm form = page.getHtmlElementById("tsf"); // Error occurs here

        form.getInputByName("q").setValueAttribute("test");

        // Creating a virtual submit button
        HtmlButton submitButton = (HtmlButton)page.createElement("button");
        submitButton.setAttribute("type", "submit");
        form.appendChild(submitButton);

          // Submitting the form and getting the result
        HtmlPage newPage = submitButton.click();

          // Getting the result as text

        String text = page.asNormalizedText();
        System.out.println(text);
    }
}
```
<p>But I am getting error message:</p>
```Exception in thread "main" com.gargoylesoftware.htmlunit.ElementNotFoundException: elementName=[*] attributeName=[id] attributeValue=[tsf]
    at com.gargoylesoftware.htmlunit.html.HtmlPage.getHtmlElementById(HtmlPage.java:1670)
    at Test.main(Test.java:20)
```

Since this tutorial is relatively old, the ID tsf might be outdated. However, if I check the form name from the google home page, I cant figure it out. Maybe I dont understand the meaning of the whole HtmlForm object. (I am completely new to this topic)

答: There is no element with ID tsf anymore. Best way to check it out is to go to the site and use Web Developer Tools of your browser (f12) mostly on every browsers. You can see the whole HTML document from there.</p>

Body:
I am trying to run the tutorial on here. The code looks like this:

public class Test {

    public static void main(String[] args) throws FailingHttpStatusCodeException, MalformedURLException, IOException {
        WebClient client = new WebClient(BrowserVersion.FIREFOX);
        HtmlPage page = client.getPage("https://google.com/");

        // Getting Form from google home page. tsf is the form name
        HtmlForm form = page.getHtmlElementById("tsf"); // Error occurs here

        form.getInputByName("q").setValueAttribute("test");

        // Creating a virtual submit button
        HtmlButton submitButton = (HtmlButton)page.createElement("button");
        submitButton.setAttribute("type", "submit");
        form.appendChild(submitButton);

          // Submitting the form and getting the result
        HtmlPage newPage = submitButton.click();

          // Getting the result as text

        String text = page.asNormalizedText();
        System.out.println(text);
    }
}

But I am getting error message:

Exception in thread "main" com.gargoylesoftware.htmlunit.ElementNotFoundException: elementName=[*] attributeName=[id] attributeValue=[tsf]
    at com.gargoylesoftware.htmlunit.html.HtmlPage.getHtmlElementById(HtmlPage.java:1670)
    at Test.main(Test.java:20)

Since this tutorial is relatively old, the ID tsf might be outdated. However, if I check the form name from the google home page, I cant figure it out. Maybe I dont understand the meaning of the whole HtmlForm object. (I am completely new to this topic)


问:
System.out.printIn cannot find symbol
Whenever I try to compile this Java program in the command prompt I get an error about System.out.printIn saying that javac cannot find symbol. System.out.print works just fine but System.out.printIn refuses to cooperate. I've posted the program and the compiler message below. Thanks for the help.

```<code>    public class BeerSong {
public static void main (String[] args) {
int beerNum = 99;
String word = "bottles";

while (beerNum > 0) {

  if (beerNum == 1) {
    word = "bottle"; //singular, ONE bottle
}

System.out.printIn(beerNum + " " + word + "of beer on the wall");
System.out.printIn(beerNum + " " + word + "of beer.");
System.out.printIn("Take one down.");
System.out.printIn("Pass it around.");
beerNum = beerNum - 1;

if (beerNum > 0) {
    System.out.printIn(beerNum + " " + word + " of beer on the wall");
}   else {
    System.out.printIn("No more bottles of beer on the wall");
} //end else
} //end while loop
} //end main method
} //end class
</code>```

```<code>C:\Users\Jesse\Desktop>javac BeerSong.java
BeerSong.java:12: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
    System.out.printIn(beerNum + " " + word + "of beer on the wall");
              ^
BeerSong.java:13: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
    System.out.printIn(beerNum + " " + word + "of beer.");
              ^
BeerSong.java:14: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
    System.out.printIn("Take one down.");
              ^
BeerSong.java:15: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
    System.out.printIn("Pass it around.");
              ^
BeerSong.java:19: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
        System.out.printIn(beerNum + " " + word + " of beer on the wall");
                  ^
BeerSong.java:21: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
            System.out.printIn("No more bottles of beer on the wall");
                      ^
6 errors
</code>```

答:
It should be System.out.println not System.out.printIn.

Use some kind of IDE (like Eclipse or NetBeans) to make sure that you can use methos in current context.

The problem here is copying the same line. Try avoiding copy/pase.

Title: System.out.printIn cannot find symbol

Body:
Whenever I try to compile this Java program in the command prompt I get an error about System.out.printIn saying that javac cannot find symbol. System.out.print works just fine but System.out.printIn refuses to cooperate. I've posted the program and the compiler message below. Thanks for the help.

    public class BeerSong {
public static void main (String[] args) {
int beerNum = 99;
String word = "bottles";

while (beerNum > 0) {

  if (beerNum == 1) {
    word = "bottle"; //singular, ONE bottle
}

System.out.printIn(beerNum + " " + word + "of beer on the wall");
System.out.printIn(beerNum + " " + word + "of beer.");
System.out.printIn("Take one down.");
System.out.printIn("Pass it around.");
beerNum = beerNum - 1;

if (beerNum > 0) {
    System.out.printIn(beerNum + " " + word + " of beer on the wall");
}   else {
    System.out.printIn("No more bottles of beer on the wall");
} //end else
} //end while loop
} //end main method
} //end class

C:\Users\Jesse\Desktop>javac BeerSong.java
BeerSong.java:12: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
    System.out.printIn(beerNum + " " + word + "of beer on the wall");
              ^
BeerSong.java:13: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
    System.out.printIn(beerNum + " " + word + "of beer.");
              ^
BeerSong.java:14: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
    System.out.printIn("Take one down.");
              ^
BeerSong.java:15: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
    System.out.printIn("Pass it around.");
              ^
BeerSong.java:19: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
        System.out.printIn(beerNum + " " + word + " of beer on the wall");
                  ^
BeerSong.java:21: cannot find symbol
symbol  : method printIn(java.lang.String)
location: class java.io.PrintStream
            System.out.printIn("No more bottles of beer on the wall");
                      ^
6 errors


答:
the problem is in the image you have to attach an image with fixed sizes and if you do not have a fixed size use: background-position: center center; background-size: cover; in this way the image will be spread all over the space without being repeated. If you have a still image, you only need width: 100%; and height: 100%; , the rest will work automatically.

body {
  background-color: hsl(233, 47%, 7%);
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 6em;
}
.all {
  background-color: hsl(244, 38%, 16%);
  width: 80em;
  height: 28em;
  border-radius: 0.725em;
  overflow: hidden;
  display: flex;
}
.bella {
  background-image: url(https://cdn.pixabay.com/photo/2021/08/25/20/42/field-6574455__340.jpg);
  height: 100%;
  background-repeat: no-repeat;
  width: 100%;
  background-position: center center;
  background-size: cover;
}
.writings {
  font-family: "Inter";
  display: flex;
  flex-direction: column;
  max-width: 30em;
  margin: 6em;
}
.writings h1 {
  font-weight: 700;
  color: white;
}
#viola {
  color: hsl(277, 64%, 61%);
}
.writings p {
  color: hsla(0, 0%, 100%, 0.75);
  font-weight: 400;
}
.figures {
  display: flex;
}
.figures h2 {
  font-weight: 700;
  color: white;
  font-family: "Inter";
}
.figures h5 {
  color: hsla(0, 0%, 100%, 0.6);
  text-transform: uppercase;
  font-family: "Lexend Deca";
  letter-spacing: 2px;
}
.fig1 {
  padding-right: 5em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="tutto"></div>
<div class="all">
  <div class="writings">
    <h1>Get <span id="viola">insights</span> that help your business grow.</h1>
    <p> Discover the benefits of data analytics and make better decisions regarding revenue, customer
      experience, and overall efficiency.</p>
    <div class="figures">
      <div class="fig1">
        <h2>10k+</h2>
        <h5> companies</h5>
      </div>
      <div class="fig1">
        <h2>1314</h2>
        <h5> templates</h5>
      </div>
      <div class="fig1">
        <h2>12M+</h2>
        <h5> queries</h5>
      </div>
    </div>
  </div>
  <div class="bella"></div>
</div>
</div></code>```

Body:
the problem is in the image you have to attach an image with fixed sizes and if you do not have a fixed size use: background-position: center center; background-size: cover; in this way the image will be spread all over the space without being repeated. If you have a still image, you only need width: 100%; and height: 100%; , the rest will work automatically.

body {
  background-color: hsl(233, 47%, 7%);
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 6em;
}
.all {
  background-color: hsl(244, 38%, 16%);
  width: 80em;
  height: 28em;
  border-radius: 0.725em;
  overflow: hidden;
  display: flex;
}
.bella {
  background-image: url(https://cdn.pixabay.com/photo/2021/08/25/20/42/field-6574455__340.jpg);
  height: 100%;
  background-repeat: no-repeat;
  width: 100%;
  background-position: center center;
  background-size: cover;
}
.writings {
  font-family: "Inter";
  display: flex;
  flex-direction: column;
  max-width: 30em;
  margin: 6em;
}
.writings h1 {
  font-weight: 700;
  color: white;
}
#viola {
  color: hsl(277, 64%, 61%);
}
.writings p {
  color: hsla(0, 0%, 100%, 0.75);
  font-weight: 400;
}
.figures {
  display: flex;
}
.figures h2 {
  font-weight: 700;
  color: white;
  font-family: "Inter";
}
.figures h5 {
  color: hsla(0, 0%, 100%, 0.6);
  text-transform: uppercase;
  font-family: "Lexend Deca";
  letter-spacing: 2px;
}
.fig1 {
  padding-right: 5em;
}

<div class="tutto"></div>
<div class="all">
  <div class="writings">
    <h1>Get <span id="viola">insights</span> that help your business grow.</h1>
    <p> Discover the benefits of data analytics and make better decisions regarding revenue, customer
      experience, and overall efficiency.</p>
    <div class="figures">
      <div class="fig1">
        <h2>10k+</h2>
        <h5> companies</h5>
      </div>
      <div class="fig1">
        <h2>1314</h2>
        <h5> templates</h5>
      </div>
      <div class="fig1">
        <h2>12M+</h2>
        <h5> queries</h5>
      </div>
    </div>
  </div>
  <div class="bella"></div>
</div>
</div>