问:
Click "Exit" button through our Application It need to go Phones's Home page & remove SharedPreferences also
My question is when I click the "Exit" button through our application It need to go to Phones's Home screen.I have Tried like this

```<code>  public void onExitAction(View botton){
          // finish();
          // super.finish();
           // System.runFinalizersOnExit(true)

            //android.os.Process.killProcess(android.os.Process.myPid());

     System.exit(0);

}
</code>```

Not working.

When I put finish() its closing that particular activity & its go to previous screen.

seconds one is When we exit the system need to remove SharedPreferences also?

Please help me on this...

Thanks in advance

答:
```<code>    public void onExitAction(View botton){
    Intent startMain = new Intent(Intent.ACTION_MAIN);
    startMain.addCategory(Intent.CATEGORY_HOME);
    startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(startMain);
    finish();
    }
</code>```

Body:
My question is when I click the "Exit" button through our application It need to go to Phones's Home screen.I have Tried like this

  public void onExitAction(View botton){
          // finish();
          // super.finish();
           // System.runFinalizersOnExit(true)

            //android.os.Process.killProcess(android.os.Process.myPid());

     System.exit(0);

}

Not working.

When I put finish() its closing that particular activity & its go to previous screen.

seconds one is When we exit the system need to remove SharedPreferences also?

Please help me on this...

Thanks in advance


来源: stackexchange

问:
Visual Studio: How to show Overloads in IntelliSense?
Once code has been written, the only way I know of to view the overloads for a method is to actually edit the method by deleting the Parenthesis () and reopening them.

Is there a shortcut key that I could press to activate this instead of having to edit my files?

For an example, please reference the ShowDialog Overload screen shot below:

答:
you mean's change overload.
just Press Shift +  ↑  / ↓</p>

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
localhost:4200 is a blank page in Angular
After login, the default link is =>
http://localhost:4200/dashboard/administration/portfolio

If I remove /portfolio from the address
http://localhost:4200/dashboard/administration

and I press "enter",

Automatically is displayed, http://localhost:4200/dashboard/administration/portfolio, I want to keep this system for all paths.

If I remove /administration/portfolio and press enter,

Automatically the page is directed to http://localhost:4200/dashboard/administration/portfolio.

So far everything is working perfectly.

My problem, if I remove dashboard/administration/portfolio.

So the link is http://localhost:4200/ then enter.

I have a blank page, I don't automatically return to http://localhost:4200/dashboard/administration/portfolio, I don't understand why?

I think it's a problem with a route?

app-routing.module.ts

```<code>const routes: Routes = [
  {
    path: '',
    canActivate: [CanActivateTeam],
    loadChildren: () => import('./views/dashboard/dashboard.module').then((m) => m.DashboardModule),
  },

  {
    path: 'sessions',
    loadChildren: () => import('./views/identity/identity.module').then((m) => m.IdentityModule),
  },
  { path: 'pipes', loadChildren: () => import('./shared/pipes/pipes.module').then(m => m.PipesModule) },

  // others
  {
    path: '**', redirectTo: ''
  },

];
</code>```

dashboard-routing.module.ts

```<code>const DASHBOARD_ROUTES: Routes = [
  {
    path: 'dashboard',
    component: DashboardComponent,

    children: [
      {
          path: '',
          redirectTo: 'administration',
          pathMatch: 'full'
      },
      {
        path: 'administration',
        loadChildren: () =>
          import('./views/administration/administration.module').then(
            (m) => m.AdministrationModule
          ),
      },
      {
        path: 'market',
        loadChildren: () =>
          import('./views/market/market.module').then((m) => m.MarketModule),
      },
      {
        path: 'dta',
        loadChildren: () =>
          import('./views/dta/dta.module').then((m) => m.DtaModule),
      },
    ],
  },
];
</code>```

administration-routing.module.ts

```<code>export const ADMINISTRATION_ROUTES: Routes = [

  {
    path: '',
    component: AdministrationComponent,

    children: [
      {
        path: '',
        pathMatch: 'full',
        redirectTo: 'portfolio',
      },

      {
        path: 'portfolio',
        component: PortfolioComponent,
      },
      {
        path: 'account-opening',
        component: AccountOpeningComponent,
      },

      {
        path: 'corporate-action',
        component: CorporateActionComponent,
      },
      {
        path: 'visualization-deposit',
        component: VisualizationDepositComponent,
      },
    ],
  },
];
</code>```

Thanks for your help.

答:
```<code>{
   path: '',
   redirectTo: 'dashboard',
   pathMatch: 'full'
},
</code>```

Add this to your DASHBOARD_ROUTES.

Thanks to this, your dashboard module will know where to go when loaded.

Body:
After login, the default link is =>
http://localhost:4200/dashboard/administration/portfolio

If I remove /portfolio from the address
http://localhost:4200/dashboard/administration

and I press "enter",

Automatically is displayed, http://localhost:4200/dashboard/administration/portfolio, I want to keep this system for all paths.

If I remove /administration/portfolio and press enter,

Automatically the page is directed to http://localhost:4200/dashboard/administration/portfolio.

So far everything is working perfectly.

My problem, if I remove dashboard/administration/portfolio.

So the link is http://localhost:4200/ then enter.

I have a blank page, I don't automatically return to http://localhost:4200/dashboard/administration/portfolio, I don't understand why?

I think it's a problem with a route?

app-routing.module.ts

const routes: Routes = [
  {
    path: '',
    canActivate: [CanActivateTeam],
    loadChildren: () => import('./views/dashboard/dashboard.module').then((m) => m.DashboardModule),
  },

  {
    path: 'sessions',
    loadChildren: () => import('./views/identity/identity.module').then((m) => m.IdentityModule),
  },
  { path: 'pipes', loadChildren: () => import('./shared/pipes/pipes.module').then(m => m.PipesModule) },

  // others
  {
    path: '**', redirectTo: ''
  },

];

dashboard-routing.module.ts

const DASHBOARD_ROUTES: Routes = [
  {
    path: 'dashboard',
    component: DashboardComponent,

    children: [
      {
          path: '',
          redirectTo: 'administration',
          pathMatch: 'full'
      },
      {
        path: 'administration',
        loadChildren: () =>
          import('./views/administration/administration.module').then(
            (m) => m.AdministrationModule
          ),
      },
      {
        path: 'market',
        loadChildren: () =>
          import('./views/market/market.module').then((m) => m.MarketModule),
      },
      {
        path: 'dta',
        loadChildren: () =>
          import('./views/dta/dta.module').then((m) => m.DtaModule),
      },
    ],
  },
];

administration-routing.module.ts

export const ADMINISTRATION_ROUTES: Routes = [

  {
    path: '',
    component: AdministrationComponent,

    children: [
      {
        path: '',
        pathMatch: 'full',
        redirectTo: 'portfolio',
      },

      {
        path: 'portfolio',
        component: PortfolioComponent,
      },
      {
        path: 'account-opening',
        component: AccountOpeningComponent,
      },

      {
        path: 'corporate-action',
        component: CorporateActionComponent,
      },
      {
        path: 'visualization-deposit',
        component: VisualizationDepositComponent,
      },
    ],
  },
];

Thanks for your help.

Body:
{
   path: '',
   redirectTo: 'dashboard',
   pathMatch: 'full'
},

Add this to your DASHBOARD_ROUTES.

Thanks to this, your dashboard module will know where to go when loaded.


问:
Display json data in a reactjs component
I'm new to react and fetch data api. I dont know how to display json data in one of my component. I have use axios to get data from api and this is my return json data

{
  "result": true,
  "items": [
    {
      "excerpt": "egghead is your source for the Badass Portfolio Projects you need to climb the career ladder as a modern web developer.",
      "_id": 360690368,
      "title": "Build the portfolio you need to be a badass web developer.",
      "link": "https://egghead.io/",
      "domain": "egghead.io"
    },
    {
      "excerpt": "From career choices to new purchases, use René Girard’s mimetic theory to resist the herd and forge your own path in life",
      "_id": 359605780,
      "link": "https://psyche.co/guides/how-to-know-what-you-really-want-and-be-free-from-mimetic-desire?ref=refind",
      "title": "How to know what you really want | Psyche Guides",
      "domain": "psyche.co"
    }
  ],
  "count": 2,
  "collectionId": 0
}
```
<p><strong>Here is list component:</strong></p>
```import * as React from "react"
import axios from "axios"

axios.get("https://api.abc.com", {
  method: "get",
  headers: {
    Authorization: `Bearer xxxxxxxx-xxxx-xxxx-xxxx-xxxx`,
    "Content-Type": "application/x-www-form-urlencoded",
  },
})
.then(res => {
  const bookmarks = JSON.stringify(res.data)
  console.log(bookmarks)
})
.catch(error => {
  console.error(error)
})

const IndexPage = ({ bookmarks }) => (
  <>

Show Data

      {bookmarks.items.map(bookmark => (

{bookmark.title}

      ))}

  </>
)

export default IndexPage
```

Can anyone help me in displaying the list? Thanks in advance

答:
This is not the way how data fetching in react works... you must fetch your data in components useEffect and store your data in useState hook, which will cause rerender and you can access this data:

```<code>import * as React from "react"
import axios from "axios"

const IndexPage = () => (
const [bookmarks, setBookmarks] = React.useState()

React.useEffect(()=>{
axios.get("https://api.abc.com", {
  method: "get",
  headers: {
    Authorization: `Bearer xxxxxxxx-xxxx-xxxx-xxxx-xxxx`,
    "Content-Type": "application/x-www-form-urlencoded",
  },
})
.then(res => {
  const bookmarks = JSON.stringify(res.data)
  setBookmarks(bookmarks)
})
.catch(error => {
  console.error(error)
})
},[])
return(
  <>
    <h1>Show Data</h1>
    <div>
      {bookmarks.items.map(bookmark => (
        <div>{bookmark.title}</div>
      ))}
    </div>
  </>
)
</code>```

edit: with custom loading solution:

```<code>import * as React from "react"
import axios from "axios"

const IndexPage = () => (
const [loading, setLoading] = React.useState(true)
const [bookmarks, setBookmarks] = React.useState()

React.useEffect(()=>{
axios.get("https://api.abc.com", {
  method: "get",
  headers: {
    Authorization: `Bearer xxxxxxxx-xxxx-xxxx-xxxx-xxxx`,
    "Content-Type": "application/x-www-form-urlencoded",
  },
})
.then(res => {
  const bookmarks = JSON.stringify(res.data)
  setBookmarks(bookmarks)
})
.catch(error => {
  console.error(error)
}).finally(()=>{setLoading(false)});
},[])

if(loading){
 return (<>Loading...</>)
}

return(
  <>
    <h1>Show Data</h1>
    <div>
      {bookmarks.items.map(bookmark => (
        <div>{bookmark.title}</div>
      ))}
    </div>
  </>
)
</code>```

Body:
I'm new to react and fetch data api. I dont know how to display json data in one of my component. I have use axios to get data from api and this is my return json data

{
  "result": true,
  "items": [
    {
      "excerpt": "egghead is your source for the Badass Portfolio Projects you need to climb the career ladder as a modern web developer.",
      "_id": 360690368,
      "title": "Build the portfolio you need to be a badass web developer.",
      "link": "https://egghead.io/",
      "domain": "egghead.io"
    },
    {
      "excerpt": "From career choices to new purchases, use René Girard’s mimetic theory to resist the herd and forge your own path in life",
      "_id": 359605780,
      "link": "https://psyche.co/guides/how-to-know-what-you-really-want-and-be-free-from-mimetic-desire?ref=refind",
      "title": "How to know what you really want | Psyche Guides",
      "domain": "psyche.co"
    }
  ],
  "count": 2,
  "collectionId": 0
}

Here is list component:

import * as React from "react"
import axios from "axios"

axios.get("https://api.abc.com", {
  method: "get",
  headers: {
    Authorization: `Bearer xxxxxxxx-xxxx-xxxx-xxxx-xxxx`,
    "Content-Type": "application/x-www-form-urlencoded",
  },
})
.then(res => {
  const bookmarks = JSON.stringify(res.data)
  console.log(bookmarks)
})
.catch(error => {
  console.error(error)
})

const IndexPage = ({ bookmarks }) => (
  <>

Show Data

      {bookmarks.items.map(bookmark => (

{bookmark.title}

      ))}

  </>
)

export default IndexPage

Can anyone help me in displaying the list? Thanks in advance

Body:
This is not the way how data fetching in react works... you must fetch your data in components useEffect and store your data in useState hook, which will cause rerender and you can access this data:

import * as React from "react"
import axios from "axios"

const IndexPage = () => (
const [bookmarks, setBookmarks] = React.useState()

React.useEffect(()=>{
axios.get("https://api.abc.com", {
  method: "get",
  headers: {
    Authorization: `Bearer xxxxxxxx-xxxx-xxxx-xxxx-xxxx`,
    "Content-Type": "application/x-www-form-urlencoded",
  },
})
.then(res => {
  const bookmarks = JSON.stringify(res.data)
  setBookmarks(bookmarks)
})
.catch(error => {
  console.error(error)
})
},[])
return(
  <>
    <h1>Show Data</h1>
    <div>
      {bookmarks.items.map(bookmark => (
        <div>{bookmark.title}</div>
      ))}
    </div>
  </>
)

edit: with custom loading solution:

import * as React from "react"
import axios from "axios"

const IndexPage = () => (
const [loading, setLoading] = React.useState(true)
const [bookmarks, setBookmarks] = React.useState()

React.useEffect(()=>{
axios.get("https://api.abc.com", {
  method: "get",
  headers: {
    Authorization: `Bearer xxxxxxxx-xxxx-xxxx-xxxx-xxxx`,
    "Content-Type": "application/x-www-form-urlencoded",
  },
})
.then(res => {
  const bookmarks = JSON.stringify(res.data)
  setBookmarks(bookmarks)
})
.catch(error => {
  console.error(error)
}).finally(()=>{setLoading(false)});
},[])

if(loading){
 return (<>Loading...</>)
}

return(
  <>
    <h1>Show Data</h1>
    <div>
      {bookmarks.items.map(bookmark => (
        <div>{bookmark.title}</div>
      ))}
    </div>
  </>
)


问:
ExpressJS not showing debug messages
I am using ExpressJS and would like to display internal debug messages, like here https://expressjs.com/en/guide/debugging.html.

When I am using this command in VS Code (Windows Powershell) "`set DEBUG=express:*; node ./dist/app.js" it is starting my Node/Express Server, however it does not display any debug messages. Do I have to add something to my code so it works?

答:
"Express uses the debug module internally to log information about route matches, middleware functions that are in use, application mode, and the flow of the request-response cycle."
Do you have this package:
https://www.npmjs.com/package/debug
And there is no semicolon between the statements.</p>

Title: ExpressJS not showing debug messages


问:
Change order y-axis of dotplot in ggplot2
I have data as below with which I want to make a dotplot. Ggplot automatically orders the Y-axis alphabetically. I want the dotplot to be configured that it the y-axis is ordered based on the values of the X-axis, from small to large. Please see below for example code, a figure of the current outcome and a figure of example desired outcome. Thanks!

Example code:

```<code># import package
library("ggplot2")
# create fake data
set.seed(1024) # keep reproducibility
go <- paste0("GO", sample(1000:2000, 5))
Count <- sample(1:20, 10)
data <- data.frame("GOs" = rep(go, 2),
                   "Condition" = rep(c("A", "B"), each = 5),
                   "GeneRatio" = 1 / sample(10, 10),
                   "p.adjust" = 0.05 / sample(10, 10),
                   "Count" = Count)

# plot: dot plot
ggplot(data = data, aes(x = GeneRatio, y = GOs,
                        color = `p.adjust`, size = Count)) +
  geom_point() +
  scale_color_gradient(low = "red", high = "blue") +
  theme_bw() +
  ylab("") +
  xlab("") +
  ggtitle("GO enrichment analysis")
</code>```

Current outcome:

Desired outcome should be something like this:

答:
I can think of two solutions that will solve your issue. For clarity the plots are faceted by condition.

Option 1 (modified version of previous answer):

```<code>library(tidyverse)

data_ordered  <- data %>%
  group_by(Condition) %>% # group by condition
  mutate(GOs = fct_reorder2(GOs, GeneRatio,-GeneRatio)) %>%  # reorder GOs by GeneRatio
  ungroup()

# plot 1
ggplot(data = data_ordered,
       aes(
         x = GeneRatio,
         y = GOs,
         color = `p.adjust`,
         size = Count
       )) +
  geom_point() +
  scale_color_gradient(low = "red", high = "blue") +
  theme_bw() +
  ylab("Ontology") +
  xlab("GeneRatio") +
  ggtitle("GO enrichment analysis") +
  facet_grid( ~ Condition)# facet plot by condition
</code>```

Option 2:

```<code>data_ordered_2 <- data %>%
  group_by(Condition) %>% # group by condition
  arrange(Condition, GeneRatio) %>% # arrange by Condition and GeneRatio
  mutate(GOs_ordered = factor (row_number(), labels = GOs)) # add column containing ordered GOs

# plot 2
ggplot(data = data_ordered_2,
       aes(
         x = GeneRatio,
         y = GOs_ordered,
         color = `p.adjust`,
         size = Count
       )) +
  geom_point() +
  scale_color_gradient(low = "red", high = "blue") +
  theme_bw() +
  ylab("Ontology") +
  xlab("GeneRatio") +
  ggtitle("Option 2") +
  facet_grid( ~ Condition)# facet plot by condition
</code>```

Body:
I have data as below with which I want to make a dotplot. Ggplot automatically orders the Y-axis alphabetically. I want the dotplot to be configured that it the y-axis is ordered based on the values of the X-axis, from small to large. Please see below for example code, a figure of the current outcome and a figure of example desired outcome. Thanks!

Example code:

# import package
library("ggplot2")
# create fake data
set.seed(1024) # keep reproducibility
go <- paste0("GO", sample(1000:2000, 5))
Count <- sample(1:20, 10)
data <- data.frame("GOs" = rep(go, 2),
                   "Condition" = rep(c("A", "B"), each = 5),
                   "GeneRatio" = 1 / sample(10, 10),
                   "p.adjust" = 0.05 / sample(10, 10),
                   "Count" = Count)

# plot: dot plot
ggplot(data = data, aes(x = GeneRatio, y = GOs,
                        color = `p.adjust`, size = Count)) +
  geom_point() +
  scale_color_gradient(low = "red", high = "blue") +
  theme_bw() +
  ylab("") +
  xlab("") +
  ggtitle("GO enrichment analysis")

Current outcome:

Desired outcome should be something like this:

Body:
I can think of two solutions that will solve your issue. For clarity the plots are faceted by condition.

Option 1 (modified version of previous answer):

library(tidyverse)

data_ordered  <- data %>%
  group_by(Condition) %>% # group by condition
  mutate(GOs = fct_reorder2(GOs, GeneRatio,-GeneRatio)) %>%  # reorder GOs by GeneRatio
  ungroup()

# plot 1
ggplot(data = data_ordered,
       aes(
         x = GeneRatio,
         y = GOs,
         color = `p.adjust`,
         size = Count
       )) +
  geom_point() +
  scale_color_gradient(low = "red", high = "blue") +
  theme_bw() +
  ylab("Ontology") +
  xlab("GeneRatio") +
  ggtitle("GO enrichment analysis") +
  facet_grid( ~ Condition)# facet plot by condition

Option 2:

data_ordered_2 <- data %>%
  group_by(Condition) %>% # group by condition
  arrange(Condition, GeneRatio) %>% # arrange by Condition and GeneRatio
  mutate(GOs_ordered = factor (row_number(), labels = GOs)) # add column containing ordered GOs

# plot 2
ggplot(data = data_ordered_2,
       aes(
         x = GeneRatio,
         y = GOs_ordered,
         color = `p.adjust`,
         size = Count
       )) +
  geom_point() +
  scale_color_gradient(low = "red", high = "blue") +
  theme_bw() +
  ylab("Ontology") +
  xlab("GeneRatio") +
  ggtitle("Option 2") +
  facet_grid( ~ Condition)# facet plot by condition


问:
Python script can't change user agent and proxies on Chrome
Actually, i have a script who start a chrome session (not headless). I want to change and rotate user agent and proxies, with fake_useragent and proxy_randomizer libraries.
I've see on somes topics here how to make this, but not work on my chrome session.
I use chromedriver 98.0.4758.82 and chrome browser 98.0.4758.82, and i don't have any error message on terminal. On "userAgent" string and "proxf" string, user agent and proxy are correctly rotate, i think an error is in argument on chrome option, but i don't know.
Here is my script today:

```<code>from fake_useragent import UserAgent
from proxy_randomizer import RegisteredProviders
from proxy_randomizer.proxy import Anonymity
import requests

# URL
url = "https://www.carrefour.fr"

warnings.filterwarnings("ignore")

# Proxies
rp = RegisteredProviders()
rp.parse_providers()
#print(f"proxy: {rp.get_random_proxy()}")
for proxy in rp.proxies:
     proxies     = { "https": f"{proxy.ip_address}:{proxy.port}" }
     #response    = requests.get("http://google.com", proxies=proxies)
prox = rp.get_random_proxy()
proxip = prox.ip_address
proxpo = prox.port
proxf = "https://"+str(proxip)+":"+str(proxpo)
#print(prox)
#print(proxip)
#print(proxpo)
#print(proxf)

# Ouverture Chrome
options = Options()
ua = UserAgent()
userAgent = ua.random
print(userAgent)
#options.headless = True
driver = webdriver.Chrome(options=options)
options.add_argument(f'user-agent={userAgent}')
options.add_argument('--proxy-server=%s' % proxf)
driver.get(url)
driver.execute_script("return navigator.userAgent;")
</code>```

Anyone have an idea why my user agent and proxies are not used on chrome session please? I think i have correct requests, but i don't know...
Thanks for help!
Bye

答:
It's ok now, here is the correct code:</p>
```<code>from fake_useragent import UserAgent
from proxy_randomizer import RegisteredProviders
from proxy_randomizer.proxy import Anonymity
import requests
from fresh_useragent import UserAgent

def getRandomUserAgent():
    lines = open('UAStrings.txt').read().splitlines()
    return random.choice(lines)
ua = getRandomUserAgent()

prox = rp.get_random_proxy()
proxl = "http://"+str(prox)

options.add_argument(f'user-agent={ua}')
options.add_argument(f'--proxy-server={proxl}')
</code>```

Body:
Actually, i have a script who start a chrome session (not headless). I want to change and rotate user agent and proxies, with fake_useragent and proxy_randomizer libraries.
I've see on somes topics here how to make this, but not work on my chrome session.
I use chromedriver 98.0.4758.82 and chrome browser 98.0.4758.82, and i don't have any error message on terminal. On "userAgent" string and "proxf" string, user agent and proxy are correctly rotate, i think an error is in argument on chrome option, but i don't know.
Here is my script today:

from fake_useragent import UserAgent
from proxy_randomizer import RegisteredProviders
from proxy_randomizer.proxy import Anonymity
import requests

# URL
url = "https://www.carrefour.fr"

warnings.filterwarnings("ignore")

# Proxies
rp = RegisteredProviders()
rp.parse_providers()
#print(f"proxy: {rp.get_random_proxy()}")
for proxy in rp.proxies:
     proxies     = { "https": f"{proxy.ip_address}:{proxy.port}" }
     #response    = requests.get("http://google.com", proxies=proxies)
prox = rp.get_random_proxy()
proxip = prox.ip_address
proxpo = prox.port
proxf = "https://"+str(proxip)+":"+str(proxpo)
#print(prox)
#print(proxip)
#print(proxpo)
#print(proxf)

# Ouverture Chrome
options = Options()
ua = UserAgent()
userAgent = ua.random
print(userAgent)
#options.headless = True
driver = webdriver.Chrome(options=options)
options.add_argument(f'user-agent={userAgent}')
options.add_argument('--proxy-server=%s' % proxf)
driver.get(url)
driver.execute_script("return navigator.userAgent;")

Anyone have an idea why my user agent and proxies are not used on chrome session please? I think i have correct requests, but i don't know...
Thanks for help!
Bye

Body:
It's ok now, here is the correct code:

from fake_useragent import UserAgent
from proxy_randomizer import RegisteredProviders
from proxy_randomizer.proxy import Anonymity
import requests
from fresh_useragent import UserAgent

def getRandomUserAgent():
    lines = open('UAStrings.txt').read().splitlines()
    return random.choice(lines)
ua = getRandomUserAgent()

prox = rp.get_random_proxy()
proxl = "http://"+str(prox)

options.add_argument(f'user-agent={ua}')
options.add_argument(f'--proxy-server={proxl}')


问:
Design tips for a program to be run in 25 years
If creating an application (that does mostly data processing) that needs to be run now and maybe (maybe not) 10 or 25 years later, what design tips are out there for such applications?

The general rules apply: rely on open source software and proven platforms and failsafe data formats.

The language must be a high-level language for readability reasons (maybe the only option will be re-writing the application in 15 years by someone who has little knowledge of the original code).

I'd go for UNIX(Linux)+Python+YAML/JSON(/CSV/plaintext), any tips for this selection or an alternative toolset? Scheme/lisp has been around for ages and is really hard to screw up the language basics as well, given that everything would be self-contained.

EDIT: please don't forget tips about actual design and code, like 2038 year issue!

答:
Java may be a good language to write it in.  java has excellent backwards compatibility, a large standard library that also has good backwards compatibility, and is popular enough that it will most likely be around in 25 years.  Even if java falls out of favour, there are enough jvm languages like scala and clojure that one will probably become popular enough to ensure the survival of the jvm and java as a by product.

Python may not be a good choice, as they occasionally break compatibility (python 3 is not compatible with python 2).


问:
head tag not appearing in view source : next:js
i have created my next js appp where i have implemented my head tag but when i check the view source  by right clicking i dont see my title and meta tags there  how can i achive that?

eventhough the head tag is missing in view souce  it can be found in inspect element

```<code><Head>
                <title> {itm.Name} - wixten </title>
                <link rel="shortcut icon" href="/wixten.png" />
                <meta
                  name="viewport"
                  content="initial-scale=1.0, width=device-width"
                />
                <meta name="description" content={itm.Summary} />
                <meta charSet="utf-8" />
                <meta property="og:title" content={itm.Name} />
                <meta property="og:description" content={itm.Summary} />
                <meta property="og:image" content="images/wixten.png" />
                <meta property="og:locale" key="og:locale" content="en_US" />
                <meta property="og:type" key="og:type" content="website" />
                <meta
                  property="og:url"
                  key="og:url"
                  content={`${baseurl}${itm._id}`}
                />
              </Head>
</code>```

i am adding full code in codesandbox

https://codesandbox.io/s/sweet-franklin-gpht9?file=/pages/index.js

the website i am faceing issue is this

https://wixten.com/query/61f4f5f9e41f700023c833c0

答: You have to call your head in the return otherwise it won't appear on the client side</p>

Body:
i have created my next js appp where i have implemented my head tag but when i check the view source  by right clicking i dont see my title and meta tags there  how can i achive that?

eventhough the head tag is missing in view souce  it can be found in inspect element

                <title> {itm.Name} - wixten </title>
                <link rel="shortcut icon" href="/wixten.png" />
                <meta
                  name="viewport"
                  content="initial-scale=1.0, width=device-width"
                />
                <meta name="description" content={itm.Summary} />
                <meta charSet="utf-8" />
                <meta property="og:title" content={itm.Name} />
                <meta property="og:description" content={itm.Summary} />
                <meta property="og:image" content="images/wixten.png" />
                <meta property="og:locale" key="og:locale" content="en_US" />
                <meta property="og:type" key="og:type" content="website" />
                <meta
                  property="og:url"
                  key="og:url"
                  content={`${baseurl}${itm._id}`}
                />

i am adding full code in codesandbox

https://codesandbox.io/s/sweet-franklin-gpht9?file=/pages/index.js

the website i am faceing issue is this

https://wixten.com/query/61f4f5f9e41f700023c833c0


问:
How can i get rid of the exception 'The RPC server is unavailable' while saving the Outlook message via python?
I'm working with win32com library and try to save mail i've just created.
I use .CreateItem() function to create mail instance and try to save it using mail.Save()
Unfortunately i get this exception (-2147023174, 'The RPC server is unavailable.', None, None). Thank you very much in advance.

答:
Most probably the Outlook.exe process has finished its work and gone. Check out the list of running processes when you got this kind of errors.

You may try to get an instance of the Explorer window to stop Outlook from closing by using Explorers.Add method which creates a new instance of the explorer window.

```<code>Sub DisplayDrafts()
 Dim myExplorers As Outlook.Explorers
 Dim myOlExpl As Outlook.Explorer
 Dim myFolder As Outlook.Folder

 Set myExplorers = Application.Explorers
 Set myFolder = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderDrafts)
 Set myOlExpl = myExplorers.Add(myFolder, olFolderDisplayNoNavigation)
' myOlExpl.Display
End Sub
</code>```

Body:
Most probably the Outlook.exe process has finished its work and gone. Check out the list of running processes when you got this kind of errors.

You may try to get an instance of the Explorer window to stop Outlook from closing by using Explorers.Add method which creates a new instance of the explorer window.

Sub DisplayDrafts()
 Dim myExplorers As Outlook.Explorers
 Dim myOlExpl As Outlook.Explorer
 Dim myFolder As Outlook.Folder

 Set myExplorers = Application.Explorers
 Set myFolder = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderDrafts)
 Set myOlExpl = myExplorers.Add(myFolder, olFolderDisplayNoNavigation)
' myOlExpl.Display
End Sub


问:
Ruby on Rails: How to Permit parameters with "_json"
I am trying to get POST requests to work coming from a React.js application to a Ruby on Rails API.

The parameters are:

```<code>Parameters: {"_json"=>"{'Name': 'ExampleSurvey', 'Draft_Status': 'true', 'Active_Status': 'false' }", "survey"=>{}}
</code>```

My survey_params method is:

```<code> def survey_params
    params.permit(:Name, :Draft_Status, :Active_Status)
 end
</code>```

My API Call from React is:

```<code>const post = (endpoint, body) => {
    const url = ANAMNESIS_CONFIG.backend.location + endpoint ?? '';
    return fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Anamnesis-Secret': ANAMNESIS_CONFIG.backend.secret
        },
        body: JSON.stringify(body)
    }).then(response => response.json())
};
</code>```
```<code>const submitHandler = e => {
        e.preventDefault();
        console.log({ surveyDetails })
        post('survey',`{'Name': '${surveyDetails.name}', 'Draft_Status': 'true', 'Active_Status': 'false' }`)
    }
</code>```

The following Curl Request allows me to enter new surveys without any issues:

```<code>curl -X POST -d "Name=Example&Draft_Status=true&Active_Status=false" http://localhost:3000/survey
</code>```

How can I edit Rails or React to get the Post request to work properly in a way that allows the curl request to still work?

Update:
Here is a picture from the logs: The first request is from Curl. The second request is from React. Hope this helps make the error more clear. Thanks for the help so far.

[

答:
In your controller you might want to skip forgery protection for json requests. It would be useful if you'd share a part of your logs where POST from React happens, otherwise it's hard to tell what the reason could be. This works when you get Can't verify CSRF token authenticity for your POST requests.

class ApplicationController < ActionController::Base
  protect_from_forgery unless: -> { request.format.json? }
end
```

Body:
I am trying to get POST requests to work coming from a React.js application to a Ruby on Rails API.

The parameters are:

Parameters: {"_json"=>"{'Name': 'ExampleSurvey', 'Draft_Status': 'true', 'Active_Status': 'false' }", "survey"=>{}}

My survey_params method is:

 def survey_params
    params.permit(:Name, :Draft_Status, :Active_Status)
 end

My API Call from React is:

const post = (endpoint, body) => {
    const url = ANAMNESIS_CONFIG.backend.location + endpoint ?? '';
    return fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Anamnesis-Secret': ANAMNESIS_CONFIG.backend.secret
        },
        body: JSON.stringify(body)
    }).then(response => response.json())
};

const submitHandler = e => {
        e.preventDefault();
        console.log({ surveyDetails })
        post('survey',`{'Name': '${surveyDetails.name}', 'Draft_Status': 'true', 'Active_Status': 'false' }`)
    }

The following Curl Request allows me to enter new surveys without any issues:

curl -X POST -d "Name=Example&Draft_Status=true&Active_Status=false" http://localhost:3000/survey

How can I edit Rails or React to get the Post request to work properly in a way that allows the curl request to still work?

Update:
Here is a picture from the logs: The first request is from Curl. The second request is from React. Hope this helps make the error more clear. Thanks for the help so far.

[


问:
Updating an existing List using Linq in C#
I have a list and data as follows.

```<code>public class Test
{
 public int Id {get;set;}
 public string Name {get;set;}
 public string Quality {get;set;}
}

Test test = new Test();
//db call to get test data
//test = [{1,'ABC','Good'},{2,'GEF','Bad'}]
</code>```

I have to modify the list such that Name should be only the first 2 characters and Quality should be the first letter.

Expected Output:

```<code>//test = [{1,'A','G'},{2,'GE','B'}]
</code>```

I tried to achieve with Linq foreach as follows. But I am not sure to write conditional statements inside forloop within Linq which resulted in error.

```<code>test.ForEach(x=> return x.Take(1))
</code>```

答:
List.ForEach is not LINQ though

```<code>test.ForEach(t => { t.Name = t.Name.Length > 2 ? t.Name.Remove(2) : t.Name; t.Quality = t.Quality.Length > 1 ? t.Quality.Remove(1) : t.Quality; });
</code>```

Better would be to simply call a method that does this.

```<code>test.ForEach(Modify);
</code>```

```<code>private static void Modify(Test t)
{
    // ,,,
}
</code>```

Body:
I have a list and data as follows.

public class Test
{
 public int Id {get;set;}
 public string Name {get;set;}
 public string Quality {get;set;}
}

Test test = new Test();
//db call to get test data
//test = [{1,'ABC','Good'},{2,'GEF','Bad'}]

I have to modify the list such that Name should be only the first 2 characters and Quality should be the first letter.

Expected Output:

//test = [{1,'A','G'},{2,'GE','B'}]

I tried to achieve with Linq foreach as follows. But I am not sure to write conditional statements inside forloop within Linq which resulted in error.

test.ForEach(x=> return x.Take(1))

Body:
List.ForEach is not LINQ though

test.ForEach(t => { t.Name = t.Name.Length > 2 ? t.Name.Remove(2) : t.Name; t.Quality = t.Quality.Length > 1 ? t.Quality.Remove(1) : t.Quality; });

Better would be to simply call a method that does this.

test.ForEach(Modify);

private static void Modify(Test t)
{
    // ,,,
}


问:
vscode shortcut key for making one edittor group bigger than others
When having multiple editor groups, they take the same space in VSCode. For example, if I have 2 vertical groups, each one takes 50% of my screen. Now, if I double click on a file name in the group e.g. 2, this group takes about 70% of my screen and becomes bigger, so I can see the code better. If I double click again, both groups will be 50-50 again.

What is this feature called? What's the shortcut key for it?

答:
This feature is called Toggle Editor Group Sizes And there is no shortcut by default, but You can set it as you like. I set my own shortcut (Ctrl+Shift+Alt+9) and tested it successfully.

Tested with Ubuntu 20.04 and Visual Studio Code 1.64.0


问:
Expected ',' or '...' before numeric const
I am new in C programming and trying to figure out some problems encountered.
When I wrote </p>

```<code>#define N 5

void Sort(int *const array,  int N);
</code>```

<p>the compiler gave me the message "Expected ',' or '...' before numeric const". After searching on the internet and found out that the problem may be casued by the #define being debugged as numeric values. I did get through the compiler by not using the #define for the constant N. However, I wondered how should I modified the above two lines so that I won't get that error message?  </p>

答:
For VS compiler you can do this:</p>

```

#define N 5

#ifdef N
    #pragma push_macro("N")
    #undef N

    #define REDEFINE_N
#endif

void Sort(int *const array,  int N);

#ifdef REDEFINE_N
    #pragma pop_macro("N")
#endif

```

Body:
I am new in C programming and trying to figure out some problems encountered.
When I wrote

#define N 5

void Sort(int *const array,  int N);

the compiler gave me the message "Expected ',' or '...' before numeric const". After searching on the internet and found out that the problem may be casued by the #define being debugged as numeric values. I did get through the compiler by not using the #define for the constant N. However, I wondered how should I modified the above two lines so that I won't get that error message?

Body:
For VS compiler you can do this:

#define N 5

#ifdef N
    #pragma push_macro("N")
    #undef N

    #define REDEFINE_N
#endif

void Sort(int *const array,  int N);

#ifdef REDEFINE_N
    #pragma pop_macro("N")
#endif


问:
css variables - declare variable if not already defined
I have a project which is split up into the parent app, and several reusable child components in separate repositories.  I'd like to define default CSS variables in these child components, which can be overridden by the parent app, however I can't find the right syntax for this.  Here's what I've tried:

```<code>/* parent */
:root {
  --color: blue;
}

/* child */
:root {
  --color: var(--color, green);
}

.test {
  width: 200px;
  height: 200px;
  background: var(--color, red);
}
</code>```

https://codepen.io/daviestar/pen/brModx

The color should be blue, but when the child :root is defined, the color is actually red, at least in Chrome.

Is there a correct approach for this?  In SASS you can add a !default flag to your child variables which basically means 'declare if it's not already declared'.

答:
I would suggest an approach by aliasing the variables in the component and using "parent" or root variables as main value while local value is by !default.

.parent {
  --background: red;
}

.child {
  --child_size: var(--size, 30px); /* !default with alias */
  --child_background: var(--background, green); /* !default with alias */

  background-color: var(--child_background);
  width: var(--child_size);
  height: var(--child_size);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="child"></div>
</div>
<hr>
<div class="child"></div>  </code>```

Body:
I have a project which is split up into the parent app, and several reusable child components in separate repositories.  I'd like to define default CSS variables in these child components, which can be overridden by the parent app, however I can't find the right syntax for this.  Here's what I've tried:

/* parent */
:root {
  --color: blue;
}

/* child */
:root {
  --color: var(--color, green);
}

.test {
  width: 200px;
  height: 200px;
  background: var(--color, red);
}

https://codepen.io/daviestar/pen/brModx

The color should be blue, but when the child :root is defined, the color is actually red, at least in Chrome.

Is there a correct approach for this?  In SASS you can add a !default flag to your child variables which basically means 'declare if it's not already declared'.

Body:
I would suggest an approach by aliasing the variables in the component and using "parent" or root variables as main value while local value is by !default.

.parent {
  --background: red;
}

.child {
  --child_size: var(--size, 30px); /* !default with alias */
  --child_background: var(--background, green); /* !default with alias */

  background-color: var(--child_background);
  width: var(--child_size);
  height: var(--child_size);
}

<div class="parent">
  <div class="child"></div>
</div>
<hr>
<div class="child"></div>


问:
Material Button icon is not aligned properly when iconPadding is small
Create a MaterialButton with following attributes:

```<code><com.google.android.material.button.MaterialButton
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        app:icon="@drawable/ic_star"
        app:iconGravity="textStart"
        app:iconPadding="0dp" />
</code>```

When updating the text to a short text, like "123", that does not change the width of the button, the icon does not align properly and may overlap the text. But if the text is long enough, like "123456789", to change the button's width, everything is alright.

It is more obvious when iconPadding is set to a small number like zero. In the gif above iconPadding is 2.

Android API version:

API 21, 26, 29

Material Library version:

com.google.android.material:material:1.6.0-alpha02

Am I doing something wrong? or this is a bug.

How can I resolve this issue?

答:
Update:

The issue is fixed (see here), waiting for the next release.

For anyone how has faced the same problem:

I reported this issue in github (here) and it is marked as a bug.

I will update this answer if it is fixed in next versions.

Body:
Create a MaterialButton with following attributes:

<com.google.android.material.button.MaterialButton
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        app:icon="@drawable/ic_star"
        app:iconGravity="textStart"
        app:iconPadding="0dp" />

When updating the text to a short text, like "123", that does not change the width of the button, the icon does not align properly and may overlap the text. But if the text is long enough, like "123456789", to change the button's width, everything is alright.

It is more obvious when iconPadding is set to a small number like zero. In the gif above iconPadding is 2.

Android API version:

API 21, 26, 29

Material Library version:

com.google.android.material:material:1.6.0-alpha02

Am I doing something wrong? or this is a bug.

How can I resolve this issue?


问:
When I start Milvus Cluster by helm, I encounter this error "0/4 nodes are available: 4 node(s) didn't satisfy existing pods anti-affinity rules."
I follow this link to install milvus cluster. When I execute this command "helm install my-release milvus/milvus" ,I find that a pod never started successfully.
enter image description here

```<code>$ kubectl get pod | grep lcl
lcl-release-milvus-querynode-56b9b4d54d-9r7jl      0/1     Pending            0                6h31m here
</code>```

Then I use "kubectl describe pods lcl-release-milvus-querynode-56b9b4d54d-9r7jl" to get the following info.

```<code>$ kubectl describe pods lcl-release-milvus-querynode-56b9b4d54d-9r7j
0/4 nodes are available: 4 node(s) didn't satisfy existing pods anti-affinity rules.
</code>```

Who can help me analyze the problem?

答: Base on the milvus chart, only the etcd has the affinity setup, but your "queryNode" also has the affinity set? You need to remove the affinity that you have set here for queryNode.

Body:
I follow this link to install milvus cluster. When I execute this command "helm install my-release milvus/milvus" ,I find that a pod never started successfully.
enter image description here

$ kubectl get pod | grep lcl
lcl-release-milvus-querynode-56b9b4d54d-9r7jl      0/1     Pending            0                6h31m here

Then I use "kubectl describe pods lcl-release-milvus-querynode-56b9b4d54d-9r7jl" to get the following info.

$ kubectl describe pods lcl-release-milvus-querynode-56b9b4d54d-9r7j
0/4 nodes are available: 4 node(s) didn't satisfy existing pods anti-affinity rules.

Who can help me analyze the problem?


问:
Javascript method document.querySelector alternative in VueJs for optimization
I need to optimize my code with all features of VueJs, so i've changed all the document.getElementById and document.querySelectorAll by using the ref in VueJs

So the only thing that i dont found an alternative is how to change :
document.querySelector with another code related to VueJs :

```<code>document.querySelector('.mc-layer__content').classList.add('disable-scroll')
</code>```

Is there any optimization related to this ?

Another important point, i can't use the ref here because the class is in the parent no in the component, so when i use this.$refs i can't see the parent element.

答:
The solution that i've foud is to use the store because the parent isnt direct :

In the child component instead to use document.querySelector,

```<code>document.querySelector('.mc-layer__content').classList.remove('disable-scroll')
</code>```

i've used :

```<code>this.$store.dispatch('app/disableScroll')
</code>```

And in the parent, i've add the dynamic class :

```<code>:class="{ 'disable-scroll': isDisabled }"
</code>```

The variable isDisabled has been managed in the store with disableScroll variable like this:

```<code>disableScroll(state) {
      state.disableScroll = true
    },
    enableScroll(state) {
      state.disableScroll = false
    },
</code>```

Body:
I need to optimize my code with all features of VueJs, so i've changed all the document.getElementById and document.querySelectorAll by using the ref in VueJs

So the only thing that i dont found an alternative is how to change :
document.querySelector with another code related to VueJs :

document.querySelector('.mc-layer__content').classList.add('disable-scroll')

Is there any optimization related to this ?

Another important point, i can't use the ref here because the class is in the parent no in the component, so when i use this.$refs i can't see the parent element.

Body:
The solution that i've foud is to use the store because the parent isnt direct :

In the child component instead to use document.querySelector,

document.querySelector('.mc-layer__content').classList.remove('disable-scroll')

i've used :

this.$store.dispatch('app/disableScroll')

And in the parent, i've add the dynamic class :

:class="{ 'disable-scroll': isDisabled }"

The variable isDisabled has been managed in the store with disableScroll variable like this:

disableScroll(state) {
      state.disableScroll = true
    },
    enableScroll(state) {
      state.disableScroll = false
    },


问:
UserModel showing error for status of the user
Can somebody help me in resolving the error. There is an error in UserModel.fromDocumentSnapshot. ITs telling userstatus has to be initialized. I have initialized it but yet the error remains. Can somebody tell me what could be the error in tis code. Looking forward to resolve this error. Please do help me

```<code>import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:get/get.dart';
import 'package:hogoco_meet_app/model/base_model.dart';
import 'package:hogoco_meet_app/services/firebasedb.dart';

enum UserStatus { Active, Inactive, None }

extension on String {
  UserStatus get getuserStatus {
    switch (this) {
      case 'Active':
        return UserStatus.Active;
        break;
      case 'Inactive':
        return UserStatus.Inactive;
        break;
      default:
        return UserStatus.None;
        break;
    }
  }
}

extension ExtendedUserStatus on UserStatus {
  bool get active => this == UserStatus.Active;
  bool get inactive => this == UserStatus.Inactive;
  bool get none => this == UserStatus.None;
  String get getuserStatus {
    switch (this) {
      case UserStatus.Active:
        return 'Active';
        break;
      case UserStatus.Inactive:
        return 'Inactive';
        break;
      default:
        return 'None';
        break;
    }
  }
}

class UserModel extends BaseModel {
  String? id;
  String? userProfilePhotoUrl;
  String? userFullName;
  String? userEmail;
  UserStatus userStatus;
  bool? userIsVerified;
  Timestamp? userRegDate;
  Timestamp? userLastLoginDate;
  List<UserModel>? userFriends;

  UserModel(
      {this.id,
      this.userProfilePhotoUrl,
      this.userFullName,
      this.userEmail,
      this.userStatus = UserStatus.Inactive,
      this.userIsVerified,
      this.userRegDate,
      this.userLastLoginDate,
      this.userFriends});

  @override
  String toString() {
    return '''UserModel: {userRegDate = ${this.userRegDate},id = ${this.id},userFullName = ${this.userFullName},userProfilePhotoURL = ${this.userProfilePhotoUrl},
    userEmail = ${this.userEmail},userFriends = ${this.userFriends},userIsVerified = ${this.userIsVerified},userStatus = ${this.userStatus}}''';
  }

  UserModel.fromDocumentSnapshot({DocumentSnapshot? documentSnapshot}) {
    final _userStatus = ((documentSnapshot!.data()! as Map<String, dynamic>)
            .containsKey('userStatus'))
        ? ((documentSnapshot.data()! as Map<String, dynamic>)["userStatus"]
                as String)
            .getuserStatus
        : UserStatus.None;

    id = documentSnapshot.id;
    userProfilePhotoUrl = (documentSnapshot.data()
        as Map<String, dynamic>)['userProfilePhotoUrl'];
    userFullName =
        (documentSnapshot.data() as Map<String, dynamic>)["userFullName"];
    userEmail = (documentSnapshot.data() as Map<String, dynamic>)["userEmail"];
    userStatus = _userStatus;
    userIsVerified =
        (documentSnapshot.data() as Map<String, dynamic>)["userIsVerified"];
    userRegDate =
        (documentSnapshot.data() as Map<String, dynamic>)['userRegDate'];
    userLastLoginDate =
        (documentSnapshot.data() as Map<String, dynamic>)['userLastLoginDate'];
    userFriends =
        (documentSnapshot.data() as Map<String, dynamic>)["userFriends"];
  }
}

class UserCrud {
  final FirebaseService<UserModel> firebaseService =
      Get.put(FirebaseService<UserModel>());

  static const String Collection = FirebaseCollections.USER;

  Stream<List<UserModel>> get getUsers {
    return firebaseService.getListStream(
      collection: Collection,
      returnVal: (query) {
        final retVal = <UserModel>[];
        query.docs.forEach((element) {
          retVal.add(UserModel.fromDocumentSnapshot(documentSnapshot: element));
        });
        return retVal;
      },
    );
  }
}
</code>```

Error

error: Non-nullable instance field 'userStatus' must be initialized. (not_initialized_non_nullable_instance_field at [hogoco_meet_app] lib\model\user_model.dart:71)

答:
The userStatus field is the only field that is declared non-nullable, which means you have to initialize it before the constructor is executed.

UserModel.fromDocumentSnapshot({DocumentSnapshot? documentSnapshot}) is called a named constructor, therefore to be able to use it you need to initialize the userStatus first and you can do that by adding it to the initializer list:

```<code>    UserModel.fromDocumentSnapshot({DocumentSnapshot? documentSnapshot}) : userStatus = UserStatus.Inactive {
    final _userStatus = ((documentSnapshot!.data()! as Map<String, dynamic>)
            .containsKey('userStatus'))
        ? ((documentSnapshot.data()! as Map<String, dynamic>)["userStatus"]
                as String)
            .getuserStatus
        : UserStatus.None;

    id = documentSnapshot.id;
    userProfilePhotoUrl = (documentSnapshot.data()
        as Map<String, dynamic>)['userProfilePhotoUrl'];
    userFullName =
        (documentSnapshot.data() as Map<String, dynamic>)["userFullName"];
    userEmail = (documentSnapshot.data() as Map<String, dynamic>)["userEmail"];
    userStatus = _userStatus;
    userIsVerified =
        (documentSnapshot.data() as Map<String, dynamic>)["userIsVerified"];
    userRegDate =
        (documentSnapshot.data() as Map<String, dynamic>)['userRegDate'];
    userLastLoginDate =
        (documentSnapshot.data() as Map<String, dynamic>)['userLastLoginDate'];
    userFriends =
        (documentSnapshot.data() as Map<String, dynamic>)["userFriends"];
  }
</code>```

Body:
Can somebody help me in resolving the error. There is an error in UserModel.fromDocumentSnapshot. ITs telling userstatus has to be initialized. I have initialized it but yet the error remains. Can somebody tell me what could be the error in tis code. Looking forward to resolve this error. Please do help me

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:get/get.dart';
import 'package:hogoco_meet_app/model/base_model.dart';
import 'package:hogoco_meet_app/services/firebasedb.dart';

enum UserStatus { Active, Inactive, None }

extension on String {
  UserStatus get getuserStatus {
    switch (this) {
      case 'Active':
        return UserStatus.Active;
        break;
      case 'Inactive':
        return UserStatus.Inactive;
        break;
      default:
        return UserStatus.None;
        break;
    }
  }
}

extension ExtendedUserStatus on UserStatus {
  bool get active => this == UserStatus.Active;
  bool get inactive => this == UserStatus.Inactive;
  bool get none => this == UserStatus.None;
  String get getuserStatus {
    switch (this) {
      case UserStatus.Active:
        return 'Active';
        break;
      case UserStatus.Inactive:
        return 'Inactive';
        break;
      default:
        return 'None';
        break;
    }
  }
}

class UserModel extends BaseModel {
  String? id;
  String? userProfilePhotoUrl;
  String? userFullName;
  String? userEmail;
  UserStatus userStatus;
  bool? userIsVerified;
  Timestamp? userRegDate;
  Timestamp? userLastLoginDate;
  List<UserModel>? userFriends;

  UserModel(
      {this.id,
      this.userProfilePhotoUrl,
      this.userFullName,
      this.userEmail,
      this.userStatus = UserStatus.Inactive,
      this.userIsVerified,
      this.userRegDate,
      this.userLastLoginDate,
      this.userFriends});

  @override
  String toString() {
    return '''UserModel: {userRegDate = ${this.userRegDate},id = ${this.id},userFullName = ${this.userFullName},userProfilePhotoURL = ${this.userProfilePhotoUrl},
    userEmail = ${this.userEmail},userFriends = ${this.userFriends},userIsVerified = ${this.userIsVerified},userStatus = ${this.userStatus}}''';
  }

  UserModel.fromDocumentSnapshot({DocumentSnapshot? documentSnapshot}) {
    final _userStatus = ((documentSnapshot!.data()! as Map<String, dynamic>)
            .containsKey('userStatus'))
        ? ((documentSnapshot.data()! as Map<String, dynamic>)["userStatus"]
                as String)
            .getuserStatus
        : UserStatus.None;

    id = documentSnapshot.id;
    userProfilePhotoUrl = (documentSnapshot.data()
        as Map<String, dynamic>)['userProfilePhotoUrl'];
    userFullName =
        (documentSnapshot.data() as Map<String, dynamic>)["userFullName"];
    userEmail = (documentSnapshot.data() as Map<String, dynamic>)["userEmail"];
    userStatus = _userStatus;
    userIsVerified =
        (documentSnapshot.data() as Map<String, dynamic>)["userIsVerified"];
    userRegDate =
        (documentSnapshot.data() as Map<String, dynamic>)['userRegDate'];
    userLastLoginDate =
        (documentSnapshot.data() as Map<String, dynamic>)['userLastLoginDate'];
    userFriends =
        (documentSnapshot.data() as Map<String, dynamic>)["userFriends"];
  }
}

class UserCrud {
  final FirebaseService<UserModel> firebaseService =
      Get.put(FirebaseService<UserModel>());

  static const String Collection = FirebaseCollections.USER;

  Stream<List<UserModel>> get getUsers {
    return firebaseService.getListStream(
      collection: Collection,
      returnVal: (query) {
        final retVal = <UserModel>[];
        query.docs.forEach((element) {
          retVal.add(UserModel.fromDocumentSnapshot(documentSnapshot: element));
        });
        return retVal;
      },
    );
  }
}

Error

error: Non-nullable instance field 'userStatus' must be initialized. (not_initialized_non_nullable_instance_field at [hogoco_meet_app] lib\model\user_model.dart:71)

Body:
The userStatus field is the only field that is declared non-nullable, which means you have to initialize it before the constructor is executed.

UserModel.fromDocumentSnapshot({DocumentSnapshot? documentSnapshot}) is called a named constructor, therefore to be able to use it you need to initialize the userStatus first and you can do that by adding it to the initializer list:

    UserModel.fromDocumentSnapshot({DocumentSnapshot? documentSnapshot}) : userStatus = UserStatus.Inactive {
    final _userStatus = ((documentSnapshot!.data()! as Map<String, dynamic>)
            .containsKey('userStatus'))
        ? ((documentSnapshot.data()! as Map<String, dynamic>)["userStatus"]
                as String)
            .getuserStatus
        : UserStatus.None;

    id = documentSnapshot.id;
    userProfilePhotoUrl = (documentSnapshot.data()
        as Map<String, dynamic>)['userProfilePhotoUrl'];
    userFullName =
        (documentSnapshot.data() as Map<String, dynamic>)["userFullName"];
    userEmail = (documentSnapshot.data() as Map<String, dynamic>)["userEmail"];
    userStatus = _userStatus;
    userIsVerified =
        (documentSnapshot.data() as Map<String, dynamic>)["userIsVerified"];
    userRegDate =
        (documentSnapshot.data() as Map<String, dynamic>)['userRegDate'];
    userLastLoginDate =
        (documentSnapshot.data() as Map<String, dynamic>)['userLastLoginDate'];
    userFriends =
        (documentSnapshot.data() as Map<String, dynamic>)["userFriends"];
  }


问:
notepad++ find number greater than a specific number
I have logs with some random numbers.

What I want to do is find numbers greater than a specific number, eg : find all number > 1234567.

Can anybody help?

答:
For anyone that can't get that to work change the first line into these 2 lines.

import re

from re import finditer


问:
CSS z-index issue
Here is the fiddle: http://jsfiddle.net/6Lk4s/

```<code><div class="box">
    <div class="c1"></div>
    <div class="c2"></div>
</div>
</code>```

I try to display .c1 and .c2 behind .box (so box has a higher z-index and all three classes have position:relative set), but I can't get it to show up this way.

What is my error?

答:
.c1 and .c2 are part of .box (as they are child element of it) if you want them to be behind it they have to be separated elements

Also to position behind .box the easiest way is to position absolute them see: http://jsfiddle.net/6Lk4s/1/

For more documentation on how z-index works see the w3c spec thanks to @Joseph Silber: http://www.w3.org/TR/CSS2/zindex.html#painting-order

Title: CSS z-index issue

Body:
Here is the fiddle: http://jsfiddle.net/6Lk4s/

I try to display .c1 and .c2 behind .box (so box has a higher z-index and all three classes have position:relative set), but I can't get it to show up this way.

What is my error?


问:
parse string to an array in Kotlin
How can I convert a string to an array of strings in Kotlin? To demonstrate, I have this:

```<code>val input_string = "[Hello, World]"
</code>```

I would like to convert it to ["Hello", "World"].

答:
Assuming the strings only consist of letters and/or numbers you could also do it like this</p>
```<code>val input_string = "[Hello, World]"
val list = Regex("\\w+").findAll(input_string).toList().map { it.value }
</code>```

Title: parse string to an array in Kotlin

Body:
How can I convert a string to an array of strings in Kotlin? To demonstrate, I have this:

val input_string = "[Hello, World]"

I would like to convert it to ["Hello", "World"].

Body:
Assuming the strings only consist of letters and/or numbers you could also do it like this

val input_string = "[Hello, World]"
val list = Regex("\\w+").findAll(input_string).toList().map { it.value }


问:
Expressjs base API delete method show error can not get error?
I'm new is Express.js; I try to build an API without any database. All routes work correctly but the post and delete API is not working.
When I hit delete URL in the browser, I find an error.

My app.js routes page look like

```<code>import express from "express";
import logger from "morgan";
import bodyParser from "body-parser";

//  get routes
import indexRouter from "./routes/index.js";
import postRouter from "./routes/post.js";
import tagRouter from "./routes/tags.js";
import commentRouter from "./routes/comment.js";
import authorRouter from "./routes/author.js";

// post routers
import postMethodRouters from "./routes/postMethodRouters.js";

//  delete routers
import deletePostRouters from "./routes/delete.js";

var app = express();

app.use(logger("dev"));
app.use(bodyParser.json());
// app.use(express.urlencoded({ extended: false }));

//  get method
app.use("/api/v1/", indexRouter);
app.use("/api/v1/post", postRouter);
app.use("/api/v1/tags", tagRouter);
app.use("/api/v1/comments", commentRouter);
app.use("/api/v1/authors", authorRouter);

//  post method
app.use("/createPost", postMethodRouters);

//  delete method
app.use("/api/v1/", deletePostRouters);

var listener = app.listen(8080, function () {
  console.log("Listening on port " + listener.address().port);
});
</code>```

My delete.js routes look like

```<code>import express from "express";

var router = express.Router();

router.delete("/delete/:id", function (req, res) {
  res.status(200).send("DELETE request to homepage");
});

export default router;
</code>```

My post.js routers look like

```<code>import express from "express";

import getBlog from "../API/Post/singleGenrater.js";

var router = express.Router();

router.post("/", function (req, res) {

  res.send("POST request to homepage");
});
export default router;
</code>```

答:
In app.js, try to fix it like below (remove the "/" after "/api/v1")

```<code>//  delete method
app.use("/api/v1", deletePostRouters);

</code>```

Second, in the file delete.js, I see that you are using the DELETE method (router.delete("/delete/:id"), but when you call the api you use it as GET (GET /api/v1/delete/id) ? It's a different method, so it won't call the api.

Body:
I'm new is Express.js; I try to build an API without any database. All routes work correctly but the post and delete API is not working.
When I hit delete URL in the browser, I find an error.

My app.js routes page look like

import express from "express";
import logger from "morgan";
import bodyParser from "body-parser";

//  get routes
import indexRouter from "./routes/index.js";
import postRouter from "./routes/post.js";
import tagRouter from "./routes/tags.js";
import commentRouter from "./routes/comment.js";
import authorRouter from "./routes/author.js";

// post routers
import postMethodRouters from "./routes/postMethodRouters.js";

//  delete routers
import deletePostRouters from "./routes/delete.js";

var app = express();

app.use(logger("dev"));
app.use(bodyParser.json());
// app.use(express.urlencoded({ extended: false }));

//  get method
app.use("/api/v1/", indexRouter);
app.use("/api/v1/post", postRouter);
app.use("/api/v1/tags", tagRouter);
app.use("/api/v1/comments", commentRouter);
app.use("/api/v1/authors", authorRouter);

//  post method
app.use("/createPost", postMethodRouters);

//  delete method
app.use("/api/v1/", deletePostRouters);

var listener = app.listen(8080, function () {
  console.log("Listening on port " + listener.address().port);
});

My delete.js routes look like

import express from "express";

var router = express.Router();

router.delete("/delete/:id", function (req, res) {
  res.status(200).send("DELETE request to homepage");
});

export default router;

My post.js routers look like

import express from "express";

import getBlog from "../API/Post/singleGenrater.js";

var router = express.Router();

router.post("/", function (req, res) {

  res.send("POST request to homepage");
});
export default router;

Body:
In app.js, try to fix it like below (remove the "/" after "/api/v1")

//  delete method
app.use("/api/v1", deletePostRouters);

Second, in the file delete.js, I see that you are using the DELETE method (router.delete("/delete/:id"), but when you call the api you use it as GET (GET /api/v1/delete/id) ? It's a different method, so it won't call the api.


问:
How design API URLs to comply with GDPR and OWASP and avoid Personal Identifiable Information in URL
Personal Identifiable Information (PII) should be considered sensitive information and OWASP states that sensitive data should not be part of the URL. https://owasp-aasvs.readthedocs.io/en/latest/requirement-9.1.html

GDPR states that "an online identifier" identifying a person directly or indirectly is PII. https://gdpr.eu/article-4-definitions/

An API providing user preferences where a resource item could look like:

```<code>{
  "id": "abc123"           //generated id
  "language": "en_EN",
  "favoriteColor": "BLUE",
  "userId": "peter@example.com"
}
</code>```

Would it then be ok for an API to have a link to this resource?

```<code>https://example.com/user-preferences/abc123
</code>```

From my understanding this would be an example of an indirect online identifier. Does that mean the id needs to be encrypted? And if that is the case - does that mean each encryption of the id (i.e every time a URL is provided from the API) must encrypted with a different salt to avoid introducing a new indirect identifier?

Different URLs for the same resource:

```<code>https://example.com/user-preferences/87wytu09ufwc2ercler4ri // abc123 encrypted with salt A
https://example.com/user-preferences/diu4w98iuywfgommbvwdxe // abc123 encrypted with salt B
</code>```

答:
What we have here is security and compliance requirements having direct impact on our API design. Indeed, it is considered bad practice to put sensitive data into the URLs (reason - every proxy, load balancer, API gateway, web server, ... along the way is allowed to log URLs of incoming requests for debug purposes and we do not want sensitive data to be spread this way). On the other way - doing GET requests ends up being tricky, because we can not put all the stuff we would like to simply into the request body. Parameters of GET requests end up in URL because HTTP and REST is designed this way.

So, what can we do then, to satisfy security and compliance needs? At least two things come to my mind.

Put sensitive data into request headers. They will not end up being part of URL so problem solved.

Solve the problem just how you have proposed to. It is nothing new to the industry. Just follow the path of solving insecure direct object references.

I would go for 1 myself. It is less mysterious than 2 in case of what is going on and how to handle test data.

Body:
Personal Identifiable Information (PII) should be considered sensitive information and OWASP states that sensitive data should not be part of the URL. https://owasp-aasvs.readthedocs.io/en/latest/requirement-9.1.html

GDPR states that "an online identifier" identifying a person directly or indirectly is PII. https://gdpr.eu/article-4-definitions/

An API providing user preferences where a resource item could look like:

{
  "id": "abc123"           //generated id
  "language": "en_EN",
  "favoriteColor": "BLUE",
  "userId": "peter@example.com"
}

Would it then be ok for an API to have a link to this resource?

https://example.com/user-preferences/abc123

From my understanding this would be an example of an indirect online identifier. Does that mean the id needs to be encrypted? And if that is the case - does that mean each encryption of the id (i.e every time a URL is provided from the API) must encrypted with a different salt to avoid introducing a new indirect identifier?

Different URLs for the same resource:

https://example.com/user-preferences/87wytu09ufwc2ercler4ri // abc123 encrypted with salt A
https://example.com/user-preferences/diu4w98iuywfgommbvwdxe // abc123 encrypted with salt B


问:
Laravel Where Count > N
I have 2 models in my app:

1. Customer.php

2. Car.php

Now I would like to run a query that returns all customers that have less than 2 cars. Where 2 is a number that can be changed by the user.

I have tried this but it didn't work, it just returns all customer records:

```<code>$customers = Customer::whereHas("cars", function($query) {
    $query->selectRaw("count(*) < ?", [2]);
})
->get();
</code>```

Edit:
The two models are linked in a pivot table, meaning A customer can have more than 1 car and a Car can belong to more than 1 customer.

答:
This is the best way:</p>
```<code>$customers = Customer::has('cars','<', 2)->get();
</code>```

Title: Laravel Where Count > N

Body:
I have 2 models in my app:

1. Customer.php

2. Car.php

Now I would like to run a query that returns all customers that have less than 2 cars. Where 2 is a number that can be changed by the user.

I have tried this but it didn't work, it just returns all customer records:

$customers = Customer::whereHas("cars", function($query) {
    $query->selectRaw("count(*) < ?", [2]);
})
->get();

Edit:
The two models are linked in a pivot table, meaning A customer can have more than 1 car and a Car can belong to more than 1 customer.

Body:
This is the best way:

$customers = Customer::has('cars','<', 2)->get();


问:
Elegant way to correctly index a Dataframe after Subsetting
I have the following dummy dataframe with two columns:

```<code>set.seed(666)
df = data.frame(group = rep(c(-1,1), times = 5, each = 1),
                values = runif(10))

   group     values
1     -1 0.77436849
2      1 0.19722419
3     -1 0.97801384
4      1 0.20132735
5     -1 0.36124443
6      1 0.74261194
7     -1 0.97872844
8      1 0.49811371
9     -1 0.01331584
10     1 0.25994613
</code>```

I want to find the row index of the maximum value from group "1" in the original dataframe. Applying which.max() after subsetting the dataframe will return the wrong row:

```<code>which.max(df[df[,1]==1,2]) #returns '3'
</code>```

As a workaround I did the following:

```<code>sdf = df[df[,1] == 1,] # subset of dataframe that keeps row names
rownames(sdf[which.max(sdf[,2]),]) # returns '6'
</code>```

Which does return the correct row index from the original dataframe. However I feel there must be an easier, more elegant solution but can't think of anything else myself. Any ideas?

I feel really stupid for asking this question but it seems I'm overlooking something very simple.

答:
This is the tidyverse way:

library(tidyverse)
set.seed(666)
df = data.frame(group = rep(c(-1,1), times = 5, each = 1),
                values = runif(10))

df %>%
  mutate(row_number = row_number()) %>%
  group_by(group) %>%
  # descending sorting
  arrange(-values) %>%
  # pick first e.g. maximum
  slice(1) %>%
  select(group, row_number)
#> # A tibble: 2 x 2
#> # Groups:   group [2]
#>   group row_number
#>   <dbl>      <int>
#> 1    -1          7
#> 2     1          6
```

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

Body:
I have the following dummy dataframe with two columns:

set.seed(666)
df = data.frame(group = rep(c(-1,1), times = 5, each = 1),
                values = runif(10))

   group     values
1     -1 0.77436849
2      1 0.19722419
3     -1 0.97801384
4      1 0.20132735
5     -1 0.36124443
6      1 0.74261194
7     -1 0.97872844
8      1 0.49811371
9     -1 0.01331584
10     1 0.25994613

I want to find the row index of the maximum value from group "1" in the original dataframe. Applying which.max() after subsetting the dataframe will return the wrong row:

which.max(df[df[,1]==1,2]) #returns '3'

As a workaround I did the following:

sdf = df[df[,1] == 1,] # subset of dataframe that keeps row names
rownames(sdf[which.max(sdf[,2]),]) # returns '6'

Which does return the correct row index from the original dataframe. However I feel there must be an easier, more elegant solution but can't think of anything else myself. Any ideas?

I feel really stupid for asking this question but it seems I'm overlooking something very simple.

Body:
This is the tidyverse way:

library(tidyverse)
set.seed(666)
df = data.frame(group = rep(c(-1,1), times = 5, each = 1),
                values = runif(10))

df %>%
  mutate(row_number = row_number()) %>%
  group_by(group) %>%
  # descending sorting
  arrange(-values) %>%
  # pick first e.g. maximum
  slice(1) %>%
  select(group, row_number)
#> # A tibble: 2 x 2
#> # Groups:   group [2]
#>   group row_number
#>   <dbl>      <int>
#> 1    -1          7
#> 2     1          6

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


问:
What do the different brackets in Ruby mean?
In Ruby, what's the difference between {} and []?

{} seems to be used for both code blocks and hashes.

Are [] only for arrays?

The documention isn't very clear.

答:
Another, not so obvious, usage of [] is as a synonym for Proc#call and Method#call. This might be a little confusing the first time you encounter it. I guess the rational behind it is that it makes it look more like a normal function call.

E.g.

```<code>proc = Proc.new { |what| puts "Hello, #{what}!" }
meth = method(:print)

proc["World"]
meth["Hello",","," ", "World!", "\n"]
</code>```

OwnerDisplayName: Tilendor

LastEditorDisplayName: John Topley

Body:
Another, not so obvious, usage of [] is as a synonym for Proc#call and Method#call. This might be a little confusing the first time you encounter it. I guess the rational behind it is that it makes it look more like a normal function call.

E.g.

proc = Proc.new { |what| puts "Hello, #{what}!" }
meth = method(:print)

proc["World"]
meth["Hello",","," ", "World!", "\n"]

OwnerDisplayName: sris


问:
Murmur Hash 3 in python
I'm trying to implement murmur hash 3 in python. I have confusion with this function mmh3.hash_bytes(key).

Here is the code that I tried:

```<code>a = bitarray()
print(mmh3.hash('A')) # output is 1423767502 a hash value
</code>```

Next, I tried one more function

```<code>print(mmh3.hash_bytes('A'))
# output is b'z\xb1)\x9a\xb7\xc2_\x037\x99\xddF\x9c\xf2}8'
</code>```

The output of mmh3.hash_bytes('A') confuses me. Shouldn't both functions have the same value? Because both hash value 'A'. Correct me if I'm wrong.

答:
From the online documentation :

mmh3.hash("foo") # returns a 32-bit signed int

[...]

mmh3.hash_bytes("foo") # 128 bit value as bytes

Wikipedia says the same thing :

The current version is MurmurHash3, which yields a 32-bit or 128-bit hash value.

This is also explicit in the header file of the C++ implementation :

void MurmurHash3_x86_32  ( const void * key, Py_ssize_t len, uint32_t seed, void * out );

void MurmurHash3_x86_128 ( const void * key, Py_ssize_t len, uint32_t seed, void * out );

Same for the tests that verify that it is different (1, 2) :

assert mmh3.hash("foo") == -156908512

[...]

assert mmh3.hash_bytes("foo") == b"aE\xf5\x01W\x86q\xe2\x87}\xba+\xe4\x87\xaf~"

So I admit that it can be surprising that the same hash function returns two different results, but actually it is not exactly the same hash function.

Title: Murmur Hash 3 in python

Body:
I'm trying to implement murmur hash 3 in python. I have confusion with this function mmh3.hash_bytes(key).

Here is the code that I tried:

a = bitarray()
print(mmh3.hash('A')) # output is 1423767502 a hash value

Next, I tried one more function

print(mmh3.hash_bytes('A'))
# output is b'z\xb1)\x9a\xb7\xc2_\x037\x99\xddF\x9c\xf2}8'

The output of mmh3.hash_bytes('A') confuses me. Shouldn't both functions have the same value? Because both hash value 'A'. Correct me if I'm wrong.


问:
How to parse a string of version numbers in Groovy?
I have a string containing a version number like major.minor.patch.build but I only want to keep major.minor.patch where each number can have 1-3 digits.
How can I do this in groovy?

Examples for a result:
1.20.30.44 -> 1.20.30
or
1.21.1.1 -> 1.21.1

答:
That should be essentially one-liners in Groovy. To start with 2:</p>
```<code>String listBased = '1.20.30.44'.split( /\./ ).take 3 join '.'
String regexBased = '1.20.30.44'.replaceFirst( /(.+)\.[^.]+/, '$1' )

assert listBased == '1.20.30'
assert regexBased == '1.20.30'
</code>```

Body:
That should be essentially one-liners in Groovy. To start with 2:

String listBased = '1.20.30.44'.split( /\./ ).take 3 join '.'
String regexBased = '1.20.30.44'.replaceFirst( /(.+)\.[^.]+/, '$1' )

assert listBased == '1.20.30'
assert regexBased == '1.20.30'


问:
Directory copying?
I need to copy some directories with PHP, so I did a few searches and found a few scripts to try, considering that there is no built in method in PHP. I ran one of them and got an error about the maximum running time of the script being exceeding. Thinking this was because some of the files were too big, I increased that time. Little did I know, the script was recursively copying the directory and then copying it inside itself... I'm still in the process of deleting everything it made...

Anyway, I was hoping someone on here would have a reliable script they've written or know about for this type of thing.

edit: hadn't occurred to me that copying a directory to inside itself wasn't a good idea. Sorry whoever wrote the code I just trashed.

答:
```<code><?php
   function copy_directory($source, $destination, $whatsgoingon = false){
      if ($destination{strlen($destination) - 1} == '/'){
         $destination = substr($destination, 0, -1);
        }
      if (!is_dir($destination)){
         if ($whatsgoingon){
            echo "Creating directory {$destination}\n";
            }
         mkdir($destination, 0755);
      }

      $folder = opendir($source);

      while ($item = readdir($folder)){
         if ($item == '.' || $item == '..'){
            continue;
            }
         if (is_dir("{$source}/{$item}")){
            copy_dir("{$source}/{$item}", "{$destination}/{$item}", $whatsgoingon);
         }else{
            if ($whatsgoingon){
               echo "Copying {$item} to {$destination}"."\n";
            }
            copy("{$source}/{$item}", "{$destination}/{$item}");
            }
      }
   }
?>
</code>```

You can use:

```<code>copy_directory('./directory', './directory2/'); // copy the directory

copy_directory('./directory', './'); // copy the files to the same directory

copy_directory('./directory', './directory2/', true);
// Show these messages:
// Creating directory ./directory2
// Copying word.docx to ./directory2
// Copying test.txt to ./directory2
</code>```

Title: Directory copying?

Body:
<?php
   function copy_directory($source, $destination, $whatsgoingon = false){
      if ($destination{strlen($destination) - 1} == '/'){
         $destination = substr($destination, 0, -1);
        }
      if (!is_dir($destination)){
         if ($whatsgoingon){
            echo "Creating directory {$destination}\n";
            }
         mkdir($destination, 0755);
      }

      $folder = opendir($source);

      while ($item = readdir($folder)){
         if ($item == '.' || $item == '..'){
            continue;
            }
         if (is_dir("{$source}/{$item}")){
            copy_dir("{$source}/{$item}", "{$destination}/{$item}", $whatsgoingon);
         }else{
            if ($whatsgoingon){
               echo "Copying {$item} to {$destination}"."\n";
            }
            copy("{$source}/{$item}", "{$destination}/{$item}");
            }
      }
   }
?>

You can use:

copy_directory('./directory', './directory2/'); // copy the directory

copy_directory('./directory', './'); // copy the files to the same directory

copy_directory('./directory', './directory2/', true);
// Show these messages:
// Creating directory ./directory2
// Copying word.docx to ./directory2
// Copying test.txt to ./directory2


问:
Vue how to group items in v-for loop
I have an array of objects, which contains menu's from a restaurant, where the user can choose a timeslot where the menu can be delivered.

here is an example of a menu object:

```<code>{
  date: '2022-02-10',
  slots: [
     {
       stock: 10,
       start: '06:00',
       end: '08:00',
     },
     {
       stock: 8,
       start: '10:00',
       end: '12:00',
     },
     {
       stock: 3,
       start: '12:00',
       end: '14:00',
     },
     {
       stock: 3,
       start: '14:00',
       end: '16:00',
     },
     {
       stock: 3,
       start: '16:00',
       end: '18:00',
     },
     {
       stock: 20,
       start: '18:00',
       end: '20:00',
     },
     {
       stock: 8,
       start: '20:00',
       end: '22:00',
     },
  ],
},
</code>```

and here is how I render them:

```<code><div v-for="(slot, index) in slots" :key="index">
   <input type="radio" :id="index" name="slot" />
   <label :for="index">
        {{ slot.start.slice(0, 2) }} - {{ slot.end.slice(0, 2) }}
   </label>
</div>
</code>```

so far so good. Now I want to group the timeslots into "morning", "afternoon" and "evening" based on the time and display them like this:

```<code>Morning
06 - 08    10 - 12

Afternoon
12 - 14    14 - 16   16 - 18

Evening
18 - 20   20 - 22
</code>```

How can I achieve that??

Thanks in advance...

答:
Group the menu slots by the end time then render them using two v-for :

Vue.config.devtools = false;
Vue.config.productionTip = false;

function pushToSlotTime(acc, slotTime, curr) {
  if (acc[slotTime]) {
    acc[slotTime].push(curr);
  } else {

    acc[slotTime] = [];
    acc[slotTime].push(curr);
  };
  return acc;
}
new Vue({
  el: '#app',

  data() {
    return {
      menu: {
        date: '2022-02-10',
        slots: [{
            stock: 10,
            start: '06:00',
            end: '08:00',
          },
          {
            stock: 8,
            start: '10:00',
            end: '12:00',
          },
          {
            stock: 3,
            start: '12:00',
            end: '14:00',
          },
          {
            stock: 3,
            start: '14:00',
            end: '16:00',
          },
          {
            stock: 3,
            start: '16:00',
            end: '18:00',
          },
          {
            stock: 20,
            start: '18:00',
            end: '20:00',
          },
          {
            stock: 8,
            start: '20:00',
            end: '22:00',
          },
        ],
      },
    }
  },
  computed: {
    groupedMenuSlots() {
      return this.menu.slots.reduce((acc, curr) => {
        let [end] = curr.end.split(':')
        if (+end <= 12) {
          return pushToSlotTime(acc, 'morning', curr)
        } else if (+end > 12 && +end <= 18) {
          return pushToSlotTime(acc, 'afternoon', curr)
        } else {
          return pushToSlotTime(acc, 'evening', curr)
        }
      }, {})
    }

  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>

<div id="app" class="container">
  <div v-for="(slots,key, index) in groupedMenuSlots" :key="index">
    <div>{{key}}</div>
    <span class="slot" v-for="slot in slots">
      <input type="radio" :id="index" name="slot" />
      <label :for="index">
         {{ slot.start.slice(0, 2) }} - {{ slot.end.slice(0, 2) }}
   </label>
    </span>
  </div>
</div></code>```

Title: Vue how to group items in v-for loop

Body:
I have an array of objects, which contains menu's from a restaurant, where the user can choose a timeslot where the menu can be delivered.

here is an example of a menu object:

{
  date: '2022-02-10',
  slots: [
     {
       stock: 10,
       start: '06:00',
       end: '08:00',
     },
     {
       stock: 8,
       start: '10:00',
       end: '12:00',
     },
     {
       stock: 3,
       start: '12:00',
       end: '14:00',
     },
     {
       stock: 3,
       start: '14:00',
       end: '16:00',
     },
     {
       stock: 3,
       start: '16:00',
       end: '18:00',
     },
     {
       stock: 20,
       start: '18:00',
       end: '20:00',
     },
     {
       stock: 8,
       start: '20:00',
       end: '22:00',
     },
  ],
},

and here is how I render them:

   <input type="radio" :id="index" name="slot" />

        {{ slot.start.slice(0, 2) }} - {{ slot.end.slice(0, 2) }}

so far so good. Now I want to group the timeslots into "morning", "afternoon" and "evening" based on the time and display them like this:

Morning
06 - 08    10 - 12

Afternoon
12 - 14    14 - 16   16 - 18

Evening
18 - 20   20 - 22

How can I achieve that??

Thanks in advance...

Body:
Group the menu slots by the end time then render them using two v-for :

Vue.config.devtools = false;
Vue.config.productionTip = false;

function pushToSlotTime(acc, slotTime, curr) {
  if (acc[slotTime]) {
    acc[slotTime].push(curr);
  } else {

    acc[slotTime] = [];
    acc[slotTime].push(curr);
  };
  return acc;
}
new Vue({
  el: '#app',

  data() {
    return {
      menu: {
        date: '2022-02-10',
        slots: [{
            stock: 10,
            start: '06:00',
            end: '08:00',
          },
          {
            stock: 8,
            start: '10:00',
            end: '12:00',
          },
          {
            stock: 3,
            start: '12:00',
            end: '14:00',
          },
          {
            stock: 3,
            start: '14:00',
            end: '16:00',
          },
          {
            stock: 3,
            start: '16:00',
            end: '18:00',
          },
          {
            stock: 20,
            start: '18:00',
            end: '20:00',
          },
          {
            stock: 8,
            start: '20:00',
            end: '22:00',
          },
        ],
      },
    }
  },
  computed: {
    groupedMenuSlots() {
      return this.menu.slots.reduce((acc, curr) => {
        let [end] = curr.end.split(':')
        if (+end <= 12) {
          return pushToSlotTime(acc, 'morning', curr)
        } else if (+end > 12 && +end <= 18) {
          return pushToSlotTime(acc, 'afternoon', curr)
        } else {
          return pushToSlotTime(acc, 'evening', curr)
        }
      }, {})
    }

  }
})

<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>

<div id="app" class="container">
  <div v-for="(slots,key, index) in groupedMenuSlots" :key="index">
    <div>{{key}}</div>
    <span class="slot" v-for="slot in slots">
      <input type="radio" :id="index" name="slot" />
      <label :for="index">
         {{ slot.start.slice(0, 2) }} - {{ slot.end.slice(0, 2) }}
   </label>
    </span>
  </div>
</div>


问:
Phaser 3: Starting a scene (stopping all other running scenes) from the global "game" object
As the title says.. Is there a way to stop all running scenes when starting a scene from the "game" object?

For now, when I call game.scene.start(...) from outside a Scene object, nothing happens. My current solution is to keep a global variable pointing to the latest started Scene (In all my scenes, I reset that global variable in the create() function with something like currentScene = this;) So when I want to start a new Scene I call currentScene.scene.start(...). But obviously that's not reliable because I could forget to reset my global variable (currentScene) in all my scenes, etc...

EDIT:

To clarifiy what I'm trying to acheive: I'm making a small multiplayer game with a couple scenes and a few GameObjects. I've a "socket" module that handles all traffic between the client and the server (I'm using socket.io). I would want to do something like:

```<code>this.socket.on('game_end', (data) => {
    // Server decides when the game stops and sends an event to all clients.
    // Here I need to stop the currently running scene (i.e. SceneInGame)
    // and show the "game finished / results" scene.
    this.game.scene.start('SceneGameEnd');
    // ^ That doesn't work. SceneInGame keeps playing and SceneGameEnd doesn't start
});
</code>```

答:
There's a way I was able to do this, that at least works with Phaser 3.55 by accessing the current scene manually and starting the new scene from there.

For example: game.scene.keys.myCurrentScene.scene.start('SceneGameEnd')
This will effectively call the this.scene of myCurrentScene and replace that scene by starting SceneGameEnd

Where myCurrentScene would be the key of the current running scene.
You can see the scene key at game.scene.keys property where all scenes are listed by key name.
However, this would only work if you know what's the key of the current running scene.
Probably there's a way to get the current running scene but I can't answer that one.

There is however a more of a brute force workaround if you don't know the key of the current running scene. You could run a loop through all scenes, regardless if it is running or not, from the array of game.scene.scenes and call scene.stop on all scenes and then run just the one you need.

For example:

// Stop all scenes
game.scenes.forEach((scene) => {
  const key = scene.scene.key; // This is not a typo, the scene here is more like a "game" object, so the scene actually is under the "scene" property.
  game.scene.stop(key);
})
// After stopping all scenes, then you can start only the scene you need
game.scene.start('SceneGameEnd');
```

Body:
As the title says.. Is there a way to stop all running scenes when starting a scene from the "game" object?

For now, when I call game.scene.start(...) from outside a Scene object, nothing happens. My current solution is to keep a global variable pointing to the latest started Scene (In all my scenes, I reset that global variable in the create() function with something like currentScene = this;) So when I want to start a new Scene I call currentScene.scene.start(...). But obviously that's not reliable because I could forget to reset my global variable (currentScene) in all my scenes, etc...

EDIT:

To clarifiy what I'm trying to acheive: I'm making a small multiplayer game with a couple scenes and a few GameObjects. I've a "socket" module that handles all traffic between the client and the server (I'm using socket.io). I would want to do something like:

this.socket.on('game_end', (data) => {
    // Server decides when the game stops and sends an event to all clients.
    // Here I need to stop the currently running scene (i.e. SceneInGame)
    // and show the "game finished / results" scene.
    this.game.scene.start('SceneGameEnd');
    // ^ That doesn't work. SceneInGame keeps playing and SceneGameEnd doesn't start
});