问:
Attach Google Slide as a pdf with the placeholder text replaced whilst sending by email
I have drafted the below code however it attached the pdf with the placeholders.

The below code takes data from a google form populates it on a google sheet and replaces all the placeholders on the template with the data from the google form. The trigger 'on form submit' has been added.
The code is as follows:

```<code>function DigitalReceipts() {

  SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Receipts").activate();

  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var lr = ss.getLastRow()

  for (var i =2;i<lr;i++){

    if(ss.getRange(i, 1).getValue()){

  //Make a copy of the template file - power point
  var documentId = DriveApp.getFileById('1FtgZuJb4KpChhgehPp1lIEtrsjvykAqRiYl5rL8yv2Q').makeCopy().getId();

  var RV = ss.getRange(i, 2).getValue();

  var DateFormat = ss.getRange(i, 4).getValue();
  var Date = Utilities.formatDate(DateFormat, "GMT+0400", "dd MMM yyyy");

  var Amount = ss.getRange(i, 5).getValue().toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  var Name = ss.getRange(i, 6).getValue();
  var Description = ss.getRange(i, 7).getValue();
  var SalesOwner = ss.getRange(i, 8).getValue();
  var PaymentType = ss.getRange(i, 9).getValue();
  var PaymentReference = ss.getRange(i, 10).getValue();

  //Get the document body as a variable
  var body = SlidesApp.openById(documentId);

  body.replaceAllText('{RV}', RV);
  body.replaceAllText('{Date}', Date);
  body.replaceAllText('{Amount}', Amount);
  body.replaceAllText('{Name}', Name);
  body.replaceAllText('{Description}', Description);
  body.replaceAllText('{Sales Owner}', SalesOwner);
  body.replaceAllText('{Payment Type}', PaymentType);
  body.replaceAllText('{Payment Reference}', PaymentReference);

  DriveApp.getFileById(documentId).setName("xxx_"+Name+"_Receipt_"+RV);

  //var body = DocumentApp.openById(documentId).getBody();

  //body.replaceText('{RV}', RV).replaceText('{Date}', Date).replaceText('{Amount}', Amount).replaceText('{Name}', Name).replaceText('{Description}', Description).replaceText('{Sales Owner}', SalesOwner).replaceText('{Payment Type}', PaymentType).replaceText('{Payment Reference}', PaymentReference);

  var receipt = body.getSlides();
  var receiptNumber = 1;

  //var receiptURL = body.getId()+receipt[receiptNumber-1].getObjectId();
  var receiptURL = body.getUrl()+"#slide=id."+receipt[receiptNumber-1].getObjectId();
  ss.getRange(i, 11).setValue(receiptURL);

      var currentEmail = ss.getRange(i, 3).getValue();
      var subjectLine = "PwC's Academy_"+Name+"_Receipt_"+RV;
      var templateText =  SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Template").getRange(1, 1).getValue();
      var messageBody = templateText.replace("{Name}", Name).replace("{Description}", Description).replace("{URL}", receiptURL);

      //var ReceiptID = ss.getRange(i, 11).getValue();
      //var ReceiptID = ReceiptURL.match(/[-\w]{25,}/);

   //var ReceiptAttachment = ss.getRange(i, 11).getValue();

   //var waiver = DriveApp.getFileById(ReceiptAttachment);
   //var liabilityWaiver = waiver.getAs(MimeType.PDF);

  var pdf = DriveApp.getFileById(documentId).getAs("application/pdf");

  MailApp.sendEmail(currentEmail, subjectLine, messageBody, {attachments: pdf,
                                                             cc: 'abc@abc.com'});

       }
     else {}
    }
}
</code>```

Would be grateful for any help/guidance.

答:
How about this modification?

From:

```<code>body.replaceAllText('{Payment Reference}', PaymentReference);

DriveApp.getFileById(documentId).setName("xxx_"+Name+"_Receipt_"+RV);
</code>```

To:

```<code>body.replaceAllText('{Payment Reference}', PaymentReference);
body.saveAndClose();  // <--- Added
DriveApp.getFileById(documentId).setName("xxx_"+Name+"_Receipt_"+RV);
</code>```

Reference:

saveAndClose()

If this was not the direct solution of your issue, I apologize.

Body:
I have drafted the below code however it attached the pdf with the placeholders.

The below code takes data from a google form populates it on a google sheet and replaces all the placeholders on the template with the data from the google form. The trigger 'on form submit' has been added.
The code is as follows:

function DigitalReceipts() {

  SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Receipts").activate();

  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var lr = ss.getLastRow()

  for (var i =2;i<lr;i++){

    if(ss.getRange(i, 1).getValue()){

  //Make a copy of the template file - power point
  var documentId = DriveApp.getFileById('1FtgZuJb4KpChhgehPp1lIEtrsjvykAqRiYl5rL8yv2Q').makeCopy().getId();

  var RV = ss.getRange(i, 2).getValue();

  var DateFormat = ss.getRange(i, 4).getValue();
  var Date = Utilities.formatDate(DateFormat, "GMT+0400", "dd MMM yyyy");

  var Amount = ss.getRange(i, 5).getValue().toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  var Name = ss.getRange(i, 6).getValue();
  var Description = ss.getRange(i, 7).getValue();
  var SalesOwner = ss.getRange(i, 8).getValue();
  var PaymentType = ss.getRange(i, 9).getValue();
  var PaymentReference = ss.getRange(i, 10).getValue();

  //Get the document body as a variable
  var body = SlidesApp.openById(documentId);

  body.replaceAllText('{RV}', RV);
  body.replaceAllText('{Date}', Date);
  body.replaceAllText('{Amount}', Amount);
  body.replaceAllText('{Name}', Name);
  body.replaceAllText('{Description}', Description);
  body.replaceAllText('{Sales Owner}', SalesOwner);
  body.replaceAllText('{Payment Type}', PaymentType);
  body.replaceAllText('{Payment Reference}', PaymentReference);

  DriveApp.getFileById(documentId).setName("xxx_"+Name+"_Receipt_"+RV);

  //var body = DocumentApp.openById(documentId).getBody();

  //body.replaceText('{RV}', RV).replaceText('{Date}', Date).replaceText('{Amount}', Amount).replaceText('{Name}', Name).replaceText('{Description}', Description).replaceText('{Sales Owner}', SalesOwner).replaceText('{Payment Type}', PaymentType).replaceText('{Payment Reference}', PaymentReference);

  var receipt = body.getSlides();
  var receiptNumber = 1;

  //var receiptURL = body.getId()+receipt[receiptNumber-1].getObjectId();
  var receiptURL = body.getUrl()+"#slide=id."+receipt[receiptNumber-1].getObjectId();
  ss.getRange(i, 11).setValue(receiptURL);

      var currentEmail = ss.getRange(i, 3).getValue();
      var subjectLine = "PwC's Academy_"+Name+"_Receipt_"+RV;
      var templateText =  SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Template").getRange(1, 1).getValue();
      var messageBody = templateText.replace("{Name}", Name).replace("{Description}", Description).replace("{URL}", receiptURL);

      //var ReceiptID = ss.getRange(i, 11).getValue();
      //var ReceiptID = ReceiptURL.match(/[-\w]{25,}/);

   //var ReceiptAttachment = ss.getRange(i, 11).getValue();

   //var waiver = DriveApp.getFileById(ReceiptAttachment);
   //var liabilityWaiver = waiver.getAs(MimeType.PDF);

  var pdf = DriveApp.getFileById(documentId).getAs("application/pdf");

  MailApp.sendEmail(currentEmail, subjectLine, messageBody, {attachments: pdf,
                                                             cc: 'abc@abc.com'});

       }
     else {}
    }
}

Would be grateful for any help/guidance.

Body:
How about this modification?

From:

body.replaceAllText('{Payment Reference}', PaymentReference);

DriveApp.getFileById(documentId).setName("xxx_"+Name+"_Receipt_"+RV);

To:

body.replaceAllText('{Payment Reference}', PaymentReference);
body.saveAndClose();  // <--- Added
DriveApp.getFileById(documentId).setName("xxx_"+Name+"_Receipt_"+RV);

Reference:

saveAndClose()

If this was not the direct solution of your issue, I apologize.


来源: stackexchange

问:
How do I detect scrolling past the start of the page using Javascript?
I have a navigation bar at the top of a HTML page that, when the client attempts to scroll past the top, should expand (using CSS and Javascript; I don't want it to be actually scrollable since I wanna give it an animation). The Javascript I was using to try to detect this is:

```<code>window.addEventListener('scroll', function(e) {
    // do whatever to confirm the page is scrolling
});
</code>```

and while this works for regularly scrolling, it doesn't detect when the client tries to scroll past the boundaries of the page. I've also tried using if (window.scrollY <= 0), but it goes off any time the client is at the top of the page (and doesn't detect whether the client is staying at the top or trying to scroll past it).

Is there a way I can detect scrolling past the top of the page using Javascript, preferably without messing with the formatting too much?

答:
You can use 'wheel' event instead of the 'scroll' event.

https://developer.mozilla.org/en-US/docs/Web/API/Element/wheel_event

```<code>addEventListener('scroll', ...)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a navigation bar at the top of a HTML page that, when the client attempts to scroll past the top, should expand (using CSS and Javascript; I don't want it to be actually scrollable since I wanna give it an animation). The Javascript I was using to try to detect this is:

window.addEventListener('scroll', function(e) {
    // do whatever to confirm the page is scrolling
});

and while this works for regularly scrolling, it doesn't detect when the client tries to scroll past the boundaries of the page. I've also tried using if (window.scrollY <= 0), but it goes off any time the client is at the top of the page (and doesn't detect whether the client is staying at the top or trying to scroll past it).

Is there a way I can detect scrolling past the top of the page using Javascript, preferably without messing with the formatting too much?

Body:
You can use 'wheel' event instead of the 'scroll' event.

https://developer.mozilla.org/en-US/docs/Web/API/Element/wheel_event

addEventListener('scroll', ...)


问:
Gorm extremely slow
Gorm seem to be extremely slow.

```<code>type Ad struct {
    AdId        string `json:"adId" gorm:"column:adId"`
    Attributes  string `json:"attributes" gorm:"column:attributes"`
    Title       string `json:"title" gorm:"column:title"`
    Description string `json:"description" gorm:"column:description"`
    Image       string `json:"image" gorm:"column:image"`
    Url         string `json:"url" gorm:"column:url"`
    Price       int    `json:"price" gorm:"column:price"`
    Address    string    `json:"address" gorm:"column:address"`
    Latitude   float64   `json:"latitude" gorm:"column:latitude"`
    Longitude  float64   `json:"longitude" gorm:"column:longitude"`
    PostedDate time.Time `json:"postedDate" gorm:"column:postedDate"`
}

db.Table("Kijiji").Find(&listing).Where("adId = ?", m["id"][0])
</code>```

The last time takes almost 60s to query. Whereas if I used "database/sql" mysql.QueryRow() its less than 500ms.

Any idea why?

Update:

The slowdown happens in this callback_query.go It appears that this function is looping through the entire table of 20k records.

```<code>func queryCallback(scope *Scope) {
    ..........
        if rows, err := scope.SQLDB().Query(scope.SQL, scope.SQLVars...); scope.Err(err) == nil {
            defer rows.Close()
            columns, _ := rows.Columns()
            for rows.Next() {
                scope.db.RowsAffected++

                elem := results
                if isSlice {
                    elem = reflect.New(resultType).Elem()
                }
                scope.scan(rows, columns, scope.New(elem.Addr().Interface()).Fields())
            ..................
        }
    }
}
</code>```

How do I fix this?

答: You did it backwards. Find executes the query and fetches the rows. You wanted db.Table("Kijiji").Where("adId = ?", m["id"][0]).Find(&listing) to apply the where condition before fetching everything.

Title: Gorm extremely slow

Body:
Gorm seem to be extremely slow.

type Ad struct {
    AdId        string `json:"adId" gorm:"column:adId"`
    Attributes  string `json:"attributes" gorm:"column:attributes"`
    Title       string `json:"title" gorm:"column:title"`
    Description string `json:"description" gorm:"column:description"`
    Image       string `json:"image" gorm:"column:image"`
    Url         string `json:"url" gorm:"column:url"`
    Price       int    `json:"price" gorm:"column:price"`
    Address    string    `json:"address" gorm:"column:address"`
    Latitude   float64   `json:"latitude" gorm:"column:latitude"`
    Longitude  float64   `json:"longitude" gorm:"column:longitude"`
    PostedDate time.Time `json:"postedDate" gorm:"column:postedDate"`
}

db.Table("Kijiji").Find(&listing).Where("adId = ?", m["id"][0])

The last time takes almost 60s to query. Whereas if I used "database/sql" mysql.QueryRow() its less than 500ms.

Any idea why?

Update:

The slowdown happens in this callback_query.go It appears that this function is looping through the entire table of 20k records.

func queryCallback(scope *Scope) {
    ..........
        if rows, err := scope.SQLDB().Query(scope.SQL, scope.SQLVars...); scope.Err(err) == nil {
            defer rows.Close()
            columns, _ := rows.Columns()
            for rows.Next() {
                scope.db.RowsAffected++

                elem := results
                if isSlice {
                    elem = reflect.New(resultType).Elem()
                }
                scope.scan(rows, columns, scope.New(elem.Addr().Interface()).Fields())
            ..................
        }
    }
}

How do I fix this?


问:
Config merging in babelv7
I just upgraded to babelv7 , earlier I had a default environment which had some aliases and a test environment which had some aliases, now in the test environment babel used to merge both the configs, in babelv7 this functionality has been removed ,how to achieve this merging functionality without repeating the aliases 2 times.

This is my babel.config.js

```<code>module.exports = {
  presets: ['custom-preset'],
  env: {
    test: {
      presets: ['@babel/preset-env', '@babel/preset-react'],
      plugins: [
        'transform-class-properties',
        [
          'module-resolver',
          {
            root: ['./app'],
            alias: {
              'test-util': './node_modules/test-util/lib',
            },
          },
        ],
      ],
    },
  },
  ignore: ['node_modules'],
  plugins: [
    [
      'transform-imports',
      {
        lodash: {
          transform: 'lodash/${member}',
          preventFullImport: true,
        },
      },
    ],
    [
      'module-resolver',
      {
        root: ['./app'],
        alias: {
          'module1': './src/components/module1',
        },
      },
    ],
  ],
};

</code>```

答:
The primary change to merging in Babel 7 is that things are actually merged more, so instead of this config producing two instances of module-resolver with two different configs, the one in test will overwrite the config for the module in the top-level.

To tell Babel that they are meant to be two independent plugins, you need to give at least one of them a unique name, which is a string passed as the third entry in the plugin item array, e.g.

```<code>  plugins: [
    'transform-class-properties',
    [
      'module-resolver',
      {
        root: ['./app'],
        alias: {
          'test-util': './node_modules/test-util/lib',
        },
      },
      'testing-resolver' // A name for the plugin so it is unique and doesn't overwrite
    ],
  ],
</code>```

Title: Config merging in babelv7

Body:
I just upgraded to babelv7 , earlier I had a default environment which had some aliases and a test environment which had some aliases, now in the test environment babel used to merge both the configs, in babelv7 this functionality has been removed ,how to achieve this merging functionality without repeating the aliases 2 times.

This is my babel.config.js

module.exports = {
  presets: ['custom-preset'],
  env: {
    test: {
      presets: ['@babel/preset-env', '@babel/preset-react'],
      plugins: [
        'transform-class-properties',
        [
          'module-resolver',
          {
            root: ['./app'],
            alias: {
              'test-util': './node_modules/test-util/lib',
            },
          },
        ],
      ],
    },
  },
  ignore: ['node_modules'],
  plugins: [
    [
      'transform-imports',
      {
        lodash: {
          transform: 'lodash/${member}',
          preventFullImport: true,
        },
      },
    ],
    [
      'module-resolver',
      {
        root: ['./app'],
        alias: {
          'module1': './src/components/module1',
        },
      },
    ],
  ],
};

Body:
The primary change to merging in Babel 7 is that things are actually merged more, so instead of this config producing two instances of module-resolver with two different configs, the one in test will overwrite the config for the module in the top-level.

To tell Babel that they are meant to be two independent plugins, you need to give at least one of them a unique name, which is a string passed as the third entry in the plugin item array, e.g.

  plugins: [
    'transform-class-properties',
    [
      'module-resolver',
      {
        root: ['./app'],
        alias: {
          'test-util': './node_modules/test-util/lib',
        },
      },
      'testing-resolver' // A name for the plugin so it is unique and doesn't overwrite
    ],
  ],


问:
What is the purpose of () in a bash function?
I couldn't really find an answer online. I'm sure there is a good reason. Does bash not have function parameters? I understand you can pass arguments to it using $1 $@ etc... just found it strange that I have never seen code with anything inside the parentheses.

Expected:

```<code>function example_f (var1,var2) { echo "$var1" ; echo "$var2" ; }
example_f("Hello World","Test")
</code>```

Real World:

```<code>function example_f () { echo "$1" ; echo "$2" ; }
example_f "Hello World" "Test"
</code>```

答:
The function keyword is a bash extension. The standard syntax for function definitions is simply:

```<code>name() { body }
</code>```

and the parentheses are needed to recognize that this is a function definition rather than an ordinary command invocation. They're not used to contain parameters, they just distinguish the syntax.

bash added the function keyword at the beginning. When you use this, the parentheses are optional, so you can write

```<code>function example_f { echo "$var1" ; echo "$var2" ; }
</code>```

Body:
I couldn't really find an answer online. I'm sure there is a good reason. Does bash not have function parameters? I understand you can pass arguments to it using $1 $@ etc... just found it strange that I have never seen code with anything inside the parentheses.

Expected:

function example_f (var1,var2) { echo "$var1" ; echo "$var2" ; }
example_f("Hello World","Test")

Real World:

function example_f () { echo "$1" ; echo "$2" ; }
example_f "Hello World" "Test"

Body:
The function keyword is a bash extension. The standard syntax for function definitions is simply:

name() { body }

and the parentheses are needed to recognize that this is a function definition rather than an ordinary command invocation. They're not used to contain parameters, they just distinguish the syntax.

bash added the function keyword at the beginning. When you use this, the parentheses are optional, so you can write

function example_f { echo "$var1" ; echo "$var2" ; }


问:
Why aren't changes saved to device after hot reload?
Sometimes I'll write and save some code, Android Studio hot reloads my attached (Android) device, and the changes work as expected. However, if I stop the program on the phone or disconnect the device from Android Studio, the changes are not present--the program looks or works the way it did before I hot reloaded changes. It's as if the changes were in the phone's memory, but not saved as part of the APK on the device. ... Is this the expected behavior? (If so, what setting changes behavior so reloaded code is compiled and saved as part of the APK loaded on the attached phone device?)

I have Android Studio 3.5.3. I did see this post, but it's a few years old now, and I do see my changes; they're just not saved on the device.

答:
When you hot reload, flutter just updates it virtually, that's the reason it works so fast.

If you want to maintain your changes you have two options:

Before disconnecting your phone re-run the app(Complete rebuild NOT hot reload)

OR

Run flutter run --release in the terminal, this will create a debug apk for your app.

Hope that helps.


问:
Why the CPU usage of a GKE Workload is not equal to the sum of the CPU usage of its pods?
I'm trying to figure out why a GKE "Workload" CPU usage is not equivalent to the sum of cpu usage of its pods.

Following image shows a Workload CPU usage.

Service Workload CPU Usage

Following images show pods CPU usage for the above Workload.

Pod #1 CPU Usage

Pod #2 CPU Usage

For example, at 9:45, the Workload cpu usage was around 3.7 cores, but at the same time Pod#1 CPU usage was around 0.9 cores and Pod#2 CPU usage was around 0.9 cores too. It means, the service Workload CPU Usage should have been around 1.8 cores, but it wasn't.

Does anyone have an idea of this behavior?

Thanks.

答:
Danny,

The CPU chart on the Workloads page is an aggregate of CPU usage for managed pods. The values are taken from the Stackdriver Monitoring metric container/cpu/usage_time, check this link. That metric represents "Cumulative CPU usage on all cores in seconds. This number divided by the elapsed time represents usage as a number of cores, regardless of any core limit that might be set."

Please let me know if you have further questions in regard to this.


问:
Pass multiple parameters to a blade directive
I'm trying to create a blade directive to highlight some words that will return from my search query.

This is my blade directive:

```<code>class AppServiceProvider extends ServiceProvider

{
    public function boot()
    {
        Blade::directive('highlight', function($expression, $string){

            $expressionValues = preg_split('/\s+/', $expression);

            foreach ($expressionValues as $value) {
                $string = str_replace($value, "<b>".$value."</b>", $string);
            }

            return "<?php echo {$string}; ?>";
        });
    }

    public function register()
    {
    }
}
</code>```

And I call in blade like this:

```<code>@highlight('ho', 'house')
</code>```

But, this erros is following me:

```<code>Missing argument 2 for App\Providers\AppServiceProvider::App\Providers\{closure}()
</code>```

How to solve it?

答:
The best way to accomplish this task is exactly as @Everrett suggested.

I checked through the blade code, and this is exactly how the laravel team has to do it as well.

If you look through vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesHelpers.php, at the compileDd function, you'll notice that they use $arguments instead of $expression like they do in all of the other compile functions found in vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/

// CompilesHelpers.php
protected function compileDd($arguments)
{
    return "<?php dd{$arguments}; ?>";
}

//CompilesConditionals.php
protected function compileIf($expression)
{
    return "<?php if{$expression}: ?>";
}
```

<p>And if you look at <code>vendor/symfony/var-dumper/Resources/functions/dump.php</code> you'll see that Laravel handles variable arguments with <code>...</code> splat notation in the <code>dd</code> function.</p>

<pre class="lang-php prettyprint-override"><code>if (!function_exists('dd')) {
    function dd(...$vars)
    {
}}
</code>```

So you could do a directive like: (I put my custom function in app\helpers)
If you do the same, you need to make sure to escape the backslashes.

Blade::directive('customFunc', function ($expression) {
    return "<?php \\App\\Helpers\\customFunc({$arguments}); ?>";
});
```

<p>and a custom function like:</p>

<pre class="lang-php prettyprint-override"><code>/**
 * Custom function to demonstrate usage
 * @param mixed ...$args
 * @return void
 */
function customFunc(...$args): void {
    // Extract variables //
    // Use pad to get expected args, and set unset to null //
    list($arg1, $arg2, $arg3) = array_pad($args, 3, null);

    // Echo out args //
    echo "arg1: ${arg1} | arg2: ${arg2} | arg3: {$arg3}";
}
</code>```

run php artisan view:clear

And then use the directive:

    @customFunc('hello','wonderful', 'world')

// Returns:
arg1: hello | arg2: wonderful | arg3: world

// Using

    @customFunc('hello', 'world')

// Returns:
arg1: hello | arg2: world | arg3:
```

The best reason to do it this way is so that if your function evolves or changes, you only need to modify the underlining function. You wont have to clear views every time you change the code.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to create a blade directive to highlight some words that will return from my search query.

This is my blade directive:

class AppServiceProvider extends ServiceProvider

{
    public function boot()
    {
        Blade::directive('highlight', function($expression, $string){

            $expressionValues = preg_split('/\s+/', $expression);

            foreach ($expressionValues as $value) {
                $string = str_replace($value, "".$value."", $string);
            }

            return "<?php echo {$string}; ?>";
        });
    }

    public function register()
    {
    }
}

And I call in blade like this:

@highlight('ho', 'house')

But, this erros is following me:

Missing argument 2 for App\Providers\AppServiceProvider::App\Providers\{closure}()

How to solve it?

Body:
The best way to accomplish this task is exactly as @Everrett suggested.

I checked through the blade code, and this is exactly how the laravel team has to do it as well.

If you look through vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesHelpers.php, at the compileDd function, you'll notice that they use $arguments instead of $expression like they do in all of the other compile functions found in vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/

// CompilesHelpers.php
protected function compileDd($arguments)
{
    return "<?php dd{$arguments}; ?>";
}

//CompilesConditionals.php
protected function compileIf($expression)
{
    return "<?php if{$expression}: ?>";
}

And if you look at vendor/symfony/var-dumper/Resources/functions/dump.php you'll see that Laravel handles variable arguments with ... splat notation in the dd function.

if (!function_exists('dd')) {
    function dd(...$vars)
    {
}}

So you could do a directive like: (I put my custom function in app\helpers)
If you do the same, you need to make sure to escape the backslashes.

Blade::directive('customFunc', function ($expression) {
    return "<?php \\App\\Helpers\\customFunc({$arguments}); ?>";
});

and a custom function like:

/**
 * Custom function to demonstrate usage
 * @param mixed ...$args
 * @return void
 */
function customFunc(...$args): void {
    // Extract variables //
    // Use pad to get expected args, and set unset to null //
    list($arg1, $arg2, $arg3) = array_pad($args, 3, null);

    // Echo out args //
    echo "arg1: ${arg1} | arg2: ${arg2} | arg3: {$arg3}";
}

run php artisan view:clear

And then use the directive:

<div>
    @customFunc('hello','wonderful', 'world')
</div>

// Returns:
arg1: hello | arg2: wonderful | arg3: world

// Using
<div>
    @customFunc('hello', 'world')
</div>
// Returns:
arg1: hello | arg2: world | arg3:

The best reason to do it this way is so that if your function evolves or changes, you only need to modify the underlining function. You wont have to clear views every time you change the code.


问:
Flask blueprint static directory does not work?
According to the Flask readme, blueprint static files are accessible at blueprintname/static. But for some reason, it doesn't work.

My blueprint is like this:

app/frontend/views.py :

```<code>frontend = Blueprint('frontend', __name__,
                     template_folder='templates',
                     static_folder='static')

@frontend.route('/') etc...
</code>```

app/frontend/js/app.js : my javascript

Blueprint registered in Flask app (routes work and everything)

When I go to abc.com/frontend/static/js/app.js, it just gives a 404.

When I follow the Flask readme to get my static files:

```<code><script src="{{url_for('frontend.static', filename='js/app.js')}}"></script>
</code>```

The output is

```<code><script src="/static/js/app.js"></script>
</code>```

Which doesn't work either. There's nothing in my root app/static/ folder.

I can't access any static files in my blueprint! Flask read me says that it should work!

```<code>admin = Blueprint('admin', __name__, static_folder='static')
</code>```

By default the rightmost part of the path is where it is exposed on the web. Because the folder is called static here it will be available at the location of the blueprint + /static. Say the blueprint is registered for /admin the static folder will be at /admin/static.

答:
I'm a little late, but none of the previous answers did really help me in achieving what I needed. I found out that I needed to do a bit of "tricks" to make the module's static folder work as I intended.
My application is composed of several modules, but for now just pretend we had "application" as the main application folder and "locations" as the module's folder where a local "static" directory is placed (where we need to load static files for this module). The following is what I did:

In the main application's __init__py file I added url_prefix='/' to my Blueprint's definition

In my module's routes.py file I used both static parameters: static_folder='static' and 'static_url_path='/locations/static' to declare the Blueprint

In the html template (which extends a template in the main application's folder), I used the following to retrieve the path to the static css file: {{url_for('locations_bp.static', filename='css/style.css')}} (locations_bp is my Bluprint's name for "locations" module)

This way, the css file is loaded as /locations/static/css/style.css and this is exactly what I wanted to achieve: above all, the url_prefix I used allows me to avoid having a prefix on all my module's routes

Body:
According to the Flask readme, blueprint static files are accessible at blueprintname/static. But for some reason, it doesn't work.

My blueprint is like this:

app/frontend/views.py :

frontend = Blueprint('frontend', __name__,
                     template_folder='templates',
                     static_folder='static')

@frontend.route('/') etc...

app/frontend/js/app.js : my javascript

Blueprint registered in Flask app (routes work and everything)

When I go to abc.com/frontend/static/js/app.js, it just gives a 404.

When I follow the Flask readme to get my static files:

The output is

Which doesn't work either. There's nothing in my root app/static/ folder.

I can't access any static files in my blueprint! Flask read me says that it should work!

admin = Blueprint('admin', __name__, static_folder='static')

By default the rightmost part of the path is where it is exposed on the web. Because the folder is called static here it will be available at the location of the blueprint + /static. Say the blueprint is registered for /admin the static folder will be at /admin/static.


答:
does this work for you?

window.addEventListener('scroll', function(e) {
    console.log(window.scrollY);
    if (window.scrollY <= 0) {
      alert('TOP');
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br></code>```

Title: How do I detect scrolling past the start of the page using Javascript?

Body:
does this work for you?

window.addEventListener('scroll', function(e) {
    console.log(window.scrollY);
    if (window.scrollY <= 0) {
      alert('TOP');
    }
});

test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>
test<br>
test<br>test<br>
test<br>test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>


问:
I'm having troubles displaying an image from JSON in a Table View
I'm trying to display images that comes from an API. The images are inside an URL and I want to fill a Table View with all the array, but it shows only one image at the Table View.

Here's my code:

```<code>   struct Autos {
        let Marca:String
        let Modelo:String
        let Precio:String
        let RutaImagen:String

    init?(_ dict:[String:Any]?){
        guard let _dict = dict,
            let marca=_dict["Marca"]as?String,
            let modelo=_dict["Modelo"]as?String,
            let precio=_dict["Precio"]as?String,
            let rutaImagen=_dict["RutaImagen"]as?String

            else { return nil }

        self.Marca = marca
        self.Modelo = modelo
        self.Precio = precio
        self.RutaImagen = rutaImagen
   }
}

  var arrAutos = [Autos]()

 func getImage(from string: String) -> UIImage? {
        // Get valid URL
        guard let url = URL(string: string)
            else {
                print("Unable to create URL")
                return nil
        }
    var image: UIImage? = nil
    do {
        // Get valid data
        let data = try Data(contentsOf: url, options: [])

        // Make image
        image = UIImage(data: data)
    }
    catch {
        print(error.localizedDescription)
    }

    return image
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 9
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      let cell = tableView.dequeueReusableCell(withIdentifier: "carsCell", for: indexPath) as! CarsDetailTableViewCell
      let url = URL(string: "http://ws-smartit.divisionautomotriz.com/wsApiCasaTrust/api/autos")!

        let task = URLSession.shared.dataTask(with: url) {
            (data, response, error) in

            guard let dataResponse = data, error == nil else {
                print(error?.localizedDescription ?? "Response Error")
                return
            }

            do {
                let jsonResponse = try JSONSerialization.jsonObject(with: dataResponse, options: []) as? NSArray
                self.arrAutos = jsonResponse!.compactMap({ Autos($0 as? [String:String])})

                DispatchQueue.main.async {
                    // Get valid string
                    let string = self.arrAutos[indexPath.row].RutaImagen
                    if let image = self.getImage(from: string) {
                        // Apply image
                        cell.imgCar.image = image
                    }
                    cell.lblBrand.text = self.arrAutos[indexPath.row].Marca
                    cell.lblPrice.text = self.arrAutos[indexPath.row].Precio
                    cell.lblModel.text = self.arrAutos[indexPath.row].Modelo
                }

            } catch let parsingError {
                print("Error", parsingError)
            }
        }
        task.resume()

    return cell
}
</code>```

The JSON serialization is working fine, because the other data is showed correctly at the table view, the issue is with the image, because in the table view only appears one image, the other rows are empty. Does anyone have an advise?

答:
I think you should download your full data before loading tableview and reload tableview in the completion handler. Call loadData() method in your viewDidLoad().

```<code>fileprivate func loadData() {

    let url = URL(string: "http://ws-smartit.divisionautomotriz.com/wsApiCasaTrust/api/autos")!

    let task = URLSession.shared.dataTask(with: url) {
        (data, response, error) in

        guard let dataResponse = data, error == nil else {
            print(error?.localizedDescription ?? "Response Error")
            return
        }

        do {
            let jsonResponse = try JSONSerialization.jsonObject(with: dataResponse, options: []) as? NSArray
            self.arrAutos = jsonResponse!.compactMap({ Autos($0 as? [String:String])})

            DispatchQueue.main.async {
                self.tableView.reloadData()
            }

        } catch let parsingError {
            print("Error", parsingError)
        }
    }
    task.resume()
}
</code>```

For loading images in tableView cell, download the image in background thread and then update the imageView in the main thread.

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "carsCell", for: indexPath) as! CarsDetailTableViewCell

        // Get valid string
    let string = self.arrAutos[indexPath.row].RutaImagen
        //print(string)
    cell.lblBrand.text = self.arrAutos[indexPath.row].Marca
    cell.lblPrice.text = self.arrAutos[indexPath.row].Precio
    cell.lblModel.text = self.arrAutos[indexPath.row].Modelo
    let url = URL(string: string)
    if url != nil {
        DispatchQueue.global().async {
            let data = try? Data(contentsOf: url!)
            DispatchQueue.main.async {
                if data != nil {
                    cell.imgCar.image = UIImage(data:data!)
                }
            }
        }
    }
    return cell
}
</code>```

Hope this will work.

Body:
I'm trying to display images that comes from an API. The images are inside an URL and I want to fill a Table View with all the array, but it shows only one image at the Table View.

Here's my code:

   struct Autos {
        let Marca:String
        let Modelo:String
        let Precio:String
        let RutaImagen:String

    init?(_ dict:[String:Any]?){
        guard let _dict = dict,
            let marca=_dict["Marca"]as?String,
            let modelo=_dict["Modelo"]as?String,
            let precio=_dict["Precio"]as?String,
            let rutaImagen=_dict["RutaImagen"]as?String

            else { return nil }

        self.Marca = marca
        self.Modelo = modelo
        self.Precio = precio
        self.RutaImagen = rutaImagen
   }
}

  var arrAutos = [Autos]()

 func getImage(from string: String) -> UIImage? {
        // Get valid URL
        guard let url = URL(string: string)
            else {
                print("Unable to create URL")
                return nil
        }
    var image: UIImage? = nil
    do {
        // Get valid data
        let data = try Data(contentsOf: url, options: [])

        // Make image
        image = UIImage(data: data)
    }
    catch {
        print(error.localizedDescription)
    }

    return image
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 9
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      let cell = tableView.dequeueReusableCell(withIdentifier: "carsCell", for: indexPath) as! CarsDetailTableViewCell
      let url = URL(string: "http://ws-smartit.divisionautomotriz.com/wsApiCasaTrust/api/autos")!

        let task = URLSession.shared.dataTask(with: url) {
            (data, response, error) in

            guard let dataResponse = data, error == nil else {
                print(error?.localizedDescription ?? "Response Error")
                return
            }

            do {
                let jsonResponse = try JSONSerialization.jsonObject(with: dataResponse, options: []) as? NSArray
                self.arrAutos = jsonResponse!.compactMap({ Autos($0 as? [String:String])})

                DispatchQueue.main.async {
                    // Get valid string
                    let string = self.arrAutos[indexPath.row].RutaImagen
                    if let image = self.getImage(from: string) {
                        // Apply image
                        cell.imgCar.image = image
                    }
                    cell.lblBrand.text = self.arrAutos[indexPath.row].Marca
                    cell.lblPrice.text = self.arrAutos[indexPath.row].Precio
                    cell.lblModel.text = self.arrAutos[indexPath.row].Modelo
                }

            } catch let parsingError {
                print("Error", parsingError)
            }
        }
        task.resume()

    return cell
}

The JSON serialization is working fine, because the other data is showed correctly at the table view, the issue is with the image, because in the table view only appears one image, the other rows are empty. Does anyone have an advise?

Body:
I think you should download your full data before loading tableview and reload tableview in the completion handler. Call loadData() method in your viewDidLoad().

fileprivate func loadData() {

    let url = URL(string: "http://ws-smartit.divisionautomotriz.com/wsApiCasaTrust/api/autos")!

    let task = URLSession.shared.dataTask(with: url) {
        (data, response, error) in

        guard let dataResponse = data, error == nil else {
            print(error?.localizedDescription ?? "Response Error")
            return
        }

        do {
            let jsonResponse = try JSONSerialization.jsonObject(with: dataResponse, options: []) as? NSArray
            self.arrAutos = jsonResponse!.compactMap({ Autos($0 as? [String:String])})

            DispatchQueue.main.async {
                self.tableView.reloadData()
            }

        } catch let parsingError {
            print("Error", parsingError)
        }
    }
    task.resume()
}

For loading images in tableView cell, download the image in background thread and then update the imageView in the main thread.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "carsCell", for: indexPath) as! CarsDetailTableViewCell

        // Get valid string
    let string = self.arrAutos[indexPath.row].RutaImagen
        //print(string)
    cell.lblBrand.text = self.arrAutos[indexPath.row].Marca
    cell.lblPrice.text = self.arrAutos[indexPath.row].Precio
    cell.lblModel.text = self.arrAutos[indexPath.row].Modelo
    let url = URL(string: string)
    if url != nil {
        DispatchQueue.global().async {
            let data = try? Data(contentsOf: url!)
            DispatchQueue.main.async {
                if data != nil {
                    cell.imgCar.image = UIImage(data:data!)
                }
            }
        }
    }
    return cell
}

Hope this will work.


问:
Replace two input text values with values from each other on button click
I  have an html form with two input fields, in first one user puts name of first town, and in other second town, after form is submitted users gets directions how to go from first town to second town.

I want to enable user to click button "Change directions" and to automatically change first town name into second and second town name into first and vise versa. ( A to B, B to A)

I guess i'm supposed to use javascript, but I'm new at it and can't get a clue anywhere.

Can anyone help me please?

```<code>input type="text" size="25" id="fromAddress" name="from"
 value=""/>
  <input name="submit1" type="submit" value="Change directions" />
<input type="text" size="25" id="toAddress" name="to"
 value="" />
<input name="submit" type="submit" value="OK" />
</code>```

答:
I would recommend jQuery if you are a beginner.

```<code>jQuery('#submit1').click(function() {
     var fromAddress = jQuery('#fromAddress').val();
     var toAddress = jQuery('#toAddress').val();

     jQuery('#fromAddress').val('toAddress');
     jQuery('#toAddress').val('fromAddress');
});
</code>```

This is just a quick sample of how you could do it. You will need the jQuery library, and I would recommend a basic knowledge of jQuery .

http://jquery.com/

Body:
I  have an html form with two input fields, in first one user puts name of first town, and in other second town, after form is submitted users gets directions how to go from first town to second town.

I want to enable user to click button "Change directions" and to automatically change first town name into second and second town name into first and vise versa. ( A to B, B to A)

I guess i'm supposed to use javascript, but I'm new at it and can't get a clue anywhere.

Can anyone help me please?

input type="text" size="25" id="fromAddress" name="from"
 value=""/>
  <input name="submit1" type="submit" value="Change directions" />
<input type="text" size="25" id="toAddress" name="to"
 value="" />
<input name="submit" type="submit" value="OK" />

Body:
I would recommend jQuery if you are a beginner.

jQuery('#submit1').click(function() {
     var fromAddress = jQuery('#fromAddress').val();
     var toAddress = jQuery('#toAddress').val();

     jQuery('#fromAddress').val('toAddress');
     jQuery('#toAddress').val('fromAddress');
});

This is just a quick sample of how you could do it. You will need the jQuery library, and I would recommend a basic knowledge of jQuery .

http://jquery.com/


问:
DotCMS page API does not return "layout" field
I want to use the Layout-as-a-Service (LaaS) feature of DotCMS. This approach is documented in
 https://dotcms.com/blog/post/more-than-a-headless-cms-layout-as-a-service-in-dotcms and also
in https://github.com/fmontes/dotcms-page.

Both articles suggest, that the DotCMS page API should return a field called "layout" in the response, e.g. to http://localhost:8080/api/v1/page/json/test-page

test-page is a page, which is using a standard template. By standard template, I mean template created with "Template Designer", with a 20% sidebar on the left, one 100% width column, both containing "Blank container".

No matter what I try, the "layout" field is never part of the response. All I get is this:

```<code>{
  "errors": [],
  "entity": {
    "canCreateTemplate": true,
    "containers": ...,
    "numberContents": 2,
    "page": ...,
    "site": ...,
    "template": ...,
    "viewAs": ...  },
  "messages": [],
  "i18nMessagesMap": {},
  "permissions": []
}
</code>```

I tried DotCMS version 5.2.0 and also 5.2.3.
Is this perhaps a feature of the Enterprise edition only?

Edit: What I expect:

```<code>{
  "errors": [],
  "entity": {
    "canCreateTemplate": true,
    "containers": ...,
    "layout": {
      "width": "responsive",
      "title": "mytemplate1",
      "header": true,
      "footer": true,
      "body": {
        "rows": [
          {
            "columns": [
              {
                "containers": [
                  {
                    "identifier": "b5ea1513-7653-4602-a729-97cd8dd099b6",
                    "uuid": "1582123997023"
                  }
                ],
                "widthPercent": 100,
                "leftOffset": 1,
                "styleClass": null,
                "preview": false,
                "width": 12,
                "left": 0
              }
            ],
            "styleClass": null
          }
        ]
      },
      "sidebar": {
        "containers": [
          {
            "identifier": "b5ea1513-7653-4602-a729-97cd8dd099b6",
            "uuid": "1582123991866"
          }
        ],
        "location": "left",
        "width": "small",
        "widthPercent": 20,
        "preview": false
      }
    }
    ...
</code>```

答:
Your page needs to use a "layout template" in order to retrieve the layout from dotCMS - using an advanced template won't work.

Also, layouts are part of the enterprise edition.  Make sure you have a license in order to use the layout manager.

Body:
I want to use the Layout-as-a-Service (LaaS) feature of DotCMS. This approach is documented in
 https://dotcms.com/blog/post/more-than-a-headless-cms-layout-as-a-service-in-dotcms and also
in https://github.com/fmontes/dotcms-page.

Both articles suggest, that the DotCMS page API should return a field called "layout" in the response, e.g. to http://localhost:8080/api/v1/page/json/test-page

test-page is a page, which is using a standard template. By standard template, I mean template created with "Template Designer", with a 20% sidebar on the left, one 100% width column, both containing "Blank container".

No matter what I try, the "layout" field is never part of the response. All I get is this:

{
  "errors": [],
  "entity": {
    "canCreateTemplate": true,
    "containers": ...,
    "numberContents": 2,
    "page": ...,
    "site": ...,
    "template": ...,
    "viewAs": ...  },
  "messages": [],
  "i18nMessagesMap": {},
  "permissions": []
}

I tried DotCMS version 5.2.0 and also 5.2.3.
Is this perhaps a feature of the Enterprise edition only?

Edit: What I expect:

{
  "errors": [],
  "entity": {
    "canCreateTemplate": true,
    "containers": ...,
    "layout": {
      "width": "responsive",
      "title": "mytemplate1",
      "header": true,
      "footer": true,
      "body": {
        "rows": [
          {
            "columns": [
              {
                "containers": [
                  {
                    "identifier": "b5ea1513-7653-4602-a729-97cd8dd099b6",
                    "uuid": "1582123997023"
                  }
                ],
                "widthPercent": 100,
                "leftOffset": 1,
                "styleClass": null,
                "preview": false,
                "width": 12,
                "left": 0
              }
            ],
            "styleClass": null
          }
        ]
      },
      "sidebar": {
        "containers": [
          {
            "identifier": "b5ea1513-7653-4602-a729-97cd8dd099b6",
            "uuid": "1582123991866"
          }
        ],
        "location": "left",
        "width": "small",
        "widthPercent": 20,
        "preview": false
      }
    }
    ...


问:
Identity-layout-renderer is not rendering anything for .NET Core console Application
I have a .NET Core Console application.

like this:

```<code>  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFrameworks>netcoreapp2.1;netcoreapp3.1</TargetFrameworks>
  </PropertyGroup>
</code>```

I'm running on Windows 10 with VS 2019.

I cannot get the below layout renderer to log anything.

https://github.com/NLog/NLog/wiki/Identity-layout-renderer

```<code>${identity:authType=Boolean:separator=String:name=Boolean
          :isAuthenticated=Boolean}
</code>```

My nlog.config

<?xml version="1.0" encoding="utf-8" ?>

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xsi:schemaLocation="NLog NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogFile="MyApp.NLog.INTERNAL.log"
      internalLogLevel="Info" >

  <targets>

    <target xsi:type="File" name="target1" fileName="MyApp.NLog.${shortdate}.log"
            layout="${date}|${level:uppercase=true}|${logger}|***|${identity:authType=true:separator=/:name=true:isAuthenticated=true}|****|${message} ${exception:format=toString,Data}|${all-event-properties}" />

  </targets>

  <rules>
    <logger name="*" minlevel="Trace" writeTo="target1" />
  </rules>
</nlog>
```

<p>example log:  :(</p>

```2020/02/19 12:03:40.617|INFO|MyCompany.MyObject|***||****|HeyYouThere |
```

<p>Nothing between ***||**** :(</p>

<p>and nlog internal log output (MyApp.NLog.INTERNAL.log) (no errors)</p>

```2020-02-19 12:03:38.3612 Info Auto loading assembly file: c:\myfolder1\myfolder2\bin\Debug\netcoreapp3.1\NLog.Extensions.Logging.dll
2020-02-19 12:03:38.3734 Info Loading assembly file: c:\myfolder1\myfolder2\bin\Debug\netcoreapp3.1\NLog.Extensions.Logging.dll
2020-02-19 12:03:38.3847 Info NLog.Extensions.Logging, Version=1.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c. File version: 1.6.1.1203. Product version: 1.6.1.
2020-02-19 12:03:38.3847 Info Auto loading assembly file: c:\myfolder1\myfolder2\bin\Debug\netcoreapp3.1\NLog.Extensions.Logging.dll succeeded!
2020-02-19 12:03:38.3847 Info Auto loading assembly file: c:\myfolder1\myfolder2\bin\Debug\netcoreapp3.1\NLog.WindowsIdentity.dll
2020-02-19 12:03:38.3847 Info Loading assembly file: c:\myfolder1\myfolder2\bin\Debug\netcoreapp3.1\NLog.WindowsIdentity.dll
2020-02-19 12:03:38.3938 Info NLog.WindowsIdentity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c. File version: 4.6.8.10751. Product version: 4.6.8.
2020-02-19 12:03:38.3938 Info Auto loading assembly file: c:\myfolder1\myfolder2\bin\Debug\netcoreapp3.1\NLog.WindowsIdentity.dll succeeded!
2020-02-19 12:03:38.3938 Info Message Template Auto Format enabled
2020-02-19 12:03:38.4652 Info Adding target FileTarget(Name=target1)
2020-02-19 12:03:38.5111 Info Found 39 configuration items
2020-02-19 12:03:38.5614 Info Configuration file change detected! Reloading in 1000ms...
2020-02-19 12:03:38.5614 Info Configuration file change detected! Reloading in 1000ms...
2020-02-19 12:03:39.5688 Info Reloading configuration...
2020-02-19 12:03:39.5688 Info Configuring from an XML element in c:\myfolder1\myfolder2\bin\Debug\netcoreapp3.1\nlog.config...
2020-02-19 12:03:39.5688 Info Message Template Auto Format enabled
2020-02-19 12:03:39.5688 Info Adding target FileTarget(Name=target1)
2020-02-19 12:03:39.5688 Info Closing old configuration.
2020-02-19 12:03:39.5987 Info Found 39 configuration items
```

<p>Nuget packages</p>

```  <ItemGroup>
    <PackageReference Include="NLog" Version="4.6.8" />
    <PackageReference Include="NLog.Extensions.Logging" Version="1.6.1" />
    <PackageReference Include="NLog.WindowsIdentity" Version="4.6.8" />
  </ItemGroup>
```

<p>As far as I can see, it looks like I have the nuget package</p>

```.nuget\packages\nlog\4.6.8\lib\netstandard2.0\NLog.dll
namespace NLog.LayoutRenderers
{
    [LayoutRenderer("identity")]
    public class IdentityLayoutRenderer : LayoutRenderer
```

答:
So the code in

https://github.com/NLog/NLog/blob/dev/src/NLog/LayoutRenderers/IdentityLayoutRenderer.cs

here is the primary piece of code:

```<code>    private static IIdentity GetValue()
    {
        var currentPrincipal = System.Threading.Thread.CurrentPrincipal;
        return currentPrincipal?.Identity;
    }
</code>```

When I run the below (slightly edited, just to see what it does)

```<code>        var currentPrincipal = System.Threading.Thread.CurrentPrincipal;
        var ident = currentPrincipal?.Identity;
</code>```

ident is null.

So that's why I get nothing in the log file.............the code resolves to null.

goFigure

So after a little homework.

The Thread.CurrentPrincipal is purposely empty.

In ASP.NET CORE, one would do something like this (typical internet answer I found)

You basically take advantage of the complete Dependency Injection overhaul.......and use that.

And with the DI approach, do you NOT rely on System.Threading.Thread.CurrentPrincipal; "being around".  (Keep reading for a work-around to this)

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    services.AddTransient<IPrincipal>(
        provider => provider.GetService<IHttpContextAccessor>().HttpContext.User);

    // ...
}
</code>```

With DotNet.Core (console app)... you probably have to add one

pseudo code below

```<code>public void ConfigureServices(IServiceCollection services)
{
    ClaimsPrincipal myprinc = new ClaimsPrincipal(  /* you'll need a ClaimsIdentity and some claims here probably */ );

    //or
    GenericPrincipal myprinc = new GenericPrincipal ( /* you'll need GenericIdentity and some roles here probably */ );

    services.AddTransient<IPrincipal>(
        provider => myprinc);

    // ...
}
</code>```

So this was not an NLog issue.  This was how DotNetCore handles System.Threading.Thread.CurrentPrincipal; differently.

Here is a good read:

https://davidpine.net/blog/principal-architecture-changes/

Now for the workaround:

I have verified that if I do this:

```<code>AppDomain.CurrentDomain.SetPrincipalPolicy(System.Security.Principal.PrincipalPolicy.WindowsPrincipal);

var currentPrincipal = System.Threading.Thread.CurrentPrincipal;
var ident = currentPrincipal?.Identity;
</code>```

I get what I (used to) expect!

and the log message.

```<code>2020/02/19 12:03:40.617|INFO|MyCompany.MyObject|***|MyDomain\MyUserName|****|HeyYouThere |
</code>```

I need to run on my linux box to see what happens (if I find time).. Maybe a "does not exist in the current context" exception ??

Please do not use the "AppDomain.CurrentDomain.SetPrincipalPolicy" blindly.
Read the davidpine article about why System.Threading.Thread.CurrentPrincipal; is oldSchool.  And DI is probably the better approach going forward.

Also (if you choose to use) :

Here is the enum:

https://learn.microsoft.com/en-us/dotnet/api/system.security.principal.principalpolicy?view=netcore-3.1

Fields

NoPrincipal   1    No principal or identity objects should be
created.

UnauthenticatedPrincipal  0    Principal and identity objects for the
unauthenticated entity should be created. An unauthenticated entity
has Name set to the empty string ("") and IsAuthenticated set to
false.

WindowsPrincipal  2    Principal and identity objects that reflect the
operating system token associated with the current execution thread
should be created, and the associated operating system groups should
be mapped into roles.

You should consider each of the values.  And you should consider the "what happens on linux" issue, if you need that.

Will this happen?

"'Windows Principal functionality is not supported on this platform.'"

Body:
I have a .NET Core Console application.

like this:

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFrameworks>netcoreapp2.1;netcoreapp3.1</TargetFrameworks>
  </PropertyGroup>

I'm running on Windows 10 with VS 2019.

I cannot get the below layout renderer to log anything.

https://github.com/NLog/NLog/wiki/Identity-layout-renderer

${identity:authType=Boolean:separator=String:name=Boolean
          :isAuthenticated=Boolean}

My nlog.config

<?xml version="1.0" encoding="utf-8" ?>

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xsi:schemaLocation="NLog NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogFile="MyApp.NLog.INTERNAL.log"
      internalLogLevel="Info" >

  <targets>

    <target xsi:type="File" name="target1" fileName="MyApp.NLog.${shortdate}.log"
            layout="${date}|${level:uppercase=true}|${logger}|***|${identity:authType=true:separator=/:name=true:isAuthenticated=true}|****|${message} ${exception:format=toString,Data}|${all-event-properties}" />

  </targets>

  <rules>
    <logger name="*" minlevel="Trace" writeTo="target1" />
  </rules>
</nlog>

example log:  :(

2020/02/19 12:03:40.617|INFO|MyCompany.MyObject|***||****|HeyYouThere |

Nothing between ***||**** :(

and nlog internal log output (MyApp.NLog.INTERNAL.log) (no errors)

2020-02-19 12:03:38.3612 Info Auto loading assembly file: c:\myfolder1\myfolder2\bin\Debug\netcoreapp3.1\NLog.Extensions.Logging.dll
2020-02-19 12:03:38.3734 Info Loading assembly file: c:\myfolder1\myfolder2\bin\Debug\netcoreapp3.1\NLog.Extensions.Logging.dll
2020-02-19 12:03:38.3847 Info NLog.Extensions.Logging, Version=1.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c. File version: 1.6.1.1203. Product version: 1.6.1.
2020-02-19 12:03:38.3847 Info Auto loading assembly file: c:\myfolder1\myfolder2\bin\Debug\netcoreapp3.1\NLog.Extensions.Logging.dll succeeded!
2020-02-19 12:03:38.3847 Info Auto loading assembly file: c:\myfolder1\myfolder2\bin\Debug\netcoreapp3.1\NLog.WindowsIdentity.dll
2020-02-19 12:03:38.3847 Info Loading assembly file: c:\myfolder1\myfolder2\bin\Debug\netcoreapp3.1\NLog.WindowsIdentity.dll
2020-02-19 12:03:38.3938 Info NLog.WindowsIdentity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c. File version: 4.6.8.10751. Product version: 4.6.8.
2020-02-19 12:03:38.3938 Info Auto loading assembly file: c:\myfolder1\myfolder2\bin\Debug\netcoreapp3.1\NLog.WindowsIdentity.dll succeeded!
2020-02-19 12:03:38.3938 Info Message Template Auto Format enabled
2020-02-19 12:03:38.4652 Info Adding target FileTarget(Name=target1)
2020-02-19 12:03:38.5111 Info Found 39 configuration items
2020-02-19 12:03:38.5614 Info Configuration file change detected! Reloading in 1000ms...
2020-02-19 12:03:38.5614 Info Configuration file change detected! Reloading in 1000ms...
2020-02-19 12:03:39.5688 Info Reloading configuration...
2020-02-19 12:03:39.5688 Info Configuring from an XML element in c:\myfolder1\myfolder2\bin\Debug\netcoreapp3.1\nlog.config...
2020-02-19 12:03:39.5688 Info Message Template Auto Format enabled
2020-02-19 12:03:39.5688 Info Adding target FileTarget(Name=target1)
2020-02-19 12:03:39.5688 Info Closing old configuration.
2020-02-19 12:03:39.5987 Info Found 39 configuration items

Nuget packages

  <ItemGroup>
    <PackageReference Include="NLog" Version="4.6.8" />
    <PackageReference Include="NLog.Extensions.Logging" Version="1.6.1" />
    <PackageReference Include="NLog.WindowsIdentity" Version="4.6.8" />
  </ItemGroup>

As far as I can see, it looks like I have the nuget package

.nuget\packages\nlog\4.6.8\lib\netstandard2.0\NLog.dll
namespace NLog.LayoutRenderers
{
    [LayoutRenderer("identity")]
    public class IdentityLayoutRenderer : LayoutRenderer

Body:
So the code in

https://github.com/NLog/NLog/blob/dev/src/NLog/LayoutRenderers/IdentityLayoutRenderer.cs

here is the primary piece of code:

    private static IIdentity GetValue()
    {
        var currentPrincipal = System.Threading.Thread.CurrentPrincipal;
        return currentPrincipal?.Identity;
    }

When I run the below (slightly edited, just to see what it does)

        var currentPrincipal = System.Threading.Thread.CurrentPrincipal;
        var ident = currentPrincipal?.Identity;

ident is null.

So that's why I get nothing in the log file.............the code resolves to null.

goFigure

So after a little homework.

The Thread.CurrentPrincipal is purposely empty.

In ASP.NET CORE, one would do something like this (typical internet answer I found)

You basically take advantage of the complete Dependency Injection overhaul.......and use that.

And with the DI approach, do you NOT rely on System.Threading.Thread.CurrentPrincipal; "being around".  (Keep reading for a work-around to this)

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    services.AddTransient<IPrincipal>(
        provider => provider.GetService<IHttpContextAccessor>().HttpContext.User);

    // ...
}

With DotNet.Core (console app)... you probably have to add one

pseudo code below

public void ConfigureServices(IServiceCollection services)
{
    ClaimsPrincipal myprinc = new ClaimsPrincipal(  /* you'll need a ClaimsIdentity and some claims here probably */ );

    //or
    GenericPrincipal myprinc = new GenericPrincipal ( /* you'll need GenericIdentity and some roles here probably */ );

    services.AddTransient<IPrincipal>(
        provider => myprinc);

    // ...
}

So this was not an NLog issue.  This was how DotNetCore handles System.Threading.Thread.CurrentPrincipal; differently.

Here is a good read:

https://davidpine.net/blog/principal-architecture-changes/

Now for the workaround:

I have verified that if I do this:

AppDomain.CurrentDomain.SetPrincipalPolicy(System.Security.Principal.PrincipalPolicy.WindowsPrincipal);

var currentPrincipal = System.Threading.Thread.CurrentPrincipal;
var ident = currentPrincipal?.Identity;

I get what I (used to) expect!

and the log message.

2020/02/19 12:03:40.617|INFO|MyCompany.MyObject|***|MyDomain\MyUserName|****|HeyYouThere |

I need to run on my linux box to see what happens (if I find time).. Maybe a "does not exist in the current context" exception ??

Please do not use the "AppDomain.CurrentDomain.SetPrincipalPolicy" blindly.
Read the davidpine article about why System.Threading.Thread.CurrentPrincipal; is oldSchool.  And DI is probably the better approach going forward.

Also (if you choose to use) :

Here is the enum:

https://learn.microsoft.com/en-us/dotnet/api/system.security.principal.principalpolicy?view=netcore-3.1

Fields

NoPrincipal   1    No principal or identity objects should be
created.

UnauthenticatedPrincipal  0    Principal and identity objects for the
unauthenticated entity should be created. An unauthenticated entity
has Name set to the empty string ("") and IsAuthenticated set to
false.

WindowsPrincipal  2    Principal and identity objects that reflect the
operating system token associated with the current execution thread
should be created, and the associated operating system groups should
be mapped into roles.

You should consider each of the values.  And you should consider the "what happens on linux" issue, if you need that.

Will this happen?

"'Windows Principal functionality is not supported on this platform.'"


问:
Is there a robust way to register dependencies in ASP.NET Core 3.1 beside adding everything into Startup class?
I have an ASP.NET Core 3.1 project. Typically, I register any dependency using the ConfigureServices() method in the Startup.cs class.

But, I find myself having to register lots of dependencies and the ConfigureServices() looks huge! I know I can probably create an extension method of a static method and call it from the ConfigureService()` class, but wondering if there is a better way.

If there a way to register dependencies in the IoC container without having to define them one at a time like this

```<code>services.AddScoped<Interface, Class>();
.... 200 lines later
services.AddScoped<ISettings, Settings>()
</code>```

答:
Grouping related dependencies into custom extension methods is a very common way to do this. ASP.NET Core already does this for many of the internal services, and you can easily expand on top of that and set them up the way you need for your application. For example to set up authentication and authorization:

```<code>public IServiceCollection AddSecurity(this IServiceCollection services)
{
    services.AddAuthentication()
        .AddCookie();

    service.AddAuthorization(options =>
    {
        options.DefaultPolicy = …;
    });

    return services;
}
</code>```

You can do the same for your application-specific services and group them logically in separate extension methods.

If you have a lot of service registrations that are very similar, you can also employ a convention-based registration e.g. using Scrutor. For example, this registers all services within a certain namespace as transient for their respective interface:

```<code>services.Scan(scan => scan
    .FromAssemblyOf<Startup>()
        .AddClasses(c => c.InNamespaces("MyApp.Services"))
            .AsImplementedInterfaces()
            .WithTransientLifetime()
);
</code>```

Scrutor allows for very complex rules to scan for services, so if your services do follow some pattern, you will likely be able to come up with a rule for that.

Body:
I have an ASP.NET Core 3.1 project. Typically, I register any dependency using the ConfigureServices() method in the Startup.cs class.

But, I find myself having to register lots of dependencies and the ConfigureServices() looks huge! I know I can probably create an extension method of a static method and call it from the ConfigureService()` class, but wondering if there is a better way.

If there a way to register dependencies in the IoC container without having to define them one at a time like this

services.AddScoped<Interface, Class>();
.... 200 lines later
services.AddScoped<ISettings, Settings>()

Body:
Grouping related dependencies into custom extension methods is a very common way to do this. ASP.NET Core already does this for many of the internal services, and you can easily expand on top of that and set them up the way you need for your application. For example to set up authentication and authorization:

public IServiceCollection AddSecurity(this IServiceCollection services)
{
    services.AddAuthentication()
        .AddCookie();

    service.AddAuthorization(options =>
    {
        options.DefaultPolicy = …;
    });

    return services;
}

You can do the same for your application-specific services and group them logically in separate extension methods.

If you have a lot of service registrations that are very similar, you can also employ a convention-based registration e.g. using Scrutor. For example, this registers all services within a certain namespace as transient for their respective interface:

services.Scan(scan => scan
    .FromAssemblyOf<Startup>()
        .AddClasses(c => c.InNamespaces("MyApp.Services"))
            .AsImplementedInterfaces()
            .WithTransientLifetime()
);

Scrutor allows for very complex rules to scan for services, so if your services do follow some pattern, you will likely be able to come up with a rule for that.


问:
Installation SDK 7.1
I want to ask about an error I faced durring the installation of SDK 7.1 compiler in order to compile .c files under matlab, knowing that I've downloaded SDK ISO and .exe but without use, from this link
http://www.microsoft.com/en-us/download/details.aspx?id=8279
I'm using Matlab 2013b,Windows7 64 bit
I got this error every time

Setup could not find the file WinSDK_amd64\WinSDK_amd64.msi at any of the specified source locations G:\Setup

答: You can find it using Visual Studio 2019 installer under the name "C++ Windows XP Support for VS 2017 (v141) tools [Deprecated]".</p>

Title: Installation SDK 7.1


问:
Difference between VARCHAR and TEXT in MySQL
When we create a table in MySQL with a VARCHAR column, we have to set the length for it. But for TEXT type we don't have to provide the length.

What are the differences between VARCHAR and TEXT?

答:
There is an important detail that has been omitted in the answer above.

MySQL imposes a limit of 65,535 bytes for the max size of each row.
The size of a VARCHAR column is counted towards the maximum row size, while TEXT columns are assumed to be storing their data by reference so they only need 9-12 bytes. That means even if the "theoretical" max size of your VARCHAR field is 65,535 characters you won't be able to achieve that if you have more than one column in your table.

Also note that the actual number of bytes required by a VARCHAR field is dependent on the encoding of the column (and the content). MySQL counts the maximum possible bytes used toward the max row size, so if you use a multibyte encoding like utf8mb4 (which you almost certainly should) it will use up even more of your maximum row size.

Correction: Regardless of how MySQL computes the max row size, whether or not the   VARCHAR/TEXT field data is ACTUALLY stored in the row or stored by reference depends on your underlying storage engine. For InnoDB the row format affects this behavior. (Thanks Bill-Karwin)

Reasons to use TEXT:

If you want to store a paragraph or more of text

If you don't need to index the column

If you have reached the row size limit for your table

Reasons to use VARCHAR:

If you want to store a few words or a sentence

If you want to index the (entire) column

If you want to use the column with foreign-key constraints


问:
Filtering items by their exact title
I am trying to filter my items by exact title by clicking on the link with the title. I managed to display the titles, but when I click on one of them I am getting an error: Reverse for 'category_search' with arguments '('',)' not found. 1 pattern(s) tried: ['search/(?P<category_id>[0-9]+)$'] , which is pointing to the TitleView function.

views.py- Just to clear some things up category_view is used to filter items by their category, which is located on different page, but the results are displayed on search.html

```<code>def category_view(request, category_id):
  item_list = Item.objects.filter(category__pk=category_id)
  category = Category.objects.get(pk=category_id)

  return render(request, "search.html", {'item_list': item_list, 'category': category})

def TitleView(request, title):
  item_list = Item.objects.filter(title__iexact=title)
  return render(request, "search.html", {'item_list': item_list})

def SearchView(request, category_id=None, title=None):
  if category_id:
      category = Category.objects.get(pk=category_id)
      item_list = Item.objects.filter(category__id=category_id)
  else:
      item_list = Item.objects.all()

  query = request.GET.get('q')
  if query:
      item_list = item_list.filter(title__icontains=query)

  price_from = request.GET.get('price_from')
  price_to = request.GET.get('price_to')

  item_list = item_list.annotate(
      current_price=Coalesce('discount_price', 'price'))

  if price_from:
      item_list = item_list.filter(current_price__gte=price_from)

  if price_to:
      item_list = item_list.filter(current_price__lte=price_to)

  context = {
      'item_list': item_list,
      'category': category,
  }
  return render(request, "search.html", context)
</code>```

html template:

```<code>    <div class="offset-md-1 col-md-2">
    <h2>Content Filter</h2> <br>
    <form method="GET" action="{% url 'core:category_search' category.id %}">
        <h5>Search</h5>
        <div class="form-row">
            <div class="form-group col-8">
                <div class="input-group">
                    <input class="form-control py-2 border-right-0 border" type="search" name="q"
                        placeholder="Brand..">
                    <span class="input-group-append">
                        <div class="input-group-text bg-transparent">
                            <i class="fa fa-search"></i>
                        </div>
                    </span>
                </div>
            </div>
        </div>
        <h5>Price from</h5>
        <div class="form-row">
            <div class="form-group col-5">
                <div class="input-group">
                    <input class="form-control py-2 border-right-0 border" type="search" name="price_from"
                        placeholder="Price from" value="{{request.GET.price_from}}">
                    <span class="input-group-append">
                        <div class="input-group-text bg-transparent">
                            <i class="fa fa-search"></i>
                        </div>
                    </span>
                </div>
            </div>
        </div>
        <h5>Price to</h5>
        <div class="form-row">
            <div class="form-group col-5">
                <div class="input-group">
                    <input class="form-control py-2 border-right-0 border" type="search" name="price_to"
                        placeholder="Price to" value="{{request.GET.price_to}}">
                    <span class="input-group-append">
                        <div class="input-group-text bg-transparent">
                            <i class="fa fa-search"></i>
                        </div>
                    </span>
                </div>
            </div>
        </div>
        <div class="form-row">
            <button type="submit" class="btn btn-outline-primary btn-md">Search</button>
        </div>
    </form>
</div>
<ul>
    {% for item in item_list %}
    <li>
        <a href="{% url 'core:title_search' title=item.title  %}">
            {{ item.title }}
        </a>
    </li>
    {% endfor %}
</ul>
</code>```

urls:

```<code>  path('search/', SearchView, name='search'),
  path('search/<int:category_id>', SearchView, name='category_search'),
  path('search/<title>', TitleView, name='title_search'),
  path('bike-category/<category_id>', category_view, name='category'),
</code>```

答:
You need to supply the category in the template's context or use a different template. Given that you're returning a list, I'm not exactly sure how you're going to pull out a category from that.

If you intended this to be a direct link to each of the items, I recommend not using title as the searching property. Instead add a SlugField to your model and mark it as unique. Then use that in your url:

```<code>path('search/<slug:slug>/', item_view, name='item_view'),
</code>```

Then your view would be:

```<code>def item_view(request, slug):
  item = Item.objects.select_related('category').get(slug__iexact=slug)
  return render(request, "search.html", {
    'item_list': [item],
    'category': item.category
  })
</code>```

Edit:

```<code>def SearchView(request, category_id=None):
    if category_id:
      category = Category.objects.get(pk=category_id)
      item_list = Item.objects.filter(category__id=category_id)
  else:
      item_list = Item.objects.all()
  title = request.GET.get('title')
  if title:
      item_list = item_list.filter(title__iexact=title)
  else:
     query = request.GET.get('q')
      if query:
          item_list = item_list.filter(title__icontains=query)

      price_from = request.GET.get('price_from')
      price_to = request.GET.get('price_to')

      item_list = item_list.annotate(
          current_price=Coalesce('discount_price', 'price'))

      if price_from:
          item_list = item_list.filter(current_price__gte=price_from)

      if price_to:
          item_list = item_list.filter(current_price__lte=price_to)

  context = {
      'item_list': item_list,
      'category': category,
  }
  return render(request, "search.html", context)
</code>```

urls:

```<code> path('search/', SearchView, name='search'),
  path('search/<int:category_id>', SearchView, name='category_search'),
  path('bike-category/<int:category_id>', category_view, name='category'),
</code>```

Template:

```<code>    <div class="offset-md-1 col-md-2">
    <h2>Content Filter</h2> <br>
    <form method="GET" action="{% if category %}{% url 'core:category_search' category.id %}{% else %}{% url 'core:search' %}{% endif %}">
        <h5>Search</h5>
        <div class="form-row">
            <div class="form-group col-8">
                <div class="input-group">
                    <input class="form-control py-2 border-right-0 border" type="search" name="q"
                        placeholder="Brand..">
                    <span class="input-group-append">
                        <div class="input-group-text bg-transparent">
                            <i class="fa fa-search"></i>
                        </div>
                    </span>
                </div>
            </div>
        </div>
        <h5>Price from</h5>
        <div class="form-row">
            <div class="form-group col-5">
                <div class="input-group">
                    <input class="form-control py-2 border-right-0 border" type="search" name="price_from"
                        placeholder="Price from" value="{{request.GET.price_from}}">
                    <span class="input-group-append">
                        <div class="input-group-text bg-transparent">
                            <i class="fa fa-search"></i>
                        </div>
                    </span>
                </div>
            </div>
        </div>
        <h5>Price to</h5>
        <div class="form-row">
            <div class="form-group col-5">
                <div class="input-group">
                    <input class="form-control py-2 border-right-0 border" type="search" name="price_to"
                        placeholder="Price to" value="{{request.GET.price_to}}">
                    <span class="input-group-append">
                        <div class="input-group-text bg-transparent">
                            <i class="fa fa-search"></i>
                        </div>
                    </span>
                </div>
            </div>
        </div>
        <div class="form-row">
            <button type="submit" class="btn btn-outline-primary btn-md">Search</button>
        </div>
    </form>
</div>
<ul>
    {% for item in item_list %}
    <li>
        <a href="{% if category %}{% url 'core:category_search' category.id %}{% else %}{% url 'core:search' %}{% endif %}?title={{item.title}}">
            {{ item.title }}
        </a>
    </li>
    {% endfor %}
</ul>
</code>```

I think I handled the form's action attribute and the links href attributes properly. You might have to clean them up for your situation.

Title: Filtering items by their exact title

Body:
I am trying to filter my items by exact title by clicking on the link with the title. I managed to display the titles, but when I click on one of them I am getting an error: Reverse for 'category_search' with arguments '('',)' not found. 1 pattern(s) tried: ['search/(?P<category_id>[0-9]+)$'] , which is pointing to the TitleView function.

views.py- Just to clear some things up category_view is used to filter items by their category, which is located on different page, but the results are displayed on search.html

def category_view(request, category_id):
  item_list = Item.objects.filter(category__pk=category_id)
  category = Category.objects.get(pk=category_id)

  return render(request, "search.html", {'item_list': item_list, 'category': category})

def TitleView(request, title):
  item_list = Item.objects.filter(title__iexact=title)
  return render(request, "search.html", {'item_list': item_list})

def SearchView(request, category_id=None, title=None):
  if category_id:
      category = Category.objects.get(pk=category_id)
      item_list = Item.objects.filter(category__id=category_id)
  else:
      item_list = Item.objects.all()

  query = request.GET.get('q')
  if query:
      item_list = item_list.filter(title__icontains=query)

  price_from = request.GET.get('price_from')
  price_to = request.GET.get('price_to')

  item_list = item_list.annotate(
      current_price=Coalesce('discount_price', 'price'))

  if price_from:
      item_list = item_list.filter(current_price__gte=price_from)

  if price_to:
      item_list = item_list.filter(current_price__lte=price_to)

  context = {
      'item_list': item_list,
      'category': category,
  }
  return render(request, "search.html", context)

html template:

Content Filter

    <form method="GET" action="{% url 'core:category_search' category.id %}">

Search

                    <input class="form-control py-2 border-right-0 border" type="search" name="q"
                        placeholder="Brand..">

Price from

                    <input class="form-control py-2 border-right-0 border" type="search" name="price_from"
                        placeholder="Price from" value="{{request.GET.price_from}}">

Price to

                    <input class="form-control py-2 border-right-0 border" type="search" name="price_to"
                        placeholder="Price to" value="{{request.GET.price_to}}">

            <button type="submit" class="btn btn-outline-primary btn-md">Search</button>

    </form>

    {% for item in item_list %}

            {{ item.title }}

    {% endfor %}

urls:

  path('search/', SearchView, name='search'),
  path('search/<int:category_id>', SearchView, name='category_search'),
  path('search/<title>', TitleView, name='title_search'),
  path('bike-category/<category_id>', category_view, name='category'),

Body:
You need to supply the category in the template's context or use a different template. Given that you're returning a list, I'm not exactly sure how you're going to pull out a category from that.

If you intended this to be a direct link to each of the items, I recommend not using title as the searching property. Instead add a SlugField to your model and mark it as unique. Then use that in your url:

path('search/<slug:slug>/', item_view, name='item_view'),

Then your view would be:

def item_view(request, slug):
  item = Item.objects.select_related('category').get(slug__iexact=slug)
  return render(request, "search.html", {
    'item_list': [item],
    'category': item.category
  })

Edit:

def SearchView(request, category_id=None):
    if category_id:
      category = Category.objects.get(pk=category_id)
      item_list = Item.objects.filter(category__id=category_id)
  else:
      item_list = Item.objects.all()
  title = request.GET.get('title')
  if title:
      item_list = item_list.filter(title__iexact=title)
  else:
     query = request.GET.get('q')
      if query:
          item_list = item_list.filter(title__icontains=query)

      price_from = request.GET.get('price_from')
      price_to = request.GET.get('price_to')

      item_list = item_list.annotate(
          current_price=Coalesce('discount_price', 'price'))

      if price_from:
          item_list = item_list.filter(current_price__gte=price_from)

      if price_to:
          item_list = item_list.filter(current_price__lte=price_to)

  context = {
      'item_list': item_list,
      'category': category,
  }
  return render(request, "search.html", context)

urls:

 path('search/', SearchView, name='search'),
  path('search/<int:category_id>', SearchView, name='category_search'),
  path('bike-category/<int:category_id>', category_view, name='category'),

Template:

    <div class="offset-md-1 col-md-2">
    <h2>Content Filter</h2> <br>
    <form method="GET" action="{% if category %}{% url 'core:category_search' category.id %}{% else %}{% url 'core:search' %}{% endif %}">
        <h5>Search</h5>
        <div class="form-row">
            <div class="form-group col-8">
                <div class="input-group">
                    <input class="form-control py-2 border-right-0 border" type="search" name="q"
                        placeholder="Brand..">
                    <span class="input-group-append">
                        <div class="input-group-text bg-transparent">
                            <i class="fa fa-search"></i>
                        </div>
                    </span>
                </div>
            </div>
        </div>
        <h5>Price from</h5>
        <div class="form-row">
            <div class="form-group col-5">
                <div class="input-group">
                    <input class="form-control py-2 border-right-0 border" type="search" name="price_from"
                        placeholder="Price from" value="{{request.GET.price_from}}">
                    <span class="input-group-append">
                        <div class="input-group-text bg-transparent">
                            <i class="fa fa-search"></i>
                        </div>
                    </span>
                </div>
            </div>
        </div>
        <h5>Price to</h5>
        <div class="form-row">
            <div class="form-group col-5">
                <div class="input-group">
                    <input class="form-control py-2 border-right-0 border" type="search" name="price_to"
                        placeholder="Price to" value="{{request.GET.price_to}}">
                    <span class="input-group-append">
                        <div class="input-group-text bg-transparent">
                            <i class="fa fa-search"></i>
                        </div>
                    </span>
                </div>
            </div>
        </div>
        <div class="form-row">
            <button type="submit" class="btn btn-outline-primary btn-md">Search</button>
        </div>
    </form>
</div>
<ul>
    {% for item in item_list %}
    <li>
        <a href="{% if category %}{% url 'core:category_search' category.id %}{% else %}{% url 'core:search' %}{% endif %}?title={{item.title}}">
            {{ item.title }}
        </a>
    </li>
    {% endfor %}
</ul>

I think I handled the form's action attribute and the links href attributes properly. You might have to clean them up for your situation.


问:
Difference between android Home key and Back key and their behaviour
Can anyone point me out or explain what is the difference between android Home key and Back key and their respective behavior related to an android app/activity.

Thank you.

答: In addition to @Fosco's comments, using back will usually cause an app to exit, where home will leave it running.  This is dependent on the application, but the general pattern is to exit the app when using back on the last activity.</p>