问:
jQuery datatables export input text option and not export specific column at same time
I've been struggling with this code. I need to avoid specific columns from being exported. I have done that but I don't know how to export the text inside any input element.

Here is the code:

```<code>$("#campaignMaterialsTable table").DataTable({
                            dom: 'Bfrtip',
                            buttons: [
                                {
                                    extend: 'excel',
                                    className: 'export-button',
                                    text: 'Export as Excel',
                                    columns: ':not(.notexport)',
                                    //exportOptions: {
                                    //    format: {
                                    //        body: function (data, row, column, node) {
                                    //            //
                                    //            //check if type is input using jquery
                                    //            return $(data).is("input") ?
                                    //                $(data).val() :
                                    //                data;
                                    //        },
                                    //        columns: ':not(.notexport)'
                                    //    }
                                    //},
                                    title: 'Campaign Materials'
                                }]
                        });
</code>```

I don't know here to put the code at the right place.. while initializing..

I referred to this links, but still not getting what I want:

https://datatables.net/forums/discussion/50724/export-values-typed-in-input-box-excelhtml5

https://datatables.net/forums/discussion/42205/export-data-with-text-box-in-td-of-data-table#latest

https://datatables.net/extensions/buttons/examples/html5/outputFormat-function.html

https://datatables.net/forums/discussion/50724/export-values-typed-in-input-box-excelhtml5

答:
you can use

```<code>exportOptions:{
       columns: ':visible'
 }
</code>```

in below buttons

```<code>buttons: [
   {
       extend: 'pdf',
       footer: true,
        exportOptions: {
            columns: ':visible'
        }

   },
</code>```

it will export only visible columns

Body:
I've been struggling with this code. I need to avoid specific columns from being exported. I have done that but I don't know how to export the text inside any input element.

Here is the code:

$("#campaignMaterialsTable table").DataTable({
                            dom: 'Bfrtip',
                            buttons: [
                                {
                                    extend: 'excel',
                                    className: 'export-button',
                                    text: 'Export as Excel',
                                    columns: ':not(.notexport)',
                                    //exportOptions: {
                                    //    format: {
                                    //        body: function (data, row, column, node) {
                                    //            //
                                    //            //check if type is input using jquery
                                    //            return $(data).is("input") ?
                                    //                $(data).val() :
                                    //                data;
                                    //        },
                                    //        columns: ':not(.notexport)'
                                    //    }
                                    //},
                                    title: 'Campaign Materials'
                                }]
                        });

I don't know here to put the code at the right place.. while initializing..

I referred to this links, but still not getting what I want:

https://datatables.net/forums/discussion/50724/export-values-typed-in-input-box-excelhtml5

https://datatables.net/forums/discussion/42205/export-data-with-text-box-in-td-of-data-table#latest

https://datatables.net/extensions/buttons/examples/html5/outputFormat-function.html

https://datatables.net/forums/discussion/50724/export-values-typed-in-input-box-excelhtml5

Body:
you can use

exportOptions:{
       columns: ':visible'
 }

in below buttons

buttons: [
   {
       extend: 'pdf',
       footer: true,
        exportOptions: {
            columns: ':visible'
        }

   },

it will export only visible columns


来源: stackexchange

问:
AmCharts 4 : Can't customize (color, strokeWidth) my series

EDIT : OK, It was my css page which had a rule on path, 'cause I use svg a lot. Removed that rule and the problem was gone !

I'm facing something pretty annoying and which I do not understand.

I'm using amChart to make a XY chart with multiple series. Not that hard.
The thing is, I can't customize my series ! Bullets and legend are ok, but not series.

Here's a screenshot for better understanding :

MyWeirdChart (new OP can't embed images, sorry)

As you can see I have my custom bullet pushed on my series and my legend is exactly what I want for my chart BUT series are staying unchanged.

Here is my JS draw function :

function drawChart(dateArray, casesArray, deathsArray, healedArray, hospitalizationsArray, reanimationsArray) {
    am4core.useTheme(am4themes_animated);
    var chart = am4core.create("chartdiv", am4charts.XYChart);
    chart.data = generateChartData(dateArray, casesArray, deathsArray, healedArray, hospitalizationsArray, reanimationsArray);

    var dateAxis = chart.xAxes.push(new am4charts.DateAxis());
    var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());

    function pushSeries(field, name, color) {
        let series = chart.series.push(new am4charts.LineSeries());
        series.dataFields.valueY = field;
        series.dataFields.dateX = "date";
        series.name = name;
        series.tooltipText = name + ": [b]{valueY}[/]";
        series.stroke = am4core.color(color);
        series.strokeWidth = 3;
        series.fill = am4core.color(color);
        series.fillOpacity = 0.5;

        let bullet = series.bullets.push(new am4charts.CircleBullet());
        bullet.circle.stroke = am4core.color(color);
        bullet.circle.strokeWidth = 2;
        bullet.circle.fill = am4core.color(color);
        bullet.circle.fillOpacity = 0.5;
        bullet.circle.radius = 3;

    }

    pushSeries("cases", "Cas confirmés", "#32B3E3");
    pushSeries("healed", "Guéris", "#00C750");
    pushSeries("hospitalizations", "Hospitalisations", "#FFBB33");
    pushSeries("reanimations", "Réanimations", "#FE3446");
    pushSeries("deaths", "Morts", "black");

    chart.cursor = new am4charts.XYCursor();
    chart.scrollbarX = new am4core.Scrollbar();
    chart.legend = new am4charts.Legend();
    chart.cursor.maxTooltipDistance = 0;
}```
</div>
</div>
</p>

<p>Did I miss something ? I crawled forums and documentations and I'm now helpless.
My code is in my webpack app.js file. But I include amCharts with HTML scripts,</p>

```

```

not with webpack import. But I guess that if this was the problem, I would not be able to draw a chart at all.

答: OK, It was my css page which had a rule on path, 'cause I use svg a lot. Removed that rule and the problem was gone !</p>

ContentLicense: CC BY-SA 4.0

Body:
EDIT : OK, It was my css page which had a rule on path, 'cause I use svg a lot. Removed that rule and the problem was gone !

I'm facing something pretty annoying and which I do not understand.

I'm using amChart to make a XY chart with multiple series. Not that hard.
The thing is, I can't customize my series ! Bullets and legend are ok, but not series.

Here's a screenshot for better understanding :

MyWeirdChart (new OP can't embed images, sorry)

As you can see I have my custom bullet pushed on my series and my legend is exactly what I want for my chart BUT series are staying unchanged.

Here is my JS draw function :

function drawChart(dateArray, casesArray, deathsArray, healedArray, hospitalizationsArray, reanimationsArray) {
    am4core.useTheme(am4themes_animated);
    var chart = am4core.create("chartdiv", am4charts.XYChart);
    chart.data = generateChartData(dateArray, casesArray, deathsArray, healedArray, hospitalizationsArray, reanimationsArray);

    var dateAxis = chart.xAxes.push(new am4charts.DateAxis());
    var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());

    function pushSeries(field, name, color) {
        let series = chart.series.push(new am4charts.LineSeries());
        series.dataFields.valueY = field;
        series.dataFields.dateX = "date";
        series.name = name;
        series.tooltipText = name + ": [b]{valueY}[/]";
        series.stroke = am4core.color(color);
        series.strokeWidth = 3;
        series.fill = am4core.color(color);
        series.fillOpacity = 0.5;

        let bullet = series.bullets.push(new am4charts.CircleBullet());
        bullet.circle.stroke = am4core.color(color);
        bullet.circle.strokeWidth = 2;
        bullet.circle.fill = am4core.color(color);
        bullet.circle.fillOpacity = 0.5;
        bullet.circle.radius = 3;

    }

    pushSeries("cases", "Cas confirmés", "#32B3E3");
    pushSeries("healed", "Guéris", "#00C750");
    pushSeries("hospitalizations", "Hospitalisations", "#FFBB33");
    pushSeries("reanimations", "Réanimations", "#FE3446");
    pushSeries("deaths", "Morts", "black");

    chart.cursor = new am4charts.XYCursor();
    chart.scrollbarX = new am4core.Scrollbar();
    chart.legend = new am4charts.Legend();
    chart.cursor.maxTooltipDistance = 0;
}

Did I miss something ? I crawled forums and documentations and I'm now helpless.
My code is in my webpack app.js file. But I include amCharts with HTML scripts,

not with webpack import. But I guess that if this was the problem, I would not be able to draw a chart at all.


问:
Default value for Text Field flutter?
How can I have a text as a place holder until onTap() happen? (onTap is on another page)

```<code>Align(
        alignment: Alignment.center,
        child: Text(//Default value goes here
          widget.categoryTitle,//this string comes from another page it changes on every onTap()
          style: TextStyle(
            color: Colors.black,
            fontSize: 17.0,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
</code>```

Right now if no onTap happens the Text is holding a white blank space, How to replace it with a default/initial value?

答:
Or you can also use shorter version for conditional expressions

```<code>Align(
    alignment: Alignment.center,
    child: Text(
      widget.categoryTitle ?? "Your Default Text Here",
      style: TextStyle(
        color: Colors.black,
        fontSize: 17.0,
        fontWeight: FontWeight.bold,
      ),
    ),
  ),
</code>```

expr1 ?? expr2,
If expr1 (widget.categoryTitle) is non-null, returns its value; otherwise, evaluates and returns the value of expr2 ("Your Default Text Here")

Title: Default value for Text Field flutter?

Body:
How can I have a text as a place holder until onTap() happen? (onTap is on another page)

Align(
        alignment: Alignment.center,
        child: Text(//Default value goes here
          widget.categoryTitle,//this string comes from another page it changes on every onTap()
          style: TextStyle(
            color: Colors.black,
            fontSize: 17.0,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),

Right now if no onTap happens the Text is holding a white blank space, How to replace it with a default/initial value?

Body:
Or you can also use shorter version for conditional expressions

Align(
    alignment: Alignment.center,
    child: Text(
      widget.categoryTitle ?? "Your Default Text Here",
      style: TextStyle(
        color: Colors.black,
        fontSize: 17.0,
        fontWeight: FontWeight.bold,
      ),
    ),
  ),

expr1 ?? expr2,
If expr1 (widget.categoryTitle) is non-null, returns its value; otherwise, evaluates and returns the value of expr2 ("Your Default Text Here")


问:
Use whereHas and query pivot table at the same time is possible in laravel?
I have 2 entities: Beneficiaries and Initiatives, those related in a pivot table beneficiary_initiative.
I want all the beneficiaries related to a specific "region". But i have following error:

```<code>SQLSTATE[42S22]: Column not found: 1054 Unknown column 'beneficiaries.region' in 'where clause' (SQL: select count(*) as aggregate from `initiatives` where `state` = 1 and exists (select * from `beneficiaries` inner join `beneficiary_initiative` on `beneficiaries`.`id` = `beneficiary_initiative`.`beneficiary_id` where `initiatives`.`id` = `beneficiary_initiative`.`initiative_id` and `beneficiaries`.`region` = 120000))
</code>```

Laravel version: 5.4

My database structure:

beneficiaries

id

name

initiatives

id

name

beneficiary_initiative

beneficiary_id

initiative_id

region

province

My models:

// Beneficiary.php
public function initiatives()
{
  return $this->belongsToMany(Initiative::class)->withPivot('region', 'province');
}
```

<pre class="lang-php prettyprint-override"><code>// Initiative.php

public function beneficiaries()
{
  return $this->belongsToMany(Beneficiary::class)->withPivot('region', 'province');
}

public static function search ($region)
{
  $query = Initiative::select(
    'initiatives.id',
    'initiatives.name'
  )->with('program')
   ->with('beneficiaries')
   ->with('contacts');

  $query->when($region !== null, function ($q) use ($region) {
      return $q->whereHas('beneficiaries', function ($q1) use ($region) {
        $q1->where('beneficiary_initiative.region', '=', $region);
      });
  });

  $initiatives = $query->get();
  return $initiatives;
}
</code>```

答:
you must join your query to be able to make 'where' in pivot table ...</p>

```<code>  $query->when($region !== null, function ($q) use ($region) {
return $q->
join('beneficiary_initiative','beneficiary_initiative.initiative_id','=','initiatives.id')
->where('beneficiary_initiative.region', '=', $region);
      });
  });
</code>```

Body:
I have 2 entities: Beneficiaries and Initiatives, those related in a pivot table beneficiary_initiative.
I want all the beneficiaries related to a specific "region". But i have following error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'beneficiaries.region' in 'where clause' (SQL: select count(*) as aggregate from `initiatives` where `state` = 1 and exists (select * from `beneficiaries` inner join `beneficiary_initiative` on `beneficiaries`.`id` = `beneficiary_initiative`.`beneficiary_id` where `initiatives`.`id` = `beneficiary_initiative`.`initiative_id` and `beneficiaries`.`region` = 120000))

Laravel version: 5.4

My database structure:

beneficiaries

id

name

initiatives

id

name

beneficiary_initiative

beneficiary_id

initiative_id

region

province

My models:

// Beneficiary.php
public function initiatives()
{
  return $this->belongsToMany(Initiative::class)->withPivot('region', 'province');
}

// Initiative.php

public function beneficiaries()
{
  return $this->belongsToMany(Beneficiary::class)->withPivot('region', 'province');
}

public static function search ($region)
{
  $query = Initiative::select(
    'initiatives.id',
    'initiatives.name'
  )->with('program')
   ->with('beneficiaries')
   ->with('contacts');

  $query->when($region !== null, function ($q) use ($region) {
      return $q->whereHas('beneficiaries', function ($q1) use ($region) {
        $q1->where('beneficiary_initiative.region', '=', $region);
      });
  });

  $initiatives = $query->get();
  return $initiatives;
}

Body:
you must join your query to be able to make 'where' in pivot table ...

  $query->when($region !== null, function ($q) use ($region) {
return $q->
join('beneficiary_initiative','beneficiary_initiative.initiative_id','=','initiatives.id')
->where('beneficiary_initiative.region', '=', $region);
      });
  });


问:
Conditionally Combine Lambdas in Kotlin for Filtering with Multiple Predicates
Suppose I have the following predicates as predefined lambdas for a Villager POJO.

```<code>    val matchesSearch: (Villager, String) -> Boolean =
        { villager: Villager, query: String -> villager.name.contains(query) }

    val matchesGender: (Villager, Int) -> Boolean =
        { villager: Villager, filter: Int -> filter == villager.gender }

    val matchesPersonality: (Villager, Int) -> Boolean =
        { villager: Villager, filter: Int -> filter == villager.personality }

    val matchesSpecies: (Villager, Int) -> Boolean =
        { villager: Villager, filter: Int -> filter == villager.species }

    val matchesHobby: (Villager, Int) -> Boolean =
        { villager: Villager, filter: Int -> filter == villager.hobby }
</code>```

I only want to apply the predicate IF a certain condition is met. For example, only filter by gender if a gender filter has been applied. Or I only want to match against the search query if one has been entered.

```<code>fun getVillagersThatMatchQueryAndFilters(list: List<Villager>): List<Villager> {

    val conditions = ArrayList<Predicate<Villager>>()

    if (searchQuery.isNotEmpty()) {
        // TODO: apply the matchesSearch() predicate lambda
        conditions.add(Predicate { villager -> villager.name.contains(query) })
    }
    if (genderFilter > 0) {
        // TODO: apply the matchesGender() predicate lambda
        conditions.add(Predicate { genderFilter == villager.gender })
    }
    if (personalityFilter > 0) {
        // TODO: apply the matchesPersonality() predicate lambda
        conditions.add(Predicate { personalityFilter == villager.personality })
    }
    if (speciesFilter > 0) {
        // TODO: apply the matchesSpecies() predicate lambda
        conditions.add(Predicate { speciesFilter == villager.species })
    }
    if (hobbyFilter > 0) {
        // TODO: apply the matchesHobby() predicate lambda
        conditions.add(Predicate { hobbyFilter == villager.hobby })
    }

    return list.filter {
        // TODO: match on all conditionally applied predicates
        conditions.allPredicatesCombinedWithAnd() // this doesn't actually exist
    }
}
</code>```

Previously I had done list.filter{ } within each condition and applied the necessary predicate, however, since I could have up to 5 predicates being applied, it is quite terrible for performance as it iterates over the list each time .filter() is called.

Is there a way to programmatically iterate over a List<Predicate<T>> and combine predicates with .and() or && so that I may apply the filter ONCE? Or if not, how can I conditionally combine these predicates?

I would use the final Java example here that uses Predicates.stream() and Collectors but it requires Android API level 24 (higher than my current Android min).

SOLUTION BELOW - thanks to suggestions from @Laurence and @IR42

Works for < Android API 24

Create a list of the lambdas and conditionally add any predicates that you wish to match list items against. Then use Collections.Aggregates.all() method to ensure you are filtering against ALL predicates. (The equivalent of doing pred1.and(pred2).and(etc.)... for all items in the list.)

Huge performance saver if you have a large number of predicates to be filtered against as list.filter() is only called ONCE.

```<code>fun getVillagersThatMatchQueryAndFilters(list: List<Villager>): List<Villager> {

    val conditions = ArrayList<(Villager) -> Boolean>()

    if (searchQuery.isNotEmpty()) {
        conditions.add{ it.name.contains(query) }
    }
    if (genderFilter > 0) {
        conditions.add{ genderFilter == it.gender }
    }
    if (personalityFilter > 0) {
        conditions.add{ personalityFilter == it.personality }
    }
    if (speciesFilter > 0) {
        conditions.add{ speciesFilter == it.species }
    }
    if (hobbyFilter > 0) {
        conditions.add{ hobbyFilter == it.hobby }
    }

    return list.filter { candidate -> conditions.all { it(candidate) } }
}
</code>```

答:
There is the all extension function, and as a point of interest the any extension function as well. I think you just have to use them in your filter block on your predicates. Here is a very simple example with a silly set of predicates:</p>

```<code>fun main() {
    val thingsToFilter = listOf(-1,2,5)

    val predicates = listOf(
        { value: Int -> value > 0 },
        { value: Int -> value > 4 }
    )

    val filtered = thingsToFilter.filter {candidate ->
        predicates.all{ it(candidate)}
    }

    print(filtered) // Outputs [5]

}
</code>```

Body:
Suppose I have the following predicates as predefined lambdas for a Villager POJO.

    val matchesSearch: (Villager, String) -> Boolean =
        { villager: Villager, query: String -> villager.name.contains(query) }

    val matchesGender: (Villager, Int) -> Boolean =
        { villager: Villager, filter: Int -> filter == villager.gender }

    val matchesPersonality: (Villager, Int) -> Boolean =
        { villager: Villager, filter: Int -> filter == villager.personality }

    val matchesSpecies: (Villager, Int) -> Boolean =
        { villager: Villager, filter: Int -> filter == villager.species }

    val matchesHobby: (Villager, Int) -> Boolean =
        { villager: Villager, filter: Int -> filter == villager.hobby }

I only want to apply the predicate IF a certain condition is met. For example, only filter by gender if a gender filter has been applied. Or I only want to match against the search query if one has been entered.

fun getVillagersThatMatchQueryAndFilters(list: List<Villager>): List<Villager> {

    val conditions = ArrayList<Predicate<Villager>>()

    if (searchQuery.isNotEmpty()) {
        // TODO: apply the matchesSearch() predicate lambda
        conditions.add(Predicate { villager -> villager.name.contains(query) })
    }
    if (genderFilter > 0) {
        // TODO: apply the matchesGender() predicate lambda
        conditions.add(Predicate { genderFilter == villager.gender })
    }
    if (personalityFilter > 0) {
        // TODO: apply the matchesPersonality() predicate lambda
        conditions.add(Predicate { personalityFilter == villager.personality })
    }
    if (speciesFilter > 0) {
        // TODO: apply the matchesSpecies() predicate lambda
        conditions.add(Predicate { speciesFilter == villager.species })
    }
    if (hobbyFilter > 0) {
        // TODO: apply the matchesHobby() predicate lambda
        conditions.add(Predicate { hobbyFilter == villager.hobby })
    }

    return list.filter {
        // TODO: match on all conditionally applied predicates
        conditions.allPredicatesCombinedWithAnd() // this doesn't actually exist
    }
}

Previously I had done list.filter{ } within each condition and applied the necessary predicate, however, since I could have up to 5 predicates being applied, it is quite terrible for performance as it iterates over the list each time .filter() is called.

Is there a way to programmatically iterate over a List<Predicate<T>> and combine predicates with .and() or && so that I may apply the filter ONCE? Or if not, how can I conditionally combine these predicates?

I would use the final Java example here that uses Predicates.stream() and Collectors but it requires Android API level 24 (higher than my current Android min).

SOLUTION BELOW - thanks to suggestions from @Laurence and @IR42

Works for < Android API 24

Create a list of the lambdas and conditionally add any predicates that you wish to match list items against. Then use Collections.Aggregates.all() method to ensure you are filtering against ALL predicates. (The equivalent of doing pred1.and(pred2).and(etc.)... for all items in the list.)

Huge performance saver if you have a large number of predicates to be filtered against as list.filter() is only called ONCE.

fun getVillagersThatMatchQueryAndFilters(list: List<Villager>): List<Villager> {

    val conditions = ArrayList<(Villager) -> Boolean>()

    if (searchQuery.isNotEmpty()) {
        conditions.add{ it.name.contains(query) }
    }
    if (genderFilter > 0) {
        conditions.add{ genderFilter == it.gender }
    }
    if (personalityFilter > 0) {
        conditions.add{ personalityFilter == it.personality }
    }
    if (speciesFilter > 0) {
        conditions.add{ speciesFilter == it.species }
    }
    if (hobbyFilter > 0) {
        conditions.add{ hobbyFilter == it.hobby }
    }

    return list.filter { candidate -> conditions.all { it(candidate) } }
}

Body:
There is the all extension function, and as a point of interest the any extension function as well. I think you just have to use them in your filter block on your predicates. Here is a very simple example with a silly set of predicates:

fun main() {
    val thingsToFilter = listOf(-1,2,5)

    val predicates = listOf(
        { value: Int -> value > 0 },
        { value: Int -> value > 4 }
    )

    val filtered = thingsToFilter.filter {candidate ->
        predicates.all{ it(candidate)}
    }

    print(filtered) // Outputs [5]

}


问:
Paramiko stdout readline() command hangs
I am using the the python paramiko library to SSH into a FTP server. I am able to use the command line to access the server and retrieve a list of files using the sftp command, however paramiko seems to be doing something that prevents me from retrieving output. Here is my python code:

```<code>import paramiko
client = paramiko.SSHClient()

client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

client.connect('###########',
        port=##,
        username='####',
        password='####',
        key_filename='#####')

stdin, stdout, stderr = client.exec_command('ls')
</code>```

this all works just fine. However the next line

```<code>stdout.readline()
</code>```

just sits there and hangs. Notice that per this thread I am not even trying to retrieve the full output, just the first line.

I also tried

```<code>stdin.close()
print(stdout.readlines())
</code>```

which returns an empty string. This suggests that maybe the server is waiting for input, but when I use the command line I am able to just send the ls command and get the output so what command could it be waiting for?

Versions:

python 3.7.4

paramiko 2.7.1

答:
Your readline might be executing before there is a return from the remote host try:

```<code>import paramiko
client = paramiko.SSHClient()

client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

client.connect('###########',
        port=##,
        username='####',
        password='####',
        key_filename='#####')

stdin, stdout, stderr = client.exec_command('ls')
stdout.channel.recv_exit_status()
print(stdout.readline())
</code>```

The recv_exit_status() will wait until there is a return from exec_command() on your remote host.

Body:
I am using the the python paramiko library to SSH into a FTP server. I am able to use the command line to access the server and retrieve a list of files using the sftp command, however paramiko seems to be doing something that prevents me from retrieving output. Here is my python code:

import paramiko
client = paramiko.SSHClient()

client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

client.connect('###########',
        port=##,
        username='####',
        password='####',
        key_filename='#####')

stdin, stdout, stderr = client.exec_command('ls')

this all works just fine. However the next line

stdout.readline()

just sits there and hangs. Notice that per this thread I am not even trying to retrieve the full output, just the first line.

I also tried

stdin.close()
print(stdout.readlines())

which returns an empty string. This suggests that maybe the server is waiting for input, but when I use the command line I am able to just send the ls command and get the output so what command could it be waiting for?

Versions:

python 3.7.4

paramiko 2.7.1

Body:
Your readline might be executing before there is a return from the remote host try:

import paramiko
client = paramiko.SSHClient()

client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

client.connect('###########',
        port=##,
        username='####',
        password='####',
        key_filename='#####')

stdin, stdout, stderr = client.exec_command('ls')
stdout.channel.recv_exit_status()
print(stdout.readline())

The recv_exit_status() will wait until there is a return from exec_command() on your remote host.


问:
jQuery to remove an option from drop down list, given option's text/value
I have a drop down list and would like to remove an option from it, given the text/value of that particular option. Is it possible using jQuery? Just like 'append' which adds an option to the drop down list, is there a function to remove an option?

I tried searching for it but all I got were examples where the entire set of options in the drop down list are removed, which is not what I seek.

cheers

答: I have used the above option to .hide entries from 2 drops down boxes (first you select the city, then you selected the area within that city). It works fine on screen but the hidden options are still selectable via keyboard inputs.</p>

ContentLicense: CC BY-SA 2.5


问:
Cython - Indexing numpy array within nogil function
I'm trying to extend the Splitter class in sklearn, which works with sklearn's decision tree classes.  More specifically, I want to add a feature_weights variable in the new class, which will affect the determination of the best split point by altering the purity calculations proportionally with the feature weights.

The new class is almost an exact copy of sklearn's BestSplitter class (https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/_splitter.pyx) with only minor changes.  Here's what I have so far:

```<code>cdef class WeightedBestSplitter(WeightedBaseDenseSplitter):

    cdef object feature_weights # new variable - 1D array of feature weights

    def __reduce__(self):
        # same as sklearn BestSplitter (basically)

    # NEW METHOD
    def set_weights(self, object feature_weights):
        feature_weights = np.asfortranarray(feature_weights, dtype=DTYPE)
        self.feature_weights = feature_weights

    cdef int node_split(self, double impurity, SplitRecord* split,
                        SIZE_t* n_constant_features) nogil except -1:

        # .... same as sklearn BestSplitter ....

        current_proxy_improvement = self.criterion.proxy_impurity_improvement()
        current_proxy_improvement *= self.feature_weights[<int>(current.feature)]  # new line

        # .... same as sklearn BestSplitter ....
</code>```

A couple notes about the above: I'm using the object variable type and np.asfortranarray because that is how the variable X is defined and set in other places and X is indexed like I'm trying to index feature_weights.  Also, custom.feature has a variable type of SIZE_t per the _splitter.pxd file (https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/_splitter.pxd).

The issue seems to be created by the variable type of self.feature_weights.  The above code throws multiple errors, but even trying to reference something like self.feature_weights[0] and set it to another variable throws the error:

```<code>Indexing Python object not allowed without gil
</code>```

I'm wondering what I need to do to be able to index self.feature_weights and use the scalar value as a multiplier.

答:
You definitely can't index a generic Python object without the GIL (as you're trying to do). You can index typed memoyviews without the GIL.

Define feature_weights as

```<code>cdef double[:] feature_weights
</code>```

Body:
I'm trying to extend the Splitter class in sklearn, which works with sklearn's decision tree classes.  More specifically, I want to add a feature_weights variable in the new class, which will affect the determination of the best split point by altering the purity calculations proportionally with the feature weights.

The new class is almost an exact copy of sklearn's BestSplitter class (https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/_splitter.pyx) with only minor changes.  Here's what I have so far:

cdef class WeightedBestSplitter(WeightedBaseDenseSplitter):

    cdef object feature_weights # new variable - 1D array of feature weights

    def __reduce__(self):
        # same as sklearn BestSplitter (basically)

    # NEW METHOD
    def set_weights(self, object feature_weights):
        feature_weights = np.asfortranarray(feature_weights, dtype=DTYPE)
        self.feature_weights = feature_weights

    cdef int node_split(self, double impurity, SplitRecord* split,
                        SIZE_t* n_constant_features) nogil except -1:

        # .... same as sklearn BestSplitter ....

        current_proxy_improvement = self.criterion.proxy_impurity_improvement()
        current_proxy_improvement *= self.feature_weights[<int>(current.feature)]  # new line

        # .... same as sklearn BestSplitter ....

A couple notes about the above: I'm using the object variable type and np.asfortranarray because that is how the variable X is defined and set in other places and X is indexed like I'm trying to index feature_weights.  Also, custom.feature has a variable type of SIZE_t per the _splitter.pxd file (https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/_splitter.pxd).

The issue seems to be created by the variable type of self.feature_weights.  The above code throws multiple errors, but even trying to reference something like self.feature_weights[0] and set it to another variable throws the error:

Indexing Python object not allowed without gil

I'm wondering what I need to do to be able to index self.feature_weights and use the scalar value as a multiplier.

Body:
You definitely can't index a generic Python object without the GIL (as you're trying to do). You can index typed memoyviews without the GIL.

Define feature_weights as

cdef double[:] feature_weights


问:
Turn 512 x 3 dataframe into 128 x 4 x 3 matrix in R
I have this dataframe here. I want to convert the last 3 columns (Colour, Number, Shape) into a 128 x 4 x 3 matrix using the values in the grouping variables 'trial' and 'Card' as guides.

```<code>trial Card Colour Number Shape
1      1     1      1      0
1      2     0      1      1
1      3     0      1      0
1      4     1      1      1
2      1     1      0      0
2      2     1      1      0
2      3     0      1      1
2      4     1      1      0
.
.
.
</code>```

My goal is to have a 3D matrix like this one below, where the first dimension are trials, the second dimension are each of the 4 cards, and the third dimension are 1. Colour 2. Number 3. Shape:

```<code>, , 1

       [,1] [,2] [,3] [,4]
  [1,]    1    0    0    1
  [2,]    1    1    0    1

, , 2

       [,1] [,2] [,3] [,4]
  [1,]    1    1    1    1
  [2,]    0    1    1    1

, , 3

       [,1] [,2] [,3] [,4]
  [1,]    0    1    0    1
  [2,]    0    0    1    0

</code>```

This is my code at the moment:

```<code>#generate fake data
data<-matrix(rbinom(128*12, 1, .5), ncol=12)
trial<-seq(from = 1, to = 128)

data<-cbind(trial,data)
data<-as.data.frame(data)

colnames(data)[2] <- "Card1_colour"
colnames(data)[3] <- "Card1_number"
colnames(data)[4] <- "Card1_shape"
colnames(data)[5] <- "Card2_colour"
colnames(data)[6] <- "Card2_number"
colnames(data)[7] <- "Card2_shape"
colnames(data)[8] <- "Card3_colour"
colnames(data)[9] <- "Card3_number"
colnames(data)[10] <- "Card3_shape"
colnames(data)[11] <- "Card4_colour"
colnames(data)[12] <- "Card4_number"
colnames(data)[13] <- "Card4_shape"

#get data into 512 x 5 format
card_match<-tidyr::pivot_longer(data, cols = -trial,
                    names_to = c('Card', '.value'),
                    names_pattern = 'Card(\\d+)_(.*)')

#Here I've tried to reshape the last 3 columns of card_match without the 'trial' and 'card' columns but it hasn't worked
card_match2<-card_match%>% select(3:5) # get only last 3 columns
card_match_final<-array(unlist(card_match2), dim=c(128,4,3)) #get 128x4x3 matrix

</code>```

The last line is my attempt to reshape the dataframe into a 3d matrix, which it has done, but the values are not in the order I want them to be. How may I alter this code, potentially using the 'trial' and 'card' variables to guide the reshaping?

答:
This is a job for xtabs:

```<code>xtabs(cbind(Colour,Number,Shape) ~ trial + Card, data)
#, ,  = Colour
#
#     Card
#trial 1 2 3 4
#    1 1 0 0 1
#    2 1 1 0 1
#
#, ,  = Number
#
#     Card
#trial 1 2 3 4
#    1 1 1 1 1
#    2 0 1 1 1
#
#, ,  = Shape
#
#     Card
#trial 1 2 3 4
#    1 0 1 0 1
#    2 0 0 1 0
</code>```

Tested on the smaller data as shown in the start of the question:

```<code># generate smaller fake data
data <- read.table(text="
trial Card Colour Number Shape
1      1     1      1      0
1      2     0      1      1
1      3     0      1      0
1      4     1      1      1
2      1     1      0      0
2      2     1      1      0
2      3     0      1      1
2      4     1      1      0",
header=TRUE)
</code>```

Body:
I have this dataframe here. I want to convert the last 3 columns (Colour, Number, Shape) into a 128 x 4 x 3 matrix using the values in the grouping variables 'trial' and 'Card' as guides.

trial Card Colour Number Shape
1      1     1      1      0
1      2     0      1      1
1      3     0      1      0
1      4     1      1      1
2      1     1      0      0
2      2     1      1      0
2      3     0      1      1
2      4     1      1      0
.
.
.

My goal is to have a 3D matrix like this one below, where the first dimension are trials, the second dimension are each of the 4 cards, and the third dimension are 1. Colour 2. Number 3. Shape:

, , 1

       [,1] [,2] [,3] [,4]
  [1,]    1    0    0    1
  [2,]    1    1    0    1

, , 2

       [,1] [,2] [,3] [,4]
  [1,]    1    1    1    1
  [2,]    0    1    1    1

, , 3

       [,1] [,2] [,3] [,4]
  [1,]    0    1    0    1
  [2,]    0    0    1    0

This is my code at the moment:

#generate fake data
data<-matrix(rbinom(128*12, 1, .5), ncol=12)
trial<-seq(from = 1, to = 128)

data<-cbind(trial,data)
data<-as.data.frame(data)

colnames(data)[2] <- "Card1_colour"
colnames(data)[3] <- "Card1_number"
colnames(data)[4] <- "Card1_shape"
colnames(data)[5] <- "Card2_colour"
colnames(data)[6] <- "Card2_number"
colnames(data)[7] <- "Card2_shape"
colnames(data)[8] <- "Card3_colour"
colnames(data)[9] <- "Card3_number"
colnames(data)[10] <- "Card3_shape"
colnames(data)[11] <- "Card4_colour"
colnames(data)[12] <- "Card4_number"
colnames(data)[13] <- "Card4_shape"

#get data into 512 x 5 format
card_match<-tidyr::pivot_longer(data, cols = -trial,
                    names_to = c('Card', '.value'),
                    names_pattern = 'Card(\\d+)_(.*)')

#Here I've tried to reshape the last 3 columns of card_match without the 'trial' and 'card' columns but it hasn't worked
card_match2<-card_match%>% select(3:5) # get only last 3 columns
card_match_final<-array(unlist(card_match2), dim=c(128,4,3)) #get 128x4x3 matrix

The last line is my attempt to reshape the dataframe into a 3d matrix, which it has done, but the values are not in the order I want them to be. How may I alter this code, potentially using the 'trial' and 'card' variables to guide the reshaping?

Body:
This is a job for xtabs:

xtabs(cbind(Colour,Number,Shape) ~ trial + Card, data)
#, ,  = Colour
#
#     Card
#trial 1 2 3 4
#    1 1 0 0 1
#    2 1 1 0 1
#
#, ,  = Number
#
#     Card
#trial 1 2 3 4
#    1 1 1 1 1
#    2 0 1 1 1
#
#, ,  = Shape
#
#     Card
#trial 1 2 3 4
#    1 0 1 0 1
#    2 0 0 1 0

Tested on the smaller data as shown in the start of the question:

# generate smaller fake data
data <- read.table(text="
trial Card Colour Number Shape
1      1     1      1      0
1      2     0      1      1
1      3     0      1      0
1      4     1      1      1
2      1     1      0      0
2      2     1      1      0
2      3     0      1      1
2      4     1      1      0",
header=TRUE)


问:
How to programmatically upload and download any file on Google Drive in Android studio
I have created an application in Android studio which store users information and other data in sqlite database. I want to give user an option to create the backup of their data(upload the database.db file) on Google Drive and restore (download the database.db file) from Google Drive.</p>

答: here is a perfect example for what you need. Go through the project and you will be able to do backup/restore of your db.</p>


问:
Assigned negative value to char in c prints "?" on macOS
```<code>#include<stdio.h>

int main(){

  signed char c;          //range of signed char is -128 to 127
  char d;                 //this is basically a signed char, if I am not wrong
  unsigned char e;        //range of unsigned char is 0 to 255
  c = -12;
  d = -12;
  e = 255;

  printf("%c\n", c);
  printf("%c\n", d);
  printf("%c\n", e);
  return 0;
}
</code>```

<p>These all char gets printed as '?'.
Trying to understand why? is it a garbage value or actually a same char assigned to different values? which is highly not possible. </p>

答:
When you pass a char, signed char, or unsigned char to printf, it is promoted to an int value (in normal C implementations, where char is narrower than int). For a %c conversion specification , printf converts that int to unsigned char and writes the resulting character.

When the character is not a printable character of the character set in use, displaying a “?” is a common behavior.

Whether char is signed or unsigned is implementation-defined, although it remains a distinct type, separate from both signed char and unsigned char.

Body:
#include<stdio.h>

int main(){

  signed char c;          //range of signed char is -128 to 127
  char d;                 //this is basically a signed char, if I am not wrong
  unsigned char e;        //range of unsigned char is 0 to 255
  c = -12;
  d = -12;
  e = 255;

  printf("%c\n", c);
  printf("%c\n", d);
  printf("%c\n", e);
  return 0;
}

These all char gets printed as '?'.
Trying to understand why? is it a garbage value or actually a same char assigned to different values? which is highly not possible.


问:
Getting author to view correct story in laravel
I'm using Laravel 7 and I'm  trying to create a site where the user can login if they have a token. I seem to have that almost working in that if you don't
have a token you can't access the page and if you put in a token that isn't in the database then it throws out an error.

The problem I'm having is that a user can still view a page they not meant to. For example I have Story 1 and Story 2, Author 1 can
view both Story 1 and 2, but Author 2 can only view Story 2.

The issue is that Author 2 can view both Story 1 and Story 2, which is wrong they only supposed to see Story 2.

I wanted to use middleware for this but I kind of hit a brick wall and not sure what next to do.

My tables

```<code>Story Table
id | title
1  | Story 1
2  | Story 2

Author Table
id | name
1  | Author 1
2  | Author 2

author_story table
id | author_id | story_id
1  |    1      |    1
2  |    1      |    2
3  |    2      |    2
</code>```

My Story.php

```<code>protected $fillable = ['title'];

public function authors()
{
    return $this->belongsToMany('App\Author');
}
</code>```

My Author.php

```<code>protected $fillable = ['name'];

public function stories()
{
    return $this->belongsToMany('App\Story');
}
</code>```

My ViewStory.php (middleware)

```<code>if(Auth::check())
{
    return $next($request);
}else{
    abort(401);
}
</code>```

答:
Do you get any error?

I think you should use hasMany relation in my author model:

```<code>return $this->belongsToMany('App\Story',story_id, id);
</code>```

Body:
I'm using Laravel 7 and I'm  trying to create a site where the user can login if they have a token. I seem to have that almost working in that if you don't
have a token you can't access the page and if you put in a token that isn't in the database then it throws out an error.

The problem I'm having is that a user can still view a page they not meant to. For example I have Story 1 and Story 2, Author 1 can
view both Story 1 and 2, but Author 2 can only view Story 2.

The issue is that Author 2 can view both Story 1 and Story 2, which is wrong they only supposed to see Story 2.

I wanted to use middleware for this but I kind of hit a brick wall and not sure what next to do.

My tables

Story Table
id | title
1  | Story 1
2  | Story 2

Author Table
id | name
1  | Author 1
2  | Author 2

author_story table
id | author_id | story_id
1  |    1      |    1
2  |    1      |    2
3  |    2      |    2

My Story.php

protected $fillable = ['title'];

public function authors()
{
    return $this->belongsToMany('App\Author');
}

My Author.php

protected $fillable = ['name'];

public function stories()
{
    return $this->belongsToMany('App\Story');
}

My ViewStory.php (middleware)

if(Auth::check())
{
    return $next($request);
}else{
    abort(401);
}

Body:
Do you get any error?

I think you should use hasMany relation in my author model:

return $this->belongsToMany('App\Story',story_id, id);


问:
excel 'Refers to:' like control in C#
I'm working on VSTO application in C#. I've a Modal form, where I want to have a control similar to Excel's Name manager 'Refers to:' textbox. Whenever the control is in textbox, user can move to Excel sheets and select the appropriate range and that range gets added in the textbox. However, if the controls isn't in 'Refers to:' textbox, user cannot switch between excel sheets.

Is there anyway by which I could implement similar functionality?

Thanks

EDIT:
I figured out a way to do this. Application.InputBox gives a window wherein user can input required formula/range. Reference: https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.excel._application.inputbox?view=excel-pia

答:
Start by using Excel InterOp object model

Assuming you have an Excel or Window object reference to either the file or window you want to take control, you could use its property Selection to get that info from the Excel file and add it to your textbox.

Title: excel 'Refers to:' like control in C#


问:
Python program cannot be executed from console due to AttributeError
OS: Windows 10

I have a very simple python script datetime.py :

import datetime
print(datetime.datetime.now())
input("press enter to continue")
```

<p>Running from console: <code>python datetime.py</code></p>

<p>Output:</p>

```Traceback (most recent call last):
  File "datetime.py", line 1, in <module>
    import datetime
  File "C:\Users\DAN024\Documents\Python\datetime.py", line 7, in <module>
    print(datetime.datetime.now())
AttributeError: partially initialized module 'datetime' has no attribute 'now' (most likely due to a circular import)
```

答: change the name of the file from datetime.py to something else</p>

Body:
OS: Windows 10

I have a very simple python script datetime.py :

import datetime
print(datetime.datetime.now())
input("press enter to continue")

Running from console: python datetime.py

Output:

Traceback (most recent call last):
  File "datetime.py", line 1, in <module>
    import datetime
  File "C:\Users\DAN024\Documents\Python\datetime.py", line 7, in <module>
    print(datetime.datetime.now())
AttributeError: partially initialized module 'datetime' has no attribute 'now' (most likely due to a circular import)


问:
How to pass ref to children of children using array of refs React?
I'm trying to pass multiple times refs to children of children but it is not working. I have a functional component called AvatarBuilder that uses the Avatars component. This component renders a list of Avatar components. The idea is to have in AvatarBuilder references to each of the Avatar component.

Here is the code snippet summarized:

const AvatarBuilder = props => {
    ...
    // in this dummy example i would have 5 avatars
    const URLS=[1,2,3,4,5];
    const refs = URLS.map(item => ({ ref: React.createRef() }));
    return (
        <>
            <Avatars
                ref={refs}
                urlList={URLS}
            />
        </>
    );

const Avatars = React.forwardRef((props, ref) => {
    let urlList = props.urlList.map((url, index) => {
        return (
            <Avatar
                ref={ref[index].ref}
                url={url}
            />
        )
    })
    return (

            {urlList}

    )
});

const Avatar = React.forwardRef((props, ref) => {
    return (

    )
});

```

<p>I get the following warning and the refs array is not updated when all the components are mounted.</p>

```index.js:1 Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

Check the render method of `ForwardRef`.
    in h (at Avatar.js:11)
    in li (at Avatar.js:10)
    in ForwardRef (at Avatars.js:10)
    in ul (at Avatars.js:24)
    in ForwardRef (at AvatarBuilder.js:189)
    in AvatarBuilder (at App.js:19)
    in div (at App.js:14)
    in App (at src/index.js:9)
    in StrictMode (at src/index.js:8)
```

Any idea how should this be fixed? Thanks!

答:
For a functional component, you must use useRef and not React.createRef since a new instance of refs will be created on in render.

If you use React.createRef, then make use of useMemo to memoize the refs

const AvatarBuilder = props => {
    // in this dummy example i would have 5 avatars
    const URLS=[1,2,3,4,5];
    const refs = React.useMemo(() =>URLS.map(item => ({ ref: React.createRef() })), []); // create refs only once
    React.useEffect(() => {
       console.log(refs);
    },[])
    return (
            <Avatars
                ref={refs}
                urlList={URLS}
            />
    );
}
const Avatars = React.forwardRef((props, ref) => {
    let urlList = props.urlList.map((url, index) => {
        return (
            <Avatar
                ref={ref[index].ref}
                url={url}
            />
        )
    })
    return (

            {urlList}

    )
});

const Avatar = React.forwardRef((props, ref) => {
    return (

    )
});

ReactDOM.render(<AvatarBuilder/>, document.getElementById('app'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="app"/></code>```

Body:
I'm trying to pass multiple times refs to children of children but it is not working. I have a functional component called AvatarBuilder that uses the Avatars component. This component renders a list of Avatar components. The idea is to have in AvatarBuilder references to each of the Avatar component.

Here is the code snippet summarized:

const AvatarBuilder = props => {
    ...
    // in this dummy example i would have 5 avatars
    const URLS=[1,2,3,4,5];
    const refs = URLS.map(item => ({ ref: React.createRef() }));
    return (
        <>
            <Avatars
                ref={refs}
                urlList={URLS}
            />
        </>
    );

const Avatars = React.forwardRef((props, ref) => {
    let urlList = props.urlList.map((url, index) => {
        return (
            <Avatar
                ref={ref[index].ref}
                url={url}
            />
        )
    })
    return (

            {urlList}

    )
});

const Avatar = React.forwardRef((props, ref) => {
    return (

    )
});

I get the following warning and the refs array is not updated when all the components are mounted.

index.js:1 Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

Check the render method of `ForwardRef`.
    in h (at Avatar.js:11)
    in li (at Avatar.js:10)
    in ForwardRef (at Avatars.js:10)
    in ul (at Avatars.js:24)
    in ForwardRef (at AvatarBuilder.js:189)
    in AvatarBuilder (at App.js:19)
    in div (at App.js:14)
    in App (at src/index.js:9)
    in StrictMode (at src/index.js:8)

Any idea how should this be fixed? Thanks!

Body:
For a functional component, you must use useRef and not React.createRef since a new instance of refs will be created on in render.

If you use React.createRef, then make use of useMemo to memoize the refs

const AvatarBuilder = props => {
    // in this dummy example i would have 5 avatars
    const URLS=[1,2,3,4,5];
    const refs = React.useMemo(() =>URLS.map(item => ({ ref: React.createRef() })), []); // create refs only once
    React.useEffect(() => {
       console.log(refs);
    },[])
    return (
            <Avatars
                ref={refs}
                urlList={URLS}
            />
    );
}
const Avatars = React.forwardRef((props, ref) => {
    let urlList = props.urlList.map((url, index) => {
        return (
            <Avatar
                ref={ref[index].ref}
                url={url}
            />
        )
    })
    return (
        <ul className="Avatars" >
            {urlList}
        </ul>
    )
});

const Avatar = React.forwardRef((props, ref) => {
    return (
        <li className="Avatar">
            <img
                src={props.url}
                ref={ref}
            />
        </li>
    )
});

ReactDOM.render(<AvatarBuilder/>, document.getElementById('app'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="app"/>


问:
Webmethods - Retrieve PDF file from SFTP and encode
I am new to webmethods and need some guidance. I am tasked to read the PDF document from SFTP server and base64 encode it. I have managed to GET the file from SFTP location and now struggling to encode it. Below is the code snippet to read the file:

```<code>INVOKE pub.client.sftp:login
INVOKE pub.client.sftp:cd
INVOKE pub.client.sftp:ls
INVOKE pub.client.sftp:get
MAP
</code>```

I later modified the code to include base64 encoding, no output is produced. Code is shown below:

```<code>INVOKE pub.client.sftp:login
INVOKE pub.client.sftp:cd
INVOKE pub.client.sftp:ls
INVOKE pub.client.sftp:get
INVOKE pub.string:base64Encode
MAP
</code>```

when i debug the code, it executes SFTP GET and stops. No information about encoding.

Please guide me to achieve this requirement. Thank you for your help in advance.

答: The pub.string:base64Encode expect a byte[] Input, you can try to convert the stream to byte[] with pub.io:streamToBytes</p>

Body:
I am new to webmethods and need some guidance. I am tasked to read the PDF document from SFTP server and base64 encode it. I have managed to GET the file from SFTP location and now struggling to encode it. Below is the code snippet to read the file:

INVOKE pub.client.sftp:login
INVOKE pub.client.sftp:cd
INVOKE pub.client.sftp:ls
INVOKE pub.client.sftp:get
MAP

I later modified the code to include base64 encoding, no output is produced. Code is shown below:

INVOKE pub.client.sftp:login
INVOKE pub.client.sftp:cd
INVOKE pub.client.sftp:ls
INVOKE pub.client.sftp:get
INVOKE pub.string:base64Encode
MAP

when i debug the code, it executes SFTP GET and stops. No information about encoding.

Please guide me to achieve this requirement. Thank you for your help in advance.


问:
jQuery / Safari Show/Hide issue with flash
Im using show/hide to load a 'loading' flash file whilst a form loads.

The div im trying to show contains an swf file

This works fine in all browsers except safari, which does not show the swf file upon clicking the submit button

ive got a test set up here...
https://www.paydaygap.co.uk/test.php

Im using...

```<code>$('#form').show();
$('#loading').hide();

$('.sendform').click(function(){

    $('#form').hide();
    $('#loading').show();

});
</code>```

and the hidden div which should show on clicking .sendform is...

```<code><div id="loading" style="padding:50px; text-align:center;">
<h1>This thing is loading</h1>
<p>
  <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0" width="300" height="300" >
    <param name="movie" value="lightboxform/loading.swf" />
    <param name="quality" value="high" />
    <param name="wmode" value="transparent" />
    <embed src="lightboxform/loading.swf" width="300" height="300" quality="high" pluginspage="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" wmode="transparent"></embed>
  </object>
</p>
</code>```

Any assistance greatly appreciated

答:
At first glance I'm wondering why you're using the old-skool embedding the flash rather than inserting it with javascript?

Try inserting the flash with swfobject or flashembed (http://flowplayer.org/tools/toolbox/flashembed.html) using:

```<code>flashembed(this, "lightboxform/loading.swf");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Im using show/hide to load a 'loading' flash file whilst a form loads.

The div im trying to show contains an swf file

This works fine in all browsers except safari, which does not show the swf file upon clicking the submit button

ive got a test set up here...
https://www.paydaygap.co.uk/test.php

Im using...

$('#form').show();
$('#loading').hide();

$('.sendform').click(function(){

    $('#form').hide();
    $('#loading').show();

});

and the hidden div which should show on clicking .sendform is...

This thing is loading

  <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0" width="300" height="300" >
    <param name="movie" value="lightboxform/loading.swf" />
    <param name="quality" value="high" />
    <param name="wmode" value="transparent" />
    <embed src="lightboxform/loading.swf" width="300" height="300" quality="high" pluginspage="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" wmode="transparent"></embed>
  </object>

Any assistance greatly appreciated

Body:
At first glance I'm wondering why you're using the old-skool embedding the flash rather than inserting it with javascript?

Try inserting the flash with swfobject or flashembed (http://flowplayer.org/tools/toolbox/flashembed.html) using:

flashembed(this, "lightboxform/loading.swf");


问:
how do i make an installer with several applications packed and installed together in start-menu (like Microsoft does)
I'm making a wpf application that launches and installs several other apps like example image from google.

It should look like Microsoft Office programs when installed like this

So I have made a test-application and published it using clickOnce, and it works perfectly fine and even makes the Start-Menu folder and all, but I could not find a way to add more apps inside the folder, or Group install them. All the sample apps I published have their own folder in the Start-Menu folder.

Do I do something else in the Publish section in the Properties menu?

Any help is appreciated.

答:
Found someone saying this
"Set the Publisher Name to the same for all your application, and they'll all appear in a subfolder on the start menu."</p>


问:
Python in powershell is giving me an import error when I try to import the module called urlib
My program uses this module, and here is the lines of code I put in order to import urlib:

```<code>import random
from urlib.request import urlopen
import sys

</code>```

Python gives the following response:

```<code>Traceback (most recent call last):
  File "oop_Test.py", line 2, in <module>
    from urlib.request import urlopen
ModuleNotFoundError: No module named 'urlib'
</code>```

From the other questions that were similar to this, the answer seems to be that Python 3 changed the way you import the module. From what I found, my code is compatible with Python 3, and yet it still gives me the error: what am i doing wrong or do you need more code?

答: The name of the module is urllib not urlib.

Body:
My program uses this module, and here is the lines of code I put in order to import urlib:

import random
from urlib.request import urlopen
import sys

Python gives the following response:

Traceback (most recent call last):
  File "oop_Test.py", line 2, in <module>
    from urlib.request import urlopen
ModuleNotFoundError: No module named 'urlib'

From the other questions that were similar to this, the answer seems to be that Python 3 changed the way you import the module. From what I found, my code is compatible with Python 3, and yet it still gives me the error: what am i doing wrong or do you need more code?


问:
How to fix YAML File Transform Task when "changes are already present"?
We are starting with Azure Pipelines (YAML) and we are experiencing the following error during a FileTransform task:

```<code>##[error]Unable to apply transformation for the given package - Changes are already present in the package.
</code>```

The result is that no transformation is taking place and the deployed config matches the Release.config

This is an ASP.NET web app with a Web.Config, Web.Stage.config, Web.Release.config etc.

The end goal is to set different stages and apply the corresponding transformations with the config files. But for now, I just would like to get the "Release" build and apply the "Stage" transformation, to make sure this task works.

If it helps, this is a snippet of the YAML:

```<code>trigger:
- master

pool:
  vmImage: 'windows-latest'

variables:
  solution: '**/*.sln'
  buildPlatform: 'Any CPU'
  buildConfiguration: 'Release'
</code>```

...

```<code>task: VSBuild@1
  inputs:
    solution: '$(solution)'
    msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)"'
    platform: '$(buildPlatform)'
    configuration: '$(buildConfiguration)'
</code>```

...

```<code>- task: PublishBuildArtifacts@1
  inputs:
    PathtoPublish: '$(Build.ArtifactStagingDirectory)'
    ArtifactName: 'drop'
    publishLocation: 'Container'

- task: FileTransform@2
  inputs:
    folderPath: '$(Build.ArtifactStagingDirectory)/**/*.zip'
    xmlTransformationRules: '-transform **\*.Stage.config -xml **\*.config'

- task: AzureRmWebAppDeployment@4
  inputs:
    ConnectionType: 'AzureRM'
    azureSubscription: 'Microsoft Partner Network(blablabla)'
    appType: 'webApp'
    WebAppName: 'mywebapp'
    packageForLinux: '$(Build.ArtifactStagingDirectory)/**/*.zip'
</code>```

Update:
The final web.config file contains a connection string like this:

```<code><add name="DefaultConnection" connectionString="$(ReplacableToken_DefaultConnection-Web.config Connection String_0)" providerName="System.Data.SqlClient"/>
</code>```

Here is the log for the build step. You can see transformaton is hapenning during build.

What am I missing here?

Thanks!

答:
I tested and found above error will occur in below cases.

1, When no configuration file or transform file were found against the file pattern in xmlTransformationRules. This could be the file pattern is incorrect or the transform file/configuration file does not exist in the package.

2, When the configuration file and transform file are not in the same folder within the specified package.

The xmlTransformationRules in above yaml was working in my test. So you need to check if
configuration file and transform file are in different folders. You need to make sure they are in the same folder for XML transformation to take effect.

See the XML transformation notes
 for more information.

Update:

By default web.config file will be transformed against the web.{buildConfiguration}.config during building.

You can disable vsbuild task to transform web.config by passing /p:IsTransformWebConfigDisabled=true to msbuildArgs attribute. See below example:

```<code>- task: VSBuild@1
  inputs:
    solution: '$(solution)'
    msbuildArgs: '/p:IsTransformWebConfigDisabled=true /p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)"'
    platform: '$(buildPlatform)'
    configuration: '$(buildConfiguration)'
</code>```

Body:
We are starting with Azure Pipelines (YAML) and we are experiencing the following error during a FileTransform task:

##[error]Unable to apply transformation for the given package - Changes are already present in the package.

The result is that no transformation is taking place and the deployed config matches the Release.config

This is an ASP.NET web app with a Web.Config, Web.Stage.config, Web.Release.config etc.

The end goal is to set different stages and apply the corresponding transformations with the config files. But for now, I just would like to get the "Release" build and apply the "Stage" transformation, to make sure this task works.

If it helps, this is a snippet of the YAML:

trigger:
- master

pool:
  vmImage: 'windows-latest'

variables:
  solution: '**/*.sln'
  buildPlatform: 'Any CPU'
  buildConfiguration: 'Release'

...

task: VSBuild@1
  inputs:
    solution: '$(solution)'
    msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)"'
    platform: '$(buildPlatform)'
    configuration: '$(buildConfiguration)'

...

- task: PublishBuildArtifacts@1
  inputs:
    PathtoPublish: '$(Build.ArtifactStagingDirectory)'
    ArtifactName: 'drop'
    publishLocation: 'Container'

- task: FileTransform@2
  inputs:
    folderPath: '$(Build.ArtifactStagingDirectory)/**/*.zip'
    xmlTransformationRules: '-transform **\*.Stage.config -xml **\*.config'

- task: AzureRmWebAppDeployment@4
  inputs:
    ConnectionType: 'AzureRM'
    azureSubscription: 'Microsoft Partner Network(blablabla)'
    appType: 'webApp'
    WebAppName: 'mywebapp'
    packageForLinux: '$(Build.ArtifactStagingDirectory)/**/*.zip'

Update:
The final web.config file contains a connection string like this:

<add name="DefaultConnection" connectionString="$(ReplacableToken_DefaultConnection-Web.config Connection String_0)" providerName="System.Data.SqlClient"/>

Here is the log for the build step. You can see transformaton is hapenning during build.

What am I missing here?

Thanks!

Body:
I tested and found above error will occur in below cases.

1, When no configuration file or transform file were found against the file pattern in xmlTransformationRules. This could be the file pattern is incorrect or the transform file/configuration file does not exist in the package.

2, When the configuration file and transform file are not in the same folder within the specified package.

The xmlTransformationRules in above yaml was working in my test. So you need to check if
configuration file and transform file are in different folders. You need to make sure they are in the same folder for XML transformation to take effect.

See the XML transformation notes
 for more information.

Update:

By default web.config file will be transformed against the web.{buildConfiguration}.config during building.

You can disable vsbuild task to transform web.config by passing /p:IsTransformWebConfigDisabled=true to msbuildArgs attribute. See below example:

- task: VSBuild@1
  inputs:
    solution: '$(solution)'
    msbuildArgs: '/p:IsTransformWebConfigDisabled=true /p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)"'
    platform: '$(buildPlatform)'
    configuration: '$(buildConfiguration)'


问:
How to access drawable from non activity class
I am in a situation where I have to use the drawable folder of my app form a non activity class. I tried using the parent activity with the following code:

```<code>ParentActivity pa = new ParentActivity();
Drawable d = pa.getResources()..getDrawable(R.drawable.icon);`
</code>```

But this returns me a NulLPointerException.
How can I achieve this?

答:
Pass the context object as a parameter  to the constructor of the non Activity class.

Then use that context object to get the Resources.

Example

```<code>public class MyClass {
  Context context;
  public MyClass(Context context) {
      this.context = context;
  }

  public void urMethod() {
    Drawable drawable=context.getResources().getDrawable(R.drawable.icon);
    // use this drawable as u need
  }
}
</code>```

Body:
I am in a situation where I have to use the drawable folder of my app form a non activity class. I tried using the parent activity with the following code:

ParentActivity pa = new ParentActivity();
Drawable d = pa.getResources()..getDrawable(R.drawable.icon);`

But this returns me a NulLPointerException.
How can I achieve this?

Body:
Pass the context object as a parameter  to the constructor of the non Activity class.

Then use that context object to get the Resources.

Example

public class MyClass {
  Context context;
  public MyClass(Context context) {
      this.context = context;
  }

  public void urMethod() {
    Drawable drawable=context.getResources().getDrawable(R.drawable.icon);
    // use this drawable as u need
  }
}


问:
Is it possible to use Docker.DotNet to start a container programmatically on Azure Pipelines?
I have a microservices application and I wan't to start the whole stack to run integration tests. The idea is to be able to run the tests from Test Explorer within Visual Studio. So I don't want to create a shell script to be able to accomplish this.

The idea is to start all external microservice dependencies in containers and then run a TestServer of the system under test to receive the test requests so that the system can call other microservices.

I found this library and liked the idea of start containers programmatically to achieve the afore mentioned.

What I don't know, is if this would work running on an Azure Pipeline. What would be the correct docker engine address on Azure to initialize Docker.DotNet?

```<code>// Default Docker Engine on Windows
using Docker.DotNet;
DockerClient client = new DockerClientConfiguration(
    new Uri("npipe://./pipe/docker_engine"))
     .CreateClient();
// Default Docker Engine on Linux
using Docker.DotNet;
DockerClient client = new DockerClientConfiguration(
    new Uri("unix:///var/run/docker.sock"))
     .CreateClient();
</code>```

答:
What I don't know, is if this would work running on an Azure Pipeline.
What would be the correct docker engine address on Azure to initialize
Docker.DotNet?

You can add Powershell task in your pipeline which runs in hosted windows agent, with content like this:

```<code>[System.IO.Directory]::GetFiles("\\.\\pipe\\") | Select-String "docker"
</code>```

Here's the result if I use hosted windows2019 agent:

So I think the address is \\.\\pipe\\docker_engine (not sure if it needs some changes like slash and backslash when using in your code).

Body:
I have a microservices application and I wan't to start the whole stack to run integration tests. The idea is to be able to run the tests from Test Explorer within Visual Studio. So I don't want to create a shell script to be able to accomplish this.

The idea is to start all external microservice dependencies in containers and then run a TestServer of the system under test to receive the test requests so that the system can call other microservices.

I found this library and liked the idea of start containers programmatically to achieve the afore mentioned.

What I don't know, is if this would work running on an Azure Pipeline. What would be the correct docker engine address on Azure to initialize Docker.DotNet?

// Default Docker Engine on Windows
using Docker.DotNet;
DockerClient client = new DockerClientConfiguration(
    new Uri("npipe://./pipe/docker_engine"))
     .CreateClient();
// Default Docker Engine on Linux
using Docker.DotNet;
DockerClient client = new DockerClientConfiguration(
    new Uri("unix:///var/run/docker.sock"))
     .CreateClient();

Body:
What I don't know, is if this would work running on an Azure Pipeline.
What would be the correct docker engine address on Azure to initialize
Docker.DotNet?

You can add Powershell task in your pipeline which runs in hosted windows agent, with content like this:

[System.IO.Directory]::GetFiles("\\.\\pipe\\") | Select-String "docker"

Here's the result if I use hosted windows2019 agent:

So I think the address is \\.\\pipe\\docker_engine (not sure if it needs some changes like slash and backslash when using in your code).


问:
making the whole page blur when I click on a certain button
So, I have a button and want the whole body to go blurry when I click on it and show an alert or a pop-up message. this is what I have been trying to do:

function myFunction() {
  $('body').css("filter","blur(2px)");
  alert("hello");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="phone_num d-none d-xl-block">
  {% trans 'try' %}
</div></code>```

But I have a couple of issues:
1- the blur doesn't last until I click okay to the alert and moves to the next page right away.
2- the alert is way up on the top of the page o can I some how move to the middle of the page?

答:
Change

```<code>onclick="myFunction"
</code>```

to

```<code>onclick=myFunction()
</code>```

function myFunction() {
  $('body').css("filter", "blur(2px)");
  alert("hello");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<div class="phone_num d-none d-xl-block">
  {% trans 'try' %}
</div></code>```

Body:
So, I have a button and want the whole body to go blurry when I click on it and show an alert or a pop-up message. this is what I have been trying to do:

function myFunction() {
  $('body').css("filter","blur(2px)");
  alert("hello");
}

  {% trans 'try' %}

But I have a couple of issues:
1- the blur doesn't last until I click okay to the alert and moves to the next page right away.
2- the alert is way up on the top of the page o can I some how move to the middle of the page?

Body:
Change

onclick="myFunction"

to

onclick=myFunction()

function myFunction() {
  $('body').css("filter", "blur(2px)");
  alert("hello");
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<div class="phone_num d-none d-xl-block">
  <a class="boxed-btn3" href="{% url 'homepage' %}" onclick=myFunction()>{% trans 'try' %}</a>
</div>


问:
Error faced while using TM package's VCorpus in R
I am facing the below error while working on the TM package with R.

```<code>library("tm")
Loading required package: NLP
Warning messages:
1: package ‘tm’ was built under R version 3.4.2
2: package ‘NLP’ was built under R version 3.4.1
</code>```

corpus <- VCorpus(DataframeSource(data))

Error: all(!is.na(match(c("doc_id", "text"), names(x)))) is not TRUE

Have tried various ways like reinstalling the package, updating with new version of R but the error still persists. For the same data file the same code runs on another system with the same version of R.

答: I encountered this error using the BTM package also. As Eva notes, it may relate to your column headings (which must be doc_id and text, respectively). However, in my case it was because my doc_id values had become corrupted and were no longer unique. If the error persists, try examining your doc_id values to ensure they increment properly.

Body:
I am facing the below error while working on the TM package with R.

library("tm")
Loading required package: NLP
Warning messages:
1: package ‘tm’ was built under R version 3.4.2
2: package ‘NLP’ was built under R version 3.4.1

corpus <- VCorpus(DataframeSource(data))

Error: all(!is.na(match(c("doc_id", "text"), names(x)))) is not TRUE

Have tried various ways like reinstalling the package, updating with new version of R but the error still persists. For the same data file the same code runs on another system with the same version of R.


问:
axios not sending json data
I am trying to post some json data using axios. The axios.post method works well:

```<code>axios.post(
    "http://localhost/api",
    {"k1":"v1","k2":"v2"}
)
</code>```

However, the following code does not work:

```<code>const axiosInstance = axios.create({
    baseURL: 'http://localhost/api',
    method: 'POST',
    data: {"k1":"v1","k2":"v2"}
});
axiosInstance.request()
</code>```

The backend is a Flask app, which cannot receive any data. It cannot even read the 'Content-type' header.
So what is the difference between the above two codes? Any idea how to modify the second method so it can work?

答:
You should stringify data before sending.

data: JSON.stringify({"k1":"v1","k2":"v2"})

Title: axios not sending json data

Body:
I am trying to post some json data using axios. The axios.post method works well:

axios.post(
    "http://localhost/api",
    {"k1":"v1","k2":"v2"}
)

However, the following code does not work:

const axiosInstance = axios.create({
    baseURL: 'http://localhost/api',
    method: 'POST',
    data: {"k1":"v1","k2":"v2"}
});
axiosInstance.request()

The backend is a Flask app, which cannot receive any data. It cannot even read the 'Content-type' header.
So what is the difference between the above two codes? Any idea how to modify the second method so it can work?


问:
How can I run all the targets in an Ant buildfile?
I would like to execute all targets instead of specifying each one.

For example:

```<code><?xml version="1.0"?>
<project name="Kte" default="all" basedir="/home/Kte">

    <target name="target1">
    </target>

    <target name="target2">
    </target>
</project>
</code>```

Currently I have use:

```<code>$ ant target1
$ ant target2
</code>```

I'd like to use:

```<code>$ ant
</code>```

and have both targets get built  (this is just an example. Reality I have a long ever changing Ant buildfile with sub-ant files so would be very handy to have an "all" feature.

答:
You could create an ant task all, which depends on all the specific targets that you have...</p>

```<code><target name="all" depends="target1, target2, ... ">
</target>

ant all
</code>```

Body:
I would like to execute all targets instead of specifying each one.

For example:

<?xml version="1.0"?>
<project name="Kte" default="all" basedir="/home/Kte">

    <target name="target1">
    </target>

    <target name="target2">
    </target>
</project>

Currently I have use:

$ ant target1
$ ant target2

I'd like to use:

$ ant

and have both targets get built  (this is just an example. Reality I have a long ever changing Ant buildfile with sub-ant files so would be very handy to have an "all" feature.

Body:
You could create an ant task all, which depends on all the specific targets that you have...

<target name="all" depends="target1, target2, ... ">
</target>

ant all


问:
Can a client side certificate be sent along in a header?
From a MS IIS server I need to request some files. I can do that manually using curl like this:

```<code>curl --cert thecert.pem --http1.1 -i https://somehost.com/somefile.pdf
</code>```

As you can see I manually provide a client side certificate along with the request. I now need to be able to do this request from the Cantaloupe image server but I can't find any option to do this in the documentation. I can however, provide headers along with the request. I don't really have experience with client side certificates, but as far as I know they cannot be placed in the header of a request.

But before I dive into the sources of Cantaloupe to make a fork and fight with Java I want to be sure that I'm right in my thinking.

Can client side certificates be defined in a request header? Or am I right in thinking that that is not possible?

答: Certificates, may it be from file or from crypto device like usb token or smartcard, can be encoded in Base64 string.  Thus it is possible to provide certificates in request header in Base64 encoded format.</p>

Body:
From a MS IIS server I need to request some files. I can do that manually using curl like this:

curl --cert thecert.pem --http1.1 -i https://somehost.com/somefile.pdf

As you can see I manually provide a client side certificate along with the request. I now need to be able to do this request from the Cantaloupe image server but I can't find any option to do this in the documentation. I can however, provide headers along with the request. I don't really have experience with client side certificates, but as far as I know they cannot be placed in the header of a request.

But before I dive into the sources of Cantaloupe to make a fork and fight with Java I want to be sure that I'm right in my thinking.

Can client side certificates be defined in a request header? Or am I right in thinking that that is not possible?


问:
Should I separate Redis from the webserver if I would like to have my Laravel application under a Load Balancer?
I am wondering, if in the future I would like to handle high volume traffic by having my Laravel application under a Load Balancer. The process will be as follow?

1 Load balancer to distribute traffic into:

2 VPS. Each one of these, with an identical Laravel application.

Each web server can connect with:
1 VPS for MYSQL

And here is my doubt, should I also separate Redis such as 1 VPS for Redis and maintaining my Jobs with Laravel Queues?

Or should Redis & Laravel Queues daemon still be on each one of the 2 identical web servers?

答:
I think the better way is to have the redis installed and set up on one of your ECS instances.

After that, you should set your Redis config (REDIS_HOST,REDIS_PORT and REDIS_PASSWORD) in the .env to connect that ECS instance, on both ECS instances. So it will become as below:

A ECS -- A ECS redis service
B ECS -- A ECS redis service

In this way, you does not have to set up an extra ECS which might cost you more and during the same time you can achieve what you want. A drawback for this method is you might need to set up 2 images for your ECS, one with Redis configured and one without.


问:
LARAVEL 7 || Trying to get property 'name' of non-object
I tried to get the name from the author table but this error always happens. What should I do?

MODEL
App\Book

```<code>public function author()
    {
        return $this->hasOne('App\Author');
    }
</code>```

App\Author

```<code>public function book()
{
       return $this->belongsTo('App\Book');
}
</code>```

Views
Author/show...

```<code>   @php
        $book = Book::with('author')->where('author_id',$author->id)->get();
   @endphp`
   @foreach ($book as $data)

       ...
          Author name : {{$data->author_id->name}}
       ...

   @endforeach
</code>```

答:
Change code in view like this :

...
   $data->author->name
...

do not use "id"

Body:
I tried to get the name from the author table but this error always happens. What should I do?

MODEL
App\Book

public function author()
    {
        return $this->hasOne('App\Author');
    }

App\Author

public function book()
{
       return $this->belongsTo('App\Book');
}

Views
Author/show...

   @php
        $book = Book::with('author')->where('author_id',$author->id)->get();
   @endphp`
   @foreach ($book as $data)

       ...
          Author name : {{$data->author_id->name}}
       ...

   @endforeach


问:
Interweaving two NumPy arrays efficiently
Assume the following arrays are given:

```<code>a = array([1, 3, 5])
b = array([2, 4, 6])
</code>```

How would one interweave them efficiently so that one gets a third array like the following?

```<code>c = array([1, 2, 3, 4, 5, 6])
</code>```

It can be assumed that length(a) == length(b).

答:
Another one-liner: np.vstack((a,b)).T.ravel()

One more: np.stack((a,b),1).ravel()

Body:
Assume the following arrays are given:

a = array([1, 3, 5])
b = array([2, 4, 6])

How would one interweave them efficiently so that one gets a third array like the following?

c = array([1, 2, 3, 4, 5, 6])

It can be assumed that length(a) == length(b).


问:
I want to embed video by url in php landing page
This is a video URL

```<code>https://lh3.googleusercontent.com/oZQBTwwbQKCuK346RgySUhXsve331f0LYNsFaf7coxCJd_zLN7n7LtTJj3rHBZ7eGBmNVYnbm94_hpb1Nbp1wpVx-PKqbkBkkuMuyPmAuiHInyctaJwuzPn8yzxU_hApAjjomS9A=m22?cpn=GpvVeTPeeVJK_253&c=WEB_EMBEDDED_PLAYER&cver=20200415
</code>```

It can be opened in Firefox browser, but I want to open this video by URL in PHP landing page.

答:
Edit: Aight, seems like google does not want you to embed videos from googleusercontent on any non-google pages. IMO the best possibility would be to upload it to youtube (you can do that right from Google Photos) and simply not list it, that way you can only access it with the link. Furthermore youtube videos are really easy to embed on a website. Refering to this: https://support.google.com/culturalinstitute/partners/answer/6056695?hl=en

Have you tried using HTML and the video tag?
If not, try this:

```<code>$videourl = 'https://lh3.googleusercontent.com/oZQBTwwbQKCuK346RgySUhXsve331f0LYNsFaf7coxCJd_zLN7n7LtTJj3rHBZ7eGBmNVYnbm94_hpb1Nbp1wpVx-PKqbkBkkuMuyPmAuiHInyctaJwuzPn8yzxU_hApAjjomS9A=m22?cpn=GpvVeTPeeVJK_253&c=WEB_EMBEDDED_PLAYER&cver=20200415';
$html = '<video width="320" height="240" controls><source src="' . $videourl . '" type="video/ogg"></video>';
print_r($html);
</code>```

Also, try the following url as $videourl:

```<code>https://lh3.googleusercontent.com/oZQBTwwbQKCuK346RgySUhXsve331f0LYNsFaf7coxCJd_zLN7n7LtTJj3rHBZ7eGBmNVYnbm94_hpb1Nbp1wpVx-PKqbkBkkuMuyPmAuiHInyctaJwuzPn8yzxU_hApAjjomS9A=m22?cpn=GpvVeTPeeVJK_253&cver=20200415
</code>```

This one is not using the web embedded player, you gotta change the tag too though.

Body:
This is a video URL

https://lh3.googleusercontent.com/oZQBTwwbQKCuK346RgySUhXsve331f0LYNsFaf7coxCJd_zLN7n7LtTJj3rHBZ7eGBmNVYnbm94_hpb1Nbp1wpVx-PKqbkBkkuMuyPmAuiHInyctaJwuzPn8yzxU_hApAjjomS9A=m22?cpn=GpvVeTPeeVJK_253&c=WEB_EMBEDDED_PLAYER&cver=20200415

It can be opened in Firefox browser, but I want to open this video by URL in PHP landing page.

Body:
Edit: Aight, seems like google does not want you to embed videos from googleusercontent on any non-google pages. IMO the best possibility would be to upload it to youtube (you can do that right from Google Photos) and simply not list it, that way you can only access it with the link. Furthermore youtube videos are really easy to embed on a website. Refering to this: https://support.google.com/culturalinstitute/partners/answer/6056695?hl=en

Have you tried using HTML and the video tag?
If not, try this:

$videourl = 'https://lh3.googleusercontent.com/oZQBTwwbQKCuK346RgySUhXsve331f0LYNsFaf7coxCJd_zLN7n7LtTJj3rHBZ7eGBmNVYnbm94_hpb1Nbp1wpVx-PKqbkBkkuMuyPmAuiHInyctaJwuzPn8yzxU_hApAjjomS9A=m22?cpn=GpvVeTPeeVJK_253&c=WEB_EMBEDDED_PLAYER&cver=20200415';
$html = '<video width="320" height="240" controls><source src="' . $videourl . '" type="video/ogg"></video>';
print_r($html);

Also, try the following url as $videourl:

https://lh3.googleusercontent.com/oZQBTwwbQKCuK346RgySUhXsve331f0LYNsFaf7coxCJd_zLN7n7LtTJj3rHBZ7eGBmNVYnbm94_hpb1Nbp1wpVx-PKqbkBkkuMuyPmAuiHInyctaJwuzPn8yzxU_hApAjjomS9A=m22?cpn=GpvVeTPeeVJK_253&cver=20200415

This one is not using the web embedded player, you gotta change the tag too though.


问:
What is the different between encode and encription?
I am using windows form and mysql.

I am very confuse about different between encode and encription?.

encode also change the string value. and decode is give back the string.

In my program,...

userid - mcs
password - mcs

i want to store these strings in mysql database. but not a same string, for security purpose.

What is secure way to store these datas.

encode and encription which is best for this requirement.

thanks in advance.

i googled for the different but till i am not clear!. any one pls tell me  the different between encode and encription?. For my requrement what i use?.

Before leave this question just vist my downvote question in Click here

答:
Encoding is how the different characters are represented according to their memory spaces (8bit etc.). Encryption is how to keep a text hidden with the use of a secret key. After encryption the text turns into a series of arbitrary bytes so you encode it with say Base64 encoding to be able to make it into a readable (and properly cachable) string.

You'll want to encrypt your user information before storing in a database for security purposes. MySql Encryption has many function to help you with that.


问:
Return only top level fields in elasticsearch query?
I have a document that has nested fields. Example:

```<code>    "mappings": {
        "blogpost": {
          "properties": {
            "title": { "type": "text"  },
            "body":  { "type": "text"  },
            "comments": {
              "type": "nested",
              "properties": {
                "name":    { "type": "text"  },
                "comment": { "type": "text"  },
                "age":     { "type": "short"   },
                "stars":   { "type": "short"   },
                "date":    { "type": "date"    }
              }
            }
          }
        }
  }
}
</code>```

Can the query be modified so that the response only contains non-nested fields?

In this example, the response would only contain body and title.

Using _source you can exclude/include fields

```<code>GET /blogpost/_search
{
    "_source":{
        "excludes":["comments"]
    }
}
</code>```

But you have to explicitly put the field names inside exclude, I'm searching for a way to exclude all nested fields without knowing their field name

答:
You can achieve that but in a static way, which means you entered the field(s) name using excludes keyword, like:

```<code>GET your_index/_search
{
    "_source": {
        "excludes": "comments"
    },
    "query": {
        "match_all" : {}
    }
}
</code>```

excludes can take an array of strings; not just one string.

Body:
I have a document that has nested fields. Example:

    "mappings": {
        "blogpost": {
          "properties": {
            "title": { "type": "text"  },
            "body":  { "type": "text"  },
            "comments": {
              "type": "nested",
              "properties": {
                "name":    { "type": "text"  },
                "comment": { "type": "text"  },
                "age":     { "type": "short"   },
                "stars":   { "type": "short"   },
                "date":    { "type": "date"    }
              }
            }
          }
        }
  }
}

Can the query be modified so that the response only contains non-nested fields?

In this example, the response would only contain body and title.

Using _source you can exclude/include fields

GET /blogpost/_search
{
    "_source":{
        "excludes":["comments"]
    }
}

But you have to explicitly put the field names inside exclude, I'm searching for a way to exclude all nested fields without knowing their field name

Body:
You can achieve that but in a static way, which means you entered the field(s) name using excludes keyword, like:

GET your_index/_search
{
    "_source": {
        "excludes": "comments"
    },
    "query": {
        "match_all" : {}
    }
}

excludes can take an array of strings; not just one string.


问:
Why are images and javascript files included in DNN no longer cached on the client after I replace them?
I installed DotNetNuke version 4.9.2 and I'm watching the primed cache states using Firebug and YSLOW...

All the images and javascript are cached on the client, unless I replace them... So If I upload a new LOGO image, it is no longer cached.  The existing ones are cached.  If i replace an existing .js file (I ran one through the minifier), it is no longer cached.  If i replace the new file with the original file, they are once again cached.

I couldn't find any documentation on this... any ideas? Thanks!

答: Have you looked at the cache settings under host settings I think?</p>

OwnerDisplayName: Jonathan Parker


问:
MYSQL ON DUPLICATE KEY UPDATE for copying table
I have 2 tables, temporary and permanent table.
My objective is to copy temporary data into permanent table but must update the permanant table.

Below are the tables

```<code>### Temp. table
CREATE TABLE `tb_temp_data` (
  `key_id` varchar(20) NOT NULL DEFAULT '',
  `h00` int(11) DEFAULT '0',
  `h01` int(11) DEFAULT '0',
  `h02` int(11) DEFAULT '0',
  `h03` int(11) DEFAULT '0',
  `h04` int(11) DEFAULT '0',
  `h05` int(11) DEFAULT '0',
  `h06` int(11) DEFAULT '0',
  `h07` int(11) DEFAULT '0',
  `h08` int(11) DEFAULT '0',
  `h09` int(11) DEFAULT '0',
  `h10` int(11) DEFAULT '0',
  `h11` int(11) DEFAULT '0',
  `h12` int(11) DEFAULT '0',
  `h13` int(11) DEFAULT '0',
  `h14` int(11) DEFAULT '0',
  `h15` int(11) DEFAULT '0',
  `h16` int(11) DEFAULT '0',
  `h17` int(11) DEFAULT '0',
  `h18` int(11) DEFAULT '0',
  `h19` int(11) DEFAULT '0',
  `h20` int(11) DEFAULT '0',
  `h21` int(11) DEFAULT '0',
  `h22` int(11) DEFAULT '0',
  `h23` int(11) DEFAULT '0',
  `grand_total` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`key_id`)
) ENGINE=MyISAM;

### Permanant table
CREATE TABLE `tb_permanant_data` (
  `key_id` varchar(20) NOT NULL DEFAULT '',
  `h00` int(11) DEFAULT '0',
  `h01` int(11) DEFAULT '0',
  `h02` int(11) DEFAULT '0',
  `h03` int(11) DEFAULT '0',
  `h04` int(11) DEFAULT '0',
  `h05` int(11) DEFAULT '0',
  `h06` int(11) DEFAULT '0',
  `h07` int(11) DEFAULT '0',
  `h08` int(11) DEFAULT '0',
  `h09` int(11) DEFAULT '0',
  `h10` int(11) DEFAULT '0',
  `h11` int(11) DEFAULT '0',
  `h12` int(11) DEFAULT '0',
  `h13` int(11) DEFAULT '0',
  `h14` int(11) DEFAULT '0',
  `h15` int(11) DEFAULT '0',
  `h16` int(11) DEFAULT '0',
  `h17` int(11) DEFAULT '0',
  `h18` int(11) DEFAULT '0',
  `h19` int(11) DEFAULT '0',
  `h20` int(11) DEFAULT '0',
  `h21` int(11) DEFAULT '0',
  `h22` int(11) DEFAULT '0',
  `h23` int(11) DEFAULT '0',
  `grand_total` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`key_id`)
) ENGINE=MyISAM;

INSERT INTO tb_permanant_data
       SELECT * FROM  tb_temp_data ;
       ON DUPLICATE KEY UPDATE h00 = ?
</code>```

I want to make sure all h00 until h23 will be updated by adding the value into tb_permanant_data but i have no idea on how to do that...

Can anyone help?

Thanks

答:
```<code>INSERT INTO tb_permanant_data SELECT * FROM tb_temp_data
ON DUPLICATE KEY UPDATE
  h00 = VALUES(h00),
  h01 = VALUES(h01),
  h02 = VALUES(h02),
  h03 = VALUES(h03),
  h04 = VALUES(h04),
  h05 = VALUES(h05),
  h06 = VALUES(h06),
  h07 = VALUES(h07),
  h08 = VALUES(h08),
  h09 = VALUES(h09),
  h10 = VALUES(h10),
  h11 = VALUES(h11),
  h12 = VALUES(h12),
  h13 = VALUES(h13),
  h14 = VALUES(h14),
  h15 = VALUES(h15),
  h16 = VALUES(h16),
  h17 = VALUES(h17),
  h18 = VALUES(h18),
  h19 = VALUES(h19),
  h20 = VALUES(h20),
  h21 = VALUES(h21),
  h22 = VALUES(h22),
  h23 = VALUES(h23);
</code>```

Note, table tb_permanant_data can contain rows which doesn't exist in tb_temp_data (by id).

Body:
I have 2 tables, temporary and permanent table.
My objective is to copy temporary data into permanent table but must update the permanant table.

Below are the tables

### Temp. table
CREATE TABLE `tb_temp_data` (
  `key_id` varchar(20) NOT NULL DEFAULT '',
  `h00` int(11) DEFAULT '0',
  `h01` int(11) DEFAULT '0',
  `h02` int(11) DEFAULT '0',
  `h03` int(11) DEFAULT '0',
  `h04` int(11) DEFAULT '0',
  `h05` int(11) DEFAULT '0',
  `h06` int(11) DEFAULT '0',
  `h07` int(11) DEFAULT '0',
  `h08` int(11) DEFAULT '0',
  `h09` int(11) DEFAULT '0',
  `h10` int(11) DEFAULT '0',
  `h11` int(11) DEFAULT '0',
  `h12` int(11) DEFAULT '0',
  `h13` int(11) DEFAULT '0',
  `h14` int(11) DEFAULT '0',
  `h15` int(11) DEFAULT '0',
  `h16` int(11) DEFAULT '0',
  `h17` int(11) DEFAULT '0',
  `h18` int(11) DEFAULT '0',
  `h19` int(11) DEFAULT '0',
  `h20` int(11) DEFAULT '0',
  `h21` int(11) DEFAULT '0',
  `h22` int(11) DEFAULT '0',
  `h23` int(11) DEFAULT '0',
  `grand_total` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`key_id`)
) ENGINE=MyISAM;

### Permanant table
CREATE TABLE `tb_permanant_data` (
  `key_id` varchar(20) NOT NULL DEFAULT '',
  `h00` int(11) DEFAULT '0',
  `h01` int(11) DEFAULT '0',
  `h02` int(11) DEFAULT '0',
  `h03` int(11) DEFAULT '0',
  `h04` int(11) DEFAULT '0',
  `h05` int(11) DEFAULT '0',
  `h06` int(11) DEFAULT '0',
  `h07` int(11) DEFAULT '0',
  `h08` int(11) DEFAULT '0',
  `h09` int(11) DEFAULT '0',
  `h10` int(11) DEFAULT '0',
  `h11` int(11) DEFAULT '0',
  `h12` int(11) DEFAULT '0',
  `h13` int(11) DEFAULT '0',
  `h14` int(11) DEFAULT '0',
  `h15` int(11) DEFAULT '0',
  `h16` int(11) DEFAULT '0',
  `h17` int(11) DEFAULT '0',
  `h18` int(11) DEFAULT '0',
  `h19` int(11) DEFAULT '0',
  `h20` int(11) DEFAULT '0',
  `h21` int(11) DEFAULT '0',
  `h22` int(11) DEFAULT '0',
  `h23` int(11) DEFAULT '0',
  `grand_total` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`key_id`)
) ENGINE=MyISAM;

INSERT INTO tb_permanant_data
       SELECT * FROM  tb_temp_data ;
       ON DUPLICATE KEY UPDATE h00 = ?

I want to make sure all h00 until h23 will be updated by adding the value into tb_permanant_data but i have no idea on how to do that...

Can anyone help?

Thanks

Body:
INSERT INTO tb_permanant_data SELECT * FROM tb_temp_data
ON DUPLICATE KEY UPDATE
  h00 = VALUES(h00),
  h01 = VALUES(h01),
  h02 = VALUES(h02),
  h03 = VALUES(h03),
  h04 = VALUES(h04),
  h05 = VALUES(h05),
  h06 = VALUES(h06),
  h07 = VALUES(h07),
  h08 = VALUES(h08),
  h09 = VALUES(h09),
  h10 = VALUES(h10),
  h11 = VALUES(h11),
  h12 = VALUES(h12),
  h13 = VALUES(h13),
  h14 = VALUES(h14),
  h15 = VALUES(h15),
  h16 = VALUES(h16),
  h17 = VALUES(h17),
  h18 = VALUES(h18),
  h19 = VALUES(h19),
  h20 = VALUES(h20),
  h21 = VALUES(h21),
  h22 = VALUES(h22),
  h23 = VALUES(h23);

Note, table tb_permanant_data can contain rows which doesn't exist in tb_temp_data (by id).