问:
How to do a group by and then filter on a column in ArangoDB
My object is below :

Document Name: Test

```<code>[{
        "_key": "12123",
        "custom_key": "1",
        value = "2"
    }, {
        "_key": "12124",
        "custom_key": "1",
        value = "3"
    }, {
        "_key": "12125",
        "custom_key": "2",
        value = "2"
    }, {
        "_key": "12126",
        "custom_key": "2",
        value = "5"
    }, {
        "_key": "12127",
        "custom_key": "2",
        value = "10"
    }
]
</code>```

How to write an arango query to get the objects with maximum value group by custom_key?

答:
Unfortunately, at the moment there is no MAX_BY aggregate function, but as a workaround you can use something like this:

```<code>FOR d IN docs
  COLLECT key = d.custom_key AGGREGATE v = MAX([d.value, d])
  RETURN { custom_key: key, doc: v[1] }
</code>```

Body:
My object is below :

Document Name: Test

[{
        "_key": "12123",
        "custom_key": "1",
        value = "2"
    }, {
        "_key": "12124",
        "custom_key": "1",
        value = "3"
    }, {
        "_key": "12125",
        "custom_key": "2",
        value = "2"
    }, {
        "_key": "12126",
        "custom_key": "2",
        value = "5"
    }, {
        "_key": "12127",
        "custom_key": "2",
        value = "10"
    }
]

How to write an arango query to get the objects with maximum value group by custom_key?

Body:
Unfortunately, at the moment there is no MAX_BY aggregate function, but as a workaround you can use something like this:

FOR d IN docs
  COLLECT key = d.custom_key AGGREGATE v = MAX([d.value, d])
  RETURN { custom_key: key, doc: v[1] }


来源: stackexchange

问:
Get the first part of a url path
If I have a url like:

http://localhost:53830/Organisations/1216/View

I want to alert the first part of the url path in lowercase format e.g. 'organisations'

So far I have:

```<code>var first = $(location).attr('pathname');

first.indexOf(1);

first.replace('/', '');

first.toLowerCase();

alert(first);
</code>```

but it's not working as intended. Can anyone help? Thanks

答:
You can use URL</p>
```<code>const first = new URL(location.href).pathname.split("/")[1]
</code>```

ContentLicense: CC BY-SA 3.0

Title: Get the first part of a url path

Body:
If I have a url like:

http://localhost:53830/Organisations/1216/View

I want to alert the first part of the url path in lowercase format e.g. 'organisations'

So far I have:

var first = $(location).attr('pathname');

first.indexOf(1);

first.replace('/', '');

first.toLowerCase();

alert(first);

but it's not working as intended. Can anyone help? Thanks

Body:
You can use URL

const first = new URL(location.href).pathname.split("/")[1]

ContentLicense: CC BY-SA 4.0


问:
delete from json conditionally
I have some JSON that looks like this

```<code>var js = '{
            "person" : {
                        "firstname" : "Steve",
                        "lastname" : "Smith",
                        "other": [
                                    {
                                       "age" : "32",
                                       "deceased" : false
                                    },
                                    {
                                       "age" : "14",
                                       "deceased" : false
                                    },
                                    {
                                       "age" : "421",
                                       "deceased" : false
                                    }
                                 ]
                       }
         }'
</code>```

I know how I delete all of "other" by doing this

```<code>var j = JSON.parse(js)
delete j[person.other]
</code>```

but what I really want is to delete the "other" node with a condition that is age = 14.

The result JSON I am looking for is

```<code>{
            "person" : {
                        "firstname" : "Steve",
                        "lastname" : "Smith",
                        "other": [
                                    {
                                       "age" : "32",
                                       "deceased" : false
                                    },
                                    {
                                       "age" : "421",
                                       "deceased" : false
                                    }
                                 ]
                       }
}
</code>```

I have looked at the delete operator here and it does not provide a conditional.

Sorry if this is too simple a question. I am learning.

Thanks

答:
You can use a filter on the array doing something like

```<code>j[person.other].filter(x => x.age != 14)
</code>```

Doc on how filter works more in depth here :

https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

Title: delete from json conditionally

Body:
I have some JSON that looks like this

var js = '{
            "person" : {
                        "firstname" : "Steve",
                        "lastname" : "Smith",
                        "other": [
                                    {
                                       "age" : "32",
                                       "deceased" : false
                                    },
                                    {
                                       "age" : "14",
                                       "deceased" : false
                                    },
                                    {
                                       "age" : "421",
                                       "deceased" : false
                                    }
                                 ]
                       }
         }'

I know how I delete all of "other" by doing this

var j = JSON.parse(js)
delete j[person.other]

but what I really want is to delete the "other" node with a condition that is age = 14.

The result JSON I am looking for is

{
            "person" : {
                        "firstname" : "Steve",
                        "lastname" : "Smith",
                        "other": [
                                    {
                                       "age" : "32",
                                       "deceased" : false
                                    },
                                    {
                                       "age" : "421",
                                       "deceased" : false
                                    }
                                 ]
                       }
}

I have looked at the delete operator here and it does not provide a conditional.

Sorry if this is too simple a question. I am learning.

Thanks

Body:
You can use a filter on the array doing something like

j[person.other].filter(x => x.age != 14)

Doc on how filter works more in depth here :

https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Array/filter


问:
In SSIS script task not getting execute when it is deployed as an single package
I have an SSIS package in which I am using script tasks. Sometimes after making changes to this package and deploying it as a single package, I find that the package runs without error but doesn't actually execute the script task. If I deploy the project as a whole - without making any changes to the package the script task perfectly.

In short, if I do a project deployment the script task work as expected but as a package deployment it doesn't work, there are occasions when deploying the project is not possible so this workaround isn't always available.

I am using Vs 2016 and my target deployment version is also SQL server 2016.

I am unable to identify the root cause for this kind of issue.

答:
You can try setting the logging option of the SQL Server Agent Job.

It can be also related to permissions. Executing the SSIS package will use your security context but running it from the agent impersonates the credentials defined in the proxy, and then runs the job step by using that security context.

Try also adding the event handlers to know better about the logs.


问:
Elasticsearch: Look for a term at the end of text
I'm indexing the following documents in Elasticsearch 5.x:

```<code>{
    "id": 1
    "description": "The quick brown fox"
}

{
    "id": 2
    "description": "The fox runs fast"
}

</code>```

If I search for the word "fox" in these documents, I will get both of them.
 How can I find documents that their description field ends with the word "fox"? In the above example, I am looking the one with id=1

If possible, I prefer to do this with a Query String.

答:
Elastic uses Lucene's Regex engine, which doesn't support everything. To solve your particular problem however, you can use wildcard search or regexp search like so:</p>
```<code>GET /products/_search
{
  "query": {
    "wildcard": {
      "description.keyword": {
        "value": "*able"
      }
    }
  }
}

GET /products/_search
{
  "query": {
    "regexp":{
      "description.keyword": {
        "value": "[a-zA-Z0-9]+fox",
        "flags": "ALL",
        "case_insensitive": true
      }
    }
  }
}
</code>```

Body:
I'm indexing the following documents in Elasticsearch 5.x:

{
    "id": 1
    "description": "The quick brown fox"
}

{
    "id": 2
    "description": "The fox runs fast"
}

If I search for the word "fox" in these documents, I will get both of them.
 How can I find documents that their description field ends with the word "fox"? In the above example, I am looking the one with id=1

If possible, I prefer to do this with a Query String.

Body:
Elastic uses Lucene's Regex engine, which doesn't support everything. To solve your particular problem however, you can use wildcard search or regexp search like so:

GET /products/_search
{
  "query": {
    "wildcard": {
      "description.keyword": {
        "value": "*able"
      }
    }
  }
}

GET /products/_search
{
  "query": {
    "regexp":{
      "description.keyword": {
        "value": "[a-zA-Z0-9]+fox",
        "flags": "ALL",
        "case_insensitive": true
      }
    }
  }
}


问:
Where to put styled components styles
components for styling my react app, so far i had a separate folder in each page's folder called Styles and stored my styled component wrappers inside it( e.g. ThemeToggler.Style.js or Section.Style.js and ... ).

But i realized that my code is getting messy and project files count increases so fast because creating a component means creating 2 files, also some styles was so simple and small that i decided to write them inside the component's main file, because its more readable.

But i still feel that this approach is not good too because some styles are too long to put them inside the component's file , also some styles are not about the component it self, maybe i have a style for showing the adjacent nav of this div if user clicks on it. I thought that i'll put them inside a separate file called DivOnHover.js but it seems not correct :)

I'll like to hear your approach for managing styled-components styles, how do you store them in your folder structure ?

答:
My Folder Structure would be like this</p>
```<code>/app
  /pages ( React Router )
  /styles ( CSS only )
  /components ( Reusable Components )
  /styled ( Styled Components )
  /hooks ( React Hooks )
  index.js
  app.js
  routes.js ( React Router )
</code>```

Title: Where to put styled components styles

Body:
My Folder Structure would be like this

/app
  /pages ( React Router )
  /styles ( CSS only )
  /components ( Reusable Components )
  /styled ( Styled Components )
  /hooks ( React Hooks )
  index.js
  app.js
  routes.js ( React Router )


问:
Sort a list of object w.r.t to a particular member/state
I have a list of java object that have 4 members.

```<code>int id;
String name;
String age;
int order;
</code>```

I want to sort the list of this object w.r.t name

答: Have a look at Arrays.sort.</p>

Body:
I have a list of java object that have 4 members.

int id;
String name;
String age;
int order;

I want to sort the list of this object w.r.t name

Body: Have a look at Arrays.sort.


问:
Intermittent HTML select freezes on Safari in iOS 15 onwards
We have a single page app written in HTML/Javascript and our customers are experiencing intermittent freezes when using HTML select drop downs on Safari on iPads in all versions of iOS 15, but not on iOS 14 or earlier. Freezes often seem to occur when coming out of sleep mode. Closing Safari and reopening fixes the problem, but its still an inconvenience if input hasn't been saved etc. We have some legacy jQuery Mobile drop downs, but the problem occurs both with those and with plain JS ones.

We've tried restarting machines, checking storage, turning off any Safari extensions, turning off GPU Process Canvas Rendering (which seems to be on by default in iOS 15) and more. It doesn't seem to be specific to particular models as users have a wide range of these.

I know the UI of select elements was changed in iOS 15 - has anyone elese experienced problems with this?

答:
Yes, I've experienced an issue with HTML selects that might be related to yours:

create a desktop shortcut to a PWA with a HTML select

open PWA

click on select => should open (OK)

press home button

activate PWA again

click on select => does NOT open

Restarting the app fixes the problem until the next reboot.

Checked that on iOS 15.1 to 15.4, error occurs on all systems. Works on iOS 14. I haven't yet found a reported issue.


问:
How do can I use the setvalue() in a foreach() loop?[Google sheet Script]
It's my first post and I am a newbee in google sheets script programing.

I want to my script when I run it, to go first through a list of clients(row[0]). when the client has been found, test for the row[2] if it is a "yes" or "no" string object and when it is a "yes" option, rewrite it as a "no".

another question that i have is how can I know which ligne (row) i am testing when i am using the foreach function.

```<code>function cleanpassagepage(NomClient)
{
  const passageclientsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("relevé chez client");
  const numlastrowIS = passageclientsheet.getLastRow();
  const dataIS = passageclientsheet.getRange(2,1,numlastrowIS,3).getValues();
  dataIS.forEach(function(row)
  {
    if (row[0]==NomClient)
    {
      if(row[2]=="non")
      {
        row[2]= setValue("oui");
      }
    }
  });
}
</code>```

PS : the script doesn't give me an error to understand where did I messed up.

thank you

答:
setValue is for range

you can try this (I have also added the num of row)

```<code>function cleanpassagepage(NomClient)
{
  const passageclientsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("relevé chez client");
  const numlastrowIS = passageclientsheet.getLastRow();
  const dataIS = passageclientsheet.getRange(2,1,numlastrowIS,3).getValues();
  var lignes=[]
  dataIS.forEach(function(row,i)
  {
    if (row[0]==NomClient)
    {
      if(row[2]=="non")
      {
        row[2]= "oui"
        lignes.push(i+2)
      }
    }
  });
  passageclientsheet.getRange(2,1,numlastrowIS,3).setValues(dataIS)
  if (lignes.length>0) Browser.msgBox('Ligne(s) modifiée()s : '+lignes.join(','))
}
</code>```

reference

setValue()

Body:
It's my first post and I am a newbee in google sheets script programing.

I want to my script when I run it, to go first through a list of clients(row[0]). when the client has been found, test for the row[2] if it is a "yes" or "no" string object and when it is a "yes" option, rewrite it as a "no".

another question that i have is how can I know which ligne (row) i am testing when i am using the foreach function.

function cleanpassagepage(NomClient)
{
  const passageclientsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("relevé chez client");
  const numlastrowIS = passageclientsheet.getLastRow();
  const dataIS = passageclientsheet.getRange(2,1,numlastrowIS,3).getValues();
  dataIS.forEach(function(row)
  {
    if (row[0]==NomClient)
    {
      if(row[2]=="non")
      {
        row[2]= setValue("oui");
      }
    }
  });
}

PS : the script doesn't give me an error to understand where did I messed up.

thank you

Body:
setValue is for range

you can try this (I have also added the num of row)

function cleanpassagepage(NomClient)
{
  const passageclientsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("relevé chez client");
  const numlastrowIS = passageclientsheet.getLastRow();
  const dataIS = passageclientsheet.getRange(2,1,numlastrowIS,3).getValues();
  var lignes=[]
  dataIS.forEach(function(row,i)
  {
    if (row[0]==NomClient)
    {
      if(row[2]=="non")
      {
        row[2]= "oui"
        lignes.push(i+2)
      }
    }
  });
  passageclientsheet.getRange(2,1,numlastrowIS,3).setValues(dataIS)
  if (lignes.length>0) Browser.msgBox('Ligne(s) modifiée()s : '+lignes.join(','))
}

reference

setValue()


问:
What are differences between { default as name } and { name as default } when exporting js modules?
I was taking a look to the swiper.esm.js from Swiper.js (source copied here for reference), and the first line is

```<code>export { default as Swiper, default } from './core/core.js';
</code>```

while the following are of the form:

```<code>export { default as Virtual } from './modules/virtual/virtual.js';
</code>```

and in MDN docs i can find that also something like

```<code>export { Something as default }
</code>```

is possible. So I can currently see the following syntaxes:

```<code>export { Something as default }
export { default as Something }
export { default as Something, default }
</code>```

What are the difference between the 3?

答:
```<code>// Import name `Something` from `...`,
//   re-export as this module's default export
export { Something as default } from '...';

// Import default export from `...`,
//   re-export as `Something` from this module
export { default as Something } from '...';

// Import default export from `...`,
//   re-export it as `Something` from this module
//   and this module's default export
export { default as Something, default } from '...';
</code>```

Body:
I was taking a look to the swiper.esm.js from Swiper.js (source copied here for reference), and the first line is

export { default as Swiper, default } from './core/core.js';

while the following are of the form:

export { default as Virtual } from './modules/virtual/virtual.js';

and in MDN docs i can find that also something like

export { Something as default }

is possible. So I can currently see the following syntaxes:

export { Something as default }
export { default as Something }
export { default as Something, default }

What are the difference between the 3?


问:
display icon in a column in react-table on mouseover/enter
Using React-table. Want to show/hide an icon in a single column on mouse enter/exit. Changing the row background via css is nbd but haven't found the trick to altering css for a single cell on row mouseover.

Wanted to know if there was a straightforward method before I start spinning a web-of-states to push the signal around.

答:
FWIW:

in the column descriptor:

```<code>Cell: ({row}) =>  <div className={`${rootClass}__table-icon`} row-key={row.id}}><SVGItem/></div>
</code>```

make sure the
 has onMouseEnter and onMouseLeave defined

add:

```<code>function rowMouseEnter(row:any) {
    document.querySelector("[row-key='" + row.id + "']").className = `${rootClass}__table-icon-selected`
}

function rowMouseLeave(row:any) {
    document.querySelector("[row-key='" + row.id + "']").className = `${rootClass}__table-icon`
}
</code>```

in css add

&__table-icon-selected: visibility: visible

and

&__table-icon: visibility: none

Body:
FWIW:

in the column descriptor:

Cell: ({row}) =>  <div className={`${rootClass}__table-icon`} row-key={row.id}}><SVGItem/></div>

make sure the <tr> has onMouseEnter and onMouseLeave defined

add:

function rowMouseEnter(row:any) {
    document.querySelector("[row-key='" + row.id + "']").className = `${rootClass}__table-icon-selected`
}

function rowMouseLeave(row:any) {
    document.querySelector("[row-key='" + row.id + "']").className = `${rootClass}__table-icon`
}

in css add

&__table-icon-selected: visibility: visible

and

&__table-icon: visibility: none


问:
CSS Grid - move it behind the menu bar
Problem: i am building a webpage and learning to use grids with CSS.
But i am running into a problem with it, as the dropdown menu i have at the top of the page, goes BEHIND the grid-items.

i've tried using the z-index: -1; and z-index:1; on just about every block there is regarding both the menu and the grid.
But so far have been unsuccesfull.

So here i am.

How do i do this??

A fiddle to see my "problem"

Here is a FIDDLE of the problem.

it might just be me which is missing something obvious, but i am still learning :D

.grid-container {
  display: grid;
  grid-template-columns: 350px 350px 350px;
  justify-content: center;
}

.grid-item {
  position: relative;
  border: 2px solid rgb(13, 7, 95);
  margin: 5px;
  padding-left: 20px;
  font-weight: bold;
}

.menu-bar {
  border-radius: 25px;
  height: -webkit-fit-content;
  height: -moz-fit-content;
  height: fit-content;
  display: inline-flex;
  background-color: rgba(0, 0, 0, 0.4);
  -webkit-backdrop-filter: blur(10px);
  backdrop-filter: blur(10px);
  align-items: center;
  padding: 0 10px;
  margin: 50px 0 0 0;
}

.menu-bar li {
  list-style: none;
  color: white;
  font-family: sans-serif;
  font-weight: bold;
  padding: 12px 16px;
  margin: 0 8px;
  position: relative;
  cursor: pointer;
  white-space: nowrap;
}

.menu-bar li::before {
  content: " ";
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  transition: 0.2s;
  border-radius: 25px;
}

.menu-bar li:hover {
  color: black;
}

.menu-bar li:hover::before {
  background: linear-gradient(to bottom, #e8edec, #d2d1d3);
  box-shadow: 0px 3px 20px 0px black;
  transform: scale(1.2);
}

ul {
  list-style-type: none;
  margin: 10px;
  padding: 10px;
}

li {
  float: center;
}

li a,
.dropbtn {
  display: inline-block;
  color: black;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover,
.dropdown:hover .dropbtn {
  background-color: red;
}

li.dropdown {
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);

}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover {
  background-color: #f1f1f1;
  z-index: 1;
}

.dropdown:hover .dropdown-content {
  display: block;
  z-index: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="menu-bar">
  <li class="dropdown">
    <p>Test 1</p>
    <div class="dropdown-content">
      <p> test 1 </p>
      <p> test 2 </p>
      <p> test 3 </p>
      <p> test 4 </p>
    </div>
  </li>
  <li class="dropdown">
    <p>Test 2</p>
    <div class="dropdown-content">
      <p> test 1 </p>
      <p> test 2 </p>
      <p> test 3 </p>
      <p> test 4 </p>
    </div>
  </li>
  <li class="dropdown">
    <p>Test 3</p>
    <div class="dropdown-content">
      <p> test 1 </p>
      <p> test 2 </p>
      <p> test 3 </p>
      <p> test 4 </p>
    </div>
  </li>
  <li class="dropdown">
    <p>Test 4 </p>
  </li>
  <li class="dropdown">
    <p>Test 5 </p>
    <div class="dropdown-content">
      <p> test 1 </p>
      <p> test 2 </p>
      <p> test 3 </p>
      <p> test 4 </p>
    </div>
  </li>
</ul>
<div class="grid-container">
  <div class="grid-item">
    <p> hello world </p>
  </div>
</div></code>```

答:
Remove position: relative from .grid-item:

.grid-container {
  display: grid;
  grid-template-columns: 350px 350px 350px;
  justify-content: center;
}

.grid-item {
  border: 2px solid rgb(13, 7, 95);
  margin: 5px;
  padding-left: 20px;
  font-weight: bold;
}

.menu-bar {
  border-radius: 25px;
  height: -webkit-fit-content;
  height: -moz-fit-content;
  height: fit-content;
  display: inline-flex;
  background-color: rgba(0, 0, 0, 0.4);
  -webkit-backdrop-filter: blur(10px);
  backdrop-filter: blur(10px);
  align-items: center;
  padding: 0 10px;
  margin: 50px 0 0 0;
}

.menu-bar li {
  list-style: none;
  color: white;
  font-family: sans-serif;
  font-weight: bold;
  padding: 12px 16px;
  margin: 0 8px;
  position: relative;
  cursor: pointer;
  white-space: nowrap;
}

.menu-bar li::before {
  content: " ";
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  transition: 0.2s;
  border-radius: 25px;
}

.menu-bar li:hover {
  color: black;
}

.menu-bar li:hover::before {
  background: linear-gradient(to bottom, #e8edec, #d2d1d3);
  box-shadow: 0px 3px 20px 0px black;
  transform: scale(1.2);
}

ul {
  list-style-type: none;
  margin: 10px;
  padding: 10px;
}

li {
  float: center;
}

li a,
.dropbtn {
  display: inline-block;
  color: black;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover,
.dropdown:hover .dropbtn {
  background-color: red;
}

li.dropdown {
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);

}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover {
  background-color: #f1f1f1;
  z-index: 1;
}

.dropdown:hover .dropdown-content {
  display: block;
  z-index: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="menu-bar">
  <li class="dropdown">
    <p>Test 1</p>
    <div class="dropdown-content">
      <p> test 1 </p>
      <p> test 2 </p>
      <p> test 3 </p>
      <p> test 4 </p>
    </div>
  </li>
  <li class="dropdown">
    <p>Test 2</p>
    <div class="dropdown-content">
      <p> test 1 </p>
      <p> test 2 </p>
      <p> test 3 </p>
      <p> test 4 </p>
    </div>
  </li>
  <li class="dropdown">
    <p>Test 3</p>
    <div class="dropdown-content">
      <p> test 1 </p>
      <p> test 2 </p>
      <p> test 3 </p>
      <p> test 4 </p>
    </div>
  </li>
  <li class="dropdown">
    <p>Test 4 </p>
  </li>
  <li class="dropdown">
    <p>Test 5 </p>
    <div class="dropdown-content">
      <p> test 1 </p>
      <p> test 2 </p>
      <p> test 3 </p>
      <p> test 4 </p>
    </div>
  </li>
</ul>
<div class="grid-container">
  <div class="grid-item">
    <p> hello world </p>
  </div>
</div></code>```

Title: CSS Grid - move it behind the menu bar

Body:
Problem: i am building a webpage and learning to use grids with CSS.
But i am running into a problem with it, as the dropdown menu i have at the top of the page, goes BEHIND the grid-items.

i've tried using the z-index: -1; and z-index:1; on just about every block there is regarding both the menu and the grid.
But so far have been unsuccesfull.

So here i am.

How do i do this??

A fiddle to see my "problem"

Here is a FIDDLE of the problem.

it might just be me which is missing something obvious, but i am still learning :D

.grid-container {
  display: grid;
  grid-template-columns: 350px 350px 350px;
  justify-content: center;
}

.grid-item {
  position: relative;
  border: 2px solid rgb(13, 7, 95);
  margin: 5px;
  padding-left: 20px;
  font-weight: bold;
}

.menu-bar {
  border-radius: 25px;
  height: -webkit-fit-content;
  height: -moz-fit-content;
  height: fit-content;
  display: inline-flex;
  background-color: rgba(0, 0, 0, 0.4);
  -webkit-backdrop-filter: blur(10px);
  backdrop-filter: blur(10px);
  align-items: center;
  padding: 0 10px;
  margin: 50px 0 0 0;
}

.menu-bar li {
  list-style: none;
  color: white;
  font-family: sans-serif;
  font-weight: bold;
  padding: 12px 16px;
  margin: 0 8px;
  position: relative;
  cursor: pointer;
  white-space: nowrap;
}

.menu-bar li::before {
  content: " ";
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  transition: 0.2s;
  border-radius: 25px;
}

.menu-bar li:hover {
  color: black;
}

.menu-bar li:hover::before {
  background: linear-gradient(to bottom, #e8edec, #d2d1d3);
  box-shadow: 0px 3px 20px 0px black;
  transform: scale(1.2);
}

ul {
  list-style-type: none;
  margin: 10px;
  padding: 10px;
}

li {
  float: center;
}

li a,
.dropbtn {
  display: inline-block;
  color: black;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover,
.dropdown:hover .dropbtn {
  background-color: red;
}

li.dropdown {
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);

}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover {
  background-color: #f1f1f1;
  z-index: 1;
}

.dropdown:hover .dropdown-content {
  display: block;
  z-index: 1;
}

Test 1

 test 1

 test 2

 test 3

 test 4

Test 2

 test 1

 test 2

 test 3

 test 4

Test 3

 test 1

 test 2

 test 3

 test 4

Test 4

Test 5

 test 1

 test 2

 test 3

 test 4

 hello world

Body:
Remove position: relative from .grid-item:

.grid-container {
  display: grid;
  grid-template-columns: 350px 350px 350px;
  justify-content: center;
}

.grid-item {
  border: 2px solid rgb(13, 7, 95);
  margin: 5px;
  padding-left: 20px;
  font-weight: bold;
}

.menu-bar {
  border-radius: 25px;
  height: -webkit-fit-content;
  height: -moz-fit-content;
  height: fit-content;
  display: inline-flex;
  background-color: rgba(0, 0, 0, 0.4);
  -webkit-backdrop-filter: blur(10px);
  backdrop-filter: blur(10px);
  align-items: center;
  padding: 0 10px;
  margin: 50px 0 0 0;
}

.menu-bar li {
  list-style: none;
  color: white;
  font-family: sans-serif;
  font-weight: bold;
  padding: 12px 16px;
  margin: 0 8px;
  position: relative;
  cursor: pointer;
  white-space: nowrap;
}

.menu-bar li::before {
  content: " ";
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  transition: 0.2s;
  border-radius: 25px;
}

.menu-bar li:hover {
  color: black;
}

.menu-bar li:hover::before {
  background: linear-gradient(to bottom, #e8edec, #d2d1d3);
  box-shadow: 0px 3px 20px 0px black;
  transform: scale(1.2);
}

ul {
  list-style-type: none;
  margin: 10px;
  padding: 10px;
}

li {
  float: center;
}

li a,
.dropbtn {
  display: inline-block;
  color: black;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover,
.dropdown:hover .dropbtn {
  background-color: red;
}

li.dropdown {
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);

}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover {
  background-color: #f1f1f1;
  z-index: 1;
}

.dropdown:hover .dropdown-content {
  display: block;
  z-index: 1;
}

<ul class="menu-bar">
  <li class="dropdown">
    <p>Test 1</p>
    <div class="dropdown-content">
      <p> test 1 </p>
      <p> test 2 </p>
      <p> test 3 </p>
      <p> test 4 </p>
    </div>
  </li>
  <li class="dropdown">
    <p>Test 2</p>
    <div class="dropdown-content">
      <p> test 1 </p>
      <p> test 2 </p>
      <p> test 3 </p>
      <p> test 4 </p>
    </div>
  </li>
  <li class="dropdown">
    <p>Test 3</p>
    <div class="dropdown-content">
      <p> test 1 </p>
      <p> test 2 </p>
      <p> test 3 </p>
      <p> test 4 </p>
    </div>
  </li>
  <li class="dropdown">
    <p>Test 4 </p>
  </li>
  <li class="dropdown">
    <p>Test 5 </p>
    <div class="dropdown-content">
      <p> test 1 </p>
      <p> test 2 </p>
      <p> test 3 </p>
      <p> test 4 </p>
    </div>
  </li>
</ul>
<div class="grid-container">
  <div class="grid-item">
    <p> hello world </p>
  </div>
</div>


问:
HTTP Content-Type Header and JSON
I have always been trying to avoid using most of the HTTP protocol's properties for the sake of fear of the unknown.

However, I said to myself that I'm going to face fear today and start using headers purposefully. I have been trying to send json data to the browser and use it right away. For example, if I have an Ajax handler function on ready state 4 which looks like so:

```<code>function ajaxHandler(response){
    alert(response.text);
}
</code>```

And I have set the content-type header in my PHP code:

```<code>header('Content-Type: application/json');
echo json_encode(array('text' => 'omrele'));
</code>```

Why can't I directly access the property from the handler function, when the browser is clearly told that the incoming data is application/json?

答:
This is old but for me PHP8 it works if the  charset is set example.</p>
```<code>header('Content-Type: application/json; charset=utf-8');
echo json_encode(array('text' => 'eggs'));
</code>```

Title: HTTP Content-Type Header and JSON

Body:
I have always been trying to avoid using most of the HTTP protocol's properties for the sake of fear of the unknown.

However, I said to myself that I'm going to face fear today and start using headers purposefully. I have been trying to send json data to the browser and use it right away. For example, if I have an Ajax handler function on ready state 4 which looks like so:

function ajaxHandler(response){
    alert(response.text);
}

And I have set the content-type header in my PHP code:

header('Content-Type: application/json');
echo json_encode(array('text' => 'omrele'));

Why can't I directly access the property from the handler function, when the browser is clearly told that the incoming data is application/json?

Body:
This is old but for me PHP8 it works if the  charset is set example.

header('Content-Type: application/json; charset=utf-8');
echo json_encode(array('text' => 'eggs'));


问:
How to load images and cache in ready function
I have developed LCD display like widget, I have 10 digits images and for every digit on display ( max 6 ) I have  and on click I change picture on div ( jquery attr('src','url'). My question is how to load all this 10 images in ready function ? I need to avoid flickering if connection is slow ( It flicker first time ) ?</p>

答:
Place all of the images in som kind of hidden div

```<code><div style="display:none;">
    <img src="a.png"/>
    <img src="b.png"/>
    <img src="c.png"/>
</div>
</code>```

This should ensure loading the images.

Body:
Place all of the images in som kind of hidden div

<div style="display:none;">
    <img src="a.png"/>
    <img src="b.png"/>
    <img src="c.png"/>
</div>

This should ensure loading the images.


问:
Is there any way to alter the url of a FileField in Django?
FileField objects have a url attribute. How do I alter it? The docs say it is read-only. Is there even a way to alter the underlying storage class? I am working with a migrated database and can't get the urls of the old directory structure to apply the new deployment. The MEDIA_ROOT is set fine, upload_to is being used in models, so new objects get saved correctly, but old ones are expected to be in the MEDIA_ROOT by the application, which is not the case.</p>

答:
From your model get all instance and change the name attribute.
For example in your model you ave a Many-to-many relationships to a document.

```<code>class Document(models.Model):
    doc_file = models.FileField(upload_to=upload_path, max_length=500)

class Repository(models.Model):
   documents = models.ManyToManyField(Document)
</code>```

...

```<code>for doc in Repository.documents.all():
    doc.doc_file.name = new_full_path
    doc.save()
</code>```

Another way is use Query Expressions

```<code>Repository.document.all().update(
    documents =Func(
        F('documents'),
        Value(old_path), Value(new_path),
        function='replace'
    )
)
</code>```

Body:
From your model get all instance and change the name attribute.
For example in your model you ave a Many-to-many relationships to a document.

class Document(models.Model):
    doc_file = models.FileField(upload_to=upload_path, max_length=500)

class Repository(models.Model):
   documents = models.ManyToManyField(Document)

...

for doc in Repository.documents.all():
    doc.doc_file.name = new_full_path
    doc.save()

Another way is use Query Expressions

Repository.document.all().update(
    documents =Func(
        F('documents'),
        Value(old_path), Value(new_path),
        function='replace'
    )
)


问:
Stack in C, converting infix with postfix
I'm trying to implement a stack in C to convert infix to postfix. But after several days of trying, im still not sure whats wrong with my code! can someone help? I made sure the line of logic is right and did on paper a lot of times, I'm new to stack, please assist!

I'm not sure exactly where is going wrong, and after a few submissions, suddenly the same code would produce segmentation error (core dumped) without much explanation.

Examples of inputs like : (A+B)+(C-D) produces (AB)+(C+D)- As for debuggers, im sticking to simple print statements at various parts of the program, I find that theres a problem with popping the '(' at the else if (infix == ')')

Running the code in online IDEs like replit and codechef. replit produces segmentation fault(core dumped) while codechef is able to produce and run an output. <- abit confused here

EDIT: My parenthesis Else if statements arent working, but I dont see why so, I tried adding simple print statements in that else if segments but they are not showing too

```<code>#include <stdio.h>
#include <stdlib.h>

#define SIZE 1000 //The limit of expression length

typedef struct _stackNode{
    char item;
    struct _stackNode *next;
}StackNode;

typedef struct _stack{
   int size;
   StackNode *head;
}Stack;

void push(Stack *sPtr, char item);
int pop(Stack *sPtr);
char peek(Stack s);
int isEmptyStack(Stack s);

void in2Post(char*, char*);

int main()
{
    char infix[SIZE];
    char postfix[SIZE];

    printf("Enter an infix expression:\n");
    scanf("%[^\n]%*c",infix);
    printf("This");
    in2Post(infix,postfix);
    printf("The postfix expression is \n");
    printf("%s\n",postfix);
    return 0;
}

void push(Stack *sPtr, char item){
    StackNode *newNode;
    newNode = (StackNode *) malloc(sizeof(StackNode));
    newNode->item = item;
    newNode->next = sPtr->head;
    sPtr->head = newNode;
    sPtr->size++;
}

int pop(Stack *sPtr){
    if(sPtr == NULL || sPtr->head == NULL){
        return 0;
    }
    else{
       StackNode *temp = sPtr->head;
       sPtr->head = sPtr->head->next;
       free(temp);
       sPtr->size--;
       return 1;
    }
}

char peek(Stack s){
    return s.head->item;
}

int isEmptyStack(Stack s){
     if(s.size == 0) return 1;
     else return 0;
}

int precedence(char item)
{
    if (item == '*' || item == '/')
    {
        return 2;
    }
    else if (item == '+' || item == '-')
    {
        return 1;
    }

    else
    {
        return 0; // if it is brackets return 0
    }
}

int isOperand(char ch)
{
  if (ch == '%' || ch == '/' || ch == '*' || ch == '+' || ch == '-')
  {
    return 0;
  }
  else
  {
    return 1;
  }
}

int is_operator(char item)
{
    if (item == '+' || item == '-' || item == '*' || item == '/')
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

void in2Post(char* infix, char* postfix)
{
 //Write your code here

  Stack* stack = (Stack*)malloc(sizeof(Stack));
  stack->head = NULL;

  if (!stack)
    return;

  int i = 0;
  int j = 0;
  while (infix[i] != '\0')
  {
    if (isOperand(infix[i]) && infix[i] != ')' && infix[i] != '(') //NEED TO MAKE SURE HERE ISNT A PARENTHESIS
    {
      postfix[j]=infix[i];
      j++;
    }
    else if (infix[i] == '(')
    {
      push(stack, infix[i]);
    }
    else if (infix[i] == ')')
    {
      while (!isEmptyStack(*stack) && peek(*stack) != '(')
      {
        postfix[j] = peek(*stack);
        j++;
        pop(stack);
        if (!isEmptyStack(*stack) && peek(*stack) !='(' )
        {
          return; // POPPING TILL REACH '(' IF IT IS NOT '(', RETURN
        }
        else
        {
          pop(stack); // removing the ()
        }
      }

    }
    else // an OPERATOR IS ENCOUNTERED
    {
      while (!isEmptyStack(*stack) && precedence(infix[i])<=precedence(peek(*stack)))
      {
        postfix[j] = peek(*stack);
        pop(stack);
        j++;
      }
      push(stack, infix[i]);

    }
    i++;
  }

  while (!isEmptyStack(*stack))
  {
    postfix[j] = peek(*stack);
    pop(stack);
    j++;
  }

  postfix[j] = '\0';
  printf("THIS IS POSTFIX %s\n", postfix);
}
</code>```

答: The first IF statement did not take into account the character might be a parenthesis. Also, the size of the stack is not initialized.</p>

Body:
I'm trying to implement a stack in C to convert infix to postfix. But after several days of trying, im still not sure whats wrong with my code! can someone help? I made sure the line of logic is right and did on paper a lot of times, I'm new to stack, please assist!

I'm not sure exactly where is going wrong, and after a few submissions, suddenly the same code would produce segmentation error (core dumped) without much explanation.

Examples of inputs like : (A+B)+(C-D) produces (AB)+(C+D)- As for debuggers, im sticking to simple print statements at various parts of the program, I find that theres a problem with popping the '(' at the else if (infix == ')')

Running the code in online IDEs like replit and codechef. replit produces segmentation fault(core dumped) while codechef is able to produce and run an output. <- abit confused here

EDIT: My parenthesis Else if statements arent working, but I dont see why so, I tried adding simple print statements in that else if segments but they are not showing too

#include <stdio.h>
#include <stdlib.h>

#define SIZE 1000 //The limit of expression length

typedef struct _stackNode{
    char item;
    struct _stackNode *next;
}StackNode;

typedef struct _stack{
   int size;
   StackNode *head;
}Stack;

void push(Stack *sPtr, char item);
int pop(Stack *sPtr);
char peek(Stack s);
int isEmptyStack(Stack s);

void in2Post(char*, char*);

int main()
{
    char infix[SIZE];
    char postfix[SIZE];

    printf("Enter an infix expression:\n");
    scanf("%[^\n]%*c",infix);
    printf("This");
    in2Post(infix,postfix);
    printf("The postfix expression is \n");
    printf("%s\n",postfix);
    return 0;
}

void push(Stack *sPtr, char item){
    StackNode *newNode;
    newNode = (StackNode *) malloc(sizeof(StackNode));
    newNode->item = item;
    newNode->next = sPtr->head;
    sPtr->head = newNode;
    sPtr->size++;
}

int pop(Stack *sPtr){
    if(sPtr == NULL || sPtr->head == NULL){
        return 0;
    }
    else{
       StackNode *temp = sPtr->head;
       sPtr->head = sPtr->head->next;
       free(temp);
       sPtr->size--;
       return 1;
    }
}

char peek(Stack s){
    return s.head->item;
}

int isEmptyStack(Stack s){
     if(s.size == 0) return 1;
     else return 0;
}

int precedence(char item)
{
    if (item == '*' || item == '/')
    {
        return 2;
    }
    else if (item == '+' || item == '-')
    {
        return 1;
    }

    else
    {
        return 0; // if it is brackets return 0
    }
}

int isOperand(char ch)
{
  if (ch == '%' || ch == '/' || ch == '*' || ch == '+' || ch == '-')
  {
    return 0;
  }
  else
  {
    return 1;
  }
}

int is_operator(char item)
{
    if (item == '+' || item == '-' || item == '*' || item == '/')
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

void in2Post(char* infix, char* postfix)
{
 //Write your code here

  Stack* stack = (Stack*)malloc(sizeof(Stack));
  stack->head = NULL;

  if (!stack)
    return;

  int i = 0;
  int j = 0;
  while (infix[i] != '\0')
  {
    if (isOperand(infix[i]) && infix[i] != ')' && infix[i] != '(') //NEED TO MAKE SURE HERE ISNT A PARENTHESIS
    {
      postfix[j]=infix[i];
      j++;
    }
    else if (infix[i] == '(')
    {
      push(stack, infix[i]);
    }
    else if (infix[i] == ')')
    {
      while (!isEmptyStack(*stack) && peek(*stack) != '(')
      {
        postfix[j] = peek(*stack);
        j++;
        pop(stack);
        if (!isEmptyStack(*stack) && peek(*stack) !='(' )
        {
          return; // POPPING TILL REACH '(' IF IT IS NOT '(', RETURN
        }
        else
        {
          pop(stack); // removing the ()
        }
      }

    }
    else // an OPERATOR IS ENCOUNTERED
    {
      while (!isEmptyStack(*stack) && precedence(infix[i])<=precedence(peek(*stack)))
      {
        postfix[j] = peek(*stack);
        pop(stack);
        j++;
      }
      push(stack, infix[i]);

    }
    i++;
  }

  while (!isEmptyStack(*stack))
  {
    postfix[j] = peek(*stack);
    pop(stack);
    j++;
  }

  postfix[j] = '\0';
  printf("THIS IS POSTFIX %s\n", postfix);
}


问:
Sum rows until customer number changes
How can I sum the rows of product sales 1-3, until the Customer Code changes? Then the next Customer sales should be summed up. There may be customers with only 1 or 2 products also.

答:
This is exactly the reason why the subtotals feature has been invented. Hereby a screenshot (not in English, sorry):

Here is the URL of the official documentation.

Title: Sum rows until customer number changes


问:
How to get a cell value from an html table to use in an axios request in reactjs?
I have a HTML table of clients, and I want to be able to delete one of them thanks to a simple axios delete request. In order to do that, I have to get the ID of the client I want to delete.
So here is what I did :

```<code>  async function deleteClient(e) {
    e.preventDefault();
    const id = document.getElementById("client").innerHTML;

    console.log(id);

    axios
      .delete("http://localhost:8080/api/clients/" + id)
      .then(function (response) {
        console.log(JSON.stringify(response.data));
      })
      .catch(function (error) {
        console.log(error);
      });
  }
</code>```

The deleteClient function is called onClick in the table. The issue is, it only ever gets the ID of the first row client and never the one from rows below. What can I do to get the right ID and be able to delete other clients ?

For info, here is my HTML table, it is filled dynamically thanks to useEffect hook and a simple axios get request :

```<code> <table className="text-white border-2 border-bikeexplogray-light rounded-full">
          <tr>
            <th>Clients</th>
          </tr>
          <tr>
            <th>ID</th>
            <th>Store Name</th>
            <th>Username</th>
            <th>Email</th>
            <th>Phone number</th>
            <th>Address</th>
            <th>Zipcode</th>
            <th>City</th>
            <th>Website</th>
            <th>Delete</th>
          </tr>{" "}
          {filteredData.map((value, index) => {
            return (
              <tr key={value.id}>
                <td id="client">{value.id}</td>
                <td>{value.storeName}</td>
                <td>{value.username}</td>
                <td>{value.email}</td>
                <td>{value.phone}</td>
                <td>{value.adress}</td>
                <td>{value.zipcode}</td>
                <td>{value.city}</td>
                <td>{value.website}</td>
                <td>
                  <button onClick={deleteClient}>Delete</button>
                </td>
              </tr>
</code>```

Thanks in advance for the help!

答:
The id attribute on the td tag must be unique within the document.

You can use data-id instead, data-* is just a standard way to attach data to the DOM.

In your event handler deleteClient you can use e.currentTarget to access the context.

function deleteClient(e) {
  // this will be your button element
  const button = e.currentTarget

  // search up the DOM tree (each parent) for this selector match
  const td = button.closest("tr > td[data-id]")

  // this should be the ID from the data-* attribute
  console.log(td.dataset.id)

  // ...
}
```

Body:
I have a HTML table of clients, and I want to be able to delete one of them thanks to a simple axios delete request. In order to do that, I have to get the ID of the client I want to delete.
So here is what I did :

  async function deleteClient(e) {
    e.preventDefault();
    const id = document.getElementById("client").innerHTML;

    console.log(id);

    axios
      .delete("http://localhost:8080/api/clients/" + id)
      .then(function (response) {
        console.log(JSON.stringify(response.data));
      })
      .catch(function (error) {
        console.log(error);
      });
  }

The deleteClient function is called onClick in the table. The issue is, it only ever gets the ID of the first row client and never the one from rows below. What can I do to get the right ID and be able to delete other clients ?

For info, here is my HTML table, it is filled dynamically thanks to useEffect hook and a simple axios get request :

            Clients

            ID
            Store Name
            Username
            Email
            Phone number
            Address
            Zipcode
            City
            Website
            Delete

{" "}
          {filteredData.map((value, index) => {
            return (

                {value.id}
                {value.storeName}
                {value.username}
                {value.email}
                {value.phone}
                {value.adress}
                {value.zipcode}
                {value.city}
                {value.website}

                  <button onClick={deleteClient}>Delete</button>

Thanks in advance for the help!


问:
iOS (iPhone/iPad) App Store - Missing developer/seller name in "app detail" page
It's hard to explain this but I've noticed that other apps have this so I will use them as examples:

If you search "Angry Birds" on the App Store (on iPhone), you will see it under the name "Clickgamer.com" but if the tap on it to take it to the "app details" page where you download the app where it is listed under a different name - "Clickgamer Technologi...".

If you search "Angry Birds Rio" on the App Store, you will see it listed under "Rovio Mobile Ltd." but if you tap onto it and view the details page (where you purchase and download the app) it has a blank space under its app name.

My app has the same scenario as Angry Birds Rio. What should I do to fill that gap under the app name on my own app?

(Sorry for not explaining this well)

答: The only thing you can ever do in this instance is contact Apple. In this case the ITunes Connect team. There is a form in the contact section when you login. </p>


问:
How to remove/hide time from jQuery DateTimePicker, Asp Net
I removed the time selection in the calendar widget and the start date in the fields also without time.
But the main problem is that when you select a date, the current time is still inserted in the field. Need only to display the date, without the time.

cshtml

```<code><div class="form-group">
@Html.LabelFor(model => model.DateTo, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
    @Html.EditorFor(model => model.DateTo, "{0:d}", new { htmlAttributes = new { @class = "form-control" } })
    @Html.ValidationMessageFor(model => model.DateTo, "", new { @class = "text-danger" })
</div>
</code>```

js

```<code>$("#DateTo").datetimepicker({
    timepicker: false,
    pickTime: false,
    closeOnDateSelect: true,
    dateFormat: "yy/mm/dd"
});
</code>```

Model

```<code>[Display(Name = "DateTo", ResourceType = typeof(Resources.Resource))]
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)]
[Required]
public DateTime DateTo { get; set; }
</code>```

jQuery DateTimePicker plugin v2.4.5
If there are simple alternative widgets for asp net, please advise.

答:
To display only the date without the time, just do it this way:

```<code>$("#DateTo").datepicker({
   dateFormat: "yy/mm/dd",
   closeOnDateSelect: true
});
</code>```

Because you're going through .datetimepicker where it picks up date and time, .datepicker picks up only thedate.

Body:
I removed the time selection in the calendar widget and the start date in the fields also without time.
But the main problem is that when you select a date, the current time is still inserted in the field. Need only to display the date, without the time.

cshtml

@Html.LabelFor(model => model.DateTo, htmlAttributes: new { @class = "control-label col-md-2" })

    @Html.EditorFor(model => model.DateTo, "{0:d}", new { htmlAttributes = new { @class = "form-control" } })
    @Html.ValidationMessageFor(model => model.DateTo, "", new { @class = "text-danger" })

js

$("#DateTo").datetimepicker({
    timepicker: false,
    pickTime: false,
    closeOnDateSelect: true,
    dateFormat: "yy/mm/dd"
});

Model

[Display(Name = "DateTo", ResourceType = typeof(Resources.Resource))]
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)]
[Required]
public DateTime DateTo { get; set; }

jQuery DateTimePicker plugin v2.4.5
If there are simple alternative widgets for asp net, please advise.

Body:
To display only the date without the time, just do it this way:

$("#DateTo").datepicker({
   dateFormat: "yy/mm/dd",
   closeOnDateSelect: true
});

Because you're going through .datetimepicker where it picks up date and time, .datepicker picks up only thedate.


问:
Unexpected shell interpretation behavior
I generated some options using shell script, echo $NLB_EIPS resulting in -p "route 1.1.1.1 255.255.255.255" -p "route 2.2.2.2 255.255.255.255" -p "route 3.3.3.3 255.255.255.255"

I need to append this option to my original command of docker run <SOME_OTHER_OPTIONS...> -p "route 192.0.0.0 255.255.0.0" -p "route 10.0.0.0 255.255.0.0". Thus, my final goal is to run docker run <SOME_OTHER_OPTIONS...> -p "route 192.0.0.0 255.255.0.0" -p "route 10.0.0.0 255.255.0.0" -p "route 1.1.1.1 255.255.255.255" -p "route 2.2.2.2 255.255.255.255" -p "route 3.3.3.3 255.255.255.255"

However, using the shell script below results in unintended behavior. Though ${NLB_EIPS[@]} holds -p "route 1.1.1.1 255.255.255.255" -p "route 2.2.2.2 255.255.255.255" -p "route 3.3.3.3 255.255.255.255", log shows me that shell script only interpreted -p "route , completely ignoring the part after the whitespace.

```<code>#!/bin/bash

ADDITIONAL_IPS="1.1.1.1 2.2.2.2 3.3.3.3"
NLB_EIPS=()
for IP in $ADDITIONAL_IPS; do
  NLB_EIPS+=" -p \"route $IP 255.255.255.255\""
done

echo "Added additional routes to NLB_EIP."
echo "NLB_EIPS: $NLB_EIPS"

docker run <SOME_OTHER_OPTIONS...> -p "route 192.0.0.0 255.255.0.0" -p "route 10.0.0.0 255.255.0.0" ${NLB_EIPS[@]}
</code>```

Any help would be greatful!

答:
You are correctly starting with the idea, that NLB_EIPS is an array where each element is a parameter to the command to be executed. But when you do a NLB_EIPS+=...., you are populating a single element with a string holding two parameters (-p, route and the IP address), plus confusing white space surrounding that stuff.

docker will never see that -p which comes in via NLB_EIPS, becaus the parameter is not a sole -p anymore. For the same reason,

```<code> docker run ' -p "route $IP 255.255.255.255"'
</code>```

would fail.

Body:
I generated some options using shell script, echo $NLB_EIPS resulting in -p "route 1.1.1.1 255.255.255.255" -p "route 2.2.2.2 255.255.255.255" -p "route 3.3.3.3 255.255.255.255"

I need to append this option to my original command of docker run <SOME_OTHER_OPTIONS...> -p "route 192.0.0.0 255.255.0.0" -p "route 10.0.0.0 255.255.0.0". Thus, my final goal is to run docker run <SOME_OTHER_OPTIONS...> -p "route 192.0.0.0 255.255.0.0" -p "route 10.0.0.0 255.255.0.0" -p "route 1.1.1.1 255.255.255.255" -p "route 2.2.2.2 255.255.255.255" -p "route 3.3.3.3 255.255.255.255"

However, using the shell script below results in unintended behavior. Though ${NLB_EIPS[@]} holds -p "route 1.1.1.1 255.255.255.255" -p "route 2.2.2.2 255.255.255.255" -p "route 3.3.3.3 255.255.255.255", log shows me that shell script only interpreted -p "route , completely ignoring the part after the whitespace.

#!/bin/bash

ADDITIONAL_IPS="1.1.1.1 2.2.2.2 3.3.3.3"
NLB_EIPS=()
for IP in $ADDITIONAL_IPS; do
  NLB_EIPS+=" -p \"route $IP 255.255.255.255\""
done

echo "Added additional routes to NLB_EIP."
echo "NLB_EIPS: $NLB_EIPS"

docker run <SOME_OTHER_OPTIONS...> -p "route 192.0.0.0 255.255.0.0" -p "route 10.0.0.0 255.255.0.0" ${NLB_EIPS[@]}

Any help would be greatful!

Body:
You are correctly starting with the idea, that NLB_EIPS is an array where each element is a parameter to the command to be executed. But when you do a NLB_EIPS+=...., you are populating a single element with a string holding two parameters (-p, route and the IP address), plus confusing white space surrounding that stuff.

docker will never see that -p which comes in via NLB_EIPS, becaus the parameter is not a sole -p anymore. For the same reason,

 docker run ' -p "route $IP 255.255.255.255"'

would fail.


问:
How to group columns and sum them, in a large CSV?
I have a large CSV (hundreds of millions of rows) and I need to sum the Value column based on the grouping of the ID, Location, and Date columns.

My CSV is similar to:

    ID Location        Date  Value
 1   1     Loc1  2022-01-27      5
 2   1     Loc1  2022-01-27      4
 3   1     Loc1  2022-01-28      7
 4   1     Loc2  2022-01-29      8
 5   2     Loc1  2022-01-27     11
 6   2     Loc2  2022-01-28      4
 7   2     Loc2  2022-01-29      6
 8   3     Loc1  2022-01-28      9
 9   3     Loc1  2022-01-28      9
10   3     Loc2  2022-01-29      1
```
<ul>
<li><code>{ID: 1, Location: Loc1, Date: 2022-01-27}</code> is one such group, and its sub values <code>5</code> and <code>4</code> should be summed to <code>9</code></li>
<li><code>{ID: 3, Location: Loc1, Date: 2022-01-28}</code> is another group and its sum should be <code>18</code></li>
</ul>
<p>Here's what that sample input should look like, processed/summed, and written to a new CSV:</p>
<pre class="lang-none prettyprint-override"><code>ID Location        Date  Value
1     Loc1  2022-01-27      9
1     Loc1  2022-01-28      7
1     Loc2  2022-01-29      8
2     Loc1  2022-01-27     11
2     Loc2  2022-01-28      4
2     Loc2  2022-01-29      6
3     Loc1  2022-01-28     18
3     Loc2  2022-01-29      1
</code>```

I know using df.groupby([columns]).sum() would give the desired result, but the CSV is so big I keep getting memory errors. I've tried looking at other ways to read/manipulate CSV data but have still not been successful, so if anyone knows a way I can do this in python without maxing out my memory that would be great!

NB: I know there is a unnamed first column in my initial csv, this is irrelevant and doesn't need to be in the outputted, but doesn't matter if it is :)

答:
The appropriate answer is probably to use Dask but you can do with Pandas and chunk. The last_row variable is the last row of the previous chunk is case of the first row of the current chunk have the same ID, Location and Date.

```<code>chunksize = 4  # Number of rows
last_row = pd.DataFrame()  # Last row of the previous chunk

with open('data.csv') as reader, open('output.csv', 'w') as writer:

    # Write headers
    writer.write(reader.readline())
    reader.seek(0)

    for chunk in pd.read_csv(reader, chunksize=chunksize):
        df = pd.concat([last_row, chunk])
        df = df.groupby(['ID', 'Location', 'Date'], as_index=False)['Value'].sum()
        df, last_row = df.iloc[:-1], df.iloc[-1:]
        df.to_csv(writer, header=False, index=False)

    # Don't forget the last row!
    last_row.to_csv(writer, header=False, index=False)
</code>```

Content of output.csv:

```<code>ID,Location,Date,Value
1,Loc1,2022-01-27,9
1,Loc1,2022-01-28,7
1,Loc2,2022-01-29,8
2,Loc1,2022-01-27,11
2,Loc2,2022-01-28,4
2,Loc2,2022-01-29,6
3,Loc1,2022-01-28,18
3,Loc2,2022-01-29,1
</code>```

Body:
I have a large CSV (hundreds of millions of rows) and I need to sum the Value column based on the grouping of the ID, Location, and Date columns.

My CSV is similar to:

    ID Location        Date  Value
 1   1     Loc1  2022-01-27      5
 2   1     Loc1  2022-01-27      4
 3   1     Loc1  2022-01-28      7
 4   1     Loc2  2022-01-29      8
 5   2     Loc1  2022-01-27     11
 6   2     Loc2  2022-01-28      4
 7   2     Loc2  2022-01-29      6
 8   3     Loc1  2022-01-28      9
 9   3     Loc1  2022-01-28      9
10   3     Loc2  2022-01-29      1

{ID: 1, Location: Loc1, Date: 2022-01-27} is one such group, and its sub values 5 and 4 should be summed to 9

{ID: 3, Location: Loc1, Date: 2022-01-28} is another group and its sum should be 18

Here's what that sample input should look like, processed/summed, and written to a new CSV:

ID Location        Date  Value
1     Loc1  2022-01-27      9
1     Loc1  2022-01-28      7
1     Loc2  2022-01-29      8
2     Loc1  2022-01-27     11
2     Loc2  2022-01-28      4
2     Loc2  2022-01-29      6
3     Loc1  2022-01-28     18
3     Loc2  2022-01-29      1

I know using df.groupby([columns]).sum() would give the desired result, but the CSV is so big I keep getting memory errors. I've tried looking at other ways to read/manipulate CSV data but have still not been successful, so if anyone knows a way I can do this in python without maxing out my memory that would be great!

NB: I know there is a unnamed first column in my initial csv, this is irrelevant and doesn't need to be in the outputted, but doesn't matter if it is :)

Body:
The appropriate answer is probably to use Dask but you can do with Pandas and chunk. The last_row variable is the last row of the previous chunk is case of the first row of the current chunk have the same ID, Location and Date.

chunksize = 4  # Number of rows
last_row = pd.DataFrame()  # Last row of the previous chunk

with open('data.csv') as reader, open('output.csv', 'w') as writer:

    # Write headers
    writer.write(reader.readline())
    reader.seek(0)

    for chunk in pd.read_csv(reader, chunksize=chunksize):
        df = pd.concat([last_row, chunk])
        df = df.groupby(['ID', 'Location', 'Date'], as_index=False)['Value'].sum()
        df, last_row = df.iloc[:-1], df.iloc[-1:]
        df.to_csv(writer, header=False, index=False)

    # Don't forget the last row!
    last_row.to_csv(writer, header=False, index=False)

Content of output.csv:

ID,Location,Date,Value
1,Loc1,2022-01-27,9
1,Loc1,2022-01-28,7
1,Loc2,2022-01-29,8
2,Loc1,2022-01-27,11
2,Loc2,2022-01-28,4
2,Loc2,2022-01-29,6
3,Loc1,2022-01-28,18
3,Loc2,2022-01-29,1


问:
How to conditionally count the number of occurrences using dplyr?
In the below reproducible example, the user stratifies the elements of a data frame based on inputs for (A) point-in-time period and (B) which of the 2 columns of values to stratify.

I'm trying to count only those rows marked with an "N" in the "Flag" column in those circumstances where the user has selected to stratify the "Values_2" elements; otherwise the Flag column is ignored when the user selects to stratify the "Values_1" elements.

The below code works except for counting elements flagged "N" when "Values_2" is chosen. I commented out my attempt to count elements flagged "N"... because it produces non-sensical results.

I will also only sum those "Value_2" elements flagged with "N" but I can figure that one out.

The image at the bottom better explains the question.

Any suggestions?

```<code>library(shiny)
library(tidyverse)
library(shinyWidgets)

ui <-
  fluidPage(
    uiOutput("stratPeriod"),
    uiOutput("stratValues"),
    h5(strong("Raw data frame:")), tableOutput("rawData"),
    h5(strong("Stratified data:")), tableOutput("stratData")
  )

server <- function(input, output, session) {

  dat <- reactive({
    data.frame(
      ID = c(1,1,2,2,2,2,3,3,3,3),
      Period = c("2020-03", "2020-04", "2020-01", "2020-02", "2020-03", "2020-04", "2020-01", "2020-02", "2020-03", "2020-04"),
      Values_1 = c(-6, 26, 36, 46, 56, 86, 100, 10, 20, 30),
      Values_2 = c(-6, 13, 18, 46, 28, 43, 100, 10, 10, 30),
      Flag = c("N","Y","Y","N","Y","Y","N","N","Y","N")
    )
  })

  output$stratPeriod <- renderUI({
    chc <- unique(na.omit(dat()[[2]]))
    selectInput(inputId = "stratPeriod",
                label = "Choose point-in-time:",
                choices = chc,
                selected = chc[1])
  })

  output$stratValues <- renderUI({
    selectInput("stratValues",
                "Choose values type to sum:",
                choices = c("Values_1","Values_2"),
                selected = c("Values_1")
    )
  })

  output$rawData <- renderTable({dat()})

  output$stratData <- renderTable({
    req(input$stratValues)
    req(input$stratPeriod)

    filter_exp1 <- parse(text=paste0("Period",  "==", "'",input$stratPeriod, "'"))

    dat_1 <- reactive({dat() %>% filter(eval(filter_exp1))})

    min <- custom_min(dat_1()[[input$stratValues]])
    max <- custom_max(dat_1()[[input$stratValues]])
    breaks <- if(any(is.infinite(c(min,max)))) c(0, 10) else seq(min, max, length.out = 6)

    tmp <- dat() %>%
      filter(eval(filter_exp1)) %>%
      mutate(Range = cut(!!sym(input$stratValues), breaks=breaks, include.lowest=TRUE, right = TRUE, dig.lab = 5)) %>%
      group_by(Range) %>%
      summarise(Count = n(),Values = sum(!!sym(input$stratValues))) %>%
      # summarise(Count = if_else(!!sym(input$stratValues) == "Values_1",n(),sum(dat()[[5]]=="N")),Values = sum(!!sym(input$stratValues))) %>%
      complete(Range, fill = list(Count = 0,Values = 0)) %>%
      ungroup %>%
      mutate(Count_pct = Count/sum(Count)*100, Values_pct = Values/sum(Values)*100) %>%
      dplyr::select(everything(), Count, Count_pct, Values, Values_pct) %>%
      bind_rows(summarise_all(., ~(if(is.numeric(.)) sum(.) else "Total")))
    tmp
  })

}

shinyApp(ui, server)
</code>```

答:
I think the easiest way might be to change the renderTable() function to the following:

```<code>output$stratData <- renderTable({
    req(input$stratValues)
    req(input$stratPeriod)

    filter_exp1 <- parse(text=paste0("Period",  "==", "'",input$stratPeriod, "'"))

    dat_1 <- reactive({dat() %>% filter(eval(filter_exp1))})
    min <- custom_min(dat_1()[[input$stratValues]])
    max <- custom_max(dat_1()[[input$stratValues]])
    breaks <- if(any(is.infinite(c(min,max)))) c(0, 10) else seq(min, max, length.out = 6)

    tmp <- dat() %>%
      filter(eval(filter_exp1)) %>%
      mutate(Range = cut(!!sym(input$stratValues), breaks=breaks, include.lowest=TRUE, right = TRUE, dig.lab = 5)) %>%
      group_by(Range)
    if(input$stratValues == "Values_2"){
      tmp <- tmp %>%
        filter(Flag == "N")
    }
    tmp <- tmp %>%
      summarise(Count = n(),Values = sum(!!sym(input$stratValues))) %>%
      complete(Range, fill = list(Count = 0,Values = 0)) %>%
      ungroup %>%
      mutate(Count_pct = Count/sum(Count)*100, Values_pct = Values/sum(Values)*100) %>%
      dplyr::select(everything(), Count, Count_pct, Values, Values_pct) %>%
      bind_rows(summarise_all(., ~(if(is.numeric(.)) sum(.) else "Total")))
    tmp
  })
</code>```

In the code above, there is an if() condition that identifies whether stratValues is Values_2.  If so, it filters the data to only include the "N" observations on Flag.  Then, it continues with the rest of the analysis.  This will work if both Values and Countare calculated only on the observations whereFlag == "N"`.

Body:
In the below reproducible example, the user stratifies the elements of a data frame based on inputs for (A) point-in-time period and (B) which of the 2 columns of values to stratify.

I'm trying to count only those rows marked with an "N" in the "Flag" column in those circumstances where the user has selected to stratify the "Values_2" elements; otherwise the Flag column is ignored when the user selects to stratify the "Values_1" elements.

The below code works except for counting elements flagged "N" when "Values_2" is chosen. I commented out my attempt to count elements flagged "N"... because it produces non-sensical results.

I will also only sum those "Value_2" elements flagged with "N" but I can figure that one out.

The image at the bottom better explains the question.

Any suggestions?

library(shiny)
library(tidyverse)
library(shinyWidgets)

ui <-
  fluidPage(
    uiOutput("stratPeriod"),
    uiOutput("stratValues"),
    h5(strong("Raw data frame:")), tableOutput("rawData"),
    h5(strong("Stratified data:")), tableOutput("stratData")
  )

server <- function(input, output, session) {

  dat <- reactive({
    data.frame(
      ID = c(1,1,2,2,2,2,3,3,3,3),
      Period = c("2020-03", "2020-04", "2020-01", "2020-02", "2020-03", "2020-04", "2020-01", "2020-02", "2020-03", "2020-04"),
      Values_1 = c(-6, 26, 36, 46, 56, 86, 100, 10, 20, 30),
      Values_2 = c(-6, 13, 18, 46, 28, 43, 100, 10, 10, 30),
      Flag = c("N","Y","Y","N","Y","Y","N","N","Y","N")
    )
  })

  output$stratPeriod <- renderUI({
    chc <- unique(na.omit(dat()[[2]]))
    selectInput(inputId = "stratPeriod",
                label = "Choose point-in-time:",
                choices = chc,
                selected = chc[1])
  })

  output$stratValues <- renderUI({
    selectInput("stratValues",
                "Choose values type to sum:",
                choices = c("Values_1","Values_2"),
                selected = c("Values_1")
    )
  })

  output$rawData <- renderTable({dat()})

  output$stratData <- renderTable({
    req(input$stratValues)
    req(input$stratPeriod)

    filter_exp1 <- parse(text=paste0("Period",  "==", "'",input$stratPeriod, "'"))

    dat_1 <- reactive({dat() %>% filter(eval(filter_exp1))})

    min <- custom_min(dat_1()[[input$stratValues]])
    max <- custom_max(dat_1()[[input$stratValues]])
    breaks <- if(any(is.infinite(c(min,max)))) c(0, 10) else seq(min, max, length.out = 6)

    tmp <- dat() %>%
      filter(eval(filter_exp1)) %>%
      mutate(Range = cut(!!sym(input$stratValues), breaks=breaks, include.lowest=TRUE, right = TRUE, dig.lab = 5)) %>%
      group_by(Range) %>%
      summarise(Count = n(),Values = sum(!!sym(input$stratValues))) %>%
      # summarise(Count = if_else(!!sym(input$stratValues) == "Values_1",n(),sum(dat()[[5]]=="N")),Values = sum(!!sym(input$stratValues))) %>%
      complete(Range, fill = list(Count = 0,Values = 0)) %>%
      ungroup %>%
      mutate(Count_pct = Count/sum(Count)*100, Values_pct = Values/sum(Values)*100) %>%
      dplyr::select(everything(), Count, Count_pct, Values, Values_pct) %>%
      bind_rows(summarise_all(., ~(if(is.numeric(.)) sum(.) else "Total")))
    tmp
  })

}

shinyApp(ui, server)

Body:
I think the easiest way might be to change the renderTable() function to the following:

output$stratData <- renderTable({
    req(input$stratValues)
    req(input$stratPeriod)

    filter_exp1 <- parse(text=paste0("Period",  "==", "'",input$stratPeriod, "'"))

    dat_1 <- reactive({dat() %>% filter(eval(filter_exp1))})
    min <- custom_min(dat_1()[[input$stratValues]])
    max <- custom_max(dat_1()[[input$stratValues]])
    breaks <- if(any(is.infinite(c(min,max)))) c(0, 10) else seq(min, max, length.out = 6)

    tmp <- dat() %>%
      filter(eval(filter_exp1)) %>%
      mutate(Range = cut(!!sym(input$stratValues), breaks=breaks, include.lowest=TRUE, right = TRUE, dig.lab = 5)) %>%
      group_by(Range)
    if(input$stratValues == "Values_2"){
      tmp <- tmp %>%
        filter(Flag == "N")
    }
    tmp <- tmp %>%
      summarise(Count = n(),Values = sum(!!sym(input$stratValues))) %>%
      complete(Range, fill = list(Count = 0,Values = 0)) %>%
      ungroup %>%
      mutate(Count_pct = Count/sum(Count)*100, Values_pct = Values/sum(Values)*100) %>%
      dplyr::select(everything(), Count, Count_pct, Values, Values_pct) %>%
      bind_rows(summarise_all(., ~(if(is.numeric(.)) sum(.) else "Total")))
    tmp
  })

In the code above, there is an if() condition that identifies whether stratValues is Values_2.  If so, it filters the data to only include the "N" observations on Flag.  Then, it continues with the rest of the analysis.  This will work if both Values and Countare calculated only on the observations whereFlag == "N"`.


问:
Python: Typehints for argparse.Namespace objects
Is there a way to have Python static analyzers (e.g. in PyCharm, other IDEs) pick up on Typehints on argparse.Namespace objects?  Example:

```<code>parser = argparse.ArgumentParser()
parser.add_argument('--somearg')
parsed = parser.parse_args(['--somearg','someval'])  # type: argparse.Namespace
the_arg = parsed.somearg  # <- Pycharm complains that parsed object has no attribute 'somearg'
</code>```

If I remove the type declaration in the inline comment, PyCharm doesn't complain, but it also doesn't pick up on invalid attributes.  For example:

```<code>parser = argparse.ArgumentParser()
parser.add_argument('--somearg')
parsed = parser.parse_args(['--somearg','someval'])  # no typehint
the_arg = parsed.somaerg   # <- typo in attribute, but no complaint in PyCharm.  Raises AttributeError when executed.
</code>```

Any ideas?

Update

Inspired by Austin's answer below, the simplest solution I could find is one using namedtuples:

```<code>from collections import namedtuple
ArgNamespace = namedtuple('ArgNamespace', ['some_arg', 'another_arg'])

parser = argparse.ArgumentParser()
parser.add_argument('--some-arg')
parser.add_argument('--another-arg')
parsed = parser.parse_args(['--some-arg', 'val1', '--another-arg', 'val2'])  # type: ArgNamespace

x = parsed.some_arg  # good...
y = parsed.another_arg  # still good...
z = parsed.aint_no_arg  # Flagged by PyCharm!
</code>```

While this is satisfactory, I still don't like having to repeat the argument names.  If the argument list grows considerably, it will be tedious updating both locations.  What would be ideal is somehow extracting the arguments from the parser object like the following:

```<code>parser = argparse.ArgumentParser()
parser.add_argument('--some-arg')
parser.add_argument('--another-arg')
MagicNamespace = parser.magically_extract_namespace()
parsed = parser.parse_args(['--some-arg', 'val1', '--another-arg', 'val2'])  # type: MagicNamespace
</code>```

I haven't been able to find anything in the argparse module that could make this possible, and I'm still unsure if any static analysis tool could be clever enough to get those values and not bring the IDE to a grinding halt.

Still searching...

Update 2

Per hpaulj's comment, the closest thing I could find to the method described above that would "magically" extract the attributes of the parsed object is something that would extract the dest attribute from each of the parser's _actions.:

```<code>parser = argparse.ArgumentParser()
parser.add_argument('--some-arg')
parser.add_argument('--another-arg')
MagicNamespace = namedtuple('MagicNamespace', [act.dest for act in parser._actions])
parsed = parser.parse_args(['--some-arg', 'val1', '--another-arg', 'val2'])  # type: MagicNamespace
</code>```

But this still does not cause attribute errors to get flagged in static analysis.  This is true also true if I pass namespace=MagicNamespace in the parser.parse_args call.

答:
Most of these answers involve using another package to handle the typing. This would be a good idea only if there wasn't such a simple solution as the one I am about to propose.

Step 1. Type Declarations

First, define the types of each argument in a dataclass like so:

from dataclasses import dataclass

@dataclass
class MyProgramArgs:
    first_var: str
    second_var: int
```
<h3>Step 2. Argument Declarations</h3>
<p>Then you can set up your parser however you like with matching arguments. For example:</p>
<pre class="lang-py prettyprint-override"><code>import argparse

parser = argparse.ArgumentParser("This CLI program uses type hints!")
parser.add_argument("-a", "--first-var")
parser.add_argument("-b", "--another-var", type=int, dest="second_var")
</code>```

Step 3. Parsing the Arguments

And finally, we parse the arguments in a way that the static type checker will know about the type of each argument:

my_args = MyProgramArgs(**vars(parser.parse_args())
```

Now the type checker knows that my_args is of type MyProgramArgs so it knows exactly which fields are available and what their type is.

Body:
Is there a way to have Python static analyzers (e.g. in PyCharm, other IDEs) pick up on Typehints on argparse.Namespace objects?  Example:

parser = argparse.ArgumentParser()
parser.add_argument('--somearg')
parsed = parser.parse_args(['--somearg','someval'])  # type: argparse.Namespace
the_arg = parsed.somearg  # <- Pycharm complains that parsed object has no attribute 'somearg'

If I remove the type declaration in the inline comment, PyCharm doesn't complain, but it also doesn't pick up on invalid attributes.  For example:

parser = argparse.ArgumentParser()
parser.add_argument('--somearg')
parsed = parser.parse_args(['--somearg','someval'])  # no typehint
the_arg = parsed.somaerg   # <- typo in attribute, but no complaint in PyCharm.  Raises AttributeError when executed.

Any ideas?

Update

Inspired by Austin's answer below, the simplest solution I could find is one using namedtuples:

from collections import namedtuple
ArgNamespace = namedtuple('ArgNamespace', ['some_arg', 'another_arg'])

parser = argparse.ArgumentParser()
parser.add_argument('--some-arg')
parser.add_argument('--another-arg')
parsed = parser.parse_args(['--some-arg', 'val1', '--another-arg', 'val2'])  # type: ArgNamespace

x = parsed.some_arg  # good...
y = parsed.another_arg  # still good...
z = parsed.aint_no_arg  # Flagged by PyCharm!

While this is satisfactory, I still don't like having to repeat the argument names.  If the argument list grows considerably, it will be tedious updating both locations.  What would be ideal is somehow extracting the arguments from the parser object like the following:

parser = argparse.ArgumentParser()
parser.add_argument('--some-arg')
parser.add_argument('--another-arg')
MagicNamespace = parser.magically_extract_namespace()
parsed = parser.parse_args(['--some-arg', 'val1', '--another-arg', 'val2'])  # type: MagicNamespace

I haven't been able to find anything in the argparse module that could make this possible, and I'm still unsure if any static analysis tool could be clever enough to get those values and not bring the IDE to a grinding halt.

Still searching...

Update 2

Per hpaulj's comment, the closest thing I could find to the method described above that would "magically" extract the attributes of the parsed object is something that would extract the dest attribute from each of the parser's _actions.:

parser = argparse.ArgumentParser()
parser.add_argument('--some-arg')
parser.add_argument('--another-arg')
MagicNamespace = namedtuple('MagicNamespace', [act.dest for act in parser._actions])
parsed = parser.parse_args(['--some-arg', 'val1', '--another-arg', 'val2'])  # type: MagicNamespace

But this still does not cause attribute errors to get flagged in static analysis.  This is true also true if I pass namespace=MagicNamespace in the parser.parse_args call.

Body:
Most of these answers involve using another package to handle the typing. This would be a good idea only if there wasn't such a simple solution as the one I am about to propose.

Step 1. Type Declarations

First, define the types of each argument in a dataclass like so:

from dataclasses import dataclass

@dataclass
class MyProgramArgs:
    first_var: str
    second_var: int

Step 2. Argument Declarations

Then you can set up your parser however you like with matching arguments. For example:

import argparse

parser = argparse.ArgumentParser("This CLI program uses type hints!")
parser.add_argument("-a", "--first-var")
parser.add_argument("-b", "--another-var", type=int, dest="second_var")

Step 3. Parsing the Arguments

And finally, we parse the arguments in a way that the static type checker will know about the type of each argument:

my_args = MyProgramArgs(**vars(parser.parse_args())

Now the type checker knows that my_args is of type MyProgramArgs so it knows exactly which fields are available and what their type is.


问:
Cubic Root in python without using the power operator
I need your help in the following question

Print the greatest integer whose cube is smaller or equal to the input number without using the power operator ,you must use the print function and match the expected output :

Print the following for input n=99:
4,not exact with difference 35

Print the following for input n=2000:
12,not exact with difference 272

Print the following for input n=1000:
10, exact!

```<code>def cubic_root(n):
      if n<0:
         n=abs(n)
         cube_root = n**(1/3)*(-1)
      else:
          cube_root = n**(1/3)
          diff = round(n-(cube_root *cube_root *cube_root ))
          print (cube_root,"not exact with",diff)
  return cube_root

print(round(cubic_root(99)))
print(round(cubic_root(2000)))
print(round(cubic_root(1000)))
</code>```

My output:

```<code>4 not exact with 35
4
12 not exact with 272
12
9 not exact with 271
9
</code>```

答:
def cubic_root(n):

```<code>n=abs(n)
result=1
x=2
if n==0:
    print('0, exact!')
elif n==1:
    print('1, exact!')
else:
    while result<n:
        result=x*x*x
        if result>=n:
            break
        x=x+1
    if result!=n:
        x=x-1
    diff=(x*x*x)-n
    if diff==0:
        print('{0}, exact!'.format(str(x)))
    else:
        diff=abs(diff)
        print('{0}, not exact with difference {1}'.format(str(x), str(diff)))
</code>```

n = int(input("enter the value: "))
cubic_root(n)

##this worked for me

Body:
I need your help in the following question

Print the greatest integer whose cube is smaller or equal to the input number without using the power operator ,you must use the print function and match the expected output :

Print the following for input n=99:
4,not exact with difference 35

Print the following for input n=2000:
12,not exact with difference 272

Print the following for input n=1000:
10, exact!

def cubic_root(n):
      if n<0:
         n=abs(n)
         cube_root = n**(1/3)*(-1)
      else:
          cube_root = n**(1/3)
          diff = round(n-(cube_root *cube_root *cube_root ))
          print (cube_root,"not exact with",diff)
  return cube_root

print(round(cubic_root(99)))
print(round(cubic_root(2000)))
print(round(cubic_root(1000)))

My output:

4 not exact with 35
4
12 not exact with 272
12
9 not exact with 271
9

Body:
def cubic_root(n):

n=abs(n)
result=1
x=2
if n==0:
    print('0, exact!')
elif n==1:
    print('1, exact!')
else:
    while result<n:
        result=x*x*x
        if result>=n:
            break
        x=x+1
    if result!=n:
        x=x-1
    diff=(x*x*x)-n
    if diff==0:
        print('{0}, exact!'.format(str(x)))
    else:
        diff=abs(diff)
        print('{0}, not exact with difference {1}'.format(str(x), str(diff)))

n = int(input("enter the value: "))
cubic_root(n)

##this worked for me


问:
How to create a dynamic object from JSON that itself contains the structure of that object
There is a nice function in json.net to convert a json into a c# object:

```<code>CMyObject myObject = Newtonsoft.Json.JsonConvert.DeserializeObject<CMyObject>(json);
</code>```

Problem with that is that the structure needs to be known upfront.

Is there a lean way if the structre itself is coming from json itself?

Here an example of the json:

{
  "data": {
    "255622": {
      "2": {
        "value": "Active"
      },
      "3": {
        "value": null
      }
    }
  },

  "schema": {
    "255622": {
      "name": "NameOfStructure",
      "properties": {
        "2": {
          "multi_value": false,
          "name": "Status",
          "type_name": "String"
        },
        "3": {
          "multi_value": false,
          "name": "StatusDate",
          "type_name": "Date"
        }
      }
    }
  }
}
```
<p>This should convert to:</p>
```myObject (type NameOfStructure)
myObject.Status = "Active" (type String - single value)
myObject.StatusDate = null (type Date - single value)
```

Any ideas?

答:
With json.net you can easily do like this:

```<code>dynamic myObject = JsonConvert.DeserializeObject(json);
</code>```

The result will be dynamic so you can reach any property by

```<code>var myField = myObject.data.yourJsonfield;
</code>```

Also same with using Newtonsoft.Json.Linq:

```<code>dynamic myObject = JObject.Parse(json);
</code>```

You can find more information here.

Body:
There is a nice function in json.net to convert a json into a c# object:

CMyObject myObject = Newtonsoft.Json.JsonConvert.DeserializeObject<CMyObject>(json);

Problem with that is that the structure needs to be known upfront.

Is there a lean way if the structre itself is coming from json itself?

Here an example of the json:

{
  "data": {
    "255622": {
      "2": {
        "value": "Active"
      },
      "3": {
        "value": null
      }
    }
  },

  "schema": {
    "255622": {
      "name": "NameOfStructure",
      "properties": {
        "2": {
          "multi_value": false,
          "name": "Status",
          "type_name": "String"
        },
        "3": {
          "multi_value": false,
          "name": "StatusDate",
          "type_name": "Date"
        }
      }
    }
  }
}

This should convert to:

myObject (type NameOfStructure)
myObject.Status = "Active" (type String - single value)
myObject.StatusDate = null (type Date - single value)

Any ideas?

Body:
With json.net you can easily do like this:

dynamic myObject = JsonConvert.DeserializeObject(json);

The result will be dynamic so you can reach any property by

var myField = myObject.data.yourJsonfield;

Also same with using Newtonsoft.Json.Linq:

dynamic myObject = JObject.Parse(json);

You can find more information here.


问:
Conditional formatting on cells we apply a formula on
Let's say you have a table containing cells that have values generated from a formula.
The value in those cells all start with a number (until the separation with a ";" ).
Now you'd like to apply a range of colors to the cells on this table, based on how high this number is.

Is it possible to have such a formula in conditional formatting ?

Sheet used for test :
https://docs.google.com/spreadsheets/d/1MUkYDPoR1NxB8qWcYr_2Fp91FgUbnUOpfGd7EUuWCOg/edit?usp=sharing

答:
at this time color scale of conditional formatting can not be set to your B2:D5 range due to its limitation. if there are not many values in your dataset you can use regular conditional formatting where you can use MAX and MIN and then LARGE  and SMALL to return 2nd, 3rd, etc. a lot of setting it up but it would work.

example:

```<code>=MAX(INDEX(REGEXEXTRACT(B$2:B$5; "(.*);")*1))=REGEXEXTRACT(B2; "(.*);")*1
</code>```

```<code>=MIN(INDEX(REGEXEXTRACT(B$2:B$5; "(.*);")*1))=REGEXEXTRACT(B2; "(.*);")*1
</code>```

```<code>=LARGE(INDEX(REGEXEXTRACT(B$2:B$5; "(.*);")*1); 2)=REGEXEXTRACT(B2; "(.*);")*1
</code>```

```<code>=SMALL(INDEX(REGEXEXTRACT(B$2:B$5; "(.*);")*1); 2)=REGEXEXTRACT(B2; "(.*);")*1
</code>```

Body:
at this time color scale of conditional formatting can not be set to your B2:D5 range due to its limitation. if there are not many values in your dataset you can use regular conditional formatting where you can use MAX and MIN and then LARGE  and SMALL to return 2nd, 3rd, etc. a lot of setting it up but it would work.

example:

=MAX(INDEX(REGEXEXTRACT(B$2:B$5; "(.*);")*1))=REGEXEXTRACT(B2; "(.*);")*1

=MIN(INDEX(REGEXEXTRACT(B$2:B$5; "(.*);")*1))=REGEXEXTRACT(B2; "(.*);")*1

=LARGE(INDEX(REGEXEXTRACT(B$2:B$5; "(.*);")*1); 2)=REGEXEXTRACT(B2; "(.*);")*1

=SMALL(INDEX(REGEXEXTRACT(B$2:B$5; "(.*);")*1); 2)=REGEXEXTRACT(B2; "(.*);")*1


问:
delete from json conditionally
I have some JSON that looks like this

```<code>var js = '{
            "person" : {
                        "firstname" : "Steve",
                        "lastname" : "Smith",
                        "other": [
                                    {
                                       "age" : "32",
                                       "deceased" : false
                                    },
                                    {
                                       "age" : "14",
                                       "deceased" : false
                                    },
                                    {
                                       "age" : "421",
                                       "deceased" : false
                                    }
                                 ]
                       }
         }'
</code>```

I know how I delete all of "other" by doing this

```<code>var j = JSON.parse(js)
delete j[person.other]
</code>```

but what I really want is to delete the "other" node with a condition that is age = 14.

The result JSON I am looking for is

```<code>{
            "person" : {
                        "firstname" : "Steve",
                        "lastname" : "Smith",
                        "other": [
                                    {
                                       "age" : "32",
                                       "deceased" : false
                                    },
                                    {
                                       "age" : "421",
                                       "deceased" : false
                                    }
                                 ]
                       }
}
</code>```

I have looked at the delete operator here and it does not provide a conditional.

Sorry if this is too simple a question. I am learning.

Thanks

答:
The best approach to this would be not to alter the json, but create another one instead:

const filtered = { ...json, other: json.other.filter(item => item.age !== "14") }
```
<p>If you really need to alter the json, you can do the following:</p>
<pre class="lang-js prettyprint-override"><code>let index = json.other.findIndex(item => item.age === "14")
while (index !== -1) {
  json.other.splice(index, 1)
  index = json.other.findIndex(item => item.age === "14")
}
</code>```

Title: delete from json conditionally

Body:
I have some JSON that looks like this

var js = '{
            "person" : {
                        "firstname" : "Steve",
                        "lastname" : "Smith",
                        "other": [
                                    {
                                       "age" : "32",
                                       "deceased" : false
                                    },
                                    {
                                       "age" : "14",
                                       "deceased" : false
                                    },
                                    {
                                       "age" : "421",
                                       "deceased" : false
                                    }
                                 ]
                       }
         }'

I know how I delete all of "other" by doing this

var j = JSON.parse(js)
delete j[person.other]

but what I really want is to delete the "other" node with a condition that is age = 14.

The result JSON I am looking for is

{
            "person" : {
                        "firstname" : "Steve",
                        "lastname" : "Smith",
                        "other": [
                                    {
                                       "age" : "32",
                                       "deceased" : false
                                    },
                                    {
                                       "age" : "421",
                                       "deceased" : false
                                    }
                                 ]
                       }
}

I have looked at the delete operator here and it does not provide a conditional.

Sorry if this is too simple a question. I am learning.

Thanks

Body:
The best approach to this would be not to alter the json, but create another one instead:

const filtered = { ...json, other: json.other.filter(item => item.age !== "14") }

If you really need to alter the json, you can do the following:

let index = json.other.findIndex(item => item.age === "14")
while (index !== -1) {
  json.other.splice(index, 1)
  index = json.other.findIndex(item => item.age === "14")
}


答:
You can easily get the id of the customer you want to delete because you are in a map() function. Each one of your rows have a unical key that is equal to value.id, so you can modify the button as follows to do the trick :

```<code><button onClick={(e) => deleteClient(e, value.id)}>Delete</button>
</code>```

And don't forget to modify your deleteClient function :

```<code>async function deleteClient(e, id) {

e.preventDefault();
    //const id = document.getElementById("client").innerHTML;

    console.log(id);

    axios
      .delete("http://localhost:8080/api/clients/" + id)
      .then(function (response) {
        console.log(JSON.stringify(response.data));
      })
      .catch(function (error) {
        console.log(error);
      });
  }
</code>```

Title: How to get a cell value from an html table to use in an axios request in reactjs?

Body:
I have a HTML table of clients, and I want to be able to delete one of them thanks to a simple axios delete request. In order to do that, I have to get the ID of the client I want to delete.
So here is what I did :

  async function deleteClient(e) {
    e.preventDefault();
    const id = document.getElementById("client").innerHTML;

    console.log(id);

    axios
      .delete("http://localhost:8080/api/clients/" + id)
      .then(function (response) {
        console.log(JSON.stringify(response.data));
      })
      .catch(function (error) {
        console.log(error);
      });
  }

The deleteClient function is called onClick in the table. The issue is, it only ever gets the ID of the first row client and never the one from rows below. What can I do to get the right ID and be able to delete other clients ?

For info, here is my HTML table, it is filled dynamically thanks to useEffect hook and a simple axios get request :

            Clients

            ID
            Store Name
            Username
            Email
            Phone number
            Address
            Zipcode
            City
            Website
            Delete

{" "}
          {filteredData.map((value, index) => {
            return (

                {value.id}
                {value.storeName}
                {value.username}
                {value.email}
                {value.phone}
                {value.adress}
                {value.zipcode}
                {value.city}
                {value.website}

                  <button onClick={deleteClient}>Delete</button>

Thanks in advance for the help!

Body:
You can easily get the id of the customer you want to delete because you are in a map() function. Each one of your rows have a unical key that is equal to value.id, so you can modify the button as follows to do the trick :

<button onClick={(e) => deleteClient(e, value.id)}>Delete</button>

And don't forget to modify your deleteClient function :

async function deleteClient(e, id) {

e.preventDefault();
    //const id = document.getElementById("client").innerHTML;

    console.log(id);

    axios
      .delete("http://localhost:8080/api/clients/" + id)
      .then(function (response) {
        console.log(JSON.stringify(response.data));
      })
      .catch(function (error) {
        console.log(error);
      });
  }


问:
Convert a float column with nan to int pandas
I am trying to convert a float pandas column with nans to int format, using apply.
I would like to use something like this:

```<code>df.col = df.col.apply(to_integer)
</code>```

where the function to_integer is given by

```<code>def to_integer(x):
    if np.isnan(x):
        return np.NaN
    else:
        return int(x)
</code>```

However, when I attempt to apply it, the column remains the same.

How could I achieve this without having to use the standard technique of dtypes?

答:
You can't have NaN in an int column, NaN are float (unless you use an object type, which is not a good idea since you'll lose many vectorial abilities).

You can however use the new nullable integer type (NA).

Conversion can be done with convert_dtypes:

```<code>df = pd.DataFrame({'col': [1, 2, None]})
df = df.convert_dtypes()

# type(df.at[0, 'col'])
# numpy.int64

# type(df.at[2, 'col'])
# pandas._libs.missing.NAType
</code>```

output:

```<code>    col
0     1
1     2
2  <NA>
</code>```

Body:
I am trying to convert a float pandas column with nans to int format, using apply.
I would like to use something like this:

df.col = df.col.apply(to_integer)

where the function to_integer is given by

def to_integer(x):
    if np.isnan(x):
        return np.NaN
    else:
        return int(x)

However, when I attempt to apply it, the column remains the same.

How could I achieve this without having to use the standard technique of dtypes?

Body:
You can't have NaN in an int column, NaN are float (unless you use an object type, which is not a good idea since you'll lose many vectorial abilities).

You can however use the new nullable integer type (NA).

Conversion can be done with convert_dtypes:

df = pd.DataFrame({'col': [1, 2, None]})
df = df.convert_dtypes()

# type(df.at[0, 'col'])
# numpy.int64

# type(df.at[2, 'col'])
# pandas._libs.missing.NAType

output:

    col
0     1
1     2
2  <NA>


问:
WPF set DataContext to a ViewModel without default constructor
I have a ViewModel that accepts several constructor parameters. As I understand because of this the only way to set View's DataContext is using code behind.

This has its downsides:

Visual Studio will not show ViewModel inteliscence for the view that is being constructed

There is no way to see design time data that is defined in my ViewModel constructor in XAML designer because designer simply breaks

What are my options?

I would like to have a ViewModel that can accept constructor parameters, have design time data and that my Visual Studio inteliscence provide me suggestions about members in my ViewModel so I could have a good design experience.

PS. I'm using MVVM Toolkit / Windows Community Toolkit from Microsoft, but I would appreciate any answer on how to achieve my end goal. Thank you.

答:
What are my options?

A common approach is to create a separate design time view model class with a parameterless constructor and set the design time data context to this type:

```<code><Window ... d:DataContext="{d:DesignInstance Type=local:DesignTimeViewModel, IsDesignTimeCreatable=True}"
</code>```

What you shouldn't do is to design your application and define your classes according to how the designer in Visual Studio works.

Body:
What are my options?

A common approach is to create a separate design time view model class with a parameterless constructor and set the design time data context to this type:

<Window ... d:DataContext="{d:DesignInstance Type=local:DesignTimeViewModel, IsDesignTimeCreatable=True}"

What you shouldn't do is to design your application and define your classes according to how the designer in Visual Studio works.