问:
Backbone.js model.save returns TypeError?
I'm trying to implement backbone.js model which looks like this in Django:

```<code>class Booking(models.Model):
    date        = models.DateField('date booked')
    time        = models.TimeField('time booked')
    duration    = models.PositiveSmallIntegerField('duration booked') #x * 15
    user        = models.ForeignKey(User, related_name='bookings')
    room        = models.ForeignKey(Room, related_name='bookings')
    description = models.TextField()
</code>```

It's served through a RESTful interface via TastyPie: /api/booking.
My backbone model is set up like this as per instructions here:

```<code>window.Booking = Backbone.Model.extend({
url     :   function(){
                return this.get('resource_uri') || this.collection.url;
            },
urlRoot :   "/api/booking",
defaults:   {
                user    :   "/api/user/5" //defaults to nobodys
                }
});
window.Bookings = Backbone.Collection.extend({
url         :   BOOKING_API,
parse       :   function(data){
                return data.objects;
            }
});
</code>```

Now trying to test it out in console like this:

```<code>var booking = new Booking({date : "2011-08-17", time: "12:45", duration: 30, room: "/api/room/1", description: "quickbook"});
booking.save();
</code>```

The above code returns a TypeError. I don't see what I'm doing wrong.

答: Because when you call save() method there is no resource_uri and no this.collection in model. So your url returns undefined

Body:
I'm trying to implement backbone.js model which looks like this in Django:

class Booking(models.Model):
    date        = models.DateField('date booked')
    time        = models.TimeField('time booked')
    duration    = models.PositiveSmallIntegerField('duration booked') #x * 15
    user        = models.ForeignKey(User, related_name='bookings')
    room        = models.ForeignKey(Room, related_name='bookings')
    description = models.TextField()

It's served through a RESTful interface via TastyPie: /api/booking.
My backbone model is set up like this as per instructions here:

window.Booking = Backbone.Model.extend({
url     :   function(){
                return this.get('resource_uri') || this.collection.url;
            },
urlRoot :   "/api/booking",
defaults:   {
                user    :   "/api/user/5" //defaults to nobodys
                }
});
window.Bookings = Backbone.Collection.extend({
url         :   BOOKING_API,
parse       :   function(data){
                return data.objects;
            }
});

Now trying to test it out in console like this:

var booking = new Booking({date : "2011-08-17", time: "12:45", duration: 30, room: "/api/room/1", description: "quickbook"});
booking.save();

The above code returns a TypeError. I don't see what I'm doing wrong.


来源: stackexchange

问:
How to change the language for the Wear OS emulator in Android Studio?
I checked all the settings in the watch emulator, but I can't figure out how to set the language. It seems like the language is set by the connected phone. My emulator is not connected to a phone though. Is there another way to achieve this?</p>

答:
There's a really handy app installed by default on the emulator called "Custom Locale". It allows you to change the locale of the device, which can be used to change the language.

Click the ADD NEW button to enter a local on the format xx_YY. Apply the new locale and exit the app to verify that the language has been updated. I changed it to Swedish and you can see in the screenshots below that the title is updated from "Recents" to "Senaste".

Pleae note that not all languages are supported by the system.

ContentLicense: CC BY-SA 4.0


问:
How to Add an Object to a Json Array Depending a value of another Key in the File Using JoltTransformationJson in NiFi
This is my first time to use JoltTransformationJson, so I have limited knowledge and experience on that. Please help me with this complicated project.

Request:
when the payment.code <> "paid", I have to do the following two things for the file.

to change the payment.code ="denied" and payment.text ="denied"

to add a JSON object to item.ADJ

When the payment.code =="paid", don't need to change anything.

Input :

{
  "resourceType": "E",
  "id": "11",
  "identifier": [
    {
      "type": {
        "coding": [
          {
            "system": "sys1",
            "code": "aaa"
          }
        ]
      },
      "value": "212"
    },
    {
      "type": {
        "coding": [
          {
            "system": "sys2",
            "code": "RRR"
          }
        ]
      },
      "value": "367"
    }
  ],
  "status": "active",
  "created": "2021-08-05T02:43:48+00:00",
  "outcome": "complete",
  "item": [
    {
      "sequence": 1,
      "product": {
        "coding": [
          {
            "system": "example",
            "code": "abc",
            "display": "ABC"
          }
        ],
        "text": "ABC"
      },
      "servicedDate": "2021-08-04",
      "quantity": {
        "value": 60
      },
      "ADJ": [
        {
          "category": {
            "coding": [
              {
                "system": "code1",
                "code": "code1",
                "display": "CODE1"
              }
            ],
            "text": "CODE1"
          },
          "amount": {
            "value": 46.45,
            "currency": "USD"
          }
        },
        {
          "category": {
            "coding": [
              {
                "system": "code2",
                "code": "code2",
                "display": "CODE2"
              }
            ],
            "text": "CODE2"
          },
          "amount": {
            "value": 12.04,
            "currency": "USD"
          }
        }
      ]
    }
  ],
  "payment": {
    "type": {
      "coding": [
        {
          "system": "http://payment.com",
          "code": "reversed/cancelled"
        }
      ],
      "text": "cancelled"
    }
  }
}
```
<p><strong>My Expected Output</strong> :</p>
<pre class="lang-json prettyprint-override"><code>{
  "resourceType": "E",
  "id": "11",
  "identifier": [
    {
      "type": {
        "coding": [
          {
            "system": "sys1",
            "code": "aaa"
          }
        ]
      },
      "value": "212"
    },
    {
      "type": {
        "coding": [
          {
            "system": "sys2",
            "code": "RRR"
          }
        ]
      },
      "value": "367"
    }
  ],
  "status": "active",
  "created": "2021-08-05T02:43:48+00:00",
  "outcome": "complete",
  "item": [
    {
      "sequence": 1,
      "product": {
        "coding": [
          {
            "system": "example",
            "code": "abc",
            "display": "ABC"
          }
        ],
        "text": "ABC"
      },
      "servicedDate": "2021-08-04",
      "quantity": {
        "value": 60
      },
      "ADJ": [
        {
          "category": {
            "coding": [
              {
                "system": "code1",
                "code": "code1",
                "display": "CODE1"
              }
            ],
            "text": "CODE1"
          },
          "amount": {
            "value": 46.45,
            "currency": "USD"
          }
        },
        {
          "category": {
            "coding": [
              {
                "system": "code2",
                "code": "code2",
                "display": "CODE2"
              }
            ],
            "text": "CODE2"
          },
          "amount": {
            "value": 12.04,
            "currency": "USD"
          }
        },
        {// new object I want to insert into
          "category": {
            "coding": [
              {
                "system": "sys_denail",
                "code": "denialreason"
              }
            ],
          "reason": {
            "coding": [
              {
                "system": "https://example.com",
                "code": "A1"
              }
            ],
            "text": "unknown"
          }}
        }
      ]
    }
  ],
  "payment": {
    "type": {
      "coding": [
        {
          "system": "http://payment.com",
          "code": "denied" //change the value to denied
        }
      ],
      "text": "denied" //change the value to denied
    }
  }
}
</code>```

Edit : I've tried to answer the second case by myself to be evaluated after the first case is answered

答:
Welcome to SO, please ask minimal and reproducible questions, and show your effort tried for the future.

What you need is to use a conditional logic along with placeholder values with ampersand symbols depending on the levels of each key name within the tree.

I have partially answered, which will handle the bottom part of your question. Indeed the logic for the rest(inserting an object to the array will be similiar)

So, consider having a look at the following solution

[
  {
    "operation": "shift",
    "spec": {
      "*": "&",
      "payment": {
        "type": {
          "coding": {
            "*": {
              "*": "&4.&3.&2[&1].&",
              "code": {
                "paid": {
                  "@1": "&6.&5.&4[&3].&2",
                  "@(4,text)": "&6.text"
                },
                "*": {
                  "#denied": "&6.&5.&4[&3].code",
                  "@(4,text)": {
                    "#denied": "&6.text"
                  }
                }
              }
            }
          }
        }
      }
    }
  }
]
```
<p><strong>Edit</strong>(<em>for your own answer related to adding an object</em>)<strong>:</strong></p>
<p>your current idea of using <strong>shift</strong> after <strong>default</strong> transformation spec is pretty good, you can rephrase like</p>
<pre class="lang-json prettyprint-override"><code>[
  {
    "operation": "default",
    "spec": {
      "temp_deny": {
        "denialreason": {
          "category": {
            "coding": [
              {
                "system": "sys_denail",
                "code": "denialreason"
              }
            ],
            "reason": {
              "coding": [
                {
                  "system": "https://example.com",
                  "code": "A1"
              }
            ],
              "text": "unknown"
            }
          }
        }
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "*": "&",
      "item": {
        "*": {
          "*": "&2[&1].&",
          "ADJ": {
            "@": "&3[&2].&",
            "@(4,temp_deny)": "&3[&2].&"
          }
        }
      }
    }
  }
]
</code>```

Body:
This is my first time to use JoltTransformationJson, so I have limited knowledge and experience on that. Please help me with this complicated project.

Request:
when the payment.code <> "paid", I have to do the following two things for the file.

to change the payment.code ="denied" and payment.text ="denied"

to add a JSON object to item.ADJ

When the payment.code =="paid", don't need to change anything.

Input :

{
  "resourceType": "E",
  "id": "11",
  "identifier": [
    {
      "type": {
        "coding": [
          {
            "system": "sys1",
            "code": "aaa"
          }
        ]
      },
      "value": "212"
    },
    {
      "type": {
        "coding": [
          {
            "system": "sys2",
            "code": "RRR"
          }
        ]
      },
      "value": "367"
    }
  ],
  "status": "active",
  "created": "2021-08-05T02:43:48+00:00",
  "outcome": "complete",
  "item": [
    {
      "sequence": 1,
      "product": {
        "coding": [
          {
            "system": "example",
            "code": "abc",
            "display": "ABC"
          }
        ],
        "text": "ABC"
      },
      "servicedDate": "2021-08-04",
      "quantity": {
        "value": 60
      },
      "ADJ": [
        {
          "category": {
            "coding": [
              {
                "system": "code1",
                "code": "code1",
                "display": "CODE1"
              }
            ],
            "text": "CODE1"
          },
          "amount": {
            "value": 46.45,
            "currency": "USD"
          }
        },
        {
          "category": {
            "coding": [
              {
                "system": "code2",
                "code": "code2",
                "display": "CODE2"
              }
            ],
            "text": "CODE2"
          },
          "amount": {
            "value": 12.04,
            "currency": "USD"
          }
        }
      ]
    }
  ],
  "payment": {
    "type": {
      "coding": [
        {
          "system": "http://payment.com",
          "code": "reversed/cancelled"
        }
      ],
      "text": "cancelled"
    }
  }
}

My Expected Output :

{
  "resourceType": "E",
  "id": "11",
  "identifier": [
    {
      "type": {
        "coding": [
          {
            "system": "sys1",
            "code": "aaa"
          }
        ]
      },
      "value": "212"
    },
    {
      "type": {
        "coding": [
          {
            "system": "sys2",
            "code": "RRR"
          }
        ]
      },
      "value": "367"
    }
  ],
  "status": "active",
  "created": "2021-08-05T02:43:48+00:00",
  "outcome": "complete",
  "item": [
    {
      "sequence": 1,
      "product": {
        "coding": [
          {
            "system": "example",
            "code": "abc",
            "display": "ABC"
          }
        ],
        "text": "ABC"
      },
      "servicedDate": "2021-08-04",
      "quantity": {
        "value": 60
      },
      "ADJ": [
        {
          "category": {
            "coding": [
              {
                "system": "code1",
                "code": "code1",
                "display": "CODE1"
              }
            ],
            "text": "CODE1"
          },
          "amount": {
            "value": 46.45,
            "currency": "USD"
          }
        },
        {
          "category": {
            "coding": [
              {
                "system": "code2",
                "code": "code2",
                "display": "CODE2"
              }
            ],
            "text": "CODE2"
          },
          "amount": {
            "value": 12.04,
            "currency": "USD"
          }
        },
        {// new object I want to insert into
          "category": {
            "coding": [
              {
                "system": "sys_denail",
                "code": "denialreason"
              }
            ],
          "reason": {
            "coding": [
              {
                "system": "https://example.com",
                "code": "A1"
              }
            ],
            "text": "unknown"
          }}
        }
      ]
    }
  ],
  "payment": {
    "type": {
      "coding": [
        {
          "system": "http://payment.com",
          "code": "denied" //change the value to denied
        }
      ],
      "text": "denied" //change the value to denied
    }
  }
}

Edit : I've tried to answer the second case by myself to be evaluated after the first case is answered

Body:
Welcome to SO, please ask minimal and reproducible questions, and show your effort tried for the future.

What you need is to use a conditional logic along with placeholder values with ampersand symbols depending on the levels of each key name within the tree.

I have partially answered, which will handle the bottom part of your question. Indeed the logic for the rest(inserting an object to the array will be similiar)

So, consider having a look at the following solution

[
  {
    "operation": "shift",
    "spec": {
      "*": "&",
      "payment": {
        "type": {
          "coding": {
            "*": {
              "*": "&4.&3.&2[&1].&",
              "code": {
                "paid": {
                  "@1": "&6.&5.&4[&3].&2",
                  "@(4,text)": "&6.text"
                },
                "*": {
                  "#denied": "&6.&5.&4[&3].code",
                  "@(4,text)": {
                    "#denied": "&6.text"
                  }
                }
              }
            }
          }
        }
      }
    }
  }
]

Edit(for your own answer related to adding an object):

your current idea of using shift after default transformation spec is pretty good, you can rephrase like

[
  {
    "operation": "default",
    "spec": {
      "temp_deny": {
        "denialreason": {
          "category": {
            "coding": [
              {
                "system": "sys_denail",
                "code": "denialreason"
              }
            ],
            "reason": {
              "coding": [
                {
                  "system": "https://example.com",
                  "code": "A1"
              }
            ],
              "text": "unknown"
            }
          }
        }
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "*": "&",
      "item": {
        "*": {
          "*": "&2[&1].&",
          "ADJ": {
            "@": "&3[&2].&",
            "@(4,temp_deny)": "&3[&2].&"
          }
        }
      }
    }
  }
]


问:
Match two strings in one line with grep
I am trying to use grep to match lines that contain two different strings. I have tried the following but this matches lines that contain either string1 or string2 which not what I want.

```<code>grep 'string1\|string2' filename
</code>```

So how do I match with grep only the lines that contain both strings?

答:
If git is initialized and added to the branch then it is better to use git grep because it is super fast and it will search inside the whole directory.</p>

```<code>git grep 'string1.*string2.*string3'
</code>```

Title: Match two strings in one line with grep

Body:
I am trying to use grep to match lines that contain two different strings. I have tried the following but this matches lines that contain either string1 or string2 which not what I want.

grep 'string1\|string2' filename

So how do I match with grep only the lines that contain both strings?

Body:
If git is initialized and added to the branch then it is better to use git grep because it is super fast and it will search inside the whole directory.

git grep 'string1.*string2.*string3'


问:
Git Ignore Case-Sensitive Folder Names
There's lots of questions/answers on committing filename changes on case-insensitive OS's, but my problem is git-ignoring a case sensitive folder (on both linux and windows).

Example: key 3rd-party software tool generates folder Test/ with build artifacts for testing.
Standard location for test files in our system are test/ folders.
The gitignore has **/Test/ (what we don't want to see/commit), but then test/ folders don't show up (what we do want to see/commit).

Testing this on latest windows git-bash, setting/toggling core.ignorecase = false doesn't seem to change the behavior.

Edit: From VonC's useful command to check per-file gitignore status, a demo

```<code>git init
mkdir -p d1/Test d2/test
touch d1/Test/hidden d2/test/visible
git config -f .gitconfig --add core.ignorecase false
echo "**/Test/" > .gitignore
</code>```

git status

```<code>Untracked files:
.gitconfig
.gitignore
# Missing d2/test/visible
</code>```

git -c core.ignorecase=false check-ignore -v  --  d1/Test/hidden

```<code>.gitignore:1:**/Test/    d1/Test/hidden
</code>```

git -c core.ignorecase=false check-ignore -v  --  d2/test/visible

```<code># Nothing, which is correct
</code>```

Second Edit:

Which leads to the (less) obvious problem: forgetting to add .gitconfig to local config: (of course it won't behave like it's changed if it's not actually changed...)

git config --local include.path ../.gitconfig

答:
setting/toggling core.ignorecase = false doesn't seem to change the behavior.

It should though.

Test it out with a file within that folder:

```<code>git -c core.ignorecase=false check-ignore -v  --  Test/a/File
</code>```

Another approach would be to sidestep the issue entirely and make sure:

the standard location is, for instance, in tests/ instead of test/,

or the key software generates tests in Tests/ instead of Test/.

Title: Git Ignore Case-Sensitive Folder Names

Body:
There's lots of questions/answers on committing filename changes on case-insensitive OS's, but my problem is git-ignoring a case sensitive folder (on both linux and windows).

Example: key 3rd-party software tool generates folder Test/ with build artifacts for testing.
Standard location for test files in our system are test/ folders.
The gitignore has **/Test/ (what we don't want to see/commit), but then test/ folders don't show up (what we do want to see/commit).

Testing this on latest windows git-bash, setting/toggling core.ignorecase = false doesn't seem to change the behavior.

Edit: From VonC's useful command to check per-file gitignore status, a demo

git init
mkdir -p d1/Test d2/test
touch d1/Test/hidden d2/test/visible
git config -f .gitconfig --add core.ignorecase false
echo "**/Test/" > .gitignore

git status

Untracked files:
.gitconfig
.gitignore
# Missing d2/test/visible

git -c core.ignorecase=false check-ignore -v  --  d1/Test/hidden

.gitignore:1:**/Test/    d1/Test/hidden

git -c core.ignorecase=false check-ignore -v  --  d2/test/visible

# Nothing, which is correct

Second Edit:

Which leads to the (less) obvious problem: forgetting to add .gitconfig to local config: (of course it won't behave like it's changed if it's not actually changed...)

git config --local include.path ../.gitconfig

Body:
setting/toggling core.ignorecase = false doesn't seem to change the behavior.

It should though.

Test it out with a file within that folder:

git -c core.ignorecase=false check-ignore -v  --  Test/a/File

Another approach would be to sidestep the issue entirely and make sure:

the standard location is, for instance, in tests/ instead of test/,

or the key software generates tests in Tests/ instead of Test/.


问:
SHOW COLUMN escaping mechanism
I have a column called \'column. I am able to use it in SELECT statements just like any other column. However, when I try to perform SHOW COLUMNS FROM myTable LIKE '\\''column' I get no results. I observed that it works if I double escape the backslash: '\\\\''column'.

I tested this from MariaDB console, but I also observed the same behaviour in MySQL 8.

How does the escaping work? How should I properly escape the value so that I can fetch the column information?

DB Fiddle

答:
From the mysql documentation

MySQL uses C escape syntax in strings (for example, \n to represent
the newline character). If you want a LIKE string to contain a literal
, you must double it. (Unless the NO_BACKSLASH_ESCAPES SQL mode is
enabled, in which case no escape character is used.) For example, to
search for \n, specify it as \\n. To search for \, specify it as \\\\;
this is because the backslashes are stripped once by the parser and
again when the pattern match is made, leaving a single backslash to be
matched against.

Title: SHOW COLUMN escaping mechanism


问:
How to disable error squiggles in visual studio code
I am using Visual Studio Code to program in C++ but it keeps giving me error squiggles. I tried disabling them in the settings by changing C_Cpp error squiggles to disabled but they still appear. Is there anything else I need to do to disable them as I find them very annoying?

答:
Currently, there is no settings to turn the error decorations off but some language extensions implement their own solutions.

If you are looking for a language agnostic solution, you can make the squiggly lines transparent by adding following setting to general settings or workspace settings file.

"workbench.colorCustomizations": {
  //                                ↓↓
  "editorError.foreground": "#00000000"
}
```
<p>For a specific language:</p>
<pre class="lang-json prettyprint-override"><code>"workbench.colorCustomizations": {
  "[jsonc]": {
    //                                ↓↓
    "editorError.foreground": "#00000000"
  }
}
</code>```

Please note that we use 8-digit hex value, the first six is not important but last two should be zero to make the color transparent.

Here is how you can do it programmatically in an extension:

workspace.getConfiguration('workbench').update( 'colorCustomizations', {
    "editorError.foreground": "#00000000",
});
```

Body:
Currently, there is no settings to turn the error decorations off but some language extensions implement their own solutions.

If you are looking for a language agnostic solution, you can make the squiggly lines transparent by adding following setting to general settings or workspace settings file.

"workbench.colorCustomizations": {
  //                                ↓↓
  "editorError.foreground": "#00000000"
}

For a specific language:

"workbench.colorCustomizations": {
  "[jsonc]": {
    //                                ↓↓
    "editorError.foreground": "#00000000"
  }
}

Please note that we use 8-digit hex value, the first six is not important but last two should be zero to make the color transparent.

Here is how you can do it programmatically in an extension:

workspace.getConfiguration('workbench').update( 'colorCustomizations', {
    "editorError.foreground": "#00000000",
});


问:
We made it reliable. What's next? Usability?
I'm working in a small development group. We are building and improving our product.

Half a year ago we couldn't think about higher characteristics, such as usability, because we had so many problems with our product. Many bugs, high technical debt, low performance and other problems kept us from being able to focus on usability.

With time we've improved our process substantially. What we've done:

Real Agile iterations

Continuous integration

Testing(unit-tests, functional Smoke tests, performance)

Code quality is 'good'

Painless deployment process

So we are now producing stable, reliable releases. The following quote (paraphrased) describes our current situation:

first - make it work; after that, make it reliable; after that, make it usable

We are geeks, so we can't 'make' a great UI by ourselves.
So what should we do? What direction can you recommend?
Maybe we should hire Usability experts part-time or full-time?
How can we explain the importance of Usability to our stakeholders?
How do we convince them that this is useful?

答:
My one-liner about the importance of usability:

What use is a reliable system that is not usable?

If you have an existing product with existing users, then what makes you think that your current UI is not usable?

Do you suspect that there are some minor changes you can make that will greatly improve usability or is something more revolutionary required? If the latter, then what about the needs of your existing users, will they be willing to re-learn a whole new UI?

Edit

A user interface can be considered "poor" for a variety of reasons...

It is just plain ugly / old fashioned / does not "look like a Windows application"

It uses metaphors or workflows which do not relate to things that the user understands or wants to do

The first of these is relatively easy to fix, especially if you hire in a great designer. The fix would be the equivalent of redecorating your lounge and buying a new sofa and TV. Same room, different experience. Your existing users would still be able to use this application.

Fixing the second of these gets a lot more complex and involved, and might really impact your codebase. It's hard to comment further without knowing more about your application.

OwnerDisplayName: Fedyashev Nikita

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Gortok

OwnerDisplayName: Richard E

LastEditorDisplayName: Richard E


问:
playbook vs blackberry api
what is the difference between blackberry smartphone sdk and blackberry playbook sdk?
can a blackberry phone application work on a blackberry playbook?</p>

答: playbook is run on the QNX OS and blackberry smartphone have their on OS.both are totaly differnet.with the help of Blackberry Brige you can run your blackberry application to playbook.they told that they will support java on playbook but still no update is comming in that.</p>

ContentLicense: CC BY-SA 3.0

Title: playbook vs blackberry api


问:
Can we pass an array as parameter in any function in PHP?
I have a function to send mail to users and I want to pass one of its parameter as an array of ids.

Is this possible to do? If yes, how can it be done?

Suppose we have a function as:

```<code>function sendemail($id, $userid) {

}
</code>```

In the example, $id should be an array.

答:
I found Delcon answer helpful but I was looking for this</p>
```<code>function sendmail($user1, $user2, $user3){
  echo $user1;
  echo $user2;
  echo $user3;
}

$users = array('user1','user2','user3');
sendmail(...$users);
</code>```

Body:
I have a function to send mail to users and I want to pass one of its parameter as an array of ids.

Is this possible to do? If yes, how can it be done?

Suppose we have a function as:

function sendemail($id, $userid) {

}

In the example, $id should be an array.

Body:
I found Delcon answer helpful but I was looking for this

function sendmail($user1, $user2, $user3){
  echo $user1;
  echo $user2;
  echo $user3;
}

$users = array('user1','user2','user3');
sendmail(...$users);


问:
Replacing string text in python w/ regex, re, or str.replace
Hi I'm looking for some help replacing a certain string pattern in my data.  I have a massive list of json data from an API, however, it appears a date field is being returned as a python function before having been parsed out into raw text.  Below is an example of the started_at attribute in the raw json data which is causing me problems:

'started_at': datetime.datetime(2022, 2, 7, 16, 37, 26)

Like instead of the actual date + timestamp in raw text, it's just represented as the python function.  When I try running json.loads() on this data, it fails because of this attribute not being properly parsed out.  So my potential solution is I want to replace the datetime.datetime(2022, 2, 7, 16, 37, 26) text with a simple variable like current_date = str(datetime.now().date()), so it will just be 2022-02-07 instead of the whole datetime string.

I've tried doing raw_json.replace(datetime.datetime(*, *, *, *, *, *), current_date), but it doesn't work because I'm not sure how to manipulate the regex in a way so that it captures ANY pattern in that format.

Putting in some reproducible code below if anybody wants to try it out:

```<code>import re
from datetime import datetime

current_date = str(datetime.now().date())
sample_json = str({'started_at': 'datetime.datetime(2022, 2, 7, 16, 37, 26)'})

formatted_json = sample_json.replace('datetime.datetime(*, *, *, *, *, *)', current_date)

</code>```

答:
After enough trial & error I got the proper regex answer.

```<code># all json text needs to be wrapped in double quotes
current_date = str(f'"{datetime.now().date()}"')
sample_json = str({'started_at': 'datetime.datetime(2022, 2, 7, 16, 37, 26)'})
formatted_json = re.sub('datetime.datetime[\(\[].*?[\)\]]', current_date, sample_json)

</code>```

The [\(\[].*?[\)\]] part will remove the parantheses and everything inside the parantheses, and adding in datetime.datetime will add that part to the string pattern as well.

Body:
Hi I'm looking for some help replacing a certain string pattern in my data.  I have a massive list of json data from an API, however, it appears a date field is being returned as a python function before having been parsed out into raw text.  Below is an example of the started_at attribute in the raw json data which is causing me problems:

'started_at': datetime.datetime(2022, 2, 7, 16, 37, 26)

Like instead of the actual date + timestamp in raw text, it's just represented as the python function.  When I try running json.loads() on this data, it fails because of this attribute not being properly parsed out.  So my potential solution is I want to replace the datetime.datetime(2022, 2, 7, 16, 37, 26) text with a simple variable like current_date = str(datetime.now().date()), so it will just be 2022-02-07 instead of the whole datetime string.

I've tried doing raw_json.replace(datetime.datetime(*, *, *, *, *, *), current_date), but it doesn't work because I'm not sure how to manipulate the regex in a way so that it captures ANY pattern in that format.

Putting in some reproducible code below if anybody wants to try it out:

import re
from datetime import datetime

current_date = str(datetime.now().date())
sample_json = str({'started_at': 'datetime.datetime(2022, 2, 7, 16, 37, 26)'})

formatted_json = sample_json.replace('datetime.datetime(*, *, *, *, *, *)', current_date)

Body:
After enough trial & error I got the proper regex answer.

# all json text needs to be wrapped in double quotes
current_date = str(f'"{datetime.now().date()}"')
sample_json = str({'started_at': 'datetime.datetime(2022, 2, 7, 16, 37, 26)'})
formatted_json = re.sub('datetime.datetime[\(\[].*?[\)\]]', current_date, sample_json)

The [\(\[].*?[\)\]] part will remove the parantheses and everything inside the parantheses, and adding in datetime.datetime will add that part to the string pattern as well.


问:
The sx styling for Drawer element does not work
I have an elementary component.
With sx I try to add styles, but they are not added to the Drawer, but to its parent block and because of this the styles are not applied.
What am I doing wrong?
Thanks.

```<code>import React from "react";
import Typography from "@mui/material/Typography";
import Drawer from "@mui/material/Drawer";

export const Menu= () => {
  return (
    <Drawer
      variant="permanent"
      sx={{ width: 240, fontSize: 14, bgcolor: "green" }}
    >
      <Typography>My Own Logo</Typography>
    </Drawer>
  );
};
</code>```

Blocks with styles

答:
You need to step into the root css of the drawer:

```<code><Drawer
  variant="permanent"
  sx={{ "& .MuiDrawer-paper": { width: 240, backgroundColor: "green" } }}
>
  <Typography fontSize={22}>My Own Logo</Typography>
</Drawer>
</code>```

Control the font size with the Typography component.

Here's a sandbox

Body:
I have an elementary component.
With sx I try to add styles, but they are not added to the Drawer, but to its parent block and because of this the styles are not applied.
What am I doing wrong?
Thanks.

import React from "react";
import Typography from "@mui/material/Typography";
import Drawer from "@mui/material/Drawer";

export const Menu= () => {
  return (
    <Drawer
      variant="permanent"
      sx={{ width: 240, fontSize: 14, bgcolor: "green" }}
    >
      <Typography>My Own Logo</Typography>
    </Drawer>
  );
};

Blocks with styles

Body:
You need to step into the root css of the drawer:

<Drawer
  variant="permanent"
  sx={{ "& .MuiDrawer-paper": { width: 240, backgroundColor: "green" } }}
>
  <Typography fontSize={22}>My Own Logo</Typography>
</Drawer>

Control the font size with the Typography component.

Here's a sandbox


问:
How to insert accented characters in ASCII-encoded Rd files?
Can LaTeX escapes for accents be used in Rd files? I tried the standard \'e and many variants (\'{e}, {\'e}, \\'e, \\'{e}, {\\'e}, etc.), but none is rendered as an accented character in the PDF or HTML output.

I want my References section (i.e. \references{}) to be rendered with accented characters, but I do not want to type non-ASCII characters in my Rd files. Is there good/recommended practice? Should I simply replace non-ASCII characters with their ASCII equivalents (é → e, ø → o)?

To be clear, I know it is possible to type accented characters (e.g., é) directly in UTF-8-encoded files, but I would prefer to keep ASCII-encoded files.

This question is not about:

how to type special/accented letters in LaTeX

how to use UTF-8 in LaTeX

accents/special characters in R Markdown

or variants.

Minimal test package

Package structure:

test
test/man
test/man/one.Rd
test/R
test/R/one.R
test/DESCRIPTION
```
<p><code>test/man/one.Rd</code>:</p>
<pre class="lang-tex prettyprint-override"><code>\name{one}
\alias{one}
\title{Get One}
\description{Accents are not rendered: \'e \'{e} {\'e} \\'e \\'{e} {\\'e}}
\usage{
one()
}
</code>```

test/R/one.R:

one <- function() 1
```
<p><code>test/DESCRIPTION</code>:</p>
<pre class="lang-yaml prettyprint-override"><code>Package: test
Version: 0.1
Title: Test
Author: Nobody
Maintainer: Nobody <no@body.org>
Description: Test.
License: GPL-3
</code>```

Build, check, and install with:

$ R CMD build test
$ R CMD check test_0.1.tar.gz
$ R CMD INSTALL test_0.1.tar.gz
```

答:
Rd syntax is only LaTeX-like: it supports a limited set of macros, but these are not guaranteed to behave like their LaTeX counterparts, if any exist. Conversely, very few LaTeX macros have Rd equivalents.

This section of the Writing R Extensions manual describes most of the built-in Rd macros. Tables 1, 2, and 3 of this technical paper provide a complete list.

This section of WRE addresses encoding specifically.
Use of non-ASCII characters in Rd files is supported, provided that you declare an appropriate encoding, either in the files themselves (via \enc and \encoding) or in DESCRIPTION (via the Encoding field). However, restriction to ASCII characters is encouraged:

Wherever possible, avoid non-ASCII chars in Rd files, and even symbols such as ‘<’, ‘>’, ‘$’, ‘^’, ‘&’, ‘|’, ‘@’, ‘~’, and ‘*’ outside ‘verbatim’ environments (since they may disappear in fonts designed to render text).

The recommended way to obtain non-ASCII characters in rendered help  without including non-ASCII characters in your Rd files is to use conditional text. \ifelse allows you to provide raw LaTeX for PDF help pages, raw HTML for HTML help pages, and verbatim text for plain text help pages:

\ifelse{latex}{\out{\'{e}}}{\ifelse{html}{\out{é}}{e}}
```
<p>That is quite verbose, so I would suggest defining your own macro(s) in <code>man/macros/macros.Rd</code>. You can do this with <code>\newcommand</code> and <code>\renewcommand</code>:</p>
<pre class="lang-none prettyprint-override"><code>\newcommand{\eacute}{\ifelse{latex}{\out{\'{e}}}{\ifelse{html}{\out{é}}{e}}}
</code>```

Then you can use \eacute{} freely in all of your Rd files. To check that text is rendered the way you want in all formats, install the package and run help(topic, help_type=), with help_type equal to "text", "html", or "pdf".

Body:
Can LaTeX escapes for accents be used in Rd files? I tried the standard \'e and many variants (\'{e}, {\'e}, \\'e, \\'{e}, {\\'e}, etc.), but none is rendered as an accented character in the PDF or HTML output.

I want my References section (i.e. \references{}) to be rendered with accented characters, but I do not want to type non-ASCII characters in my Rd files. Is there good/recommended practice? Should I simply replace non-ASCII characters with their ASCII equivalents (é → e, ø → o)?

To be clear, I know it is possible to type accented characters (e.g., é) directly in UTF-8-encoded files, but I would prefer to keep ASCII-encoded files.

This question is not about:

how to type special/accented letters in LaTeX

how to use UTF-8 in LaTeX

accents/special characters in R Markdown

or variants.

Minimal test package

Package structure:

test
test/man
test/man/one.Rd
test/R
test/R/one.R
test/DESCRIPTION

test/man/one.Rd:

\name{one}
\alias{one}
\title{Get One}
\description{Accents are not rendered: \'e \'{e} {\'e} \\'e \\'{e} {\\'e}}
\usage{
one()
}

test/R/one.R:

one <- function() 1

test/DESCRIPTION:

Package: test
Version: 0.1
Title: Test
Author: Nobody
Maintainer: Nobody <no@body.org>
Description: Test.
License: GPL-3

Build, check, and install with:

$ R CMD build test
$ R CMD check test_0.1.tar.gz
$ R CMD INSTALL test_0.1.tar.gz

Body:
Rd syntax is only LaTeX-like: it supports a limited set of macros, but these are not guaranteed to behave like their LaTeX counterparts, if any exist. Conversely, very few LaTeX macros have Rd equivalents.

This section of the Writing R Extensions manual describes most of the built-in Rd macros. Tables 1, 2, and 3 of this technical paper provide a complete list.

This section of WRE addresses encoding specifically.
Use of non-ASCII characters in Rd files is supported, provided that you declare an appropriate encoding, either in the files themselves (via \enc and \encoding) or in DESCRIPTION (via the Encoding field). However, restriction to ASCII characters is encouraged:

Wherever possible, avoid non-ASCII chars in Rd files, and even symbols such as ‘<’, ‘>’, ‘$’, ‘^’, ‘&’, ‘|’, ‘@’, ‘~’, and ‘*’ outside ‘verbatim’ environments (since they may disappear in fonts designed to render text).

The recommended way to obtain non-ASCII characters in rendered help  without including non-ASCII characters in your Rd files is to use conditional text. \ifelse allows you to provide raw LaTeX for PDF help pages, raw HTML for HTML help pages, and verbatim text for plain text help pages:

\ifelse{latex}{\out{\'{e}}}{\ifelse{html}{\out{&eacute;}}{e}}

That is quite verbose, so I would suggest defining your own macro(s) in man/macros/macros.Rd. You can do this with \newcommand and \renewcommand:

\newcommand{\eacute}{\ifelse{latex}{\out{\'{e}}}{\ifelse{html}{\out{&eacute;}}{e}}}

Then you can use \eacute{} freely in all of your Rd files. To check that text is rendered the way you want in all formats, install the package and run help(topic, help_type=), with help_type equal to "text", "html", or "pdf".


问:
Reliably ingesting a CSV file where a value can be a JSON string?
I am parsing CSV files where values include strings that represent JSON objects, among boolean, normal strings, and other values. The CSV file has a header. As I iterate over the non-header rows of the CSV file, I use Javascript's split method with the following regex to grab the value at each 'cell' of the CSV row:

```<code>let currentLine = lines[i].split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/)
</code>```

Unfortunately, it doesn't always delimit lines containing legal JSON strings. Some strings are captured, but strings like this one gets truncated in odd places, wrecking the parsing of the entire CSV file:

```<code>'{"an object" : [{"sub-object 1": {
    "description": "sub-object is for blah blah",
    "nestedArray": ["param1","param2","param3"]}},
  {"sub-object 2": {
    "description": "sub-object is for blah blah",
    "nestedArray": ["param1","param2","param3"]}},
  {"sub-object 3": {
    "description": "sub-object is for blah blah",
    "nestedArray": ["param1","param2","param3"]}}
  ]
}'
</code>```

As far as I can tell, the above is legal JSON (curiously, https://jsonformatter.curiousconcept.com/# validates the above if it's pasted without single quotes surrounding it -- not sure why that would be). Any thoughts on how to properly parse this? I thought this would be a fairly trivial task but apparently JSON is not frequently embedded as a value in CSV files. Not sure if there's a standard or best practices way of handling this.

EDIT: To clarify, if anyone has a regex that would capture the above json string in a CSV file, I'd be greatly appreciated if you could share it with me

答:
This can be used as a template for general purpose CSV parsing.

```<code>(?:(?:^|,|\r?\n)[^\S\r\n]*)(?:("[^"\\]*(?:\\[\S\s][^"\\]*)*"|'[^'\\]*(?:\\[\S\s][^'\\]*)*'|[^,\r\n]*)(?:[^\S\r\n]*(?=$|,|\r?\n)))
</code>```

test: https://regex101.com/r/AnQqyv/1

Where the field is trimmed in capture group 1

```<code> (?:                           # Delimiter comma or newline
    (?: ^ | , | \r? \n )
    [^\S\r\n]*                    # leading optional whitespaces
 )
 (?:
    (                             # (1 start), field
       "                             # " Quoted
       [^"\\]*
       (?: \\ [\S\s] [^"\\]* )*
       "
     |                              # or
       '                             # ' Quoted
       [^'\\]*
       (?: \\ [\S\s] [^'\\]* )*
       '
     |                              # or
       [^,\r\n]*                     # Non-quoted
    )                             # (1 end)
    (?:
       [^\S\r\n]*                    # trailing optional whitespaces
       (?= $ | , | \r? \n )          # Delimiter ahead, comma or newline
    )
 )
</code>```

Body:
I am parsing CSV files where values include strings that represent JSON objects, among boolean, normal strings, and other values. The CSV file has a header. As I iterate over the non-header rows of the CSV file, I use Javascript's split method with the following regex to grab the value at each 'cell' of the CSV row:

let currentLine = lines[i].split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/)

Unfortunately, it doesn't always delimit lines containing legal JSON strings. Some strings are captured, but strings like this one gets truncated in odd places, wrecking the parsing of the entire CSV file:

'{"an object" : [{"sub-object 1": {
    "description": "sub-object is for blah blah",
    "nestedArray": ["param1","param2","param3"]}},
  {"sub-object 2": {
    "description": "sub-object is for blah blah",
    "nestedArray": ["param1","param2","param3"]}},
  {"sub-object 3": {
    "description": "sub-object is for blah blah",
    "nestedArray": ["param1","param2","param3"]}}
  ]
}'

As far as I can tell, the above is legal JSON (curiously, https://jsonformatter.curiousconcept.com/# validates the above if it's pasted without single quotes surrounding it -- not sure why that would be). Any thoughts on how to properly parse this? I thought this would be a fairly trivial task but apparently JSON is not frequently embedded as a value in CSV files. Not sure if there's a standard or best practices way of handling this.

EDIT: To clarify, if anyone has a regex that would capture the above json string in a CSV file, I'd be greatly appreciated if you could share it with me

Body:
This can be used as a template for general purpose CSV parsing.

(?:(?:^|,|\r?\n)[^\S\r\n]*)(?:("[^"\\]*(?:\\[\S\s][^"\\]*)*"|'[^'\\]*(?:\\[\S\s][^'\\]*)*'|[^,\r\n]*)(?:[^\S\r\n]*(?=$|,|\r?\n)))

test: https://regex101.com/r/AnQqyv/1

Where the field is trimmed in capture group 1

 (?:                           # Delimiter comma or newline
    (?: ^ | , | \r? \n )
    [^\S\r\n]*                    # leading optional whitespaces
 )
 (?:
    (                             # (1 start), field
       "                             # " Quoted
       [^"\\]*
       (?: \\ [\S\s] [^"\\]* )*
       "
     |                              # or
       '                             # ' Quoted
       [^'\\]*
       (?: \\ [\S\s] [^'\\]* )*
       '
     |                              # or
       [^,\r\n]*                     # Non-quoted
    )                             # (1 end)
    (?:
       [^\S\r\n]*                    # trailing optional whitespaces
       (?= $ | , | \r? \n )          # Delimiter ahead, comma or newline
    )
 )


问:
django_debug_toolbar and Docker
So I got docker and Django to work locally, first by building an image from a Dockerfile, then using Fig to get postgres image, link it to the base image, and run the localserver. Everything works just fine, except for django_debug_toolbar. For some reason it just won't show up. Have the dockerhost ip as well in the internal_ips.
Can anyone help me out with it? Docker is running on mac via boot2docker.

Thanks!

My settings:

init.py

```<code>import os

if 'DEBUG' not in os.environ or not os.environ['DEBUG']:
    from .local import *
else:
    pass
</code>```

base.py

```<code>""" common and global settings """

from sys import path
from os import environ
from os.path import abspath, basename, dirname, join, normpath
from django.core.exceptions import ImproperlyConfigured
import dj_database_url

def get_env_variable(var_name):
    try:
        return environ[var_name]
    except KeyError:
        error_msg = "Set the environment variable" % var_name
        raise ImproperlyConfigured(error_msg)

# Paths
DJANGO_ROOT = dirname(dirname(abspath(__file__)))
SITE_ROOT = dirname(DJANGO_ROOT)
SITE_NAME = basename(DJANGO_ROOT)
# End Paths

# URLs
MEDIA_ROOT = normpath(join(SITE_ROOT, 'media'))
MEDIA_URL = "/media/"

STATIC_ROOT = normpath(join(SITE_ROOT, 'assets'))
STATIC_URL = "/static/"

STATICFILES_DIRS = (
    normpath(join(SITE_ROOT, 'static')),
)

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

ROOT_URLCONF = '%s.urls' % SITE_NAME

path.insert(0, join(DJANGO_ROOT, 'apps'))  # add apps folder to system path
# End URLs

# Database
# example:  postgres://joris:luna@localhost/bitbybit
DATABASES = {'default': dj_database_url.config(
   default='postgres://postgres@db:5432/postgres')}
# End Database

# Templates
TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.debug',
    'django.core.context_processors.i18n',
    'django.core.context_processors.media',
    'django.core.context_processors.static',
    'django.core.context_processors.tz',
    'django.contrib.messages.context_processors.messages',
    'django.core.context_processors.request',
)

TEMPLATE_LOADERS = (
   'django.template.loaders.filesystem.Loader',
   'django.template.loaders.app_directories.Loader',
)

TEMPLATE_DIRS = (
    normpath(join(SITE_ROOT, 'templates')),
)
# End Templates

# SECURITY WARNING: keep the secret key used in production secret!
# make it unique and store it as an environment variable
SECRET_KEY = r"d%g7_h6cz=xbhs*5-i+e$c7mns*s)^_+#^8n@^-2dno@uie-z9"

# Application
DJANGO_APPS = (
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',
)

LOCAL_APPS = (
   'home',
)

INSTALLED_APPS = DJANGO_APPS + LOCAL_APPS

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'debug_toolbar.middleware.DebugToolbarMiddleware',
)

WSGI_APPLICATION = '%s.wsgi.application' % SITE_NAME
# End Application

# Internationalization
LANGAUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True
# End Internationalization
</code>```

Local.py

```<code>from .base import *

# Debug config
DEBUG = True
TEMPLATE_DEBUG = DEBUG
# End Debug config

# Hosts
ALLOWED_HOSTS = ['127.0.0.1', 'localhost']
# End Hosts

# Django Debug Toolbar config
INSTALLED_APPS += (
    'debug_toolbar', )

INTERNAL_IPS = ('127.0.0.1', 'localhost')
# End Django Debug Toolbar config
</code>```

答:
The simplest solution is to use gethostbyname_ex instead of gethostbyname

```<code>INTERNAL_IPS = ['127.0.0.1', '10.0.2.2' ]
if DEBUG:
   import socket
   hostname, _, ips =socket.gethostbyname_ex(socket.gethostname())
   INTERNAL_IPS += [ip[:-1] + '1' for ip in ips]
</code>```

Title: django_debug_toolbar and Docker

Body:
So I got docker and Django to work locally, first by building an image from a Dockerfile, then using Fig to get postgres image, link it to the base image, and run the localserver. Everything works just fine, except for django_debug_toolbar. For some reason it just won't show up. Have the dockerhost ip as well in the internal_ips.
Can anyone help me out with it? Docker is running on mac via boot2docker.

Thanks!

My settings:

init.py

import os

if 'DEBUG' not in os.environ or not os.environ['DEBUG']:
    from .local import *
else:
    pass

base.py

""" common and global settings """

from sys import path
from os import environ
from os.path import abspath, basename, dirname, join, normpath
from django.core.exceptions import ImproperlyConfigured
import dj_database_url

def get_env_variable(var_name):
    try:
        return environ[var_name]
    except KeyError:
        error_msg = "Set the environment variable" % var_name
        raise ImproperlyConfigured(error_msg)

# Paths
DJANGO_ROOT = dirname(dirname(abspath(__file__)))
SITE_ROOT = dirname(DJANGO_ROOT)
SITE_NAME = basename(DJANGO_ROOT)
# End Paths

# URLs
MEDIA_ROOT = normpath(join(SITE_ROOT, 'media'))
MEDIA_URL = "/media/"

STATIC_ROOT = normpath(join(SITE_ROOT, 'assets'))
STATIC_URL = "/static/"

STATICFILES_DIRS = (
    normpath(join(SITE_ROOT, 'static')),
)

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

ROOT_URLCONF = '%s.urls' % SITE_NAME

path.insert(0, join(DJANGO_ROOT, 'apps'))  # add apps folder to system path
# End URLs

# Database
# example:  postgres://joris:luna@localhost/bitbybit
DATABASES = {'default': dj_database_url.config(
   default='postgres://postgres@db:5432/postgres')}
# End Database

# Templates
TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.debug',
    'django.core.context_processors.i18n',
    'django.core.context_processors.media',
    'django.core.context_processors.static',
    'django.core.context_processors.tz',
    'django.contrib.messages.context_processors.messages',
    'django.core.context_processors.request',
)

TEMPLATE_LOADERS = (
   'django.template.loaders.filesystem.Loader',
   'django.template.loaders.app_directories.Loader',
)

TEMPLATE_DIRS = (
    normpath(join(SITE_ROOT, 'templates')),
)
# End Templates

# SECURITY WARNING: keep the secret key used in production secret!
# make it unique and store it as an environment variable
SECRET_KEY = r"d%g7_h6cz=xbhs*5-i+e$c7mns*s)^_+#^8n@^-2dno@uie-z9"

# Application
DJANGO_APPS = (
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',
)

LOCAL_APPS = (
   'home',
)

INSTALLED_APPS = DJANGO_APPS + LOCAL_APPS

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'debug_toolbar.middleware.DebugToolbarMiddleware',
)

WSGI_APPLICATION = '%s.wsgi.application' % SITE_NAME
# End Application

# Internationalization
LANGAUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True
# End Internationalization

Local.py

from .base import *

# Debug config
DEBUG = True
TEMPLATE_DEBUG = DEBUG
# End Debug config

# Hosts
ALLOWED_HOSTS = ['127.0.0.1', 'localhost']
# End Hosts

# Django Debug Toolbar config
INSTALLED_APPS += (
    'debug_toolbar', )

INTERNAL_IPS = ('127.0.0.1', 'localhost')
# End Django Debug Toolbar config

Body:
The simplest solution is to use gethostbyname_ex instead of gethostbyname

INTERNAL_IPS = ['127.0.0.1', '10.0.2.2' ]
if DEBUG:
   import socket
   hostname, _, ips =socket.gethostbyname_ex(socket.gethostname())
   INTERNAL_IPS += [ip[:-1] + '1' for ip in ips]


问:
how i write a code for delete from cursor in gtk entry
how i write a code for delete from cursor in gtk entry

i write a code When I enter a text I delete it from button .

i try to delete only one character from entry cursor

i use g_signal_connect(): delete-from-cursor

but in callback (function) I do not know what to do

i use this code from source https://docs.gtk.org/gtk3/signal.Entry.delete-from-cursor.html

the function void clicked_callback(GtkEntry* entry,GtkDeleteType type,gint count,gpointer user_data)
{

the code of application :

```<code>#include <gdk/gdk.h>
#include <gtk/gtk.h>
#include<stdio.h>
void clicked_callback(GtkEntry* entry,GtkDeleteType type,gint count,gpointer user_data)
{
    g_print("pressed");
}
int main(int argc, char **argv)
{
    gtk_init(&argc,&argv);
    GtkWidget *window;
    GtkWidget *entry;
    GtkWidget *grid;
    GtkWidget *button;
    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_default_size(GTK_WINDOW(window),200,200);
    grid = gtk_grid_new();
    gtk_container_add(GTK_CONTAINER(window),grid);
    entry = gtk_entry_new();
    gtk_widget_set_name(entry,"newname");
    gtk_container_add(GTK_CONTAINER(window),entry);
    gtk_grid_attach(GTK_GRID(grid), entry, 0, 0, 5, 1);
    button = gtk_button_new_with_label("I");
    gtk_grid_attach(GTK_GRID(grid),button, 0, 1, 1, 1);
    g_signal_connect_swapped(button, "delete_from_cursor", G_CALLBACK(clicked_callback), entry);
    gtk_widget_show_all(window);
    gtk_main();
    return 0;
}
</code>```

答:
I found the answer. The code here will be in Python, but I'll explain the principles, so hopefully it won't be to hard to translate to C.

What you need to do first is connect a function to the button's clicked signal. In Python, it looks like this:

button = Gtk.Button.new_with_label("I")
button.connect("clicked", button_clicked_function)
```
<p>In that function, you need to call the entry's <code>delete_from_cursor()</code> method, with <code>GtkDeleteType</code> of <code>CHARS</code> for the <code>type</code> argument, and a <code>-1</code> for the <code>count</code> argument. This <code>-1</code> tells it to delete 1 letter to the <em>left</em> of the cursor, instead of the right. Here is what this looks like in Python:</p>
<pre class="lang-py prettyprint-override"><code>def button_clicked_function(button):
    entry.do_delete_from_cursor(entry, Gtk.DeleteType.CHARS, -1)
</code>```

Body:
how i write a code for delete from cursor in gtk entry

i write a code When I enter a text I delete it from button .

i try to delete only one character from entry cursor

i use g_signal_connect(): delete-from-cursor

but in callback (function) I do not know what to do

i use this code from source https://docs.gtk.org/gtk3/signal.Entry.delete-from-cursor.html

the function void clicked_callback(GtkEntry* entry,GtkDeleteType type,gint count,gpointer user_data)
{

the code of application :

#include <gdk/gdk.h>
#include <gtk/gtk.h>
#include<stdio.h>
void clicked_callback(GtkEntry* entry,GtkDeleteType type,gint count,gpointer user_data)
{
    g_print("pressed");
}
int main(int argc, char **argv)
{
    gtk_init(&argc,&argv);
    GtkWidget *window;
    GtkWidget *entry;
    GtkWidget *grid;
    GtkWidget *button;
    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_default_size(GTK_WINDOW(window),200,200);
    grid = gtk_grid_new();
    gtk_container_add(GTK_CONTAINER(window),grid);
    entry = gtk_entry_new();
    gtk_widget_set_name(entry,"newname");
    gtk_container_add(GTK_CONTAINER(window),entry);
    gtk_grid_attach(GTK_GRID(grid), entry, 0, 0, 5, 1);
    button = gtk_button_new_with_label("I");
    gtk_grid_attach(GTK_GRID(grid),button, 0, 1, 1, 1);
    g_signal_connect_swapped(button, "delete_from_cursor", G_CALLBACK(clicked_callback), entry);
    gtk_widget_show_all(window);
    gtk_main();
    return 0;
}

Body:
I found the answer. The code here will be in Python, but I'll explain the principles, so hopefully it won't be to hard to translate to C.

What you need to do first is connect a function to the button's clicked signal. In Python, it looks like this:

button = Gtk.Button.new_with_label("I")
button.connect("clicked", button_clicked_function)

In that function, you need to call the entry's delete_from_cursor() method, with GtkDeleteType of CHARS for the type argument, and a -1 for the count argument. This -1 tells it to delete 1 letter to the left of the cursor, instead of the right. Here is what this looks like in Python:

def button_clicked_function(button):
    entry.do_delete_from_cursor(entry, Gtk.DeleteType.CHARS, -1)


问:
Why is scikit-learn SVM classifier cross validation so slow?
I am trying to compare multiple classifiers on a dataset that I have. To get accurate accuracy scores for the classifiers I am now performing 10 fold cross validation for each classifier. This goes well for all of them except SVM (both linear and rbf kernels). The data is loaded like this:

```<code>dataset = pd.read_csv("data/distance_annotated_indels.txt", delimiter="\t", header=None)

X = dataset.iloc[:, [5,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26]].values
y = dataset.iloc[:, 4].values

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)

from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
</code>```

Cross validation for for example a Random Forest works fine:

```<code>start = time.time()
classifier = RandomForestClassifier(n_estimators = 100, criterion = 'entropy')
classifier.fit(X_train, y_train)
y_pred = classifier.predict(X_test)
cv = ShuffleSplit(n_splits=10, test_size=0.2)
scores = cross_val_score(classifier, X, y, cv=10)
print(classification_report(y_test, y_pred))
print("Random Forest accuracy after 10 fold CV: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2) + ", " + str(round(time.time() - start, 3)) + "s")
</code>```

Output:

```<code>             precision    recall  f1-score   support

          0       0.97      0.95      0.96      3427
          1       0.95      0.97      0.96      3417

avg / total       0.96      0.96      0.96      6844

Random Forest accuracy after 10 fold CV: 0.92 (+/- 0.06), 90.842s
</code>```

However for SVM this process takes ages (waited for 2 hours, still nothing). The sklearn website does not make me any wiser. Is there something I should be doing different for SVM classifiers? The SVM code is as follows:

```<code>start = time.time()
classifier = SVC(kernel = 'linear')
classifier.fit(X_train, y_train)
y_pred = classifier.predict(X_test)
scores = cross_val_score(classifier, X, y, cv=10)
print(classification_report(y_test, y_pred))
print("Linear SVM accuracy after 10 fold CV: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2) + ", " + str(round(time.time() - start, 3)) + "s")
</code>```

答:
alternatively you can try using optimized SVM implementation - for example with scikit-learn-intelex - https://github.com/intel/scikit-learn-intelex

First install package

pip install scikit-learn-intelex
```
<p>And then add in your python script</p>
<pre class="lang-py prettyprint-override"><code>from sklearnex import patch_sklearn
patch_sklearn()
</code>```

Body:
I am trying to compare multiple classifiers on a dataset that I have. To get accurate accuracy scores for the classifiers I am now performing 10 fold cross validation for each classifier. This goes well for all of them except SVM (both linear and rbf kernels). The data is loaded like this:

dataset = pd.read_csv("data/distance_annotated_indels.txt", delimiter="\t", header=None)

X = dataset.iloc[:, [5,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26]].values
y = dataset.iloc[:, 4].values

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)

from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)

Cross validation for for example a Random Forest works fine:

start = time.time()
classifier = RandomForestClassifier(n_estimators = 100, criterion = 'entropy')
classifier.fit(X_train, y_train)
y_pred = classifier.predict(X_test)
cv = ShuffleSplit(n_splits=10, test_size=0.2)
scores = cross_val_score(classifier, X, y, cv=10)
print(classification_report(y_test, y_pred))
print("Random Forest accuracy after 10 fold CV: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2) + ", " + str(round(time.time() - start, 3)) + "s")

Output:

             precision    recall  f1-score   support

          0       0.97      0.95      0.96      3427
          1       0.95      0.97      0.96      3417

avg / total       0.96      0.96      0.96      6844

Random Forest accuracy after 10 fold CV: 0.92 (+/- 0.06), 90.842s

However for SVM this process takes ages (waited for 2 hours, still nothing). The sklearn website does not make me any wiser. Is there something I should be doing different for SVM classifiers? The SVM code is as follows:

start = time.time()
classifier = SVC(kernel = 'linear')
classifier.fit(X_train, y_train)
y_pred = classifier.predict(X_test)
scores = cross_val_score(classifier, X, y, cv=10)
print(classification_report(y_test, y_pred))
print("Linear SVM accuracy after 10 fold CV: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2) + ", " + str(round(time.time() - start, 3)) + "s")

Body:
alternatively you can try using optimized SVM implementation - for example with scikit-learn-intelex - https://github.com/intel/scikit-learn-intelex

First install package

pip install scikit-learn-intelex

And then add in your python script

from sklearnex import patch_sklearn
patch_sklearn()


问:
Add dynamic icon beside  tag
I am trying with this example.

I am trying to add down arrow beside 'Show more' and up arrow beside 'Show less' (please refer the image below).

I was trying with the following code example but still no luck.

```<code>$('#nav li').each(function(i) {
$(this).append('<i class="fa' + ' ' + iconsArray[i] + '"></i>')})
</code>```

How can I add the icon beside  tag in the given example?

答:
I did something like this. (wanted to post it but website maintenance just started before of it..)

<!DOCTYPE html>

    <title>jQuery Read More/Less Toggle Example</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" integrity="sha512-Fo3rlrZj/k7ujTnHg4CGR2D7kSs0v4LLanw2qksYuRlEzO+tcaEPQogQ0KaoGN26/zrn20ImR1DfuLWnOo7aBA==" crossorigin="anonymous" referrerpolicy="no-referrer" />

      Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

      Morbi placerat imperdiet risus quis blandit. Ut lobortis elit luctus, feugiat erat vitae, interdum diam. Nam sit amet arcu vitae justo lacinia ultricies nec eget tellus. Curabitur id sapien massa. In hac habitasse platea dictumst. Integer tristique leo consectetur libero pretium pretium. Nunc sed mauris magna. Praesent varius purus id turpis iaculis iaculis. Nulla convallis magna nunc, id rhoncus massa ornare in. Donec et feugiat sem, ac rhoncus mauris. Quisque eget tempor massa.

```

Title: Add dynamic icon beside <a> tag

Body:
I am trying with this example.

I am trying to add down arrow beside 'Show more' and up arrow beside 'Show less' (please refer the image below).

I was trying with the following code example but still no luck.

$('#nav li').each(function(i) {
$(this).append('')})

How can I add the icon beside  tag in the given example?

Body:
I did something like this. (wanted to post it but website maintenance just started before of it..)

<!DOCTYPE html>
<html>
  <head>
    <title>jQuery Read More/Less Toggle Example</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" integrity="sha512-Fo3rlrZj/k7ujTnHg4CGR2D7kSs0v4LLanw2qksYuRlEzO+tcaEPQogQ0KaoGN26/zrn20ImR1DfuLWnOo7aBA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <style type="text/css" media="screen">
      .morecontent span {
          display: none;
      }
      .morelink {
        display: block;
        padding: 15px;
        border: 2px solid #000;
        color: #000;
        text-decoration: none;
        max-width: 120px;
        text-align: center;
      }
      .morelink span {
        display: inline-block;
        text-decoration:underline;
      }
      .morelink i {
        display: inline-block;
      }
    </style>
  </head>
  <body>
    <span class="more">
      Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </span>
    <br><br>
    <div class="more">
      Morbi placerat imperdiet risus quis blandit. Ut lobortis elit luctus, feugiat erat vitae, interdum diam. Nam sit amet arcu vitae justo lacinia ultricies nec eget tellus. Curabitur id sapien massa. In hac <a href="#">habitasse</a> platea dictumst. Integer tristique leo consectetur libero pretium pretium. Nunc sed mauris magna. Praesent varius purus id turpis iaculis iaculis. Nulla <em>convallis magna nunc</em>, id rhoncus massa ornare in. Donec et feugiat sem, ac rhoncus mauris. Quisque eget tempor massa.
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
      $(document).ready(function() {
          // Configure/customize these variables.
          var showChar = 100;  // How many characters are shown by default
          var ellipsestext = "...";
          var moretext = "<span>Show more</span>&nbsp;&nbsp;<i class='fas fa-angle-down'></i>";
          var lesstext = "<span>Show less</span>&nbsp;&nbsp;<i class='fas fa-angle-up'></i>";

          $('.more').each(function() {
              var content = $(this).html();

              if(content.length > showChar) {

                  var c = content.substr(0, showChar);
                  var h = content.substr(showChar, content.length - showChar);

                  var html = c + '<span class="moreellipses">' + ellipsestext+ '&nbsp;</span><span class="morecontent"><span>' + h + '</span>&nbsp;&nbsp;<a href="" class="morelink">' + moretext + '</a></span>';

                  $(this).html(html);
              }

          });

          $(".morelink").click(function(){
              let lessMoreText = $(this).hasClass("less") ? moretext : lesstext;
              $(this).toggleClass("less").html(lessMoreText);

              $(this).parent().prev().toggle();
              $(this).prev().toggle();
              return false;
          });
      });
    </script>
  </body>
</html>


问:
Make Nginx return custom error page when backend is down
I have Nginx working as reverse proxy and Django application behind it. Django app is connected to Nginx through UWSGI. Django app is deployed using Docker and gets down for a second or so during deployment. I would like to instruct Nginx to return custom 503 error page during that period.

Below is my Nginx config:

```<code>upstream server_django {
    server 0.0.0.0:8000;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name server.com;

    location / {
        # required to serve static assets
        alias    /data/server.com/website_root/;
        try_files $uri @django;
    }

    location @django {
        uwsgi_pass  server_django;
        include     /etc/nginx/uwsgi_params;
    }
}
</code>```

I have tried adding following config inside "server" block:

```<code>uwsgi_intercept_errors on;
error_page 502 503 504 =503 @django_is_down;
location @django_is_down {
    root /error_pages/server.com/;
    add_header Retry-After 10 always;
    index 503.html;
}
</code>```

but it didn't help since Nginx stared serving default 404 page when backend is down.

How do I detect when Django is down in Nginx and serve custom error page when that happens?

答:
When you are using named location as an error handler, it uses an original request URI (whatever it is), so assuming you've got a request like http://your.domain/some/route/ it will use /some/route/ URI and would try to find an 503.html index file under the /error_pages/server.com//some/route directory. For /some/route request (without a trailing slash) it would try to find the /error_pages/server.com//some/route file and won't using whatever you specify as the index file at all. That means the only two requests which will be ended with the 503.html file being served are http://your.domain/ and http://your.domain/503.html, everything else will give you an HTTP 404 error. And if you don't get your custom 503.html even for those two, maybe the /error_pages isn't a top level directory and you mean something like /var/www/error_pages/server.com instead?

Back to the question. If you want to use a named location as an error handler, you should rewrite any original request URI to a new value:

location @django {
    error_page 502 503 504 =503 @django_is_down;
    uwsgi_pass  server_django;
    include     /etc/nginx/uwsgi_params;
}

location @django_is_down {
    root /error_pages/server.com;
    add_header Retry-After 10 always;
    rewrite ^ /503.html break;
}
```
<p>Alternatively you can change your URI using <code>error_page</code> directive itself and an internal location:</p>
<pre class="lang-none prettyprint-override"><code>location @django {
    error_page 502 503 504 =503 /503.html;
    uwsgi_pass  server_django;
    include     /etc/nginx/uwsgi_params;
}

location = /503.html {
    internal;
    root /error_pages/server.com;
    add_header Retry-After 10 always;
}
</code>```

If you want to reserve /503.html URI for your django app, you can use whatever else you want, e.g.

location @django {
    error_page 502 503 504 =503 /django_is_down/503.html;
    uwsgi_pass  server_django;
    include     /etc/nginx/uwsgi_params;
}

location = /django_is_down/503.html {
    internal;
    root /error_pages/server.com;
    add_header Retry-After 10 always;
}
```

(but for that case you should place your 503.html file under the /error_pages/server.com/django_is_down directory).

Body:
I have Nginx working as reverse proxy and Django application behind it. Django app is connected to Nginx through UWSGI. Django app is deployed using Docker and gets down for a second or so during deployment. I would like to instruct Nginx to return custom 503 error page during that period.

Below is my Nginx config:

upstream server_django {
    server 0.0.0.0:8000;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name server.com;

    location / {
        # required to serve static assets
        alias    /data/server.com/website_root/;
        try_files $uri @django;
    }

    location @django {
        uwsgi_pass  server_django;
        include     /etc/nginx/uwsgi_params;
    }
}

I have tried adding following config inside "server" block:

uwsgi_intercept_errors on;
error_page 502 503 504 =503 @django_is_down;
location @django_is_down {
    root /error_pages/server.com/;
    add_header Retry-After 10 always;
    index 503.html;
}

but it didn't help since Nginx stared serving default 404 page when backend is down.

How do I detect when Django is down in Nginx and serve custom error page when that happens?

Body:
When you are using named location as an error handler, it uses an original request URI (whatever it is), so assuming you've got a request like http://your.domain/some/route/ it will use /some/route/ URI and would try to find an 503.html index file under the /error_pages/server.com//some/route directory. For /some/route request (without a trailing slash) it would try to find the /error_pages/server.com//some/route file and won't using whatever you specify as the index file at all. That means the only two requests which will be ended with the 503.html file being served are http://your.domain/ and http://your.domain/503.html, everything else will give you an HTTP 404 error. And if you don't get your custom 503.html even for those two, maybe the /error_pages isn't a top level directory and you mean something like /var/www/error_pages/server.com instead?

Back to the question. If you want to use a named location as an error handler, you should rewrite any original request URI to a new value:

location @django {
    error_page 502 503 504 =503 @django_is_down;
    uwsgi_pass  server_django;
    include     /etc/nginx/uwsgi_params;
}

location @django_is_down {
    root /error_pages/server.com;
    add_header Retry-After 10 always;
    rewrite ^ /503.html break;
}

Alternatively you can change your URI using error_page directive itself and an internal location:

location @django {
    error_page 502 503 504 =503 /503.html;
    uwsgi_pass  server_django;
    include     /etc/nginx/uwsgi_params;
}

location = /503.html {
    internal;
    root /error_pages/server.com;
    add_header Retry-After 10 always;
}

If you want to reserve /503.html URI for your django app, you can use whatever else you want, e.g.

location @django {
    error_page 502 503 504 =503 /django_is_down/503.html;
    uwsgi_pass  server_django;
    include     /etc/nginx/uwsgi_params;
}

location = /django_is_down/503.html {
    internal;
    root /error_pages/server.com;
    add_header Retry-After 10 always;
}

(but for that case you should place your 503.html file under the /error_pages/server.com/django_is_down directory).


问:
Why does click event handler fire immediately upon page load?
I playing around with a function that I want to bind to all the links. At the present the function fires when the page loads, instead of when I click on the link.

Here's my code. (I can post the function showDiv(), if you need to see it.) Can you tell if I'm doing something wrong or stupid here?

```<code>$(document).ready(function(){

    $('a.test').bind("click", showDiv());

});
</code>```

Thanks!

答:
Looks like you're calling the function showDiv directly there (and binding the return result of showDiv() to the click handler instead of binding it directly.

You want something like

```<code>$(document).ready(function() { $('a.test').bind("click", showDiv); });
</code>```

Body:
I playing around with a function that I want to bind to all the links. At the present the function fires when the page loads, instead of when I click on the link.

Here's my code. (I can post the function showDiv(), if you need to see it.) Can you tell if I'm doing something wrong or stupid here?

$(document).ready(function(){

    $('a.test').bind("click", showDiv());

});

Thanks!

Body:
Looks like you're calling the function showDiv directly there (and binding the return result of showDiv() to the click handler instead of binding it directly.

You want something like

$(document).ready(function() { $('a.test').bind("click", showDiv); });


问:
Use sed to Replace Multiple Lines
I'm trying to use sed to replace multiple lines which are found via regex with one substitution.  For example, given the following simplified text file

```<code>first
second
third
fourth
fifth
sixth
seventh
eighth
</code>```

How would I go about using regex to find the second to fourth lines and replace the whole range with one instance of the word "found" so that the end result is

```<code>first
found
fifth
sixth
seventh
eighth
</code>```

I'm basically looking to combine the substitution syntax (sed 's/second/found/') with the range syntax (sed '/second/,/fourth/') into something like sed 's/second/,/fourth/found/' that actually works.

答:
awk suited this job better:

awk '/^second$/ {p=1} !p; /^fourth$/ {p=0; print "found"}' file

first
found
fifth
sixth
seventh
eighth
```
<hr />
<p>If you really want to use <code>sed</code> then use:</p>
<pre class="lang-sh prettyprint-override"><code>sed '/^second$/,/^fourth$/{/^second$/i\
found
d
}' file
</code>```

Title: Use sed to Replace Multiple Lines

Body:
I'm trying to use sed to replace multiple lines which are found via regex with one substitution.  For example, given the following simplified text file

first
second
third
fourth
fifth
sixth
seventh
eighth

How would I go about using regex to find the second to fourth lines and replace the whole range with one instance of the word "found" so that the end result is

first
found
fifth
sixth
seventh
eighth

I'm basically looking to combine the substitution syntax (sed 's/second/found/') with the range syntax (sed '/second/,/fourth/') into something like sed 's/second/,/fourth/found/' that actually works.

Body:
awk suited this job better:

awk '/^second$/ {p=1} !p; /^fourth$/ {p=0; print "found"}' file

first
found
fifth
sixth
seventh
eighth

If you really want to use sed then use:

sed '/^second$/,/^fourth$/{/^second$/i\
found
d
}' file


问:
Convert binary matrix to column-indexed lists by row in R
Given a binary matrix B, I can usually get a list of the column indexes of the 1s by row using Blist <- apply(B==1, 1, which). However, this doesn't work when, for example, rowSums(B)[1] == rowSums(B)[2].

Here's an example where it works:

```<code>> B <- matrix(c(1,1,0,0,1,0,0,0,1),3,3)
> B
     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    1    1    0
[3,]    0    0    1
> Blist <- apply(B==1, 1, which)
> Blist
[[1]]
[1] 1

[[2]]
[1] 1 2

[[3]]
[1] 3
</code>```

Here's an example when it doesn't work:

```<code>> B <- matrix(c(1,0,0,0,1,0,0,0,1),3,3)
> B
     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    1    0
[3,]    0    0    1
> Blist <- apply(B==1, 1, which)
> Blist
[1] 1 2 3
</code>```

In this case, the desired result is:

```<code>> Blist
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3
</code>```

How can I modify Blist <- apply(B==1, 1, which) so that the result is always organized as a list?

答:
There is simplify argument which is TRUE by default.  The default usage from ?apply`

apply(X, MARGIN, FUN, ..., simplify = TRUE)

simplify - a logical indicating whether results should be simplified if possible.

Also, it states

If the calls to FUN return vectors of different lengths, or if simplify is FALSE, apply returns a list of length prod(dim(X)[MARGIN]) with dim set to MARGIN if this has length greater than one.

```<code>apply(B==1, 1, which, simplify = FALSE)
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3
</code>```

Body:
Given a binary matrix B, I can usually get a list of the column indexes of the 1s by row using Blist <- apply(B==1, 1, which). However, this doesn't work when, for example, rowSums(B)[1] == rowSums(B)[2].

Here's an example where it works:

> B <- matrix(c(1,1,0,0,1,0,0,0,1),3,3)
> B
     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    1    1    0
[3,]    0    0    1
> Blist <- apply(B==1, 1, which)
> Blist
[[1]]
[1] 1

[[2]]
[1] 1 2

[[3]]
[1] 3

Here's an example when it doesn't work:

> B <- matrix(c(1,0,0,0,1,0,0,0,1),3,3)
> B
     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    1    0
[3,]    0    0    1
> Blist <- apply(B==1, 1, which)
> Blist
[1] 1 2 3

In this case, the desired result is:

> Blist
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

How can I modify Blist <- apply(B==1, 1, which) so that the result is always organized as a list?

Body:
There is simplify argument which is TRUE by default.  The default usage from ?apply`

apply(X, MARGIN, FUN, ..., simplify = TRUE)

simplify - a logical indicating whether results should be simplified if possible.

Also, it states

If the calls to FUN return vectors of different lengths, or if simplify is FALSE, apply returns a list of length prod(dim(X)[MARGIN]) with dim set to MARGIN if this has length greater than one.

apply(B==1, 1, which, simplify = FALSE)
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3


Title: Convert binary matrix to column-indexed lists by row in R

Body:
m = which(B == 1, arr.ind=TRUE)
split(m[,"col"], m[,"row"])
# $`1`
# [1] 1

# $`2`
# [1] 2

# $`3`
# [1] 3


问:
How can I validate a string to only allow alphanumeric characters in it?
How can I validate a string using Regular Expressions to only allow alphanumeric characters in it?

(I don't want to allow for any spaces either).

答:
12 years and 7 months later, if anyone comes across this article nowadays.

Compiled RegEx actually has the best performance in .NET 5 and .NET 6

Please look at the following link where I compare several different answers given on this question. Mainly comparing Compiled RegEx, For-Loops, and Linq Predicates: https://dotnetfiddle.net/WOPQRT

Notes:
As stated, this method is only faster in .NET 5 and .NET 6.

.NET Core 3.1 and below show RegEx being the slowest.

Regardless of the version of .NET, the For-Loop method is consistently faster than the Linq Predicate.


问:
MS Graph API - Get access without a user - Verifying MS response
When using MS-Graph oauth flow "Get Access without a user", Microsoft responds with a GET request of the following structure (from the example in the linked page):

```<code>GET https://localhost/myapp/permissions
?tenant=a8990e1f-ff32-408a-9f8e-78d3b9139b95
&state=12345
&admin_consent=True
</code>```

Is there anyway to verify that the response came from Microsoft?

In our application we're using the state to link an internal tenant-id with the Microsoft tenant-id. If the above response can be forged, an adversary may link his own tenant-id to the victim's Microsoft tenant-id.

答: You don't really need to check for this step (3) in the doc, because if the admin didn't consent, you would not be able to get an actual token for your app in step 4. However, you might be able to get the Referrer, if it's important to know which page the user came from to get back to your 'https://localhost' page.

Body:
When using MS-Graph oauth flow "Get Access without a user", Microsoft responds with a GET request of the following structure (from the example in the linked page):

GET https://localhost/myapp/permissions
?tenant=a8990e1f-ff32-408a-9f8e-78d3b9139b95
&state=12345
&admin_consent=True

Is there anyway to verify that the response came from Microsoft?

In our application we're using the state to link an internal tenant-id with the Microsoft tenant-id. If the above response can be forged, an adversary may link his own tenant-id to the victim's Microsoft tenant-id.


问:
Compare two polars DataFrames for equality
How do I compare two polars DataFrames for value equality? It appears that == is only true if the two tables are the same object:

import polars as pl
pl.DataFrame({"x": [1,2,3]}) == pl.DataFrame({"x": [1,2,3]})  # False
```

答: In addition to the correct answer above, it is good to note that for unit testing there is polars.testing.assert_frame_equal, which provides better error reporting, has more configuration options and raises an assertion on False.</p>


问:
iPhone - Problem with NSDate to get time interval according to current time zone
I am using NSDate to get the NSTimeInterval according to current time zone.
But I'm getting information related to UTC.
I'm using methods like "dateWithTimeIntervalSinceNow" and "dateWithTimeIntervalSince1970"
How can I get time interval as per my time zone?</p>

答:
This has been answered in a fair bit of detail here.

How to convert time to the time zone of the iPhone device?

You might also want to check this out

Using TimeZones


问:
range() as method argument for loop iterator
this code generates a nice loop :

for i in range(self.ix):

```<code>__pyx_t_3 = __pyx_v_self->ix;
__pyx_t_4 = __pyx_t_3;
for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) {
  __pyx_v_i = __pyx_t_5;
</code>```

but i want to be able to pass this iterator as argument (so i can have different iterators/generators)

if i try this :

```<code>  cdef ixrange(self): return range(self.ix)
</code>```

already is too unwieldy and the loop is no longer a simple loop. :

```<code>static PyObject *__pyx_f_3lib_10sparse_ary_9SparseAry_ixrange(struct __pyx_obj_3lib_10sparse_ary_SparseAry *__pyx_v_self) {
  PyObject *__pyx_r = NULL;
  __Pyx_RefNannyDeclarations
  __Pyx_RefNannySetupContext("ixrange", 0);
  __Pyx_XDECREF(__pyx_r);
  __pyx_t_1 = __Pyx_PyInt_From_unsigned_int(__pyx_v_self->ix); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 139, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_1);
  __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_builtin_range, __pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 139, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_2);
  __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
  __pyx_r = __pyx_t_2;
  __pyx_t_2 = 0;
  goto __pyx_L0;

  /* function exit code */
  __pyx_L1_error:;
  __Pyx_XDECREF(__pyx_t_1);
  __Pyx_XDECREF(__pyx_t_2);
  __Pyx_AddTraceback("lib.sparse_ary.SparseAry.ixrange", __pyx_clineno, __pyx_lineno, __pyx_filename);
  __pyx_r = 0;
  __pyx_L0:;
  __Pyx_XGIVEREF(__pyx_r);
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}
</code>```

any way i can make it simple loop again ?

答:
I don't think it is possible.

The effect of for i in range(self.ix): is to generate a range object, and then call next on that range object until a StopIteration exception is raised. That's also the behaviour that Cython takes for general for loops.

There's actually a fairly long list of conditions that have to be met for Cython to transform that into an optimized loop:

range must be used directly - i.e. it = range(...); for i in it won't work because you might need the range object after the loop.

the types of the start and stop point must be integers.

the type of the loop variable must be an integer (Cython can infer this, but if you assign something of a different type to the loop variable then it won't work)

Cython must know that you haven't reassigned range

The sign of the stop variable must be known.

In your case I think you're hoping for Cython to look inside the cdef function and pick out the range. This is beyond what the current optimizer can do. But also, you can override cdef functions in a derived class (in C++ terms, they're "virtual"), so Cython could almost never safely make the optimization.

Cython is usually able to optimize best when you really restrict the types it's working with. The request that it should generate a fast C for loop but also be able to handle arbitrary iterators does not seem realistically achievable.

Body:
this code generates a nice loop :

for i in range(self.ix):

__pyx_t_3 = __pyx_v_self->ix;
__pyx_t_4 = __pyx_t_3;
for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) {
  __pyx_v_i = __pyx_t_5;

but i want to be able to pass this iterator as argument (so i can have different iterators/generators)

if i try this :

  cdef ixrange(self): return range(self.ix)

already is too unwieldy and the loop is no longer a simple loop. :

static PyObject *__pyx_f_3lib_10sparse_ary_9SparseAry_ixrange(struct __pyx_obj_3lib_10sparse_ary_SparseAry *__pyx_v_self) {
  PyObject *__pyx_r = NULL;
  __Pyx_RefNannyDeclarations
  __Pyx_RefNannySetupContext("ixrange", 0);
  __Pyx_XDECREF(__pyx_r);
  __pyx_t_1 = __Pyx_PyInt_From_unsigned_int(__pyx_v_self->ix); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 139, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_1);
  __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_builtin_range, __pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 139, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_2);
  __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
  __pyx_r = __pyx_t_2;
  __pyx_t_2 = 0;
  goto __pyx_L0;

  /* function exit code */
  __pyx_L1_error:;
  __Pyx_XDECREF(__pyx_t_1);
  __Pyx_XDECREF(__pyx_t_2);
  __Pyx_AddTraceback("lib.sparse_ary.SparseAry.ixrange", __pyx_clineno, __pyx_lineno, __pyx_filename);
  __pyx_r = 0;
  __pyx_L0:;
  __Pyx_XGIVEREF(__pyx_r);
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

any way i can make it simple loop again ?