问:
Isolating/indexing/ranging through a list object tuple set
So basically I have a tuple set kind of like this.

```<code>tuple_set = [('name1', 'score'), ('name2', 'score'), ('name3', 'score')]
</code>```

It basically is a specific list in a larger dictionary of names/scores. I need to isolate name1, name2 and name3 in something that I can iterate through like a list.

It also might work if I can range through it but I can't take the range of the list object/tupleset.

Also appending to a list like this won't work cause it will only put a list of name1s

```<code>a_list = []

for stuff in tuple_set:
    a_list.append(tuple_set[0][0])
</code>```

output: a_list = ["name1", "name1", "name1"]

Does someone know the solution?

答:
Your loop never uses the iteration variable, it just adds the same element over and over. Actually use the loop variable (ideally via unpacking to useful variable names) and things work:

```<code>for name, score in tuple_set:
    a_list.append(name)
</code>```

Or one-line it as a list comprehension:

```<code>a_list = [name for name, score in tuple_set]
</code>```

Body:
So basically I have a tuple set kind of like this.

tuple_set = [('name1', 'score'), ('name2', 'score'), ('name3', 'score')]

It basically is a specific list in a larger dictionary of names/scores. I need to isolate name1, name2 and name3 in something that I can iterate through like a list.

It also might work if I can range through it but I can't take the range of the list object/tupleset.

Also appending to a list like this won't work cause it will only put a list of name1s

a_list = []

for stuff in tuple_set:
    a_list.append(tuple_set[0][0])

output: a_list = ["name1", "name1", "name1"]

Does someone know the solution?

Body:
Your loop never uses the iteration variable, it just adds the same element over and over. Actually use the loop variable (ideally via unpacking to useful variable names) and things work:

for name, score in tuple_set:
    a_list.append(name)

Or one-line it as a list comprehension:

a_list = [name for name, score in tuple_set]


来源: stackexchange

问:
Setting an existing dictionary's values to all zeros
If I have this dict:

```<code>dict1 = {"Key1": [[1, 3, 4], [2, 5, 8]], "key2": [4, 5]}
</code>```

How can I set all the values to 0?

Output should be like this:

```<code>dict1 = {"Key1": [[0,0,0], [0,0,0]], "key2": [0,0]}
</code>```

答:
You can modify the dictionary "in-place" — i.e. without replacing it with a new one —  via a relatively simple recursive function:</p>

```<code>def zero_values(obj):
    if isinstance(obj, dict):
        for k, v in obj.items():
            obj[k] = zero_values(v)
        return obj
    elif isinstance(obj, list):
        for i, v in enumerate(obj):
            obj[i] = zero_values(v)
        return obj
    else:
        return 0

dict1 = { "Key1" :[ [1, 3, 4], [2 , 5 , 8] ], "key2" : [4, 5] }
zero_values(dict1)
print(dict1)  # -> {'Key1': [[0, 0, 0], [0, 0, 0]], 'key2': [0, 0]}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
If I have this dict:

dict1 = {"Key1": [[1, 3, 4], [2, 5, 8]], "key2": [4, 5]}

How can I set all the values to 0?

Output should be like this:

dict1 = {"Key1": [[0,0,0], [0,0,0]], "key2": [0,0]}

Body:
You can modify the dictionary "in-place" — i.e. without replacing it with a new one —  via a relatively simple recursive function:

def zero_values(obj):
    if isinstance(obj, dict):
        for k, v in obj.items():
            obj[k] = zero_values(v)
        return obj
    elif isinstance(obj, list):
        for i, v in enumerate(obj):
            obj[i] = zero_values(v)
        return obj
    else:
        return 0

dict1 = { "Key1" :[ [1, 3, 4], [2 , 5 , 8] ], "key2" : [4, 5] }
zero_values(dict1)
print(dict1)  # -> {'Key1': [[0, 0, 0], [0, 0, 0]], 'key2': [0, 0]}


问:
Nesting a TypeScript React component inside another
So I'm trying to nest a TypeScript React component within another, but it complains about types. It would seem it wants me to add all of my props into the parent interface?

Is there a way of doing this without having to have all my types listed in the child component interface, but then also having to add the types to the parent component interface?

Note: I am using Styled Components in the example below

```<code>interface IField {
  children: React.ReactNode
}

export function Field({ children, htmlFor, label, required, ...props }: IField) {
  return (
    <FormField {...props}>
      <Label htmlFor={htmlFor} label={label} required={required}/>
      {children}
    </FormField>
  )
}

interface ILabel {
  htmlFor: string
  label: string
  required?: boolean
}

export function Label({ htmlFor, label, required }: ILabel) {
  return (
    <FormLabel htmlFor={htmlFor}>
      {label}
      {required && (
        <Required />
      )}
    </FormLabel>
  )
}
</code>```

Error I get:

```<code>Type '{}' is missing the following properties from type 'ILabel': htmlFor, label
</code>```

Thanks for any help in advance!

答:
To avoid adding the properties from the child interface back to the parent component interface you can use extends (see TypeScript inheritance documentation).

After that, you can pass the props from the parent to the child component by using {...props} deconstructor on the child component.

And finally, if you are using TypeScript might as well use React.FunctionComponent typing to avoid having to manually type children.

You can check at this simplified working example:

  https://stackblitz.com/edit/react-stackoverflow-60228406

I tried to adapt your snippet below...

import React from 'react';

interface IField extends ILabel {
}

export const Field: React.FunctionComponent<IField> = (props) => {
  return (
    <FormField>

      {props.children}
    </FormField>
  )
};

interface ILabel {
  htmlFor: string
  label: string
  required?: boolean
}

export const Label: React.FunctionComponent<ILabel> = (props) => {
  return (
    <FormLabel htmlFor={props.htmlFor}>
      {props.label}
      {props.required && (<Required />)}
    </FormLabel>
  )
};
```

Body:
So I'm trying to nest a TypeScript React component within another, but it complains about types. It would seem it wants me to add all of my props into the parent interface?

Is there a way of doing this without having to have all my types listed in the child component interface, but then also having to add the types to the parent component interface?

Note: I am using Styled Components in the example below

interface IField {
  children: React.ReactNode
}

export function Field({ children, htmlFor, label, required, ...props }: IField) {
  return (
    <FormField {...props}>

      {children}
    </FormField>
  )
}

interface ILabel {
  htmlFor: string
  label: string
  required?: boolean
}

export function Label({ htmlFor, label, required }: ILabel) {
  return (
    <FormLabel htmlFor={htmlFor}>
      {label}
      {required && (
        <Required />
      )}
    </FormLabel>
  )
}

Error I get:

Type '{}' is missing the following properties from type 'ILabel': htmlFor, label

Thanks for any help in advance!

Body:
To avoid adding the properties from the child interface back to the parent component interface you can use extends (see TypeScript inheritance documentation).

After that, you can pass the props from the parent to the child component by using {...props} deconstructor on the child component.

And finally, if you are using TypeScript might as well use React.FunctionComponent typing to avoid having to manually type children.

You can check at this simplified working example:

  https://stackblitz.com/edit/react-stackoverflow-60228406

I tried to adapt your snippet below...

import React from 'react';

interface IField extends ILabel {
}

export const Field: React.FunctionComponent<IField> = (props) => {
  return (
    <FormField>
      <Label {...props} />
      {props.children}
    </FormField>
  )
};

interface ILabel {
  htmlFor: string
  label: string
  required?: boolean
}

export const Label: React.FunctionComponent<ILabel> = (props) => {
  return (
    <FormLabel htmlFor={props.htmlFor}>
      {props.label}
      {props.required && (<Required />)}
    </FormLabel>
  )
};


问:
Is it a good idea to use lambda expression instead of delegates?
Lambda expression can used instead of delegates, I'm not sure that it is a good way,I think it is more handy than delegates but I'm not sure that it is a good idea.

Is it a good idea to use lambda expression instead of delegates?

答:
You can create a delegate instance in several different ways:

Using C# 3 lambda expression:

```<code>Func<int> getFive = () => 5;
</code>```

Using the C# 2 anonymous method syntax:

```<code>Func<int> getFive = delegate { return 5 };
</code>```

Using non-anonymous method (available since C# 1):

```<code>int GetFive()
{
    return 5;
}
…
Func<int> getFive = GetFive;
</code>```

I think each of these has its uses.

The delegate { } syntax has the advantage that you don't have to declare the parameters if you don't need them.

Lambda expressions are very succinct and can be translated to expressions instead of delegates, which is very useful for LINQ-to-some-DB, and means you can use the same syntax for querying in-memory structures and databases.

Using non-anonymous methods means you can easily reuse them and is also suitable for long methods.

All the cases above are translated to equivalent code. The only difference is whether the method is visible to you.

Both lambda expressions and anonymous methods can also be closures, i.e. they can capture local variables.

ContentLicense: CC BY-SA 3.0

Body:
You can create a delegate instance in several different ways:

Using C# 3 lambda expression:

Func<int> getFive = () => 5;

Using the C# 2 anonymous method syntax:

Func<int> getFive = delegate { return 5 };

Using non-anonymous method (available since C# 1):

int GetFive()
{
    return 5;
}
…
Func<int> getFive = GetFive;

I think each of these has its uses.

The delegate { } syntax has the advantage that you don't have to declare the parameters if you don't need them.

Lambda expressions are very succinct and can be translated to expressions instead of delegates, which is very useful for LINQ-to-some-DB, and means you can use the same syntax for querying in-memory structures and databases.

Using non-anonymous methods means you can easily reuse them and is also suitable for long methods.

All the cases above are translated to equivalent code. The only difference is whether the method is visible to you.

Both lambda expressions and anonymous methods can also be closures, i.e. they can capture local variables.


问:
How to pass values from Pyqt5 GUI to multiple processes
I have the following code:

```<code>from PyQt5 import uic, QtWidgets
import os
import sys
import threading
from multiprocessing import Pool

def fetchdata(num):
    message = window.lineEdit()
    print(message)

def processchain():
    p=Pool(processes=15)
    data=p.map(fetchdata,range(1,1000))

def alltask():
    x = threading.Thread(target=processchain)
    x.start()

if __name__ == '__main__':

    y = os.getcwd()

    app=QtWidgets.QApplication(sys.argv)
    window = uic.loadUi(os.path.normpath(y)+ "\\" + "estate.ui")
    window.pushButton.clicked.connect(alltask)

    window.show()

    sys.exit(app.exec_())
</code>```

The fetchdata function being multiprocessed has a line input = window.lineEdit.text() which gives an error saying the window variable isnt defined. Does it mean I have to pass the window variable to the thread in the alltask function then pass it from the thread to the processchain function which then passes it on to all the multiprocesses? Seems like a pain and am hoping there is an easier way

How I can have the GUI objects available to every thread and process? Below is the code for reproducing the estate.ui file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>640</width>
    <height>186</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <widget class="QPushButton" name="pushButton">
    <property name="geometry">
     <rect>
      <x>370</x>
      <y>30</y>
      <width>151</width>
      <height>71</height>
     </rect>
    </property>
    <property name="text">
     <string>ENTER</string>
    </property>
   </widget>
   <widget class="QLineEdit" name="lineEdit">
    <property name="geometry">
     <rect>
      <x>120</x>
      <y>49</y>
      <width>191</width>
      <height>31</height>
     </rect>
    </property>
   </widget>
   <widget class="QLabel" name="label">
    <property name="geometry">
     <rect>
      <x>40</x>
      <y>60</y>
      <width>47</width>
      <height>13</height>
     </rect>
    </property>
    <property name="text">
     <string>INPUT</string>
    </property>
   </widget>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>640</width>
     <height>21</height>
    </rect>
   </property>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>
</code>```

答:
The GUI should not be accessed from another thread or other process, what should be done is to send the text information at the time of starting the thread and the processes:

from multiprocessing import Pool
import os
import sys
import threading

from PyQt5 import uic, QtWidgets

def fetchdata(value):
    num, message = value
    print(num, message)
    return True

def processchain(message):
    p = Pool(processes=15)
    data = p.map(fetchdata, [(i, message) for i in range(1, 1000)])
    print("results:", data)

def alltask(message):
    threading.Thread(target=processchain, args=(message,), daemon=True).start()

if __name__ == "__main__":

    app = QtWidgets.QApplication(sys.argv)
    ui_filename = os.path.join(os.path.dirname(os.path.realpath(__file__)), "estate.ui")
    window = uic.loadUi(ui_filename)

    def on_clicked():
        message = window.lineEdit.text()
        alltask(message)

    window.pushButton.clicked.connect(on_clicked)
    window.show()

    sys.exit(app.exec_())
```

Body:
I have the following code:

from PyQt5 import uic, QtWidgets
import os
import sys
import threading
from multiprocessing import Pool

def fetchdata(num):
    message = window.lineEdit()
    print(message)

def processchain():
    p=Pool(processes=15)
    data=p.map(fetchdata,range(1,1000))

def alltask():
    x = threading.Thread(target=processchain)
    x.start()

if __name__ == '__main__':

    y = os.getcwd()

    app=QtWidgets.QApplication(sys.argv)
    window = uic.loadUi(os.path.normpath(y)+ "\\" + "estate.ui")
    window.pushButton.clicked.connect(alltask)

    window.show()

    sys.exit(app.exec_())

The fetchdata function being multiprocessed has a line input = window.lineEdit.text() which gives an error saying the window variable isnt defined. Does it mean I have to pass the window variable to the thread in the alltask function then pass it from the thread to the processchain function which then passes it on to all the multiprocesses? Seems like a pain and am hoping there is an easier way

How I can have the GUI objects available to every thread and process? Below is the code for reproducing the estate.ui file:

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>640</width>
    <height>186</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <widget class="QPushButton" name="pushButton">
    <property name="geometry">
     <rect>
      <x>370</x>
      <y>30</y>
      <width>151</width>
      <height>71</height>
     </rect>
    </property>
    <property name="text">
     <string>ENTER</string>
    </property>
   </widget>
   <widget class="QLineEdit" name="lineEdit">
    <property name="geometry">
     <rect>
      <x>120</x>
      <y>49</y>
      <width>191</width>
      <height>31</height>
     </rect>
    </property>
   </widget>
   <widget class="QLabel" name="label">
    <property name="geometry">
     <rect>
      <x>40</x>
      <y>60</y>
      <width>47</width>
      <height>13</height>
     </rect>
    </property>
    <property name="text">
     <string>INPUT</string>
    </property>
   </widget>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>640</width>
     <height>21</height>
    </rect>
   </property>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>


问:
How can I delete committed items that haven't been pushed to git yet?
I tried to push files that were too big for the GitHub limit and couldn't push them. I removed them from the folder, but they're still there, waiting to be committed, and it's blocking other push attempts too.</p>

答:
Your problem is due to the fact that Git doesn't push files.  Git pushes commits.

Git doesn't really store files either: Git stores commits.  Commits themselves store files, but the key point is, you either have all of a commit, or none of it.  There's no way to pick and choose just a few files out of it.

When you added the big files and committed, you made commits that have those files.  Then you made additional, later commits that don't have those files.

So, keeping in mind that each commit stores a full and complete snapshot of all of your files—well, all of the files that are in that commit, which might be more or fewer files than some earlier commit—let's look at the rest of a commit.  Besides the snapshot, a commit stores some metadata: some information about the commit itself.  For instance, the commits you made have your name and email address in them, from your user.name and user.email settings.  When you ran git commit, Git made you enter a log message, to say why you made the commit; the log message for each commit is part of that commit's metadata.

Commits are numbered, but not sequentially (that would be too easy!).  They have big ugly hash IDs as their numbers.  Every commit gets a unique hash ID, reserved for that commit forever more, and in a way, reserved for that commit long before you made it, except that the actual hash ID depends on all the metadata, and one of the items in the metadata is the date-and-time-stamp of when you made it.  So until you actually chose a particular second of a particular minute of a particular hour of a particular day (etc), we wouldn't know what the hash ID would be.  Still, that hash ID, from now on, means that commit.  Your Git and any other Git can exchange commits, and know if they have each other's commits, by just comparing hash IDs.

The last key piece of metadata, though, is that every commit1 stores its previous commit's hash ID as its parent.  So every commit remembers which commit comes before it.

This means commits form a sort of backwards-pointing chain:

```<code>... <-F <-G <-H
</code>```

where H stands for some big ugly hash ID.  Commit H holds earlier commit G's big ugly hash ID as its parent; we say that H points to G.  Commit G holds F's hash ID, so G points to F, and so on.

Note: the hash IDs are exquisitely sensitive to every bit of data in the commit.  This means no part of any commit can ever change.  (That's why it's OK to trust in the hash ID.)

When you run git push, your Git calls up another Git.  Your Git says: Hey, I'd like to give you my latest commit H.  Do you have it yet?  They say: No, send it over.  Your Git says: "To have H you need G, do you have it yet?*  They say no, send that one too, and so on.  This repeats until we reach a point where they say: Oh, yes, I have that one.

That's how your Git knows what it needs to send, and sends it all: just the right set of commits.

But you've got commit H, which doesn't have the big files, and commit G, which does, and then maybe you and they both have commit F.  So your Git insists on sending both commits to them.  That's because you can't have a commit, in Git, unless you have all of its parents.2

1Some commits store two or more previous-commit hash IDs.  These are merge commits.  At least one commit in any non-empty repository stores no previous hash ID: the very first commit someone makes can't remember a parent, as there is no previous commit.  This kind of commit is called a root commit.

2There are some ways to avoid having all of the parents, but they don't apply to this case.

What you need to do

What you need to do, then, is construct some new commit(s).

Commit H is sort of OK on its own, except it isn't on its own: it is indelibly linked to commit G, and commit G isn't OK because it has some really big files in it, that you don't want to have.  Commit F is OK and they they already have F ... or maybe F is bad too, and it's E that's OK and they already have.  Whatever your situation is, you have to figure out which commits are good and which aren't.

So, what we need to do is find out which commit they have, and which commits we have that are good and which are bad, and re-copy our good ones while leaving out our bad ones.  There are a lot of ways to do this, but often the best one is to use git rebase -i:

```<code>git rebase -i origin/master
</code>```

Our name origin/master is our Git's way of remembering their Git's master.  This assumes your current branch name is master, i.e., that the picture we should draw really looks like this:

```<code>...--F   <-- origin/master
      \
       G--H   <-- master (HEAD)
</code>```

Here, commit G is the one with the big file(s), and commit H is the one that takes them away again.  We'd like to copy G-plus-H such that the big files are gone.  Since H simply removes the file, we can use git rebase -i's squash command to combine G and H into one new commit, I, that does what G+H did, all in one:

```<code>pick <hash> subject line for commit G
pick <hash> subject line for commit H
</code>```

becomes:

```<code>pick <hash> subject line for commit G
squash <hash> subject line for commit H
</code>```

We write this out and git rebase goes and squashes the two and invokes our editor to let us write the new commit message.

When the whole thing is done, we end up with this:

```<code>       I   <-- master (HEAD)
      /
...--F   <-- origin/master
      \
       G--H   [abandoned]
</code>```

That is, we kept existing commit F without touching it at all.  Then we had Git extract G, pile H on top of it (removing the big files), and commit the result as new commit I.  Our Git then took our name master off commit H, which was OK except that it linked to G.  It now has our name master set to point to commit I.

We can now run git push origin master successfully: our Git will call up their Git, and say I'd like to offer you commit I if you don't have it.  They'll say OK, what about I's parents?  Our Git will say I's parent is F.  They'll say Oh I have that one!  Our Git will send commit I and then ask them to set their master to point to commit I.

If all goes well this time, they'll now have commit I.  They never see our G and H again, and neither do we: we no longer have a name by which to find the big ugly hash ID of commit H.

Eventually—after 30 or more days, typically, though you can tweak this—our Git notices that no one seems to want H at all, and that G can only be found by starting at H and working backwards.  So our Git will actually throw out commits H and G at this point (when the maintenance git gc command gets around to it, really), and our repository will shrink because we don't have the commit with the big file.

(If your commits are more complicated, you may need a somewhat fancier git rebase, or git rebase -i might no longer be the best tool for all of this.  A great deal depends on exactly what's wrong and whether there's more than one way to fix it.)

Body:
Your problem is due to the fact that Git doesn't push files.  Git pushes commits.

Git doesn't really store files either: Git stores commits.  Commits themselves store files, but the key point is, you either have all of a commit, or none of it.  There's no way to pick and choose just a few files out of it.

When you added the big files and committed, you made commits that have those files.  Then you made additional, later commits that don't have those files.

So, keeping in mind that each commit stores a full and complete snapshot of all of your files—well, all of the files that are in that commit, which might be more or fewer files than some earlier commit—let's look at the rest of a commit.  Besides the snapshot, a commit stores some metadata: some information about the commit itself.  For instance, the commits you made have your name and email address in them, from your user.name and user.email settings.  When you ran git commit, Git made you enter a log message, to say why you made the commit; the log message for each commit is part of that commit's metadata.

Commits are numbered, but not sequentially (that would be too easy!).  They have big ugly hash IDs as their numbers.  Every commit gets a unique hash ID, reserved for that commit forever more, and in a way, reserved for that commit long before you made it, except that the actual hash ID depends on all the metadata, and one of the items in the metadata is the date-and-time-stamp of when you made it.  So until you actually chose a particular second of a particular minute of a particular hour of a particular day (etc), we wouldn't know what the hash ID would be.  Still, that hash ID, from now on, means that commit.  Your Git and any other Git can exchange commits, and know if they have each other's commits, by just comparing hash IDs.

The last key piece of metadata, though, is that every commit1 stores its previous commit's hash ID as its parent.  So every commit remembers which commit comes before it.

This means commits form a sort of backwards-pointing chain:

... <-F <-G <-H

where H stands for some big ugly hash ID.  Commit H holds earlier commit G's big ugly hash ID as its parent; we say that H points to G.  Commit G holds F's hash ID, so G points to F, and so on.

Note: the hash IDs are exquisitely sensitive to every bit of data in the commit.  This means no part of any commit can ever change.  (That's why it's OK to trust in the hash ID.)

When you run git push, your Git calls up another Git.  Your Git says: Hey, I'd like to give you my latest commit H.  Do you have it yet?  They say: No, send it over.  Your Git says: "To have H you need G, do you have it yet?*  They say no, send that one too, and so on.  This repeats until we reach a point where they say: Oh, yes, I have that one.

That's how your Git knows what it needs to send, and sends it all: just the right set of commits.

But you've got commit H, which doesn't have the big files, and commit G, which does, and then maybe you and they both have commit F.  So your Git insists on sending both commits to them.  That's because you can't have a commit, in Git, unless you have all of its parents.2

1Some commits store two or more previous-commit hash IDs.  These are merge commits.  At least one commit in any non-empty repository stores no previous hash ID: the very first commit someone makes can't remember a parent, as there is no previous commit.  This kind of commit is called a root commit.

2There are some ways to avoid having all of the parents, but they don't apply to this case.

What you need to do

What you need to do, then, is construct some new commit(s).

Commit H is sort of OK on its own, except it isn't on its own: it is indelibly linked to commit G, and commit G isn't OK because it has some really big files in it, that you don't want to have.  Commit F is OK and they they already have F ... or maybe F is bad too, and it's E that's OK and they already have.  Whatever your situation is, you have to figure out which commits are good and which aren't.

So, what we need to do is find out which commit they have, and which commits we have that are good and which are bad, and re-copy our good ones while leaving out our bad ones.  There are a lot of ways to do this, but often the best one is to use git rebase -i:

git rebase -i origin/master

Our name origin/master is our Git's way of remembering their Git's master.  This assumes your current branch name is master, i.e., that the picture we should draw really looks like this:

...--F   <-- origin/master
      \
       G--H   <-- master (HEAD)

Here, commit G is the one with the big file(s), and commit H is the one that takes them away again.  We'd like to copy G-plus-H such that the big files are gone.  Since H simply removes the file, we can use git rebase -i's squash command to combine G and H into one new commit, I, that does what G+H did, all in one:

pick <hash> subject line for commit G
pick <hash> subject line for commit H

becomes:

pick <hash> subject line for commit G
squash <hash> subject line for commit H

We write this out and git rebase goes and squashes the two and invokes our editor to let us write the new commit message.

When the whole thing is done, we end up with this:

       I   <-- master (HEAD)
      /
...--F   <-- origin/master
      \
       G--H   [abandoned]

That is, we kept existing commit F without touching it at all.  Then we had Git extract G, pile H on top of it (removing the big files), and commit the result as new commit I.  Our Git then took our name master off commit H, which was OK except that it linked to G.  It now has our name master set to point to commit I.

We can now run git push origin master successfully: our Git will call up their Git, and say I'd like to offer you commit I if you don't have it.  They'll say OK, what about I's parents?  Our Git will say I's parent is F.  They'll say Oh I have that one!  Our Git will send commit I and then ask them to set their master to point to commit I.

If all goes well this time, they'll now have commit I.  They never see our G and H again, and neither do we: we no longer have a name by which to find the big ugly hash ID of commit H.

Eventually—after 30 or more days, typically, though you can tweak this—our Git notices that no one seems to want H at all, and that G can only be found by starting at H and working backwards.  So our Git will actually throw out commits H and G at this point (when the maintenance git gc command gets around to it, really), and our repository will shrink because we don't have the commit with the big file.

(If your commits are more complicated, you may need a somewhat fancier git rebase, or git rebase -i might no longer be the best tool for all of this.  A great deal depends on exactly what's wrong and whether there's more than one way to fix it.)


问:
Cannot retrieve cell value within custom function
```<code>Function MergeNames(sArrDep As String, rMergeRange As Range) As String
Dim sTeamMember As String, rNames As Range
Dim iCol As Integer, sMergeNames As String, iIndex As Integer
    If rMergeRange.Rows.Count > 1 Then Exit Function
    Set rNames = Range("NAMES")
    With rMergeRange
        If sArrDep = "A" Or sArrDep = "D" Then
            iCol = .Columns.Count
                For iIndex = 1 To iCol
                Debug.Print .Cells(1, iIndex)
                    If .Cells(1, iIndex).Value = sArrDep Then
                        sTeamMember = rNames.Cells(1, iCol)
                        If sMergeNames = "" Then
                            sMergeNames = sTeamMember
                        Else
                            sMergeNames = sMergeNames & "; " & sTeamMember
                        End If
                    End If
                Next iIndex
        Else
            Exit Function
        End If
    End With
    MergeNames = sMergeNames
End Function
</code>```

In the immediate window the cell value appears correctly:

? rmergerange.cells(1,iindex).value

A

However in the custom function the returned value = empty. When I run the same code as a subroutine then the content of the cell is correctly retrieved.

What am I doing wrong

答: It appears that after removing the debug.print the code executes properly at a reasonable speed. Problem solved</p>

Body:
Function MergeNames(sArrDep As String, rMergeRange As Range) As String
Dim sTeamMember As String, rNames As Range
Dim iCol As Integer, sMergeNames As String, iIndex As Integer
    If rMergeRange.Rows.Count > 1 Then Exit Function
    Set rNames = Range("NAMES")
    With rMergeRange
        If sArrDep = "A" Or sArrDep = "D" Then
            iCol = .Columns.Count
                For iIndex = 1 To iCol
                Debug.Print .Cells(1, iIndex)
                    If .Cells(1, iIndex).Value = sArrDep Then
                        sTeamMember = rNames.Cells(1, iCol)
                        If sMergeNames = "" Then
                            sMergeNames = sTeamMember
                        Else
                            sMergeNames = sMergeNames & "; " & sTeamMember
                        End If
                    End If
                Next iIndex
        Else
            Exit Function
        End If
    End With
    MergeNames = sMergeNames
End Function

In the immediate window the cell value appears correctly:

? rmergerange.cells(1,iindex).value

A

However in the custom function the returned value = empty. When I run the same code as a subroutine then the content of the cell is correctly retrieved.

What am I doing wrong


问:
ng-select2 dropdown still shows after clicking browser back button
I am using an ng-select2 component here

  <ng-select2 id="supportTicketFilter" class="support-ticket-filter" width="370" [data]="filterValues"
            [options]="options" (valueChanged)="filterTable($event)" name="searchBar" data-selected="selected">
</ng-select2>```

The issue is that when the drop down is selected as seen belowenter image description here

and you click the back button on the browser, the dropdown menu still appears on the next page.

enter image description here

Has anyone run into this issue before?
The only thing I can think of now is to listen for the back button on the browser and then try to toggle something in the ng-select2.

答:
Found the solution, there was a class added on the container for the list that is rendered when clicking the dropdown.

for angular solutions was this

ngOnDestroy(): void {
    const selectOptionsContainer = $('.select2-container');
    selectOptionsContainer.removeClass('select2-container--open')
  }```

Body:
I am using an ng-select2 component here

  <ng-select2 id="supportTicketFilter" class="support-ticket-filter" width="370" [data]="filterValues"
            [options]="options" (valueChanged)="filterTable($event)" name="searchBar" data-selected="selected">
</ng-select2>

The issue is that when the drop down is selected as seen belowenter image description here

and you click the back button on the browser, the dropdown menu still appears on the next page.

enter image description here

Has anyone run into this issue before?
The only thing I can think of now is to listen for the back button on the browser and then try to toggle something in the ng-select2.


问:
Shifting a graphics Path object over
In Java, Android specifically, how do I transform a Path object over 100 pixels? Like in C#, I would use the following code to do this:

```<code>// Create a path and add and ellipse.
GraphicsPath myPath = new GraphicsPath();
myPath.AddEllipse(0, 0, 100, 200);

// Draw the starting position to screen.
e.Graphics.DrawPath(Pens.Black, myPath);

// Move the ellipse 100 points to the right.
Matrix translateMatrix = new Matrix();
translateMatrix.Translate(100, 0);
myPath.Transform(translateMatrix);

// Draw the transformed ellipse to the screen.
e.Graphics.DrawPath(new Pen(Color.Red, 2), myPath);
</code>```

How do I do this in Android? I already have my Path object:

```<code>@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    Paint pnt = new Paint();
    Path p = new Path();

    pnt.setStyle(Paint.Style.STROKE);
    pnt.setColor(Color.WHITE);

    p.moveTo(97.4f, 87.6f);
    p.lineTo(97.4f, 3.8f);

    p.lineTo(-1.2f, 1.2f);
    p.lineTo(-0.4f,-0.4f);

    p.lineTo(-0.4f,87f);

    p.lineTo(97.4f, 87.6f);
    p.close();

    canvas.drawPath(p, pnt);
}
</code>```

What do you I need to do in order to shift my Path object over 100 pixels?

答: I think Path.offset(float dx, float dy) is what you're looking for.

Title: Shifting a graphics Path object over

Body:
In Java, Android specifically, how do I transform a Path object over 100 pixels? Like in C#, I would use the following code to do this:

// Create a path and add and ellipse.
GraphicsPath myPath = new GraphicsPath();
myPath.AddEllipse(0, 0, 100, 200);

// Draw the starting position to screen.
e.Graphics.DrawPath(Pens.Black, myPath);

// Move the ellipse 100 points to the right.
Matrix translateMatrix = new Matrix();
translateMatrix.Translate(100, 0);
myPath.Transform(translateMatrix);

// Draw the transformed ellipse to the screen.
e.Graphics.DrawPath(new Pen(Color.Red, 2), myPath);

How do I do this in Android? I already have my Path object:

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    Paint pnt = new Paint();
    Path p = new Path();

    pnt.setStyle(Paint.Style.STROKE);
    pnt.setColor(Color.WHITE);

    p.moveTo(97.4f, 87.6f);
    p.lineTo(97.4f, 3.8f);

    p.lineTo(-1.2f, 1.2f);
    p.lineTo(-0.4f,-0.4f);

    p.lineTo(-0.4f,87f);

    p.lineTo(97.4f, 87.6f);
    p.close();

    canvas.drawPath(p, pnt);
}

What do you I need to do in order to shift my Path object over 100 pixels?


问:
Creating a gradient in background with PDFBox
How can I create a gradient in PDFBox? Or maybe "can I?".

I don't want to create them and export to jpeg or something else. I need a light document, so this has to be programmed somehow.

Any ideas?

答:
Here's a class I made to make the creation of gradients easier. It supports axial gradients with multiple colors. It uses java.awt.Color to specify colors but that can be replaced easily.

public class PDGradient extends PDShadingType2 {

    public PDGradient(List<GradientPart> parts) {
        super(new COSDictionary());

        // PDF 1.7 - 8.7.4.5.3 Type 2 (Axial) Shadings
        setColorSpace(PDDeviceRGB.INSTANCE);
        setShadingType(PDShadingType2.SHADING_TYPE2);
        setFunction(createGradientFunction(parts));
    }

    private static PDFunction createGradientFunction(List<GradientPart> parts) {
        if (parts.size() < 2) {
            throw new IllegalArgumentException("Gradient must have at least 2 colors.");
        }

        GradientPart first = parts.get(0);
        GradientPart last = parts.get(parts.size() - 1);
        if (first.ratio != 0f) {
            throw new IllegalArgumentException("Gradient first color ratio must be 0.");
        } else if (last.ratio != 1f) {
            throw new IllegalArgumentException("Gradient last color ratio must be 1.");
        }
        if (parts.size() == 2) {
            // Only two colors, use exponential function.
            return createColorFunction(first.color, last.color);
        }

        // Multiple colors, use stitching function to combine exponential functions
        // PDF 1.7 - 7.10.4 Type 3 (Stitching) Functions
        COSDictionary dict = new COSDictionary();
        COSArray functions = new COSArray();
        COSArray bounds = new COSArray();
        COSArray encode = new COSArray();
        GradientPart lastPart = first;
        for (int i = 1; i < parts.size(); i++) {
            GradientPart part = parts.get(i);

            // Add exponential function for interpolating between these two colors.
            functions.add(createColorFunction(lastPart.color, part.color));

            // Specify function bounds, except for first and last, which are specified by domain.
            if (i != parts.size() - 1) {
                bounds.add(new COSFloat(part.ratio));
            }

            // Used to interpolate stitching function subdomain (eg: [0.2 0.5]
            // to the exponential function domain, which is always [0.0 1.0].
            encode.add(COSInteger.ZERO);
            encode.add(COSInteger.ONE);

            lastPart = part;
        }

        dict.setInt(COSName.FUNCTION_TYPE, 3);
        dict.setItem(COSName.DOMAIN, new PDRange());  // [0.0 1.0]
        dict.setItem(COSName.FUNCTIONS, functions);
        dict.setItem(COSName.BOUNDS, bounds);
        dict.setItem(COSName.ENCODE, encode);

        return new PDFunctionType3(dict);
    }

    private static PDFunction createColorFunction(Color start, Color end) {
        // PDF 1.7 - 7.10.3 Type 2 (Exponential Interpolation) Functions
        COSDictionary dict = new COSDictionary();
        dict.setInt(COSName.FUNCTION_TYPE, 2);
        dict.setItem(COSName.DOMAIN, new PDRange());  // [0.0 1.0]
        dict.setItem(COSName.C0, createColorCOSArray(start));
        dict.setItem(COSName.C1, createColorCOSArray(end));
        dict.setInt(COSName.N, 1);  // Linear interpolation
        return new PDFunctionType2(dict);
    }

    private static COSArray createColorCOSArray(Color color) {
        // Create a COSArray for a color.
        // java.awt.Color uses 0-255 values while PDF uses 0-1.
        COSArray a = new COSArray();
        a.add(new COSFloat(color.getRed() / 255f));
        a.add(new COSFloat(color.getGreen() / 255f));
        a.add(new COSFloat(color.getBlue() / 255f));
        return a;
    }

    /**
     * Specifies a color and its position in a {@link PDGradient}.
     */
    public static class GradientPart {

        public final Color color;
        public final float ratio;

        public GradientPart(Color color, float ratio) {
            this.color = color;
            this.ratio = ratio;
        }
    }
}
```

<p>Example usage:</p>

<pre class="lang-java prettyprint-override"><code>List<GradientPart> parts = new ArrayList<>();
parts.add(new GradientPart(Color.RED, 0.0f));
parts.add(new GradientPart(Color.YELLOW, 0.5f));
parts.add(new GradientPart(Color.GREEN, 1.0f));
PDGradient gradient = new PDGradient(parts);
gradient.setCoords(...);
pdfStream.shadingFill(gradient)
</code>```

This works essentially the same as the other answer for two colors gradients, using an exponential function (type 2) to linearly interpolate between two colors. If there are more colors, a stitching (type 3) function is used to combine multiple exponential functions with different subdomains.

Body:
Here's a class I made to make the creation of gradients easier. It supports axial gradients with multiple colors. It uses java.awt.Color to specify colors but that can be replaced easily.

public class PDGradient extends PDShadingType2 {

    public PDGradient(List<GradientPart> parts) {
        super(new COSDictionary());

        // PDF 1.7 - 8.7.4.5.3 Type 2 (Axial) Shadings
        setColorSpace(PDDeviceRGB.INSTANCE);
        setShadingType(PDShadingType2.SHADING_TYPE2);
        setFunction(createGradientFunction(parts));
    }

    private static PDFunction createGradientFunction(List<GradientPart> parts) {
        if (parts.size() < 2) {
            throw new IllegalArgumentException("Gradient must have at least 2 colors.");
        }

        GradientPart first = parts.get(0);
        GradientPart last = parts.get(parts.size() - 1);
        if (first.ratio != 0f) {
            throw new IllegalArgumentException("Gradient first color ratio must be 0.");
        } else if (last.ratio != 1f) {
            throw new IllegalArgumentException("Gradient last color ratio must be 1.");
        }
        if (parts.size() == 2) {
            // Only two colors, use exponential function.
            return createColorFunction(first.color, last.color);
        }

        // Multiple colors, use stitching function to combine exponential functions
        // PDF 1.7 - 7.10.4 Type 3 (Stitching) Functions
        COSDictionary dict = new COSDictionary();
        COSArray functions = new COSArray();
        COSArray bounds = new COSArray();
        COSArray encode = new COSArray();
        GradientPart lastPart = first;
        for (int i = 1; i < parts.size(); i++) {
            GradientPart part = parts.get(i);

            // Add exponential function for interpolating between these two colors.
            functions.add(createColorFunction(lastPart.color, part.color));

            // Specify function bounds, except for first and last, which are specified by domain.
            if (i != parts.size() - 1) {
                bounds.add(new COSFloat(part.ratio));
            }

            // Used to interpolate stitching function subdomain (eg: [0.2 0.5]
            // to the exponential function domain, which is always [0.0 1.0].
            encode.add(COSInteger.ZERO);
            encode.add(COSInteger.ONE);

            lastPart = part;
        }

        dict.setInt(COSName.FUNCTION_TYPE, 3);
        dict.setItem(COSName.DOMAIN, new PDRange());  // [0.0 1.0]
        dict.setItem(COSName.FUNCTIONS, functions);
        dict.setItem(COSName.BOUNDS, bounds);
        dict.setItem(COSName.ENCODE, encode);

        return new PDFunctionType3(dict);
    }

    private static PDFunction createColorFunction(Color start, Color end) {
        // PDF 1.7 - 7.10.3 Type 2 (Exponential Interpolation) Functions
        COSDictionary dict = new COSDictionary();
        dict.setInt(COSName.FUNCTION_TYPE, 2);
        dict.setItem(COSName.DOMAIN, new PDRange());  // [0.0 1.0]
        dict.setItem(COSName.C0, createColorCOSArray(start));
        dict.setItem(COSName.C1, createColorCOSArray(end));
        dict.setInt(COSName.N, 1);  // Linear interpolation
        return new PDFunctionType2(dict);
    }

    private static COSArray createColorCOSArray(Color color) {
        // Create a COSArray for a color.
        // java.awt.Color uses 0-255 values while PDF uses 0-1.
        COSArray a = new COSArray();
        a.add(new COSFloat(color.getRed() / 255f));
        a.add(new COSFloat(color.getGreen() / 255f));
        a.add(new COSFloat(color.getBlue() / 255f));
        return a;
    }

    /**
     * Specifies a color and its position in a {@link PDGradient}.
     */
    public static class GradientPart {

        public final Color color;
        public final float ratio;

        public GradientPart(Color color, float ratio) {
            this.color = color;
            this.ratio = ratio;
        }
    }
}

Example usage:

List<GradientPart> parts = new ArrayList<>();
parts.add(new GradientPart(Color.RED, 0.0f));
parts.add(new GradientPart(Color.YELLOW, 0.5f));
parts.add(new GradientPart(Color.GREEN, 1.0f));
PDGradient gradient = new PDGradient(parts);
gradient.setCoords(...);
pdfStream.shadingFill(gradient)

This works essentially the same as the other answer for two colors gradients, using an exponential function (type 2) to linearly interpolate between two colors. If there are more colors, a stitching (type 3) function is used to combine multiple exponential functions with different subdomains.


答:
You can also solve this by using the zip approach so something like this:

```<code> print(list(list(zip(*tuple_set))[0]))
</code>```

the * is used to unpack the arguments in the tuple_set specifically the first item i.e accessing 0 and getting just the names back

Hope that helps :)

Title: Isolating/indexing/ranging through a list object tuple set

Body:
You can also solve this by using the zip approach so something like this:

 print(list(list(zip(*tuple_set))[0]))

the * is used to unpack the arguments in the tuple_set specifically the first item i.e accessing 0 and getting just the names back

Hope that helps :)


问:
Onkeypress function returning spaces instead of letters
I am using the following in and attempt to get a user's letter guess to appear on screen, but when I check the devtools the keypress is being returned to the array like [ , , , , , ,]. No letters. Ideas?

var letguessText = document.getElementById("letguess")
var guessArray = []

document.onkeypress = function(event) {
  var guess = event.key

  guessArray.push(String.fromCharCode(guess));
  letguessText.textContent = guessArray;
}
```

答:
You don't need fromCharCode as the event.key is the character. Here is an example.

var letguessText = document.getElementById("letguess")
var guessArray = []

document.onkeypress = function(event) {
  var guess = event.key
  guessArray.push(guess);
  letguessText.textContent = guessArray;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="letguess">Start typing</p></code>```

Body:
You don't need fromCharCode as the event.key is the character. Here is an example.

var letguessText = document.getElementById("letguess")
var guessArray = []

document.onkeypress = function(event) {
  var guess = event.key
  guessArray.push(guess);
  letguessText.textContent = guessArray;
}

<p id="letguess">Start typing</p>


问:
issue ORA-00001: unique constraint violated coming in INSERT/UPDATE
I am trying to insert some values in table throught the application and get issue ORA-00001: unique constraint violated.
I see that sequences are out of sync with the highest id of the table, but even after fixing the sequence number the error still persists.
How can I debug this error more, does oracle logs give more error? how can I see the oracle logs?
Thanks
Priyank

update: we are using the audit logging plugin and in the domain class for User we catch the save event and log the entry into the audit log

So in User class we do:

```<code>class User {

//some attributes, constraints, mappings

def onSave = {
 Graaudit aInstance = new Graaudit();
         aInstance.eventType= "GRA User Create"
         aInstance.eventDescription = "GRA User Created"
         aInstance.objectid = username
         aInstance.objecttype = 'GRAUSER'
         aInstance.user_id = RequestContextHolder.currentRequestAttributes().session.username

          aInstance.withTransaction{
              aInstance.save()
          }
    }

}
</code>```

When we dont have the above code in the onSave event the User is created successfully.
 I am assuming its related to hibernate transaction which we are using on aInstance, thats dying or the current transaction is dying due to that save.
 If we dont use the transaction we get an exception "org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here"
Not sure how to fix this issue..
Thanks

答:
select the
index then select the ones needed then select sql and click action then click rebuild

Body:
I am trying to insert some values in table throught the application and get issue ORA-00001: unique constraint violated.
I see that sequences are out of sync with the highest id of the table, but even after fixing the sequence number the error still persists.
How can I debug this error more, does oracle logs give more error? how can I see the oracle logs?
Thanks
Priyank

update: we are using the audit logging plugin and in the domain class for User we catch the save event and log the entry into the audit log

So in User class we do:

class User {

//some attributes, constraints, mappings

def onSave = {
 Graaudit aInstance = new Graaudit();
         aInstance.eventType= "GRA User Create"
         aInstance.eventDescription = "GRA User Created"
         aInstance.objectid = username
         aInstance.objecttype = 'GRAUSER'
         aInstance.user_id = RequestContextHolder.currentRequestAttributes().session.username

          aInstance.withTransaction{
              aInstance.save()
          }
    }

}

When we dont have the above code in the onSave event the User is created successfully.
 I am assuming its related to hibernate transaction which we are using on aInstance, thats dying or the current transaction is dying due to that save.
 If we dont use the transaction we get an exception "org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here"
Not sure how to fix this issue..
Thanks


问:
Easy way to convert the MS Access database to Web application
As per requirement, we need to convert the existing MS Access database to a web application. Is there any easy way to convert the MS Access database to web application?  As of now they are inserting the data to access db using access Forms.  User also wish to continue access form feature even if we create new web application for the same. That means user should have the option to access the MS access database through Access forms as well as web application.

Please guide me away to solve this issue.

Best Regards,
Ranish

答:
There are generally two approaches with more details covered in this article looking at ways to convert microsoft access to web application

Direct Port means simply a basic migration whereby you port more or less verbatim basic Access forms into a web portal i.e. Microsft Access to a browser-based version as is using a third-party tool. Some of these are quite mundane in that it just allows you to run the Access application inside an internet browser (whoopee!) or can be quite drawn out and then limits you on how much you can change afterward. With even more complex cases requiring a consultant to help you migrate the system. Though it does help to know your user count as the higher you tend to be, the less appealing a third-party porting service becomes due to subscription-based models.

Upsize -the more involved or complex your data structure is an upsize using custom development and splitting the system across web and data tiers might be worth it if

You've got a special process or some secret sauce you're looking to keep.

Likely going to have a significant user count and want to avoid subscription

Inherently cynical or cautious, and want to handle your own architecture and security

Looking for a specific user experience


问:
Why does my heap.h file give me a LNK2001 error?
I've done some searching and have seen this error but in many cases it was caused by missing an include.
The header file is underneath "header files" in vs2019 as well

The error is caused in main at Leaf<int> leaf(3);

Here is my main.cpp

```<code>#include "heap.h"
#include <iostream>

using namespace std;

int main()
{
    //Need to complete testing from main
    Heap<int> heap(2);
    Leaf<int> leaf(3);

    //heap.insert(3);
}
</code>```

Here is the relevant class in heap.h

```<code>template <typename T> class Leaf : public Node<T> {
private:
    T key;
public:
    Leaf(T value) { key = value; }
    virtual Leaf<T>* toLeaf() { return this; }
    virtual Leaf<T>* insert(T key, Node<T>*& created) {
        Leaf<T>* newLeaf = new Leaf<T>(key);
        created = newLeaf;
        return newLeaf;
    }
};
</code>```

Error:

```<code>Severity    Code    Description Project File    Line    Suppression State
Error   LNK2001 unresolved external symbol "public: virtual class Leaf<int> * __cdecl Node<int>::insert(int,class Node<int> * &)" (?insert@?$Node@H@@UEAAPEAV?$Leaf@H@@HAEAPEAV1@@Z)    2-3-4 Heap  C:\Users\catcal\source\repos\2-3-4 Heap\2-3-4 Heap\main.obj 1
</code>```

答:
Why does my heap.h give me a link error?

You can check to see what kind of link error this is by the defined error number and in this case, it is LNK2001. This is stating that you have an unresolved external symbol.

When you try to call a function within a translation unit - a *.cpp file that has not yet been defined will cause the Linker to fail. It will generate the LNK2001 error that you are seeing. It simply doesn't know what to do with the function that you are trying to call simply because it has not yet been defined.

Looking closer at the description tells you what is causing this error flag to be triggered by the linker. It states that the Node<int>::insert(int,class Node<int> * &) can not be found or that there is no definition for it that is declared by public: virtual class Leaf<int> *

The reason you are seeing this is that in your main.cpp file you are making a call to both of Heap's and Leaf's constructors. And from your heap.h file you are also defining Leaf to be publicly inherited from Node. So when it tries to construct Leaf<T> it fails to do so because it can not completely construct Node<T>.

From the code that you have shown; you have declared and defined Leaf<T>::insert(T key, Node<T>*& created) but without seeing the reset of this header file for other possible includes as well as your the declaration and definition of your Node<T> class template, there is no easy way of knowing. However, I suspect that Node<T>::insert(T key, Node<int>* &) is not being defined or generated through template deduction since Node<T>::insert(T key, Node<T>* &) has not yet been defined.

Body:
I've done some searching and have seen this error but in many cases it was caused by missing an include.
The header file is underneath "header files" in vs2019 as well

The error is caused in main at Leaf<int> leaf(3);

Here is my main.cpp

#include "heap.h"
#include <iostream>

using namespace std;

int main()
{
    //Need to complete testing from main
    Heap<int> heap(2);
    Leaf<int> leaf(3);

    //heap.insert(3);
}

Here is the relevant class in heap.h

template <typename T> class Leaf : public Node<T> {
private:
    T key;
public:
    Leaf(T value) { key = value; }
    virtual Leaf<T>* toLeaf() { return this; }
    virtual Leaf<T>* insert(T key, Node<T>*& created) {
        Leaf<T>* newLeaf = new Leaf<T>(key);
        created = newLeaf;
        return newLeaf;
    }
};

Error:

Severity    Code    Description Project File    Line    Suppression State
Error   LNK2001 unresolved external symbol "public: virtual class Leaf<int> * __cdecl Node<int>::insert(int,class Node<int> * &)" (?insert@?$Node@H@@UEAAPEAV?$Leaf@H@@HAEAPEAV1@@Z)    2-3-4 Heap  C:\Users\catcal\source\repos\2-3-4 Heap\2-3-4 Heap\main.obj 1


问:
Jenkins add/update to all jobs : should have email alerts to default recipients list
our jenkins have about 100 jobs already, i want to add editable email notification for all jobs, so that all jobs should have email alerts to default recipients list.   Looking for Groovy Script for Jenkins Script Console to Add or Modify email notification  Setting .

```<code>Jenkins.instance.items.each { item ->

  println("JOB: " + item.name)

  // code for setting email notification if not exist
  if(item.XXXX == null) {
    println("No email notification step ")

  }
   else {
    //   code to update the current email settings
    println("Set new setting")

  }
 item.save()
 println(" done")

}
</code>```

Or some other automated way is also fine.
Thanks !

答:
Assuming you are using hudson.plugins.emailext.ExtendedEmailPublisher and all jobs already have the step added, this should probably cover the iteration part.

```<code>// Gets all jobs and folders recursively
items = Jenkins.instance.getAllItems();

items.each { item ->
   def status = ''
   def base_email = ''
   def ext_email = []
   if (item.class.name == "hudson.model.FreeStyleProject") {
      item.publishersList.findAll {it instanceof hudson.plugins.emailext.ExtendedEmailPublisher}.each { publisher ->
         status = publisher.disabled
         base_email=publisher.recipientList?.replaceAll("\\r|\\n", " ")
         publisher.configuredTriggers?.each { entry ->
            if (entry.email.recipientList) {
                ext_email << "${entry.class.name.replace("hudson.plugins.emailext.plugins.trigger.", "")}: ${entry.email.recipientList?.replaceAll("\\r|\\n", " ")}"
            }
         }
      }
      if ( base_email ) {
            println item.fullName + "( " + status + " )"
            println "  +- " + base_email
            ext_email.each {
               println "   - " + it
            }
      } else {
         println "# " + item.fullName
      }
   }
}
return
</code>```

If you are using hudson.tasks.Mailer,it's only one field: publisher.recipients

Then you either

```<code>publisher.recipientList="someone@somewhere.com"
item.save()
</code>```

or equivalent as needed.

Note: Extended Email plugin has a toggle to disable sending emails "Disable Extended Email Publisher (publisher.disabled), so report on that too.

If you need to add the plugin, then it would be something like:
item.publishersList.add(new hudson.plugins.emailext.ExtendedEmailPublisher(<parameters>)(see javadoc)

Body:
our jenkins have about 100 jobs already, i want to add editable email notification for all jobs, so that all jobs should have email alerts to default recipients list.   Looking for Groovy Script for Jenkins Script Console to Add or Modify email notification  Setting .

Jenkins.instance.items.each { item ->

  println("JOB: " + item.name)

  // code for setting email notification if not exist
  if(item.XXXX == null) {
    println("No email notification step ")

  }
   else {
    //   code to update the current email settings
    println("Set new setting")

  }
 item.save()
 println(" done")

}

Or some other automated way is also fine.
Thanks !

Body:
Assuming you are using hudson.plugins.emailext.ExtendedEmailPublisher and all jobs already have the step added, this should probably cover the iteration part.

// Gets all jobs and folders recursively
items = Jenkins.instance.getAllItems();

items.each { item ->
   def status = ''
   def base_email = ''
   def ext_email = []
   if (item.class.name == "hudson.model.FreeStyleProject") {
      item.publishersList.findAll {it instanceof hudson.plugins.emailext.ExtendedEmailPublisher}.each { publisher ->
         status = publisher.disabled
         base_email=publisher.recipientList?.replaceAll("\\r|\\n", " ")
         publisher.configuredTriggers?.each { entry ->
            if (entry.email.recipientList) {
                ext_email << "${entry.class.name.replace("hudson.plugins.emailext.plugins.trigger.", "")}: ${entry.email.recipientList?.replaceAll("\\r|\\n", " ")}"
            }
         }
      }
      if ( base_email ) {
            println item.fullName + "( " + status + " )"
            println "  +- " + base_email
            ext_email.each {
               println "   - " + it
            }
      } else {
         println "# " + item.fullName
      }
   }
}
return

If you are using hudson.tasks.Mailer,it's only one field: publisher.recipients

Then you either

publisher.recipientList="someone@somewhere.com"
item.save()

or equivalent as needed.

Note: Extended Email plugin has a toggle to disable sending emails "Disable Extended Email Publisher (publisher.disabled), so report on that too.

If you need to add the plugin, then it would be something like:
item.publishersList.add(new hudson.plugins.emailext.ExtendedEmailPublisher(<parameters>)(see javadoc)


问:
Invalid Resource and malformed policy errors - aws cloudformation YAML
Addig bucketpolicy for a s3 Bucket. But am running into multiple problems defining it in YAML. Here is the sample -

```<code> S3CURBucketPolicy:
    Type: 'AWS::S3::BucketPolicy'
    Properties:
      PolicyDocument:
        Statement:
          - Action:
              - 's3:ListBucket'
            Resource: !Join [ '', ["arn:aws:s3:::", !Ref S3BucketTest]]
            Effect: Allow
            Condition:
              StringEquals:
                'AWS:SourceAccount':
                  - 12334456676
            Principal: '*'
      Bucket: !Ref S3BucketTest
</code>```

S3BucketTest is the resource name of s3 bucket I defined in the same cft

```<code>S3BucketTest:
  Type: AWS::S3::Bucket
</code>```

I was able to create s3 bucket without any issues, but the bucketpolicy giving errors.

For the above yaml, it says that resource name is invalid.

If I have multiple Actions and I mention them in [], it throws invalid Acttions and malformed policy error.

I alo want to mention multiple resources.

I am essentially looking to replicatee this in YAML -

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "stmt_cross_acct_rs_Access",
            "Effect": "Allow",
            "Principal": {
                "AWS": ["arn:aws:iam::12345678:role/role_rs_1", "arn:aws:iam::12345678:root"]
            },
            "Action": [
                "s3:GetBucketLocation",
                "s3:GetObject",
                "s3:ListBucket",
                "s3:ListBucketMultipartUploads",
                "s3:ListMultipartUploadParts",
                "s3:AbortMultipartUpload",
                "s3:PutObject"
            ],
            "Resource": [
                "arn:aws:s3:::<demo-bucket>",
                "arn:aws:s3:::<demo-bucket>/*"
            ]
        }
    ]
}
</code>```

答:
Assuming you have a 'demobucket' as either a bucket resource or a parameter, the JSON above would look like this in YAML:

```<code>    Version: 2012-10-17
    Statement:
      - Sid: stmt_cross_acct_rs_Access
        Effect: Allow
        Principal:
          AWS:
            - arn:aws:iam::12345678:role/role_rs_1
            - arn:aws:iam::12345678:root
        Action:
          - s3:GetBucketLocation
          - s3:GetObject
          - s3:ListBucket
          - s3:ListBucketMultipartUploads
          - s3:ListMultipartUploadParts
          - s3:AbortMultipartUpload
          - s3:PutObject
        Resource:
          - !Sub 'arn:aws:s3:::${demobucket}'
          - !Sub 'arn:aws:s3:::${demobucket}/*'
</code>```

This is what you should do for the YAML you had:

```<code> S3CURBucketPolicy:
    Type: 'AWS::S3::BucketPolicy'
    Properties:
      PolicyDocument:
        Statement:
          - Action:
              - 's3:ListBucket'
            Resource: !GetAtt S3BucketTest.Arn
            Effect: Allow
            Condition:
              StringEquals:
                'AWS:SourceAccount':
                  - 12334456676
            Principal: '*'
      Bucket: !Ref S3BucketTest
</code>```

Body:
Addig bucketpolicy for a s3 Bucket. But am running into multiple problems defining it in YAML. Here is the sample -

 S3CURBucketPolicy:
    Type: 'AWS::S3::BucketPolicy'
    Properties:
      PolicyDocument:
        Statement:
          - Action:
              - 's3:ListBucket'
            Resource: !Join [ '', ["arn:aws:s3:::", !Ref S3BucketTest]]
            Effect: Allow
            Condition:
              StringEquals:
                'AWS:SourceAccount':
                  - 12334456676
            Principal: '*'
      Bucket: !Ref S3BucketTest

S3BucketTest is the resource name of s3 bucket I defined in the same cft

S3BucketTest:
  Type: AWS::S3::Bucket

I was able to create s3 bucket without any issues, but the bucketpolicy giving errors.

For the above yaml, it says that resource name is invalid.

If I have multiple Actions and I mention them in [], it throws invalid Acttions and malformed policy error.

I alo want to mention multiple resources.

I am essentially looking to replicatee this in YAML -

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "stmt_cross_acct_rs_Access",
            "Effect": "Allow",
            "Principal": {
                "AWS": ["arn:aws:iam::12345678:role/role_rs_1", "arn:aws:iam::12345678:root"]
            },
            "Action": [
                "s3:GetBucketLocation",
                "s3:GetObject",
                "s3:ListBucket",
                "s3:ListBucketMultipartUploads",
                "s3:ListMultipartUploadParts",
                "s3:AbortMultipartUpload",
                "s3:PutObject"
            ],
            "Resource": [
                "arn:aws:s3:::<demo-bucket>",
                "arn:aws:s3:::<demo-bucket>/*"
            ]
        }
    ]
}

Body:
Assuming you have a 'demobucket' as either a bucket resource or a parameter, the JSON above would look like this in YAML:

    Version: 2012-10-17
    Statement:
      - Sid: stmt_cross_acct_rs_Access
        Effect: Allow
        Principal:
          AWS:
            - arn:aws:iam::12345678:role/role_rs_1
            - arn:aws:iam::12345678:root
        Action:
          - s3:GetBucketLocation
          - s3:GetObject
          - s3:ListBucket
          - s3:ListBucketMultipartUploads
          - s3:ListMultipartUploadParts
          - s3:AbortMultipartUpload
          - s3:PutObject
        Resource:
          - !Sub 'arn:aws:s3:::${demobucket}'
          - !Sub 'arn:aws:s3:::${demobucket}/*'

This is what you should do for the YAML you had:

 S3CURBucketPolicy:
    Type: 'AWS::S3::BucketPolicy'
    Properties:
      PolicyDocument:
        Statement:
          - Action:
              - 's3:ListBucket'
            Resource: !GetAtt S3BucketTest.Arn
            Effect: Allow
            Condition:
              StringEquals:
                'AWS:SourceAccount':
                  - 12334456676
            Principal: '*'
      Bucket: !Ref S3BucketTest


问:
Linking two list using V-for and v-if
Platform: SharePoint 2016

Framework: Vuejs

I work for an organization that has a blog but the weird thing is that the pictures of the authors is stored independently.

There is a column in both lists that associates the connection.
The outer v-for loops through the blog posts and the inner v-for loops through the pictures.

If the value from the outer v-for equals the inner v-for , I want the image to show.
Here's the code:

```<code><v-row v-for="post in postArray">
    <table style="width:100%;margin-top:5px;margin-bottom:5px;border-bottom:1px gray solid;font-size:14px">
        <tr>
            <td style="padding:5px;width:80px;vertical-align:top;">
                <span v-for="blog in blogPictureArray" >
                    <span v-if='blog.Name' == 'post.Category'>
                        <img v-bind:src="blog.Name || alternateImg" v-bind:alt="post.BlogImgAlt" width="55" height="55" />
                    </span>
                </span>
            </td>
            <td>
                <p class="bloghead"><a v-bind:href="editLink + post.Id">{{post.Title}}</a></p>
                <p>by {{post.Author0  || "N/A"}} | {{convertDate(post.Created)}}
                <br />{{stripHtml(post.Body)}}<a v-bind:href="editLink + post.Id">read more</a></p>
            </td>
        </tr>
    </table>
</v-row>
</code>```

The picture is blank but I don't get an error either so I'm not sure what am I doing wrong?

Any ideas?

答:
Are you sure you want to set blog.Name as source of an image? I have no idea what its value is, but according to its semantics that might be My Bali diving trip rather than path/to/author.jpg.

Another thing i'd got rid of declarative loop inside of loop logic. Just move it to component's method:

```<code><img :src="getImgSrc(post)">
...
methods: {
  getImgSrc(post) {
    // Here check the pictureArray and return proper image path
  }
}
</code>```

And in the end... a table design? Common it's 2020 :)

Title: Linking two list using V-for and v-if

Body:
Platform: SharePoint 2016

Framework: Vuejs

I work for an organization that has a blog but the weird thing is that the pictures of the authors is stored independently.

There is a column in both lists that associates the connection.
The outer v-for loops through the blog posts and the inner v-for loops through the pictures.

If the value from the outer v-for equals the inner v-for , I want the image to show.
Here's the code:

<v-row v-for="post in postArray">

{{post.Title}}

by {{post.Author0  || "N/A"}} | {{convertDate(post.Created)}}

{{stripHtml(post.Body)}}read more

</v-row>

The picture is blank but I don't get an error either so I'm not sure what am I doing wrong?

Any ideas?

Body:
Are you sure you want to set blog.Name as source of an image? I have no idea what its value is, but according to its semantics that might be My Bali diving trip rather than path/to/author.jpg.

Another thing i'd got rid of declarative loop inside of loop logic. Just move it to component's method:

<img :src="getImgSrc(post)">
...
methods: {
  getImgSrc(post) {
    // Here check the pictureArray and return proper image path
  }
}

And in the end... a table design? Common it's 2020 :)


问:
git gui not working after installing in Mac (e.g. Mountain Lion)
When I ran git gui, I got this:

```<code>$ git gui
git: 'gui' is not a git command. See 'git --help'.

Did you mean one of these?
    grep
    init
    pull
    push
</code>```

But I ran other git commands fine, including gitk. How can I fix this?

Thanks.

答:
2020

```<code>brew install git
brew install git-gui
git config --global --add alias.gui '!sh -c '/usr/local/opt/git/libexec/git-core/git-gui''
</code>```

Now, enjoy:

```<code>git gui
</code>```

Body:
When I ran git gui, I got this:

$ git gui
git: 'gui' is not a git command. See 'git --help'.

Did you mean one of these?
    grep
    init
    pull
    push

But I ran other git commands fine, including gitk. How can I fix this?

Thanks.

Body:
2020

brew install git
brew install git-gui
git config --global --add alias.gui '!sh -c '/usr/local/opt/git/libexec/git-core/git-gui''

Now, enjoy:

git gui


问:
Manipulation with large dimensional matrix in R
I would like to calculate the following function for each row of a matrix M of dimension 3e+07x4.

```<code>func <- function(x){

   (dmultinom(c(x[c(1,2)],50-sum(x[c(1,2)])), size = NULL, rep(1/3,3), log = FALSE))/(x[3]^2+x[4]^3)

}
</code>```

I am using the following code

```<code>as.numeric(unlist(apply(M, 1, function(v) func(v))))
</code>```

Unfortunately, it is taking a long time. I'd like to do this in a short time.

答:
Luckily, lgamma is a Primitive function and hence an option is to vectorize dmultinom by yourself. Here is a option combined with data.table for faster sped

```<code>set.seed(0L)
nr <- 3e7 #3e7
size <- 50L
DT <- data.table(X1=sample(1:20, nr, TRUE), X2=sample(1:20, nr, TRUE), X3=3, X4=4)

system.time({
    DT[, paste0("lgX", 1L:3L) := c(lapply(1+.SD, lgamma), .(lgamma(1+size-X1-X2))), .SDcols=X1:X2][,
       dmn := exp(lgamma(size + 1L) + log(1/3) * size - (lgX1 + lgX2 + lgX3)) / (X3^2 + X4^2)]
    DT$dmn
})

#   user  system elapsed
#   7.44    0.17    7.64
</code>```

Body:
I would like to calculate the following function for each row of a matrix M of dimension 3e+07x4.

func <- function(x){

   (dmultinom(c(x[c(1,2)],50-sum(x[c(1,2)])), size = NULL, rep(1/3,3), log = FALSE))/(x[3]^2+x[4]^3)

}

I am using the following code

as.numeric(unlist(apply(M, 1, function(v) func(v))))

Unfortunately, it is taking a long time. I'd like to do this in a short time.

Body:
Luckily, lgamma is a Primitive function and hence an option is to vectorize dmultinom by yourself. Here is a option combined with data.table for faster sped

set.seed(0L)
nr <- 3e7 #3e7
size <- 50L
DT <- data.table(X1=sample(1:20, nr, TRUE), X2=sample(1:20, nr, TRUE), X3=3, X4=4)

system.time({
    DT[, paste0("lgX", 1L:3L) := c(lapply(1+.SD, lgamma), .(lgamma(1+size-X1-X2))), .SDcols=X1:X2][,
       dmn := exp(lgamma(size + 1L) + log(1/3) * size - (lgX1 + lgX2 + lgX3)) / (X3^2 + X4^2)]
    DT$dmn
})

#   user  system elapsed
#   7.44    0.17    7.64


问:
Is it not possible to run compiled C++ applications in Windows 95 and Windows NT 4.0?
Whenever I use MinGW to compile C++ applications, they work correctly in modern versions of Microsoft Windows including Windows 2000 and Windows XP.

However, when I attempt to run them on Windows 95 and Windows NT 4.0, I get these errors:

Does that mean that the idea of running compiled C++ applications is fundamentally unsupported in those versions?

Note: I haven't tested <s>Windows 98 and </s>Windows ME yet.

Edit: I've tested Windows 98. The testsortingvisualization runs properly, but the tetrisimplementation displays a blank command prompt and doesn't halt. Both of these programs gave the exact same error given above in Windows 95 and Windows NT 4.0. Keep in mind, Windows 2000 can run both correctly.

Edit:
Microsoft claims some of the functions I used (WriteConsoleOutput, GetAsyncKeyState) have a minimal requirement of Windows 2000. Indeed, it's tested not to work in Windows 98. I haven't figured out a more compatible way to do console output (system 8-bit codepage, 80 columns, 25 rows, 16 colors) or key detection.

The MSVCRT.DLL failure: the DLL is a critical dependency for compiled C++ applications, so it's fundamentally not possible to run any compiled C++ applications on Windows 95 at all.

I haven't found an explanation for the NT 4.0 issue.

答:
The MS Visual C++ runtime DLL was not distributed with early versions of Windows, you either statically linked the code to the Microsoft libraries (not possible with MinGW), or you deploy the dependencies with your application.

The redistributable parts of VC++ (in which MSVCRT.DLL is included) are provided in a redistributable package specific to various versions of VC++, MSCVRT.DLL is from VC++ 6.0, and no longer available from from official sources; at your own risk you can get it from here for example.

Your Windows NT 4.0 error is a matter of your code using an API that was not part of the Win32 API when NT 4 was current.  You can specify the target Windows version through various macros to restrict the API available to your code. That will then generate a compile time error rather then a runtime error. If that particular call is critical to your application, then it simply cannot be run on WinNT.  The documentation for SetCriticalSectionSpinCount() states that the minimum supported system is XP.

With respect to your console I/O issue, MSVCRT.DLL includes Microsoft's conio library (not the same or as extensive as Borland's). MinGW includes conio.h header I think or here.  That may provide what you need.


问:
How can I pass an argument to a PowerShell script?
There's a PowerShell script named itunesForward.ps1 that makes iTunes fast forward 30 seconds:

```<code>$iTunes = New-Object -ComObject iTunes.Application

if ($iTunes.playerstate -eq 1)
{
  $iTunes.PlayerPosition = $iTunes.PlayerPosition + 30
}
</code>```

It is executed with a prompt line command:

```<code>powershell.exe itunesForward.ps1
</code>```

Is it possible to pass an argument from the command line and have it applied in the script instead of the hardcoded 30 seconds value?

答:
```<code># ENTRY POINT MAIN()
Param(
    [Parameter(Mandatory=$True)]
    [String] $site,
    [Parameter(Mandatory=$True)]
    [String] $application,
    [Parameter(Mandatory=$True)]
    [String] $dir,
    [Parameter(Mandatory=$True)]
    [String] $applicationPool
)

# Create Web IIS Application
function ValidateWebSite ([String] $webSiteName)
{
    $iisWebSite = Get-Website -Name $webSiteName
    if($Null -eq $iisWebSite)
    {
        Write-Error -Message "Error: Web Site Name: $($webSiteName) not exists."  -Category ObjectNotFound
    }
    else
    {
        return 1
    }
}

# Get full path from IIS WebSite
function GetWebSiteDir ([String] $webSiteName)
{
    $iisWebSite = Get-Website -Name $webSiteName
    if($Null -eq $iisWebSite)
    {
        Write-Error -Message "Error: Web Site Name: $($webSiteName) not exists."  -Category ObjectNotFound
    }
    else
    {
        return $iisWebSite.PhysicalPath
    }
}

# Create Directory
function CreateDirectory([string]$fullPath)
{
    $existEvaluation = Test-Path $fullPath -PathType Any
    if($existEvaluation -eq $false)
    {
        new-item $fullPath -itemtype directory
    }
    return 1
}

function CreateApplicationWeb
{
    Param(
        [String] $WebSite,
        [String] $WebSitePath,
        [String] $application,
        [String] $applicationPath,
        [String] $applicationPool
        )
    $fullDir = "$($WebSitePath)\$($applicationPath)"
    CreateDirectory($fullDir)
    New-WebApplication -Site $WebSite -Name $application -PhysicalPath $fullDir -ApplicationPool $applicationPool -Force
}

$fullWebSiteDir = GetWebSiteDir($Site)f($null -ne $fullWebSiteDir)
{
    CreateApplicationWeb -WebSite $Site -WebSitePath $fullWebSiteDir -application $application  -applicationPath $dir -applicationPool $applicationPool
}
</code>```

Body:
There's a PowerShell script named itunesForward.ps1 that makes iTunes fast forward 30 seconds:

$iTunes = New-Object -ComObject iTunes.Application

if ($iTunes.playerstate -eq 1)
{
  $iTunes.PlayerPosition = $iTunes.PlayerPosition + 30
}

It is executed with a prompt line command:

powershell.exe itunesForward.ps1

Is it possible to pass an argument from the command line and have it applied in the script instead of the hardcoded 30 seconds value?


问:
How to un-obfuscate JavaScript starting with const and a bunch of vars
Hi i found this extension and would like to see the contents of the script itself to check what is actually does. I tried putting the script through all sort of javascript de/un-obfuscators and none worked.

Please tell me one that works or send me the de-obfuscated JS.

CODE HERE

答:
The point of obfuscating something is so it cant be reversed. It has stripped all names and minified intentionally to make it as hard as possible.

You can reverse it partially but it won't be very readable.

For example if you obfuscate this

function hi(first, second) {
  const third = first + second
  return third
}
hi(1, 2);
```

<p>You will get something like this.</p>

<pre class="lang-js prettyprint-override"><code>function hi(_0x850806,_0x3f2655){const _0x2231a6=_0x850806+_0x3f2655;return _0x2231a6;}hi(0x1,0x2);
</code>```

As this only uses primitive functionality it can easily be reversed to

function hi(_0x850806, _0x3f2655) {
  const _0x2231a6 = _0x850806 + _0x3f2655;
  return _0x2231a6;
}
hi(0x1, 0x2);
```

<p>However, if you use some more complex functions (eg Array.includes). Like this</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function hi(first, arr) {
  if (arr.includes(first)) {
    console.log('true')
  } else {
    console.log('false')
  }
}

const res = hi(1, [1, 2, 3]);</code>```

This can be obfuscated to

const _0x41ab=['includes','log','true'];(function(_0x4972c4,_0x6d8a76){const _0x4e2cf3=function(_0x383eb3){while(--_0x383eb3){_0x4972c4['push'](_0x4972c4['shift']());}};_0x4e2cf3(++_0x6d8a76);}(_0x41ab,0x1d7));const _0x4ad9=function(_0x4972c4,_0x6d8a76){_0x4972c4=_0x4972c4-0x0;let _0x4e2cf3=_0x41ab[_0x4972c4];return _0x4e2cf3;};function hi(_0x5b3f5d,_0x577a76){if(_0x577a76[_0x4ad9('0x0')](_0x5b3f5d)){console['log'](_0x4ad9('0x2'));}else{console[_0x4ad9('0x1')]('false');}}const res=hi(0x1,[0x1,0x2,0x3]);
```

<p>After tidying it up you get this.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const _0x41ab = ['includes', 'log', 'true'];
(function(_0x4972c4, _0x6d8a76) {
  const _0x4e2cf3 = function(_0x383eb3) {
    while (--_0x383eb3) {
      _0x4972c4['push'](_0x4972c4['shift']());
    }
  };
  _0x4e2cf3(++_0x6d8a76);
}(_0x41ab, 0x1d7));
const _0x4ad9 = function(_0x4972c4, _0x6d8a76) {
  _0x4972c4 = _0x4972c4 - 0x0;
  let _0x4e2cf3 = _0x41ab[_0x4972c4];
  return _0x4e2cf3;
};

function hi(_0x5b3f5d, _0x577a76) {
  if (_0x577a76[_0x4ad9('0x0')](_0x5b3f5d)) {
    console['log'](_0x4ad9('0x2'));
  } else {
    console[_0x4ad9('0x1')]('false');
  }
}
const res = hi(0x1, [0x1, 0x2, 0x3]);</code>```

As you can see, this snippet will give the same output as the non-obfuscated code, however, is much harder to read.

Now imagine applying this to a big project and you see why it is almost impossible.

Body:
The point of obfuscating something is so it cant be reversed. It has stripped all names and minified intentionally to make it as hard as possible.

You can reverse it partially but it won't be very readable.

For example if you obfuscate this

function hi(first, second) {
  const third = first + second
  return third
}
hi(1, 2);

You will get something like this.

function hi(_0x850806,_0x3f2655){const _0x2231a6=_0x850806+_0x3f2655;return _0x2231a6;}hi(0x1,0x2);

As this only uses primitive functionality it can easily be reversed to

function hi(_0x850806, _0x3f2655) {
  const _0x2231a6 = _0x850806 + _0x3f2655;
  return _0x2231a6;
}
hi(0x1, 0x2);

However, if you use some more complex functions (eg Array.includes). Like this

function hi(first, arr) {
  if (arr.includes(first)) {
    console.log('true')
  } else {
    console.log('false')
  }
}

const res = hi(1, [1, 2, 3]);

This can be obfuscated to

const _0x41ab=['includes','log','true'];(function(_0x4972c4,_0x6d8a76){const _0x4e2cf3=function(_0x383eb3){while(--_0x383eb3){_0x4972c4['push'](_0x4972c4['shift']());}};_0x4e2cf3(++_0x6d8a76);}(_0x41ab,0x1d7));const _0x4ad9=function(_0x4972c4,_0x6d8a76){_0x4972c4=_0x4972c4-0x0;let _0x4e2cf3=_0x41ab[_0x4972c4];return _0x4e2cf3;};function hi(_0x5b3f5d,_0x577a76){if(_0x577a76[_0x4ad9('0x0')](_0x5b3f5d)){console['log'](_0x4ad9('0x2'));}else{console[_0x4ad9('0x1')]('false');}}const res=hi(0x1,[0x1,0x2,0x3]);

After tidying it up you get this.

const _0x41ab = ['includes', 'log', 'true'];
(function(_0x4972c4, _0x6d8a76) {
  const _0x4e2cf3 = function(_0x383eb3) {
    while (--_0x383eb3) {
      _0x4972c4['push'](_0x4972c4['shift']());
    }
  };
  _0x4e2cf3(++_0x6d8a76);
}(_0x41ab, 0x1d7));
const _0x4ad9 = function(_0x4972c4, _0x6d8a76) {
  _0x4972c4 = _0x4972c4 - 0x0;
  let _0x4e2cf3 = _0x41ab[_0x4972c4];
  return _0x4e2cf3;
};

function hi(_0x5b3f5d, _0x577a76) {
  if (_0x577a76[_0x4ad9('0x0')](_0x5b3f5d)) {
    console['log'](_0x4ad9('0x2'));
  } else {
    console[_0x4ad9('0x1')]('false');
  }
}
const res = hi(0x1, [0x1, 0x2, 0x3]);

As you can see, this snippet will give the same output as the non-obfuscated code, however, is much harder to read.

Now imagine applying this to a big project and you see why it is almost impossible.


问:
How to use pywinauto to set_text in python IDLE editor?
I want to control python IDLE with pywinauto.

I can start IDLE but cannot input text.

Here is my code:

```<code>import pywinauto
app = pywinauto.application.Application(backend="uia").start(r"C:\Python37\pythonw.exe C:\Python37\Lib\idlelib\idle.pyw")
app2 = pywinauto.application.Application().connect(process=app.process)
</code>```

I tried to use app2.Property.print_control_identifiers() but it returns:

```<code>Traceback (most recent call last):
  File "C:\Python37\lib\site-packages\pywinauto\application.py", line 256, in __resolve_control
    criteria)
  File "C:\Python37\lib\site-packages\pywinauto\timings.py", line 458, in wait_until_passes
    raise err

pywinauto.timings.TimeoutError

During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    app2.Property.print_control_identifiers()
  File "C:\Python37\lib\site-packages\pywinauto\application.py", line 595, in print_control_identifiers
    this_ctrl = self.__resolve_control(self.criteria)[-1]
  File "C:\Python37\lib\site-packages\pywinauto\application.py", line 259, in __resolve_control
    raise e.original_exception
  File "C:\Python37\lib\site-packages\pywinauto\timings.py", line 436, in wait_until_passes
    func_val = func(*args, **kwargs)
  File "C:\Python37\lib\site-packages\pywinauto\application.py", line 201, in __get_ctrl
    dialog = self.backend.generic_wrapper_class(findwindows.find_element(**criteria[0]))
  File "C:\Python37\lib\site-packages\pywinauto\findwindows.py", line 84, in find_element
    elements = find_elements(**kwargs)
  File "C:\Python37\lib\site-packages\pywinauto\findwindows.py", line 303, in find_elements
    elements = findbestmatch.find_best_control_matches(best_match, wrapped_elems)
  File "C:\Python37\lib\site-packages\pywinauto\findbestmatch.py", line 533, in find_best_control_matches
    raise MatchError(items = name_control_map.keys(), tofind = search_text)
pywinauto.findbestmatch.MatchError: Could not find 'Property' in 'dict_keys(['*Python 3.7.2 Shell*TkTopLevel', '*Python 3.7.2 Shell*', 'TkTopLevel'])'
</code>```

How to solve the problem?

Thank you.

答:
```<code>app = pywinauto.application.Application(backend="uia").start(r"C:\Python37\pythonw.exe C:\Python37\Lib\idlelib\idle.pyw")
app2 = pywinauto.application.Application().connect(process=app.process)
app3 = app2.top_window()
app3.print_control_identifiers()
</code>```

Body:
I want to control python IDLE with pywinauto.

I can start IDLE but cannot input text.

Here is my code:

import pywinauto
app = pywinauto.application.Application(backend="uia").start(r"C:\Python37\pythonw.exe C:\Python37\Lib\idlelib\idle.pyw")
app2 = pywinauto.application.Application().connect(process=app.process)

I tried to use app2.Property.print_control_identifiers() but it returns:

Traceback (most recent call last):
  File "C:\Python37\lib\site-packages\pywinauto\application.py", line 256, in __resolve_control
    criteria)
  File "C:\Python37\lib\site-packages\pywinauto\timings.py", line 458, in wait_until_passes
    raise err

pywinauto.timings.TimeoutError

During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    app2.Property.print_control_identifiers()
  File "C:\Python37\lib\site-packages\pywinauto\application.py", line 595, in print_control_identifiers
    this_ctrl = self.__resolve_control(self.criteria)[-1]
  File "C:\Python37\lib\site-packages\pywinauto\application.py", line 259, in __resolve_control
    raise e.original_exception
  File "C:\Python37\lib\site-packages\pywinauto\timings.py", line 436, in wait_until_passes
    func_val = func(*args, **kwargs)
  File "C:\Python37\lib\site-packages\pywinauto\application.py", line 201, in __get_ctrl
    dialog = self.backend.generic_wrapper_class(findwindows.find_element(**criteria[0]))
  File "C:\Python37\lib\site-packages\pywinauto\findwindows.py", line 84, in find_element
    elements = find_elements(**kwargs)
  File "C:\Python37\lib\site-packages\pywinauto\findwindows.py", line 303, in find_elements
    elements = findbestmatch.find_best_control_matches(best_match, wrapped_elems)
  File "C:\Python37\lib\site-packages\pywinauto\findbestmatch.py", line 533, in find_best_control_matches
    raise MatchError(items = name_control_map.keys(), tofind = search_text)
pywinauto.findbestmatch.MatchError: Could not find 'Property' in 'dict_keys(['*Python 3.7.2 Shell*TkTopLevel', '*Python 3.7.2 Shell*', 'TkTopLevel'])'

How to solve the problem?

Thank you.


问:
use appinsights in an on-premise web server
We would like to use appinsights to collect data for our on-premise sites.

I found an article https://unhandled.wordpress.com/2018/02/01/using-azure-application-insights-with-on-premises-servers/

which will install an old (2016) software (Application Insights Status Monitor).
Is it still the right way to use appinsight in an on-premise web server?

答:
There are two ways to instrument on-premise web server.

Option I: Use Status Monitor v2 to auto-instrument your application. No need to change code.

Option II: Add Application Insights SDK to your web application project. Redeploy your application.


问:
Server side singleton injection in Nuxt
I need a shared  object (e.g.cache/logger/service) instance (singleton) on serverside accessible to SS middleware/plugins/nuxtserverinit.

I have tried a local module which tries to inject $cache in serverside context during render:done hook (see below), but no matter what I tried it still was not available during SS request processing.

// modules/myCache.js
export default function(_moduleOptions,config) {

  this.nuxt.hook("render:before", context => {
     const cache=new myExoticCache()

// I tried all the below combinations
     context.nuxt.$cache1=cache
     context.serverContext.$cache2=cache
     context.options.$cache3=cache
     context.globals.$cache4=cache

  });

  this.nuxt.hook("render:done", context => {

// tried the above here too

  });
}

// plugins/myplug.js
export default ({serverContext,nuxt}, inject) => {
//all of the below are undefined
//nuxt.$cache
//serverContext.$cache

}
```

Seems like I am missing something. Would be great to find out what.
How can I pass value from route:done hook to any server-side middleware/plugin/nuxtserverinit.

答:
You can extend ssrContext from 'vue-renderer:ssr:prepareContext' hook.</p>

```<code>// modules/myCache.js
export default function(_moduleOptions) {
    const $cache = 'CACHE';
    this.nuxt.hook('vue-renderer:ssr:prepareContext', ssrContext => {
        ssrContext.$cache = $cache;
    })
}

// plugins/myplug.js
export default function ({ ssrContext }) {
    if (process.server) {
        console.log(ssrContext.$cache)
    }
}
</code>```

Title: Server side singleton injection in Nuxt

Body:
I need a shared  object (e.g.cache/logger/service) instance (singleton) on serverside accessible to SS middleware/plugins/nuxtserverinit.

I have tried a local module which tries to inject $cache in serverside context during render:done hook (see below), but no matter what I tried it still was not available during SS request processing.

// modules/myCache.js
export default function(_moduleOptions,config) {

  this.nuxt.hook("render:before", context => {
     const cache=new myExoticCache()

// I tried all the below combinations
     context.nuxt.$cache1=cache
     context.serverContext.$cache2=cache
     context.options.$cache3=cache
     context.globals.$cache4=cache

  });

  this.nuxt.hook("render:done", context => {

// tried the above here too

  });
}

// plugins/myplug.js
export default ({serverContext,nuxt}, inject) => {
//all of the below are undefined
//nuxt.$cache
//serverContext.$cache

}

Seems like I am missing something. Would be great to find out what.
How can I pass value from route:done hook to any server-side middleware/plugin/nuxtserverinit.

Body:
You can extend ssrContext from 'vue-renderer:ssr:prepareContext' hook.

// modules/myCache.js
export default function(_moduleOptions) {
    const $cache = 'CACHE';
    this.nuxt.hook('vue-renderer:ssr:prepareContext', ssrContext => {
        ssrContext.$cache = $cache;
    })
}

// plugins/myplug.js
export default function ({ ssrContext }) {
    if (process.server) {
        console.log(ssrContext.$cache)
    }
}


问:
Is this well defined code?
I'm still slightly confused after reading this topic. Is the following C++ expression *d++ = ~(*d); well defined? Yes, I know compound expressions like this are ugly.. I didn't write it.

I see a slight difference in the generated assembly when I compare it to:

```<code>*d = ~(*d);
d++;
</code>```

Assembly:

```<code>*d++ = ~(*d);
0x83384    LDR           R3,[R0 <d>,4]        <<diff
0x83388    ADD           R1 <c>, R1 <c>, 1
0x8338c    MVN           R3, R3
0x83390    STR           R3,[R0 <d>],4
</code>```

vs

```<code>*d = ~(*d);
d++;
0x83384   LDR           R3,[R0 <d>]
0x83388   ADD           R1 <c>, R1 <c>, 1
0x8338c   MVN           R3, R3
0x83390   STR           R3,[R0 <d>],4
</code>```

Thanks!

答:
You just do not know when the ++ gets evaluated. I suppose your compiler evaluates it before the ~(*d) which results in

```<code>*d = ~(*(d+1));
</code>```

thus your dicrepancy.

Title: Is this well defined code?

Body:
I'm still slightly confused after reading this topic. Is the following C++ expression *d++ = ~(*d); well defined? Yes, I know compound expressions like this are ugly.. I didn't write it.

I see a slight difference in the generated assembly when I compare it to:

*d = ~(*d);
d++;

Assembly:

*d++ = ~(*d);
0x83384    LDR           R3,[R0 <d>,4]        <<diff
0x83388    ADD           R1 <c>, R1 <c>, 1
0x8338c    MVN           R3, R3
0x83390    STR           R3,[R0 <d>],4

vs

*d = ~(*d);
d++;
0x83384   LDR           R3,[R0 <d>]
0x83388   ADD           R1 <c>, R1 <c>, 1
0x8338c   MVN           R3, R3
0x83390   STR           R3,[R0 <d>],4

Thanks!

Body:
You just do not know when the ++ gets evaluated. I suppose your compiler evaluates it before the ~(*d) which results in

*d = ~(*(d+1));

thus your dicrepancy.