问:
How do I check if my Discord.Net bot is already connected to a Voice Channel
My bot can join and leave a voice channel without issue but how would I validate if it's already connected to a voice chat?

Code from my audio service .cs file

```<code>public async Task<IAudioClient> ConnecttoVC(SocketCommandContext ctx)
        {
            SocketGuildUser user = ctx.User as SocketGuildUser;
            IVoiceChannel chnl = user.VoiceChannel;
            if(chnl == null)
            {
                await ctx.Channel.SendMessageAsync("Not connected!");
                return null;
            }
            await ctx.Channel.SendMessageAsync("Joining Voice!");
            return await chnl.ConnectAsync();
        }
</code>```

答:
So I was using the VoiceChannel property of .CurrentUser to check if the bot is connected or not and I was having issues with the bot joining and leaving simultaneously or not joining at all. So I decided to just add a bool variable to my class and it works for me.

```<code>private bool voiceCheck;
        public AudioService() { voiceCheck = false; }

public async Task<IAudioClient> ConnecttoVC(SocketCommandContext ctx)
        {
            SocketGuildUser user = ctx.User as SocketGuildUser;
            IVoiceChannel chnl = user.VoiceChannel;
            if(chnl == null)
            {
                await ctx.Channel.SendMessageAsync("Not connected!");
                return null;
            }
            if(voiceCheck == true)
            {
                await ctx.Channel.SendMessageAsync("Already connected!");
                return null;
            }
            await ctx.Channel.SendMessageAsync("Joining Voice!");
            voiceCheck = true;
            return await chnl.ConnectAsync();
        }

</code>```

Between my ConnecttoVC and Leave(omitted) methods, voiceCheck would switch between true and false while checking for each respectively.

Body:
My bot can join and leave a voice channel without issue but how would I validate if it's already connected to a voice chat?

Code from my audio service .cs file

public async Task<IAudioClient> ConnecttoVC(SocketCommandContext ctx)
        {
            SocketGuildUser user = ctx.User as SocketGuildUser;
            IVoiceChannel chnl = user.VoiceChannel;
            if(chnl == null)
            {
                await ctx.Channel.SendMessageAsync("Not connected!");
                return null;
            }
            await ctx.Channel.SendMessageAsync("Joining Voice!");
            return await chnl.ConnectAsync();
        }

Body:
So I was using the VoiceChannel property of .CurrentUser to check if the bot is connected or not and I was having issues with the bot joining and leaving simultaneously or not joining at all. So I decided to just add a bool variable to my class and it works for me.

private bool voiceCheck;
        public AudioService() { voiceCheck = false; }

public async Task<IAudioClient> ConnecttoVC(SocketCommandContext ctx)
        {
            SocketGuildUser user = ctx.User as SocketGuildUser;
            IVoiceChannel chnl = user.VoiceChannel;
            if(chnl == null)
            {
                await ctx.Channel.SendMessageAsync("Not connected!");
                return null;
            }
            if(voiceCheck == true)
            {
                await ctx.Channel.SendMessageAsync("Already connected!");
                return null;
            }
            await ctx.Channel.SendMessageAsync("Joining Voice!");
            voiceCheck = true;
            return await chnl.ConnectAsync();
        }

Between my ConnecttoVC and Leave(omitted) methods, voiceCheck would switch between true and false while checking for each respectively.


来源: stackexchange

问:
Django - context - How to pass context to ALL views
Because I need to cycle through a model table to render the options/nav-links in the navbar, and the navbar is rendered on every page. Hence, I find myself passing in the same context to every class-based view and it's quite repetitive:

class Xxx:
    ...
    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context['categories'] = Category.objects.get_categories_with_item()
        return context
```

Is there a DRYer way to do this? Thanks!!

PS. and also, is *args necessary in get_context_data method? I've seen code with it and code without

答:
You can to write custom context processor

```<code>from django.core.context_processors import request

def custom_processor(request):
    categories = Category.objects.get_categories_with_item()
    return {"categories": categories}
</code>```

You need to add this function to TEMPLATES -> "OPTIONS" -> "context_processors"

ContentLicense: CC BY-SA 4.0

Body:
Because I need to cycle through a model table to render the options/nav-links in the navbar, and the navbar is rendered on every page. Hence, I find myself passing in the same context to every class-based view and it's quite repetitive:

class Xxx:
    ...
    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context['categories'] = Category.objects.get_categories_with_item()
        return context

Is there a DRYer way to do this? Thanks!!

PS. and also, is *args necessary in get_context_data method? I've seen code with it and code without

Body:
You can to write custom context processor

from django.core.context_processors import request

def custom_processor(request):
    categories = Category.objects.get_categories_with_item()
    return {"categories": categories}

You need to add this function to TEMPLATES -> "OPTIONS" -> "context_processors"


问:
ERROR: (gcloud.app.deploy) You must provide your own Dockerfile when using a custom runtime
I am trying to schedule an R job on Google Cloud using App Engine. I am following the article

https://code.markedmondson.me/4-ways-schedule-r-scripts-on-google-cloud-platform/

However, when I try to deploy the app using gcloud app deploy --project shiny-demo I get the following error

```<code>Enabling service [appengineflex.googleapis.com] on project [shiny-demo]...
Waiting for async operation operations/acf.33c5e6da-6f9e-4e66-b7d3-f0611eddc0ce to complete...
Operation finished successfully. The following command can describe the Operation details:
 gcloud services operations describe operations/tmo-acf.33c5e6da-6f9e-4e66-b7d3-f0611eddc0ce
Beginning deployment of service [default]...
ERROR: (gcloud.app.deploy) You must provide your own Dockerfile when using a custom runtime. Otherwise provide a "runtime" field with one of the supported runtimes.
</code>```

I do have a Dockerfile in the same folder as my yaml file, however somehow it does not recognize the Dockerfile. Below is my yaml file:

# app.yaml file
runtime: custom
env: flex

manual_scaling:
  instances: 1
resources:
  cpu: 1
  memory_gb: 0.5
  disk_size_gb: 10

env_variables:
  GCS_AUTH_FILE: authkey.json
```

<p>My Dockerfile:</p>

```# DOCKER
FROM trestletech/plumber
LABEL maintainer="mark"
RUN export DEBIAN_FRONTEND=noninteractive; apt-get -y update \
 && apt-get install -y libcairo2-dev \
    libcurl4-openssl-dev \
    libgmp-dev \
    libpng-dev \
    libssl-dev \
    libxml2-dev \
    make \
    pandoc \
    pandoc-citeproc \
    zlib1g-dev
RUN ["install2.r", "-r 'https://cloud.r-project.org'", "readr", "googleCloudStorageR", "bigrquery", "Rcpp", "digest", "crayon", "withr", "mime", "R6", "jsonlite", "xtable", "magrittr", "httr", "curl", "testthat", "devtools", "hms", "shiny", "httpuv", "memoise", "htmltools", "openssl", "tibble", "remotes"]
RUN ["installGithub.r", "MarkEdmondson1234/googleAuthR@7917351", "hadley/rlang@ff87439"]
WORKDIR /payload/
COPY [".", "./"]

EXPOSE 8080
ENTRYPOINT ["R", "-e", "pr <- plumber::plumb(commandArgs()[4]); pr$run(host='0.0.0.0', port=8080)"]
CMD ["myscript.R"]
```

I am a bit new to Docker.

Adding the picture for folder structure:

答:
Does your Dockerfile name is Dockerfile (first letter uppercase)?

Windows sometimes saves the file internally as .txt.

A Dockerfile must be created with no extension. To do this in Windows,
  create the file with your editor of choice, then save it with the
  notation "Dockerfile" (including the quotes).

Is your Dockefile in the right path at the same level as the app.yaml?

Body:
I am trying to schedule an R job on Google Cloud using App Engine. I am following the article

https://code.markedmondson.me/4-ways-schedule-r-scripts-on-google-cloud-platform/

However, when I try to deploy the app using gcloud app deploy --project shiny-demo I get the following error

Enabling service [appengineflex.googleapis.com] on project [shiny-demo]...
Waiting for async operation operations/acf.33c5e6da-6f9e-4e66-b7d3-f0611eddc0ce to complete...
Operation finished successfully. The following command can describe the Operation details:
 gcloud services operations describe operations/tmo-acf.33c5e6da-6f9e-4e66-b7d3-f0611eddc0ce
Beginning deployment of service [default]...
ERROR: (gcloud.app.deploy) You must provide your own Dockerfile when using a custom runtime. Otherwise provide a "runtime" field with one of the supported runtimes.

I do have a Dockerfile in the same folder as my yaml file, however somehow it does not recognize the Dockerfile. Below is my yaml file:

# app.yaml file
runtime: custom
env: flex

manual_scaling:
  instances: 1
resources:
  cpu: 1
  memory_gb: 0.5
  disk_size_gb: 10

env_variables:
  GCS_AUTH_FILE: authkey.json

My Dockerfile:

# DOCKER
FROM trestletech/plumber
LABEL maintainer="mark"
RUN export DEBIAN_FRONTEND=noninteractive; apt-get -y update \
 && apt-get install -y libcairo2-dev \
    libcurl4-openssl-dev \
    libgmp-dev \
    libpng-dev \
    libssl-dev \
    libxml2-dev \
    make \
    pandoc \
    pandoc-citeproc \
    zlib1g-dev
RUN ["install2.r", "-r 'https://cloud.r-project.org'", "readr", "googleCloudStorageR", "bigrquery", "Rcpp", "digest", "crayon", "withr", "mime", "R6", "jsonlite", "xtable", "magrittr", "httr", "curl", "testthat", "devtools", "hms", "shiny", "httpuv", "memoise", "htmltools", "openssl", "tibble", "remotes"]
RUN ["installGithub.r", "MarkEdmondson1234/googleAuthR@7917351", "hadley/rlang@ff87439"]
WORKDIR /payload/
COPY [".", "./"]

EXPOSE 8080
ENTRYPOINT ["R", "-e", "pr <- plumber::plumb(commandArgs()[4]); pr$run(host='0.0.0.0', port=8080)"]
CMD ["myscript.R"]

I am a bit new to Docker.

Adding the picture for folder structure:


问:
How to remove widget's title in Liferay's custom theme
I created a custom theme for Liferay 7.2 through IDE. When I try to modify "Look and feel" setting of any widget, I'm unable to remove the title or to see the option's dropdown of "Application Decorators".

I followed this tutorial and created the "liferay-look-and-feel.xml". With this file the option's dropdown is now visible, but I still cannot remove any title. Even selecting "Barebone" option and "No" in "Use Custom Title".

I printed the portlet preferences, and the "portletSetupUseCustomTitle" property is set to false

Probably, I have a missing configuration on my Theme's settings but I'm not aware about which one is.

答:
```<code>In your custom theme find  portlet.ftl file Add this line where title are shown
   <#if portlet_display.getPortletDecoratorId() != "barebone">
            <div class="autofit-col autofit-col-expand">
            <h2 class="portlet-title-text">${portlet_title}</h2>
            </div>
  </#if>
</code>```


问:
how do I encrypt and then decrypt the text of username and password used in database class file
I have created a class file database.php which handles all the sql queries and connecting to database. I store username and password for the database in a variable (which is easily seen if one gains access to the php file).

I want to encrypt that username and password so that even after having that php file one is not able to have an idea of the original username and password.

Please help me as I am in need of some idea desperately.

Thanks

答: One of solution can be used is to hash some stable environment parameters, like sha1($_SERVER['HTTP_HOST'].$_SERVER['...']) and use the hash as db password.</p>

ContentLicense: CC BY-SA 2.5


问:
Is the PHP CURL api cleaner/faster/better than using streams for HTTP/HTTPS access?
I currently use pretty exclusively the PHP stream context functionality (see http://us2.php.net/manual/en/function.stream-context-create.php) to access HTTP resources and I've been able to successfully use it to do PUTs, DELETEs, POSTs, manage cookies and do just about everything I've needed to do. I originally started using it because I had SSL issues with earlier Debian PHP cURL builds (there was an OpenSSL double-initialization issue within the Apache process that errored out when trying to access SSL urls): those are probably fixed now but I've not had occasion to go back.

In discussions with a friend he contended that the cURL api is faster/better so I wanted to ask: is there any definite experience/knowledge about which option is superior, and in what ways?

答: In regards to performance, cURL wins by a lot consistently. I won't deny that it's harder to use and it might not matter for general use, but the difference was pretty dramatic and I thought it was worth pointing out.

ContentLicense: CC BY-SA 3.0


问:
"index not backed by a repository" error from libgit2 when writing tree from index for 'pull' commit
When I do index.write_tree()) (index is an Index resulting from a merge using merge_commits), I get an error "Failed to write tree. the index file is not backed up by an existing repository". I have an existing repository. [It was bare in the original version of this post, but I have changed it to non-bare, and it is still not working.]  What am I doing wrong?

More generally, I am trying to implement git pull (a fetch then a merge). In the catch-up case, I understand that after the fetch and the merge, I need to write out a commit. That is what I am trying to do. How do I do that?

Basically, my code is

 let index = repo.merge_commits(&our_commit, &their_commit, Some(&MergeOptions::new()))?;
 if !index.has_conflicts() {
   let new_tree_oid = index.write_tree()?; // error occurs here
   let new_tree = repo.find_tree(new_tree_oid)?;
   //...
 }
```

This is using the rust git2 crate, which wraps the libgit2 library.

答:
You have an in-memory index, you don't have the repository's index.  This is the distinction that is preventing you from writing it.

You have a few options for dealing with an in-memory index:

You can convert it to a tree (and then you could create a commit that uses that tree), using git_index_write_tree_to.  The write_tree_to function will let you specify the repository that you want to write to.

You can make it the repository's index, using git_repository_set_index.

Though I would question why you're using git_merge_commits instead of just git_merge, which should take care of all of this for you, including dealing with conflicts.  If you're truly doing a git pull emulation, then you'll need to cope with that.

Body:
When I do index.write_tree()) (index is an Index resulting from a merge using merge_commits), I get an error "Failed to write tree. the index file is not backed up by an existing repository". I have an existing repository. [It was bare in the original version of this post, but I have changed it to non-bare, and it is still not working.]  What am I doing wrong?

More generally, I am trying to implement git pull (a fetch then a merge). In the catch-up case, I understand that after the fetch and the merge, I need to write out a commit. That is what I am trying to do. How do I do that?

Basically, my code is

 let index = repo.merge_commits(&our_commit, &their_commit, Some(&MergeOptions::new()))?;
 if !index.has_conflicts() {
   let new_tree_oid = index.write_tree()?; // error occurs here
   let new_tree = repo.find_tree(new_tree_oid)?;
   //...
 }

This is using the rust git2 crate, which wraps the libgit2 library.


问:
Modify Code - Delete a row of data referenced from a cell. Google Apps Script / Google Sheets
I would like to modify the below code, so that instead of it being fixed inside the code - it would delete a row based on a certain cell. So if H2 had "expected" it would look at the datarange and delete any row that contained expected. then if you change H2 to "completed" it would then run the script and delete all rows that contain completed etc etc. I will run it from a custom menu.

```<code> function DeleteText() {
 // This Code will delete any "Donation Sub-Task" in Column A.
 var sheet = SpreadsheetApp.getActive();
 sheet.setActiveSheet(sheet.getSheetByName('JIRA JQL QUERY - READ ONLY'), true);
 var rows = sheet.getDataRange();
 var numRows = rows.getNumRows();
 var values = rows.getValues();
 var rowsDeleted = 0;
 for (var i = 0; i <= numRows - 1; i++) {
 var row = values[i];
  if (row[0] == 'expected') {
 sheet.deleteRow((parseInt(i)+1) - rowsDeleted);
 rowsDeleted++;
     }
   }
 };
</code>```

As Always Thanks in Advance

答:
Requirement:

Script to delete rows depending on value in cell "H2".

Script:

```<code>function findAndDeleteRows() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('JIRA JQL QUERY - READ ONLY');
  var range = sheet.getDataRange();
  var value = sheet.getRange('H2').getValue();
  var find = range.createTextFinder(value).findAll().reverse();
  if (find.length > 0) {
    for (i = 0; i < find.length; i++) {
      sheet.deleteRow(find[i].getRow());
    }
  }
}
</code>```

Explanation:

We can use the TextFinder to achieve this pretty easily, it returns all of the rows that have your specific text. I use Array.reverse() so that the rows are deleted from the bottom upwards, otherwise you'll get rows deleted that you wanted to keep. Once we've got all of the rows we need, we can loop through them and use .deleteRow() to get rid of them.

References:

.createTextFinder()

Array.reverse()

.deleteRow()

Body:
I would like to modify the below code, so that instead of it being fixed inside the code - it would delete a row based on a certain cell. So if H2 had "expected" it would look at the datarange and delete any row that contained expected. then if you change H2 to "completed" it would then run the script and delete all rows that contain completed etc etc. I will run it from a custom menu.

 function DeleteText() {
 // This Code will delete any "Donation Sub-Task" in Column A.
 var sheet = SpreadsheetApp.getActive();
 sheet.setActiveSheet(sheet.getSheetByName('JIRA JQL QUERY - READ ONLY'), true);
 var rows = sheet.getDataRange();
 var numRows = rows.getNumRows();
 var values = rows.getValues();
 var rowsDeleted = 0;
 for (var i = 0; i <= numRows - 1; i++) {
 var row = values[i];
  if (row[0] == 'expected') {
 sheet.deleteRow((parseInt(i)+1) - rowsDeleted);
 rowsDeleted++;
     }
   }
 };

As Always Thanks in Advance

Body:
Requirement:

Script to delete rows depending on value in cell "H2".

Script:

function findAndDeleteRows() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('JIRA JQL QUERY - READ ONLY');
  var range = sheet.getDataRange();
  var value = sheet.getRange('H2').getValue();
  var find = range.createTextFinder(value).findAll().reverse();
  if (find.length > 0) {
    for (i = 0; i < find.length; i++) {
      sheet.deleteRow(find[i].getRow());
    }
  }
}

Explanation:

We can use the TextFinder to achieve this pretty easily, it returns all of the rows that have your specific text. I use Array.reverse() so that the rows are deleted from the bottom upwards, otherwise you'll get rows deleted that you wanted to keep. Once we've got all of the rows we need, we can loop through them and use .deleteRow() to get rid of them.

References:

.createTextFinder()

Array.reverse()

.deleteRow()


问:
"No tests found for given includes" when running Gradle tests in IntelliJ IDEA
I cannot run tests via Gradle in IntelliJ IDEA because of "No tests found for given includes" error.

How can I fix it?

GradleTests

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertTrue;

public class GradleTests {
    @Test
    public void initTest() {
        assertTrue(true);
    }
}
```

<p>build.gradle</p>

```plugins {
    id 'java'
}

group 'org.example'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    //testCompile group: 'junit', name: 'junit', version: '4.12'

    // https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api
    testCompile group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.6.0'
}

test {
    useJUnitPlatform()
}
```

<p>Error:</p>

```> Task :test FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':test'.
> No tests found for given includes: [GradleTests.initTest](filter.includeTestsMatching)
```

Some notes:

Issue is reproduced with both JUnit 4 and 5

IntelliJ IDEA 2019.3.3 (Community Edition), Build #IC-193.6494.35, built on February 11, 2020

Test is in src/test/java

changing runner like Intelij 2019.1 update breaks JUnit tests didn't help

without useJUnitPlatform() result is the same

答:
Thanks to Ben Watson I've found solution. Since JUnit 5.4.0 there is aggregate artifact with both api and engine dependencies. So just adding one dependency to build.gradle resolved this issue.

testCompile ('org.junit.jupiter:junit-jupiter:5.6.0')
```

Body:
I cannot run tests via Gradle in IntelliJ IDEA because of "No tests found for given includes" error.

How can I fix it?

GradleTests

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertTrue;

public class GradleTests {
    @Test
    public void initTest() {
        assertTrue(true);
    }
}

build.gradle

plugins {
    id 'java'
}

group 'org.example'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    //testCompile group: 'junit', name: 'junit', version: '4.12'

    // https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api
    testCompile group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.6.0'
}

test {
    useJUnitPlatform()
}

Error:

> Task :test FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':test'.
> No tests found for given includes: [GradleTests.initTest](filter.includeTestsMatching)

Some notes:

Issue is reproduced with both JUnit 4 and 5

IntelliJ IDEA 2019.3.3 (Community Edition), Build #IC-193.6494.35, built on February 11, 2020

Test is in src/test/java

changing runner like Intelij 2019.1 update breaks JUnit tests didn't help

without useJUnitPlatform() result is the same


问:
How calling a column in a function is different from calling a column outside in pandas dataframe?
```<code>df=pd.DataFrame({"Age":[11,12,14,15,np.NaN,np.NaN],"Class":[10,11,10,11,9,9]})
df

def impute_age(cols):
    Age = cols[0]
    Class = cols[1]

    if np.isnan(Age):

        if Class == 10:
            return 11

        elif Class == 11:
            return 12

        else:
            return 9

    else:
        return Age

df.apply(impute_age,axis=1)
</code>```

<p>Here in this impute_age function, it called first row as cols[0],but if we call a column of a dataframe outside the funcion by using cols[0], it will show error because we have to specify the column name. Why? </p>

答:
From the DataFrame.apply documentation:

Objects passed to the function are Series objects [...]

This means that what's passed to impute_age is a Series, not the complete DataFrame. i.e. the function is not applied to df but to df.loc[i] (for each possible i): If you print df.loc[0][0] you'll get the Age value of the first row.

Body:
df=pd.DataFrame({"Age":[11,12,14,15,np.NaN,np.NaN],"Class":[10,11,10,11,9,9]})
df

def impute_age(cols):
    Age = cols[0]
    Class = cols[1]

    if np.isnan(Age):

        if Class == 10:
            return 11

        elif Class == 11:
            return 12

        else:
            return 9

    else:
        return Age

df.apply(impute_age,axis=1)

Here in this impute_age function, it called first row as cols[0],but if we call a column of a dataframe outside the funcion by using cols[0], it will show error because we have to specify the column name. Why?


问:
JSON format to Data Frame in Python
I am reading API data from the cloud server in JSON format as shown here

How to write a code to store this data frame into the data frame in any database. How to convert JSON format to DataFrame?

The requirement output format is shown in table2

答:
You can try this one, tell me if it works!

```<code>import request
import json
import pandas as pd

response = request(url='http://google.com') # Assuming the url
res = response.json()
df = pd.DataFrame(data)
</code>```

Goodluck mate!

Title: JSON format to Data Frame in Python

Body:
You can try this one, tell me if it works!

import request
import json
import pandas as pd

response = request(url='http://google.com') # Assuming the url
res = response.json()
df = pd.DataFrame(data)

Goodluck mate!


答:
You can flatten values per rows by numpy.concatenate to numpy array and call mean:

```<code>df['MEAN'] = [np.concatenate(x).mean() for x in df.to_numpy()]
#for oldier pandas versions
#df['MEAN'] = [np.concatenate(x).mean() for x in df.values]
print (df)
              x             y             z      MEAN
x  [1, 2, 4, 3]  [1, 2, 4, 3]  [1, 2, 4, 3]  2.500000
y  [8, 2, 6, 4]  [1, 2, 4, 3]  [1, 2, 4, 3]  3.333333
z  [1, 2, 4, 9]  [1, 2, 4, 3]  [1, 2, 4, 3]  3.000000
</code>```

Title: Calculate mean for each row containing lists of values

Body:
I have a pandas dataframe with multiple rows and columns, where each cell contains a list of values. I want to calculate mean of values (in lists) for each row separately.

Dataframe looks like this:

l1 = [[1,2,4,3],[1,2,4,3], [1,2,4,3]]
l2 = [[8,2,6,4],[1,2,4,3],[1,2,4,3]]
l3 = [[1,2,4,9],[1,2,4,3],[1,2,4,3]]

df = pd.DataFrame([l1, l2, l3], columns=list('xyz'))

the df:

      x          y       z ...
x [1,2,4,3] [1,2,4,3] [1,2,4,3]

y [8,2,6,4] [1,2,4,3] [1,2,4,3]

z [1,2,4,9] [1,2,4,3] [1,2,4,3]

and i want result like this:

      x          y       z         MEAN
x [1,2,4,3] [1,2,4,3] [1,2,4,3]   2.50000

y [8,2,6,4] [1,2,4,3] [1,2,4,3]   3.33333

z [1,2,4,9] [1,2,4,3] [1,2,4,3]   3.00000

Any suggestions?

Body:
You can flatten values per rows by numpy.concatenate to numpy array and call mean:

df['MEAN'] = [np.concatenate(x).mean() for x in df.to_numpy()]
#for oldier pandas versions
#df['MEAN'] = [np.concatenate(x).mean() for x in df.values]
print (df)
              x             y             z      MEAN
x  [1, 2, 4, 3]  [1, 2, 4, 3]  [1, 2, 4, 3]  2.500000
y  [8, 2, 6, 4]  [1, 2, 4, 3]  [1, 2, 4, 3]  3.333333
z  [1, 2, 4, 9]  [1, 2, 4, 3]  [1, 2, 4, 3]  3.000000


问:
angular convert number to persian
I want to convert English numbers to Persian number in angular 4:

```<code>persianNumbers = ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"];
englishNumbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
price="1000$";
price= this.fixnumber(price,this.persianNumbers,this.englishNumbers);

fixnumber(src,persian,english){
   for(var i=0; i<10; i++)
      {
        var str = /english[i]/gi;
        src = src.replace(str, persian[i]);
      }
    return src;
}
</code>```

It doesn't work.

答:
Use map

```<code>let persianNumbersMap = new Map<string, string>();
map.set("0", "۰");
map.set("1", "۱");
map.set("2", "۲");
map.set("3", "۳");
map.set("4", "۳");
map.set("5", "۵");
map.set("6", "۶");
map.set("7", "۷");
map.set("8", "۸");
map.set("9", "۹");
</code>```

To use:

```<code>map.get("1");
</code>```

Title: angular convert number to persian

Body:
I want to convert English numbers to Persian number in angular 4:

persianNumbers = ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"];
englishNumbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
price="1000$";
price= this.fixnumber(price,this.persianNumbers,this.englishNumbers);

fixnumber(src,persian,english){
   for(var i=0; i<10; i++)
      {
        var str = /english[i]/gi;
        src = src.replace(str, persian[i]);
      }
    return src;
}

It doesn't work.

Body:
Use map

let persianNumbersMap = new Map<string, string>();
map.set("0", "۰");
map.set("1", "۱");
map.set("2", "۲");
map.set("3", "۳");
map.set("4", "۳");
map.set("5", "۵");
map.set("6", "۶");
map.set("7", "۷");
map.set("8", "۸");
map.set("9", "۹");

To use:

map.get("1");


问:
T-SQL: Deleting all duplicate rows but keeping one
I have a table with a very large amount of rows. Duplicates are not allowed but due to a problem with how the rows were created I know there are some duplicates in this table.
I need to eliminate the extra rows from the perspective of the key columns. Some other columns may have slightly different data but I do not care about that. I still need to keep one of these rows however. SELECT DISTINCT won't work because it operates on all columns and I need to suppress duplicates based on the key columns.

How can I delete the extra rows but still keep one efficiently?

答:
You didn't say what version you were using, but in SQL 2005 and above, you can use a common table expression with the OVER Clause.  It goes a little something like this:

```<code>WITH cte AS (
  SELECT[foo], [bar],
     row_number() OVER(PARTITION BY foo, bar ORDER BY baz) AS [rn]
  FROM TABLE
)
DELETE cte WHERE [rn] > 1
</code>```

Play around with it and see what you get.

(Edit: In an attempt to be helpful, someone edited the ORDER BY clause within the CTE. To be clear, you can order by anything you want here, it needn't be one of the columns returned by the cte. In fact, a common use-case here is that "foo, bar" are the group identifier and "baz" is some sort of time stamp. In order to keep the latest, you'd do ORDER BY baz desc)

Body:
You didn't say what version you were using, but in SQL 2005 and above, you can use a common table expression with the OVER Clause.  It goes a little something like this:

WITH cte AS (
  SELECT[foo], [bar],
     row_number() OVER(PARTITION BY foo, bar ORDER BY baz) AS [rn]
  FROM TABLE
)
DELETE cte WHERE [rn] > 1

Play around with it and see what you get.

(Edit: In an attempt to be helpful, someone edited the ORDER BY clause within the CTE. To be clear, you can order by anything you want here, it needn't be one of the columns returned by the cte. In fact, a common use-case here is that "foo, bar" are the group identifier and "baz" is some sort of time stamp. In order to keep the latest, you'd do ORDER BY baz desc)


问:
Slick Carousel Dots is showing 'number/button'

.slick-dots {
  position: absolute;
  height: 50px;
  bottom: 0px;
  width: 100%;
  left: 0px;
  padding: 0px;
  margin: 0px;
  list-style-type: none;
  text-align: center;
  font-size: 10;
}

.slick-dots li {
  position: relative;
  display: inline-block;
  width: 20px;
  height: 20px;
  margin: 0 5px;
  padding: 0;
  cursor: pointer;
}

.slick-dots li a {
  position: absolute;
  bottom: 100%;
  left: 50%;
  width: 120px;
  height: 75px;
  display: block;
  visibility: hidden;
  border: 4px solid rgba(0, 0, 0, .50);
  margin-left: -60px;
  margin-bottom: 15px;
  -webkit-transition: visibility 0.5s linear 0.5s;
  transition: visibility 0.5s linear 0.5s;
  -webkit-animation: fadeOut 0.5s both;
  animation: fadeOut 0.5s both;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">

  <div class="col-12 col-md-12 banner-section">
    <div class="slikslider3" style="clear: both">

      <div>
        <picture>
          <source media="(max-width: 900px)" srcset="https://upload.wikimedia.org/wikipedia/commons/thumb/7/77/Google_Images_2015_logo.svg/1200px-Google_Images_2015_logo.svg.png">
          <img src="https://content.fortune.com/wp-content/uploads/2017/01/google.jpeg" alt="banner" style="z-index:1" class="img-fluid">
        </picture>

      </div>

      <!-- 1st end -->
      <div>
        <picture>
          <source media="(max-width: 900px)" srcset="https://upload.wikimedia.org/wikipedia/commons/thumb/7/77/Google_Images_2015_logo.svg/1200px-Google_Images_2015_logo.svg.png">
          <img src="https://content.fortune.com/wp-content/uploads/2017/01/google.jpeg" alt="banner" style="z-index:1" class="img-fluid">
        </picture>
      </div>
    </div>
  </div>
</div></code>```

But somehow is that the dots is showing numbers instead of dots , any idea how to do it? Search through all the methods/solution but the "numbers" still showing

I have attached my HTML codes, somehow that the number is showing instead of the dots .

答:
Hope this help you.</p>

```<code>.slick-dots li a.dot {
    font-size: 0;
    width: 20px;
    height: 20px;
    border-radius: 100%;
    border: 1px solid #ddd;
}
.slick-active a.dot {
    background: red;
}
</code>```

Body:
.slick-dots {
  position: absolute;
  height: 50px;
  bottom: 0px;
  width: 100%;
  left: 0px;
  padding: 0px;
  margin: 0px;
  list-style-type: none;
  text-align: center;
  font-size: 10;
}

.slick-dots li {
  position: relative;
  display: inline-block;
  width: 20px;
  height: 20px;
  margin: 0 5px;
  padding: 0;
  cursor: pointer;
}

.slick-dots li a {
  position: absolute;
  bottom: 100%;
  left: 50%;
  width: 120px;
  height: 75px;
  display: block;
  visibility: hidden;
  border: 4px solid rgba(0, 0, 0, .50);
  margin-left: -60px;
  margin-bottom: 15px;
  -webkit-transition: visibility 0.5s linear 0.5s;
  transition: visibility 0.5s linear 0.5s;
  -webkit-animation: fadeOut 0.5s both;
  animation: fadeOut 0.5s both;
}

        <picture>
          <source media="(max-width: 900px)" srcset="https://upload.wikimedia.org/wikipedia/commons/thumb/7/77/Google_Images_2015_logo.svg/1200px-Google_Images_2015_logo.svg.png">

        </picture>

        <picture>
          <source media="(max-width: 900px)" srcset="https://upload.wikimedia.org/wikipedia/commons/thumb/7/77/Google_Images_2015_logo.svg/1200px-Google_Images_2015_logo.svg.png">

        </picture>

But somehow is that the dots is showing numbers instead of dots , any idea how to do it? Search through all the methods/solution but the "numbers" still showing

I have attached my HTML codes, somehow that the number is showing instead of the dots .

Body:
Hope this help you.

.slick-dots li a.dot {
    font-size: 0;
    width: 20px;
    height: 20px;
    border-radius: 100%;
    border: 1px solid #ddd;
}
.slick-active a.dot {
    background: red;
}


问:
SAML Service Provider redirects to IDP login page
I'm trying to build an IdP using ITfoxtec. From the Service Provider's site, it will generate SAML requests and redirects them to the IdP. Now I'm on an IdP's login page, but I'm trying to understand how the ITfoxtec codes work.

```<code>[Route("Login")]
        public IActionResult Login()
        {
            var requestBinding = new Saml2RedirectBinding();
            var relyingParty = ValidateRelyingParty(ReadRelyingPartyFromLoginRequest(requestBinding));

            var saml2AuthnRequest = new Saml2AuthnRequest(config);
            try
            {
                requestBinding.Unbind(Request.ToGenericHttpRequest(), saml2AuthnRequest);

                // ****  Handle user login e.g. in GUI ****
                // Test user with session index and claims
                var sessionIndex = Guid.NewGuid().ToString();
                var claims = CreateTestUserClaims(saml2AuthnRequest.Subject?.NameID?.ID);
                var response = LoginResponse(saml2AuthnRequest.Id, Saml2StatusCodes.Success, requestBinding.RelayState, relyingParty, sessionIndex, claims);

                return response;
            }
            catch (Exception exc)
            {
#if DEBUG
                Debug.WriteLine($"Saml 2.0 Authn Request error: {exc.ToString()}\nSaml Auth Request: '{saml2AuthnRequest.XmlDocument?.OuterXml}'\nQuery String: {Request.QueryString}");
#endif
                return LoginResponse(saml2AuthnRequest.Id, Saml2StatusCodes.Responder, requestBinding.RelayState, relyingParty);
            }
        }
</code>```

How come this Login() method receives a SAML request from SP and returns SAML response right away in one method? When SP redirects to IdP, I'm expecting to land on IdP's login page with username/password fields that authenticate against my own database. Then return SAML response to SP if successful.

Please let me know if I'm misunderstanding the concept or guide me on how to implement this.

答:
You are correct about the flow and that the SAML 2.0 Authn Response are generated right away. You need to implement the login dialog and username/password validation your self as you can see in my comment // ****  Handle user login e.g. in GUI ****.

Meaning that you need to cut the Login method in half. After the first half of the Login method you need to start some kind of sequence insight the IdP where the user is authenticated. And then return to the second half of the Login method which issues the SAML 2.0 Authn Response.

Body:
I'm trying to build an IdP using ITfoxtec. From the Service Provider's site, it will generate SAML requests and redirects them to the IdP. Now I'm on an IdP's login page, but I'm trying to understand how the ITfoxtec codes work.

[Route("Login")]
        public IActionResult Login()
        {
            var requestBinding = new Saml2RedirectBinding();
            var relyingParty = ValidateRelyingParty(ReadRelyingPartyFromLoginRequest(requestBinding));

            var saml2AuthnRequest = new Saml2AuthnRequest(config);
            try
            {
                requestBinding.Unbind(Request.ToGenericHttpRequest(), saml2AuthnRequest);

                // ****  Handle user login e.g. in GUI ****
                // Test user with session index and claims
                var sessionIndex = Guid.NewGuid().ToString();
                var claims = CreateTestUserClaims(saml2AuthnRequest.Subject?.NameID?.ID);
                var response = LoginResponse(saml2AuthnRequest.Id, Saml2StatusCodes.Success, requestBinding.RelayState, relyingParty, sessionIndex, claims);

                return response;
            }
            catch (Exception exc)
            {
#if DEBUG
                Debug.WriteLine($"Saml 2.0 Authn Request error: {exc.ToString()}\nSaml Auth Request: '{saml2AuthnRequest.XmlDocument?.OuterXml}'\nQuery String: {Request.QueryString}");
#endif
                return LoginResponse(saml2AuthnRequest.Id, Saml2StatusCodes.Responder, requestBinding.RelayState, relyingParty);
            }
        }

How come this Login() method receives a SAML request from SP and returns SAML response right away in one method? When SP redirects to IdP, I'm expecting to land on IdP's login page with username/password fields that authenticate against my own database. Then return SAML response to SP if successful.

Please let me know if I'm misunderstanding the concept or guide me on how to implement this.


问:
AppEngine: Python 3 Version of Search API
Our service is evaluating steps to upgrade from python 2.7 to python 3.7. We heavily use document search api, but I cannot find any similar api for python 3.

Is there a plan to support document search api in python 3? or any available alternatives?

Thanks in advance.

Environment: appengine, python 2.7, standard environment.

答:
Host any full-text search database such as Elasticsearch on Compute Engine and access it from your service.

https://cloud.google.com/appengine/docs/standard/python/migrate-to-python3/migrating-services


问:
PHP 7.0 and MySQL start-up error "undefined symbol: mysqlnd_allocator in Unknown"
Getting this warning on a custom-compiled version of PHP7, even when running php -v.

Tried all solutions posted.  What could cause this?

PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php/20151012/pdo_mysql.so' - /usr/lib/php/20151012/pdo_mysql.so: undefined symbol: mysqlnd_allocator in Unknown on line 0

There are similar questions to this, but they are not quite the same problem - they generally relate to a missing mcrypt library. I confirmed that mycrypt is in fact loaded, as well as pdo_mysql when printing out phpinfo().

Is there something wrong with the order? Also, this is for PHP 7, which I believe has different formats for ini files.

Edit: Following instructions here for recompile.  Not too experienced in this: http://www.hashbangcode.com/blog/compiling-and-installing-php7-ubuntu

Also, removed MySQL completely with apt-get purge.  No luck with anything.

答:
Sometimes there is an issue with not loaded correctly extensions in the php.ini file.
I had similar error and it start working only after I have added these extensions before pdo_mysql to the php.ini:

```<code>extension=mysqlnd
extension=pdo
extension=pdo_mysql
</code>```

And it finally worked!

However it shows warnings that mysqlnd, PDO and pdo_mysql was loaded before, it means that pdo_mysql already enabled and can be commented out at all. For further info please check PHP Warning: Module already loaded in Unknown on line 0

Body:
Sometimes there is an issue with not loaded correctly extensions in the php.ini file.
I had similar error and it start working only after I have added these extensions before pdo_mysql to the php.ini:

extension=mysqlnd
extension=pdo
extension=pdo_mysql

And it finally worked!

However it shows warnings that mysqlnd, PDO and pdo_mysql was loaded before, it means that pdo_mysql already enabled and can be commented out at all. For further info please check PHP Warning: Module already loaded in Unknown on line 0


问:
Jquery - Accessing input element within a class by its index
I need some pointer here. I am trying to set the value of multiple input text within a class by its index value. The extra validate class is just for inline form validation and I think it is not the problem.

I was able to access multiple check boxes within a class using the same method but I can't figure this one out. Can someone please give me a hint as to what I did wrong? Thank you.

Script

```<code>//--(4) Load Delivery Cost Input Box
var tmpstr = $('#editDeliveryCost').html();
if (tmpstr != ""){
   var tmparray = tmpstr.split(',');
   for (i = 0; i < tmparray.length; ++i) {
      $('.typeDeliveryCost:eq('+(tmparray[i]-1)+')').val(tmparray[i]);
   }
</code>```

HTML

```<code><input type="text" name='cost[]' id='inp01' class="validate[required,custom[price]] typeDeliveryCost" />
<input type="text" name='cost[]' id='inp02' class="validate[required,custom[price]] typeDeliveryCost" />
<input type="text" name='cost[]' id='inp03' class="validate[required,custom[price]] typeDeliveryCost" />
<input type="text" name='cost[]' id='inp04' class="validate[required,custom[price]] typeDeliveryCost" />
</code>```

答:
change this    </p>

```<code>$('.typeDeliveryCost:eq('+(tmparray[i]-1)+')').val(tmparray[i]);
</code>```

<p>to </p>

```<code>$('.typeDeliveryCost:eq(' + i + ')').val(tmparray[i]);
</code>```

Body:
I need some pointer here. I am trying to set the value of multiple input text within a class by its index value. The extra validate class is just for inline form validation and I think it is not the problem.

I was able to access multiple check boxes within a class using the same method but I can't figure this one out. Can someone please give me a hint as to what I did wrong? Thank you.

Script

//--(4) Load Delivery Cost Input Box
var tmpstr = $('#editDeliveryCost').html();
if (tmpstr != ""){
   var tmparray = tmpstr.split(',');
   for (i = 0; i < tmparray.length; ++i) {
      $('.typeDeliveryCost:eq('+(tmparray[i]-1)+')').val(tmparray[i]);
   }

HTML

<input type="text" name='cost[]' id='inp01' class="validate[required,custom[price]] typeDeliveryCost" />
<input type="text" name='cost[]' id='inp02' class="validate[required,custom[price]] typeDeliveryCost" />
<input type="text" name='cost[]' id='inp03' class="validate[required,custom[price]] typeDeliveryCost" />
<input type="text" name='cost[]' id='inp04' class="validate[required,custom[price]] typeDeliveryCost" />

Body:
change this

$('.typeDeliveryCost:eq('+(tmparray[i]-1)+')').val(tmparray[i]);

to

$('.typeDeliveryCost:eq(' + i + ')').val(tmparray[i]);


问:
How to enable discover role when joining a channel from a peer
I am having following error when trying to execute a transaction using the Discovery service from Fabric Java SDK

```<code>org.hyperledger.fabric.sdk.exception.ServiceDiscoveryException: The channel is not configured with any peers with the 'discover' role
</code>```

I joined the channel using peer shell command, not the Fabric Java SDK. How can I configure that discover role in the channel once it is already joined?

Thanks

答:
I came up with the exact missing part of code. Hope it helps someone with a similar issue. It was just a matter of adding the required peerRoles as @david_k comments:

I had:

```<code>channel.addPeer(peer);
</code>```

and replacing it with this fixed the issue:

```<code>channel.addPeer(peer, createPeerOptions().setPeerRoles(EnumSet.of(PeerRole.SERVICE_DISCOVERY, PeerRole.LEDGER_QUERY, PeerRole.EVENT_SOURCE, PeerRole.CHAINCODE_QUERY)));
</code>```

Body:
I am having following error when trying to execute a transaction using the Discovery service from Fabric Java SDK

org.hyperledger.fabric.sdk.exception.ServiceDiscoveryException: The channel is not configured with any peers with the 'discover' role

I joined the channel using peer shell command, not the Fabric Java SDK. How can I configure that discover role in the channel once it is already joined?

Thanks

Body:
I came up with the exact missing part of code. Hope it helps someone with a similar issue. It was just a matter of adding the required peerRoles as @david_k comments:

I had:

channel.addPeer(peer);

and replacing it with this fixed the issue:

channel.addPeer(peer, createPeerOptions().setPeerRoles(EnumSet.of(PeerRole.SERVICE_DISCOVERY, PeerRole.LEDGER_QUERY, PeerRole.EVENT_SOURCE, PeerRole.CHAINCODE_QUERY)));


问:
While Loop Function after a button is pressed and stop looping when another button is pressed C#
In my Windorm Form application, I have two buttons which a loop function will begin to do the work when button1 is pressed and stop executing after button2 is pressed. How could i do this to prevent my GUI from non-responsive.
How could i insert command while(button2.clicked != true)

My code for button 1:

```<code>private async void EmoStart_Click_1(object sender, EventArgs e)
    {
        //var repeat = "true";
        string imageFilePath = "C:\\Users\\Administrator\\source\\repos\\FaceDetection\\FaceDetection\\test3.jpg";
       while (VoiceStart_Click_2 != "true")
       {
        var image = pictureBox1.Image;
        image = resizeImage(image, new Size(1209, 770));
        image.Save(imageFilePath);
        if (File.Exists(imageFilePath))
        {
            var Emo = await FaceEmotion.MakeAnalysisRequest(imageFilePath);
            if (Emo[0].FaceAttributes.Emotion.Anger >= 0.5)
            {
                EmoBox.Text = "Anger, Bad Driving Condition, Soft Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Contempt >= 0.5)
            {
                EmoBox.Text = "Contempt, Bad Driving Condition, Soft Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Disgust >= 0.5)
            {
                EmoBox.Text = "Disgust, Bad Driving Condition, Soft Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Fear >= 0.5)
            {
                EmoBox.Text = "Fear, Bad Driving Condition, Soft Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Happiness >= 0.5)
            {
                EmoBox.Text = "Happiness, Good Driving Condition";
            }
            else if (Emo[0].FaceAttributes.Emotion.Neutral >= 0.5)
            {
                EmoBox.Text = "Neutral, Good Driving Condition";
            }
            else if (Emo[0].FaceAttributes.Emotion.Sadness >= 0.5)
            {
                EmoBox.Text = "Sadness, Bad Driving Condition, Rock Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Surprise >= 0.5)
            {
                EmoBox.Text = "Happiness, Bad Driving Condition, Soft Music will be played";
            }
            else
            {
                EmoBox.Text = "Stable Condition, Good Driving Condition";
            }
        }
    }
</code>```

While for my button2 code:

```<code>private async void VoiceStart_Click_2(object sender, EventArgs e)
{
    string command = await Voice.RecognizeSpeechAsync();
    VoiceBox.Text = command;
}
</code>```

Thank you!

答:
You can use a global variable(bool is a good choice)

when VoiceStart_Click_2 change the variable

and do check the variable when EmoStart_Click_1 is clicked

```<code>if (variable==true)
{
    var Emo = await FaceEmotion.MakeAnalysisRequest(imageFilePath);
    if (Emo[0].FaceAttributes.Emotion.Anger >= 0.5)
    {
       EmoBox.Text = "Anger, Bad Driving Condition, Soft Music will be played";
    }
    ...

}
</code>```

Body:
In my Windorm Form application, I have two buttons which a loop function will begin to do the work when button1 is pressed and stop executing after button2 is pressed. How could i do this to prevent my GUI from non-responsive.
How could i insert command while(button2.clicked != true)

My code for button 1:

private async void EmoStart_Click_1(object sender, EventArgs e)
    {
        //var repeat = "true";
        string imageFilePath = "C:\\Users\\Administrator\\source\\repos\\FaceDetection\\FaceDetection\\test3.jpg";
       while (VoiceStart_Click_2 != "true")
       {
        var image = pictureBox1.Image;
        image = resizeImage(image, new Size(1209, 770));
        image.Save(imageFilePath);
        if (File.Exists(imageFilePath))
        {
            var Emo = await FaceEmotion.MakeAnalysisRequest(imageFilePath);
            if (Emo[0].FaceAttributes.Emotion.Anger >= 0.5)
            {
                EmoBox.Text = "Anger, Bad Driving Condition, Soft Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Contempt >= 0.5)
            {
                EmoBox.Text = "Contempt, Bad Driving Condition, Soft Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Disgust >= 0.5)
            {
                EmoBox.Text = "Disgust, Bad Driving Condition, Soft Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Fear >= 0.5)
            {
                EmoBox.Text = "Fear, Bad Driving Condition, Soft Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Happiness >= 0.5)
            {
                EmoBox.Text = "Happiness, Good Driving Condition";
            }
            else if (Emo[0].FaceAttributes.Emotion.Neutral >= 0.5)
            {
                EmoBox.Text = "Neutral, Good Driving Condition";
            }
            else if (Emo[0].FaceAttributes.Emotion.Sadness >= 0.5)
            {
                EmoBox.Text = "Sadness, Bad Driving Condition, Rock Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Surprise >= 0.5)
            {
                EmoBox.Text = "Happiness, Bad Driving Condition, Soft Music will be played";
            }
            else
            {
                EmoBox.Text = "Stable Condition, Good Driving Condition";
            }
        }
    }

While for my button2 code:

private async void VoiceStart_Click_2(object sender, EventArgs e)
{
    string command = await Voice.RecognizeSpeechAsync();
    VoiceBox.Text = command;
}

Thank you!

Body:
You can use a global variable(bool is a good choice)

when VoiceStart_Click_2 change the variable

and do check the variable when EmoStart_Click_1 is clicked

if (variable==true)
{
    var Emo = await FaceEmotion.MakeAnalysisRequest(imageFilePath);
    if (Emo[0].FaceAttributes.Emotion.Anger >= 0.5)
    {
       EmoBox.Text = "Anger, Bad Driving Condition, Soft Music will be played";
    }
    ...

}


问:
2 Vectors under for loop
I have a dataframe df with ID column. I am trying to make all possible combination between another vector called dates

```<code>df

ID
Asda
Dsaa
Fasd
Das

dates <- seq(as.Date("2019-12-27"), as.Date(" "), by=1)
</code>```

I have written a following for loop. But I get only below result

```<code>for (i in df$ID) {
  for (j in dates) {
    new_value <- c(i, j)
  }
}
</code>```

Result below

```<code>new_value
        ID        Date
      "Das"     "18258"
</code>```

Expected result is : Can i get all combination of ID and dates?

答:
You can use merge to get all combinations of your variables:

```<code>df <- data.frame(ID = c("Asda", "Dsaa", "Fasd", "Das"))
dates <- seq(as.Date("2019-12-27"), as.Date("2019-12-28"), by=1)

merge(df, dates, by = NULL)
</code>```

Result:

```<code>    ID          y
1 Asda 2019-12-27
2 Dsaa 2019-12-27
3 Fasd 2019-12-27
4  Das 2019-12-27
5 Asda 2019-12-28
6 Dsaa 2019-12-28
7 Fasd 2019-12-28
8  Das 2019-12-28
</code>```

Edit: For loop only

```<code>new_df <- data.frame()
for (i in df$ID) {
  for (j in dates) {
    new_df <- rbind(new_df, data.frame(ID = i, Date = j))
  }
}
</code>```

Title: 2 Vectors under for loop

Body:
I have a dataframe df with ID column. I am trying to make all possible combination between another vector called dates

df

ID
Asda
Dsaa
Fasd
Das

dates <- seq(as.Date("2019-12-27"), as.Date(" "), by=1)

I have written a following for loop. But I get only below result

for (i in df$ID) {
  for (j in dates) {
    new_value <- c(i, j)
  }
}

Result below

new_value
        ID        Date
      "Das"     "18258"

Expected result is : Can i get all combination of ID and dates?

Body:
You can use merge to get all combinations of your variables:

df <- data.frame(ID = c("Asda", "Dsaa", "Fasd", "Das"))
dates <- seq(as.Date("2019-12-27"), as.Date("2019-12-28"), by=1)

merge(df, dates, by = NULL)

Result:

    ID          y
1 Asda 2019-12-27
2 Dsaa 2019-12-27
3 Fasd 2019-12-27
4  Das 2019-12-27
5 Asda 2019-12-28
6 Dsaa 2019-12-28
7 Fasd 2019-12-28
8  Das 2019-12-28

Edit: For loop only

new_df <- data.frame()
for (i in df$ID) {
  for (j in dates) {
    new_df <- rbind(new_df, data.frame(ID = i, Date = j))
  }
}


答:
All possible combinations of ID and dates

```<code>expand.grid(df$ID,dates)
</code>```

Edit: using for loops

```<code>k=1
temp=matrix(NA,length(df$ID)*length(dates),2)
for (i in df$ID) {
    for (j in dates){
        temp[k,]=c(i,j)
        k=k+1
    }
}
</code>```

Title: 2 Vectors under for loop

Body:
All possible combinations of ID and dates

expand.grid(df$ID,dates)

Edit: using for loops

k=1
temp=matrix(NA,length(df$ID)*length(dates),2)
for (i in df$ID) {
    for (j in dates){
        temp[k,]=c(i,j)
        k=k+1
    }
}


问:
How can I convert this cURL request that send a file to an API into a PostMan request?
I have the following problem. I can perform the following request via cURL:

```<code>curl -F file=@"C:\\FE_example.xlsx" http://localhost:8080/api/comp_vibr_and_temp_tab
</code>```

and it works fine. As you can see I am attaching a file to a POST request (the expected format for the file is MultiPart). The value returned by this API is a JSON.

Using the previous cURL command it works fine but trying to perform the same request via PostMan I obtain an error.

In PostMan I set the file into the Body section. Into the Header section I set:

```<code>Content-Type: multipart/form-data
</code>```

Trying to perform the request I obtain the following error message:

```<code>{
    "timestamp": 1581890120091,
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.web.multipart.support.MissingServletRequestPartException",
    "message": "Required request part 'file' is not present",
    "path": "/api/comp_vibr_and_temp_tab"
}
</code>```

Why? What is wrong? How can I convert my cURL request into a correct PostMan one?

答: You can try above steps to resolve your problem.

Body:
I have the following problem. I can perform the following request via cURL:

curl -F file=@"C:\\FE_example.xlsx" http://localhost:8080/api/comp_vibr_and_temp_tab

and it works fine. As you can see I am attaching a file to a POST request (the expected format for the file is MultiPart). The value returned by this API is a JSON.

Using the previous cURL command it works fine but trying to perform the same request via PostMan I obtain an error.

In PostMan I set the file into the Body section. Into the Header section I set:

Content-Type: multipart/form-data

Trying to perform the request I obtain the following error message:

{
    "timestamp": 1581890120091,
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.web.multipart.support.MissingServletRequestPartException",
    "message": "Required request part 'file' is not present",
    "path": "/api/comp_vibr_and_temp_tab"
}

Why? What is wrong? How can I convert my cURL request into a correct PostMan one?


问:
How to detect Pivot View using MVVM in WP7?
basically I have a pivot control in my WP7 app that contains 3 views. On each view I'm calling 1 of my 3 different web services that I run. What I'm trying to do is call the service only when they navigate to that particular view.

It's pretty simple using the code behind because all you do is use selected index with a switch statement and you can fire certain methods accordingly. Any idea on how to accomplish this from a view model?

NOTE: I'm using MVVM Light.

UPDATE: Here's my code that I would normally use:

```<code>private void PivotItem_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        int currentPivot = ResultsPivot.SelectedIndex;
        switch (currentPivot)
        {
            case 0:
                //Fire Method 1
                break;
            case 1:
                //Fire Method 2
                break;
            case 2:
                //Fire Method 3
                break;
            default:
                //Fire default method
                break;
        }
    }
</code>```

答: I haven't used MVVM Light directly, but you should be able to bind the selected index / item to a property on the view model. When that property is changed you could do your switch.</p>

Body:
basically I have a pivot control in my WP7 app that contains 3 views. On each view I'm calling 1 of my 3 different web services that I run. What I'm trying to do is call the service only when they navigate to that particular view.

It's pretty simple using the code behind because all you do is use selected index with a switch statement and you can fire certain methods accordingly. Any idea on how to accomplish this from a view model?

NOTE: I'm using MVVM Light.

UPDATE: Here's my code that I would normally use:

private void PivotItem_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        int currentPivot = ResultsPivot.SelectedIndex;
        switch (currentPivot)
        {
            case 0:
                //Fire Method 1
                break;
            case 1:
                //Fire Method 2
                break;
            case 2:
                //Fire Method 3
                break;
            default:
                //Fire default method
                break;
        }
    }


问:
Numpy: Elegant solution to calculating output matrix of function with indefinite number of variables
I have been searching all weekend for a more elegant (read: no manual for-loop programming) solution to the following problem:

Lets assume we have a custom function f() with an indefinite number of inputs. For simplicity, let us start with two:

```<code>def f(x,y):
    return x + y
</code>```

Now I pass an array with the correct number of variables to this function:

```<code>x = np.array([x0, x1, x2, ..., xn])
y = np.array([y0, y1, y2, ..., yn])
</code>```

The answer I look for is:

```<code>z = np.array([[x0 + y0, x0 + y1, x0 + y2, ..., x0 + yn],
              [x1 + y0, x1 + y1, x1 + y2, ..., x1 + yn],
              [x2 + y0, x2 + y1, x2 + y2, ..., x2 + yn],
              ...])
</code>```

So, in summary, I am looking for a function, that I can pass another custom function to, which then calculates all possible combinations, without me having to program a ridiculous number of for-loops.

Please help me, hive mind!

Edit 1: the custom function may be of arbitrary complexity. From my real world problem, this is one example:

```<code>def f(x, y):
    return 1 - (x/2)**y*binom(y, y/2)
</code>```

Edit 2: the accepted answer works as intended. The answer of Dishin H Goyani linking to stackoverflow.com/a/32742943/6075699 produces the same result using a different path.

Thanks everyone! Stackoverflow rules!

答:
I suggest numpy array broadcasting.

Example:

```<code>import numpy as np

# initial arrays
x = np.arange(1, 15, 3)
y = np.arange(1, 6) + 100

# get them to 2d
x2 = np.atleast_2d(x)
y2 = np.atleast_2d(y).T  #y should be vertical

# simple stuff
print("sum:\n", x2 + y2)

# complicated stuff
print("complicated:\n", x2/(1+y2) + np.exp(-y2/(1+x2)))
</code>```

Body:
I have been searching all weekend for a more elegant (read: no manual for-loop programming) solution to the following problem:

Lets assume we have a custom function f() with an indefinite number of inputs. For simplicity, let us start with two:

def f(x,y):
    return x + y

Now I pass an array with the correct number of variables to this function:

x = np.array([x0, x1, x2, ..., xn])
y = np.array([y0, y1, y2, ..., yn])

The answer I look for is:

z = np.array([[x0 + y0, x0 + y1, x0 + y2, ..., x0 + yn],
              [x1 + y0, x1 + y1, x1 + y2, ..., x1 + yn],
              [x2 + y0, x2 + y1, x2 + y2, ..., x2 + yn],
              ...])

So, in summary, I am looking for a function, that I can pass another custom function to, which then calculates all possible combinations, without me having to program a ridiculous number of for-loops.

Please help me, hive mind!

Edit 1: the custom function may be of arbitrary complexity. From my real world problem, this is one example:

def f(x, y):
    return 1 - (x/2)**y*binom(y, y/2)

Edit 2: the accepted answer works as intended. The answer of Dishin H Goyani linking to stackoverflow.com/a/32742943/6075699 produces the same result using a different path.

Thanks everyone! Stackoverflow rules!

Body:
I suggest numpy array broadcasting.

Example:

import numpy as np

# initial arrays
x = np.arange(1, 15, 3)
y = np.arange(1, 6) + 100

# get them to 2d
x2 = np.atleast_2d(x)
y2 = np.atleast_2d(y).T  #y should be vertical

# simple stuff
print("sum:\n", x2 + y2)

# complicated stuff
print("complicated:\n", x2/(1+y2) + np.exp(-y2/(1+x2)))


问:
Why VS code shows it's invalid syntax for a python code using abc Module - python3.8.0
See code below, type the same as written in Book Data Structur and Algorthm in Python, I am new to programming, can someone help?</p>

```<code>from abc import ABCMeta, abstractmethod

class Sequence(metaclass=ABCMeta):

    @abstractmethod
    def __len__(self):

    @abstractmethod
    def __getitem__(self, j): **# Here there is red wave line under 'def'**

    def __contains__(self, val):
        for j in range(len(self)):
            if self[j] == val:
                return True
        return False

    def index(self, val):
        for j in range(len(self)):
            if self[j] == val:
                return j
        raise ValueError('value not in sequence')

    def count(self, val):
        k = 0
        for j in range(len(self)):
            if self[j] == val:
                k += 1
        return k
</code>```

答:
In python
Indentation is important also there is # used for comment

please go through the following code which is error-free

```<code>from abc import ABCMeta, abstractmethod

class Sequence(metaclass=ABCMeta):

    @abstractmethod
    def __len__(self):
        pass

    @abstractmethod
    def __getitem__(self, j):
        #**# Here there is red wave line under 'def'**
        pass
    def __contains__(self, val):

        for j in range(len(self)):
            if self[j] == val:
                return True
        return False

    def index(self, val):
        for j in range(len(self)):
            if self[j] == val:
                return j
        raise ValueError('value not in sequence')

    def count(self, val):
        k = 0
        for j in range(len(self)):
            if self[j] == val:
                k += 1
        return ks
</code>```

learning python for beginning use: learn python the hard way

or use python learning

Body:
See code below, type the same as written in Book Data Structur and Algorthm in Python, I am new to programming, can someone help?

from abc import ABCMeta, abstractmethod

class Sequence(metaclass=ABCMeta):

    @abstractmethod
    def __len__(self):

    @abstractmethod
    def __getitem__(self, j): **# Here there is red wave line under 'def'**

    def __contains__(self, val):
        for j in range(len(self)):
            if self[j] == val:
                return True
        return False

    def index(self, val):
        for j in range(len(self)):
            if self[j] == val:
                return j
        raise ValueError('value not in sequence')

    def count(self, val):
        k = 0
        for j in range(len(self)):
            if self[j] == val:
                k += 1
        return k

Body:
In python
Indentation is important also there is # used for comment

please go through the following code which is error-free

from abc import ABCMeta, abstractmethod

class Sequence(metaclass=ABCMeta):

    @abstractmethod
    def __len__(self):
        pass

    @abstractmethod
    def __getitem__(self, j):
        #**# Here there is red wave line under 'def'**
        pass
    def __contains__(self, val):

        for j in range(len(self)):
            if self[j] == val:
                return True
        return False

    def index(self, val):
        for j in range(len(self)):
            if self[j] == val:
                return j
        raise ValueError('value not in sequence')

    def count(self, val):
        k = 0
        for j in range(len(self)):
            if self[j] == val:
                k += 1
        return ks

learning python for beginning use: learn python the hard way

or use python learning


问:
Azure functions output bindings parameter name does not included in context.bindings
I use Iothub trigger functions , and I want to set Cosmosdb as output . When its done, I logged out context.bindings only shows {"IoTHubMessages":["Test Message"]}

did i miss something?

any suggestion would be appreciated, Thanks

EDITED :
functions.json

index.js

as third parameter, it is undefined.

答:
The output binding is not initialized before we create it by declaring it in index.js

If the comsumer group has reached the limit of connections , It would not proceed to receive data from Iothub input


问:
OpenIdConnectProtocolException: Message contains error: 'invalid_request', error_description: 'AADB2C90079:
I am using the Azure AD B2C authentication in my ASP .NET Core web app. I also want to get notification after successful authentication of user so that I can add custom roles and for that I am trying to register OnAuthorizationCodeReceived callback. But as soon as I do it I am getting following exception...

OpenIdConnectProtocolException: Message contains error: 'invalid_request', error_description: 'AADB2C90079: Clients must send a client_secret when redeeming a confidential grant.

The original code in the Setup.cs which works is...

```<code>    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(AzureADB2CDefaults.AuthenticationScheme)
            .AddAzureADB2C(options => Configuration.Bind("AzureAdB2C", options));

        services.AddControllersWithViews();
        services.AddRazorPages();
    }
</code>```

But when I add following code in ConfigureServices() function...

```<code>        services.Configure<OpenIdConnectOptions>(AzureADB2CDefaults.OpenIdScheme, options =>
        {
            options.ResponseType = OpenIdConnectResponseType.Code;
            options.Events = new OpenIdConnectEvents
            {
                OnAuthorizationCodeReceived = OnAuthorizationCodeReceived,
            };
        });

public async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
{
}
</code>```

It starts generating above mentioned exception when I click on Signin button. Looks like I am able to authenticate and I get OnAuthorizationCodeReceived callback too. But once control returns from OnAuthorizationCodeReceived that exception occurs with following stack...

Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler.RedeemAuthorizationCodeAsync(OpenIdConnectMessage tokenEndpointRequest)
Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler.HandleRemoteAuthenticateAsync()

Please let me know what's wrong here?

答:
You are using the OAuth 2.0 authorization code flow since you are setting code to ResponseType in OIDC config :

```<code>options.ResponseType = OpenIdConnectResponseType.Code;
</code>```

Please check this document , code flow need client_secretwhen requesting ancess token if your app is  web apps or web APIs .

If you want to add custom roles after login , OnTokenValidated event offers you the chance to modify the ClaimsIdentity obtained from the incoming token , code below is for your reference :

```<code>options.Events = new OpenIdConnectEvents
{
    OnTokenValidated = ctx =>
    {
        //query the database to get the role

        // add claims
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Role, "Admin")
        };
        var appIdentity = new ClaimsIdentity(claims);

        ctx.Principal.AddIdentity(appIdentity);

        return Task.CompletedTask;
    },
};
</code>```

But if you want to query the Microsoft Graph , then use OnAuthorizationCodeReceived event and use MSAL to get access token for Microsoft Graph .

Body:
I am using the Azure AD B2C authentication in my ASP .NET Core web app. I also want to get notification after successful authentication of user so that I can add custom roles and for that I am trying to register OnAuthorizationCodeReceived callback. But as soon as I do it I am getting following exception...

OpenIdConnectProtocolException: Message contains error: 'invalid_request', error_description: 'AADB2C90079: Clients must send a client_secret when redeeming a confidential grant.

The original code in the Setup.cs which works is...

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(AzureADB2CDefaults.AuthenticationScheme)
            .AddAzureADB2C(options => Configuration.Bind("AzureAdB2C", options));

        services.AddControllersWithViews();
        services.AddRazorPages();
    }

But when I add following code in ConfigureServices() function...

        services.Configure<OpenIdConnectOptions>(AzureADB2CDefaults.OpenIdScheme, options =>
        {
            options.ResponseType = OpenIdConnectResponseType.Code;
            options.Events = new OpenIdConnectEvents
            {
                OnAuthorizationCodeReceived = OnAuthorizationCodeReceived,
            };
        });

public async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
{
}

It starts generating above mentioned exception when I click on Signin button. Looks like I am able to authenticate and I get OnAuthorizationCodeReceived callback too. But once control returns from OnAuthorizationCodeReceived that exception occurs with following stack...

Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler.RedeemAuthorizationCodeAsync(OpenIdConnectMessage tokenEndpointRequest)
Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler.HandleRemoteAuthenticateAsync()

Please let me know what's wrong here?

Body:
You are using the OAuth 2.0 authorization code flow since you are setting code to ResponseType in OIDC config :

options.ResponseType = OpenIdConnectResponseType.Code;

Please check this document , code flow need client_secretwhen requesting ancess token if your app is  web apps or web APIs .

If you want to add custom roles after login , OnTokenValidated event offers you the chance to modify the ClaimsIdentity obtained from the incoming token , code below is for your reference :

options.Events = new OpenIdConnectEvents
{
    OnTokenValidated = ctx =>
    {
        //query the database to get the role

        // add claims
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Role, "Admin")
        };
        var appIdentity = new ClaimsIdentity(claims);

        ctx.Principal.AddIdentity(appIdentity);

        return Task.CompletedTask;
    },
};

But if you want to query the Microsoft Graph , then use OnAuthorizationCodeReceived event and use MSAL to get access token for Microsoft Graph .


问:
PHP : Failed to delete multiple selected data
Currently, I created a system that enables the user to delete multiple data by using the checkbox.

The step is like this:

1) user select team, time before and time after at dashboard.php. The user click button 'Search' to display the result. The display result use AJAX. AJAX will redirect to range.php

2) User can select any data row that displays and delete.

My problem is, delete function is failed although I do the correct step and code. Below is the current code:

range.php

```<code>    <?php

    require_once "../../../config/configPDO.php";
    require_once "../../../config/check.php";

    $email = $_SESSION['login_user'];

    if(isset($_POST["From"], $_POST["to"], $_POST["team"]))
    {

    $result = '';
    $query = "SELECT * FROM ot_report LEFT JOIN ot_users ON ot_report.badgeid = ot_users.badgeid WHERE ot_users.team_id = '".$_POST['team']."' AND report_date BETWEEN '".$_POST["From"]."' AND '".$_POST["to"]."' ORDER BY ot_report.report_date DESC";
    $sql = $conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
    $sql -> execute();

    if(isset($_POST['save'])){
        $checkbox = $_POST['check'];
        for($i=0;$i<count($checkbox);$i++){
            $del_id = $checkbox[$i];

            $sql2 = "DELETE FROM ot_report WHERE report_id=:report_id";
            $query2 = $conn->prepare($sql2);
            $query2->execute(array(':report_id' => $del_id));

            header("Location: dashboard.php");
        }
    }

    if($sql->rowCount() > 0)
    {
        echo'

        <form method="post" action="">
        <div><a href="../pdf.php?from='.$_POST["From"].'&to='.$_POST["to"].' &team='.$_POST["team"].'" target="_blank"><u>PDF View</u></a></div><br>
        <div class="row" style="height: 300px; overflow-y: scroll;">
        <div class="col-lg-12 grid-margin stretch-card">
        <table class = "table-bordered" width = "100%">
        <thead>
        <tr>
        <th width = "10%"><input type="checkbox" id="checkAl"> All</th>
        <th width = "3%">id</th>
        <th width = "15%">Date</th>
        <th width = "25%">Supervisor</th>
        <th width = "30%">Task Name</th>
        <th width = "10%">Status</th>
        <th width = "7%">Action</th>
        </tr>
        </thead>
        <tbody>';
        $i=0;
        while($row = $sql->fetch(PDO::FETCH_ASSOC))
        {
            $datereport = $row['report_date'];
            $datereport2 = strtotime($datereport);
            $report_date = date('d M Y', $datereport2);

            $status=$row['report_status'];
            if($status=="Pending")
            {
                $color="color:blue";
            }
            else
            {
                $color="color:green";
            }

            if ($row['ot_start'] == '00:00:00'){
                $ot_start = '-';
            }else{}

            if ($row['ot_end'] == '00:00:00'){
                $ot_end = '-';
            }else{}

            echo'<tr>';
                echo '<td><input type="checkbox" id="checkItem" name="check[]" value='.$row['report_id'].'></td>';
                echo '<td>'.$row["report_id"].'</td>';
                echo '<td>'.$report_date.'</td>';
                echo '<td>'.$row["fullname"].'</td>';
                echo '<td>'.$row["task_name"].'</td>';
                echo '<td align="center" style='.$color.'><strong>'.$status.'</strong></td>';
                echo '<td align="center">';
                echo '<a class="btn-view btn-primary btn-sm" href="view_task/view_task.php?report_id='. $row["report_id"] .'" data-toggle="tooltip">View</a>';
                echo '<a class="btn-view btn-danger btn-sm" href="delete.php?report_id='. $row["report_id"] .'" onClick=\'return confirm("Do you want to remove team?")\'>Delete</a></td>';
                echo '</td>';

            echo '</tr>';
            $i++;

        }
            echo '<tr>';
                echo '<td><p align="center"><button type="submit" class="btn-danger btn-sm" name="save">DELETE</button></p></td>';
            echo '</tr>';
            echo '</form>';

    }
    else
    {
        echo '
        <table class = "table-bordered" width = "100%">
        <thead>
        <tr>
        <th width = "5%">id</th>
        <th width = "12%">Date</th>
        <th width = "29%">Supervisor</th>
        <th width = "23%">Task Name</th>
        <th width = "7%">From</th>
        <th width = "7%">To</th>
        <th width = "10%">Status</th>
        <th width = "7%">Action</th>
        </tr>
        <tr>
        <td colspan="8">No report found</td>
        </tr>';
    }
    echo '</body></table></div></div>';

    }

    ?>

    <script>
    $("#checkAl").click(function () {
    $('input:checkbox').not(this).prop('checked', this.checked);
    });
    </script>
</code>```

Can anyone knows how to solve the problem?

答:
```<code>$sql2 = "DELETE FROM ot_report WHERE report_id=:report_id";
</code>```

Try changing this to:

```<code>$query = "DELETE FROM ot_report WHERE report_id LIKE ?";
$sql2 = $conn->prepare($query);
$sql2->bind_param("i", $del_id);
$sql2->execute();
</code>```

Body:
Currently, I created a system that enables the user to delete multiple data by using the checkbox.

The step is like this:

1) user select team, time before and time after at dashboard.php. The user click button 'Search' to display the result. The display result use AJAX. AJAX will redirect to range.php

2) User can select any data row that displays and delete.

My problem is, delete function is failed although I do the correct step and code. Below is the current code:

range.php

    <?php

    require_once "../../../config/configPDO.php";
    require_once "../../../config/check.php";

    $email = $_SESSION['login_user'];

    if(isset($_POST["From"], $_POST["to"], $_POST["team"]))
    {

    $result = '';
    $query = "SELECT * FROM ot_report LEFT JOIN ot_users ON ot_report.badgeid = ot_users.badgeid WHERE ot_users.team_id = '".$_POST['team']."' AND report_date BETWEEN '".$_POST["From"]."' AND '".$_POST["to"]."' ORDER BY ot_report.report_date DESC";
    $sql = $conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
    $sql -> execute();

    if(isset($_POST['save'])){
        $checkbox = $_POST['check'];
        for($i=0;$i<count($checkbox);$i++){
            $del_id = $checkbox[$i];

            $sql2 = "DELETE FROM ot_report WHERE report_id=:report_id";
            $query2 = $conn->prepare($sql2);
            $query2->execute(array(':report_id' => $del_id));

            header("Location: dashboard.php");
        }
    }

    if($sql->rowCount() > 0)
    {
        echo'

        <form method="post" action="">

PDF View

        <input type="checkbox" id="checkAl"> All
        id
        Date
        Supervisor
        Task Name
        Status
        Action

';
        $i=0;
        while($row = $sql->fetch(PDO::FETCH_ASSOC))
        {
            $datereport = $row['report_date'];
            $datereport2 = strtotime($datereport);
            $report_date = date('d M Y', $datereport2);

            $status=$row['report_status'];
            if($status=="Pending")
            {
                $color="color:blue";
            }
            else
            {
                $color="color:green";
            }

            if ($row['ot_start'] == '00:00:00'){
                $ot_start = '-';
            }else{}

            if ($row['ot_end'] == '00:00:00'){
                $ot_end = '-';
            }else{}

            echo'
';
                echo '<input type="checkbox" id="checkItem" name="check[]" value='.$row['report_id'].'>	';
                echo ''.$row["report_id"].'	';
                echo ''.$report_date.'	';
                echo ''.$row["fullname"].'	';
                echo ''.$row["task_name"].'	';
                echo ''.$status.'	';
                echo '';
                echo 'View';
                echo 'Delete	';
                echo '	';

            echo '
';
            $i++;

        }
            echo '
';
                echo '
<button type="submit" class="btn-danger btn-sm" name="save">DELETE</button>
	';
            echo '
';
            echo '</form>';

    }
    else
    {
        echo '

        id
        Date
        Supervisor
        Task Name
        From
        To
        Status
        Action

        No report found

';
    }
    echo '

';

    }

    ?>

Can anyone knows how to solve the problem?

Body:
$sql2 = "DELETE FROM ot_report WHERE report_id=:report_id";

Try changing this to:

$query = "DELETE FROM ot_report WHERE report_id LIKE ?";
$sql2 = $conn->prepare($query);
$sql2->bind_param("i", $del_id);
$sql2->execute();


问:
problem in the output of query - php+json
```<code>function tableOne() {

        $query = mysql_query("SELECT valor FROM grafico") or die(mysql_error());
        $i = 0;
        while($row = mysql_fetch_assoc($query)) {
            $arr[] = array($row[valor]);
            ++$i;
        }
        echo json_encode($arr);
    }
}
</code>```

the output will be

[["15573"],["31978"],["11227"],["5752"],["20817"],["32182"]]

i need something like:

```<code>["15573","31978","11227","5752","20817","32182","10935"]
</code>```

i tried some changes in the code but the output is not what i want.

thanks

答:
```<code>$query = mysql_query("SELECT valor FROM grafico") or die(mysql_error());

$arr = array();
while ($row = mysql_fetch_assoc($query)) {
    $arr[] = $row['valor'];  // get rid of the array() wrapper
}

echo json_encode($arr);
</code>```

Body:
function tableOne() {

        $query = mysql_query("SELECT valor FROM grafico") or die(mysql_error());
        $i = 0;
        while($row = mysql_fetch_assoc($query)) {
            $arr[] = array($row[valor]);
            ++$i;
        }
        echo json_encode($arr);
    }
}

the output will be

[["15573"],["31978"],["11227"],["5752"],["20817"],["32182"]]

i need something like:

["15573","31978","11227","5752","20817","32182","10935"]

i tried some changes in the code but the output is not what i want.

thanks