问:
When will JAVA STACK throw OutOfMemory Error instead of StackOverFlowError, in STACK?
I read that both OutOfMemoryError and StackOverFlowError can happen in stack.
But I wonder when will OOM be thrown in stack?

Is it thrown when creating new object in stack? Then I guess this new object does not belong to a stack frame, otherwise SOF will be thrown.

Thank you very much for answering. I searched on google but did not find a related answer.

I'm very sorry for previous unclear abreviations!!

答:
I believe you are talking about OutOfMemoryError and StackOverflowError.

OutOfMemoryError happens when there is no more free space in the Heap for allocating a new Object. The rest of the space is occupied by strongly referenced objects. Garbage collection cannot reclaim the space those objects space. Objects and arrays are always allocated in the Heap, not in the Stack. (Scape Analysis/Scalar replacement/JIT may be an exception)

StackOverFlow happens when there is no more free space in the jvm stack. The stack stores local method variables and frames, which are created every method invocation (the usual error stacktrace for instance).

You can read further details about Heap and Stack in the JVM specification.

Heap

Stack


来源: stackexchange

问:
Template integrate in asp .net 6
I want to integrate a bootswatch theme in my ASP .NET MVC Core project. I am working with Dot net version 6. I can not integrate the template, the background always remains the same in my application. Can anyone suggest to me a proper way to integrate the template?</p>

答:
1. You can run npm init --yes, and install bootswatch with npm command.

2. Copy the node_modules folder, and paste into the wwwroot.

Please include the node_modules folder in your project.

3. Modify the _Layout.cshtml.

Test Result

For more details, you also can follow this video to learn.

Tips: The name in package.json can't same as bootswatch, otherwise you will fail to install bootswatch.

ContentLicense: CC BY-SA 4.0

Title: Template integrate in asp .net 6


问:
C++ Visual Studio 2010 not linking native static library
I am converting a C++ Visual Studio 2005 project to Visual Studio 2010, and I have used this guide in the process.
I have one issue left which is, that the linker does not link a native static library (it is not a .NET assembly but a third part library sqsapi32.lib). I have included the library sqsapi32.lib in the Properties->Configuration Properties->Linker->Input->Additional Dependencies, but the linker keep notifying the following warning:

```<code>warning LNK4248: unresolved typeref token (01000014) for 'SQLDA'; image may not run
</code>```

running the .exe file produces the following error: "The program can't start because sqsapi32.dll is missing from your computer".

How can I fix this? It worked using Visual Studio 2005.

答:
The warning and the error you've shown aren't necessarily linked (no pun intended!).

To get around the error, ensure the sqsapi32.dll is placed in the same location as the exe you're trying to run.

Good luck,

ContentLicense: CC BY-SA 3.0

Body:
I am converting a C++ Visual Studio 2005 project to Visual Studio 2010, and I have used this guide in the process.
I have one issue left which is, that the linker does not link a native static library (it is not a .NET assembly but a third part library sqsapi32.lib). I have included the library sqsapi32.lib in the Properties->Configuration Properties->Linker->Input->Additional Dependencies, but the linker keep notifying the following warning:

warning LNK4248: unresolved typeref token (01000014) for 'SQLDA'; image may not run

running the .exe file produces the following error: "The program can't start because sqsapi32.dll is missing from your computer".

How can I fix this? It worked using Visual Studio 2005.


问:
How to increase BI Server Cache Size in OBIEE12c
We are using OBIEE12c (12.2.0.4) for analytical reporting. In order to reduce "Cache Miss", we would like to increase the size of BI Server cache. It would be very helpful if anyone would help us by guiding us the way to increase BI server Cache size.</p>

答:
The following is the workaround the increase the size of BI server cache.

Step 1: Login to the Weblogic enterprise manager
(http://server-ip:9500/em)
Step 2: Click on Target Navigation

Step 3: Click on biinstance under Business Intelligence

Step 4: Click on Performance tab, under Configuration tab.

Step 5: Click on Lock and Edit the Configuration file

Step 6:  Tick "Cache Enable"

Step 7:  Now, change the size of BI server cache and then apply and activate changes.

Visit the link (https://www.learn-it-with-examples.com/datawarehouse-bigdata/bi/obiee/enable-disable-oracle-bi-server-cache.html) for more details.


问:
Why won't my nav lis display horizontally with floats?
I'm new to coding and trying to figure out why my nav li's will not display horizontally? I've tried a few things which I've noted in the code below.

The catch here is, I must use floats instead of flexbox.

header nav>* {
  float: left;
  width: 7%;
  margin: 0 5%;
  padding-bottom: 30px;
  list-style: none;
  text-decoration: none;
}

header nav ul li {
  width: 100px;
  float: right;
  display: block;
  text-decoration: none;
  /*margin-left: 2px;
  display: inline; not working*/
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <nav>
    Courses
    <form action="">
      <input type="text" placeholder="Search">
    </form>
    <img class="icon" src="#">
    <h2>Tech Academy</h2>
    <ul id="SideBar">
      <li>Donate</li>
      <li>Login</li>
      <li>Sign up</li>
    </ul>
  </nav>
</header></code>```

I have tried changing the specificity to a class or id and that hasn't fixed anything. I should also note that 'text-decoration' is not working for the li but is working for the a 'courses'? * border: box-sizing is also at the top of the css sheet.

This is what it looks like on the browser

I am very new to coding and this one has had me stumped for hours. T

答:
Use this on css.....</p>
```<code>#SideBar{
display: flex;
}
</code>```

Body:
I'm new to coding and trying to figure out why my nav li's will not display horizontally? I've tried a few things which I've noted in the code below.

The catch here is, I must use floats instead of flexbox.

header nav>* {
  float: left;
  width: 7%;
  margin: 0 5%;
  padding-bottom: 30px;
  list-style: none;
  text-decoration: none;
}

header nav ul li {
  width: 100px;
  float: right;
  display: block;
  text-decoration: none;
  /*margin-left: 2px;
  display: inline; not working*/
}

    Courses
    <form action="">
      <input type="text" placeholder="Search">
    </form>

Tech Academy

Donate

Login

Sign up

I have tried changing the specificity to a class or id and that hasn't fixed anything. I should also note that 'text-decoration' is not working for the li but is working for the a 'courses'? * border: box-sizing is also at the top of the css sheet.

This is what it looks like on the browser

I am very new to coding and this one has had me stumped for hours. T

Body:
Use this on css.....

#SideBar{
display: flex;
}


问:
#await blocks in an #each loop and DOM refresh performance issue
I'm looping through items I retrieved from a Sveltekit store, and retrieving additional information asynchronously for each of the iterated items.

The simplified code looks like:

        {#each $order.itemIDs as itemID}
          {#await calcItemPrice(itemID)}
          {:then price}
            {#await itemFor(itemID)}
            {:then item}
              <OrderItem itemID={item._id} description={item.description} price={price} />
            {/await}
          {/await}
        {/each}
```

Separately, the UI allows to add more entries (with update) to $order.itemIDs, which triggers a redrawing of the DOM elements in the each loop. The key problems with this are:

Redrawing the #each loop every time an item is added means remaking the asynchronous calls for each of the items every time. This clearly impact performance as more and more items are added.

During this (slow) redrawing, DOM elements in the #each flash as they disappear from a moment and reappear once all fetch queries have been performed.

I think my question is two-fold:

How can I make it so that adding a new itemID to $order.itemIDs will not trigger a redraw of all the rendered elements, but instead just append the new element to the DOM?

At what time should I run my asynchronous call to improve rendering performance? (I have a feeling than running at rendering time is suboptimal)

答:
A first thing to do would be to use a keyed each block instead, this will make that only the items that have changed actually get re-rendered:

```<code>{#each $order.itemIDs as itemID (itemID)}
</code>```

Make sure the ID you use is unique, the above is just an example!

That said, I would not use an await block in a loop, I believe that is just asking for problems down the line.  See if it can be possible to load those items elsewhere instead, perhaps with an await block for the very first run.

How to implement this would of course heavily depend on your use case and requirements, one idea could be to have another array that is populated from the store:

let items = []

async function loadItems(stored) {
  const changed = stored.filter(s => !items.some(s => s.id == s));
  const result = await Promise.all(changed.map(async => calcsHere))
  items = [...items, ...result];
}

$: loadItems($order.itemIDs)
```

The above code declares an array items and a function loadItems that will run every time the store changes.
What the function itself does is:

filter out the items that are new (to not refetch them)

fire off fetches for all new items simultaneously and wait for all them to return

add the new items to the old items

(Note that I might have plenty of errors in that code, it's just a general concept)

One downside of this is that you do cannot have a 'loading' indicator, although you could perhaps do that by pushing the new items to the array with some kind of 'loading' flag and then overwriting them.

Body:
I'm looping through items I retrieved from a Sveltekit store, and retrieving additional information asynchronously for each of the iterated items.

The simplified code looks like:

        {#each $order.itemIDs as itemID}
          {#await calcItemPrice(itemID)}
          {:then price}
            {#await itemFor(itemID)}
            {:then item}
              <OrderItem itemID={item._id} description={item.description} price={price} />
            {/await}
          {/await}
        {/each}

Separately, the UI allows to add more entries (with update) to $order.itemIDs, which triggers a redrawing of the DOM elements in the each loop. The key problems with this are:

Redrawing the #each loop every time an item is added means remaking the asynchronous calls for each of the items every time. This clearly impact performance as more and more items are added.

During this (slow) redrawing, DOM elements in the #each flash as they disappear from a moment and reappear once all fetch queries have been performed.

I think my question is two-fold:

How can I make it so that adding a new itemID to $order.itemIDs will not trigger a redraw of all the rendered elements, but instead just append the new element to the DOM?

At what time should I run my asynchronous call to improve rendering performance? (I have a feeling than running at rendering time is suboptimal)

Body:
A first thing to do would be to use a keyed each block instead, this will make that only the items that have changed actually get re-rendered:

{#each $order.itemIDs as itemID (itemID)}

Make sure the ID you use is unique, the above is just an example!

That said, I would not use an await block in a loop, I believe that is just asking for problems down the line.  See if it can be possible to load those items elsewhere instead, perhaps with an await block for the very first run.

How to implement this would of course heavily depend on your use case and requirements, one idea could be to have another array that is populated from the store:

let items = []

async function loadItems(stored) {
  const changed = stored.filter(s => !items.some(s => s.id == s));
  const result = await Promise.all(changed.map(async => calcsHere))
  items = [...items, ...result];
}

$: loadItems($order.itemIDs)

The above code declares an array items and a function loadItems that will run every time the store changes.
What the function itself does is:

filter out the items that are new (to not refetch them)

fire off fetches for all new items simultaneously and wait for all them to return

add the new items to the old items

(Note that I might have plenty of errors in that code, it's just a general concept)

One downside of this is that you do cannot have a 'loading' indicator, although you could perhaps do that by pushing the new items to the array with some kind of 'loading' flag and then overwriting them.


答:
First of all, spacings between attributes in html files have no effect at all on the browser display, and same for spacing in css files.

The second thing, I'm not sure why you don't want to use flex (it's handy here - you set the display of the parent attribute (ul) to display: flex; flex-direction: row; and it will do the trick).

But if you don't want to use it, there are 2 other tricks:

#1

ul {
    display: contents; /* this will make the parent act like it doesn't exist - and then do whatever you want with the children*/
}

li {
    display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="SideBar">
    <li>Donate</li>
    <li>Login</li>
    <li>Sign up</li>
</ul></code>```

#2 grid

ul {
    display: grid;
    grid-template-columns: max-content max-content max-content; /*instaed of max-content, you can assign the width you want for each li*/
}

li {
    margin : 5px;
    list-style: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="SideBar">
    <li>Donate</li>
    <li>Login</li>
    <li>Sign up</li>
</ul></code>```

Title: Why won't my nav lis display horizontally with floats?

Body:
First of all, spacings between attributes in html files have no effect at all on the browser display, and same for spacing in css files.

The second thing, I'm not sure why you don't want to use flex (it's handy here - you set the display of the parent attribute (ul) to display: flex; flex-direction: row; and it will do the trick).

But if you don't want to use it, there are 2 other tricks:

#1

ul {
    display: contents; /* this will make the parent act like it doesn't exist - and then do whatever you want with the children*/
}

li {
    display: inline-block;
}

<ul id="SideBar">
    <li><a href="#">Donate</a></li>
    <li><a href="#">Login</a></li>
    <li><a href="#">Sign up</a></li>
</ul>

#2 grid

ul {
    display: grid;
    grid-template-columns: max-content max-content max-content; /*instaed of max-content, you can assign the width you want for each li*/
}

li {
    margin : 5px;
    list-style: none;
}

<ul id="SideBar">
    <li><a href="#">Donate</a></li>
    <li><a href="#">Login</a></li>
    <li><a href="#">Sign up</a></li>
</ul>


问:
TypeError: data.map is not a function i am getting an error while api call and an error called id is not defined
i want to navigate to other page while clicking on the button and while clicking the button i also have to call an api.but its not working can anyone tell me whats the problem
[its the api link] [1]: https://api.tvmaze.com/shows/$%7Bid%7D its my contact component</p>
```<code>import React,{useState,useEffect} from 'react';
import axios from 'axios';

export const Contact = () => {
  const url = `https://api.tvmaze.com/shows/${id}`;

  const [data, setData] = useState([]);

  useEffect(() => {
    axios.get(url).then((json) => setData(json.data));
  }, []);

  const renderTable = () => {
    return data.map((user, i) => {
     return (
     <tr key={i}>
      <td>{user.show?.name}</td>
      <td>{user.show?.language}</td>
      <td>{user.show?.genres}</td>
      <td>{user.show?.runtime}</td>
      <td>{user.show?.premiered}</td>
      <td>{user.show?.rating?.average}</td>
      <td>{user.show?.network?.country?.name}</td>
      <td>
        <img src={user?.show?.image?.medium} alt="poster" />
      </td>
    </tr>
      );
    });
  };

  return (
    <div>
      <table className=" table table-bordered">
        <thead>
          <tr>
            <th scope="col">Name</th>
            <th scope="col">language</th>
            <th scope="col">genres</th>
            <th scope="col">runtime</th>
            <th scope="col">premiered</th>
            <th scope="col">Rating</th>
            <th scope="col">country name</th>
            <th scope="col">image</th>
          </tr>
        </thead>
        <tbody>{renderTable()}</tbody>
      </table>
    </div>
  );
};
</code>```

答:
I think the problem is in api and also the id here

const url = `https://api.tvmaze.com/shows/${id}

where have you declared the id ? and to make sure that the data is coming fine before using it first console.log() the response data and see what you get and open the network tab to see the reason of the error clearly

Body:
i want to navigate to other page while clicking on the button and while clicking the button i also have to call an api.but its not working can anyone tell me whats the problem
[its the api link] [1]: https://api.tvmaze.com/shows/$%7Bid%7D its my contact component

import React,{useState,useEffect} from 'react';
import axios from 'axios';

export const Contact = () => {
  const url = `https://api.tvmaze.com/shows/${id}`;

  const [data, setData] = useState([]);

  useEffect(() => {
    axios.get(url).then((json) => setData(json.data));
  }, []);

  const renderTable = () => {
    return data.map((user, i) => {
     return (

      {user.show?.name}
      {user.show?.language}
      {user.show?.genres}
      {user.show?.runtime}
      {user.show?.premiered}
      {user.show?.rating?.average}
      {user.show?.network?.country?.name}

      );
    });
  };

  return (

            Name
            language
            genres
            runtime
            premiered
            Rating
            country name
            image

{renderTable()}

  );
};


问:
Neo4j & JPype Installation Issue
I use Ubuntu 10.10 and before continuing with the installation, I installed JPype and openjdk-6-jdk & all its dependencies using synaptic.

I proceeded with the install of Neo4j & Python as mentioned on:

```<code>http://components.neo4j.org/neo4j.py/0.1-SNAPSHOT/
</code>```

But when I did

```<code>sudo python setup.py install
</code>```

in the neo4j-python folder, it gave the following error output

```<code>Traceback (most recent call last):
  File "setup.py", line 146, in <module>
    main()
  File "setup.py", line 134, in main
    args[attr] = pom[attr]
  File "/home/aman/Softwares/neo4j-python/pom.py", line 58, in __getitem__
    element)
  File "/home/aman/Softwares/neo4j-python/pom.py", line 57, in <lambda>
    return self.pattern.sub(lambda match:self[match.groupdict()['var']],
  File "/home/aman/Softwares/neo4j-python/pom.py", line 54, in __getitem__
    element = self.parent[path]
  File "/home/aman/Softwares/neo4j-python/pom.py", line 91, in __getitem__
    return replacement.get(path, lambda s,x:x)(self, self.__pom[path])
  File "/home/aman/Softwares/neo4j-python/pom.py", line 56, in __getitem__
    raise KeyError(path)
KeyError: 'project.artifactId'
</code>```

Any idea what am I doing wrong?

答:
This solution might work: https://gist.github.com/809425

For other ways of using Neo4j with Python see http://www.delicious.com/neo4j/drivers+python and maybe http://www.delicious.com/neo4j/python to get more information.

Title: Neo4j & JPype Installation Issue

Body:
I use Ubuntu 10.10 and before continuing with the installation, I installed JPype and openjdk-6-jdk & all its dependencies using synaptic.

I proceeded with the install of Neo4j & Python as mentioned on:

http://components.neo4j.org/neo4j.py/0.1-SNAPSHOT/

But when I did

sudo python setup.py install

in the neo4j-python folder, it gave the following error output

Traceback (most recent call last):
  File "setup.py", line 146, in <module>
    main()
  File "setup.py", line 134, in main
    args[attr] = pom[attr]
  File "/home/aman/Softwares/neo4j-python/pom.py", line 58, in __getitem__
    element)
  File "/home/aman/Softwares/neo4j-python/pom.py", line 57, in <lambda>
    return self.pattern.sub(lambda match:self[match.groupdict()['var']],
  File "/home/aman/Softwares/neo4j-python/pom.py", line 54, in __getitem__
    element = self.parent[path]
  File "/home/aman/Softwares/neo4j-python/pom.py", line 91, in __getitem__
    return replacement.get(path, lambda s,x:x)(self, self.__pom[path])
  File "/home/aman/Softwares/neo4j-python/pom.py", line 56, in __getitem__
    raise KeyError(path)
KeyError: 'project.artifactId'

Any idea what am I doing wrong?


问:
I tried to use top keyword but not working
I have not used top so far in PG admin.. Now while going through a YouTube series I came to know about this top keyword..

```<code>select distinct top 2 salary from salary order by salary desc
</code>```

but it didn't work. Is limit alternate for top and what are the difference that's there in Postgre DB

Can I use this as alternate,

```<code>select salary from salary order by salary desc limit 2
</code>```

答:
Use this :</p>
```<code>select salary
    from salary
    group by salary
    order by salary  desc
    limit 2
</code>```

Body:
I have not used top so far in PG admin.. Now while going through a YouTube series I came to know about this top keyword..

select distinct top 2 salary from salary order by salary desc

but it didn't work. Is limit alternate for top and what are the difference that's there in Postgre DB

Can I use this as alternate,

select salary from salary order by salary desc limit 2

Body:
Use this :

select salary
    from salary
    group by salary
    order by salary  desc
    limit 2


问:
Java input design
I am starting to learn Java, could you please advise if adding an underline in input (System.in) is possible?

sampleDesign

```<code>package sampleDesign;
import java.util.Scanner;
class sampleDesign {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        System.out.println("-----------Label 1--------------");
        System.out.print("Design Input: " );
        String input1 = scan.nextLine();
    }
}
</code>```

答:
Can you?  Yes.  Should you, probably not.

```<code>import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        System.out.print("Name: __________");
        System.out.print("\b");
        System.out.print("\b");
        System.out.print("\b");
        System.out.print("\b");
        System.out.print("\b");
        System.out.print("\b");
        System.out.print("\b");
        System.out.print("\b");
        System.out.print("\b");
        System.out.print("\b");
        Scanner scanner = new Scanner(System.in);
        scanner.nextLine();
    }
}
</code>```

So, immediate problems, it's a pain to type and it won't restrict the user from input more characters.

Java's "terminal" support is pretty rudimentary.  If you want any kind of "fancy" looking "terminal" inputs, you'd probably need to find a decent "curses" implementation/binding

What's a good Java, curses-like, library for terminal applications?

Terminal and ncurses Java libraries

webfolderio/curses4j

as a few ... and no, I've not used any of them

Title: Java input design

Body:
I am starting to learn Java, could you please advise if adding an underline in input (System.in) is possible?

sampleDesign

package sampleDesign;
import java.util.Scanner;
class sampleDesign {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        System.out.println("-----------Label 1--------------");
        System.out.print("Design Input: " );
        String input1 = scan.nextLine();
    }
}

Body:
Can you?  Yes.  Should you, probably not.

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        System.out.print("Name: __________");
        System.out.print("\b");
        System.out.print("\b");
        System.out.print("\b");
        System.out.print("\b");
        System.out.print("\b");
        System.out.print("\b");
        System.out.print("\b");
        System.out.print("\b");
        System.out.print("\b");
        System.out.print("\b");
        Scanner scanner = new Scanner(System.in);
        scanner.nextLine();
    }
}

So, immediate problems, it's a pain to type and it won't restrict the user from input more characters.

Java's "terminal" support is pretty rudimentary.  If you want any kind of "fancy" looking "terminal" inputs, you'd probably need to find a decent "curses" implementation/binding

What's a good Java, curses-like, library for terminal applications?

Terminal and ncurses Java libraries

webfolderio/curses4j

as a few ... and no, I've not used any of them


问:
Add a future date manually to a Pyspark column
Need to add a pyspark column with future_date: '9999-12-31' to a pyspark column

Tried:

```<code>.withColumn('valid_to_date', F.to_date(F.lit('9999-12-31'), 'yyyy-MM-dd'))
</code>```

Error:

AssertionError: col should be Column

Body:
Need to add a pyspark column with future_date: '9999-12-31' to a pyspark column

Tried:

.withColumn('valid_to_date', F.to_date(F.lit('9999-12-31'), 'yyyy-MM-dd'))

Error:

AssertionError: col should be Column

Body:
Working Perfectly fine , in my case , Can you share the entire stacktrace

d = {
        'date_col':['10-Oct-15', '11-Oct-17', '2-Feb-20', '02-Feb-20']
    }

sparkDF = sql.createDataFrame(pd.DataFrame(d))

sparkDF = sparkDF.withColumn('valid_to_date', F.to_date(F.lit('9999-12-31'), 'yyyy-MM-dd'))

sparkDF.show()

+---------+-------------+
| date_col|valid_to_date|
+---------+-------------+
|10-Oct-15|   9999-12-31|
|11-Oct-17|   9999-12-31|
| 2-Feb-20|   9999-12-31|
|02-Feb-20|   9999-12-31|
+---------+-------------+


问:
Showing "Launching Emulator" in a small window but emulator has already started and running
I opened virtual device list and clicked one of it to start. A small window popped up saying "Launching Emulator".
After sometimes later the emulator showed up, cool booted and working fine.

But the small window still says "Launching Emulator/Starting AVD". It doesn't have any close icon to close it.
Other background process disappeared after they completed but "Launching Emulator/Starting AVD" still stays there.
https://ibb.co/s14jkDZ
Current AS version 2021.1.1 Patch 1
If its a duplicate question, let us know

答: I think it is bug from studio.. I also face the same issue... To fix the problem, I just go to the task manager and under the Android task sheet, close that service by using End task..</p>


问:
Validate post sub item in AdonisJs
Validate post sub item in AdonisJs.

I can't validate a sub item of the post. I believe it is not found.

I need to validate "codigo" that is inside "nfe"

Request

```<code>{
  nfe: {
    codigo: '56456',
    motorista: 'NOME',
    contato: 'CONTATO',
    casa: true
  },
  fornecedor: 'ALIMENTOS',
  lab: 'sim',
}
</code>```

Controller

```<code>await request.validate(NfeValidator)
</code>```

Validator

```<code>public schema = schema.create({
    'nfe.codigo': schema.string({trim: true}, [rules.unique({table: 'nfes', column: 'codigo'})])
  })
</code>```

答: A field was included in the root of the request post to be checked.</p>

Title: Validate post sub item in AdonisJs

Body:
Validate post sub item in AdonisJs.

I can't validate a sub item of the post. I believe it is not found.

I need to validate "codigo" that is inside "nfe"

Request

{
  nfe: {
    codigo: '56456',
    motorista: 'NOME',
    contato: 'CONTATO',
    casa: true
  },
  fornecedor: 'ALIMENTOS',
  lab: 'sim',
}

Controller

await request.validate(NfeValidator)

Validator

public schema = schema.create({
    'nfe.codigo': schema.string({trim: true}, [rules.unique({table: 'nfes', column: 'codigo'})])
  })


问:
SQL MAX of multiple columns?
How do you return 1 value per row of the max of several columns:

TableName

```<code>[Number, Date1, Date2, Date3, Cost]
</code>```

I need to return something like this:

```<code>[Number, Most_Recent_Date, Cost]
</code>```

Query?

答:
This is an old answer and broken in many way.

See https://stackoverflow.com/a/6871572/194653 which has way more upvotes and works with sql server 2008+ and handles nulls, etc.

Original but problematic answer:

Well, you can use the CASE statement:

```<code>SELECT
    CASE
        WHEN Date1 >= Date2 AND Date1 >= Date3 THEN Date1
        WHEN Date2 >= Date1 AND Date2 >= Date3 THEN Date2
        WHEN Date3 >= Date1 AND Date3 >= Date2 THEN Date3
        ELSE                                        Date1
    END AS MostRecentDate
</code>```

OwnerDisplayName: BenBruscella

Title: SQL MAX of multiple columns?

Body:
How do you return 1 value per row of the max of several columns:

TableName

[Number, Date1, Date2, Date3, Cost]

I need to return something like this:

[Number, Most_Recent_Date, Cost]

Query?

LastEditorDisplayName: Nigel Campbell

Body:
This is an old answer and broken in many way.

See https://stackoverflow.com/a/6871572/194653 which has way more upvotes and works with sql server 2008+ and handles nulls, etc.

Original but problematic answer:

Well, you can use the CASE statement:

SELECT
    CASE
        WHEN Date1 >= Date2 AND Date1 >= Date3 THEN Date1
        WHEN Date2 >= Date1 AND Date2 >= Date3 THEN Date2
        WHEN Date3 >= Date1 AND Date3 >= Date2 THEN Date3
        ELSE                                        Date1
    END AS MostRecentDate

OwnerDisplayName: lassevk


问:
What is Shadow Memory?
What is Shadow Memory? Can SO briefly shed light on how memory profiling tools use it?</p>

答:
You either mean general term: http://en.wikipedia.org/wiki/Shadow_memory

Or particular feature used in PC, which is better knowns as "shadow RAM": http://en.wikipedia.org/wiki/RAM#Shadow_RAM

OwnerDisplayName: Prabhu. S

ContentLicense: CC BY-SA 2.5

Title: What is Shadow Memory?

OwnerDisplayName: vartec


问:
Chaining a new object instance in PHP
We have the following chaining:

```<code>$obj = new obj();
$obj->setname($params1)->setcolor($params2);
</code>```

Is there a way to do the same chaining on one line, without creating a dummy function?

P.S: I want to skip the part where the constructor itself is on a new line. I want to construct the object and start the chaining on the same line. Something like this:

```<code>$obj = new obj()->setname($params1)->setcolor($params2);
</code>```

答:
Sure is. Simplt return this at the end of each function, to return the object so your next chained function can use it.

```<code><?php
    class A
    {
        public __constructor()
        { .... }

        public function B($params)
        {
            //Processing
            return this;
        }

        public function C($params)
        {
            //Processing
            return this;
        }

        public function D($params)
        {
            //Processing
        }
    }
    $O = new A();
    $O->B($params)->C($params)->D($params); //Will work because B and C return this
    $O->B($params)->D($params)->C($params); //WILL NOT work because D doesn't return this
?>
</code>```

Title: Chaining a new object instance in PHP

Body:
We have the following chaining:

$obj = new obj();
$obj->setname($params1)->setcolor($params2);

Is there a way to do the same chaining on one line, without creating a dummy function?

P.S: I want to skip the part where the constructor itself is on a new line. I want to construct the object and start the chaining on the same line. Something like this:

$obj = new obj()->setname($params1)->setcolor($params2);

Body:
Sure is. Simplt return this at the end of each function, to return the object so your next chained function can use it.

<?php
    class A
    {
        public __constructor()
        { .... }

        public function B($params)
        {
            //Processing
            return this;
        }

        public function C($params)
        {
            //Processing
            return this;
        }

        public function D($params)
        {
            //Processing
        }
    }
    $O = new A();
    $O->B($params)->C($params)->D($params); //Will work because B and C return this
    $O->B($params)->D($params)->C($params); //WILL NOT work because D doesn't return this
?>


问:
TypeError: int() argument must be a string, a bytes-like object or a number, not 'TextInput'
I am developing a Kivy password generator. The user is required to input a number (digit) into the app for password generate depending on how many characters are intended. Then, the app will generate a random character from the randint, finally, the output will be displayed into the output entry for a copy to the click board. Following are my code:

password_generator.py

```<code>from kivy.app import App
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.core.window import Window

from random  import randint

Builder.load_file('password_generator.kv')

Window.size = (350, 600)

class MainApp(App):
    title='Password Generator'
    def build(self):
        Window.clearcolor = (255/255, 255/255, 0, 1)
        return Mylayout()

    def password(self):

        self.root.ids.output_entry = ''

        pw_length = int(self.root.ids.input_entry)

        my_password = ''

        for x in range(pw_length):
            my_password += chr(randint(33, 126))

        self.root.ids.output_entry = my_password

    def clip_board(self):
        self.root.clipboard_clear()

        self.root.clipboard_append(self.root.ids.output_entry)

    def delete(self):
        self.root.ids.input_entry = ''
        self.root.ids.output_entry = ''

class Mylayout(Widget):
    pass

if __name__ == '__main__':
    MainApp().run()
</code>```

password_generator.kv

```<code>#:import Factory kivy.factory.Factory

<MyLayout>

    FloatLayout:

        Label:
            id: label_frame
            text: 'How Many Characters?'
            pos_hint: {'x': .8, 'y':5}
            size_hint: (2, .4)
            color: (0, 0, 0, 1)
            font_size: 24

        TextInput:
            id: input_entry
            text: ''
            multiline: False
            font_family: 'Helvatica'
            font_size: 24
            pos_hint: {'x': .8, 'y':4.5}
            size_hint: (2, .4)
            halign: "center"
            focus: True
            color: 'black'

        Button:
            text:'Generate A Strong Password'
            on_press: app.password()
            pos_hint: {'x': .8, 'y':3.8}
            size_hint: (2, .4)
            font_size: 15

        TextInput:
            id: output_entry
            text: ''
            multiline: False
            font_family: 'Helvatica'
            font_size: 24
            pos_hint: {'x': .8, 'y':3}
            size_hint: (2, .4)
            halign: "center"
            focus: True
            color: 'black'
            background_color : (255/255, 255/255, 0, 1)
            #foreground_color:  self.background_color
            color : 'black'

        Button:
            text : 'Copy To Clickboard'
            on_release: Factory.MyPopup().open(),
            on_press: app.clip_board()
            pos_hint: {'x': .8, 'y':2.5}
            size_hint: (2, .4)
            font_size: 15

        Button:
            text : "Reset"
            on_press : app.delete()
            pos_hint: {'x': .8, 'y':1.5}
            size_hint: (2, .4)
            font_size: 15

<MyPopup@Popup>
    # auto_dismiss: False
    auto_dismiss: True
    size_hint: 0.6, 0.2
    pos_hint: {'x':0.2, 'top':0.6}

    title: "Message Informed"

    BoxLayout
        orientation: "vertical"
        size: root.width, root.height
        Label:
            text: "Password Copied!"
            font_size: 15
        Button:
            text: "Close!"
            font_size: 15
            on_release: root.dismiss()
</code>```

When I click Generate Strong Password button and was required to output a random password character in the output entry, however, the following error was incurred:

```<code>Traceback (most recent call last):
   File "c:\Users\Kelvin Loh\Documents\kivyMD\password_generator.py", line 53, in <module>
     MainApp().run()
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\app.py", line 950, in run
     runTouchApp()
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\base.py", line 582, in runTouchApp
     EventLoop.mainloop()
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\base.py", line 347, in mainloop
     self.idle()
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\base.py", line 391, in idle
     self.dispatch_input()
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\base.py", line 342, in dispatch_input
     post_dispatch_input(*pop(0))
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\base.py", line 248, in post_dispatch_input
     listener.dispatch('on_motion', etype, me)
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\core\window\__init__.py", line 1412, in on_motion
     self.dispatch('on_touch_down', me)
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\core\window\__init__.py", line 1428, in on_touch_down
     if w.dispatch('on_touch_down', touch):
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\uix\widget.py", line 545, in on_touch_down
     if child.dispatch('on_touch_down', touch):
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\uix\widget.py", line 545, in on_touch_down
     if child.dispatch('on_touch_down', touch):
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\uix\behaviors\button.py", line 151, in on_touch_down
     self.dispatch('on_press')
   File "kivy\_event.pyx", line 705, in kivy._event.EventDispatcher.dispatch
   File "kivy\_event.pyx", line 1248, in kivy._event.EventObservers.dispatch
   File "kivy\_event.pyx", line 1132, in kivy._event.EventObservers._dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\lang\builder.py", line 57, in custom_callback
     exec(__kvlang__.co_value, idmap)
   File "C:\Users\Kelvin Loh\Documents\kivyMD\password_generator.kv", line 30, in <module>
     on_press: app.password()
   File "c:\Users\Kelvin Loh\Documents\kivyMD\password_generator.py", line 24, in password
     pw_length = int(self.root.ids.input_entry)
   File "kivy\weakproxy.pyx", line 254, in kivy.weakproxy.WeakProxy.__int__
 TypeError: int() argument must be a string, a bytes-like object or a number, not 'TextInput'
</code>```

How to resolve?

答:
Try changing pw_length in your password() function to:

```<code>pw_length = int(self.root.ids.input_entry.text or 0)
</code>```

input_entry is a TextInput which can't be converted to an int. I think you want to convert its value (input_entry.text) to an int, not the widget itself. To do that, change the pw_length = ... line in password() method as above.

Body:
I am developing a Kivy password generator. The user is required to input a number (digit) into the app for password generate depending on how many characters are intended. Then, the app will generate a random character from the randint, finally, the output will be displayed into the output entry for a copy to the click board. Following are my code:

password_generator.py

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.core.window import Window

from random  import randint

Builder.load_file('password_generator.kv')

Window.size = (350, 600)

class MainApp(App):
    title='Password Generator'
    def build(self):
        Window.clearcolor = (255/255, 255/255, 0, 1)
        return Mylayout()

    def password(self):

        self.root.ids.output_entry = ''

        pw_length = int(self.root.ids.input_entry)

        my_password = ''

        for x in range(pw_length):
            my_password += chr(randint(33, 126))

        self.root.ids.output_entry = my_password

    def clip_board(self):
        self.root.clipboard_clear()

        self.root.clipboard_append(self.root.ids.output_entry)

    def delete(self):
        self.root.ids.input_entry = ''
        self.root.ids.output_entry = ''

class Mylayout(Widget):
    pass

if __name__ == '__main__':
    MainApp().run()

password_generator.kv

#:import Factory kivy.factory.Factory

<MyLayout>

    FloatLayout:

        Label:
            id: label_frame
            text: 'How Many Characters?'
            pos_hint: {'x': .8, 'y':5}
            size_hint: (2, .4)
            color: (0, 0, 0, 1)
            font_size: 24

        TextInput:
            id: input_entry
            text: ''
            multiline: False
            font_family: 'Helvatica'
            font_size: 24
            pos_hint: {'x': .8, 'y':4.5}
            size_hint: (2, .4)
            halign: "center"
            focus: True
            color: 'black'

        Button:
            text:'Generate A Strong Password'
            on_press: app.password()
            pos_hint: {'x': .8, 'y':3.8}
            size_hint: (2, .4)
            font_size: 15

        TextInput:
            id: output_entry
            text: ''
            multiline: False
            font_family: 'Helvatica'
            font_size: 24
            pos_hint: {'x': .8, 'y':3}
            size_hint: (2, .4)
            halign: "center"
            focus: True
            color: 'black'
            background_color : (255/255, 255/255, 0, 1)
            #foreground_color:  self.background_color
            color : 'black'

        Button:
            text : 'Copy To Clickboard'
            on_release: Factory.MyPopup().open(),
            on_press: app.clip_board()
            pos_hint: {'x': .8, 'y':2.5}
            size_hint: (2, .4)
            font_size: 15

        Button:
            text : "Reset"
            on_press : app.delete()
            pos_hint: {'x': .8, 'y':1.5}
            size_hint: (2, .4)
            font_size: 15

<MyPopup@Popup>
    # auto_dismiss: False
    auto_dismiss: True
    size_hint: 0.6, 0.2
    pos_hint: {'x':0.2, 'top':0.6}

    title: "Message Informed"

    BoxLayout
        orientation: "vertical"
        size: root.width, root.height
        Label:
            text: "Password Copied!"
            font_size: 15
        Button:
            text: "Close!"
            font_size: 15
            on_release: root.dismiss()

When I click Generate Strong Password button and was required to output a random password character in the output entry, however, the following error was incurred:

Traceback (most recent call last):
   File "c:\Users\Kelvin Loh\Documents\kivyMD\password_generator.py", line 53, in <module>
     MainApp().run()
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\app.py", line 950, in run
     runTouchApp()
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\base.py", line 582, in runTouchApp
     EventLoop.mainloop()
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\base.py", line 347, in mainloop
     self.idle()
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\base.py", line 391, in idle
     self.dispatch_input()
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\base.py", line 342, in dispatch_input
     post_dispatch_input(*pop(0))
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\base.py", line 248, in post_dispatch_input
     listener.dispatch('on_motion', etype, me)
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\core\window\__init__.py", line 1412, in on_motion
     self.dispatch('on_touch_down', me)
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\core\window\__init__.py", line 1428, in on_touch_down
     if w.dispatch('on_touch_down', touch):
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\uix\widget.py", line 545, in on_touch_down
     if child.dispatch('on_touch_down', touch):
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\uix\widget.py", line 545, in on_touch_down
     if child.dispatch('on_touch_down', touch):
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\uix\behaviors\button.py", line 151, in on_touch_down
     self.dispatch('on_press')
   File "kivy\_event.pyx", line 705, in kivy._event.EventDispatcher.dispatch
   File "kivy\_event.pyx", line 1248, in kivy._event.EventObservers.dispatch
   File "kivy\_event.pyx", line 1132, in kivy._event.EventObservers._dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\lang\builder.py", line 57, in custom_callback
     exec(__kvlang__.co_value, idmap)
   File "C:\Users\Kelvin Loh\Documents\kivyMD\password_generator.kv", line 30, in <module>
     on_press: app.password()
   File "c:\Users\Kelvin Loh\Documents\kivyMD\password_generator.py", line 24, in password
     pw_length = int(self.root.ids.input_entry)
   File "kivy\weakproxy.pyx", line 254, in kivy.weakproxy.WeakProxy.__int__
 TypeError: int() argument must be a string, a bytes-like object or a number, not 'TextInput'

How to resolve?

Body:
Try changing pw_length in your password() function to:

pw_length = int(self.root.ids.input_entry.text or 0)

input_entry is a TextInput which can't be converted to an int. I think you want to convert its value (input_entry.text) to an int, not the widget itself. To do that, change the pw_length = ... line in password() method as above.


问:
Enum.TryParse doesn't accept my out parameter as an object
I have the following line:

var parseSortField = (BasicProfileSortableFields?)Enum.TryParse(typeof(BasicProfileSortableFields?), sortOptions.SortColumn, out BasicProfileSortableFields? sortField);

Around the out parameter, I'm getting an error that says

Argument 3: cannot convert from 'out Services.Models.BasicProfileSortableFields?' to 'out object?'

Regular parsing works but I'm trying to catch a scenario where my string is not in the mentioned enum. Also the enum I'm referencing is from a nuget package and not actually written by me if that helps.

答:
nullable enums can's be handled by Enum.TryParse

workaround: handle the null case with a ?: ternary conditional operator

```<code>BasicProfileSortableFields temp;
BasicProfileSortableFields? parseSortField = Enum.TryParse<BasicProfileSortableFields>(sortOptions.SortColumn, out temp) ? (BasicProfileSortableFields?)temp : null);
</code>```

Body:
nullable enums can's be handled by Enum.TryParse

workaround: handle the null case with a ?: ternary conditional operator

BasicProfileSortableFields temp;
BasicProfileSortableFields? parseSortField = Enum.TryParse<BasicProfileSortableFields>(sortOptions.SortColumn, out temp) ? (BasicProfileSortableFields?)temp : null);


问:
Form not posting data to database in django
I have a django model form to register a new user into Users table in Django. I have selected fields which I want to use. The form is showing correctly on the html page but the problem is when I submit the form, the data is not saved in the database. I tried to get the field values using name = request.POST['field'] and use print(name) all the data is being printed on the console.  Below is my code

forms.py

```<code>class UserForm(UserCreationForm):
    first_name = forms.CharField(required=False, label='First Name',
                                 widget=forms.TextInput(
                                     attrs={'style': 'font-size:medium', 'class': 'form-control form-control-sm'}))
    last_name = forms.CharField(required=False, label='Last Name',
                                widget=forms.TextInput(
                                    attrs={'style': 'font-size:medium', 'class': 'form-control form-control-sm'}))
    email = forms.EmailField(required=False, label='Email Address',
                             widget=forms.TextInput(
                                 attrs={'style': 'font-size:medium', 'class': 'form-control form-control-sm'}))
    username = forms.EmailField(required=False, label='Username',
                                widget=forms.TextInput(
                                    attrs={'style': 'font-size:medium', 'class': 'form-control form-control-sm'}))
    password = forms.EmailField(required=False, label='Password',
                                 widget=forms.PasswordInput(
                                     attrs={'style': 'font-size:medium', 'class': 'form-control form-control-sm'}))
    password1 = forms.EmailField(required=False, label='Confirm password',
                                 widget=forms.PasswordInput(
                                     attrs={'style': 'font-size:medium', 'class': 'form-control form-control-sm'}))

    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email', 'username', 'password','password1')

</code>```

My UserForm(): class is implementing  UserCreationForm in the forms.py class UserForm(UserCreationForm):  .

views.py

```<code>def reg(request):

    if request.method=='POST':

        form= UserForm(request.POST)
        if form.is_valid():
            user = form.save()
            group = Group.objects.get(name="patient")
            user.groups.add(group)
            return redirect('profile')

    else:

        form=UserForm()
    head = 'Create user account'

    title = 'Consultation | create account'
    context={'form':form, 'head':head, 'title':title}
    return render(request, 'registration.html', context)
</code>```

template Registration.html

```<code>{% extends 'base-reg.html' %}
{% block content %}
<div class="container-fluid" style="display:flex; align-items: center; justify-content: center;">
    {% for message in messages %}
    {{message}}
    {% endfor %}
    <form action="" method="post" class="card col-md-6 col-sm-12 shadow-sm" style="margin-top: 50px; padding-top: 0px;">
        <div style="background: darkslategray; padding: 10px;" class="shadow">
            <h4 class="text-white" style="width: fit-content; margin: auto;">{{head}}</h4>
        </div>
        <div class="p-3">

            {% csrf_token %}
            <div class="form-group p-2">
                <div class="row" >
                    <div class="col-6">
                        {{ form.first_name.label}}
                         {{ form.first_name}}
                    </div>
                    <div class="col-6">
                        {{ form.last_name.label}}
                        {{ form.last_name}}
                    </div>
                </div>
            </div>

            <div class="form-group p-2">

                {{ form.email.label}}
                {{ form.email}}
           </div>
           <div class="form-group p-2">
            {{ form.username.label}}
            {{ form.username}}
           </div>
           <div class="form-group p-2">
            <div class="row" >
                <div class="col-6">
                    {{ form.password.label}}
                     {{ form.password}}
                </div>
                <div class="col-6">
                    {{ form.password1.label}}
                    {{ form.password1}}
                </div>
            </div>
           </div>

            <div class="form-group p-2">
                <p class="p-2">Already have an account?  <a href="{% url 'login' %}">login here</a></p>
                <input type="submit" value="Create account" class="btn btn-outline-info btn-sm">
            </div>

        </div>

    </form>
</div>
{% endblock %}
</code>```

答:
I think the problem is where you save in the views.py. Try this:

```<code>user = form.save(commit=False)
group = Group.objects.get(name="patient")
user.groups.add(group)
user.save()
return redirect('profile')
</code>```

Body:
I have a django model form to register a new user into Users table in Django. I have selected fields which I want to use. The form is showing correctly on the html page but the problem is when I submit the form, the data is not saved in the database. I tried to get the field values using name = request.POST['field'] and use print(name) all the data is being printed on the console.  Below is my code

forms.py

class UserForm(UserCreationForm):
    first_name = forms.CharField(required=False, label='First Name',
                                 widget=forms.TextInput(
                                     attrs={'style': 'font-size:medium', 'class': 'form-control form-control-sm'}))
    last_name = forms.CharField(required=False, label='Last Name',
                                widget=forms.TextInput(
                                    attrs={'style': 'font-size:medium', 'class': 'form-control form-control-sm'}))
    email = forms.EmailField(required=False, label='Email Address',
                             widget=forms.TextInput(
                                 attrs={'style': 'font-size:medium', 'class': 'form-control form-control-sm'}))
    username = forms.EmailField(required=False, label='Username',
                                widget=forms.TextInput(
                                    attrs={'style': 'font-size:medium', 'class': 'form-control form-control-sm'}))
    password = forms.EmailField(required=False, label='Password',
                                 widget=forms.PasswordInput(
                                     attrs={'style': 'font-size:medium', 'class': 'form-control form-control-sm'}))
    password1 = forms.EmailField(required=False, label='Confirm password',
                                 widget=forms.PasswordInput(
                                     attrs={'style': 'font-size:medium', 'class': 'form-control form-control-sm'}))

    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email', 'username', 'password','password1')

My UserForm(): class is implementing  UserCreationForm in the forms.py class UserForm(UserCreationForm):  .

views.py

def reg(request):

    if request.method=='POST':

        form= UserForm(request.POST)
        if form.is_valid():
            user = form.save()
            group = Group.objects.get(name="patient")
            user.groups.add(group)
            return redirect('profile')

    else:

        form=UserForm()
    head = 'Create user account'

    title = 'Consultation | create account'
    context={'form':form, 'head':head, 'title':title}
    return render(request, 'registration.html', context)

template Registration.html

{% extends 'base-reg.html' %}
{% block content %}

    {% for message in messages %}
    {{message}}
    {% endfor %}
    <form action="" method="post" class="card col-md-6 col-sm-12 shadow-sm" style="margin-top: 50px; padding-top: 0px;">

{{head}}

            {% csrf_token %}

                        {{ form.first_name.label}}
                         {{ form.first_name}}

                        {{ form.last_name.label}}
                        {{ form.last_name}}

                {{ form.email.label}}
                {{ form.email}}

            {{ form.username.label}}
            {{ form.username}}

                    {{ form.password.label}}
                     {{ form.password}}

                    {{ form.password1.label}}
                    {{ form.password1}}

Already have an account?  login here

                <input type="submit" value="Create account" class="btn btn-outline-info btn-sm">

    </form>

{% endblock %}

Body:
I think the problem is where you save in the views.py. Try this:

user = form.save(commit=False)
group = Group.objects.get(name="patient")
user.groups.add(group)
user.save()
return redirect('profile')


问:
Databinding with parameters
I'm currently trying to develop a small finance application. My application needs a quite complex GUI (basically a table with dynamic rows and columns as well as categories and subcategories); since I couldn't think of a standard xaml-way to achieve that, I'm writing a custom control that is supposed to display my data.

So long story short, I'm creating a lot of different WPF UI elements in C# code directly, not in XAML. Now I'll need a way to synchronize some of these component's values with dynamically changing data. An obvious example is that some of my text boxes (or labels or whatever) will need to display the price of a stock. It should thus be bound to another class which provides up to date prices.

My main problem is that I don't know in advance which prices will be needed and where they should be displayed. So what I'd need is basically a way for my textbox to contact my price-object and ask "hey, i'm going to need a price for stock US0123456789. Please tell me that price and keep updating my value whenever the price of that stock is updated."

All databinding examples I found were usually focused on binding to the variables within a specific object instance, but I can't simply bind to, say, PriceObject.Price because there can't be a simple "Price" variable. After all, there's going to be various different stocks managed by the price object and each text box only needs the price of one specific stock, so it'd need to bind to something like PriceObject.PriceForStock("US0123456789"). I couldn't find a way to bind to a method, though, and I don't know how how else it'd be possible.

The only way I could think of was to have a Dictionary in my GUI-class witch stock ISINs as its keys and a reference to the UI Element as value. Then my GUI could observe the Price Object and each time prices change, and event is triggered and the GUI class could update the UI Element manually, something like (pseudo code incoming):

```<code>private Dictionary<string, UIElement> displayed_stocks = new Dictionary<string, UIElement>();

private void create_gui()
{
   Textbox textbox = new Textbox();
   displayed_stocks.Add(isin, textbox);
}

private void receive_change_event_of_price_object(string affected_isin, double new_price)
{
  displayed_stocks[affected_isin].Text = new_price.ToString();
}
</code>```

But I don't know, I feel like this is a sloppy solution. Especially because I won't only need dynamic prices but also other dynamic information like portfolio holdings, which will rely not only on ISIN but on ISIN and portfolio ID, so it wouldn't be that simple with a dictionary. Is there any better way to do it? I'd be glad to be pushed in the right direction there!
Thanks

答: If you create an indexer on the object you bind to you can bind with a parameter in a clean and easy manner, see this link for more information.</p>

Title: Databinding with parameters

Body:
I'm currently trying to develop a small finance application. My application needs a quite complex GUI (basically a table with dynamic rows and columns as well as categories and subcategories); since I couldn't think of a standard xaml-way to achieve that, I'm writing a custom control that is supposed to display my data.

So long story short, I'm creating a lot of different WPF UI elements in C# code directly, not in XAML. Now I'll need a way to synchronize some of these component's values with dynamically changing data. An obvious example is that some of my text boxes (or labels or whatever) will need to display the price of a stock. It should thus be bound to another class which provides up to date prices.

My main problem is that I don't know in advance which prices will be needed and where they should be displayed. So what I'd need is basically a way for my textbox to contact my price-object and ask "hey, i'm going to need a price for stock US0123456789. Please tell me that price and keep updating my value whenever the price of that stock is updated."

All databinding examples I found were usually focused on binding to the variables within a specific object instance, but I can't simply bind to, say, PriceObject.Price because there can't be a simple "Price" variable. After all, there's going to be various different stocks managed by the price object and each text box only needs the price of one specific stock, so it'd need to bind to something like PriceObject.PriceForStock("US0123456789"). I couldn't find a way to bind to a method, though, and I don't know how how else it'd be possible.

The only way I could think of was to have a Dictionary in my GUI-class witch stock ISINs as its keys and a reference to the UI Element as value. Then my GUI could observe the Price Object and each time prices change, and event is triggered and the GUI class could update the UI Element manually, something like (pseudo code incoming):

private Dictionary<string, UIElement> displayed_stocks = new Dictionary<string, UIElement>();

private void create_gui()
{
   Textbox textbox = new Textbox();
   displayed_stocks.Add(isin, textbox);
}

private void receive_change_event_of_price_object(string affected_isin, double new_price)
{
  displayed_stocks[affected_isin].Text = new_price.ToString();
}

But I don't know, I feel like this is a sloppy solution. Especially because I won't only need dynamic prices but also other dynamic information like portfolio holdings, which will rely not only on ISIN but on ISIN and portfolio ID, so it wouldn't be that simple with a dictionary. Is there any better way to do it? I'd be glad to be pushed in the right direction there!
Thanks


问:
Default Javascript objects are very slow when large?
I am doing a modified version of collecting word co-occurrences, so I wrote my own javascript, and I am tracking the occurrences in three objects. However, once the objects get large (~8 million, 3 million, and 172000) a function that took 5 seconds per 100000 sentences now takes minutes to do one sentence with 30 words (30 tokens). I am nowhere near my RAM cap (I have 12 more GBs of RAM it could be using, and the program is only using 2.2GB). Using Node.js v17.3.1.

Why does my function take so long when the objects get bigger (even though the sentences remain the same length)? Should I be using a different object besides Javascript's default object, or is there a way improve the speed of access and setting these objects when they are so big?

Code:

```<code>  let posCounts = {};
  let negCounts = {};
  // the number of times each word occurs
  let wordCounts = {};
  let tokens = // some function that gets tokens;
    for (let k = 0; k < tokens.length; k++) {
      // count word occurences
      if (tokens[k] in wordCounts) {
        wordCounts[tokens[k]] += 1;
      } else {
        wordCounts[tokens[k]] = 1;
      }
      for(let tok = k + 1; tok < tokens.length; tok++) {
        if (tok == k) {
          // avoid word to self cooccurrence
          // should no longer be possible
          continue;
        } else {
           // check which form of the cooccurence exists already in either count
           actual_tok = (tokens[k] + "-" + tokens[tok]);
           if(actual_tok in posCounts || actual_tok in negCounts) {
             // no-op
           } else {
             actual_tok = (tokens[tok] + "-" + tokens[k]);
           }

           // condition set before this block of code
           if(condition) {
             if (actual_tok in posCounts) {
               posCounts[actual_tok] += 1;
             } else {
               posCounts[actual_tok] = 1;
             }
           } else {
             if (actual_tok in negCounts) {
               negCounts[actual_tok] += 1;
             } else {
               negCounts[actual_tok] = 1;
             }
           }
         }
      }

    }
</code>```

Update: I've tried increasing the heap size via node train_matrices.js --max-old-space-size=12288 and node train_matrices.js --max_old_space_size=12288 (underline instead of dash), and that didn't work either.

答:
Probably not the main issue in your code, but you can reduce the number of lookups by changing this structure from this:

```<code>  if (tokens[k] in wordCounts) {
    wordCounts[tokens[k]] += 1;
  } else {
    wordCounts[tokens[k]] = 1;
  }
</code>```

to this:

```<code>  let token = tokens[k];
  let cnt = wordCounts[token] || 0;
  wordCounts[token] = cnt + 1;
</code>```

And, as I said in a comment, I've read that a Map object with .get() and .set() is better suited when there are lots of dynamically created keys whereas plain objects are better suited when you have lots of objects with all the same keys (as the JS compiler can sometimes make a C-like struct for it), but this can't be done when you're regularly adding new keys.

Body:
I am doing a modified version of collecting word co-occurrences, so I wrote my own javascript, and I am tracking the occurrences in three objects. However, once the objects get large (~8 million, 3 million, and 172000) a function that took 5 seconds per 100000 sentences now takes minutes to do one sentence with 30 words (30 tokens). I am nowhere near my RAM cap (I have 12 more GBs of RAM it could be using, and the program is only using 2.2GB). Using Node.js v17.3.1.

Why does my function take so long when the objects get bigger (even though the sentences remain the same length)? Should I be using a different object besides Javascript's default object, or is there a way improve the speed of access and setting these objects when they are so big?

Code:

  let posCounts = {};
  let negCounts = {};
  // the number of times each word occurs
  let wordCounts = {};
  let tokens = // some function that gets tokens;
    for (let k = 0; k < tokens.length; k++) {
      // count word occurences
      if (tokens[k] in wordCounts) {
        wordCounts[tokens[k]] += 1;
      } else {
        wordCounts[tokens[k]] = 1;
      }
      for(let tok = k + 1; tok < tokens.length; tok++) {
        if (tok == k) {
          // avoid word to self cooccurrence
          // should no longer be possible
          continue;
        } else {
           // check which form of the cooccurence exists already in either count
           actual_tok = (tokens[k] + "-" + tokens[tok]);
           if(actual_tok in posCounts || actual_tok in negCounts) {
             // no-op
           } else {
             actual_tok = (tokens[tok] + "-" + tokens[k]);
           }

           // condition set before this block of code
           if(condition) {
             if (actual_tok in posCounts) {
               posCounts[actual_tok] += 1;
             } else {
               posCounts[actual_tok] = 1;
             }
           } else {
             if (actual_tok in negCounts) {
               negCounts[actual_tok] += 1;
             } else {
               negCounts[actual_tok] = 1;
             }
           }
         }
      }

    }

Update: I've tried increasing the heap size via node train_matrices.js --max-old-space-size=12288 and node train_matrices.js --max_old_space_size=12288 (underline instead of dash), and that didn't work either.

Body:
Probably not the main issue in your code, but you can reduce the number of lookups by changing this structure from this:

  if (tokens[k] in wordCounts) {
    wordCounts[tokens[k]] += 1;
  } else {
    wordCounts[tokens[k]] = 1;
  }

to this:

  let token = tokens[k];
  let cnt = wordCounts[token] || 0;
  wordCounts[token] = cnt + 1;

And, as I said in a comment, I've read that a Map object with .get() and .set() is better suited when there are lots of dynamically created keys whereas plain objects are better suited when you have lots of objects with all the same keys (as the JS compiler can sometimes make a C-like struct for it), but this can't be done when you're regularly adding new keys.


问:
django no module name 'config'
I wrote these apps using Python 2 and now am using Python 3.

I've tried:

Changing to a new virtualenv and reinstalling requirements

pip install config -> returns a new Syntax error in an Exception...

pip install django-config

When running: python3 manage.py runserver
I keep getting the following error:

```<code>Traceback (most recent call last):
      File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
      File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
utility.execute()
      File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 308, in execute
settings.INSTALLED_APPS
      File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__
self._setup(name)
      File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 41, in _setup
self._wrapped = Settings(settings_module)
      File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 110, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
      File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
      File "<frozen importlib._bootstrap>", line 994, in _gcd_import
      File "<frozen importlib._bootstrap>", line 971, in _find_and_load
      File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked
      File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
      File "<frozen importlib._bootstrap>", line 994, in _gcd_import
      File "<frozen importlib._bootstrap>", line 971, in _find_and_load
      File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked
      File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
      File "<frozen importlib._bootstrap>", line 994, in _gcd_import
      File "<frozen importlib._bootstrap>", line 971, in _find_and_load
      File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
    ModuleNotFoundError: No module named 'config'
</code>```

答:
Change this line:

```<code>django.config.urls
</code>```

to:

```<code>django.conf.urls
</code>```

Title: django no module name 'config'

Body:
I wrote these apps using Python 2 and now am using Python 3.

I've tried:

Changing to a new virtualenv and reinstalling requirements

pip install config -> returns a new Syntax error in an Exception...

pip install django-config

When running: python3 manage.py runserver
I keep getting the following error:

Traceback (most recent call last):
      File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
      File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
utility.execute()
      File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 308, in execute
settings.INSTALLED_APPS
      File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__
self._setup(name)
      File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 41, in _setup
self._wrapped = Settings(settings_module)
      File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 110, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
      File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
      File "<frozen importlib._bootstrap>", line 994, in _gcd_import
      File "<frozen importlib._bootstrap>", line 971, in _find_and_load
      File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked
      File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
      File "<frozen importlib._bootstrap>", line 994, in _gcd_import
      File "<frozen importlib._bootstrap>", line 971, in _find_and_load
      File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked
      File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
      File "<frozen importlib._bootstrap>", line 994, in _gcd_import
      File "<frozen importlib._bootstrap>", line 971, in _find_and_load
      File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
    ModuleNotFoundError: No module named 'config'

Body:
Change this line:

django.config.urls

to:

django.conf.urls


问:
Internal Server Error on Terraform provisioned API Gateway Trigger
I'm using Terraform to allocate a Lambda function that's triggered by a request to an API Gateway on AWS. Here's my .tf file:

```<code>dsf
</code>```

This correctly sets up the Lambda function, but something is off with the API Gateway. When I curl with the output URL (https://cqsso4fw67.execute-api.us-east-1.amazonaws.com), it gives me the following:

```<code>curl https://cqsso4fw67.execute-api.us-east-1.amazonaws.com/
{"message":"Internal Server Error"}%
</code>```

If I manually remove this API Gateway and create a new one from the AWS Console within the Lambda function and run curl again, I get "SUCCESS!" (which is what my Lambda should do).

```<code>smf
</code>```

Any ideas how I can fix the .tf file to correctly setup the API Gateway trigger?

Here are the differences between the one created in AWS and the one provisioned in Terraform. Terraform one is at the top.

答:
The TF code that you showed is correct. Most likely reason for the failure is your lambda function, which you haven't showed. You have to inspect lambda function logs in CloudWatch to check why it fails.

Edit:

The function should return:

```<code>    return {
        'statusCode': 200,
        'body': 'SUCCESS'
    }
</code>```

Body:
I'm using Terraform to allocate a Lambda function that's triggered by a request to an API Gateway on AWS. Here's my .tf file:

dsf

This correctly sets up the Lambda function, but something is off with the API Gateway. When I curl with the output URL (https://cqsso4fw67.execute-api.us-east-1.amazonaws.com), it gives me the following:

curl https://cqsso4fw67.execute-api.us-east-1.amazonaws.com/
{"message":"Internal Server Error"}%

If I manually remove this API Gateway and create a new one from the AWS Console within the Lambda function and run curl again, I get "SUCCESS!" (which is what my Lambda should do).

smf

Any ideas how I can fix the .tf file to correctly setup the API Gateway trigger?

Here are the differences between the one created in AWS and the one provisioned in Terraform. Terraform one is at the top.

Body:
The TF code that you showed is correct. Most likely reason for the failure is your lambda function, which you haven't showed. You have to inspect lambda function logs in CloudWatch to check why it fails.

Edit:

The function should return:

    return {
        'statusCode': 200,
        'body': 'SUCCESS'
    }


问:
Why am I getting this error in my rails solidus app after installing bootstrap?
I am trying to set up a solidus app with custom css using bootstrap-sass. (I am following this tutorial)

Prior to getting this error, the page would load just fine but none of the bootstrap css would load correctly. This error started after I added

```<code>#= require bootstrap_sprockets
#= require_tree
</code>```

to my all.coffee file

and adding

```<code>gem 'sassc-rails'
</code>```

to my Gemfile

the complete all.sass file:

```<code>@import "bootstrap-sprockets"
@import "bootstrap"
</code>```

the complete all.coffee file:

```<code>#= require jquery
#= require jquery_ujs
#= require spree
#= require bootstrap_sprockets
#= require_tree
</code>```

the complete Gemfile:

```<code>source 'https://rubygems.org'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.0.0'
# Use postgresql as the database for Active Record
gem 'pg', '~> 0.18'
# Use Puma as the app server
gem 'puma', '~> 3.0'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

gem 'bootstrap-sass'
gem 'sassc-rails'

gem 'solidus'
gem 'solidus_auth_devise'
gem 'deface'

# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platform: :mri
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console'
  gem 'listen', '~> 3.0.5'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
</code>```

when I run the server I get the following error:

```<code>Error: Function very-light finished without @return
        on line 38:34 of ../../.rvm/gems/ruby-2.6.3/gems/solidus_backend-2.2.2/app/assets/stylesheets/spree/backend/globals/_variables.scss, in function `very-light`
        from line 38:34 of ../../.rvm/gems/ruby-2.6.3/gems/solidus_backend-2.2.2/app/assets/stylesheets/spree/backend/globals/_variables.scss
        from line 6:9 of ../../.rvm/gems/ruby-2.6.3/gems/solidus_backend-2.2.2/app/assets/stylesheets/spree/backend/spree_admin.scss
>> $color-border:                   very-light($color-3, 12) !default;
</code>```

I'm not sure what exactly I need to do to fix this. I've made sure that I have the required gems for bootstrap-sass in my Gemfile and I've tried running bundle update.

答:
the latest sassc-rails gem implemented via sassc, wich requires all CSS functions should ensure that they do not end without a @return statement.

and solidus fix it after v2.9, you can see it on https://github.com/solidusio/solidus/commit/aeba736e742eaf39e45b294433e33d663ac66f24

Body:
I am trying to set up a solidus app with custom css using bootstrap-sass. (I am following this tutorial)

Prior to getting this error, the page would load just fine but none of the bootstrap css would load correctly. This error started after I added

#= require bootstrap_sprockets
#= require_tree

to my all.coffee file

and adding

gem 'sassc-rails'

to my Gemfile

the complete all.sass file:

@import "bootstrap-sprockets"
@import "bootstrap"

the complete all.coffee file:

#= require jquery
#= require jquery_ujs
#= require spree
#= require bootstrap_sprockets
#= require_tree

the complete Gemfile:

source 'https://rubygems.org'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.0.0'
# Use postgresql as the database for Active Record
gem 'pg', '~> 0.18'
# Use Puma as the app server
gem 'puma', '~> 3.0'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

gem 'bootstrap-sass'
gem 'sassc-rails'

gem 'solidus'
gem 'solidus_auth_devise'
gem 'deface'

# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platform: :mri
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console'
  gem 'listen', '~> 3.0.5'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

when I run the server I get the following error:

Error: Function very-light finished without @return
        on line 38:34 of ../../.rvm/gems/ruby-2.6.3/gems/solidus_backend-2.2.2/app/assets/stylesheets/spree/backend/globals/_variables.scss, in function `very-light`
        from line 38:34 of ../../.rvm/gems/ruby-2.6.3/gems/solidus_backend-2.2.2/app/assets/stylesheets/spree/backend/globals/_variables.scss
        from line 6:9 of ../../.rvm/gems/ruby-2.6.3/gems/solidus_backend-2.2.2/app/assets/stylesheets/spree/backend/spree_admin.scss
>> $color-border:                   very-light($color-3, 12) !default;

I'm not sure what exactly I need to do to fix this. I've made sure that I have the required gems for bootstrap-sass in my Gemfile and I've tried running bundle update.


问:
How to open file from URI?
I would like to crate, a file uploader fragment.

First of all, user picks up files, and after that I show the picked up files in a recycler view.

If the user clicks to recyclerView item, I would like to open the file.

So it is the problem, I tried a lot of answer, but I can't solve this.

I tried to open specific files for example pdf, and the pdf reader is opened, but couldn't find the file, and it happened when I want to open image fil as well

In the feature, when it is works, I would like to save and open different files for exaple images, documents etc

minSdk : 19
target: 30

```<code>onActivityResult:
 if (resultCode == Activity.RESULT_OK) {
                    data?.let { it ->
                        var list = mutableListOf<DocumentView>()

                        if (it.clipData != null) {
                            for (i in 0 until it.clipData!!.itemCount) {
                                it.clipData?.getItemAt(i)?.uri?.let { uri ->
                                    viewModel.selectedFilesUri.add(uri)
                                }
                            }
                        } else {
                            it.data?.let { uri ->
                                viewModel.selectedFilesUri.add(uri)

                                getFileMetaData(uri)?.let { documentView ->
                                    list.add(documentView)
                                }
                            }
                        }

                        refreshFileList()
                    }
                }

    private fun refreshFileList(){
        val uris = viewModel.selectedFilesUri
        val list = mutableListOf<DocumentView>()

        uris.forEach { uri->
            getFileMetaData(uri)?.let {
                list.add(it)
            }
        }

        adapter.submitList(list)
    }

    private fun openFile(documentView: DocumentView, uri: Uri) {
        val intent = Intent(Intent.ACTION_VIEW)
        intent.setDataAndType(uri,"application/pdf")
        startActivity(intent)
    }

Manifest Provider:
 <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_path" />
        </provider>

file_path:
<paths>
    <external-path name="external_files" path="."/>
</paths>
</code>```

答:
You can set it this way easier</p>
```<code>intent.setFlags(Intent.FLAG_GRANT_READ_PERMISSION);
</code>```

Title: How to open file from URI?

Body:
I would like to crate, a file uploader fragment.

First of all, user picks up files, and after that I show the picked up files in a recycler view.

If the user clicks to recyclerView item, I would like to open the file.

So it is the problem, I tried a lot of answer, but I can't solve this.

I tried to open specific files for example pdf, and the pdf reader is opened, but couldn't find the file, and it happened when I want to open image fil as well

In the feature, when it is works, I would like to save and open different files for exaple images, documents etc

minSdk : 19
target: 30

onActivityResult:
 if (resultCode == Activity.RESULT_OK) {
                    data?.let { it ->
                        var list = mutableListOf<DocumentView>()

                        if (it.clipData != null) {
                            for (i in 0 until it.clipData!!.itemCount) {
                                it.clipData?.getItemAt(i)?.uri?.let { uri ->
                                    viewModel.selectedFilesUri.add(uri)
                                }
                            }
                        } else {
                            it.data?.let { uri ->
                                viewModel.selectedFilesUri.add(uri)

                                getFileMetaData(uri)?.let { documentView ->
                                    list.add(documentView)
                                }
                            }
                        }

                        refreshFileList()
                    }
                }

    private fun refreshFileList(){
        val uris = viewModel.selectedFilesUri
        val list = mutableListOf<DocumentView>()

        uris.forEach { uri->
            getFileMetaData(uri)?.let {
                list.add(it)
            }
        }

        adapter.submitList(list)
    }

    private fun openFile(documentView: DocumentView, uri: Uri) {
        val intent = Intent(Intent.ACTION_VIEW)
        intent.setDataAndType(uri,"application/pdf")
        startActivity(intent)
    }

Manifest Provider:
 <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_path" />
        </provider>

file_path:
<paths>
    <external-path name="external_files" path="."/>
</paths>

Body:
You can set it this way easier

intent.setFlags(Intent.FLAG_GRANT_READ_PERMISSION);


问:
Only process the buffered channel when it is full
I want to process all the elements of the buffered channel, only when it is completely full. I couldn't use for-range because it would need closing the channel else it would throw deadlock. I need to keep the channel open for next set of batch. Is this approach ok? I am passing length in the param because channel is still getting data and I want to process everything in order.

func flush(chnMap map[string]chan string) {
    for _, v := range chnMap {
        if len(v) == CAP {
            go processChan(v, len(v))
        }
    }
}

func processChan(chn <-chan string, length int) {
    for i := 0; i < length; i++ {
        op := <-chn
        //process chan
    }
}
```

答:
I'd say your current solution is probably 95% correct. However, there are still some changes you could make:

```<code>func flush(chnMap map[string]chan string) {
    for _, v := range chnMap {
        if len(v) >= CAP {
            go processChan(v, len(v))
        }
    }
}

func processChan(chn <-chan string, length int) {
    for i := 0; i < length; i++ {
        op := <-chn
        // process chan
    }
}
</code>```

This code is more or less the same as what you have except that it will call processChan when len(v) is the same size as CAP or larger than CAP. This will cover the case where the channel is overfull when you check it for processing. You could of course handle this by giving your buffer an explicit capacity, but this will work without enforcing that design decision.

Body:
I'd say your current solution is probably 95% correct. However, there are still some changes you could make:

func flush(chnMap map[string]chan string) {
    for _, v := range chnMap {
        if len(v) >= CAP {
            go processChan(v, len(v))
        }
    }
}

func processChan(chn <-chan string, length int) {
    for i := 0; i < length; i++ {
        op := <-chn
        // process chan
    }
}

This code is more or less the same as what you have except that it will call processChan when len(v) is the same size as CAP or larger than CAP. This will cover the case where the channel is overfull when you check it for processing. You could of course handle this by giving your buffer an explicit capacity, but this will work without enforcing that design decision.


问:
What's the difference between a Python module and a Python package?
What's the difference between a Python module and a Python package?

See also: What's the difference between "package" and "module" (for other languages)

答:
Module: A module is a simple Python file with a (.py) extension that contains collections of functions and global variables. It is an executable file, and the notion of Package in Python is used to arrange all of the modules.

For an Example: Save the code in a file called demo (module.py).

```<code>def myModule1(name):
    print("My Module name is: "+ name)
</code>```

Import the demo module module and use the myModule1 function within it.

```<code>import demo_module

demo_module.myModule1("Math")
</code>```

Solution:

My Module name is: Math

Package: A package is a basic directory that contains a collection of modules. This directory contains Python modules as well as a (__init .py__) file that the interpreter uses to recognize it as a Package. The package is nothing more than a namespace. Within the package, there are sub-packages.

For an Example:

Student (Package)

| __init__.py (Constructor)

| details.py (Module)

| marks.py (Module)

| collegeDetails.py (Module)

| demo_module.py (Module)

A package is a set of modules organized into directories to form a package directory.

```<code>from Student import details, collegeDetails, demo_module
</code>```

Body:
Module: A module is a simple Python file with a (.py) extension that contains collections of functions and global variables. It is an executable file, and the notion of Package in Python is used to arrange all of the modules.

For an Example: Save the code in a file called demo (module.py).

def myModule1(name):
    print("My Module name is: "+ name)

Import the demo module module and use the myModule1 function within it.

import demo_module

demo_module.myModule1("Math")

Solution:

My Module name is: Math

Package: A package is a basic directory that contains a collection of modules. This directory contains Python modules as well as a (__init .py__) file that the interpreter uses to recognize it as a Package. The package is nothing more than a namespace. Within the package, there are sub-packages.

For an Example:

Student (Package)

| __init__.py (Constructor)

| details.py (Module)

| marks.py (Module)

| collegeDetails.py (Module)

| demo_module.py (Module)

A package is a set of modules organized into directories to form a package directory.

from Student import details, collegeDetails, demo_module


问:
How can I close my dropdown menu when sveltekit route changes?
I have a <SideBar /> component and onDestroy() doesn't seem to fire on route changes.

I need to close the menu when the route changes otherwise the menu stays open which is a bad UX.

```<code><script>
    import { page } from '$app/stores';
    import { onDestroy } from 'svelte';
    let isMainNavOpen = true;
    let isGroupNavOpen = false;
    function toggleGroupMenu(e) {
        e.preventDefault();

        isGroupNavOpen = !isGroupNavOpen;
    }

    $: currentPath = $page.url.pathname;
</script>

    <nav>
        <header class="groups" class:closed={!isGroupNavOpen}>
            <div class="dropdown">
                <a href="#" class="toggler" on:click|preventDefault={toggleGroupMenu}>
                    <img src="/icons/chevron.svg" alt="" border="0" />
                </a>
                <ul>
                    {#each groupMenu as item, i}
                        <li class:active={currentPath === item.path}>
                            <a href="/groups/{item.id}"
                                ><img
                                    class="avatar"
                                    src="/icons/avatar.group.png"
                                    alt=""
                                    border="0"
                                />{item.name}</a
                            >
                        </li>
                    {/each}
                </ul>
                <a href="/groups" class="button secondary outlined">Explore Groups</a>
            </div>
        </header>
    </nav>

<style>
    nav {
        padding: 1.2rem;
        flex-grow: 1;
        display: flex;
        flex-direction: column;
    }

    nav header {
        color: #fff;
        display: flex;
        flex-direction: column;
    }

    .groups.closed li:not(:first-child) {
        display: none;
    }

    .groups .toggler {
        position: absolute;
        top: 2.5rem;
        right: 1rem;
        margin-left: 1.4rem;
    }

    .groups .toggler img {
        transform: rotate(180deg);
    }

    .groups.closed .toggler img {
        transform: rotate(0deg);
    }

    .groups ul {
        width: 100%;
        max-height: 22rem;
        overflow-y: auto;
        background-color: #060536;
        color: #fff;
        border-radius: 0.8rem;
    }

    .groups ul .active {
        background-color: #34326d;
    }

    .groups .dropdown {
        width: 100%;
        position: absolute;
        top: 0;
        left: 0;
        z-index: 1;
        background-color: #060536;
    }

    header.groups {
        padding: 0;
        position: relative;
        overflow: visible;
    }

    .groups .avatar {
        width: 5rem;
        display: block;
        margin-right: 1.4rem;
    }

    .groups li {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .groups li a {
        padding: 1rem;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        flex-grow: 1;
        color: #fff;
        text-decoration: none;
        font-weight: 600;
        word-break: break-all;
    }

    .groups .button {
        font-weight: 600;
        font-size: 1.4rem;
        width: 80%;
        margin: 1rem auto;
    }

    .groups.closed .button {
        display: none;
    }

    nav ul {
        display: flex;
        flex-direction: column;
    }

    nav ul {
        list-style-type: none;
        padding: 0;
        margin: 0;
        flex: 1;
    }
</style>
</code>```

I probably also need an underlay where if they click off the menu it closes too.

答:
I am going to suppose you add this Sidebar to a layout page somewhere, which means that on a page change this component is not destroyed, it stays the same (unless you move to a page with a different layout). In SvelteKit navigating only changes the part in the  <slot> not the rest.

You can solve this by simply reacting to page changes:

$: $page.url && (isGroupNavOpen = false)
```

Body:
I have a <SideBar /> component and onDestroy() doesn't seem to fire on route changes.

I need to close the menu when the route changes otherwise the menu stays open which is a bad UX.

                    {#each groupMenu as item, i}

                            {item.name}

                    {/each}

                Explore Groups

I probably also need an underlay where if they click off the menu it closes too.