问:
Smarty template not updated/refreshed in PHP loop
I use smarty to send a daily report to several email, fetching data from a mysql DB
Steps:
1- get first email from DB where to send report with other parameters
2- get data from DB based on specific email and parameters
3- push data to smarty template
4- send template via email
5- loop ( to 2d email, etc)

All works good for initial email. But for the second email, it just keeps the initial email data without refreshing the data. I have used $smarty->clearAllCache(); but for some reason i cannot get the template to be reinitialized after each email loop.

```<code><?php
require_once('../vendor/autoload.php');
require_once '../script/PDOModel.php';
require ('smarty/Smarty.class.php');
$credentials = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('api-key', '');
 $apiInstance = new SendinBlue\Client\Api\TransactionalEmailsApi(new GuzzleHttp\Client(),$credentials);
$pdomodel = new PDOModel();

date_default_timezone_set('Europe/Riga');
$pdomodel->connect("xxx", "xxx", "xxx", "xxx");

// iterate through emails

$sql="select * from email_report";
$iterate=$pdomodel->executeQuery($sql);
foreach ($iterate as $myrow) {

 $data3 = [];

 $smarty = new Smarty();
 $smarty->clearAllCache();

....

// first dep daily
$sql="SELECT COUNT(USERID) AS FD FROM (
SELECT USERID,MIN(SUMMARY_DATE) FROM DataFeedConsCore WHERE BRAND_ID=$brandid  and TRAN_TYPE='DEPOSIT' and $agent GROUP BY USERID HAVING MIN(SUMMARY_DATE) ='$thedate') total";
echo $sql.'<br>';
$records=$pdomodel->executeQuery($sql);
foreach ($records as $row) {
$DAILY_FD=$row['FD'];
}

...

$sql="SELECT ...";
echo $sql.'<br><br><br>';

            $FDresults = $pdomodel->executeQuery($sql);
                        foreach($FDresults as $row)
                        {
                        $data3[]=$row;
                        }

...
$smarty->assign('DAILY_FD', $DAILY_FD);

$smarty->assign('fdmonth', $data3);

$output = $smarty->fetch('daily_report.tpl');

// send email
$sendSmtpEmail = new \SendinBlue\Client\Model\SendSmtpEmail([
   'subject' => 'Report : '.$thedate,
   'sender' => ['name' => 'xxx', 'email' => 'xxx'],
   'to' => [

          ['name' => 'xx', 'email' => 'xxx@xxx.com']
     ],
   'htmlContent' => $output
]);

try {
  $result = $apiInstance->sendTransacEmail($sendSmtpEmail);
  print_r($result);
} catch (Exception $e) {
  echo $e->getMessage(),PHP_EOL;
}

}
</code>```

Body:
I use smarty to send a daily report to several email, fetching data from a mysql DB
Steps:
1- get first email from DB where to send report with other parameters
2- get data from DB based on specific email and parameters
3- push data to smarty template
4- send template via email
5- loop ( to 2d email, etc)

All works good for initial email. But for the second email, it just keeps the initial email data without refreshing the data. I have used $smarty->clearAllCache(); but for some reason i cannot get the template to be reinitialized after each email loop.

<?php
require_once('../vendor/autoload.php');
require_once '../script/PDOModel.php';
require ('smarty/Smarty.class.php');
$credentials = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('api-key', '');
 $apiInstance = new SendinBlue\Client\Api\TransactionalEmailsApi(new GuzzleHttp\Client(),$credentials);
$pdomodel = new PDOModel();

date_default_timezone_set('Europe/Riga');
$pdomodel->connect("xxx", "xxx", "xxx", "xxx");

// iterate through emails

$sql="select * from email_report";
$iterate=$pdomodel->executeQuery($sql);
foreach ($iterate as $myrow) {

 $data3 = [];

 $smarty = new Smarty();
 $smarty->clearAllCache();

....

// first dep daily
$sql="SELECT COUNT(USERID) AS FD FROM (
SELECT USERID,MIN(SUMMARY_DATE) FROM DataFeedConsCore WHERE BRAND_ID=$brandid  and TRAN_TYPE='DEPOSIT' and $agent GROUP BY USERID HAVING MIN(SUMMARY_DATE) ='$thedate') total";
echo $sql.'
';
$records=$pdomodel->executeQuery($sql);
foreach ($records as $row) {
$DAILY_FD=$row['FD'];
}

...

$sql="SELECT ...";
echo $sql.'

';

            $FDresults = $pdomodel->executeQuery($sql);
                        foreach($FDresults as $row)
                        {
                        $data3[]=$row;
                        }

...
$smarty->assign('DAILY_FD', $DAILY_FD);

$smarty->assign('fdmonth', $data3);

$output = $smarty->fetch('daily_report.tpl');

// send email
$sendSmtpEmail = new \SendinBlue\Client\Model\SendSmtpEmail([
   'subject' => 'Report : '.$thedate,
   'sender' => ['name' => 'xxx', 'email' => 'xxx'],
   'to' => [

          ['name' => 'xx', 'email' => 'xxx@xxx.com']
     ],
   'htmlContent' => $output
]);

try {
  $result = $apiInstance->sendTransacEmail($sendSmtpEmail);
  print_r($result);
} catch (Exception $e) {
  echo $e->getMessage(),PHP_EOL;
}

}


来源: stackexchange

问:
Apache rewrite for wildcard domains issue
I have a php app on Apache2 that is supposed to treat subdomains on the code level.
My goal is to redirect any wildcard subdomain to the main domain's index.php.
I do not use .htaccess.
I searched Stackoverflow also googled and for the solution, and could not find one.
The virtual host looks like this:

```<code><VirtualHost *:80>
      ServerAdmin admin@website.com
      ServerName website.com
      ServerAlias *.website.com
      DocumentRoot /var/www/html/site_admin/public_html
      # Directory path where code exists
        <Directory /var/www/html/site_admin/public_html>
                Options Indexes FollowSymLinks
                AllowOverride All
                Order allow,deny
                allow from all
        </Directory>
        ErrorLog ${APACHE_LOG_DIR}/website.com-error.log
        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel error
        CustomLog ${APACHE_LOG_DIR}/website.com.log combined
        RewriteEngine On
        #If the domain (any domain) is not exactly website.com...
        RewriteCond %{HTTP_HOST} !^website\.com$ [NC]
        RewriteRule (.*) http://(.*).website.com [L,R=301,QSA]
        RewriteRule ^.*$ /index.php [NC,L]
</VirtualHost>
</code>```

When I access the main domain, I can see the website content. However, if I access sub.website.com, I get redirected to %28.%2A%29.website.com

Please advice

Thanks ahead

Igal

ContentLicense: CC BY-SA 4.0

Body:
I have a php app on Apache2 that is supposed to treat subdomains on the code level.
My goal is to redirect any wildcard subdomain to the main domain's index.php.
I do not use .htaccess.
I searched Stackoverflow also googled and for the solution, and could not find one.
The virtual host looks like this:

<VirtualHost *:80>
      ServerAdmin admin@website.com
      ServerName website.com
      ServerAlias *.website.com
      DocumentRoot /var/www/html/site_admin/public_html
      # Directory path where code exists
        <Directory /var/www/html/site_admin/public_html>
                Options Indexes FollowSymLinks
                AllowOverride All
                Order allow,deny
                allow from all
        </Directory>
        ErrorLog ${APACHE_LOG_DIR}/website.com-error.log
        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel error
        CustomLog ${APACHE_LOG_DIR}/website.com.log combined
        RewriteEngine On
        #If the domain (any domain) is not exactly website.com...
        RewriteCond %{HTTP_HOST} !^website\.com$ [NC]
        RewriteRule (.*) http://(.*).website.com [L,R=301,QSA]
        RewriteRule ^.*$ /index.php [NC,L]
</VirtualHost>

When I access the main domain, I can see the website content. However, if I access sub.website.com, I get redirected to %28.%2A%29.website.com

Please advice

Thanks ahead

Igal


问:
How to realloc a struct in a function
I want to add a new word, read from keyboard, to my dictionary with a function made by me, increasing his priority.

here is my try. When i run this code, i get this message : Process finished with exit code -1073741819 (0xC0000005)

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct dictionary_entry{
    char *word;
    int priority;
};
void adauga_cuvant(struct dictionary_entry **dictionar, int Lungime, char cuvant[21]){

    *dictionar = realloc( *dictionar, (Lungime)*sizeof(struct dictionary_entry));
    dictionar[(Lungime)]->word =(char *) malloc(strlen(cuvant)*sizeof(char *));
    strcpy(dictionar[(Lungime)]->word, cuvant);
    dictionar[(Lungime)]->priority = 1;
}
int main() {
    int N, M, i;
    char aux[21];
    struct dictionary_entry *dictionary;
    scanf("%d", &N);
    dictionary = (struct dictionary_entry *)malloc(N * sizeof(struct dictionary_entry));
    for(i = 0; i < N; i++) {
        scanf("%s", aux);
        dictionary[i].word = (char *)malloc( strlen(aux) * sizeof(char));
        strcpy(dictionary[i].word, aux);
        dictionary[i].priority = 0;
    }
    scanf("%s", aux);
    N++;
    adauga_cuvant(&dictionary, N, aux);
    for(i = 0; i < N; i++) {
        printf("%s %d\n", dictionary[i].word, dictionary[i].priority);
    }
    return 0;
}

</code>```

Title: How to realloc a struct in a function

Body:
I want to add a new word, read from keyboard, to my dictionary with a function made by me, increasing his priority.

here is my try. When i run this code, i get this message : Process finished with exit code -1073741819 (0xC0000005)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct dictionary_entry{
    char *word;
    int priority;
};
void adauga_cuvant(struct dictionary_entry **dictionar, int Lungime, char cuvant[21]){

    *dictionar = realloc( *dictionar, (Lungime)*sizeof(struct dictionary_entry));
    dictionar[(Lungime)]->word =(char *) malloc(strlen(cuvant)*sizeof(char *));
    strcpy(dictionar[(Lungime)]->word, cuvant);
    dictionar[(Lungime)]->priority = 1;
}
int main() {
    int N, M, i;
    char aux[21];
    struct dictionary_entry *dictionary;
    scanf("%d", &N);
    dictionary = (struct dictionary_entry *)malloc(N * sizeof(struct dictionary_entry));
    for(i = 0; i < N; i++) {
        scanf("%s", aux);
        dictionary[i].word = (char *)malloc( strlen(aux) * sizeof(char));
        strcpy(dictionary[i].word, aux);
        dictionary[i].priority = 0;
    }
    scanf("%s", aux);
    N++;
    adauga_cuvant(&dictionary, N, aux);
    for(i = 0; i < N; i++) {
        printf("%s %d\n", dictionary[i].word, dictionary[i].priority);
    }
    return 0;
}


问:
Parse XSLT file with input parameter
Suppose I have to parse an XSLT file.
I am using import lxml.etree as et library from python.

xslt = et.parse('XSLT.xslt')

The XSLT file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="xsl:template">
    <xsl:copy>
      <xsl:apply-templates select="*|@*"/>
      <xsl:copy-of select="document('a15.xslt')/*/*[3]/*"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>
</code>```

Do you know how to make the a15.xslt dynamic by adding it from the input?
For example

xslt = et.parse('XSLT.xslt', a15)

```<code><xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="xsl:template">
     <xsl:copy>
        <xsl:apply-templates select="*|@*"/>
        <xsl:copy-of select="document('$var.xslt')/*/*[3]/*"/>
     </xsl:copy>
    </xsl:template>
</xsl:stylesheet>
</code>```

I cannot find a proper example with this. Any ideas?

Title: Parse XSLT file with input parameter

Body:
Suppose I have to parse an XSLT file.
I am using import lxml.etree as et library from python.

xslt = et.parse('XSLT.xslt')

The XSLT file:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="xsl:template">
    <xsl:copy>
      <xsl:apply-templates select="*|@*"/>
      <xsl:copy-of select="document('a15.xslt')/*/*[3]/*"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

Do you know how to make the a15.xslt dynamic by adding it from the input?
For example

xslt = et.parse('XSLT.xslt', a15)

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="xsl:template">
     <xsl:copy>
        <xsl:apply-templates select="*|@*"/>
        <xsl:copy-of select="document('$var.xslt')/*/*[3]/*"/>
     </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

I cannot find a proper example with this. Any ideas?


问:
SSIS connection to BigQuery using ODBC - how to store/retrieve .json in a Vault?
We are connecting from On-premises SQL Server to GCP BigQuery using Magnitude Simba ODBC Driver.

We would like to use HashiCorp Vault in order to store the .json file with credentials of the service account, but I don't know if it is possible.

I'd like the configure the ODBC driver to retrieve the .json from the Vault, rather than hard-coding the key file path in the ODBC configuration.

Does anyone one how to do it? I couldn't find in the documentation :'-(

Thanks a lot in advance

Looked up in the Magnitude Simba documentation

as well as searched on the web.


问:
styling card using ngx-bootstrap 9 , bootstrap 5 and Angular material 14
how to make Twelve demo card as a grid layout
three row and four columns.

i tried to use row and columns class but it never change grid layout ,but it change the card size.

how can i do it and how can i do it without changing the card size.


问:
ef core linq to entities with multi-level where clauses
I'm working on an api endpoint that takes optional search parameters. This is sort of complicated because of the table structure. I'm trying to figure out the best and most efficient approach to filtering the data. Bear with me, the data structure is much more complex but I'm simplifying the entity objects (see below). Because I can only do this in linq to sql/entities and not a stored procedure (client rules). The challenge is applying the filters on certain levels of the entity data, not just the top level. For example if I wanted to filter on Stream Id, where does the where clause go? Again, I've just never had a scenario like this, while using linq to entities and so I'm very curious on the best approaches, if any. Would I make 3 separate predicate builders to achieve this? Looking forward to feedback!

EDIT
To be clear I was thinking along the lines of having a different predicate per filter like below and then inserting the predicate in it's corresponding Where clause.

```<code>var p = PredicateBuilder.New<Library>();
if (request.LibraryId > 0)
    p = p.And(x => x.LibraryId == request.LibraryId);
if (!string.IsNullOrEmpty(request.LibraryName))
    p = p.And(x => x.LibraryName!.Contains(request.LibraryName));
</code>```

Then using .Where(p) but never tried it this way in multiple places.

Sample query

```<code>var libraries = DBContext.Library!.DefaultIfEmpty()!
    .Include(x => x.Version)!
    .ThenInclude(v => v.Emission)!
    .ThenInclude(e => e.StreamEmission)!
    .ThenInclude(se => se!.Stream)!
    //.WHERE(predicate1)**
    //filter on library Id, Library Name
    .Select(lm => new LibraryViewModel
    {
        LibraryId = lm.LibraryId,
        LibraryName = lm.LibraryName,
        Versions = lm.Versions!
        //.WHERE(predicate2)
        //filter on Version Id, Version Name, Create Date
        .Select(vm => new VersionViewModel
        {
            VersionId = vm.VersionId,
            VersionName = vm.VersionName,
            CreateDate = vm.CreateDate,
            Streams = vm.Emission!
            .Select(vdse => vdse.StreamEmission)
            .Select(ds => ds!Stream)
            //.WHERE(predicate3)
            //filter on Stream Id or Stream Name
            .GroupBy(dse => new { dse!.StreamId, dse.StreamName })
            .Select(sm => new StreamViewModel
            {
                StreamId = sm!.Key.StreamId,
                StreamName = sm.Key.StreamName,
            }).ToList()
        }).ToList()
    });
</code>```

Sample json response

```<code>[{
  "LibraryId" : 24,
  "LibraryName" : "Library 24",
  "Versions" : [
  {
      "VersionId" : 30,
      "VersionName : "Version 30",
      "CreateDate" : "12/1/2019",
      "Streams" : [
          {
              "StreamId" : 1,
              "StreamName" : "Stream Name 1"
          },
          {
              "StreamId" : 2,
              "StreamName" : "Stream Name 2"
          }]
  }]
}],
</code>```

Entity Objects

```<code>public class Library
{
 public int LibraryId {get;set;}
 public string LibraryName {get;set;}
 //navigation property
 public ICollection<Version> Versions {get;set;}
}

public class Version
{
 public int VersionId {get;set;}
 public string VersionName {get;set;}
 public DataTime CreateDate {get;set;}
 //navigation property
 public ICollection<Emission> Emissions {get;set;}
 //navigation property
 public Library? Library {get;set;}
}

//join table/class between Version and StreamEmission tables
public class Emission
{
 public int EmissionId {get;set;}
 public string Name {get;set;}
 //emission foreign key
 public StreamEmissionId {get;set;}
 //navigation property
 public StreamEmission StreamEmission {get;set;}
 public int VersionId {get;set;}
 //navigation property
 public Version? Version {get;set;}
}

//join table between Stream and Emission tables
public class StreamEmission
{
 public int StreamEmissionId {get;set;}
 public int StreamId {get;set;}
 //navigation property
 public Stream Stream {get;set;}
}

public class Stream
{
 public int StreamId {get;set;}
 public string StreamName {get;set;}
 //navigation property
 public ICollection<StreamEmission> StreamEmissions {get;set;}
}
</code>```

Body:
I'm working on an api endpoint that takes optional search parameters. This is sort of complicated because of the table structure. I'm trying to figure out the best and most efficient approach to filtering the data. Bear with me, the data structure is much more complex but I'm simplifying the entity objects (see below). Because I can only do this in linq to sql/entities and not a stored procedure (client rules). The challenge is applying the filters on certain levels of the entity data, not just the top level. For example if I wanted to filter on Stream Id, where does the where clause go? Again, I've just never had a scenario like this, while using linq to entities and so I'm very curious on the best approaches, if any. Would I make 3 separate predicate builders to achieve this? Looking forward to feedback!

EDIT
To be clear I was thinking along the lines of having a different predicate per filter like below and then inserting the predicate in it's corresponding Where clause.

var p = PredicateBuilder.New<Library>();
if (request.LibraryId > 0)
    p = p.And(x => x.LibraryId == request.LibraryId);
if (!string.IsNullOrEmpty(request.LibraryName))
    p = p.And(x => x.LibraryName!.Contains(request.LibraryName));

Then using .Where(p) but never tried it this way in multiple places.

Sample query

var libraries = DBContext.Library!.DefaultIfEmpty()!
    .Include(x => x.Version)!
    .ThenInclude(v => v.Emission)!
    .ThenInclude(e => e.StreamEmission)!
    .ThenInclude(se => se!.Stream)!
    //.WHERE(predicate1)**
    //filter on library Id, Library Name
    .Select(lm => new LibraryViewModel
    {
        LibraryId = lm.LibraryId,
        LibraryName = lm.LibraryName,
        Versions = lm.Versions!
        //.WHERE(predicate2)
        //filter on Version Id, Version Name, Create Date
        .Select(vm => new VersionViewModel
        {
            VersionId = vm.VersionId,
            VersionName = vm.VersionName,
            CreateDate = vm.CreateDate,
            Streams = vm.Emission!
            .Select(vdse => vdse.StreamEmission)
            .Select(ds => ds!Stream)
            //.WHERE(predicate3)
            //filter on Stream Id or Stream Name
            .GroupBy(dse => new { dse!.StreamId, dse.StreamName })
            .Select(sm => new StreamViewModel
            {
                StreamId = sm!.Key.StreamId,
                StreamName = sm.Key.StreamName,
            }).ToList()
        }).ToList()
    });

Sample json response

[{
  "LibraryId" : 24,
  "LibraryName" : "Library 24",
  "Versions" : [
  {
      "VersionId" : 30,
      "VersionName : "Version 30",
      "CreateDate" : "12/1/2019",
      "Streams" : [
          {
              "StreamId" : 1,
              "StreamName" : "Stream Name 1"
          },
          {
              "StreamId" : 2,
              "StreamName" : "Stream Name 2"
          }]
  }]
}],

Entity Objects

public class Library
{
 public int LibraryId {get;set;}
 public string LibraryName {get;set;}
 //navigation property
 public ICollection<Version> Versions {get;set;}
}

public class Version
{
 public int VersionId {get;set;}
 public string VersionName {get;set;}
 public DataTime CreateDate {get;set;}
 //navigation property
 public ICollection<Emission> Emissions {get;set;}
 //navigation property
 public Library? Library {get;set;}
}

//join table/class between Version and StreamEmission tables
public class Emission
{
 public int EmissionId {get;set;}
 public string Name {get;set;}
 //emission foreign key
 public StreamEmissionId {get;set;}
 //navigation property
 public StreamEmission StreamEmission {get;set;}
 public int VersionId {get;set;}
 //navigation property
 public Version? Version {get;set;}
}

//join table between Stream and Emission tables
public class StreamEmission
{
 public int StreamEmissionId {get;set;}
 public int StreamId {get;set;}
 //navigation property
 public Stream Stream {get;set;}
}

public class Stream
{
 public int StreamId {get;set;}
 public string StreamName {get;set;}
 //navigation property
 public ICollection<StreamEmission> StreamEmissions {get;set;}
}


问:
Extracting all data from JIRA REST API
I have a JIRA API that pulls latest board information into a google sheet using app script. I have reduced the script to just pull through a single 'Label' field into my sheet.

This label field can have one or many labels attached in Jira. The problem I face as of now is that I get the first label that is attached to that Jira ticket. But in cases where there more than one label attached, this does not pull through.

I can see the multiple labels pull through in the logs, but cant work out how to pull this into the sheet.

example of the output from Logger.log(Response);

{"expand":"schema,names","startAt":0,"maxResults":1000,"total":8,"issues":[{"expand":"operations,versionedRepresentations,editmeta,changelog,renderedFields","id":"123456","self":"URL Removed","key":"Board-1674","fields":{"labels":["Mobile"]}},{"expand":"operations,versionedRepresentations,editmeta,changelog,renderedFields","id":"123457","self":"URL Removed","key":"Board-1608","fields":{"labels":["T&M","Merchandising_Support"]}}]}

In the scenario above I would get the label for Mobile as expected for the first result for Board-1674, but only T&M for the second ticket for Board-1608, not Merchandising_Support.

Any help would be really appreciated.

```<code>{
 var currentJMLE = SpreadsheetApp.getActiveSpreadsheet();
 var ss = currentJMLE.getSheetByName('Tester');
 var range = ss.getRange(2, 1, ss.getLastRow(), ss.getLastColumn());
 range.clear();
 SpreadsheetApp.flush();

 var encCreds = authenticateRequests();
 var url = "xxxxxxx";
 var filter = { "jql":"project = Board AND status in ( 'To Be Reviewed', 'Agree To Proceed')", "fields":['labels'], "maxResults":1000} ;

 var options = {
   method:             "post",
   contentType:        "application/json",
   headers:            {"Authorization": "Basic " + encCreds},
   payload:            JSON.stringify(filter),
   muteHttpExceptions: true
 };

 var response = UrlFetchApp.fetch(url, options);
 Logger.log(response);
var sourceData = JSON.parse(response);

 var arrayForSpreadsheet=[]
 sourceData.issues.forEach(function(ticket){

arrayForSpreadsheet.push([
,getValue(ticket.fields,"labels")

   ])
 })
 var rows=arrayForSpreadsheet.length
 var columns=arrayForSpreadsheet[0].length
 var range = ss.getRange(2, 1, rows, columns);
 range.setValues(arrayForSpreadsheet);
}

function getValue(ticket,properties) {
 var props=properties.split(".")
 if (props.length<1 || props.length>2) {
   throw "invalid number of properties"
 }
 if (ticket[props[0]]==null) {
   return null
 } else {
   if (props.length==1) {
     return ticket[props[0]]
   } else {
     if (ticket[props[0]][props[1]]==null) {
       return null
     } else {
       return ticket[props[0]][props[1]]
     }
   }
 }
}```

```

Title: Extracting all data from JIRA REST API

Body:
I have a JIRA API that pulls latest board information into a google sheet using app script. I have reduced the script to just pull through a single 'Label' field into my sheet.

This label field can have one or many labels attached in Jira. The problem I face as of now is that I get the first label that is attached to that Jira ticket. But in cases where there more than one label attached, this does not pull through.

I can see the multiple labels pull through in the logs, but cant work out how to pull this into the sheet.

example of the output from Logger.log(Response);

{"expand":"schema,names","startAt":0,"maxResults":1000,"total":8,"issues":[{"expand":"operations,versionedRepresentations,editmeta,changelog,renderedFields","id":"123456","self":"URL Removed","key":"Board-1674","fields":{"labels":["Mobile"]}},{"expand":"operations,versionedRepresentations,editmeta,changelog,renderedFields","id":"123457","self":"URL Removed","key":"Board-1608","fields":{"labels":["T&M","Merchandising_Support"]}}]}

In the scenario above I would get the label for Mobile as expected for the first result for Board-1674, but only T&M for the second ticket for Board-1608, not Merchandising_Support.

Any help would be really appreciated.

{
 var currentJMLE = SpreadsheetApp.getActiveSpreadsheet();
 var ss = currentJMLE.getSheetByName('Tester');
 var range = ss.getRange(2, 1, ss.getLastRow(), ss.getLastColumn());
 range.clear();
 SpreadsheetApp.flush();

 var encCreds = authenticateRequests();
 var url = "xxxxxxx";
 var filter = { "jql":"project = Board AND status in ( 'To Be Reviewed', 'Agree To Proceed')", "fields":['labels'], "maxResults":1000} ;

 var options = {
   method:             "post",
   contentType:        "application/json",
   headers:            {"Authorization": "Basic " + encCreds},
   payload:            JSON.stringify(filter),
   muteHttpExceptions: true
 };

 var response = UrlFetchApp.fetch(url, options);
 Logger.log(response);
var sourceData = JSON.parse(response);

 var arrayForSpreadsheet=[]
 sourceData.issues.forEach(function(ticket){

arrayForSpreadsheet.push([
,getValue(ticket.fields,"labels")

   ])
 })
 var rows=arrayForSpreadsheet.length
 var columns=arrayForSpreadsheet[0].length
 var range = ss.getRange(2, 1, rows, columns);
 range.setValues(arrayForSpreadsheet);
}

function getValue(ticket,properties) {
 var props=properties.split(".")
 if (props.length<1 || props.length>2) {
   throw "invalid number of properties"
 }
 if (ticket[props[0]]==null) {
   return null
 } else {
   if (props.length==1) {
     return ticket[props[0]]
   } else {
     if (ticket[props[0]][props[1]]==null) {
       return null
     } else {
       return ticket[props[0]][props[1]]
     }
   }
 }
}```


问:
Properly scale map for multiple screen sizes on python's folium
I'm publishing a map here, that captures the mouse click position and sends it to an API where it is used to plot a meteogram (only works for Longitudes between 60W and 80 E, feel free to use it if you find it useful).

I've published it on pythonanywhere and it runs with flask as an app. The map and buttons are created using the folium library.

Everything works fine except on mobile screen where I can't find a way to properly scale the map and its elements (+ and - zoom buttons for example) when viewing on portrait mode. It works fine on landscape, but I would like it to be better on portrait mode also.

My code below

```<code>import folium,branca
from flask import Flask
from folium.plugins import LocateControl

app = Flask(__name__)
app.config["Debug"] = True
@app.route('/')

def index():
    start_coords = (38, -8)
    fig=branca.element.Figure(height="100%",width="100%")

    m=folium.Map(location=start_coords, zoom_start=4,max_bounds=True)

    e=folium.LatLngPopup()
    m.add_child(e)

    LocateControl(strings={'drawMarker':'false'}).add_to(m)

    fig.add_child(m)

    return m._repr_html_()
</code>```

I've tried to add the following line after creating the map object:

```<code>m.get_root().header.add_child(folium.Element('<meta name="viewport" content="width=device-width,'
'initial-scale=1.0, user-scalable=no" />'))
</code>```

like in the example here. But I don't see anything happening.

I'm not sure if its because folium creates everything inside an iframe, or I'm just simply not adding the right code.

Any help would be greatly appreciated

Thanks!

Body:
I'm publishing a map here, that captures the mouse click position and sends it to an API where it is used to plot a meteogram (only works for Longitudes between 60W and 80 E, feel free to use it if you find it useful).

I've published it on pythonanywhere and it runs with flask as an app. The map and buttons are created using the folium library.

Everything works fine except on mobile screen where I can't find a way to properly scale the map and its elements (+ and - zoom buttons for example) when viewing on portrait mode. It works fine on landscape, but I would like it to be better on portrait mode also.

My code below

import folium,branca
from flask import Flask
from folium.plugins import LocateControl

app = Flask(__name__)
app.config["Debug"] = True
@app.route('/')

def index():
    start_coords = (38, -8)
    fig=branca.element.Figure(height="100%",width="100%")

    m=folium.Map(location=start_coords, zoom_start=4,max_bounds=True)

    e=folium.LatLngPopup()
    m.add_child(e)

    LocateControl(strings={'drawMarker':'false'}).add_to(m)

    fig.add_child(m)

    return m._repr_html_()

I've tried to add the following line after creating the map object:

m.get_root().header.add_child(folium.Element('<meta name="viewport" content="width=device-width,'
'initial-scale=1.0, user-scalable=no" />'))

like in the example here. But I don't see anything happening.

I'm not sure if its because folium creates everything inside an iframe, or I'm just simply not adding the right code.

Any help would be greatly appreciated

Thanks!


问:
Iterate through matrix columns and print elements that appear n times in specific row and column
The program loads matrix with number of rows that user has input. For example, matrix look like this:

```<code>0 0
0 0
2 0
2 1
2 1
2 1
2 0
2 0
2 1
</code>```

If in column are five or more same elements (1 or 2) in row, i want to extract sequence of first five appearances of that element in row and to print its coordinates from original matrix. First number represent row and second column. It should look like this:

```<code>2 0
3 0
4 0
5 0
6 0

matrix=[[0,0],[0,0],[2,0],[2,1],[2,1],[2,1],[2,0],[2,0],[2,1]]

columns=list(zip(*matrix))
</code>```

I had idea to iterate trough columns and to use the function that counts how many times element appears, but I don't know how to print this coordinates. Is there any way to to that?

```<code>
def count_occurence(desired):
    count = 0
    last_item = None
    for item in lis:
        if item == desired:
            if last_item == desired:
                continue
            count += 1
        last_item = item
    return count

</code>```

Body:
The program loads matrix with number of rows that user has input. For example, matrix look like this:

0 0
0 0
2 0
2 1
2 1
2 1
2 0
2 0
2 1

If in column are five or more same elements (1 or 2) in row, i want to extract sequence of first five appearances of that element in row and to print its coordinates from original matrix. First number represent row and second column. It should look like this:

2 0
3 0
4 0
5 0
6 0

matrix=[[0,0],[0,0],[2,0],[2,1],[2,1],[2,1],[2,0],[2,0],[2,1]]

columns=list(zip(*matrix))

I had idea to iterate trough columns and to use the function that counts how many times element appears, but I don't know how to print this coordinates. Is there any way to to that?

def count_occurence(desired):
    count = 0
    last_item = None
    for item in lis:
        if item == desired:
            if last_item == desired:
                continue
            count += 1
        last_item = item
    return count


问:
Gremlin-python - how to automate graph creation
I'm trying to create on EC2 with Amazon Linux 2 a python script to create a graph on neptune AWS.

```<code>from __future__  import print_function

from gremlin_python import statics
from gremlin_python.structure.graph import Graph
from gremlin_python.process.graph_traversal import __
from gremlin_python.process.strategies import *
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection

import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import networkx as nx

graph = Graph()

remoteConn = DriverRemoteConnection('wss://myendpoint:8182/gremlin','g')
g = graph.traversal().withRemote(remoteConn)

def list_all(self, limit=500):
    g.V().limit(limit).elementMap().toList()

def find_vertex(self, vid):
    g.V(vid).elementMap().next()

def list_by_label_name(self, vlabel, name):
    g.V().has(vlabel, 'name', name).elementMap().toList()

vertices = g.V().groupCount().toList()
edges  = g.E().groupCount().toList()

print(vertices)
print(edges)

# Find up to 15 routes from LHR to SJC that make one stop.
paths = g.V() \
             .out().out().has('table').limit(15) \
             .path().by('table').toList()

# Create a new empty DiGraph
G=nx.DiGraph()

# Add the routes we found to DiGraph we just created
for p in paths:
    G.add_edge(p[0],p[1])
    G.add_edge(p[1],p[2])

# Give the starting and ending airports a different color
colors = []

for label in G:
    if label in['table']:
        colors.append('yellow')
    else:
        colors.append('#11cc77')

# Now draw the graph
plt.figure(figsize=(5,5))
nx.draw(G, node_color=colors, node_size=1200, with_labels=True)
plt.show()

remoteConn.close()

</code>```

no issue to connect to neptune but with import matplotlib.pyplot as plt I have an issue when I run the script

```<code>Traceback (most recent call last):
  File "gremlinexample.py", line 13, in <module>
    import matplotlib.pyplot as plt
  File "/home/ec2-user/.local/lib/python2.7/site-packages/matplotlib/pyplot.py", line 115, in <module>
    _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
  File "/home/ec2-user/.local/lib/python2.7/site-packages/matplotlib/backends/__init__.py", line 63, in pylab_setup
    [backend_name], 0)
  File "/home/ec2-user/.local/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py", line 4, in <module>
    from . import tkagg  # Paint image to Tk photo blitter extension.
  File "/home/ec2-user/.local/lib/python2.7/site-packages/matplotlib/backends/tkagg.py", line 5, in <module>
    from six.moves import tkinter as Tk
  File "/usr/lib/python2.7/site-packages/six.py", line 203, in load_module
    mod = mod._resolve()
  File "/usr/lib/python2.7/site-packages/six.py", line 115, in _resolve
    return _import_module(self.mod)
  File "/usr/lib/python2.7/site-packages/six.py", line 82, in _import_module
    __import__(name)
ImportError: No module named Tkinter
</code>```

I tried to install Tkinter with

```<code>$ pip install tk
DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support
Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: tk in ./.local/lib/python2.7/site-packages (0.1.0)
</code>```

and with

```<code>$ pip3 install tk
Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: tk in ./.local/lib/python3.7/site-packages (0.1.0)
</code>```

but I have always the same problem

My goals is to draw a neptune graph with a python script. I don't want to use a neptune notebook because I want to build my graph for a web app that calls a python script

Body:
I'm trying to create on EC2 with Amazon Linux 2 a python script to create a graph on neptune AWS.

from __future__  import print_function

from gremlin_python import statics
from gremlin_python.structure.graph import Graph
from gremlin_python.process.graph_traversal import __
from gremlin_python.process.strategies import *
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection

import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import networkx as nx

graph = Graph()

remoteConn = DriverRemoteConnection('wss://myendpoint:8182/gremlin','g')
g = graph.traversal().withRemote(remoteConn)

def list_all(self, limit=500):
    g.V().limit(limit).elementMap().toList()

def find_vertex(self, vid):
    g.V(vid).elementMap().next()

def list_by_label_name(self, vlabel, name):
    g.V().has(vlabel, 'name', name).elementMap().toList()

vertices = g.V().groupCount().toList()
edges  = g.E().groupCount().toList()

print(vertices)
print(edges)

# Find up to 15 routes from LHR to SJC that make one stop.
paths = g.V() \
             .out().out().has('table').limit(15) \
             .path().by('table').toList()

# Create a new empty DiGraph
G=nx.DiGraph()

# Add the routes we found to DiGraph we just created
for p in paths:
    G.add_edge(p[0],p[1])
    G.add_edge(p[1],p[2])

# Give the starting and ending airports a different color
colors = []

for label in G:
    if label in['table']:
        colors.append('yellow')
    else:
        colors.append('#11cc77')

# Now draw the graph
plt.figure(figsize=(5,5))
nx.draw(G, node_color=colors, node_size=1200, with_labels=True)
plt.show()

remoteConn.close()

no issue to connect to neptune but with import matplotlib.pyplot as plt I have an issue when I run the script

Traceback (most recent call last):
  File "gremlinexample.py", line 13, in <module>
    import matplotlib.pyplot as plt
  File "/home/ec2-user/.local/lib/python2.7/site-packages/matplotlib/pyplot.py", line 115, in <module>
    _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
  File "/home/ec2-user/.local/lib/python2.7/site-packages/matplotlib/backends/__init__.py", line 63, in pylab_setup
    [backend_name], 0)
  File "/home/ec2-user/.local/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py", line 4, in <module>
    from . import tkagg  # Paint image to Tk photo blitter extension.
  File "/home/ec2-user/.local/lib/python2.7/site-packages/matplotlib/backends/tkagg.py", line 5, in <module>
    from six.moves import tkinter as Tk
  File "/usr/lib/python2.7/site-packages/six.py", line 203, in load_module
    mod = mod._resolve()
  File "/usr/lib/python2.7/site-packages/six.py", line 115, in _resolve
    return _import_module(self.mod)
  File "/usr/lib/python2.7/site-packages/six.py", line 82, in _import_module
    __import__(name)
ImportError: No module named Tkinter

I tried to install Tkinter with

$ pip install tk
DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support
Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: tk in ./.local/lib/python2.7/site-packages (0.1.0)

and with

$ pip3 install tk
Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: tk in ./.local/lib/python3.7/site-packages (0.1.0)

but I have always the same problem

My goals is to draw a neptune graph with a python script. I don't want to use a neptune notebook because I want to build my graph for a web app that calls a python script


问:
What's the range of RMSE? Is there a maximum value?
What is the range of RMSE during a evaluation model? I know that close to 0 is better, but tis there a maximum value for this? I can't find the answer... If I have a 52 RMSE how can I say if it's a good result?</p>


问:
Word Frequency Counter encounters error on first letter
```<code>def byFreq():
    filename = open("alice.txt", "r", encoding="utf-8-sig")
    infile = filename.read()
    words = infile.split()
    return len(words)

def count_words(file_name, output_amount):
    filename = open(file_name, "r", encoding="utf-8-sig")
    infile = filename.read()
    words = infile.lower()
    for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~':
        ch.replace(ch, "")
        counts = {}
        for w in words:
            counts[w] = counts[w].get(w, 0) + 1
            items = list(counts.items())
            items.sort()
            items.sort(key=byFreq, reverse=True)
            for i in range(output_amount):
                word, count = items[i]
                print("{0:<15}{1:>5}".format(word,count))

count_words("alice.txt", 10)
</code>```

I am trying to count the words in a text file by frequency of occurence. When I try to run the program, I get this error: counts[w] = counts[w].get(w, 0) + 1 KeyError: 't'
So, it seems that the program encounters an erorr on the very first letter, and I can't figure out why.

Body:
def byFreq():
    filename = open("alice.txt", "r", encoding="utf-8-sig")
    infile = filename.read()
    words = infile.split()
    return len(words)

def count_words(file_name, output_amount):
    filename = open(file_name, "r", encoding="utf-8-sig")
    infile = filename.read()
    words = infile.lower()
    for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~':
        ch.replace(ch, "")
        counts = {}
        for w in words:
            counts[w] = counts[w].get(w, 0) + 1
            items = list(counts.items())
            items.sort()
            items.sort(key=byFreq, reverse=True)
            for i in range(output_amount):
                word, count = items[i]
                print("{0:<15}{1:>5}".format(word,count))

count_words("alice.txt", 10)

I am trying to count the words in a text file by frequency of occurence. When I try to run the program, I get this error: counts[w] = counts[w].get(w, 0) + 1 KeyError: 't'
So, it seems that the program encounters an erorr on the very first letter, and I can't figure out why.


问:
How to integrate Hashicorp vault to a third party application which is deployed on kubernetes?
I am using Bitnami postgresql for my application which is deployed on my on-prem k8 cluster. Bitnami provides a helm chart where I can configure admin creds in values.yaml file. For example I mention the admin user and pass in the helm chart itself. What Bitnami does is it creates a k8 secret for that entry and feeds the app when needed. What i want is not to store it as a k8 secret rather fetching this on fly from vault. For example when admin user tries to login with admin's cred from ui, backend communicates to vault -> fetch the secret and response back to the application. How do I achieve this since it is a third party application and i have no control on a built image?</p>


问:
Mapboxmap won't add line layer to maps style
I am trying to display a trailing line behind the puck which is following the user/device location (this part works) but when the puck moves no line is added to the maps style

See below my main activity

```<code>public class MapActivity extends LocationComponentActivity implements PermissionsListener, OnMapReadyCallback {

    private static final String LINE_SOURCE_ID = "line-source-id";
    private MapboxMap mapboxMap;
    private MapView mapView;
    private LocationComponent locationComponent;
    PermissionsManager permissionsManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Mapbox.getInstance(this, "pk.eyJ1IjoiYWFyb25jb252ZXJ5IiwiYSI6ImNsN2l6ZHptMTB0YnYzcHBid2hrY2Q5cXUifQ.vMh6oO3R5sWWPPxklfrHRA");
        setContentView(R.layout.map_layout);
        mapView = findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState);
        mapView.getMapAsync(this);
    }

    @Override
    public void onMapReady(@NonNull final MapboxMap mapboxMap) {
        MapActivity.this.mapboxMap = mapboxMap;
        mapboxMap.setStyle(Style.OUTDOORS, new Style.OnStyleLoaded() {
            @Override
            public void onStyleLoaded(@NonNull Style style) {
                enableLocationComponent(style);

            }
        });
    }

    @SuppressWarnings( {"MissingPermission"})
    private void enableLocationComponent(@NonNull Style loadedMapStyle) {
        // Check if permissions are enabled and if not request
        if (PermissionsManager.areLocationPermissionsGranted(this)) {

            // Get an instance of the component
            LocationComponent locationComponent = mapboxMap.getLocationComponent();

            // Activate with options
            locationComponent.activateLocationComponent(
                    LocationComponentActivationOptions.builder(this, loadedMapStyle).build());

            // Enable to make component visible
            locationComponent.setLocationComponentEnabled(true);

            // Set the component's camera mode
            locationComponent.setCameraMode(CameraMode.TRACKING);

            // Set the component's render mode
            locationComponent.setRenderMode(RenderMode.COMPASS);
            locationComponent.zoomWhileTracking(15);

        } else {
            permissionsManager = new PermissionsManager(this);
            permissionsManager.requestLocationPermissions(this);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onExplanationNeeded(List<String> permissionsToExplain) {
        Toast.makeText(this, R.string.user_location_permission_explanation, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onPermissionResult(boolean granted) {
        if (granted) {
            mapboxMap.getStyle(new Style.OnStyleLoaded() {
                @Override
                public void onStyleLoaded(@NonNull Style style) {
                    enableLocationComponent(style);
                    // Permissions are granted, so we can add the GeoJSON source and line layer
                    addGeoJsonSourceAndLineLayer(mapboxMap);
                }
            });
        } else {
            Toast.makeText(this, R.string.user_location_permission_not_granted, Toast.LENGTH_LONG).show();
            finish();
        }
    }

    private void addGeoJsonSourceAndLineLayer(MapboxMap mapboxMap) {
        // Get the current location of the device
        Location currentLocation = locationComponent.getLastKnownLocation();

        // Create a list of coordinates for the polyline
        List<Point> coordinates = new ArrayList<>();
        coordinates.add(Point.fromLngLat(currentLocation.getLongitude(), currentLocation.getLatitude()));

        // Create a LineString object and set the geometry for the polyline
        LineString lineString = LineString.fromLngLats(coordinates);

        // Create a Feature object with the LineString geometry
        Feature feature = Feature.fromGeometry(lineString);

        // Create a FeatureCollection with the Feature object
        FeatureCollection featureCollection = FeatureCollection.fromFeature(feature);

        // Create a GeoJSON source from the feature collection
        GeoJsonSource source = new GeoJsonSource(LINE_SOURCE_ID, featureCollection);

        // Add the GeoJSON source to the map's style
        mapboxMap.getStyle().addSource(source);

        // Create a line layer with the GeoJSON source
        LineLayer lineLayer = new LineLayer("line-layer-id", LINE_SOURCE_ID)
                .withProperties(lineColor(Color.RED), lineWidth(5f));

        // Add the line layer to the map's style
        mapboxMap.getStyle().addLayer(lineLayer);
    }

    @Override
    @SuppressWarnings( {"MissingPermission"})
    protected void onStart() {
        super.onStart();
        mapView.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mapView.onStop();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
    }
}

</code>```

I have tried a few different methods and tried implementing it within the onMapReady and location component method but not work

I have been able to draw a static line using hard coded coordinates so I feel that the issue is something to with passing the coordinates as a line string live

Body:
I am trying to display a trailing line behind the puck which is following the user/device location (this part works) but when the puck moves no line is added to the maps style

See below my main activity

public class MapActivity extends LocationComponentActivity implements PermissionsListener, OnMapReadyCallback {

    private static final String LINE_SOURCE_ID = "line-source-id";
    private MapboxMap mapboxMap;
    private MapView mapView;
    private LocationComponent locationComponent;
    PermissionsManager permissionsManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Mapbox.getInstance(this, "pk.eyJ1IjoiYWFyb25jb252ZXJ5IiwiYSI6ImNsN2l6ZHptMTB0YnYzcHBid2hrY2Q5cXUifQ.vMh6oO3R5sWWPPxklfrHRA");
        setContentView(R.layout.map_layout);
        mapView = findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState);
        mapView.getMapAsync(this);
    }

    @Override
    public void onMapReady(@NonNull final MapboxMap mapboxMap) {
        MapActivity.this.mapboxMap = mapboxMap;
        mapboxMap.setStyle(Style.OUTDOORS, new Style.OnStyleLoaded() {
            @Override
            public void onStyleLoaded(@NonNull Style style) {
                enableLocationComponent(style);

            }
        });
    }

    @SuppressWarnings( {"MissingPermission"})
    private void enableLocationComponent(@NonNull Style loadedMapStyle) {
        // Check if permissions are enabled and if not request
        if (PermissionsManager.areLocationPermissionsGranted(this)) {

            // Get an instance of the component
            LocationComponent locationComponent = mapboxMap.getLocationComponent();

            // Activate with options
            locationComponent.activateLocationComponent(
                    LocationComponentActivationOptions.builder(this, loadedMapStyle).build());

            // Enable to make component visible
            locationComponent.setLocationComponentEnabled(true);

            // Set the component's camera mode
            locationComponent.setCameraMode(CameraMode.TRACKING);

            // Set the component's render mode
            locationComponent.setRenderMode(RenderMode.COMPASS);
            locationComponent.zoomWhileTracking(15);

        } else {
            permissionsManager = new PermissionsManager(this);
            permissionsManager.requestLocationPermissions(this);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onExplanationNeeded(List<String> permissionsToExplain) {
        Toast.makeText(this, R.string.user_location_permission_explanation, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onPermissionResult(boolean granted) {
        if (granted) {
            mapboxMap.getStyle(new Style.OnStyleLoaded() {
                @Override
                public void onStyleLoaded(@NonNull Style style) {
                    enableLocationComponent(style);
                    // Permissions are granted, so we can add the GeoJSON source and line layer
                    addGeoJsonSourceAndLineLayer(mapboxMap);
                }
            });
        } else {
            Toast.makeText(this, R.string.user_location_permission_not_granted, Toast.LENGTH_LONG).show();
            finish();
        }
    }

    private void addGeoJsonSourceAndLineLayer(MapboxMap mapboxMap) {
        // Get the current location of the device
        Location currentLocation = locationComponent.getLastKnownLocation();

        // Create a list of coordinates for the polyline
        List<Point> coordinates = new ArrayList<>();
        coordinates.add(Point.fromLngLat(currentLocation.getLongitude(), currentLocation.getLatitude()));

        // Create a LineString object and set the geometry for the polyline
        LineString lineString = LineString.fromLngLats(coordinates);

        // Create a Feature object with the LineString geometry
        Feature feature = Feature.fromGeometry(lineString);

        // Create a FeatureCollection with the Feature object
        FeatureCollection featureCollection = FeatureCollection.fromFeature(feature);

        // Create a GeoJSON source from the feature collection
        GeoJsonSource source = new GeoJsonSource(LINE_SOURCE_ID, featureCollection);

        // Add the GeoJSON source to the map's style
        mapboxMap.getStyle().addSource(source);

        // Create a line layer with the GeoJSON source
        LineLayer lineLayer = new LineLayer("line-layer-id", LINE_SOURCE_ID)
                .withProperties(lineColor(Color.RED), lineWidth(5f));

        // Add the line layer to the map's style
        mapboxMap.getStyle().addLayer(lineLayer);
    }

    @Override
    @SuppressWarnings( {"MissingPermission"})
    protected void onStart() {
        super.onStart();
        mapView.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mapView.onStop();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
    }
}

I have tried a few different methods and tried implementing it within the onMapReady and location component method but not work

I have been able to draw a static line using hard coded coordinates so I feel that the issue is something to with passing the coordinates as a line string live


问:
Flutter Embede Printing with Nego
I'm currently stuck in Flutter calling the printing package of the Nexgo-SmartPOS-SDK SDK. I've found some projects as below:

https://github.com/Matt-Murungi/nexgo_printer

However, due to my lack of experience, I am unable to assist.

Could anybody help share the concept of calling the SDK and printing?

I am extremely grateful for your assistance.

Regard, thanks.
Vandet

Title: Flutter Embede Printing with Nego


问:
Correct way to setup a webhook with PHP using the Telegram API to forward messages
I need help with setting up the webhook. The webhook is successfully registered with the telegram bot and every attempt to simulate a message via postman does not succeed because I do not have the full JSON structure of a message being sent to the webhook (ERROR 404).

I do not see a possibility to debug the script as with forwarding real messages I do not have any feedback. Except nothing happening.

This script tries to forward whatever message it (the bot) is being sent to a test group (ID: -843007471)

```<code><?php

$config = require_once 'admin/options.php';
$token = $config['api_token'];

$input = file_get_contents('php://input');
$data = json_decode($input); // seems to be working

$from_chat_id = $data->message->chat->id; // seems to be working

$target_chat_ids = $config['group_ids']; // test group

$message_id = $data->message->messageId; // seems to be working

$startTime = time();

foreach($target_chat_ids as $k => $target_chat_id) {

    if(time() - $startTime > 3) {
        $startTime=time();
        sleep(1);
    }

    $res = telegramHTTPRequest('Bot ' . $token, 'forwardMessage', ['chat_id' =>  $target_chat_id ,'from_chat_id' => $from_chat_id ,'disable_notification' => false, 'message_id' => $message_id]);

    print_r($res);
    // Postman shows:
    // [ok] =>
    // [error_code] => 404
    // [description] => Not Found
}

function makeHTTPRequest($url, $method, $datas = [], $certAddress = false)
    {
        $url = rtrim($url, '/');
        $url = $url . "/" . trim($method, '/');
        $ch = curl_init();
        if (isset($datas['proxy_url']) && (isset($datas['proxy_port']))) {
            curl_setopt($ch, CURLOPT_PROXY, $datas['proxy_url']); //your proxy url
            curl_setopt($ch, CURLOPT_PROXYPORT, $datas['proxy_port']); // your proxy port number
            unset($datas['proxy_url']);
            unset($datas['proxy_port']);
            if (isset($datas['proxy_userpwd'])) {
                curl_setopt($ch, CURLOPT_PROXYUSERPWD, $datas['proxy_userpwd']); //username:pass
                unset($datas['proxy_userpwd']);
            }
        }

        curl_setopt($ch, CURLOPT_URL, $url);
        if (isset($datas['CURLOPT_CAINFO'])) {
            curl_setopt($ch, CURLOPT_CAINFO, $datas['CURLOPT_CAINFO']);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

//         curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($datas));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $datas);
        $res = curl_exec($ch);

        if (curl_error($ch)) {
//             var_dump(curl_error($ch));
            return curl_error($ch);
        } else {

            return json_decode($res);
        }
    }

function telegramHTTPRequest($token, $method, $datas = null)
    {
        $url = "https://api.telegram.org/bot" . $token;
        return isset($datas) ? makeHTTPRequest($url, $method, $datas) : makeHTTPRequest($url, $method);

    }

?>
</code>```

To know a way to debug the script myself would also be a great help.

Body:
I need help with setting up the webhook. The webhook is successfully registered with the telegram bot and every attempt to simulate a message via postman does not succeed because I do not have the full JSON structure of a message being sent to the webhook (ERROR 404).

I do not see a possibility to debug the script as with forwarding real messages I do not have any feedback. Except nothing happening.

This script tries to forward whatever message it (the bot) is being sent to a test group (ID: -843007471)

<?php

$config = require_once 'admin/options.php';
$token = $config['api_token'];

$input = file_get_contents('php://input');
$data = json_decode($input); // seems to be working

$from_chat_id = $data->message->chat->id; // seems to be working

$target_chat_ids = $config['group_ids']; // test group

$message_id = $data->message->messageId; // seems to be working

$startTime = time();

foreach($target_chat_ids as $k => $target_chat_id) {

    if(time() - $startTime > 3) {
        $startTime=time();
        sleep(1);
    }

    $res = telegramHTTPRequest('Bot ' . $token, 'forwardMessage', ['chat_id' =>  $target_chat_id ,'from_chat_id' => $from_chat_id ,'disable_notification' => false, 'message_id' => $message_id]);

    print_r($res);
    // Postman shows:
    // [ok] =>
    // [error_code] => 404
    // [description] => Not Found
}

function makeHTTPRequest($url, $method, $datas = [], $certAddress = false)
    {
        $url = rtrim($url, '/');
        $url = $url . "/" . trim($method, '/');
        $ch = curl_init();
        if (isset($datas['proxy_url']) && (isset($datas['proxy_port']))) {
            curl_setopt($ch, CURLOPT_PROXY, $datas['proxy_url']); //your proxy url
            curl_setopt($ch, CURLOPT_PROXYPORT, $datas['proxy_port']); // your proxy port number
            unset($datas['proxy_url']);
            unset($datas['proxy_port']);
            if (isset($datas['proxy_userpwd'])) {
                curl_setopt($ch, CURLOPT_PROXYUSERPWD, $datas['proxy_userpwd']); //username:pass
                unset($datas['proxy_userpwd']);
            }
        }

        curl_setopt($ch, CURLOPT_URL, $url);
        if (isset($datas['CURLOPT_CAINFO'])) {
            curl_setopt($ch, CURLOPT_CAINFO, $datas['CURLOPT_CAINFO']);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

//         curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($datas));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $datas);
        $res = curl_exec($ch);

        if (curl_error($ch)) {
//             var_dump(curl_error($ch));
            return curl_error($ch);
        } else {

            return json_decode($res);
        }
    }

function telegramHTTPRequest($token, $method, $datas = null)
    {
        $url = "https://api.telegram.org/bot" . $token;
        return isset($datas) ? makeHTTPRequest($url, $method, $datas) : makeHTTPRequest($url, $method);

    }

?>

To know a way to debug the script myself would also be a great help.


问:
Issue with Grafana exposition with Nginx Ingress and subpath. Error: If you're seeing this Grafana has failed to load its application files
I try to expose Grafana thanks to Nginx ingress and behind a url subpath.
First I deploy the nginx ingress controller Helm chart (version ingress-nginx-4.3.0)
I installed it with helm kube-prometheus-stack chart (version kube-prometheus-stack-41.7.3).
I use this values.yaml file for the prometheus-stack chart installation:

```<code>grafana:
  testFramework:
    enabled: false
  ingress:
    enabled: true
    annotations: {
      kubernetes.io/ingress.class: nginx
    }
    hosts:
      - "mydomain"
    pathType: Prefix
    path: /grafana
  grafana.ini:
    server:
      domain: "mydomain"
      root_url: "https://mydomain/grafana"
      serve_from_sub_path: true
  admin:
    existingSecret: grafana-admin-credentials
    serviceMonitor:
      enabled: true
    podDisruptionBudget:
      minAvailable: 1
    persistence:
      enabled: true
      storageClassName: default
alertmanager:
  podDisruptionBudget:
    enabled: true
prometheus:
  podDisruptionBudget:
    enabled: true
  prometheusSpec:
    storageSpec:
      volumeClaimTemplate:
        spec:
          storageClassName: default
          accessModes: ["ReadWriteOnce"]
          resources:
            requests:
              storage: 50Gi
kubeScheduler:
  enabled: false
kubeControllerManager:
  enabled: false
</code>```

I meet an error page with some advices to load application files:

If you're seeing this Grafana has failed to load its application files

This could be caused by your reverse proxy settings.

If you host grafana under subpath make sure your grafana.ini root_url setting includes subpath. If not using a reverse proxy make sure to set serve_from_sub_path to true.

If you have a local dev build make sure you build frontend using: yarn start, yarn start:hot, or yarn build

Sometimes restarting grafana-server can help

Check if you are using a non-supported browser. For more information, refer to the list of supported browsers.

During my researches, I found this subject that seems to be the same issue but when I try to do the same configuration, it does not work: Trying to rewrite url for Grafana with Ingress

Did anyone ever meet this kind of issue and can explain me why the application can't load its application file please?
Thanks in avance for your help

Body:
I try to expose Grafana thanks to Nginx ingress and behind a url subpath.
First I deploy the nginx ingress controller Helm chart (version ingress-nginx-4.3.0)
I installed it with helm kube-prometheus-stack chart (version kube-prometheus-stack-41.7.3).
I use this values.yaml file for the prometheus-stack chart installation:

grafana:
  testFramework:
    enabled: false
  ingress:
    enabled: true
    annotations: {
      kubernetes.io/ingress.class: nginx
    }
    hosts:
      - "mydomain"
    pathType: Prefix
    path: /grafana
  grafana.ini:
    server:
      domain: "mydomain"
      root_url: "https://mydomain/grafana"
      serve_from_sub_path: true
  admin:
    existingSecret: grafana-admin-credentials
    serviceMonitor:
      enabled: true
    podDisruptionBudget:
      minAvailable: 1
    persistence:
      enabled: true
      storageClassName: default
alertmanager:
  podDisruptionBudget:
    enabled: true
prometheus:
  podDisruptionBudget:
    enabled: true
  prometheusSpec:
    storageSpec:
      volumeClaimTemplate:
        spec:
          storageClassName: default
          accessModes: ["ReadWriteOnce"]
          resources:
            requests:
              storage: 50Gi
kubeScheduler:
  enabled: false
kubeControllerManager:
  enabled: false

I meet an error page with some advices to load application files:

If you're seeing this Grafana has failed to load its application files

This could be caused by your reverse proxy settings.

If you host grafana under subpath make sure your grafana.ini root_url setting includes subpath. If not using a reverse proxy make sure to set serve_from_sub_path to true.

If you have a local dev build make sure you build frontend using: yarn start, yarn start:hot, or yarn build

Sometimes restarting grafana-server can help

Check if you are using a non-supported browser. For more information, refer to the list of supported browsers.

During my researches, I found this subject that seems to be the same issue but when I try to do the same configuration, it does not work: Trying to rewrite url for Grafana with Ingress

Did anyone ever meet this kind of issue and can explain me why the application can't load its application file please?
Thanks in avance for your help


问:
App build failed while pushing django-telegram-bot to dokku
Currently trying to deploy my bot to a VPS I have. I followed the documentation and the setup when it comes to both the VPS setup, dokku installation and app creation. I had no issues.

When trying to deploy my app with

```<code>git push dokku master
</code>```

I get the output:

```<code>
Enumerating objects: 87, done.
Counting objects: 100% (87/87), done.
Delta compression using up to 16 threads
Compressing objects: 100% (81/81), done.
Writing objects: 100% (87/87), 45.75 KiB | 936.00 KiB/s, done.
Total 87 (delta 3), reused 0 (delta 0), pack-reused 0
remote: -----> Cleaning up...
remote: -----> Building bot from herokuish
remote: -----> Adding BUILD_ENV to build environment...
remote:        BUILD_ENV added successfully
remote:        -----> Warning: Multiple default buildpacks reported the ability to handle this app. The first buildpack in the list below will be used.
remote:               Detected buildpacks: multi python
remote:        -----> Multipack app detected
remote: =====> Downloading Buildpack: https://github.com/heroku/heroku-buildpack-python.git#v191@v191
remote: =====> Detected Framework: Python
remote:        !     Requested runtime (python-3.8.3) is not available for this stack (heroku-20).
remote:        !     Aborting.  More info: https://devcenter.heroku.com/articles/python-support
remote:  !     Failure during app build
remote:  !     Removing invalid image tag dokku/bot:latest
remote:  !     App build failed
To ipaddress:bot
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'ipaddress:bot'
</code>```

I tried specifying the builpack url with

```<code>dokku config:set dtb BUILDPACK_URL=https://github.com/heroku/heroku-buildpack-python.git#v191
</code>```

but get the following output

```<code>-----> Setting config vars
       BUILDPACK_URL:  https://github.com/heroku/heroku-buildpack-python.git#v191
-----> Restarting app bot
 !     App image (dokku/bot:latest) not found

</code>```

Body:
Currently trying to deploy my bot to a VPS I have. I followed the documentation and the setup when it comes to both the VPS setup, dokku installation and app creation. I had no issues.

When trying to deploy my app with

git push dokku master

I get the output:

Enumerating objects: 87, done.
Counting objects: 100% (87/87), done.
Delta compression using up to 16 threads
Compressing objects: 100% (81/81), done.
Writing objects: 100% (87/87), 45.75 KiB | 936.00 KiB/s, done.
Total 87 (delta 3), reused 0 (delta 0), pack-reused 0
remote: -----> Cleaning up...
remote: -----> Building bot from herokuish
remote: -----> Adding BUILD_ENV to build environment...
remote:        BUILD_ENV added successfully
remote:        -----> Warning: Multiple default buildpacks reported the ability to handle this app. The first buildpack in the list below will be used.
remote:               Detected buildpacks: multi python
remote:        -----> Multipack app detected
remote: =====> Downloading Buildpack: https://github.com/heroku/heroku-buildpack-python.git#v191@v191
remote: =====> Detected Framework: Python
remote:        !     Requested runtime (python-3.8.3) is not available for this stack (heroku-20).
remote:        !     Aborting.  More info: https://devcenter.heroku.com/articles/python-support
remote:  !     Failure during app build
remote:  !     Removing invalid image tag dokku/bot:latest
remote:  !     App build failed
To ipaddress:bot
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'ipaddress:bot'

I tried specifying the builpack url with

dokku config:set dtb BUILDPACK_URL=https://github.com/heroku/heroku-buildpack-python.git#v191

but get the following output

-----> Setting config vars
       BUILDPACK_URL:  https://github.com/heroku/heroku-buildpack-python.git#v191
-----> Restarting app bot
 !     App image (dokku/bot:latest) not found


问:
Multiple group counter/sum in SQL Server
For example, I have 2 tables. Each employee has several operations. (operationId is used to join)

In the database, this is Table1:

```<code>dbid  operationId  employeeName
-------------------------------
 1         1         emp1
 2         2         emp2
</code>```

Table2:

```<code>dbid  operationName       timeStart            timeEnd
--------------------------------------------------------------
 1      working1     2022-12-19 00:00:00  2022-12-19 02:00:00
 2      working2     2022-12-19 18:00:00  2022-12-19 21:00:00
 3      working2     2022-12-19 00:00:00  2022-12-20 00:00:00
</code>```

timeStart datatype is datetime.

The question is how to write a correct select that will show each day grouped duration of operations for each employee, like:

```<code>  date         hoursOfOperationsPerDay, hours   employeeName
------------------------------------------------------------
2022-12-19               5                         emp1
2022-12-19              24                         emp2
</code>```

I know how to make group select for each day, but I don't know how to add to select employees

Body:
For example, I have 2 tables. Each employee has several operations. (operationId is used to join)

In the database, this is Table1:

dbid  operationId  employeeName
-------------------------------
 1         1         emp1
 2         2         emp2

Table2:

dbid  operationName       timeStart            timeEnd
--------------------------------------------------------------
 1      working1     2022-12-19 00:00:00  2022-12-19 02:00:00
 2      working2     2022-12-19 18:00:00  2022-12-19 21:00:00
 3      working2     2022-12-19 00:00:00  2022-12-20 00:00:00

timeStart datatype is datetime.

The question is how to write a correct select that will show each day grouped duration of operations for each employee, like:

  date         hoursOfOperationsPerDay, hours   employeeName
------------------------------------------------------------
2022-12-19               5                         emp1
2022-12-19              24                         emp2

I know how to make group select for each day, but I don't know how to add to select employees


问:
This code delets any apparation of e character in a word or close it runs succesfully but when my close contains space the code doesnt run sucessfully
```<code>#include<stdio.h>
#include<stdlib.h>
#include <string.h>
int main()
{
    char  ch[20];
    int i,j;

     do{
        printf("Donner ch :");
        scanf("%s",&ch);
    }while(strlen(ch)<0);

    for(i=0;i<strlen (ch);++i)
    {
        if(ch[i] == 'e')
        {
            for(j=i;j<=strlen(ch)-1;j++)
                ch[j]=ch[j+1];

        }
    }

     printf("la chaine obtenue est %s", ch);
    return 0;
}
</code>```

compilation result

Here doesnt run sucessfully     enter image description here

Here it runs sucessfully  enter image description here

Body:
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
int main()
{
    char  ch[20];
    int i,j;

     do{
        printf("Donner ch :");
        scanf("%s",&ch);
    }while(strlen(ch)<0);

    for(i=0;i<strlen (ch);++i)
    {
        if(ch[i] == 'e')
        {
            for(j=i;j<=strlen(ch)-1;j++)
                ch[j]=ch[j+1];

        }
    }

     printf("la chaine obtenue est %s", ch);
    return 0;
}

compilation result

Here doesnt run sucessfully     enter image description here

Here it runs sucessfully  enter image description here


问:
Metamask transactions are not popping up when pushing the fund button on my website

import { ethers } from "./ethers.5.6.esm.min.js"
import { abi, contractAddress } from "./constants.js"

const connectButton = document.getElementById("connectButton")
const fundButton = document.getElementById("fundButton")

connectButton.onclick = connect
fundButton.onclick = fund

console.log(ethers)

async function connect() {
    if (typeof window.ethereum !== "undefined") {
        await window.ethereum.request({ method: "eth_requestAccounts" })
        connectButton.innerHTML = "Connected!"
    } else {
        connectButton.innerHTML = "Please install metamask"
    }
}
async function fund(ethAmount) {
    const ethAmount = "77"
    console.log(`funding with ${ethAmount}`)
    if (typeof window.ethereum !== "undefined") {
        // provider / connection to the blockchain
        // signer / wallet / someone with some gas to actually send it
        //contract that we are interacting with
        // ^ ABI and address
        const provider = new ethers.providers.Web3Provider(window.ethereum)
        const signer = provider.getSigner()
        const contract = new ethers.Contract(contractAddress, abi, signer)
        const transactionResponse = await contract.fund({
            value: ethers.utils.parseEther(ethAmount),
        })
    }
}
```
<p>above is the javascript code for my sample website for which the code lies below</p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>

    <title>Fund Me App</title>
</head>
<body>
   Hello!
   <script src="./index.js" type="module">
   </script>
   <button id="connectButton"> Connect </button>
   <button id="fundButton"> Fund </button>
</body>
</html>
</code>```

I have created a hardhat localhost and added the hardhat network to my metamask wallet, however when I push the fund button, no transactions are popping up on my metamask

Body:
import { ethers } from "./ethers.5.6.esm.min.js"
import { abi, contractAddress } from "./constants.js"

const connectButton = document.getElementById("connectButton")
const fundButton = document.getElementById("fundButton")

connectButton.onclick = connect
fundButton.onclick = fund

console.log(ethers)

async function connect() {
    if (typeof window.ethereum !== "undefined") {
        await window.ethereum.request({ method: "eth_requestAccounts" })
        connectButton.innerHTML = "Connected!"
    } else {
        connectButton.innerHTML = "Please install metamask"
    }
}
async function fund(ethAmount) {
    const ethAmount = "77"
    console.log(`funding with ${ethAmount}`)
    if (typeof window.ethereum !== "undefined") {
        // provider / connection to the blockchain
        // signer / wallet / someone with some gas to actually send it
        //contract that we are interacting with
        // ^ ABI and address
        const provider = new ethers.providers.Web3Provider(window.ethereum)
        const signer = provider.getSigner()
        const contract = new ethers.Contract(contractAddress, abi, signer)
        const transactionResponse = await contract.fund({
            value: ethers.utils.parseEther(ethAmount),
        })
    }
}

above is the javascript code for my sample website for which the code lies below

<!DOCTYPE html>

    <title>Fund Me App</title>

   Hello!

   <button id="connectButton"> Connect </button>
   <button id="fundButton"> Fund </button>

I have created a hardhat localhost and added the hardhat network to my metamask wallet, however when I push the fund button, no transactions are popping up on my metamask


问:
Can apps feature sending msgs directly w/o msg dialog appearing but still get into Google Play Store?
I was reading the flutter plugin information for the flutter_sms plugin, specifically the following:

```<code>Sending Direct #
WARNING, there is a narrow category of apps that can get into the play store using this feature.
Using it is only advisable if you fit into this category or you intent to distribute through a third party platform

On Android, you can skip the additional dialog with the sendDirect parameter.
</code>```

So I would like to know:

What category / types of apps DO get through to the Play Store if they have this feature of directly sending messages to some recipients without the message dialog appearing explicitly? \

If someone is aware of an example of an app that has this feature and passed through to the Play Store, please link that.

Otherwise please guide me to some regulation description regarding this matter (I am interested since I think this feature would be beneficial in my use-case).

Thanks!

Body:
I was reading the flutter plugin information for the flutter_sms plugin, specifically the following:

Sending Direct #
WARNING, there is a narrow category of apps that can get into the play store using this feature.
Using it is only advisable if you fit into this category or you intent to distribute through a third party platform

On Android, you can skip the additional dialog with the sendDirect parameter.

So I would like to know:

What category / types of apps DO get through to the Play Store if they have this feature of directly sending messages to some recipients without the message dialog appearing explicitly? \

If someone is aware of an example of an app that has this feature and passed through to the Play Store, please link that.

Otherwise please guide me to some regulation description regarding this matter (I am interested since I think this feature would be beneficial in my use-case).

Thanks!


问:
Adding Up Values Based on the name of a Sales Rep Name
Please how do I sum up values based on the name of a sales rep? Below is an example of the table I am trying to perform such operations on.

Date
SalesRep
Amount

12/14/2022
Alvin_KO
3000

12/15/2022
Stan_O
-600

12/15/2022
Alvin_KO
200

12/17/2022
Stan_KO
9000


问:
Define the offset of lag/lead function dynamically in pyspark
This is the input dataframe , with a id column and  2 date columns (yyyy-mm-dd) format . I want to merge the
rows when the difference between "Active_to" of  current row and "Active_from" of subsequent row is < = 2 days.

```<code> id |active_from  | active_to
 -----------------------------
  1 | 2021-01-10  | 2022-01-15
  1 | 2022-01-16  | 2022-02-10
  1 | 2022-02-10  | 2022-02-15
  1 | 2022-02-19  | 2022-02-27
</code>```

So, the output should look like this

```<code> id | active_from | active_to
 -----------------------------
  1 | 2021-01-10  | 2022-02-15
  1 | 2022-02-19  | 2022-02-27
</code>```

I have done this

```<code>win_spec = Window.partitionBy('id').orderBy(f.col('active_from'))
continous_window_len =2
df = (df.withColumn("lag_active_to",f.lag("active_to",1).over(win_spec))
     .withColumn("diff",f.datediff(f.col('active_from') , f.col('lag_active_to')))
     .withColumn('derived_active_to', when((f.lead('diff',1).over(win_spec) <=continous_window_len ) , f.lead("active_to",1).over(win_spec))
                                                                .otherwise(f.col('active_to'))))

df = df.filter((df.diff.isNull()) | (df.diff  > continous_window_len)).drop("diff","lag_active_to")

 id |active_from  | active_to | derived_active_to
 -------------------------------------------------
  1 | 2021-01-10  | 2022-01-15 | 2022-02-10
  1 | 2022-01-16  | 2022-02-10 | 2022-02-15
  1 | 2022-02-10  | 2022-02-15 | 2022-02-15
  1 | 2022-02-19  | 2022-02-27 | 2022-02-27
</code>```

The problem with this approach is that I can't merge more than 1 continuous row.
Basically , how do I expand the active_to column of row 1 to row 3 and beyond ?

Body:
This is the input dataframe , with a id column and  2 date columns (yyyy-mm-dd) format . I want to merge the
rows when the difference between "Active_to" of  current row and "Active_from" of subsequent row is < = 2 days.

 id |active_from  | active_to
 -----------------------------
  1 | 2021-01-10  | 2022-01-15
  1 | 2022-01-16  | 2022-02-10
  1 | 2022-02-10  | 2022-02-15
  1 | 2022-02-19  | 2022-02-27

So, the output should look like this

 id | active_from | active_to
 -----------------------------
  1 | 2021-01-10  | 2022-02-15
  1 | 2022-02-19  | 2022-02-27

I have done this

win_spec = Window.partitionBy('id').orderBy(f.col('active_from'))
continous_window_len =2
df = (df.withColumn("lag_active_to",f.lag("active_to",1).over(win_spec))
     .withColumn("diff",f.datediff(f.col('active_from') , f.col('lag_active_to')))
     .withColumn('derived_active_to', when((f.lead('diff',1).over(win_spec) <=continous_window_len ) , f.lead("active_to",1).over(win_spec))
                                                                .otherwise(f.col('active_to'))))

df = df.filter((df.diff.isNull()) | (df.diff  > continous_window_len)).drop("diff","lag_active_to")

 id |active_from  | active_to | derived_active_to
 -------------------------------------------------
  1 | 2021-01-10  | 2022-01-15 | 2022-02-10
  1 | 2022-01-16  | 2022-02-10 | 2022-02-15
  1 | 2022-02-10  | 2022-02-15 | 2022-02-15
  1 | 2022-02-19  | 2022-02-27 | 2022-02-27

The problem with this approach is that I can't merge more than 1 continuous row.
Basically , how do I expand the active_to column of row 1 to row 3 and beyond ?


问:
ServiceNow converting GetXMLWait to GetXML - Synchronous to Async
I am currently trying to convert a client script that is functioning synchronously to asynchronously.

The goal of the script is to populate the date timestamp field with the current system time whenever the
checkbox is filled (set to true), but it is not functioning when I swap to async.

Below is the current client script:

```<code>// Refer to script include "MyTestTimeAjax"
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        return;
    }

    if (newValue == 'true') {
        var ajax = new GlideAjax('MyTestTimeAjax');
        ajax.addParam('sysparm_name', 'nowDateTime');
        ajax.getXMLWait();
        var rightnow = ajax.getAnswer();
        g_form.setValue('u_test_draft', rightnow);

    } else {
        g_form.clearValue('u_test_draft');
    }
}
</code>```

And here is the script include

```<code>var MyTestTimeAjax = Class.create();
MyTestTimeAjax.prototype = Object.extendsObject(AbstractAjaxProcessor, {

    nowDateTime: function() {
        return gs.nowDateTime();
    }
});
</code>```

Now, I have given at attempt at converting using a callback function within the client script. But no matter what I try, I either end up with undefined as the value, or it remains blank even when the checkbox is true.

Here is my attempt at it.

```<code>// Refer to script include "MyDateTimeAjax"
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        return;
    }
    if (newValue == 'true') {
        var ajax = new GlideAjax('MyTestTimeAjax');
        ajax.addParam('sysparm_name', 'nowDateTime');
        ajax.getXML(DateTime);
        //var rightnow = ajax.getAnswer;
        //g_form.setValue('u_test_draft', rightnow);
    } else {
        g_form.clearValue('u_test_draft');
    }

    function DateTime(response) {
        // This is where we get the response returned from the MyTestTimeAjax Script Include
        var answer = response.response.XML.documentElement.getAttribute("answer");
         g_form.setValue('u_test_draft',answer);
    }
}
</code>```

Please if anyone can provide guidance or assistance on this, I would greatly appreciate it.

Body:
I am currently trying to convert a client script that is functioning synchronously to asynchronously.

The goal of the script is to populate the date timestamp field with the current system time whenever the
checkbox is filled (set to true), but it is not functioning when I swap to async.

Below is the current client script:

// Refer to script include "MyTestTimeAjax"
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        return;
    }

    if (newValue == 'true') {
        var ajax = new GlideAjax('MyTestTimeAjax');
        ajax.addParam('sysparm_name', 'nowDateTime');
        ajax.getXMLWait();
        var rightnow = ajax.getAnswer();
        g_form.setValue('u_test_draft', rightnow);

    } else {
        g_form.clearValue('u_test_draft');
    }
}

And here is the script include

var MyTestTimeAjax = Class.create();
MyTestTimeAjax.prototype = Object.extendsObject(AbstractAjaxProcessor, {

    nowDateTime: function() {
        return gs.nowDateTime();
    }
});

Now, I have given at attempt at converting using a callback function within the client script. But no matter what I try, I either end up with undefined as the value, or it remains blank even when the checkbox is true.

Here is my attempt at it.

// Refer to script include "MyDateTimeAjax"
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        return;
    }
    if (newValue == 'true') {
        var ajax = new GlideAjax('MyTestTimeAjax');
        ajax.addParam('sysparm_name', 'nowDateTime');
        ajax.getXML(DateTime);
        //var rightnow = ajax.getAnswer;
        //g_form.setValue('u_test_draft', rightnow);
    } else {
        g_form.clearValue('u_test_draft');
    }

    function DateTime(response) {
        // This is where we get the response returned from the MyTestTimeAjax Script Include
        var answer = response.response.XML.documentElement.getAttribute("answer");
         g_form.setValue('u_test_draft',answer);
    }
}

Please if anyone can provide guidance or assistance on this, I would greatly appreciate it.


问:
json file not found when unit test
I have a python file and a helper json file. The json is loaded via

```<code>with open("scraper_dbs.json") as f:
    scraper_dbs = json.load(f)
</code>```

From my testfolder I want to test the file which looks like

```<code>from path.to.file import function
</code>```

On this import statement I get the error
FileNotFoundError: [Errno 2] No such file or directory: 'scraper_dbs.json'

When I run the python code itself it finds the json and continues on.
What do I miss?

Title: json file not found when unit test

Body:
I have a python file and a helper json file. The json is loaded via

with open("scraper_dbs.json") as f:
    scraper_dbs = json.load(f)

From my testfolder I want to test the file which looks like

from path.to.file import function

On this import statement I get the error
FileNotFoundError: [Errno 2] No such file or directory: 'scraper_dbs.json'

When I run the python code itself it finds the json and continues on.
What do I miss?


问:
Is there a way to view Register memory value in IDA (like x64dbg)?
Is there a way to view the register memory value in IDA, like x64dbg?
I can hoover over the register in the register panel and see it's memory value but I want to know if I can sho wit like in x64dbg?

like this:


问:
find rotation+scaling matrix that maps two vectors
I have two vectors in space, say v1 = [(x11,y11,z11), (x12, y12, z12)] and v2=[(x21,y21,z21), (x22,y22,z22)]. The semantic here is such that each vector represents an arrow that points from its first point to the second point.

I would like to calculate a matrix M such that v2=M*v1 and M is only a rotation+scaling+translation matrix.

This looks to me like a generic 3d graphics question that must have been solved a million times already...


问:
How to make NodeJS return a response to an XMLHttpRequest?
I am building a database app, and a key component would be allowing clients to create and manipulate their users' accounts. For efficient functionality, I would want to create a way for their front end to send a POST request via fetch or XMLHttpRequest. However, my problem is that the request is not processed by my back end and demo front end. Here is my code:

Front end javascript:

```<code>let xhr = new XMLHttpRequest();
// we defined the xhr

xhr.onreadystatechange = function () {
  if (this.readyState == 4) {
    console.log(this.response);
  }
};

xhr.open('POST', 'https://PlasticStudiousCells.programprodigy.repl.co/add-user', true);
xhr.send(
  JSON.stringify({
    'user': 'lol',
    'key': 'QKsP2s23LP',
    'data': {
      'name': 'lol',
      'email': 'lol@lol.com',
      'password': 'lol'
    }
  })
);
</code>```

My back end code:

```<code>app.post('/add-user', function(req, res) {
  console.log(req.body);
  let user = JSON.parse(req.body);
  let keys = JSON.parse(fs.readFileSync('/home/runner/PlasticStudiousCells/dbs/keys.json'));
  if (keys[encrypt(user.key)]) {
    try {
      addUser(keys[encrypt(user.key)], user.user, user.data);
      res.status(200).send('User successfully added.');
      console.log(user.user +' successfully added.');
    } catch(err) {
      res.status(404).send(err);
      console.log(err);
    }
  }
})
</code>```

I assure you that addUser is a defined function and works.

Body:
I am building a database app, and a key component would be allowing clients to create and manipulate their users' accounts. For efficient functionality, I would want to create a way for their front end to send a POST request via fetch or XMLHttpRequest. However, my problem is that the request is not processed by my back end and demo front end. Here is my code:

Front end javascript:

let xhr = new XMLHttpRequest();
// we defined the xhr

xhr.onreadystatechange = function () {
  if (this.readyState == 4) {
    console.log(this.response);
  }
};

xhr.open('POST', 'https://PlasticStudiousCells.programprodigy.repl.co/add-user', true);
xhr.send(
  JSON.stringify({
    'user': 'lol',
    'key': 'QKsP2s23LP',
    'data': {
      'name': 'lol',
      'email': 'lol@lol.com',
      'password': 'lol'
    }
  })
);

My back end code:

app.post('/add-user', function(req, res) {
  console.log(req.body);
  let user = JSON.parse(req.body);
  let keys = JSON.parse(fs.readFileSync('/home/runner/PlasticStudiousCells/dbs/keys.json'));
  if (keys[encrypt(user.key)]) {
    try {
      addUser(keys[encrypt(user.key)], user.user, user.data);
      res.status(200).send('User successfully added.');
      console.log(user.user +' successfully added.');
    } catch(err) {
      res.status(404).send(err);
      console.log(err);
    }
  }
})

I assure you that addUser is a defined function and works.


问:
Pygame not installing. It's saying "The error generates from a sub process, and is likely not a problem with pip."

I was trying to install pygame and I typed 'pip install pygame' and it started installing it but then the installation was interrupted, please help me in downloading the pygame.


问:
The remote certificate is invalid according to the validation procedure when loading report viewer control
I get the error The remote certificate is invalid according to the validation procedure
when loading the report viewer control in an asp.net MVC 4 application.

I'm suspecting it is because the remote report server is accessed via https.
Below is the code.

```<code>   var irsc = new CustomReportCredentials(AppConfiguration.SSRSReportUser, AppConfiguration.SSRSReportPwd, AppConfiguration.SSRSReportDomain);

            Microsoft.Reporting.WebForms.ReportViewer _reportViewer = new Microsoft.Reporting.WebForms.ReportViewer();

            _reportViewer.ServerReport.ReportServerCredentials = irsc;
            _reportViewer.ProcessingMode = ProcessingMode.Remote;
            _reportViewer.ServerReport.ReportServerUrl = new Uri(AppConfiguration.SSRSReportServerURL);
            _reportViewer.ServerReport.ReportPath = reportPath;
            _reportViewer.ServerReport.SetParameters(reportParameters);
            _reportViewer.SizeToReportContent = true;
            _reportViewer.ShowParameterPrompts = false;
            _reportViewer.AsyncRendering = true;
</code>```

is there a way to skip the ssl check in the ReportServerCredentials parameter?

Body:
I get the error The remote certificate is invalid according to the validation procedure
when loading the report viewer control in an asp.net MVC 4 application.

I'm suspecting it is because the remote report server is accessed via https.
Below is the code.

   var irsc = new CustomReportCredentials(AppConfiguration.SSRSReportUser, AppConfiguration.SSRSReportPwd, AppConfiguration.SSRSReportDomain);

            Microsoft.Reporting.WebForms.ReportViewer _reportViewer = new Microsoft.Reporting.WebForms.ReportViewer();

            _reportViewer.ServerReport.ReportServerCredentials = irsc;
            _reportViewer.ProcessingMode = ProcessingMode.Remote;
            _reportViewer.ServerReport.ReportServerUrl = new Uri(AppConfiguration.SSRSReportServerURL);
            _reportViewer.ServerReport.ReportPath = reportPath;
            _reportViewer.ServerReport.SetParameters(reportParameters);
            _reportViewer.SizeToReportContent = true;
            _reportViewer.ShowParameterPrompts = false;
            _reportViewer.AsyncRendering = true;

is there a way to skip the ssl check in the ReportServerCredentials parameter?


问:
How can I properly tell cmake which CXX compiler to use?
I am trying to build a project from cmake on CentOS 7. The project requires C++ 17 and I'm getting this error from the build:

```<code>CMake Error at nvbench/nvbench/CMakeLists.txt:86 (target_compile_features):
  target_compile_features The compiler feature "cxx_std_17" is not known to
  CXX compiler

  "GNU"

  version 4.8.5.
</code>```

L86:

```<code>target_compile_features(nvbench PUBLIC cuda_std_17 PRIVATE cxx_std_17)
</code>```

Naturally, CentOS 7's g++ has version 4.8.5 and doesn't support C++ 17, but I have devtoolset 9 which has g++ version 9.3.1. I've added these lines near the top CMakeLists.txt:

```<code>set(CMAKE_C_COMPILER /opt/rh/devtoolset-9/root/bin/gcc)
set(CMAKE_CXX_COMPILER /opt/rh/devtoolset-9/root/bin/g++)
</code>```

but cmake still references the default compiler and not the one in the devtoolset.

Also made sure to run with scl enable devtoolset-9 'cmake ..' but that didn't work either.

How can I fix this so cmake uses g++ in the devtooset?

Body:
I am trying to build a project from cmake on CentOS 7. The project requires C++ 17 and I'm getting this error from the build:

CMake Error at nvbench/nvbench/CMakeLists.txt:86 (target_compile_features):
  target_compile_features The compiler feature "cxx_std_17" is not known to
  CXX compiler

  "GNU"

  version 4.8.5.

L86:

target_compile_features(nvbench PUBLIC cuda_std_17 PRIVATE cxx_std_17)

Naturally, CentOS 7's g++ has version 4.8.5 and doesn't support C++ 17, but I have devtoolset 9 which has g++ version 9.3.1. I've added these lines near the top CMakeLists.txt:

set(CMAKE_C_COMPILER /opt/rh/devtoolset-9/root/bin/gcc)
set(CMAKE_CXX_COMPILER /opt/rh/devtoolset-9/root/bin/g++)

but cmake still references the default compiler and not the one in the devtoolset.

Also made sure to run with scl enable devtoolset-9 'cmake ..' but that didn't work either.

How can I fix this so cmake uses g++ in the devtooset?


问:
MYSQL 5.7 - Can't give grants with wildcard grant option
I have a user that currently has a wild card grant option, such as:

```<code>GRANT ALL PRIVILEGES ON `myPrefix\_%`.* TO 'myUser'@'%' WITH GRANT OPTION
</code>```

myUser is designed to create users under that wildcard.
I was able to create a database named myPrefix_database_12345 with this user. But, if, for example, I want to create a grant for nextUser:

```<code>GRANT ALL PRIVILEGES ON myPrefix_database_12345.* TO 'nextUser'@'%'
</code>```

It returns me this error, when it should have permissions to do so:

```<code>ERROR 1044 (42000): Access denied for user 'myUser'@'%' to database 'myPrefix_database_12345'
</code>```

I'm wondering if this is even possible or should another approach be made?

Thanks.

Body:
I have a user that currently has a wild card grant option, such as:

GRANT ALL PRIVILEGES ON `myPrefix\_%`.* TO 'myUser'@'%' WITH GRANT OPTION

myUser is designed to create users under that wildcard.
I was able to create a database named myPrefix_database_12345 with this user. But, if, for example, I want to create a grant for nextUser:

GRANT ALL PRIVILEGES ON myPrefix_database_12345.* TO 'nextUser'@'%'

It returns me this error, when it should have permissions to do so:

ERROR 1044 (42000): Access denied for user 'myUser'@'%' to database 'myPrefix_database_12345'

I'm wondering if this is even possible or should another approach be made?

Thanks.