问:
Grab an URL after a submit_form
I want to scrape the database of 'Peoples Daily', a Chinese newspaper. One way to get access to an archive from '47 - today is by the DFN (Deutsches Forschungsnetzwerk) and an valid crossasia.org account.

1.The first step is to choose your institution at https://login.erf.sbb.spk-berlin.de/hanshibboleth/login, which redirects you to the DFN webpage with a formular to select your institution.

Choose Crossasia.org (VHO)

This will redirect you to the login-page of crossasia.org

My problem is now the following :
I think I achieve the first step with the rvest package running the following code

```<code>require("rvest")
session <- html_session("https://login.erf.sbb.spk-berlin.de/hanshibboleth/login")

form <- html_form(session)[[1]]

form <- set_values(form,
                   user_idp = "CrossAsia.org (VHO)")
</code>```

If you repeat the first step in your browser the webpage redirects you immediately to CrossAsia.org, sadly it seems that this does not work in R. So here is my question :

How can I jump to the login-page or grab the URL of the login-page? Since the login-page seems to have session-specific token aswell, copy-paste the login-page link from your browser is not an option.

答:
Ok after playing around with the chrome dev-tool I found that using
https://sp.erf.sbb.spk-berlin.de/Shibboleth.sso/Login?SAMLDS=1&target=ss%3Amem%3A34f673898b5d4cb8f67f552c14c99ae1ed8d8e9185419b104896382fd711f1a2?user_idp=CrossAsia.org%20(VHO)&entityID=https%3A%2F%2Flogin.crossasia.org%2Fidp%2Fshibboleth directs you automatically to the login page. So case closed.

To give a more general answer :
Before I clicked on "Select" button of the page, I opened the 'network' tab of the dev-tool. Therefore just press Command+Option+C (Mac) or Control+Shift+C (Windows, Linux, Chrome OS). Then check the box "Preserve Log" so all interactions between sending the request and redirecting is logged. Afterwards just check the called links and try them in another browser (or delete your cache) to prevent that the result is just a cached version of the target webpage.

Title: Grab an URL after a submit_form

Body:
I want to scrape the database of 'Peoples Daily', a Chinese newspaper. One way to get access to an archive from '47 - today is by the DFN (Deutsches Forschungsnetzwerk) and an valid crossasia.org account.

1.The first step is to choose your institution at https://login.erf.sbb.spk-berlin.de/hanshibboleth/login, which redirects you to the DFN webpage with a formular to select your institution.

Choose Crossasia.org (VHO)

This will redirect you to the login-page of crossasia.org

My problem is now the following :
I think I achieve the first step with the rvest package running the following code

require("rvest")
session <- html_session("https://login.erf.sbb.spk-berlin.de/hanshibboleth/login")

form <- html_form(session)[[1]]

form <- set_values(form,
                   user_idp = "CrossAsia.org (VHO)")

If you repeat the first step in your browser the webpage redirects you immediately to CrossAsia.org, sadly it seems that this does not work in R. So here is my question :

How can I jump to the login-page or grab the URL of the login-page? Since the login-page seems to have session-specific token aswell, copy-paste the login-page link from your browser is not an option.


来源: stackexchange

问:
Incompatible peer dependencies found - upgrading Angular from 8 to 9
I am following the official document to upgrade.

This step completed without any errors.

```<code>ng update @angular/core@8 @angular/cli@8
</code>```

Next step failed.

```<code>ng update @angular/core @angular/cli
The installed Angular CLI version is older than the latest stable version.
Installing a temporary version to perform the update.
Installing packages for tooling via npm.
Installed packages for tooling via npm.
Using package manager: 'npm'
Collecting installed dependencies...
Found 45 dependencies.
Fetching dependency metadata from registry...
                  Package "@angular/core" has a missing peer dependency of "tslib" @ "^1.10.0".
                  Package "@angular/animations" has a missing peer dependency of "tslib" @ "^1.10.0".
                  Package "@angular/compiler" has a missing peer dependency of "tslib" @ "^1.10.0".
                  Package "@angular/forms" has a missing peer dependency of "tslib" @ "^1.10.0".
                  Package "@angular/common" has a missing peer dependency of "tslib" @ "^1.10.0".
                  Package "@angular/platform-browser" has a missing peer dependency of "tslib" @ "^1.10.0".
                  Package "@angular/compiler-cli" has a missing peer dependency of "tslib" @ "^1.10.0".
                  Package "@angular/router" has a missing peer dependency of "tslib" @ "^1.10.0".
                  Package "@angular/platform-browser-dynamic" has a missing peer dependency of "tslib" @ "^1.10.0".
                  Package "@ngtools/webpack" has an incompatible peer dependency to "typescript" (requires ">=3.4 < 3.6", would install "3.7.5").
Incompatible peer dependencies found.
Peer dependency warnings when installing dependencies means that those dependencies might not work correctly together.
You can use the '--force' option to ignore incompatible peer dependencies and instead address these warnings later.

</code>```

I checked the node_modules and the correct version of tslib is installed.
I manually added the tslib entry and ran npm install to see if the error goes away.

```<code>  "dependencies": {
    "@angular/animations": "^8.2.14",
    "@angular/common": "^8.2.14",
    "@angular/compiler": "^8.2.14",
    "@angular/core": "^8.2.14",
    "@angular/forms": "^8.2.14",
    "@angular/language-service": "^8.2.14",
    "@angular/platform-browser": "^8.2.14",
    "@angular/platform-browser-dynamic": "^8.2.14",
    "@angular/router": "^8.2.14",
    "@ng-bootstrap/ng-bootstrap": "^5.3.0",
    "classlist.js": "^1.1.20150312",
    "core-js": "^3.6.4",
    "npm": "^6.13.7",
    "rxjs": "^6.5.4",
    "web-animations-js": "^2.3.2",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/architect": "^0.803.25",
    "@angular-devkit/build-angular": "^0.803.25",
    "@angular-devkit/build-optimizer": "^0.803.25",
    "@angular-devkit/build-webpack": "^0.803.25",
    "@angular-devkit/core": "^8.3.25",
    "@angular-devkit/schematics": "^8.3.25",
    "@angular/cli": "^8.3.25",
    "@angular/compiler-cli": "^8.2.14",
    "@ngtools/webpack": "^8.3.25",
    "@schematics/angular": "^8.3.25",
    "@schematics/update": "^0.803.25",
    "@types/jasmine": "^3.5.4",
    "@types/jasminewd2": "^2.0.8",
    "@types/node": "^12.12.27",
    "tslib": "^1.10.0",
    "codelyzer": "^5.2.1",
    "jasmine-core": "^3.5.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "^4.4.1",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage-istanbul-reporter": "^2.1.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.5.2",
    "protractor": "^5.4.3",
    "rxjs-tslint": "^0.1.7",
    "ts-node": "^8.6.2",
    "tslint": "^5.20.1",
    "typescript": "~3.4",
    "webpack": "^4.41.6",
    "webpack-dev-server": "^3.10.3"
  }
</code>```

ng v output

```<code>Angular CLI: 8.3.25
Node: 12.13.0
OS: win32 x64
Angular: 8.2.14
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.803.24
@angular-devkit/build-angular     0.803.25
@angular-devkit/build-optimizer   0.803.24
@angular-devkit/build-webpack     0.803.25
@angular-devkit/core              8.3.24
@angular-devkit/schematics        8.3.24
@angular/cli                      8.3.25
@ngtools/webpack                  8.3.24
@schematics/angular               8.3.24
@schematics/update                0.803.24
rxjs                              6.5.4
typescript                        3.4.5
webpack                           4.41.5
</code>```

I haven't tried to use --force option. Is there another way?

答:
Looks like you glanced over one of the errors:

Package "@ngtools/webpack" has an incompatible peer dependency to "typescript" (requires ">=3.4 < 3.6", would install "3.7.5").

Try a lower version of @ngtools/webpack that works with TypeScript 3.4 to 3.5.

Alternatively, update your TypeScript version in the package.json to 3.7.5 and run npm update, then you should be able to update @angular/core & @angular/cli.

ContentLicense: CC BY-SA 4.0

Body:
I am following the official document to upgrade.

This step completed without any errors.

ng update @angular/core@8 @angular/cli@8

Next step failed.

ng update @angular/core @angular/cli
The installed Angular CLI version is older than the latest stable version.
Installing a temporary version to perform the update.
Installing packages for tooling via npm.
Installed packages for tooling via npm.
Using package manager: 'npm'
Collecting installed dependencies...
Found 45 dependencies.
Fetching dependency metadata from registry...
                  Package "@angular/core" has a missing peer dependency of "tslib" @ "^1.10.0".
                  Package "@angular/animations" has a missing peer dependency of "tslib" @ "^1.10.0".
                  Package "@angular/compiler" has a missing peer dependency of "tslib" @ "^1.10.0".
                  Package "@angular/forms" has a missing peer dependency of "tslib" @ "^1.10.0".
                  Package "@angular/common" has a missing peer dependency of "tslib" @ "^1.10.0".
                  Package "@angular/platform-browser" has a missing peer dependency of "tslib" @ "^1.10.0".
                  Package "@angular/compiler-cli" has a missing peer dependency of "tslib" @ "^1.10.0".
                  Package "@angular/router" has a missing peer dependency of "tslib" @ "^1.10.0".
                  Package "@angular/platform-browser-dynamic" has a missing peer dependency of "tslib" @ "^1.10.0".
                  Package "@ngtools/webpack" has an incompatible peer dependency to "typescript" (requires ">=3.4 < 3.6", would install "3.7.5").
Incompatible peer dependencies found.
Peer dependency warnings when installing dependencies means that those dependencies might not work correctly together.
You can use the '--force' option to ignore incompatible peer dependencies and instead address these warnings later.

I checked the node_modules and the correct version of tslib is installed.
I manually added the tslib entry and ran npm install to see if the error goes away.

  "dependencies": {
    "@angular/animations": "^8.2.14",
    "@angular/common": "^8.2.14",
    "@angular/compiler": "^8.2.14",
    "@angular/core": "^8.2.14",
    "@angular/forms": "^8.2.14",
    "@angular/language-service": "^8.2.14",
    "@angular/platform-browser": "^8.2.14",
    "@angular/platform-browser-dynamic": "^8.2.14",
    "@angular/router": "^8.2.14",
    "@ng-bootstrap/ng-bootstrap": "^5.3.0",
    "classlist.js": "^1.1.20150312",
    "core-js": "^3.6.4",
    "npm": "^6.13.7",
    "rxjs": "^6.5.4",
    "web-animations-js": "^2.3.2",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/architect": "^0.803.25",
    "@angular-devkit/build-angular": "^0.803.25",
    "@angular-devkit/build-optimizer": "^0.803.25",
    "@angular-devkit/build-webpack": "^0.803.25",
    "@angular-devkit/core": "^8.3.25",
    "@angular-devkit/schematics": "^8.3.25",
    "@angular/cli": "^8.3.25",
    "@angular/compiler-cli": "^8.2.14",
    "@ngtools/webpack": "^8.3.25",
    "@schematics/angular": "^8.3.25",
    "@schematics/update": "^0.803.25",
    "@types/jasmine": "^3.5.4",
    "@types/jasminewd2": "^2.0.8",
    "@types/node": "^12.12.27",
    "tslib": "^1.10.0",
    "codelyzer": "^5.2.1",
    "jasmine-core": "^3.5.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "^4.4.1",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage-istanbul-reporter": "^2.1.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.5.2",
    "protractor": "^5.4.3",
    "rxjs-tslint": "^0.1.7",
    "ts-node": "^8.6.2",
    "tslint": "^5.20.1",
    "typescript": "~3.4",
    "webpack": "^4.41.6",
    "webpack-dev-server": "^3.10.3"
  }

ng v output

Angular CLI: 8.3.25
Node: 12.13.0
OS: win32 x64
Angular: 8.2.14
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.803.24
@angular-devkit/build-angular     0.803.25
@angular-devkit/build-optimizer   0.803.24
@angular-devkit/build-webpack     0.803.25
@angular-devkit/core              8.3.24
@angular-devkit/schematics        8.3.24
@angular/cli                      8.3.25
@ngtools/webpack                  8.3.24
@schematics/angular               8.3.24
@schematics/update                0.803.24
rxjs                              6.5.4
typescript                        3.4.5
webpack                           4.41.5

I haven't tried to use --force option. Is there another way?


问:
Using javascript/jquery, is there a way to stop the rest of a webpage from loading until the header section is loaded?
I have a header (with a video inside), and the header is constructed using a plugin (I am on WordPress). When viewing the website on mobile, the header section takes some time to load, during which the rest of the content fills the empty space. When the header is finally loaded everything realigns as it should (the whole thing takes like 4 seconds).

However, the client prefers the rest of the page is loaded only after the header is there. Is there some javascript/jquery way of doing this that I am missing? Thank you.

Assume the page is constructed this way:

```<code><html>
<head>...</head>
<body>
<section class="header">...</section>
<section class="section1">...</section>
<section class="section2">...</section>
<section class="section3">...</section>
</body>
</html>
</code>```

答:
How about this?</p>

```<code>$(".header").ready(function(){
  $(".section1).show();
  $(".section2).show();
  $(".section3).show();
})
</code>```

Body:
I have a header (with a video inside), and the header is constructed using a plugin (I am on WordPress). When viewing the website on mobile, the header section takes some time to load, during which the rest of the content fills the empty space. When the header is finally loaded everything realigns as it should (the whole thing takes like 4 seconds).

However, the client prefers the rest of the page is loaded only after the header is there. Is there some javascript/jquery way of doing this that I am missing? Thank you.

Assume the page is constructed this way:

...

...

...

...

...

Body:
How about this?

$(".header").ready(function(){
  $(".section1).show();
  $(".section2).show();
  $(".section3).show();
})


问:
How would I write an algorithm to find the greatest jump from number to number in a sequence?
If your sequence is 4 2 1, the largest jump is from 4 to 2. If your sequence is 3 10 5 16 8 4 2 1, the largest jump is from 5 to 16.

I've made an algorithm however I'm not completely sure what I have done wrong (whever I haven't made the loop properly, set my variables correctly, or something else). I'm not sure what I need to set my index, BiggestDiff, or CurrentDiff too. I tried using a while loop to compare each number in my vector but I get zero (I'm assuming because I set BiggestDiff to zero)

If anyone can point me in the right direction, show me an example, or something else, that will be greatly appreciated.

Here is my code below

```<code>int findBiggestDiff(std::vector<int> sequence)
{
  int index = 0;
  int BiggestDiff = 0 ;
  int CurrentDiff = BiggestDiff;
  CurrentDiff = std::abs(sequence[index] - sequence[index + 1]);
  while (index < sequence.size())
  {
    if (CurrentDiff > BiggestDiff)
    {
      BiggestDiff = CurrentDiff;
    }

    return index;
  }
}
</code>```

答:
You aren't recalculating CurrentDiff at all. Also, your return statement in the in the wrong spot. You can do something like this (not tested)

```<code>int findLargest( const std::vector<int> &sequence ) {
  if ( sequence.size() < 2 ) return -1; // if there's not at least two elements, there's nothing valid.
  int index = 0;
  int biggestIndex = -1;
  int biggestDiff = -1;

  while (index < sequence.size() - 1) // -1 so that the +1 below doesn't go out of range
  {
    // get the current difference
    int currentDiff = std::abs(sequence[index] - sequence[index + 1]);
    if (currentDiff > biggestDiff)
    {
       // update stats
       biggestIndex = index;
       biggestDiff = currentDiff;
    }
    ++index;
  }
  return biggestIndex
}

int main() {
   //…
   int index = findLargest( sequence );
   if ( index != -1 ) {
       std::cout << "Biggest difference was between " << sequence[index] << " and " << sequence[index+1];
   }
}
</code>```

Body:
If your sequence is 4 2 1, the largest jump is from 4 to 2. If your sequence is 3 10 5 16 8 4 2 1, the largest jump is from 5 to 16.

I've made an algorithm however I'm not completely sure what I have done wrong (whever I haven't made the loop properly, set my variables correctly, or something else). I'm not sure what I need to set my index, BiggestDiff, or CurrentDiff too. I tried using a while loop to compare each number in my vector but I get zero (I'm assuming because I set BiggestDiff to zero)

If anyone can point me in the right direction, show me an example, or something else, that will be greatly appreciated.

Here is my code below

int findBiggestDiff(std::vector<int> sequence)
{
  int index = 0;
  int BiggestDiff = 0 ;
  int CurrentDiff = BiggestDiff;
  CurrentDiff = std::abs(sequence[index] - sequence[index + 1]);
  while (index < sequence.size())
  {
    if (CurrentDiff > BiggestDiff)
    {
      BiggestDiff = CurrentDiff;
    }

    return index;
  }
}

Body:
You aren't recalculating CurrentDiff at all. Also, your return statement in the in the wrong spot. You can do something like this (not tested)

int findLargest( const std::vector<int> &sequence ) {
  if ( sequence.size() < 2 ) return -1; // if there's not at least two elements, there's nothing valid.
  int index = 0;
  int biggestIndex = -1;
  int biggestDiff = -1;

  while (index < sequence.size() - 1) // -1 so that the +1 below doesn't go out of range
  {
    // get the current difference
    int currentDiff = std::abs(sequence[index] - sequence[index + 1]);
    if (currentDiff > biggestDiff)
    {
       // update stats
       biggestIndex = index;
       biggestDiff = currentDiff;
    }
    ++index;
  }
  return biggestIndex
}

int main() {
   //…
   int index = findLargest( sequence );
   if ( index != -1 ) {
       std::cout << "Biggest difference was between " << sequence[index] << " and " << sequence[index+1];
   }
}


问:
Printing long strings in C# with Graphics.DrawString
Good morning.
I have to print some long strings that falls off the margins of my page. I'm not able to split automatically as a multi-line string.

```<code>private void pd_PrintPage(object sender, PrintPageEventArgs ev)
{
  ...
  string line ="Condimentum a a ac aenean parturient risus suscipit et orci scelerisque convallis porttitor enim venenatis viverra.Egestas nibh natoque mus etiam a parturient feugiat hendrerit a sagittis viverra dui ante varius lectus arcu."
  float leftMargin = ev.MarginBounds.Left;
  float topMargin = ev.MarginBounds.Top;
  ev.Graphics.DrawString(line, printFont, Brushes.Black, new RectangleF(leftMargin, yPos, 400.0f, 200.0f));
  ...
}
</code>```

I tried using the overload with the bounding box specification, as you can see, but the result is a jam of chars on the page, because the lines from the long string is printed over itself.

Is there a quick way to solve this problem?

Thanks

答:
SOLVED
I finally solved my problem. It's not so easy to explain how, so I post here a piece of code that shows what I did:

```<code>private void pd_PrintPage(object sender, PrintPageEventArgs ev)
    {
        float linesPerPage = 0;
        int count = 0;
        float leftMargin = ev.MarginBounds.Left;
        float topMargin = ev.MarginBounds.Top;
        float printAreaHeight = ev.MarginBounds.Height;
        float printAreaWidth = ev.MarginBounds.Width;
        string line = null;
        float yPos = topMargin;

        int charactersFitted = 0;
        int linesFilled = 0;
        SizeF theSize = new SizeF();
        Font printFont = new Font("Arial", 12, FontStyle.Regular);

        SizeF layoutSize = new SizeF(printAreaWidth, printAreaHeight);

        // Calculate the number of lines per page.
        linesPerPage = printAreaHeight / printFont.GetHeight(ev.Graphics);

        // Print each line of the array.
        while (count < linesPerPage && lineIdx < linesArray.Count())
        {
            line = linesArray[lineIdx++];
            theSize = ev.Graphics.MeasureString(line, printFont, layoutSize, new StringFormat(), out charactersFitted, out linesFilled);
            ev.Graphics.DrawString(line, printFont, Brushes.Black, new RectangleF(50.0F, yPos, theSize.Width, theSize.Height));
            yPos += (1 + linesFilled) * printFont.GetHeight(ev.Graphics);
            count += linesFilled + 1;
         }

         // If more lines exist, print another page.
         if (count > linesPerPage)
            ev.HasMorePages = true;
         else
            ev.HasMorePages = false;
    }
</code>```

Body:
Good morning.
I have to print some long strings that falls off the margins of my page. I'm not able to split automatically as a multi-line string.

private void pd_PrintPage(object sender, PrintPageEventArgs ev)
{
  ...
  string line ="Condimentum a a ac aenean parturient risus suscipit et orci scelerisque convallis porttitor enim venenatis viverra.Egestas nibh natoque mus etiam a parturient feugiat hendrerit a sagittis viverra dui ante varius lectus arcu."
  float leftMargin = ev.MarginBounds.Left;
  float topMargin = ev.MarginBounds.Top;
  ev.Graphics.DrawString(line, printFont, Brushes.Black, new RectangleF(leftMargin, yPos, 400.0f, 200.0f));
  ...
}

I tried using the overload with the bounding box specification, as you can see, but the result is a jam of chars on the page, because the lines from the long string is printed over itself.

Is there a quick way to solve this problem?

Thanks

Body:
SOLVED
I finally solved my problem. It's not so easy to explain how, so I post here a piece of code that shows what I did:

private void pd_PrintPage(object sender, PrintPageEventArgs ev)
    {
        float linesPerPage = 0;
        int count = 0;
        float leftMargin = ev.MarginBounds.Left;
        float topMargin = ev.MarginBounds.Top;
        float printAreaHeight = ev.MarginBounds.Height;
        float printAreaWidth = ev.MarginBounds.Width;
        string line = null;
        float yPos = topMargin;

        int charactersFitted = 0;
        int linesFilled = 0;
        SizeF theSize = new SizeF();
        Font printFont = new Font("Arial", 12, FontStyle.Regular);

        SizeF layoutSize = new SizeF(printAreaWidth, printAreaHeight);

        // Calculate the number of lines per page.
        linesPerPage = printAreaHeight / printFont.GetHeight(ev.Graphics);

        // Print each line of the array.
        while (count < linesPerPage && lineIdx < linesArray.Count())
        {
            line = linesArray[lineIdx++];
            theSize = ev.Graphics.MeasureString(line, printFont, layoutSize, new StringFormat(), out charactersFitted, out linesFilled);
            ev.Graphics.DrawString(line, printFont, Brushes.Black, new RectangleF(50.0F, yPos, theSize.Width, theSize.Height));
            yPos += (1 + linesFilled) * printFont.GetHeight(ev.Graphics);
            count += linesFilled + 1;
         }

         // If more lines exist, print another page.
         if (count > linesPerPage)
            ev.HasMorePages = true;
         else
            ev.HasMorePages = false;
    }


问:
TypeError at /account/ sequence item 1: expected a bytes-like object, NoneType found
I am trying to get a progress bar to load as per the instructions here.

At the moment this is my view.

```<code>def progress_view(request):
count_pag = 200
result = hello.tasks.my_task(8,request).delay(1)
context = {'task_id': result.task_id}
return render(request, 'display_progress.html', context={'task_id': result})
</code>```

This is my tasks.py

```<code>@shared_task(bind=True)
def my_task(self, seconds, request):
   progress_recorder = ProgressRecorder(self)
   result = 0
   for i in range(seconds):
      time.sleep(1)
      result += i
      progress_recorder.set_progress(i + 1, seconds)
   return result
</code>```

There is no problem when i remove the 'request' input. But i need some sort of extra input into the function in order to do the processing i want. How to add extra inputs to the 'my_task' function without giving a traceback like below???

```<code>Traceback:

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
35.             response = get_response(request)

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
128.                 response = self.process_exception_by_middleware(e, request)

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/alvintung/rndtwitr/hello/views.py" in account
22.             return progress_view(request)

File "/Users/alvintung/rndtwitr/hello/views.py" in progress_view
33.     result = hello.tasks.my_task(8,request).delay(1)

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/celery.
/local.py" in __call__
191.         return self._get_current_object()(*a, **kw)

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/celery/app/task.py" in __call__
375.             return self.run(*args, **kwargs)

File "/Users/alvintung/rndtwitr/hello/tasks.py" in my_task
27.         progress_recorder.set_progress(i + 1, seconds)

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/celery_progress/backend.py" in set_progress
40.                 'description': description

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/celery/app/task.py" in update_state
892.         self.backend.store_result(task_id, meta, state)

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/celery/backends/base.py" in store_result
322.                            request=request, **kwargs)

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/celery/backends/base.py" in _store_result
664.         self.set(self.get_key_for_task(task_id), self.encode(meta))

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/celery/backends/base.py" in get_key_for_task
 570.             self.task_keyprefix, key_t(task_id), key_t(key),

Exception Type: TypeError at /account/
Exception Value: sequence item 1: expected a bytes-like object, NoneType found
</code>```

答:
You don't need to call task function directly. To run it in a background you should use delay() and provide arguments there:

```<code>def progress_view(request):
    count_pag = 200
    result = hello.tasks.my_task.delay(8, request.POST.get("extra_data"))  # assuming POST body contains extra_data input
    context = {'task_id': result.task_id}
    return render(request, 'display_progress.html', context={'task_id': result})
</code>```

Also note that arguments you are passing to celery task should be serializable. So you cannot pass full request object to the task. You shoud use requred data from POST body:

```<code>@shared_task(bind=True)
def my_task(self, seconds, extra_data):
   print(extra_data) # data from request body
   progress_recorder = ProgressRecorder(self)
   result = 0
   for i in range(seconds):
      time.sleep(1)
      result += i
      progress_recorder.set_progress(i + 1, seconds)
   return result
</code>```

Body:
I am trying to get a progress bar to load as per the instructions here.

At the moment this is my view.

def progress_view(request):
count_pag = 200
result = hello.tasks.my_task(8,request).delay(1)
context = {'task_id': result.task_id}
return render(request, 'display_progress.html', context={'task_id': result})

This is my tasks.py

@shared_task(bind=True)
def my_task(self, seconds, request):
   progress_recorder = ProgressRecorder(self)
   result = 0
   for i in range(seconds):
      time.sleep(1)
      result += i
      progress_recorder.set_progress(i + 1, seconds)
   return result

There is no problem when i remove the 'request' input. But i need some sort of extra input into the function in order to do the processing i want. How to add extra inputs to the 'my_task' function without giving a traceback like below???

Traceback:

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
35.             response = get_response(request)

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
128.                 response = self.process_exception_by_middleware(e, request)

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/alvintung/rndtwitr/hello/views.py" in account
22.             return progress_view(request)

File "/Users/alvintung/rndtwitr/hello/views.py" in progress_view
33.     result = hello.tasks.my_task(8,request).delay(1)

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/celery.
/local.py" in __call__
191.         return self._get_current_object()(*a, **kw)

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/celery/app/task.py" in __call__
375.             return self.run(*args, **kwargs)

File "/Users/alvintung/rndtwitr/hello/tasks.py" in my_task
27.         progress_recorder.set_progress(i + 1, seconds)

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/celery_progress/backend.py" in set_progress
40.                 'description': description

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/celery/app/task.py" in update_state
892.         self.backend.store_result(task_id, meta, state)

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/celery/backends/base.py" in store_result
322.                            request=request, **kwargs)

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/celery/backends/base.py" in _store_result
664.         self.set(self.get_key_for_task(task_id), self.encode(meta))

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/celery/backends/base.py" in get_key_for_task
 570.             self.task_keyprefix, key_t(task_id), key_t(key),

Exception Type: TypeError at /account/
Exception Value: sequence item 1: expected a bytes-like object, NoneType found

Body:
You don't need to call task function directly. To run it in a background you should use delay() and provide arguments there:

def progress_view(request):
    count_pag = 200
    result = hello.tasks.my_task.delay(8, request.POST.get("extra_data"))  # assuming POST body contains extra_data input
    context = {'task_id': result.task_id}
    return render(request, 'display_progress.html', context={'task_id': result})

Also note that arguments you are passing to celery task should be serializable. So you cannot pass full request object to the task. You shoud use requred data from POST body:

@shared_task(bind=True)
def my_task(self, seconds, extra_data):
   print(extra_data) # data from request body
   progress_recorder = ProgressRecorder(self)
   result = 0
   for i in range(seconds):
      time.sleep(1)
      result += i
      progress_recorder.set_progress(i + 1, seconds)
   return result


问:
How is malware removed from binary executeables?
The malware museum has samples of DOS virusses, but surprisingly without the malware payload, only the visual effects such as the LSD remain.

How exactly has the malicous code been removed from the malware samples? “sterilized malware”

答: The malware videos you see on the webpage is running in an emulator, the downloaded ZIP file contains the real malicious sample, do not execute them on your machine ;)


问:
Bootstrap 3.4.0 includes breaking changes?
Does anybody of you know, whether Bootstrap 3.4.0 includes breaking changes (in comparison to 3.3.x)? The following document does not state one or the other:
https://blog.getbootstrap.com/2018/12/13/bootstrap-3-4-0/

Kind Regards,
Mark

答:
I found two clues, that might suggest the correct answer:

Bootstrap promises to follow the Semantic Versioning standard: https://github.com/twbs/bootstrap#versioning

The Upgrade documentation does not include any instructions specifically for version 3.3: https://getbootstrap.com/docs/3.4/migration/


问:
How to type an autocurry in TypeScript
I'm trying to write types for the following function:

const curry = (
  f, arr = []
) => (...args) => (
  a => a.length >= f.length ?
    f(...a) :
    curry(f, a)
)([...arr, ...args]);
```

<p>I found this neat article that created a type for <code>curry</code> like this:</p>

```type Head<T extends any[]> =
  T extends [any, ...any[]]
  ? T[0]
  : never;

type Tail<T extends any[]> =
  ((...t: T) => any) extends ((_: any, ...tail: infer TT) => any)
  ? TT
  : [];

type HasTail<T extends any[]> =
  T extends ([] | [any])
  ? false
  : true;

type Curry
 =
  (arg: Head
) => HasTail
 extends true
  ? Curry<Tail
, R>
  : R;
```

My problem is, this Curry type's signature does not match my curry function's (or are my TypeScript skills to bad and it does?). Additionally, I can't figure out how to write an implementation for curry that matches the Curry type.

How would one implement the types for my curry? And how would an implementation look like that uses the Curry type?

答:
One major caveat here: Function.length is weird; it's only going to behave well for functions without default or rest arguments.  For example, depending on what version of JS your TS compiler is targeting, you could get different answers for the following code:

```<code>console.log(((arg = 1) => { }).length); // 0? 1?
</code>```

So keep that in mind when you use anything that depends on runtime reflection of function argument length.

Your curry() function is assignable to the Curry type definition, but not vice versa.  The Curry type definition expects exactly one argument each time it is called if the underlying function still needs arguments, whereas your curry will accept any number of arguments when it's called.  That means we can give curry() the Curry type, but the compiler will limit the number of arguments you call it with.  It could look like this:

```<code>function curry<P extends any[], R>(f: (...args: P) => R): Curry<Required<P>, R> {
  const _curry = (
    f: (...args: any) => any, arr: any[] = []
  ) => (...args: any) => (
    a => a.length >= f.length ?
      f(...a) :
      _curry(f, a)
  )([...arr, ...args]);
  return _curry(f);
}
</code>```

Here we are essentially giving up on having the compiler do any real type checking inside the implementation; everything inside is more or less of the anytype.  You might be able to get a little better type safety in there but not much; the compiler will not be able to verify the manipulations involved in appending to the end of a tuple type, and you'd end up using type assertions everywhere.

The Required
 bit might not be necessary; it just depends on what you want to see happen for functions with optional arguments.  In general I'd be really careful using this on any functions of union types or whose argument lists can be different lengths, etc.

Let's just make sure the compiler is happy with a normal usage:

```<code>function test(x: string, y: number, z: boolean) {
  return z ? x : y;
}

const t0 = curry(test);
const t1 = t0("abc");
const t2 = t1(123);
const t3 = t2(true);
console.log(t3); // abc
const t4 = t2(false);
console.log(t4); // 123
</code>```

Looks good.

As for how you would make a TS typing for the full possibly-multiple-args-at-a-time version of curry(), it requires type level tuple concatenation, which is not currently directly supported (see microsoft/TypeScript#5453).  You can write something that works involving recursive conditional types, but since recursive types are also not directly supported (see microsoft/TypeScript#26980), I wouldn't recommend them for production systems.

Or you could pick some maximum length to support, like say, three arguments at a time, and write an version of Curry that works for that, but I don't know if it's really worth it:

```<code>type Curry3<P extends any[], R> = P extends [] ? R : (
  ((a0: Head<P>) => Curry3<Tail<P>, R>) & (
    P extends [any] ? unknown : (
      ((a0: Head<P>, a1: Head<Tail<P>>) => Curry3<Tail<Tail<P>>, R>) & (
        P extends [any, any] ? unknown : (
          ((a0: Head<P>, a1: Head<Tail<P>>, a2: Head<Tail<Tail<P>>>) =>
            Curry3<Tail<Tail<Tail<P>>>, R>)
        )
      )
    )
  )
);
</code>```

especially because that particular definition uses overloads which might not play nicely everywhere.

Anyway, hope that helps; good luck!

Playground link to code

Title: How to type an autocurry in TypeScript

Body:
I'm trying to write types for the following function:

const curry = (
  f, arr = []
) => (...args) => (
  a => a.length >= f.length ?
    f(...a) :
    curry(f, a)
)([...arr, ...args]);

I found this neat article that created a type for curry like this:

type Head<T extends any[]> =
  T extends [any, ...any[]]
  ? T[0]
  : never;

type Tail<T extends any[]> =
  ((...t: T) => any) extends ((_: any, ...tail: infer TT) => any)
  ? TT
  : [];

type HasTail<T extends any[]> =
  T extends ([] | [any])
  ? false
  : true;

type Curry
 =
  (arg: Head
) => HasTail
 extends true
  ? Curry<Tail
, R>
  : R;

My problem is, this Curry type's signature does not match my curry function's (or are my TypeScript skills to bad and it does?). Additionally, I can't figure out how to write an implementation for curry that matches the Curry type.

How would one implement the types for my curry? And how would an implementation look like that uses the Curry type?

Body:
One major caveat here: Function.length is weird; it's only going to behave well for functions without default or rest arguments.  For example, depending on what version of JS your TS compiler is targeting, you could get different answers for the following code:

console.log(((arg = 1) => { }).length); // 0? 1?

So keep that in mind when you use anything that depends on runtime reflection of function argument length.

Your curry() function is assignable to the Curry type definition, but not vice versa.  The Curry type definition expects exactly one argument each time it is called if the underlying function still needs arguments, whereas your curry will accept any number of arguments when it's called.  That means we can give curry() the Curry type, but the compiler will limit the number of arguments you call it with.  It could look like this:

function curry<P extends any[], R>(f: (...args: P) => R): Curry<Required<P>, R> {
  const _curry = (
    f: (...args: any) => any, arr: any[] = []
  ) => (...args: any) => (
    a => a.length >= f.length ?
      f(...a) :
      _curry(f, a)
  )([...arr, ...args]);
  return _curry(f);
}

Here we are essentially giving up on having the compiler do any real type checking inside the implementation; everything inside is more or less of the anytype.  You might be able to get a little better type safety in there but not much; the compiler will not be able to verify the manipulations involved in appending to the end of a tuple type, and you'd end up using type assertions everywhere.

The Required<P> bit might not be necessary; it just depends on what you want to see happen for functions with optional arguments.  In general I'd be really careful using this on any functions of union types or whose argument lists can be different lengths, etc.

Let's just make sure the compiler is happy with a normal usage:

function test(x: string, y: number, z: boolean) {
  return z ? x : y;
}

const t0 = curry(test);
const t1 = t0("abc");
const t2 = t1(123);
const t3 = t2(true);
console.log(t3); // abc
const t4 = t2(false);
console.log(t4); // 123

Looks good.

As for how you would make a TS typing for the full possibly-multiple-args-at-a-time version of curry(), it requires type level tuple concatenation, which is not currently directly supported (see microsoft/TypeScript#5453).  You can write something that works involving recursive conditional types, but since recursive types are also not directly supported (see microsoft/TypeScript#26980), I wouldn't recommend them for production systems.

Or you could pick some maximum length to support, like say, three arguments at a time, and write an version of Curry that works for that, but I don't know if it's really worth it:

type Curry3<P extends any[], R> = P extends [] ? R : (
  ((a0: Head<P>) => Curry3<Tail<P>, R>) & (
    P extends [any] ? unknown : (
      ((a0: Head<P>, a1: Head<Tail<P>>) => Curry3<Tail<Tail<P>>, R>) & (
        P extends [any, any] ? unknown : (
          ((a0: Head<P>, a1: Head<Tail<P>>, a2: Head<Tail<Tail<P>>>) =>
            Curry3<Tail<Tail<Tail<P>>>, R>)
        )
      )
    )
  )
);

especially because that particular definition uses overloads which might not play nicely everywhere.

Anyway, hope that helps; good luck!

<a href="https://www.typescriptlang.org/play/#code/C4TwDgpgBAEhCGATAPAFShAHsCA7RAzlPLiANoC6AfFALwBQUU6WO+RZJIANFAHQCulCoygB+ZmQAMIpgC4ouCADcIAJwDc9eqEjN4ASwA2aDNjyFipSjQZMAFPYF9gC1AEo6NLp9YWijgD6Cly8zsCGRgoGuABm6sweXlYg7qISqKiiCpRaOuDQMPAEqJGmfuwpNnSiLOaV9pRQAD5QnKQUaUwSsfBGBBDZUMBqAK4QebrQAMKjamogyAAKZmyWQhS8AEq2ovbwagDmCnBIy1SetDRFJWVLNBWWI+Oi3VCz84ulxufbVK9QBRbPIAYwA9rgCGCjBA+EYwYdHPsjnQoABGS40ADeUAAvu44XhDsAABZdfJ6D4LADMy1W-iqmygO1RK0eHAo4mZgKg9j2+ykJwQKHumPecxpaDuVD+ngAZLyAWz6pZ2iBORJRrgANa4MEAd1wPL5TFNvIFQrO9148DRlpQ3xM9wuySpIFpjqlP2dsqgCpNZtNyrWHFCKQ1UC1uoNRoUAcDpsc8EFsGFv2IdtTZ09PuIACZ7V6TDmqKXMQCE0w3R6yp6S6XZRXTV1Ay2mC20u48vRYlqQcADBCoCCJYtgwyNn97LE484DocCAolmKtu4FG7kFsIABHUYGNQQEUy5nY0TgyHAKCBEefVHxqAz3lzo6LlJisMHNQhayc2htWRQGKTiCC+36pMk97wMk8CErgxIklAVB-rEsHweITaxMBfDwJ4chNteo7TjaHaNM+ahhCBC6dFoTAHsAcxGgRnzTl29C4toPZ9gOQ44AQwD2JgCh8WoMSHLwIAKLgowALYAEbqLwABeCiyWC0IILgnhYqIdEMVAilcpgPIgFo7HaOefHDFIqI3gs9i8cArEWZewBoqiwBSPYABE8CySCXlORClnAHm7lovYaJ5tSgUXsM1LuXm9ljBAMVQjCcIIvZ0UaFAAD0uXEH59DOcMAAsCXTn0AypepGWIsApVdnlBWRdSHG9rg-aDkaUJqMAADyuBoFQyJfpITLSfAYBxoJzBisJoktIoMnyeRUCIBABAghYoliCpakwiQWk6RA9FqEan58L1-ECeJYraWaJXSUZf6TWAAmsY9QWXtJICom99ipDRpq6edvLPVAyBQL9XIALRuQoMNQxDEgI1AUieAAVLyG1bTtcFw2jGLA-ipkcdoQA" rel="nofollow noreferrer">Playground link to code


问:
How to stop server side processing when user clicks browser stop button (ASP.net C#)
I remember I could easily do this in PHP but can't seem to find an answer for ASP.Net. I have a web app that connects to Pop3 server to download emails when a user clicks a button or at set intervals. This process can take a very long time to finish depending on the number of emails to be downloaded. I noticed that when I click the browser stop button the process still continues to download emails preventing the user from navigating to another page. I have tried Response.IsClientConnected property but it doesn't seem to be working.

Any help would be highly appreciated.

答: You can't. The stop button in the browser will only stop rendering the response. The server however, will keep building the response till it's complete.</p>

ContentLicense: CC BY-SA 3.0


问:
Docker + Node.js + Windows
What I want: dockerize a Node.js web app (I am on Windows)

Windows container

docker-compose up gets me this error:

```<code>Service 'webapp' failed to build: no matching manifest for windows/amd64 in the manifest list entries
</code>```

As far as I understand that is because there is no Node.js image for windows, and a fix would be to switch to Linux container.

Not enough memory

When I try to switch to a linux container, Docker tells me that I don't have enough memory. Changing the amount of allocated memory through the settings does not fix it.

Edit: files

docker-compose

```<code>version: '3'

services:
  webapp:
    build: ./Front
    volumes:
      - ./Front:./dockerized
    ports:
     - 5001:8080
</code>```

Dockerfile:

```<code>FROM node:alpine

RUN mkdir -p ../dockerized

WORKDIR ../dockerized

COPY package*.json ../dockerized

RUN npm install

COPY . ../dockerized

EXPOSE 8080
CMD [ "npm", "start" ]
</code>```

答:
I was able to successfully deploy and run this by changing the Dockerfile as follows...</p>

```<code>FROM mcr.microsoft.com/windows/servercore:1803 as installer

SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop';$ProgressPreference='silentlyContinue';"]

RUN Invoke-WebRequest -OutFile nodejs.zip -UseBasicParsing "https://nodejs.org/dist/v12.4.0/node-v12.4.0-win-x64.zip"; Expand-Archive nodejs.zip -DestinationPath C:\; Rename-Item "C:\\node-v12.4.0-win-x64" c:\nodejs

FROM mcr.microsoft.com/windows/nanoserver:1803

WORKDIR C:/nodejs
COPY --from=installer C:/nodejs/ .
RUN SETX PATH C:\nodejs
RUN npm config set registry https://registry.npmjs.org/
</code>```

Title: Docker + Node.js + Windows

Body:
What I want: dockerize a Node.js web app (I am on Windows)

Windows container

docker-compose up gets me this error:

Service 'webapp' failed to build: no matching manifest for windows/amd64 in the manifest list entries

As far as I understand that is because there is no Node.js image for windows, and a fix would be to switch to Linux container.

Not enough memory

When I try to switch to a linux container, Docker tells me that I don't have enough memory. Changing the amount of allocated memory through the settings does not fix it.

Edit: files

docker-compose

version: '3'

services:
  webapp:
    build: ./Front
    volumes:
      - ./Front:./dockerized
    ports:
     - 5001:8080

Dockerfile:

FROM node:alpine

RUN mkdir -p ../dockerized

WORKDIR ../dockerized

COPY package*.json ../dockerized

RUN npm install

COPY . ../dockerized

EXPOSE 8080
CMD [ "npm", "start" ]

Body:
I was able to successfully deploy and run this by changing the Dockerfile as follows...

FROM mcr.microsoft.com/windows/servercore:1803 as installer

SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop';$ProgressPreference='silentlyContinue';"]

RUN Invoke-WebRequest -OutFile nodejs.zip -UseBasicParsing "https://nodejs.org/dist/v12.4.0/node-v12.4.0-win-x64.zip"; Expand-Archive nodejs.zip -DestinationPath C:\; Rename-Item "C:\\node-v12.4.0-win-x64" c:\nodejs

FROM mcr.microsoft.com/windows/nanoserver:1803

WORKDIR C:/nodejs
COPY --from=installer C:/nodejs/ .
RUN SETX PATH C:\nodejs
RUN npm config set registry https://registry.npmjs.org/


问:
How to get SKU Number
What is a SKU Number and how do I get my application one for the appstore?</p>

答: Since there are already a couple answers on what it is, here's where to find it

Title: How to get SKU Number


问:
knex: the operator "undefined" is not permitted
im trying to use knex in nodejs whith a where that receive from a param, but the message 'TypeError: The operator "undefined" is not permitted' is showing, this is a part of my code and the console out

```<code>async retrieve(where, fields) {
    console.log(where);
    var _this = this;
    return new Promise((resolve, reject) => {
        //si no tengo where lo pongo como objeto vacio
        where = where || {};
        //si no tengo fields cojo los de defecto del schema
        if(!fields){
            fields = Object.keys(_this.schema.properties).map((key) => {
                return key;
            });
        }
        //selecciono
        console.log('este es el where justo antes de knex', where);
        _this.connection(_this.table)
        .where(where)
        .select(fields)
        .then((rows) => {
            resolve(rows);
        })
        .catch((error) => {
            console.log(error);
            reject(GlobalMessages.db.dbError);
        });
    });
}
</code>```

答: Please check this thing: where = where || {}; I've got the same error if passed a raw string instead the object.

Body:
im trying to use knex in nodejs whith a where that receive from a param, but the message 'TypeError: The operator "undefined" is not permitted' is showing, this is a part of my code and the console out

async retrieve(where, fields) {
    console.log(where);
    var _this = this;
    return new Promise((resolve, reject) => {
        //si no tengo where lo pongo como objeto vacio
        where = where || {};
        //si no tengo fields cojo los de defecto del schema
        if(!fields){
            fields = Object.keys(_this.schema.properties).map((key) => {
                return key;
            });
        }
        //selecciono
        console.log('este es el where justo antes de knex', where);
        _this.connection(_this.table)
        .where(where)
        .select(fields)
        .then((rows) => {
            resolve(rows);
        })
        .catch((error) => {
            console.log(error);
            reject(GlobalMessages.db.dbError);
        });
    });
}


问:
How to increase visualizer timeout for Visual Studio 2017
This was answered for previous versions,

However in version 15 (VS2017), the same registries for increasing NormalEvalTimeout and QuickwatchTimeout are missing.

答:
For newer versions of Visual Studio, this setting was moved to settings file. You should look to modify the LongEvalTimeout, NormalEvalTimeout and/or QuickwatchTimeout properties in the following file

C:\Program Files (x86)\Microsoft Visual Studio\YYYY\VERSION\Common7\IDE\Profiles\LANG.vssettings

Where

YYYY is the VS version (e.g. 2017 or 2019)

VERSION Enterprise or Professional

LANG is the programming language you want to change the setting for (e.g. CSharp, VB or VC)


问:
Why won't Apache Server start in MAMP?
I'm trying to view php files locally on my mac.

I'm running Yosemite.

I have MAMP installed on my computer. When I press start the MySQL server starts but Apache doesn't. An error message appears saying 'Error. Apache couldn't be started. Please check your MAMP installation'

I've gone through the internet typing stuff into terminal and changing 'envvars' to '_envvars' but nothing works.

I reinstalled OSX and that worked but when I shut down the computer the problem occurs again.

Can anyone help?

Thanks

答:
For MAMP :

You can open the terminal and write:

ps aux | grep mysql
lsof -i
killall -9 mysqld
```

I hope is good for you!

Bye

Title: Why won't Apache Server start in MAMP?

Body:
For MAMP :

You can open the terminal and write:

ps aux | grep mysql
lsof -i
killall -9 mysqld

I hope is good for you!

Bye


问:
Count by condition applied to the same column in Pandas
This is my data frame.

```<code>acc_index    veh_count    veh_type
001             1            1
002             2            1
002             2            2
003             2            1
003             2            2
004             1            1
005             2            1
005             2            3
006             1            2
007             2            1
007             2            2
008             2            1
008             2            1
009             3            1
009             3            1
009             3            2
</code>```

acc_index is unique for each accident

veh_count shows how many vehicles are involved in one accident

veh_type shows the type of vehicles involved in an accident (1=bicycle, 2=car, 3=bus).

What I want to do is to count the number of accidents between cars and bicycles (so, where veh_type=1 and veh_type=9 for the same acc_index), even if there were more cars or bicycles involved, I still want to count it as one accident. How can I do that?

I tried to do it with the code below, but I get the count of all accidents involving cars or bikes, and I want to get only the ones between them.

```<code>df[(df['veh_count'] >=2) & (df.veh_type.isin(['1','2']))].groupby(['acc_index', 'veh_count', 'veh_type']).count()
</code>```

I want to get something like this below, but also with the whole dataframe, and not only total sum.

```<code>acc_index    veh_count    veh_type     count
002             2            1
002             2            2
                           count         1
003             2            1
003             2            2
                           count         1
007             2            1
007             2            2
                           count         1
009             3            1
009             3            1
009             3            2
                           count         1
                        total_count      4
</code>```

If you have a better solution/idea, I would appreciate.

答:
IIUC, you can check veh_type for those of interest and groupby:

```<code>(df.assign(car=df.veh_type.eq(1),
          bike=df.veh_type.eq(2))  # change 2 to correct type
   [['acc_index','car','bike']]
   .groupby('acc_index')
   .any()
   .all(1).sum()
)
</code>```

Output:

```<code>4
</code>```

Update: If you want all the the rows:

```<code>s = (df.assign(car=df.veh_type.eq(1),
          bike=df.veh_type.eq(2))  # change 2 to correct type
   [['acc_index','car','bike']]
   .groupby('acc_index')
   .any()
   .all(1)
)

df[df['acc_index'].map(s)]
</code>```

Output:

```<code>    acc_index  veh_count  veh_type
1           2          2         1
2           2          2         2
3           3          2         1
4           3          2         2
9           7          2         1
10          7          2         2
13          9          3         1
14          9          3         1
15          9          3         2
</code>```

Body:
This is my data frame.

acc_index    veh_count    veh_type
001             1            1
002             2            1
002             2            2
003             2            1
003             2            2
004             1            1
005             2            1
005             2            3
006             1            2
007             2            1
007             2            2
008             2            1
008             2            1
009             3            1
009             3            1
009             3            2

acc_index is unique for each accident

veh_count shows how many vehicles are involved in one accident

veh_type shows the type of vehicles involved in an accident (1=bicycle, 2=car, 3=bus).

What I want to do is to count the number of accidents between cars and bicycles (so, where veh_type=1 and veh_type=9 for the same acc_index), even if there were more cars or bicycles involved, I still want to count it as one accident. How can I do that?

I tried to do it with the code below, but I get the count of all accidents involving cars or bikes, and I want to get only the ones between them.

df[(df['veh_count'] >=2) & (df.veh_type.isin(['1','2']))].groupby(['acc_index', 'veh_count', 'veh_type']).count()

I want to get something like this below, but also with the whole dataframe, and not only total sum.

acc_index    veh_count    veh_type     count
002             2            1
002             2            2
                           count         1
003             2            1
003             2            2
                           count         1
007             2            1
007             2            2
                           count         1
009             3            1
009             3            1
009             3            2
                           count         1
                        total_count      4

If you have a better solution/idea, I would appreciate.

Body:
IIUC, you can check veh_type for those of interest and groupby:

(df.assign(car=df.veh_type.eq(1),
          bike=df.veh_type.eq(2))  # change 2 to correct type
   [['acc_index','car','bike']]
   .groupby('acc_index')
   .any()
   .all(1).sum()
)

Output:

4

Update: If you want all the the rows:

s = (df.assign(car=df.veh_type.eq(1),
          bike=df.veh_type.eq(2))  # change 2 to correct type
   [['acc_index','car','bike']]
   .groupby('acc_index')
   .any()
   .all(1)
)

df[df['acc_index'].map(s)]

Output:

    acc_index  veh_count  veh_type
1           2          2         1
2           2          2         2
3           3          2         1
4           3          2         2
9           7          2         1
10          7          2         2
13          9          3         1
14          9          3         1
15          9          3         2


问:
Find substring in string from the end
I need to find position of string in substring. Scan has to begin from the end. For example:

```<code>findch(L"asdhuifdsahdfasasd", L"asd");
</code>```

return 16 instead of 1

Here is my function:

```<code>int findchr(LPCWSTR T, LPCWSTR P)
{
    int n = lstrlenW(T);
    int m = lstrlenW(P);

    for (int i = 0; i <= n - m; ++i) {
        int j = 0;
        while (j < m && T[i + j] == P[j]) {
            ++j;
        }
        if (j == m) {
            return i;
        }
    }
    return -1;
}
</code>```

答:
```<code>int findchr(LPCWSTR str, LPCWSTR substr)
{
    int n = lstrlenW(str);
    int m = lstrlenW(substr);

    for (int i = n; i >= m - n; --i) {
        int j = 0;
        while (j < m && str[i + j] == substr[j]) {
            ++j;
        }
        if (j == m) {
            return i;
        }
    }
    return -1;
}
</code>```

Title: Find substring in string from the end

Body:
I need to find position of string in substring. Scan has to begin from the end. For example:

findch(L"asdhuifdsahdfasasd", L"asd");

return 16 instead of 1

Here is my function:

int findchr(LPCWSTR T, LPCWSTR P)
{
    int n = lstrlenW(T);
    int m = lstrlenW(P);

    for (int i = 0; i <= n - m; ++i) {
        int j = 0;
        while (j < m && T[i + j] == P[j]) {
            ++j;
        }
        if (j == m) {
            return i;
        }
    }
    return -1;
}


问:
Is there a way to prevent a query from setting the serial primary key?
I've got a bunch of tables with the 'serial' keyword on a primary key so that auto-increment will work. The problem is that I can make a query to insert a row using any id number which overrides the auto-increment. Is there a reason for this? Or, is there a way to prevent a user from adding/changing this value?

Here's an example of my table config:

```<code>create table if not exists departments (
    department_id serial primary key,
    name varchar(64) not null unique
);
</code>```

if I run the following query, I can add any number to primary key:

```<code>insert into departments (department_id, name) values (9001, 'FooBar')
</code>```

I think I want to prevent this from happening. I'd like to get some opinions.

答:
Unless '9001' isn't already in the registers, it shouldn't cause any trouble.
If the filed 'department_id' is already auto increment you can just run your insert statement like </p>

```<code>INSERT INTO departments (name) VALUES ('FooBar')
</code>```

Body:
I've got a bunch of tables with the 'serial' keyword on a primary key so that auto-increment will work. The problem is that I can make a query to insert a row using any id number which overrides the auto-increment. Is there a reason for this? Or, is there a way to prevent a user from adding/changing this value?

Here's an example of my table config:

create table if not exists departments (
    department_id serial primary key,
    name varchar(64) not null unique
);

if I run the following query, I can add any number to primary key:

insert into departments (department_id, name) values (9001, 'FooBar')

I think I want to prevent this from happening. I'd like to get some opinions.

Body:
Unless '9001' isn't already in the registers, it shouldn't cause any trouble.
If the filed 'department_id' is already auto increment you can just run your insert statement like

INSERT INTO departments (name) VALUES ('FooBar')


问:
Convert JS Object to form data
How can I can convert my JS Object to FormData?

The reason why I want to do this is, I have an object that I constructed out of the ~100 form field values.

```<code>var item = {
   description: 'Some Item',
   price : '0.00',
   srate : '0.00',
   color : 'red',
   ...
   ...
}
</code>```

Now I am asked to add the upload file functionality to my form which, of-course is impossible via JSON and so I am planning on moving to FormData. So is there any way that I can convert my JS object to FormData?

答:
Recursively

const toFormData = (f => f(f))(h => f => f(x => h(h)(f)(x)))(f => fd => pk => d => {
  if (d instanceof Object) {
    Object.keys(d).forEach(k => {
      const v = d[k] === null ? '' : d[k] === true ? 1 : d[k] === false ? 0 : d[k]
      if (pk) k = `${pk}[${k}]`
      if (v instanceof Object && !(v instanceof Date) && !(v instanceof File)) {
        return f(fd)(k)(v)
      } else {
        fd.append(k, v)
      }
    })
  }
  return fd
})(new FormData())()

let data = {
  name: 'John',
  age: 30,
  colors: ['red', 'green', 'blue'],
  children: [
    { name: 'Max', age: 3 },
    { name: 'Madonna', age: 10 }
  ]
}
console.log('data', data)
document.getElementById("data").insertAdjacentHTML('beforeend', JSON.stringify(data))

let formData = toFormData(data)

for (let key of formData.keys()) {
  console.log(key, formData.getAll(key).join(','))
  document.getElementById("item").insertAdjacentHTML('beforeend', `<li>${key} = ${formData.getAll(key).join(',')}</li>`)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="data"></p>
<ul id="item"></ul></code>```

Title: Convert JS Object to form data

Body:
How can I can convert my JS Object to FormData?

The reason why I want to do this is, I have an object that I constructed out of the ~100 form field values.

var item = {
   description: 'Some Item',
   price : '0.00',
   srate : '0.00',
   color : 'red',
   ...
   ...
}

Now I am asked to add the upload file functionality to my form which, of-course is impossible via JSON and so I am planning on moving to FormData. So is there any way that I can convert my JS object to FormData?

Body:
Recursively

const toFormData = (f => f(f))(h => f => f(x => h(h)(f)(x)))(f => fd => pk => d => {
  if (d instanceof Object) {
    Object.keys(d).forEach(k => {
      const v = d[k] === null ? '' : d[k] === true ? 1 : d[k] === false ? 0 : d[k]
      if (pk) k = `${pk}[${k}]`
      if (v instanceof Object && !(v instanceof Date) && !(v instanceof File)) {
        return f(fd)(k)(v)
      } else {
        fd.append(k, v)
      }
    })
  }
  return fd
})(new FormData())()

let data = {
  name: 'John',
  age: 30,
  colors: ['red', 'green', 'blue'],
  children: [
    { name: 'Max', age: 3 },
    { name: 'Madonna', age: 10 }
  ]
}
console.log('data', data)
document.getElementById("data").insertAdjacentHTML('beforeend', JSON.stringify(data))

let formData = toFormData(data)

for (let key of formData.keys()) {
  console.log(key, formData.getAll(key).join(','))
  document.getElementById("item").insertAdjacentHTML('beforeend', `<li>${key} = ${formData.getAll(key).join(',')}</li>`)
}

<p id="data"></p>
<ul id="item"></ul>


问:
How to pad a number with leading zero in a SAS Macro loop counter?
So I have a range of datasets in a specific library. These datasets are named in the format DATASET_YYYYMM, with one dataset for each month. I am trying to append a range of these datasets based on user input for the date range. i.e. If start_date is 01NOV2019 and the end_date is 31JAN2020, I want to append the three datasets: LIBRARY.DATASET_201911, LIBRARY.DATASET_201912 and LIBRARY.DATASET_202001.

The range is obviously variable, so I can't simply name the datasets manually in a set function. Since I need to loop through the years and months in the date range, I believe a macro is the best way to do this. I'm using a loop within the SET statement to append all the datasets. I have copied my example code below. It does work in theory. But in practice, only if we are looping over the months of November and December. As the format of the dataset name has a two digit month, for Jan-Sept it will be 01-09. The month function returns 1-9 however, and of course a 'File DATASET_NAME does not exist' error is thrown.
Problem is I cannot figure out a way to get it to interpret the month with leading 0, without ruining functionality of another part of the loop/macro.

I have tried numerous approaches to format the number as z2, cannot get any to work.
i.e. Including PUTN functions in the DO line for quote_month as follows, it ignores the leading zero when generating the dataset name in the line below.

```<code>%DO quote_month = %SYSFUNC(IFN(&quote_year. = &start_year.,%SYSFUNC(PUTN(&start_month.,z2.)),1,.)) %TO %SYSFUNC(IFN(&quote_year. = &end_year.,%SYSFUNC(PUTN(&end_month.,z2.)),12,.));
</code>```

Below is example code (without any attempt to reformat it to z2) - it will throw an error because it cannot find 'dataset_20201' because it is actually called 'dataset_202001'. The dataset called dataset_combined_example produces the desired output of the code by manually referencing the dataset names which it will be unable to do in practice. Does anyone know how to go about this?

```<code>DATA _NULL_;
    FORMAT start_date end_date DATE9.;
    start_date = '01NOV2019'd;
    end_date = '31JAN2020'd;
    CALL symput('start_date',start_date);
    CALL symput('end_date',end_date);
RUN;

DATA dataset_201911;
   input name $;
   datalines;
Nov1
Nov2
;
RUN;
DATA dataset_201912;
   input name $;
   datalines;
Dec1
Dec2
;
RUN;
DATA dataset_202001;
   input name $;
   datalines;
Jan1
Jan2
;
RUN;

DATA dataset_combined_example;
    SET dataset_201911 dataset_201912 dataset_202001;
RUN;

%MACRO get_table(start_date, end_date);
    %LET start_year = %SYSFUNC(year(&start_date.));
    %LET end_year = %SYSFUNC(year(&end_date.));
    %LET start_month = %SYSFUNC(month(&start_date.));
    %LET end_month = %SYSFUNC(month(&end_date.));
    DATA dataset_combined;
        SET
            %DO quote_year = &start_year. %TO &end_year.;
                %DO quote_month = %SYSFUNC(IFN(&quote_year. = &start_year.,&start_month.,1,.)) %TO %SYSFUNC(IFN(&quote_year. = &end_year.,&end_month.,12,.));
                    dataset_&quote_year.&quote_month.
                %END;
            %END;
        ;
    RUN;
%MEND;
%get_table(&start_date.,&end_date.);
</code>```

答:
You can also do this using the metadata tables without having to resort to macro loops in the first place:

```<code>/* A few datasets to combine */
data
  DATASET_201910
  DATASET_201911
  DATASET_201912
  DATASET_202001
  ;
run;

%let START_DATE = '01dec2019'd;
%let END_DATE = '31jan2020'd;

proc sql noprint;
  select catx('.', libname, memname) into :DS_LIST separated by ' '
  from dictionary.tables
  where
    &START_DATE <=
      case
        when prxmatch('/DATASET_\d{6}/', memname)
          then input(scan(memname, -1, '_'), yymmn6.)
        else -99999
      end
    <= &END_DATE
    and libname = 'WORK'
  ;
quit;

data combined_datasets /view=combined_datasets;
  set &DS_LIST;
run;
</code>```

The case-when in the where clause ensures that any other datasets present in the same library that don't match the expected naming scheme are ignored.

One key difference with this approach is that you will never end up attempting to read a dataset that doesn't exist if one of the expected datasets in your range is missing.

Body:
So I have a range of datasets in a specific library. These datasets are named in the format DATASET_YYYYMM, with one dataset for each month. I am trying to append a range of these datasets based on user input for the date range. i.e. If start_date is 01NOV2019 and the end_date is 31JAN2020, I want to append the three datasets: LIBRARY.DATASET_201911, LIBRARY.DATASET_201912 and LIBRARY.DATASET_202001.

The range is obviously variable, so I can't simply name the datasets manually in a set function. Since I need to loop through the years and months in the date range, I believe a macro is the best way to do this. I'm using a loop within the SET statement to append all the datasets. I have copied my example code below. It does work in theory. But in practice, only if we are looping over the months of November and December. As the format of the dataset name has a two digit month, for Jan-Sept it will be 01-09. The month function returns 1-9 however, and of course a 'File DATASET_NAME does not exist' error is thrown.
Problem is I cannot figure out a way to get it to interpret the month with leading 0, without ruining functionality of another part of the loop/macro.

I have tried numerous approaches to format the number as z2, cannot get any to work.
i.e. Including PUTN functions in the DO line for quote_month as follows, it ignores the leading zero when generating the dataset name in the line below.

%DO quote_month = %SYSFUNC(IFN(&quote_year. = &start_year.,%SYSFUNC(PUTN(&start_month.,z2.)),1,.)) %TO %SYSFUNC(IFN(&quote_year. = &end_year.,%SYSFUNC(PUTN(&end_month.,z2.)),12,.));

Below is example code (without any attempt to reformat it to z2) - it will throw an error because it cannot find 'dataset_20201' because it is actually called 'dataset_202001'. The dataset called dataset_combined_example produces the desired output of the code by manually referencing the dataset names which it will be unable to do in practice. Does anyone know how to go about this?

DATA _NULL_;
    FORMAT start_date end_date DATE9.;
    start_date = '01NOV2019'd;
    end_date = '31JAN2020'd;
    CALL symput('start_date',start_date);
    CALL symput('end_date',end_date);
RUN;

DATA dataset_201911;
   input name $;
   datalines;
Nov1
Nov2
;
RUN;
DATA dataset_201912;
   input name $;
   datalines;
Dec1
Dec2
;
RUN;
DATA dataset_202001;
   input name $;
   datalines;
Jan1
Jan2
;
RUN;

DATA dataset_combined_example;
    SET dataset_201911 dataset_201912 dataset_202001;
RUN;

%MACRO get_table(start_date, end_date);
    %LET start_year = %SYSFUNC(year(&start_date.));
    %LET end_year = %SYSFUNC(year(&end_date.));
    %LET start_month = %SYSFUNC(month(&start_date.));
    %LET end_month = %SYSFUNC(month(&end_date.));
    DATA dataset_combined;
        SET
            %DO quote_year = &start_year. %TO &end_year.;
                %DO quote_month = %SYSFUNC(IFN(&quote_year. = &start_year.,&start_month.,1,.)) %TO %SYSFUNC(IFN(&quote_year. = &end_year.,&end_month.,12,.));
                    dataset_&quote_year.&quote_month.
                %END;
            %END;
        ;
    RUN;
%MEND;
%get_table(&start_date.,&end_date.);

Body:
You can also do this using the metadata tables without having to resort to macro loops in the first place:

/* A few datasets to combine */
data
  DATASET_201910
  DATASET_201911
  DATASET_201912
  DATASET_202001
  ;
run;

%let START_DATE = '01dec2019'd;
%let END_DATE = '31jan2020'd;

proc sql noprint;
  select catx('.', libname, memname) into :DS_LIST separated by ' '
  from dictionary.tables
  where
    &START_DATE <=
      case
        when prxmatch('/DATASET_\d{6}/', memname)
          then input(scan(memname, -1, '_'), yymmn6.)
        else -99999
      end
    <= &END_DATE
    and libname = 'WORK'
  ;
quit;

data combined_datasets /view=combined_datasets;
  set &DS_LIST;
run;

The case-when in the where clause ensures that any other datasets present in the same library that don't match the expected naming scheme are ignored.

One key difference with this approach is that you will never end up attempting to read a dataset that doesn't exist if one of the expected datasets in your range is missing.


问:
Getting a Random hexadecimal using an array in JavaScript
I have written a little code that generates a random color. It is based in an array that goes from 0 to 9 and A,B,C,D,E,F:

```<code><!DOCTYPE html>
<html lang="es">

<head>
    <meta charset="utf-8">
    <title>Ejercicio 7</title>
    <script type="text/javascript">

        function changeColor() {
            const intensity = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, "A", "B", "C", "D", "E", "F"];
            let randomColor1 = intensity[Math.floor(Math.random() * intensity.length)];
            let randomColor2 = intensity[Math.floor(Math.random() * intensity.length)];
            let randomColor3 = intensity[Math.floor(Math.random() * intensity.length)];
            let randomColor4 = intensity[Math.floor(Math.random() * intensity.length)];
            let randomColor5 = intensity[Math.floor(Math.random() * intensity.length)];
            let randomColor6 = intensity[Math.floor(Math.random() * intensity.length)];
            const randomColor = `#${randomColor1}${randomColor2}${randomColor3}${randomColor4}${randomColor5}${randomColor6}`;
            document.body.style.backgroundColor = randomColor;

        }
    </script>
</head>

<body onload="changeColor()">
    <button onclick="changeColor()">Pincha aquí</button>
</body>

</html>
</code>```

The problem is I don't understand this piece of repeated code:

```<code>intensity[Math.floor(Math.random() * intensity.length)]

</code>```

I know it gives me a random element from the array "intensity", but I don't know  how it works. Can someone explain to me? Thank you in advance.

答:
With Math.random() you get a number (float) between 0 and 1 (but not 1 as Andreas points out).

If you want a number from 0 to X you have to multiply for X Math.random() * X.

And the index of intensity goes from 0 to intensity.length.

That's why you need Math.random() * intensity.length to get an index of intensity randomly.

As the result of this multiplication is a float you can use floor to strip decimals and then you have at this moment:
Math.floor(Math.random() * intensity.length)

Which is the random index of intensity to get:

```<code>intensity[Math.floor(Math.random() * intensity.length)]
</code>```

Body:
I have written a little code that generates a random color. It is based in an array that goes from 0 to 9 and A,B,C,D,E,F:

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Ejercicio 7</title>

    <button onclick="changeColor()">Pincha aquí</button>

The problem is I don't understand this piece of repeated code:

intensity[Math.floor(Math.random() * intensity.length)]

I know it gives me a random element from the array "intensity", but I don't know  how it works. Can someone explain to me? Thank you in advance.

Body:
With Math.random() you get a number (float) between 0 and 1 (but not 1 as Andreas points out).

If you want a number from 0 to X you have to multiply for X Math.random() * X.

And the index of intensity goes from 0 to intensity.length.

That's why you need Math.random() * intensity.length to get an index of intensity randomly.

As the result of this multiplication is a float you can use floor to strip decimals and then you have at this moment:
Math.floor(Math.random() * intensity.length)

Which is the random index of intensity to get:

intensity[Math.floor(Math.random() * intensity.length)]


问:
Make Jupyter Notebook clickable
I did develop an application for several users on windows, without internet access using python and Jupyter Notebook as a graphical interface.
The application intend to process some data, they just have to copy paste the path to their datafile and run through different step.

As a user they just want to double click somewhere to open it. I may not fully understand Jupyter Notebook but I would like to find a simple way to make the notebook clickable ...

Could you help me ?

Thx

答: Have you looked at nteract? It was a suggestion in a similar question here, that was linked from a question with a similar title as yours, but referenced the previous version of the tech that is now Jupyter notebook.</p>

Title: Make Jupyter Notebook clickable


问:
How to not count cells across sheets which do not contain text?
Currently I have a formula which calculates the text contained within a given cell across multiple sheets i.e.:

```<code>=COUNTIF(Sheet1!G3:G1151, "COMPLETE") + COUNTIF(Sheet2!G3:G1151, "COMPLETE")
</code>```

I need to not calculate (Count) a cell if it does not contain text, i.e.:

```<code>=COUNTIF(Sheet1!G3:G1151, "COMPLETE") + COUNTIF(Sheet2!G3:G1151, "COMPLETE") + !COUNTIF(Sheet2!G3:G1151, "COMPLETE")
</code>```

Any ideas? thanks

答:
Not is <>:

```<code>=COUNTIF(Sheet1!G3:G1151, "<>COMPLETE") + COUNTIF(Sheet2!G3:G1151, "<>COMPLETE") + COUNTIF(Sheet2!G3:G1151, "<>COMPLETE")
</code>```

Body:
Currently I have a formula which calculates the text contained within a given cell across multiple sheets i.e.:

=COUNTIF(Sheet1!G3:G1151, "COMPLETE") + COUNTIF(Sheet2!G3:G1151, "COMPLETE")

I need to not calculate (Count) a cell if it does not contain text, i.e.:

=COUNTIF(Sheet1!G3:G1151, "COMPLETE") + COUNTIF(Sheet2!G3:G1151, "COMPLETE") + !COUNTIF(Sheet2!G3:G1151, "COMPLETE")

Any ideas? thanks

Body:
Not is <>:

=COUNTIF(Sheet1!G3:G1151, "<>COMPLETE") + COUNTIF(Sheet2!G3:G1151, "<>COMPLETE") + COUNTIF(Sheet2!G3:G1151, "<>COMPLETE")


问:
Can we create one IAM User that has access to create other IAM users in AWS
In S3, can we create an IAM user and give it rights to create other IAM users?</p>

答:
S3 and IAM are 2 different AWS services. S3 has nothing to do with IAM user creation.
I'll go ahead and assume that you meant creating an IAM user with permissions to create other users.

Yes, it is possible to do so. You just have to attach a suitable IAM policy to the newly created user. Following policy should get you started.

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "iam:CreateUser",
                "iam:CreateAccessKey"
            ],
            "Resource": "*"
        }
    ]
}
</code>```

Body:
S3 and IAM are 2 different AWS services. S3 has nothing to do with IAM user creation.
I'll go ahead and assume that you meant creating an IAM user with permissions to create other users.

Yes, it is possible to do so. You just have to attach a suitable IAM policy to the newly created user. Following policy should get you started.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "iam:CreateUser",
                "iam:CreateAccessKey"
            ],
            "Resource": "*"
        }
    ]
}


问:
Shared memory ('sys/shm.h') with emscripten
I've been exploring emscripten by trying to compile some basic wasm example that uses 'sys/shm.h'

Here's the code I'm trying to compile:

```<code>#include <stdio.h>
#include <sys/shm.h>

int main(int argc, char *argv[]) {
    key_t key = ftok("shmfile",65);
    int shmid = shmget(key,1024,0666|IPC_CREAT);

    char *str = (char*) shmat(shmid,(void*)0,0);
    sprintf(str, "balhhh");

    printf("Data in memory: %s\n",str);

    shmdt(str);
    return 0;
}
</code>```

Here is my compilation output:

```<code>➜  wasm emcc --version
emcc (Emscripten gcc/clang-like replacement) 1.39.8 (commit 1458145cf4f3db0fb548343e6acab267eef8e4ef)
Copyright (C) 2014 the Emscripten authors (see AUTHORS.txt)
This is free and open source software under the MIT license.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

➜  wasm emcc -o shared.html shared.c -s WASM=1 -s USE_PTHREADS=1
error: undefined symbol: ftok
warning: Link with `-s LLD_REPORT_UNDEFINED` to get more information on undefined symbols
warning: To disable errors for undefined symbols use `-s ERROR_ON_UNDEFINED_SYMBOLS=0`
error: undefined symbol: shmat
error: undefined symbol: shmdt
error: undefined symbol: shmget
Error: Aborting compilation due to previous errors
shared:ERROR: '/home/wave/Downloads/emsdk/node/12.9.1_64bit/bin/node /home/wave/Downloads/emsdk/upstream/emscripten/src/compiler.js /tmp/tmpiWE3Ei.txt' failed (1)

➜  wasm emcc -o shared.html shared.c -s WASM=1 -s USE_PTHREADS=1 -s LLD_REPORT_UNDEFINED
wasm-ld: error: /tmp/emscripten_temp_bNjvle/shared_0.o: undefined symbol: ftok
wasm-ld: error: /tmp/emscripten_temp_bNjvle/shared_0.o: undefined symbol: shmget
wasm-ld: error: /tmp/emscripten_temp_bNjvle/shared_0.o: undefined symbol: shmat
wasm-ld: error: /tmp/emscripten_temp_bNjvle/shared_0.o: undefined symbol: shmdt
wasm-ld: error: /home/wave/.emscripten_cache/wasm-obj/libc-mt.a(emscripten_pthread.c.o): undefined symbol: initPthreadsJS
shared:ERROR: '/home/wave/Downloads/emsdk/upstream/bin/wasm-ld -o /tmp/emscripten_temp_bNjvle/shared.wasm --lto-O0 /tmp/emscripten_temp_bNjvle/shared_0.o -L/home/wave/Downloads/emsdk/upstream/emscripten/system/local/lib -L/home/wave/Downloads/emsdk/upstream/emscripten/system/lib -L/home/wave/.emscripten_cache/wasm-obj /home/wave/.emscripten_cache/wasm-obj/libc-mt.a /home/wave/.emscripten_cache/wasm-obj/libcompiler_rt.a /home/wave/.emscripten_cache/wasm-obj/libc-wasm.a /home/wave/.emscripten_cache/wasm-obj/libdlmalloc-mt.a /home/wave/.emscripten_cache/wasm-obj/libpthread-mt.a /home/wave/.emscripten_cache/wasm-obj/libc_rt_wasm.a /home/wave/.emscripten_cache/wasm-obj/libsockets-mt.a --allow-undefined-file=/tmp/tmp5_bZ9l.undefined --import-memory --import-table --shared-memory -mllvm -combiner-global-alias-analysis=false -mllvm -enable-emscripten-sjlj -mllvm -disable-lsr --strip-debug --export __wasm_call_ctors --export __data_end --export main --export __errno_location --export emscripten_get_global_libc --export __pthread_tsd_run_dtors --export __emscripten_pthread_data_constructor -z stack-size=5242880 --initial-memory=16777216 --no-entry --max-memory=16777216 --global-base=1024' failed (1)
</code>```

I guess there is shared memory support in emscripten, but I just can't get wasm-ld to link it correctly.
Can anyone help?

Thanks,
Gal

答: Emscripten does not support SysV shared memory (the functions in sys/shm.h).</p>

Body:
I've been exploring emscripten by trying to compile some basic wasm example that uses 'sys/shm.h'

Here's the code I'm trying to compile:

#include <stdio.h>
#include <sys/shm.h>

int main(int argc, char *argv[]) {
    key_t key = ftok("shmfile",65);
    int shmid = shmget(key,1024,0666|IPC_CREAT);

    char *str = (char*) shmat(shmid,(void*)0,0);
    sprintf(str, "balhhh");

    printf("Data in memory: %s\n",str);

    shmdt(str);
    return 0;
}

Here is my compilation output:

➜  wasm emcc --version
emcc (Emscripten gcc/clang-like replacement) 1.39.8 (commit 1458145cf4f3db0fb548343e6acab267eef8e4ef)
Copyright (C) 2014 the Emscripten authors (see AUTHORS.txt)
This is free and open source software under the MIT license.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

➜  wasm emcc -o shared.html shared.c -s WASM=1 -s USE_PTHREADS=1
error: undefined symbol: ftok
warning: Link with `-s LLD_REPORT_UNDEFINED` to get more information on undefined symbols
warning: To disable errors for undefined symbols use `-s ERROR_ON_UNDEFINED_SYMBOLS=0`
error: undefined symbol: shmat
error: undefined symbol: shmdt
error: undefined symbol: shmget
Error: Aborting compilation due to previous errors
shared:ERROR: '/home/wave/Downloads/emsdk/node/12.9.1_64bit/bin/node /home/wave/Downloads/emsdk/upstream/emscripten/src/compiler.js /tmp/tmpiWE3Ei.txt' failed (1)

➜  wasm emcc -o shared.html shared.c -s WASM=1 -s USE_PTHREADS=1 -s LLD_REPORT_UNDEFINED
wasm-ld: error: /tmp/emscripten_temp_bNjvle/shared_0.o: undefined symbol: ftok
wasm-ld: error: /tmp/emscripten_temp_bNjvle/shared_0.o: undefined symbol: shmget
wasm-ld: error: /tmp/emscripten_temp_bNjvle/shared_0.o: undefined symbol: shmat
wasm-ld: error: /tmp/emscripten_temp_bNjvle/shared_0.o: undefined symbol: shmdt
wasm-ld: error: /home/wave/.emscripten_cache/wasm-obj/libc-mt.a(emscripten_pthread.c.o): undefined symbol: initPthreadsJS
shared:ERROR: '/home/wave/Downloads/emsdk/upstream/bin/wasm-ld -o /tmp/emscripten_temp_bNjvle/shared.wasm --lto-O0 /tmp/emscripten_temp_bNjvle/shared_0.o -L/home/wave/Downloads/emsdk/upstream/emscripten/system/local/lib -L/home/wave/Downloads/emsdk/upstream/emscripten/system/lib -L/home/wave/.emscripten_cache/wasm-obj /home/wave/.emscripten_cache/wasm-obj/libc-mt.a /home/wave/.emscripten_cache/wasm-obj/libcompiler_rt.a /home/wave/.emscripten_cache/wasm-obj/libc-wasm.a /home/wave/.emscripten_cache/wasm-obj/libdlmalloc-mt.a /home/wave/.emscripten_cache/wasm-obj/libpthread-mt.a /home/wave/.emscripten_cache/wasm-obj/libc_rt_wasm.a /home/wave/.emscripten_cache/wasm-obj/libsockets-mt.a --allow-undefined-file=/tmp/tmp5_bZ9l.undefined --import-memory --import-table --shared-memory -mllvm -combiner-global-alias-analysis=false -mllvm -enable-emscripten-sjlj -mllvm -disable-lsr --strip-debug --export __wasm_call_ctors --export __data_end --export main --export __errno_location --export emscripten_get_global_libc --export __pthread_tsd_run_dtors --export __emscripten_pthread_data_constructor -z stack-size=5242880 --initial-memory=16777216 --no-entry --max-memory=16777216 --global-base=1024' failed (1)

I guess there is shared memory support in emscripten, but I just can't get wasm-ld to link it correctly.
Can anyone help?

Thanks,
Gal


问:
Transaction atomic needed for bulk create?
I'm using the bulk_create method from Django to create many entries at once.

To ensure that the changes are only committed if there is no exception I'm thinking about adding transaction.atomic() to the code blocks but I'm not sure if I need to add it.

From my understanding I only need to add it in Scenario 2 because in this case I'm executing more than one query.

Scenario 1

Create 1.000 entries in one query

```<code>Entry.objects.bulk_create([
    Entry(headline='This is a test'),
    Entry(headline='This is only a test'),
    # ...
])
</code>```

Scenario 2

Create 10.000 entries in in batches of 1.000

```<code>Entry.objects.bulk_create([
    Entry(headline='This is a test'),
    Entry(headline='This is only a test'),
    # ...
], batch_size=1_000)
</code>```

答: No, you don't have to for either scenario. According to the Django source code, using transaction atomic would be redundant for bulk_create as that method already uses atomic transactions.

Body:
I'm using the bulk_create method from Django to create many entries at once.

To ensure that the changes are only committed if there is no exception I'm thinking about adding transaction.atomic() to the code blocks but I'm not sure if I need to add it.

From my understanding I only need to add it in Scenario 2 because in this case I'm executing more than one query.

Scenario 1

Create 1.000 entries in one query

Entry.objects.bulk_create([
    Entry(headline='This is a test'),
    Entry(headline='This is only a test'),
    # ...
])

Scenario 2

Create 10.000 entries in in batches of 1.000

Entry.objects.bulk_create([
    Entry(headline='This is a test'),
    Entry(headline='This is only a test'),
    # ...
], batch_size=1_000)


问:
React Router changes the URL but doesn't rerender the component
I'm making a ReactJS websites, the problem is that when the user click on a <Link to="path"> the URL location changes, but the whole webpage becomes black and inside the

 there is no child, except if I reload the page, in that case the page will normally render.

Searching in the web, they say to use BrowserRouter that wraps all the content, and to use the <Switch>, and of course I've tried it, but still don't work.

This is my code
app.js

```<code>import React, { useEffect, useState } from "react";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import Indirizzi from "./Contenuti/Indirizzi";
import Bottone from "./Util/Bottone";
import MostraMaterie from "./Contenuti/MostraMaterie";
import "./App.css";
import FullNavBar from "./NavBar/FullNavBar";

function App() {
  const [indirzzi, cambiaIndirizzi] = useState([]);

  const fetchIndirizzi = async () => {
    let indirizzi = await fetch(
      "https://vps.lellovitiello.tk/Riassunty/API/indirizzi.php"
    );
    indirizzi = await indirizzi.json();

    cambiaIndirizzi(indirizzi);
    console.log(indirizzi);
  };
  useEffect(fetchIndirizzi, []);

  return (
    <Router>
      <Switch>
        <Route path="/mostraMateria/:id">
          <MostraMaterie />
        </Route>
        <Route exact path="/">

          <FullNavBar indirizzi={indirzzi} />{" "}
          <Link to="/Login">
            <Bottone TestoBottone="Per caricare un riassunto" />
          </Link>{" "}
          <Indirizzi key="Indirizzi" data={indirzzi} />{" "}
        </Route>{" "}
      </Switch>{" "}
    </Router>
  );
}

export default App;

</code>```

I've tried to move around the <Route path="/mostraMateria/:id"> around in the file, but the result is always the same.

The only way to let this work is to remove the <Switch> but this will render the other router always, how can I solve if this is solvable?

edit
Even adding exact as suggested in the comments to both routes still doesn't work.

app.js

```<code>import React, { useEffect, useState } from "react";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import Indirizzi from "./Contenuti/Indirizzi";
import Bottone from "./Util/Bottone";
import MostraMaterie from "./Contenuti/MostraMaterie";
import "./App.css";
import FullNavBar from "./NavBar/FullNavBar";

function App() {
  const [indirzzi, cambiaIndirizzi] = useState([]);

  const fetchIndirizzi = async () => {
    let indirizzi = await fetch(
      "https://vps.lellovitiello.tk/Riassunty/API/indirizzi.php"
    );
    indirizzi = await indirizzi.json();

    cambiaIndirizzi(indirizzi);
    console.log(indirizzi);
  };
  useEffect(fetchIndirizzi, []);

  return (
    <Router>
      <Switch>
        <Route exact path="/mostraMateria/:id">
          <MostraMaterie />
        </Route>
        <Route exact path="/">

          <FullNavBar indirizzi={indirzzi} />{" "}
          <Link to="/Login">
            <Bottone TestoBottone="Per caricare un riassunto" />
          </Link>{" "}
          <Indirizzi key="Indirizzi" data={indirzzi} />{" "}
        </Route>{" "}
      </Switch>{" "}
    </Router>
  );
}

export default App;

</code>```

Edit 2

Even using import { withRouter } from "react-router"; and export default withRouter(MostraMaterie); inside the component that should be shown doesn't work.

Edit 3

I've created a new React Project, and there the routes work, my question now is, because I've the <Link> that breaks my app inside a component inside another and so on, could this be the problem?

答:
I've solved my problem, how? I don't know.

I was fixing warnings given by the console, and suddenly start working.

The error I fixed were:

1) Use effect doen't expect a Promise as parameter

2) Every child must have their unique key.

Body:
I'm making a ReactJS websites, the problem is that when the user click on a <Link to="path"> the URL location changes, but the whole webpage becomes black and inside the

 there is no child, except if I reload the page, in that case the page will normally render.

Searching in the web, they say to use BrowserRouter that wraps all the content, and to use the <Switch>, and of course I've tried it, but still don't work.

This is my code
app.js

import React, { useEffect, useState } from "react";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import Indirizzi from "./Contenuti/Indirizzi";
import Bottone from "./Util/Bottone";
import MostraMaterie from "./Contenuti/MostraMaterie";
import "./App.css";
import FullNavBar from "./NavBar/FullNavBar";

function App() {
  const [indirzzi, cambiaIndirizzi] = useState([]);

  const fetchIndirizzi = async () => {
    let indirizzi = await fetch(
      "https://vps.lellovitiello.tk/Riassunty/API/indirizzi.php"
    );
    indirizzi = await indirizzi.json();

    cambiaIndirizzi(indirizzi);
    console.log(indirizzi);
  };
  useEffect(fetchIndirizzi, []);

  return (
    <Router>
      <Switch>
        <Route path="/mostraMateria/:id">
          <MostraMaterie />
        </Route>
        <Route exact path="/">

          <FullNavBar indirizzi={indirzzi} />{" "}
          <Link to="/Login">
            <Bottone TestoBottone="Per caricare un riassunto" />
          </Link>{" "}
          <Indirizzi key="Indirizzi" data={indirzzi} />{" "}
        </Route>{" "}
      </Switch>{" "}
    </Router>
  );
}

export default App;

I've tried to move around the <Route path="/mostraMateria/:id"> around in the file, but the result is always the same.

The only way to let this work is to remove the <Switch> but this will render the other router always, how can I solve if this is solvable?

edit
Even adding exact as suggested in the comments to both routes still doesn't work.

app.js

import React, { useEffect, useState } from "react";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import Indirizzi from "./Contenuti/Indirizzi";
import Bottone from "./Util/Bottone";
import MostraMaterie from "./Contenuti/MostraMaterie";
import "./App.css";
import FullNavBar from "./NavBar/FullNavBar";

function App() {
  const [indirzzi, cambiaIndirizzi] = useState([]);

  const fetchIndirizzi = async () => {
    let indirizzi = await fetch(
      "https://vps.lellovitiello.tk/Riassunty/API/indirizzi.php"
    );
    indirizzi = await indirizzi.json();

    cambiaIndirizzi(indirizzi);
    console.log(indirizzi);
  };
  useEffect(fetchIndirizzi, []);

  return (
    <Router>
      <Switch>
        <Route exact path="/mostraMateria/:id">
          <MostraMaterie />
        </Route>
        <Route exact path="/">

          <FullNavBar indirizzi={indirzzi} />{" "}
          <Link to="/Login">
            <Bottone TestoBottone="Per caricare un riassunto" />
          </Link>{" "}
          <Indirizzi key="Indirizzi" data={indirzzi} />{" "}
        </Route>{" "}
      </Switch>{" "}
    </Router>
  );
}

export default App;

Edit 2

Even using import { withRouter } from "react-router"; and export default withRouter(MostraMaterie); inside the component that should be shown doesn't work.

Edit 3

I've created a new React Project, and there the routes work, my question now is, because I've the <Link> that breaks my app inside a component inside another and so on, could this be the problem?


问:
Strategies For Tracking Down Memory Leaks When You've Done Everything Wrong
My program, alas, has a memory leak somewhere, but I'll be damned if I know what it is.

Its job is to read in a bunch of ~2MB files, do some parsing and string replacement, then output them in various formats. Naturally, this means a lot of strings, and so doing memory tracing shows that I have a lot of strings, which is exactly what I'd expect. The structure of the program is a series of classes (each in their own thread, because I'm an idiot) that acts on an object that represents each file in memory. (Each object has an input queue that uses a lock on both ends. While this means I get to run this simple processing in parallel, it also means I have multiple 2MB objects sitting in memory.) Each object's structure is defined by a schema object.

My processing classes raise events when they've done their processing and pass a reference to the large object that holds all my strings to add it to the next processing object's queue. Replacing the event with a function call to add to the queue does not stop the leak. One of the output formats requires me to use an unmanaged object. Implementing Dispose() on the class does not stop the leak. I've replaced all the references to the schema object with an index name. No dice. I got no idea what's causing it, and no idea where to look. The memory trace doesn't help because all I see are a bunch of strings being created, and I don't see where the references are sticking in memory.

We're pretty much going to give up and roll back at this point, but I have a pathological need to know exactly how I messed this up. I know Stack Overflow can't exactly comb my code, but what strategies can you suggest for tracking this leak down? I'm probably going to do this in my own time, so any approach is viable.

答:
The best memory profiling tool for .Net is this:

http://memprofiler.com

Also, while I'm here, the best performance profiler for .Net is this:

http://www.yourkit.com/dotnet/download/index.jsp

They are also great value for money, have low overhead and are easy to use.  Anyone serious about .Net development should consider both of these a personal investment and purchase immediately.  Both of them have a free trial.

I work on a real time game engine with over 700k lines of code written in C# and have spent hundreds of hours using both these tools.  I have used the Sci Tech product since 2002 and YourKit! for the last three years.  Although I've tried quite a few of the others I have always returned to these.

IMHO, they are both absolutely brilliant.

OwnerDisplayName: Merus

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Christian Beaumont