问:
Setting unique ID to a table cell created in JavaScript from a JSON file
I create table cells and rows in JavaScript and add information from JSON file in table cells. I assign a unique id to table cells in my code but I get error that the ids are undefined and when I want to use them later on the ids are "blank".

I can't understand why this happens! Note that the table gets created and everything shows as i will. Below you can see my code and other relevant information, please no jQuery, thanks!

HTML:

```<code><div id="info">
    <table id="country">
    </table>
</div>
</code>```

JavaScript:

```<code>            document.getElementById("country").innerHTML = "";
            for (var i = 0; i < jsonData.api.countries.length; i = i + 2) {
                document.getElementById("country").innerHTML += "<tr><td id = '" + jsonData.api.countries[i].code + "' > " + "<img src=" + jsonData.api.countries[i].flag + ">" + "<p>" + jsonData.api.countries[i].country + "</p>" + "</td>" +
                    "<td id = '" + jsonData.api.countries[i + 1].code + "' > " + "<img src=" + jsonData.api.countries[i + 1].flag + ">" + "<p>" + jsonData.api.countries[i + 1].country + "</p>" + "</td>"
                    +"</tr>";

                }
</code>```

The error that i get in console log:

```<code>Uncaught TypeError: Cannot read property 'code' of undefined
at XMLHttpRequest.myfunction
</code>```

Here is a picture of how the html looks like in page elements:

Sample of jsonfile:

答: Cannot read property 'x' of undefined means that you're trying to access a property of a null object. Try to log jsonData.api.countries[i+1]. My guess is that once you reach the last index of your for loop, you try to access the i+1 object that doesn't exist. You may want to continue your for loop until jsonData.api.countries.length-1 instead.

Body:
I create table cells and rows in JavaScript and add information from JSON file in table cells. I assign a unique id to table cells in my code but I get error that the ids are undefined and when I want to use them later on the ids are "blank".

I can't understand why this happens! Note that the table gets created and everything shows as i will. Below you can see my code and other relevant information, please no jQuery, thanks!

HTML:

JavaScript:

            document.getElementById("country").innerHTML = "";
            for (var i = 0; i < jsonData.api.countries.length; i = i + 2) {
                document.getElementById("country").innerHTML += "
 " + "" + "
" + jsonData.api.countries[i].country + "
" + "	" +
                    " " + "" + "
" + jsonData.api.countries[i + 1].country + "
" + "	"
                    +"
";

                }

The error that i get in console log:

Uncaught TypeError: Cannot read property 'code' of undefined
at XMLHttpRequest.myfunction

Here is a picture of how the html looks like in page elements:

Sample of jsonfile:


来源: stackexchange

问:
searching in n 2-dimensional arrays
Help with how to implement searching on n 2-dimenssional arrays. To be more specific:
If I have 6 tables and I am putting these into a 2-dimensional array.I will provide a value say 10 like how val=0 here. I need to search from these tables all the combination values that make up 10. The value will be computed taking values from all these tables.</p>

```<code>public static int Main() {
  int[] a = {2,1,4,7};
  int[] b = {3,-3,-8,0};
  int[] c = {-1,-4,-7,6};
  int sum;
  int i; int j;  int k;
  int val = 0;
  for(i = 0; i < 4; i++) {
    for(j = 0;j<4;j++) {
      for(k = 0;k<4;k++) {
        sum = a[i]* b[j]* c[k];

        if(sum == val)
          System.out.printf("%d  %d  %d\n",a[i],b[j],c[k]);
      }
    }
  }
}
</code>```

答:
Following will be the code you require:

(The solution includes recursion making your problem go easier)

```<code>private ArrayList numbers = new ArrayList();

public void CalculateSum(int tableNumber)
{
    if(!Tables.isLast(tableNumber))
    {
        int[][] a = Tables.Get(tableNumber);
        for(int y = 0; y < a.length; y++)
        {
            for(int x = 0; x < a[y].length; x++)
            {
                numbers.add(a[y][x]);
                CalculateSum(tableNumber + 1);
                numbers.remove(tableNumber - 1);
            }
        }
    }else
    {
        int[][] a = Tables.Get(tableNumber);
        for(int y = 0; y < a.length; y++)
        {
            for(int x = 0; x < a[y].length; x++)
            {
                if((sum(numbers) + a[y][x]) == checkValue)
                {
                    PrintNumbers(numbers);
                    System.out.print(a[y][x]);
                    System.out.println();
                }
            }
        }
    }
}
</code>```

You need to implement a class ('Tables' as my solution) write methods:

boolean isLast(int tableNo): to check whether the given table is the last table your tables list

int[][] Get(int tableNo): to get the table with the specified index

Also the method sum should sum the values in the numbers ArrayList.
PrintNumbers method should print the numbers in the numbers ArrayList in a row.
checkValue is the value you want to check.

Hope this helps....

Please write if you want any clarification on this algorithm.

ContentLicense: CC BY-SA 3.0

Title: searching in n 2-dimensional arrays

Body:
Help with how to implement searching on n 2-dimenssional arrays. To be more specific:
If I have 6 tables and I am putting these into a 2-dimensional array.I will provide a value say 10 like how val=0 here. I need to search from these tables all the combination values that make up 10. The value will be computed taking values from all these tables.

public static int Main() {
  int[] a = {2,1,4,7};
  int[] b = {3,-3,-8,0};
  int[] c = {-1,-4,-7,6};
  int sum;
  int i; int j;  int k;
  int val = 0;
  for(i = 0; i < 4; i++) {
    for(j = 0;j<4;j++) {
      for(k = 0;k<4;k++) {
        sum = a[i]* b[j]* c[k];

        if(sum == val)
          System.out.printf("%d  %d  %d\n",a[i],b[j],c[k]);
      }
    }
  }
}

Body:
Following will be the code you require:

(The solution includes recursion making your problem go easier)

private ArrayList numbers = new ArrayList();

public void CalculateSum(int tableNumber)
{
    if(!Tables.isLast(tableNumber))
    {
        int[][] a = Tables.Get(tableNumber);
        for(int y = 0; y < a.length; y++)
        {
            for(int x = 0; x < a[y].length; x++)
            {
                numbers.add(a[y][x]);
                CalculateSum(tableNumber + 1);
                numbers.remove(tableNumber - 1);
            }
        }
    }else
    {
        int[][] a = Tables.Get(tableNumber);
        for(int y = 0; y < a.length; y++)
        {
            for(int x = 0; x < a[y].length; x++)
            {
                if((sum(numbers) + a[y][x]) == checkValue)
                {
                    PrintNumbers(numbers);
                    System.out.print(a[y][x]);
                    System.out.println();
                }
            }
        }
    }
}

You need to implement a class ('Tables' as my solution) write methods:

boolean isLast(int tableNo): to check whether the given table is the last table your tables list

int[][] Get(int tableNo): to get the table with the specified index

Also the method sum should sum the values in the numbers ArrayList.
PrintNumbers method should print the numbers in the numbers ArrayList in a row.
checkValue is the value you want to check.

Hope this helps....

Please write if you want any clarification on this algorithm.


问:
Rename rownames
I would like to rename row names by removing common part of a row name

```<code>          a b  c
CDA_Part  1 4  4
CDZ_Part  3 4  4
CDX_Part  1 4  4

</code>```

result

```<code>     a b  c
CDA  1 4  4
CDZ  3 4  4
CDX  1 4  4
</code>```

答:
You can try this approach, you can use Reduce with intersect to determine the common parts in the name, Note I am assuming here that you have structure like below in your dataset, where underscore is a separator between two words. This solution will work with both word_commonpart or commonpart_word, like in the example below.

Logic:
Using strsplit, split-ted the column basis underscore(not eating underscore as well, so used look around zero width assertions), now using Reduce to find intersection between the strings of all rownames. Those found are then pasted as regex with pipe separated items and replaced by Nothing using gsub.

Input:

```<code>structure(list(a = 1:4, b = 4:7), class = "data.frame", row.names = c("CDA_Part",
"CDZ_Part", "CDX_Part", "Part_ABC"))
</code>```

Solution:

```<code>red <- Reduce('intersect', strsplit(rownames(df),"(?=_)",perl=T))
##1. determining the common parts
e <- expand.grid(red, red)
##2. getting all the combinations of underscores and the remaining parts
rownames(df) <- gsub(paste0(do.call('paste0', e[e$Var1!=e$Var2,]), collapse = "|"), '', rownames(df))
##3. filtering only those combinations which are different and pasting together using do.call
##4. using paste0 to get regex seperated by pipe
##5.replacing the common parts with nothing here
</code>```

Output:

```<code>> df
#        a b
#    CDA 1 4
#    CDZ 2 5
#    CDX 3 6
#    ABC 4 7
</code>```

ContentLicense: CC BY-SA 4.0

Title: Rename rownames

Body:
I would like to rename row names by removing common part of a row name

          a b  c
CDA_Part  1 4  4
CDZ_Part  3 4  4
CDX_Part  1 4  4

result

     a b  c
CDA  1 4  4
CDZ  3 4  4
CDX  1 4  4

Body:
You can try this approach, you can use Reduce with intersect to determine the common parts in the name, Note I am assuming here that you have structure like below in your dataset, where underscore is a separator between two words. This solution will work with both word_commonpart or commonpart_word, like in the example below.

Logic:
Using strsplit, split-ted the column basis underscore(not eating underscore as well, so used look around zero width assertions), now using Reduce to find intersection between the strings of all rownames. Those found are then pasted as regex with pipe separated items and replaced by Nothing using gsub.

Input:

structure(list(a = 1:4, b = 4:7), class = "data.frame", row.names = c("CDA_Part",
"CDZ_Part", "CDX_Part", "Part_ABC"))

Solution:

red <- Reduce('intersect', strsplit(rownames(df),"(?=_)",perl=T))
##1. determining the common parts
e <- expand.grid(red, red)
##2. getting all the combinations of underscores and the remaining parts
rownames(df) <- gsub(paste0(do.call('paste0', e[e$Var1!=e$Var2,]), collapse = "|"), '', rownames(df))
##3. filtering only those combinations which are different and pasting together using do.call
##4. using paste0 to get regex seperated by pipe
##5.replacing the common parts with nothing here

Output:

> df
#        a b
#    CDA 1 4
#    CDZ 2 5
#    CDX 3 6
#    ABC 4 7


问:
SwiftUI load data from Firebase to TextView
I have a Swift5 project but i decided that it would be easier to build only one of it's screen with SwiftUI.

The problem is that i don't know anything about SwiftUI so i am sorry if my question is stupid lol.

There is a TextView on the screen and i would like to load the text data from firebase.

My problem is that i can't use the loaded data in the TextView.

Can someone help me how i can use the function's variable in my VStack ( if its even possible )?

I tried putting the function in the VStack but it gave me some error.

Here is my code:

```<code> var body: some View {
        List {
            VStack {
                Text("Just some dummy data, this is not important.")
                // i want the "text" variable from loadData() to be in this Text
            }
        }.onAppear {
            func loadData() {
                guard let userdef = userdefStr(forKey: "didSelect") else { return }

                self.db.collection("news").whereField("title", isEqualTo: userdef)
                    .getDocuments() { (querySnapshot, err) in
                        if let err = err {
                            print("Error getting documents: \(err)")
                        } else {
                            for document in querySnapshot!.documents {

                               let text = document.data()["text"] as? String ?? ""
                                // this variable should be in the VStack's Text
                                print("text: \(text)")
                                Text(text)
                            }
                        }
                }
            }
            // i think this is how i can call the loadData function,maybe i am wrong
            loadData()
        }
}
</code>```

答:
The answer for my question is called 'SwiftUI state variables'.

I had to make a new State variable:

@State var text = "Just some dummy data, this is not important."

In the VStack: Text(text)

Ad lastly after the let text = document.data()["text"] as? String ?? "" i put self.text = description

Body:
I have a Swift5 project but i decided that it would be easier to build only one of it's screen with SwiftUI.

The problem is that i don't know anything about SwiftUI so i am sorry if my question is stupid lol.

There is a TextView on the screen and i would like to load the text data from firebase.

My problem is that i can't use the loaded data in the TextView.

Can someone help me how i can use the function's variable in my VStack ( if its even possible )?

I tried putting the function in the VStack but it gave me some error.

Here is my code:

 var body: some View {
        List {
            VStack {
                Text("Just some dummy data, this is not important.")
                // i want the "text" variable from loadData() to be in this Text
            }
        }.onAppear {
            func loadData() {
                guard let userdef = userdefStr(forKey: "didSelect") else { return }

                self.db.collection("news").whereField("title", isEqualTo: userdef)
                    .getDocuments() { (querySnapshot, err) in
                        if let err = err {
                            print("Error getting documents: \(err)")
                        } else {
                            for document in querySnapshot!.documents {

                               let text = document.data()["text"] as? String ?? ""
                                // this variable should be in the VStack's Text
                                print("text: \(text)")
                                Text(text)
                            }
                        }
                }
            }
            // i think this is how i can call the loadData function,maybe i am wrong
            loadData()
        }
}


问:
How to create a sign in method using firestore database and firebase authentication
Hi im making a app with a register page where the user enters email, password, shared secret and then a sign in page. Using firestore i store the users shared secret which works fine. I also use the firebase authentication method for email and password. The issue i have is on the sign up page using the firebase authentication signInWithEmailAndPassword method i can only call the email and password. How would i go about checking the shared secret of the user as well as the email and password?

thanks for any help

答: When using email and password based sign-in, Firebase Authentication only lets you use that email and password pair to authenticate the user.  It has no concept of a shared secret.  If you want to check additional data, you will have to do that after the user is signed in, and decide what to do if the data doesn't match.</p>


问:
Setting environment variables package.json in Windows 10
UPDATE: As it is explained in the question, this is not a duplicate because I have already tried adding the set keyword before the environment variable and that did not solve the problem.

I am in the process of learning node and typing examples from a book. The first examples deal with showing how the "http" module works and how to create a server to listen to requests. At some point the book asks to add the following line to the scripts section of the package.json file:

"server": "SERVERPORT=3002 node ./fiboserver"

When I try to run the example with npm run server I get the following error message:

'SERVERPORT' is not recognized as an internal or external command

I haven't been able to find any answer on the internet, at most I found that I could try:

"server": "set SERVERPORT=3002 node ./fiboserver"

But that doesn't help either, the only difference is that instead of the error message I get the command prompt again so apparently the server is never run.

I believe the author used a Linux machine, I am using a Windows 10 laptop.

I am really committed to learn Node and my line of work is on Windows environments. I believe that setting environment variables on package.json is important so I could really use some help in figuring this out.

Thank you.

答:
I've gone through the same problem and used one of the following methods.

Method 1

If I run (without using the npm wrapper script)

```<code>HOST=0.0.0.0 PORT=8000 ./node_modules/.bin/react-scripts start
</code>```

it works fine. As Quentin says,

Must be something to do with how npm shells out then

To fix it, I've gone to package.json and changed the "start" script to

```<code>"start": "./node_modules/.bin/react-scripts start",
</code>```

Then npm start works fine.

Method 2

Use the cross-env package.

For that install it using the following command

```<code>npm i cross-env
</code>```

then go to package.json and change it to

```<code>"start": "cross-env ./node_modules/.bin/react-scripts start",
</code>```

And then running npm start will also work fine:

Body:
I've gone through the same problem and used one of the following methods.

Method 1

If I run (without using the npm wrapper script)

HOST=0.0.0.0 PORT=8000 ./node_modules/.bin/react-scripts start

it works fine. As Quentin says,

Must be something to do with how npm shells out then

To fix it, I've gone to package.json and changed the "start" script to

"start": "./node_modules/.bin/react-scripts start",

Then npm start works fine.

Method 2

Use the cross-env package.

For that install it using the following command

npm i cross-env

then go to package.json and change it to

"start": "cross-env ./node_modules/.bin/react-scripts start",

And then running npm start will also work fine:


问:
how to crop a zoomed image using jquery
I have to make a customized avatar in which i need to zoom image and crop that using jquery
i found many plugins for zooming and cropping separately but precisely none for both . the server side i use is PHP.

答:
Use

imagemagick crop

http://pecl.php.net/package/imagick

Title: how to crop a zoomed image using jquery


问:
error: Object literal may only specify known properties in angular
I'm going crazy for this error:

```<code>Object literal may only specify known properties, and 'brand' does not exist in type 'BrandCB[]'.
</code>```

I don't know what's happen. How to solve this issue?
this is the code:
gallery.component.ts

```<code>import { CarsService } from '../services/cars.service';
import { Car } from './../models/car';
import { Component, OnInit } from '@angular/core';
import { BrandCB } from '../models/brandCB';

@Component({
  selector: 'app-gallery',
  templateUrl: './gallery.component.html',
  styleUrls: ['./gallery.component.css']
})
export class GalleryComponent implements OnInit {

  cars:Car[];
  brands:BrandCB[];
  selectedBrand:string;
  observableCars;
  observableBrands;

  constructor(public carsService: CarsService) {

  }

  ngOnInit() {
    this.getCars('all');
    this.observableBrands = this.carsService.getBrands().subscribe( (data:any) => {
      this.brands = {brand:data['brand'], checked:'false'}; //this is the error row
      console.table(data);
    });
  }

  onOptionsSelected(event: { target: { filter: any; }; }){
    this.getCars(this.selectedBrand)
  }

  getCars(filter){

    this.observableCars = this.carsService.getCars().subscribe(data => {

      if(filter!="all"){
        this.cars = data.filter( car => car.brand == this.selectedBrand);
      }else{
        this.cars = data;
      }

    });
  }

  a(event){
    let name = event.target.name;
    let checked = event.target.checked;

    if(name=='all'){
      if(checked==true){
        //uncheck tutti gli altri
      }
    } else {
      // filtra in base alle caselle checked
        // crea un array di checked items
    }

  }

  ngOnDestroy(){
    this.observableCars.unsubscribe();
    this.observableBrands.unsubscribe();
  }
}
</code>```

brandCB.ts

```<code>export class BrandCB {
    brand:any;
    checked:boolean;
}
</code>```

StackOverflow is telling me that my post is mostly code and i should write something else, so I m doing, bla bla bla and more bla bla bla. Have you seen the accident outside?

答:
As your line of error shows, you are trying to assign an object to array. Basically you need to push your brandData in brands array instead of assigning it.

Try this line

```<code>this.brands = [{brand:data['brand'], checked:'false'}];
</code>```

This will set your brand data to first element of array. But as your service method name is 'getBrands' are you sure only a single brand value will be returned from service instead of array ?

Body:
I'm going crazy for this error:

Object literal may only specify known properties, and 'brand' does not exist in type 'BrandCB[]'.

I don't know what's happen. How to solve this issue?
this is the code:
gallery.component.ts

import { CarsService } from '../services/cars.service';
import { Car } from './../models/car';
import { Component, OnInit } from '@angular/core';
import { BrandCB } from '../models/brandCB';

@Component({
  selector: 'app-gallery',
  templateUrl: './gallery.component.html',
  styleUrls: ['./gallery.component.css']
})
export class GalleryComponent implements OnInit {

  cars:Car[];
  brands:BrandCB[];
  selectedBrand:string;
  observableCars;
  observableBrands;

  constructor(public carsService: CarsService) {

  }

  ngOnInit() {
    this.getCars('all');
    this.observableBrands = this.carsService.getBrands().subscribe( (data:any) => {
      this.brands = {brand:data['brand'], checked:'false'}; //this is the error row
      console.table(data);
    });
  }

  onOptionsSelected(event: { target: { filter: any; }; }){
    this.getCars(this.selectedBrand)
  }

  getCars(filter){

    this.observableCars = this.carsService.getCars().subscribe(data => {

      if(filter!="all"){
        this.cars = data.filter( car => car.brand == this.selectedBrand);
      }else{
        this.cars = data;
      }

    });
  }

  a(event){
    let name = event.target.name;
    let checked = event.target.checked;

    if(name=='all'){
      if(checked==true){
        //uncheck tutti gli altri
      }
    } else {
      // filtra in base alle caselle checked
        // crea un array di checked items
    }

  }

  ngOnDestroy(){
    this.observableCars.unsubscribe();
    this.observableBrands.unsubscribe();
  }
}

brandCB.ts

export class BrandCB {
    brand:any;
    checked:boolean;
}

StackOverflow is telling me that my post is mostly code and i should write something else, so I m doing, bla bla bla and more bla bla bla. Have you seen the accident outside?

Body:
As your line of error shows, you are trying to assign an object to array. Basically you need to push your brandData in brands array instead of assigning it.

Try this line

this.brands = [{brand:data['brand'], checked:'false'}];

This will set your brand data to first element of array. But as your service method name is 'getBrands' are you sure only a single brand value will be returned from service instead of array ?


问:
How to require all files within a directory using webpack?
I am on webpack v4.

A number of libraries commonly ask a URL to some configuration or data file (that's part of the application's sources) to be provided at some API call. This is easily doable in webpack by require-ing the file in question (and having a file-loader configured).

I am now faced with a slightly different problem: a certain API requires the relative URL to some directory where a bunch of files will be found. What is the proper way to handle this in webpack? As far as I can tell, it is not possible to require an entire directory and there's no "directory-loader".

答:
If you want to perform the require calls at compile-time, you can use require.context:

This can be useful if you want to require all files in a directory or matching a pattern.

Read the webpack docs for more information [1].

Example from the docs:

```<code>function importAll (r) {
  r.keys().forEach(r);
}

importAll(require.context('../components/', true, /\.js$/));
</code>```

[1] https://webpack.js.org/guides/dependency-management/#requirecontext

Body:
If you want to perform the require calls at compile-time, you can use require.context:

This can be useful if you want to require all files in a directory or matching a pattern.

Read the webpack docs for more information [1].

Example from the docs:

function importAll (r) {
  r.keys().forEach(r);
}

importAll(require.context('../components/', true, /\.js$/));

[1] https://webpack.js.org/guides/dependency-management/#requirecontext


问:
Define a variable for a ":" slice
I want to define a function that will operate on a part of a dataframe if another variable is set, or on the full dataframe otherwhile. For instance :

```<code>def mean_loc(df, col_name, idx=None):
    if idx is not None:
        return df.loc[idx, col_name].mean()
    else:
        return df[col_name].mean()
</code>```

This works just fine but I was wondering if this was possible to do something like that :

```<code>def mean_loc_2(df, col_name, idx=None):
    if idx is None:
        idx = :
    return df.loc[idx, col_name].mean()
</code>```

This of course does not work but I was wondering if there existed a bypass ? If I do idx = df.index, the evaluation of df.loc[df.index, col_name] is way longer than doing df.loc[:, col_name]. I've tried working with slice from the built-in functions by doing idx = slice(len(df)) but without any success (it's also longer and does not work for DateTime indexes).

Does anyone know how to do such a thing ?

答:
: is not a value; it's part of Python's syntax. What you want is the slice object that the : syntax represents.

```<code>if idx is None:
    idx = slice(None)  # sadly, slice() does not work
</code>```

Since a slice object is immutable, it's safe to use one as the default parameter value.

```<code>def mean_loc_2(df, col_name, idx=slice(None)):
    return df.loc[idx, col_name].mean()
</code>```

Title: Define a variable for a ":" slice

Body:
I want to define a function that will operate on a part of a dataframe if another variable is set, or on the full dataframe otherwhile. For instance :

def mean_loc(df, col_name, idx=None):
    if idx is not None:
        return df.loc[idx, col_name].mean()
    else:
        return df[col_name].mean()

This works just fine but I was wondering if this was possible to do something like that :

def mean_loc_2(df, col_name, idx=None):
    if idx is None:
        idx = :
    return df.loc[idx, col_name].mean()

This of course does not work but I was wondering if there existed a bypass ? If I do idx = df.index, the evaluation of df.loc[df.index, col_name] is way longer than doing df.loc[:, col_name]. I've tried working with slice from the built-in functions by doing idx = slice(len(df)) but without any success (it's also longer and does not work for DateTime indexes).

Does anyone know how to do such a thing ?

Body:
: is not a value; it's part of Python's syntax. What you want is the slice object that the : syntax represents.

if idx is None:
    idx = slice(None)  # sadly, slice() does not work

Since a slice object is immutable, it's safe to use one as the default parameter value.

def mean_loc_2(df, col_name, idx=slice(None)):
    return df.loc[idx, col_name].mean()


问:
How to delete a XML child node using SQL Server 2016
I have the following Xml example snippet taken from a larger file:

```<code><EntityAttributeValue>
  <Value />
  <Attribute>
    <Id>0</Id>
    <Name>Use 3</Name>
    <AttributeType>other</AttributeType>
  </Attribute>
  <AttributeValueId>999998</AttributeValueId>
  <ProductTypeId xsi:nil="true" />
</EntityAttributeValue>
</code>```

I am trying to remove the <ProductTypeId> node using SQL so that the above will look like this:

```<code><EntityAttributeValue>
  <Value />
  <Attribute>
    <Id>13</Id>
    <Name>Use 3</Name>
    <AttributeType>other</AttributeType>
  </Attribute>
  <AttributeValueId>999998</AttributeValueId>
</EntityAttributeValue>
</code>```

I have used the following to SQL query the XML and isolate the above snippet(first one)

```<code>select t.c.query('.') as Attributes
from @XMLData.nodes('/Item/ContentAttributeValues/EntityAttributeValue') t(c)
where t.c.value('(Attribute/Id)[1]','INT') = 0
</code>```

I have tried

```<code>SET @XMLData.modify('delete (/Item/ContentAttributeValues/EntityAttributeValue/ProductTypeId)')
</code>```

to remove all the product ids, but to no avail, any help would be greatly recieved.

Cheers

答:
Here is a full example. I had to add a namespace to the root to accommodate the xsi:nil="true" attribute.

SQL

```<code>-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, xmldata XML NOT NULL);
INSERT INTO @tbl (xmldata) VALUES
(N'<Item xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <ContentAttributeValues>
        <EntityAttributeValue>
            <Value/>
            <Attribute>
                <Id>0</Id>
                <Name>Use 3</Name>
                <AttributeType>other</AttributeType>
            </Attribute>
            <AttributeValueId>999998</AttributeValueId>
            <ProductTypeId xsi:nil="true"/>
        </EntityAttributeValue>
        <EntityAttributeValue>
            <Value/>
            <Attribute>
                <Id>10</Id>
                <Name>Use 7</Name>
                <AttributeType>other</AttributeType>
            </Attribute>
            <AttributeValueId>999770</AttributeValueId>
            <ProductTypeId xsi:nil="true"/>
        </EntityAttributeValue>
    </ContentAttributeValues>
</Item>');
-- DDL and sample data population, end

UPDATE @tbl
SET xmldata.modify('delete /Item/ContentAttributeValues/EntityAttributeValue/ProductTypeId');

SELECT * FROM @tbl;
</code>```

Output XML

```<code><Item xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <ContentAttributeValues>
    <EntityAttributeValue>
      <Value />
      <Attribute>
        <Id>0</Id>
        <Name>Use 3</Name>
        <AttributeType>other</AttributeType>
      </Attribute>
      <AttributeValueId>999998</AttributeValueId>
    </EntityAttributeValue>
    <EntityAttributeValue>
      <Value />
      <Attribute>
        <Id>10</Id>
        <Name>Use 7</Name>
        <AttributeType>other</AttributeType>
      </Attribute>
      <AttributeValueId>999770</AttributeValueId>
    </EntityAttributeValue>
  </ContentAttributeValues>
</Item>
</code>```

Body:
I have the following Xml example snippet taken from a larger file:

<EntityAttributeValue>
  <Value />
  <Attribute>
    <Id>0</Id>
    <Name>Use 3</Name>
    <AttributeType>other</AttributeType>
  </Attribute>
  <AttributeValueId>999998</AttributeValueId>
  <ProductTypeId xsi:nil="true" />
</EntityAttributeValue>

I am trying to remove the <ProductTypeId> node using SQL so that the above will look like this:

<EntityAttributeValue>
  <Value />
  <Attribute>
    <Id>13</Id>
    <Name>Use 3</Name>
    <AttributeType>other</AttributeType>
  </Attribute>
  <AttributeValueId>999998</AttributeValueId>
</EntityAttributeValue>

I have used the following to SQL query the XML and isolate the above snippet(first one)

select t.c.query('.') as Attributes
from @XMLData.nodes('/Item/ContentAttributeValues/EntityAttributeValue') t(c)
where t.c.value('(Attribute/Id)[1]','INT') = 0

I have tried

SET @XMLData.modify('delete (/Item/ContentAttributeValues/EntityAttributeValue/ProductTypeId)')

to remove all the product ids, but to no avail, any help would be greatly recieved.

Cheers

Body:
Here is a full example. I had to add a namespace to the root to accommodate the xsi:nil="true" attribute.

SQL

-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, xmldata XML NOT NULL);
INSERT INTO @tbl (xmldata) VALUES
(N'<Item xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <ContentAttributeValues>
        <EntityAttributeValue>
            <Value/>
            <Attribute>
                <Id>0</Id>
                <Name>Use 3</Name>
                <AttributeType>other</AttributeType>
            </Attribute>
            <AttributeValueId>999998</AttributeValueId>
            <ProductTypeId xsi:nil="true"/>
        </EntityAttributeValue>
        <EntityAttributeValue>
            <Value/>
            <Attribute>
                <Id>10</Id>
                <Name>Use 7</Name>
                <AttributeType>other</AttributeType>
            </Attribute>
            <AttributeValueId>999770</AttributeValueId>
            <ProductTypeId xsi:nil="true"/>
        </EntityAttributeValue>
    </ContentAttributeValues>
</Item>');
-- DDL and sample data population, end

UPDATE @tbl
SET xmldata.modify('delete /Item/ContentAttributeValues/EntityAttributeValue/ProductTypeId');

SELECT * FROM @tbl;

Output XML

<Item xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <ContentAttributeValues>
    <EntityAttributeValue>
      <Value />
      <Attribute>
        <Id>0</Id>
        <Name>Use 3</Name>
        <AttributeType>other</AttributeType>
      </Attribute>
      <AttributeValueId>999998</AttributeValueId>
    </EntityAttributeValue>
    <EntityAttributeValue>
      <Value />
      <Attribute>
        <Id>10</Id>
        <Name>Use 7</Name>
        <AttributeType>other</AttributeType>
      </Attribute>
      <AttributeValueId>999770</AttributeValueId>
    </EntityAttributeValue>
  </ContentAttributeValues>
</Item>


问:
Statistical analysis and plotting in pandas (python)
I have some Capacitance-voltage (also known as C-V) measurement data. They are obtained for various parameters called 'wafer', 'Die', 'ID' etc. I store them in a pandas dataframe.

Now if I apply df.plot(x='V',y='C'), I get a plot of all the data without any classification.

How can I efficiently analyze and compare the data for different parameters? For example, I want to compare C vs V plot-

For different wafers

For different 'Die' when wafer='D09'

For wafer='D10' and G<3 at V=2.5

etc.

```<code>import pandas as pd

V=[2.5,2,1.5,1,0]
C_1=[5e-6,3e-6,1e-6,0.3e-6,0.1e-6]
G_1=[3e-3,1.2e-3,1e-3,0.8e-3,0.02e-3]

C_2=[5.5e-6,3.5e-6,1.5e-6,0.4e-6,0.3e-6]
G_2=[3.2e-3,1.4e-3,1.5e-3,1.8e-3,0.2e-3]

C_3=[5.3e-6,3.7e-6,1.7e-6,0.6e-6,0.45e-6]
G_3=[5.2e-3,2.4e-3,2.5e-3,2.8e-3,0.25e-3]

C_4=[5.1e-6,6.7e-6,2.7e-6,1.6e-6,1.45e-6]
G_4=[5.3e-3,3.4e-3,1.5e-3,3.8e-3,1.25e-3]

data_1={'Wafer':'D09','ID':'ab','Die':150,'x':6,'y': 15,'V':V,'C':C_1,'G':G_1}
data_2={'Wafer':'D09','ID':'cd','Die':130,'x':10,'y': 15,'V':V,'C':C_2,'G':G_2}
data_3={'Wafer':'D10','ID':'cd','Die':140,'x':4,'y': 15,'V':V,'C':C_3,'G':G_3}
data_4={'Wafer':'D10','ID':'ab','Die':120,'x':12,'y': 15,'V':V,'C':C_4,'G':G_4}

df1=pd.DataFrame(data_1)
df2=pd.DataFrame(data_2)
df3=pd.DataFrame(data_3)
df4=pd.DataFrame(data_4)

df=pd.concat([df1,df2,df3])
</code>```

答:
You could do conditions as:

```<code>new_df_1= df[df['Wafer']=='D09']
new_df_2= df[(df['Wafer']=='D09') & (df['Die']==150)]
new_df_3= df[df['G'] < 3]
new_df_4= df[df['V'] < 2.5]
new_df_5= df[(df['G']== 3) & (df['V'] < 2.5)]
</code>```

and easily plot the new dataframes.
Is that what you actually need?

Body:
I have some Capacitance-voltage (also known as C-V) measurement data. They are obtained for various parameters called 'wafer', 'Die', 'ID' etc. I store them in a pandas dataframe.

Now if I apply df.plot(x='V',y='C'), I get a plot of all the data without any classification.

How can I efficiently analyze and compare the data for different parameters? For example, I want to compare C vs V plot-

For different wafers

For different 'Die' when wafer='D09'

For wafer='D10' and G<3 at V=2.5

etc.

import pandas as pd

V=[2.5,2,1.5,1,0]
C_1=[5e-6,3e-6,1e-6,0.3e-6,0.1e-6]
G_1=[3e-3,1.2e-3,1e-3,0.8e-3,0.02e-3]

C_2=[5.5e-6,3.5e-6,1.5e-6,0.4e-6,0.3e-6]
G_2=[3.2e-3,1.4e-3,1.5e-3,1.8e-3,0.2e-3]

C_3=[5.3e-6,3.7e-6,1.7e-6,0.6e-6,0.45e-6]
G_3=[5.2e-3,2.4e-3,2.5e-3,2.8e-3,0.25e-3]

C_4=[5.1e-6,6.7e-6,2.7e-6,1.6e-6,1.45e-6]
G_4=[5.3e-3,3.4e-3,1.5e-3,3.8e-3,1.25e-3]

data_1={'Wafer':'D09','ID':'ab','Die':150,'x':6,'y': 15,'V':V,'C':C_1,'G':G_1}
data_2={'Wafer':'D09','ID':'cd','Die':130,'x':10,'y': 15,'V':V,'C':C_2,'G':G_2}
data_3={'Wafer':'D10','ID':'cd','Die':140,'x':4,'y': 15,'V':V,'C':C_3,'G':G_3}
data_4={'Wafer':'D10','ID':'ab','Die':120,'x':12,'y': 15,'V':V,'C':C_4,'G':G_4}

df1=pd.DataFrame(data_1)
df2=pd.DataFrame(data_2)
df3=pd.DataFrame(data_3)
df4=pd.DataFrame(data_4)

df=pd.concat([df1,df2,df3])

Body:
You could do conditions as:

new_df_1= df[df['Wafer']=='D09']
new_df_2= df[(df['Wafer']=='D09') & (df['Die']==150)]
new_df_3= df[df['G'] < 3]
new_df_4= df[df['V'] < 2.5]
new_df_5= df[(df['G']== 3) & (df['V'] < 2.5)]

and easily plot the new dataframes.
Is that what you actually need?


问:
Filter Django models based on date comparision
I have a Subscription models that has an end_date attribute.

```<code>class Subscription(models.Model):
    client = models.OneToOneField(ClientProfile, on_delete=models.CASCADE)
    trainer = models.ForeignKey(TrainerProfile, null=True, blank=True,
        on_delete=models.SET_NULL, limit_choices_to={'is_staff': True})
    plan = models.ForeignKey(Plan, on_delete=models.CASCADE)
    transaction = models.OneToOneField(PaymentHistory, on_delete=models.CASCADE)
    start_date = models.DateTimeField()
    end_date = models.DateTimeField()
</code>```

I want to send an email to the user having subscription to notify once:

```<code>(subscription.end_date - timezone.now()).days < 3
</code>```

How would I filter data from django based on these type of comparision in filter() rather than reading all the Subscription objects in the memory.

答:
Firstly, you can find 3 days from now. After you can use end_date__lte param. Like that:

```<code>comparing_date =  datetime.datetime.today() + datetime.timedelta(days=3)
subscriptions =  Subscription.objects.filter(end_date__lte=comparing_date)
</code>```

Body:
I have a Subscription models that has an end_date attribute.

class Subscription(models.Model):
    client = models.OneToOneField(ClientProfile, on_delete=models.CASCADE)
    trainer = models.ForeignKey(TrainerProfile, null=True, blank=True,
        on_delete=models.SET_NULL, limit_choices_to={'is_staff': True})
    plan = models.ForeignKey(Plan, on_delete=models.CASCADE)
    transaction = models.OneToOneField(PaymentHistory, on_delete=models.CASCADE)
    start_date = models.DateTimeField()
    end_date = models.DateTimeField()

I want to send an email to the user having subscription to notify once:

(subscription.end_date - timezone.now()).days < 3

How would I filter data from django based on these type of comparision in filter() rather than reading all the Subscription objects in the memory.

Body:
Firstly, you can find 3 days from now. After you can use end_date__lte param. Like that:

comparing_date =  datetime.datetime.today() + datetime.timedelta(days=3)
subscriptions =  Subscription.objects.filter(end_date__lte=comparing_date)


问:
Java dynamically generate SQL query - ATHENA
I am trying to generate sql query based on user input. There are 4 search fields on the UI:
FIRST_NAME, LAST_NAME, SUBJECT, MARKS

Based on user input I am planning to generate SQL query. Input can be of any combination.

eg: select * from TABLE where FIRST_NAME="some_value";

This query needs to be generated when FIRST_NAME is given and other fields are null

select  * from TABLE where FIRST_NAME="some_value" and LAST_NAME="some_value";

This query needs to be generated when FIRST_NAME and LAST_NAME are given and other fields are null

Since there are 4 input fields, number of possible queries that can be generated are 24 (factorial of 4).

One idea is to write if condition for all 24 cases.

Java pseudo code:

```<code>String QUERY = "select * from TABLE where ";

if (FIRST_NAME!=null) {

    QUERY = QUERY + "FIRST_NAME='use_input_value';"

}
if (LAST_NAME!=null) {

    QUERY = QUERY + "LAST_NAME='use_input_value';"

}
if (SUBJECT!=null) {

    QUERY = QUERY + "SUBJECT='use_input_value';"

}
if (MARKS!=null) {

    QUERY = QUERY + "MARKS='use_input_value';"

}
</code>```

I am not able to figure out how to generate SQL queries with AND coditions for multiple Input values.
I have been through concepts on dynamically generate sql query but couldn't process further.

Can someone help me on this.

FYI: I have been through How to dynamically generate SQL query based on user's selections?, still not able to generate query string based on user input.

答:
Let's think about what would happen if you just ran the code you wrote and both FIRST_NAME and LAST_NAME are provided. You'll wind up with this:

```<code>select * from TABLE where FIRST_NAME='use_input_value';LAST_NAME='use_input_value';
</code>```

There are two problems here:

The query is syntactically incorrect.

It contains the literals 'use_input_value' instead of the values you want.

To fix the first problem, let's first add and to the start of each expression, and remove the semicolons, something like this:

```<code>String QUERY = "select * from TABLE where";
if (FIRST_NAME!=null) {
    QUERY = QUERY + " and FIRST_NAME='use_input_value'";
}
</code>```

Notice the space before the and. We can also remove the space after where.

Now the query with both FIRST_NAME and LAST_NAME will look like this:

```<code>select * from TABLE where and FIRST_NAME='use_input_value' and LAST_NAME='use_input_value'
</code>```

Better but now there's an extra and. We can fix that by adding a dummy always-true condition at the start of the query:

```<code>String QUERY = "select * from TABLE where 1=1";
</code>```

Then we append a semicolon after all the conditions have been evaluated, and we have a valid query:

```<code>select * from TABLE where 1=1 and FIRST_NAME='use_input_value' and LAST_NAME='use_input_value';
</code>```

(It may not be necessary to append the semicolon. Most databases don't require semicolons at the end of a single query like this.)

On to the string literals. You should add a placeholder instead, and simultaneously add the value you want to use to a List.

```<code>String QUERY = "select * from TABLE where";
List<String> args = new ArrayList<>();
if (FIRST_NAME!=null) {
    QUERY = QUERY + " and FIRST_NAME=?";
    args.add(FIRST_NAME);
}
</code>```

After you've handled all the conditions you'll have a string with N '?' placeholders and a List with N values. At that point just prepare a query from the SQL string and add the placeholders.

```<code>PreparedStatement statement = conn.prepareStatement(QUERY);
for (int i = 0; i < args.size(); i++) {
    statement.setString(i + 1, args[i]);
}
</code>```

For some reason columns and parameters are indexed starting at 1 in the JDBC API, so we have to add 1 to i to produce the parameter index.

Then execute the PreparedStatement.

Body:
I am trying to generate sql query based on user input. There are 4 search fields on the UI:
FIRST_NAME, LAST_NAME, SUBJECT, MARKS

Based on user input I am planning to generate SQL query. Input can be of any combination.

eg: select * from TABLE where FIRST_NAME="some_value";

This query needs to be generated when FIRST_NAME is given and other fields are null

select  * from TABLE where FIRST_NAME="some_value" and LAST_NAME="some_value";

This query needs to be generated when FIRST_NAME and LAST_NAME are given and other fields are null

Since there are 4 input fields, number of possible queries that can be generated are 24 (factorial of 4).

One idea is to write if condition for all 24 cases.

Java pseudo code:

String QUERY = "select * from TABLE where ";

if (FIRST_NAME!=null) {

    QUERY = QUERY + "FIRST_NAME='use_input_value';"

}
if (LAST_NAME!=null) {

    QUERY = QUERY + "LAST_NAME='use_input_value';"

}
if (SUBJECT!=null) {

    QUERY = QUERY + "SUBJECT='use_input_value';"

}
if (MARKS!=null) {

    QUERY = QUERY + "MARKS='use_input_value';"

}

I am not able to figure out how to generate SQL queries with AND coditions for multiple Input values.
I have been through concepts on dynamically generate sql query but couldn't process further.

Can someone help me on this.

FYI: I have been through How to dynamically generate SQL query based on user's selections?, still not able to generate query string based on user input.

Body:
Let's think about what would happen if you just ran the code you wrote and both FIRST_NAME and LAST_NAME are provided. You'll wind up with this:

select * from TABLE where FIRST_NAME='use_input_value';LAST_NAME='use_input_value';

There are two problems here:

The query is syntactically incorrect.

It contains the literals 'use_input_value' instead of the values you want.

To fix the first problem, let's first add and to the start of each expression, and remove the semicolons, something like this:

String QUERY = "select * from TABLE where";
if (FIRST_NAME!=null) {
    QUERY = QUERY + " and FIRST_NAME='use_input_value'";
}

Notice the space before the and. We can also remove the space after where.

Now the query with both FIRST_NAME and LAST_NAME will look like this:

select * from TABLE where and FIRST_NAME='use_input_value' and LAST_NAME='use_input_value'

Better but now there's an extra and. We can fix that by adding a dummy always-true condition at the start of the query:

String QUERY = "select * from TABLE where 1=1";

Then we append a semicolon after all the conditions have been evaluated, and we have a valid query:

select * from TABLE where 1=1 and FIRST_NAME='use_input_value' and LAST_NAME='use_input_value';

(It may not be necessary to append the semicolon. Most databases don't require semicolons at the end of a single query like this.)

On to the string literals. You should add a placeholder instead, and simultaneously add the value you want to use to a List.

String QUERY = "select * from TABLE where";
List<String> args = new ArrayList<>();
if (FIRST_NAME!=null) {
    QUERY = QUERY + " and FIRST_NAME=?";
    args.add(FIRST_NAME);
}

After you've handled all the conditions you'll have a string with N '?' placeholders and a List with N values. At that point just prepare a query from the SQL string and add the placeholders.

PreparedStatement statement = conn.prepareStatement(QUERY);
for (int i = 0; i < args.size(); i++) {
    statement.setString(i + 1, args[i]);
}

For some reason columns and parameters are indexed starting at 1 in the JDBC API, so we have to add 1 to i to produce the parameter index.

Then execute the PreparedStatement.


问:
How can I make a file visible both when project is deployed on a server and when its classes are run from test classes?
If I use a file calling it directly:

```<code>FileInputStream fileInputStream = new FileInputStream("SR02_pattern.xls");
</code>```

( the file is in \apv\main-app directory), it won't be deployed, and of course, it won't be seen when the project will be run on the server.

If I put the file in the /apv/main-web/WEB-INF/classes/ directory, it will be deployed and I can call it by

```<code>InputStream inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("SR02_pattern.xls")
</code>```

when the project is deployed on the server, but that line won't read the file in the case the class was run from the test.

Probably, the place where the file will be looked for by getResourceAsStream("SR02_pattern.xls"), is set by some system properties and I can use them, but I don't know which properties can help.

How can I read the file in both cases by the same code without passing it as a parameter into the class?

There are many answers on SO for either of those cases, but I couldn't find one that works for both. The default paths for both cases are different.

Of course, I can put the file in both places, and in case the file is not in the first folder, look it in the second, as I am doing now, but upkeeping two copies is prone to errors and I desire to use better style.

答:
You should use this.getClass().getResourceAsStream('/SR02-pattern.xl') for all parts in test as well in production code. The / defines the root directory for the resources.

The files you would like to read should be located in src/main/resources. This will result in the final war package at the location WEB-INF/classes.

Body:
If I use a file calling it directly:

FileInputStream fileInputStream = new FileInputStream("SR02_pattern.xls");

( the file is in \apv\main-app directory), it won't be deployed, and of course, it won't be seen when the project will be run on the server.

If I put the file in the /apv/main-web/WEB-INF/classes/ directory, it will be deployed and I can call it by

InputStream inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("SR02_pattern.xls")

when the project is deployed on the server, but that line won't read the file in the case the class was run from the test.

Probably, the place where the file will be looked for by getResourceAsStream("SR02_pattern.xls"), is set by some system properties and I can use them, but I don't know which properties can help.

How can I read the file in both cases by the same code without passing it as a parameter into the class?

There are many answers on SO for either of those cases, but I couldn't find one that works for both. The default paths for both cases are different.

Of course, I can put the file in both places, and in case the file is not in the first folder, look it in the second, as I am doing now, but upkeeping two copies is prone to errors and I desire to use better style.


问:
Converting minutes to hours in prolog
I am trying to convert total minutes(N) to number of hours(H) and number of minutes(M) in prolog using this code (Have not implemented counting the minutes yet):

```<code>minutes_to_hours(N, H, M) :-

   (   N >= 60
   ->  H is H1+1,
       N is N1-60,
       minutes_to_hours(N, H, M)
   ;   writeln(H)
   ).
</code>```

I get this error:

```<code>Arguments are not sufficiently instantiated
In:
[2] _1440 is _1446+1
[1] mins_to_hours_and_mins(60,_1508,_1510) at  line 1
</code>```

答:
As you requested, a possible solution using recursion could be:

```<code>minutes_to_hours(Mins,Hours) :-
    (   Mins > 60 ->
        M is Mins - 60,
        H1 is Hours + 1,
        minutes_to_hours(M,H1) ;
        format('Hours: ~w, Reminder: ~w~n',[Hours,Mins])
    ).

?- minutes_to_hours(125,0).
Hours: 2, Reminder: 5
true
</code>```

However, you should prefer the solution of @CapelliC with mod and //.

Title: Converting minutes to hours in prolog

Body:
I am trying to convert total minutes(N) to number of hours(H) and number of minutes(M) in prolog using this code (Have not implemented counting the minutes yet):

minutes_to_hours(N, H, M) :-

   (   N >= 60
   ->  H is H1+1,
       N is N1-60,
       minutes_to_hours(N, H, M)
   ;   writeln(H)
   ).

I get this error:

Arguments are not sufficiently instantiated
In:
[2] _1440 is _1446+1
[1] mins_to_hours_and_mins(60,_1508,_1510) at  line 1

Body:
As you requested, a possible solution using recursion could be:

minutes_to_hours(Mins,Hours) :-
    (   Mins > 60 ->
        M is Mins - 60,
        H1 is Hours + 1,
        minutes_to_hours(M,H1) ;
        format('Hours: ~w, Reminder: ~w~n',[Hours,Mins])
    ).

?- minutes_to_hours(125,0).
Hours: 2, Reminder: 5
true

However, you should prefer the solution of @CapelliC with mod and //.


问:
What's the best way to have reusable dialog boxes?
What's the best way to create reusable dialog boxes in Android?

Reading through the Dialog dev guide, I know I can use AlertDialog.Builder(this); in one of my Activitys, but what if I want to use this in multiple Activities? If this was some other class I would extend it, so MyDialog extends AlertDialog, but then I cannot use the Builder.

Any suggestions?

答:
Crate one class file like as AllMethod.java and add this code in that class file.

```<code>public static void showAlert(Activity act, String msg, DialogInterface.OnClickListener listener) {
        AlertDialog.Builder alert = new AlertDialog.Builder(act);
        alert.setMessage(msg);
        alert.setPositiveButton("OK", listener);
        alert.show();
    }
</code>```

and you can use from any class like below code.

```<code>AllMethod.showAlert(mActivity, "", new DialogInterface.OnClickListener() {
        @Override
         public void onClick(DialogInterface dialog, int which) {
         // Do your code for click
         }
});
</code>```

Body:
Crate one class file like as AllMethod.java and add this code in that class file.

public static void showAlert(Activity act, String msg, DialogInterface.OnClickListener listener) {
        AlertDialog.Builder alert = new AlertDialog.Builder(act);
        alert.setMessage(msg);
        alert.setPositiveButton("OK", listener);
        alert.show();
    }

and you can use from any class like below code.

AllMethod.showAlert(mActivity, "", new DialogInterface.OnClickListener() {
        @Override
         public void onClick(DialogInterface dialog, int which) {
         // Do your code for click
         }
});


问:
Laravel MySQL groupby created_at with date format without time
I have a table column named created_at type datetime.
and I want to use groupby for created_at with date only and without time.
Here's my existing code :

```<code>$data = BloodPressureHistory::where('user_id', $id)
    ->groupBy('created_at')
    ->orderBy('created_at', 'DESC')
    ->paginate(7);
</code>```

答:
Use groupBy(DB::raw()) and DATE_FORMAT like this:

$data = BloodPressureHistory::where('user_id', $id)
                           ->groupBy(DB::raw('DATE_FORMAT(created_at,"%Y-%m-%d")'))
                           ->orderBy('created_at', 'DESC')
                           ->paginate(7);
```

Body:
I have a table column named created_at type datetime.
and I want to use groupby for created_at with date only and without time.
Here's my existing code :

$data = BloodPressureHistory::where('user_id', $id)
    ->groupBy('created_at')
    ->orderBy('created_at', 'DESC')
    ->paginate(7);


问:
Power bi group ranking
Can you help me? I want the rank to be assigned within the filtered range (filter by date). Tell me, please, what am I doing wrong? CustomerSaleIndex1 = VAR CurrentOrderDate = \'public _smsnt_delete\'[date_transaction] VAR CurrentOrderTr = \'public _smsnt_delete\'[transaction_id] VAR CurrentCustomerKey = \'public _smsnt_delete\'[card_number] RETURN RANKX(FILTER(ALLSELECTED(\'public _smsnt_delete\'); \'public _smsnt_delete\'[card_number] = CurrentCustomerKey);\'public _smsnt_delete\'[date_transaction];;ASC;Dense)</p>

答:
In terms of your separator in the filter function, you are using the semicolon ";" over the comma separator ","?

Also you've declared CurrentOrderDate as a variable, why not use it. On the other side of things, why is CurrentOrderTr even declared? As you don't use it in the function:

```<code>CustomerSaleIndex1 =
VAR CurrentOrderDate = 'public _smsnt_delete\'[date_transaction]
VAR CurrentCustomerKey = 'public _smsnt_delete\'[card_number]

RETURN
RANKX(FILTER(ALLSELECTED('public
_smsnt_delete\'),'public_smsnt_delete\'[card_number] = CurrentCustomerKey),
CurrentOrderDate,,ASC,Dense)
</code>```

https://learn.microsoft.com/en-us/dax/rankx-function-dax

Title: Power bi group ranking

Body:
In terms of your separator in the filter function, you are using the semicolon ";" over the comma separator ","?

Also you've declared CurrentOrderDate as a variable, why not use it. On the other side of things, why is CurrentOrderTr even declared? As you don't use it in the function:

CustomerSaleIndex1 =
VAR CurrentOrderDate = 'public _smsnt_delete\'[date_transaction]
VAR CurrentCustomerKey = 'public _smsnt_delete\'[card_number]

RETURN
RANKX(FILTER(ALLSELECTED('public
_smsnt_delete\'),'public_smsnt_delete\'[card_number] = CurrentCustomerKey),
CurrentOrderDate,,ASC,Dense)

https://learn.microsoft.com/en-us/dax/rankx-function-dax


问:
Typo3 Fluid ignoring max image sizes set in typoscript
I've set in my Constants

```<code>styles.content.textmedia.maxW = 400
styles.content.textmedia.maxWInText = 400
styles.content.imgtext.maxW = 800
</code>```

and tried a simple

```<code><f:image src="..."></f:image>
</code>```

without any params and on the frontend the image is still rendered on its original width ignoring my maxW constants

The original problem was to set different maxW for each column in gridelements which also did not work for fluid content. So i tried to break it down to the simplest maxW setting and even that is not working.

If i take the Text & Image contentelement, it works as expected so i assume, the system is behaving correctly but for any reason fluid images are ignoring the setting?!

Is there anything i do wrong or is there something missing which sets the maxW for f:image? I cant set the maxW in the f:image directly cause it may be located in different columns with different sizes, so i have to set it outside of the f:image tag.

Update:
The main target was to be able to use gridelements as the gridengine and using dce for creating content elements while the elements should knew about the column widths, they are located in to scale images properly.

With the help of Mikel Wohlschlegel i got the missing hint, to fix my problem.

答:
Short anwer:

The image viewhelper does not automatically apply any dimensions defined in the constants. f:image is part of ext:fluid, the constants you set are part of ext:fluid_styled_content. The image viewhelper always needs a width or a maxWidth argument if you want to set one. You need to pass your constants to the frontend.

Long answer:

You can see, how it is done in fluid_styled_content:

Have a look into: typo3/sysext/fluid_styled_content/Configuration/TypoScript/ContentElement/Image.typoscript
A DataProcessor passes this constants to the GalleryProcessor

```<code>tt_content.image {
templateName = Image
dataProcessing {
    20 = TYPO3\CMS\Frontend\DataProcessing\GalleryProcessor
    20 {
        maxGalleryWidth = {$styles.content.textmedia.maxW}
        maxGalleryWidthInText = {$styles.content.textmedia.maxWInText}
    }
}
</code>```

and are passed through to the frontend as {column.dimensions}
See typo3/sysext/fluid_styled_content/Resources/Private/Partials/Media/Gallery.html

```<code><f:render partial="Media/Type" arguments="{file: column.media, dimensions: column.dimensions, data: data, settings: settings}" />
</code>```

to finally gets applied as width argument in typo3/sysext/fluid_styled_content/Resources/Private/Partials/Media/Rendering/Image.html

```<code><f:media class="image-embed-item" file="{file}" width="{dimensions.width}" height="{dimensions.height}" alt="{file.alternative}" title="{file.title}" />
</code>```

Body:
I've set in my Constants

styles.content.textmedia.maxW = 400
styles.content.textmedia.maxWInText = 400
styles.content.imgtext.maxW = 800

and tried a simple

<f:image src="..."></f:image>

without any params and on the frontend the image is still rendered on its original width ignoring my maxW constants

The original problem was to set different maxW for each column in gridelements which also did not work for fluid content. So i tried to break it down to the simplest maxW setting and even that is not working.

If i take the Text & Image contentelement, it works as expected so i assume, the system is behaving correctly but for any reason fluid images are ignoring the setting?!

Is there anything i do wrong or is there something missing which sets the maxW for f:image? I cant set the maxW in the f:image directly cause it may be located in different columns with different sizes, so i have to set it outside of the f:image tag.

Update:
The main target was to be able to use gridelements as the gridengine and using dce for creating content elements while the elements should knew about the column widths, they are located in to scale images properly.

With the help of Mikel Wohlschlegel i got the missing hint, to fix my problem.

Body:
Short anwer:

The image viewhelper does not automatically apply any dimensions defined in the constants. f:image is part of ext:fluid, the constants you set are part of ext:fluid_styled_content. The image viewhelper always needs a width or a maxWidth argument if you want to set one. You need to pass your constants to the frontend.

Long answer:

You can see, how it is done in fluid_styled_content:

Have a look into: typo3/sysext/fluid_styled_content/Configuration/TypoScript/ContentElement/Image.typoscript
A DataProcessor passes this constants to the GalleryProcessor

tt_content.image {
templateName = Image
dataProcessing {
    20 = TYPO3\CMS\Frontend\DataProcessing\GalleryProcessor
    20 {
        maxGalleryWidth = {$styles.content.textmedia.maxW}
        maxGalleryWidthInText = {$styles.content.textmedia.maxWInText}
    }
}

and are passed through to the frontend as {column.dimensions}
See typo3/sysext/fluid_styled_content/Resources/Private/Partials/Media/Gallery.html

<f:render partial="Media/Type" arguments="{file: column.media, dimensions: column.dimensions, data: data, settings: settings}" />

to finally gets applied as width argument in typo3/sysext/fluid_styled_content/Resources/Private/Partials/Media/Rendering/Image.html

<f:media class="image-embed-item" file="{file}" width="{dimensions.width}" height="{dimensions.height}" alt="{file.alternative}" title="{file.title}" />


问:
mingw-w64 pure assembler code without additional (redundancy) info
I'm learning reverse engineering. I trying to compile code to assembler view for better understanding. How I can disable any additional (redundancy) info in the assembler code? I want to only leave the pure assembler code

current command (windows) gcc -S .\test.c -masm=intel -O0

output:

```<code>    .file   "test.c"
    .intel_syntax noprefix
    .text
    .def    __main; .scl    2;  .type   32; .endef
    .globl  main
    .def    main;   .scl    2;  .type   32; .endef
    .seh_proc   main
main:
    push    rbp
    .seh_pushreg    rbp
    mov rbp, rsp
    .seh_setframe   rbp, 0
    sub rsp, 32
    .seh_stackalloc 32
    .seh_endprologue
    call    __main
    nop
    add rsp, 32
    pop rbp
    ret
    .seh_endproc
    .ident  "GCC: (x86_64-posix-seh-rev0, Built by MinGW-W64 project) 8.1.0"
</code>```

This output produces redundancy info. For example, I can remove .file   "test.c" it does not affect anything.

Source:

```<code>void main() {
    }
</code>```

答:
gcc -s is the option to strip symbols. However, you can run strip afterwards to remove extra data which still might be included.

What is the difference between "gcc -s" and a "strip" command?

However, this primarily affects the final binary and not necessarily the source code which you get with -S.

If you want to understand the code better, I would recommend to compile it to a binary and load it into a debugger for inspection, keeping the generated asm source as a reference.

Body:
I'm learning reverse engineering. I trying to compile code to assembler view for better understanding. How I can disable any additional (redundancy) info in the assembler code? I want to only leave the pure assembler code

current command (windows) gcc -S .\test.c -masm=intel -O0

output:

    .file   "test.c"
    .intel_syntax noprefix
    .text
    .def    __main; .scl    2;  .type   32; .endef
    .globl  main
    .def    main;   .scl    2;  .type   32; .endef
    .seh_proc   main
main:
    push    rbp
    .seh_pushreg    rbp
    mov rbp, rsp
    .seh_setframe   rbp, 0
    sub rsp, 32
    .seh_stackalloc 32
    .seh_endprologue
    call    __main
    nop
    add rsp, 32
    pop rbp
    ret
    .seh_endproc
    .ident  "GCC: (x86_64-posix-seh-rev0, Built by MinGW-W64 project) 8.1.0"

This output produces redundancy info. For example, I can remove .file   "test.c" it does not affect anything.

Source:

void main() {
    }


问:
Click event doesn't execute on <object> tag
I have an <object> within an anchor tag which has an Angular click event attached to it like this:

```<code><a (click)="myAction()">
  <object data="/images/icon.svg"></object>
</a>
</code>```

When I click directly on the <object> the click event doesn't work, however, when I click on the padding of the anchor tag (or I remove the object and replace it with text or an  icon), the click event does work. What is causing this?

答:
<object>s are separate documents; effectively they are s.

Use an  or inline <svg> element instead.

Body:
I have an <object> within an anchor tag which has an Angular click event attached to it like this:

  <object data="/images/icon.svg"></object>

When I click directly on the <object> the click event doesn't work, however, when I click on the padding of the anchor tag (or I remove the object and replace it with text or an  icon), the click event does work. What is causing this?

Body:
<object>s are separate documents; effectively they are <iframe>s.

Use an <img> or inline <svg> element instead.


问:
Remove Duplicate Result on Query
could help me solve this duplication problem where it returns more than 1 result for the same record I want to bring only 1 result for each id, and only the last history of each record.

My Query:

```<code>SELECT DISTINCT ON(tickets.ticket_id,ticket_histories.created_at)
        ticket.id AS ticket_id,
        tickets.priority,
        tickets.title,
        tickets.company,
        tickets.ticket_statuse,
        tickets.created_at AS created_ticket,
        group_user.id AS group_id,
        group_user.name AS user_group,
        ch_history.description AS ch_description,
        ch_history.created_at AS ch_history
      FROM
        tickets
      INNER JOIN company ON (company.id = tickets.company_id)
      INNER JOIN (SELECT id,
        tickets_id,
        description,
        user_id,
        MAX(tickets.created_at) AS created_ticket
       FROM
        ch_history
       GROUP BY id,
        created_at,
        ticket_id,
        user_id,
        description
      ORDER BY created_at DESC LIMIT 1) AS ch_history ON (ch_history.ticket_id = ticket.id)
      INNER JOIN users ON (users.id = ch_history.user_id)
      INNER JOIN group_users ON (group_users.id = users.group_user_id)
      WHERE company = 15
      GROUP BY
        tickets.id,
        ch_history.created_at DESC;
</code>```

Result of my query, but returns 3 or 5 identical ids with different histories
I want to return only 1 id of each ticket, and only the last recorded history of each tick

```<code> ticket_id | priority |                title                | company_id | ticket_statuse |       created_ticket       |                     company                          |  user_group     | group_id |     ch_description      |        ch_history
            -----------+------------+--------------------------------------+------------+-----------------+----------------------------+------------------------------------------------------+-----------------+----------+------------------------+----------------------------
                 49713 |          2 | REMOVE DATA                       |      1 | t               | 2019-12-09 17:50:35.724485 | SAME COMPANY                                         | people          |        5 | TEST 1                  | 2019-12-10 09:31:45.780667
                 49706 |          2 | INCLUDE DATA                      |      1 | f               | 2019-12-09 09:16:35.320708 | SAME COMPANY                                         | people          |        5 | TEST 2                  | 2019-12-10 09:38:52.769515
                 49706 |          2 | ANY TITLE                         |      1 | f               | 2019-12-09 09:16:35.320708 | SAME COMPANY                                         | people          |        5 | TEST 3                  | 2019-12-10 09:39:22.779473
                 49706 |          2 | NOTING ELSE MAT                   |      1 | f               | 2019-12-09 09:16:35.320708 | SAME COMPANY                                         | people          |        5 | TESTE 4                 | 2019-12-10 09:42:59.50332
                 49706 |          2 | WHITESTRIPES                      |      1 | f               | 2019-12-09 09:16:35.320708 | SAME COMPANY                                         | people          |        5 | TEST 5                  | 2019-12-10 09:44:30.675434
</code>```

wanted to return as below

```<code> ticket_id | priority |                title                | company_id | ticket_statuse |       created_ticket       |                     company                       |  user_group     | group_id |     ch_description      |        ch_history
-----------+------------+--------------------------------------+------------+-----------------+----------------------------+------------------------------------------------------+-----------------+----------+------------------------+----------------------------
     49713 |          2 | REMOVE DATA                       |      1 | t               | 2019-12-09 17:50:10.724485 | SAME COMPANY                                         | people          |        5 | TEST 1                  | 2020-01-01 18:31:45.780667
     49707 |          2 | INCLUDE DATA                      |      1 | f               | 2019-12-11 19:22:21.320701 | SAME COMPANY                                         | people          |        5 | TEST 2                  | 2020-02-05 16:38:52.769515
     49708 |          2 | ANY TITLE                         |      1 | f               | 2019-12-15 07:15:57.320950 | SAME COMPANY                                         | people          |        5 | TEST 3                  | 2020-02-06 07:39:22.779473
     49709 |          2 | NOTING ELSE MAT                   |      1 | f               | 2019-12-16 08:30:28.320881 | SAME COMPANY                                         | people          |        5 | TESTE 4                 | 2020-01-07 11:42:59.50332
     49701 |          2 | WHITESTRIPES                      |      1 | f               | 2019-12-21 11:04:00.320450 | SAME COMPANY                                         | people          |        5 | TEST 5                  | 2020-01-04 10:44:30.675434
</code>```

I wanted to return as shown below, see that the field ch_description, and ch_history bring only the most recent records and only the last of each ticket listed, without duplication I wanted to bring this way could help me.

答:
Two things jump out at me:

You have listed "created at" as part of your "distinct on," which is going to inherently give you multiple rows per ticket id (unless there happens to be only one)

The distinct on should make the subquery on the ticket history unnecessary...  and even if you chose to do it this way, you again are going on the "created at" column, which will give you multiple results.  The ideal subquery, should you choose this approach, would have been to group by ticket_id and only ticket_id.

Slightly related:

An alternative approach to the subquery would be an analytic function (windowing function), but I'll save that for another day.

I think the query you want, which will give you one row per ticket_id, based on the history table's created_at field would be something like this:

```<code>select distinct on (t.id)
  <your fields here>
from
  tickets t
  join company c on t.company_id = c.id
  join ch_history ch on ch.ticket_id = t.id
  join users u on ch.user_id = u.ud
  join group_users g on u.group_user_id = g.id
where
  company = 15
order by
  t.id, ch.created_at  -- this is what tells distinct on which record to choose
</code>```

Title: Remove Duplicate Result on Query

Body:
could help me solve this duplication problem where it returns more than 1 result for the same record I want to bring only 1 result for each id, and only the last history of each record.

My Query:

SELECT DISTINCT ON(tickets.ticket_id,ticket_histories.created_at)
        ticket.id AS ticket_id,
        tickets.priority,
        tickets.title,
        tickets.company,
        tickets.ticket_statuse,
        tickets.created_at AS created_ticket,
        group_user.id AS group_id,
        group_user.name AS user_group,
        ch_history.description AS ch_description,
        ch_history.created_at AS ch_history
      FROM
        tickets
      INNER JOIN company ON (company.id = tickets.company_id)
      INNER JOIN (SELECT id,
        tickets_id,
        description,
        user_id,
        MAX(tickets.created_at) AS created_ticket
       FROM
        ch_history
       GROUP BY id,
        created_at,
        ticket_id,
        user_id,
        description
      ORDER BY created_at DESC LIMIT 1) AS ch_history ON (ch_history.ticket_id = ticket.id)
      INNER JOIN users ON (users.id = ch_history.user_id)
      INNER JOIN group_users ON (group_users.id = users.group_user_id)
      WHERE company = 15
      GROUP BY
        tickets.id,
        ch_history.created_at DESC;

Result of my query, but returns 3 or 5 identical ids with different histories
I want to return only 1 id of each ticket, and only the last recorded history of each tick

 ticket_id | priority |                title                | company_id | ticket_statuse |       created_ticket       |                     company                          |  user_group     | group_id |     ch_description      |        ch_history
            -----------+------------+--------------------------------------+------------+-----------------+----------------------------+------------------------------------------------------+-----------------+----------+------------------------+----------------------------
                 49713 |          2 | REMOVE DATA                       |      1 | t               | 2019-12-09 17:50:35.724485 | SAME COMPANY                                         | people          |        5 | TEST 1                  | 2019-12-10 09:31:45.780667
                 49706 |          2 | INCLUDE DATA                      |      1 | f               | 2019-12-09 09:16:35.320708 | SAME COMPANY                                         | people          |        5 | TEST 2                  | 2019-12-10 09:38:52.769515
                 49706 |          2 | ANY TITLE                         |      1 | f               | 2019-12-09 09:16:35.320708 | SAME COMPANY                                         | people          |        5 | TEST 3                  | 2019-12-10 09:39:22.779473
                 49706 |          2 | NOTING ELSE MAT                   |      1 | f               | 2019-12-09 09:16:35.320708 | SAME COMPANY                                         | people          |        5 | TESTE 4                 | 2019-12-10 09:42:59.50332
                 49706 |          2 | WHITESTRIPES                      |      1 | f               | 2019-12-09 09:16:35.320708 | SAME COMPANY                                         | people          |        5 | TEST 5                  | 2019-12-10 09:44:30.675434

wanted to return as below

 ticket_id | priority |                title                | company_id | ticket_statuse |       created_ticket       |                     company                       |  user_group     | group_id |     ch_description      |        ch_history
-----------+------------+--------------------------------------+------------+-----------------+----------------------------+------------------------------------------------------+-----------------+----------+------------------------+----------------------------
     49713 |          2 | REMOVE DATA                       |      1 | t               | 2019-12-09 17:50:10.724485 | SAME COMPANY                                         | people          |        5 | TEST 1                  | 2020-01-01 18:31:45.780667
     49707 |          2 | INCLUDE DATA                      |      1 | f               | 2019-12-11 19:22:21.320701 | SAME COMPANY                                         | people          |        5 | TEST 2                  | 2020-02-05 16:38:52.769515
     49708 |          2 | ANY TITLE                         |      1 | f               | 2019-12-15 07:15:57.320950 | SAME COMPANY                                         | people          |        5 | TEST 3                  | 2020-02-06 07:39:22.779473
     49709 |          2 | NOTING ELSE MAT                   |      1 | f               | 2019-12-16 08:30:28.320881 | SAME COMPANY                                         | people          |        5 | TESTE 4                 | 2020-01-07 11:42:59.50332
     49701 |          2 | WHITESTRIPES                      |      1 | f               | 2019-12-21 11:04:00.320450 | SAME COMPANY                                         | people          |        5 | TEST 5                  | 2020-01-04 10:44:30.675434

I wanted to return as shown below, see that the field ch_description, and ch_history bring only the most recent records and only the last of each ticket listed, without duplication I wanted to bring this way could help me.

Body:
Two things jump out at me:

You have listed "created at" as part of your "distinct on," which is going to inherently give you multiple rows per ticket id (unless there happens to be only one)

The distinct on should make the subquery on the ticket history unnecessary...  and even if you chose to do it this way, you again are going on the "created at" column, which will give you multiple results.  The ideal subquery, should you choose this approach, would have been to group by ticket_id and only ticket_id.

Slightly related:

An alternative approach to the subquery would be an analytic function (windowing function), but I'll save that for another day.

I think the query you want, which will give you one row per ticket_id, based on the history table's created_at field would be something like this:

select distinct on (t.id)
  <your fields here>
from
  tickets t
  join company c on t.company_id = c.id
  join ch_history ch on ch.ticket_id = t.id
  join users u on ch.user_id = u.ud
  join group_users g on u.group_user_id = g.id
where
  company = 15
order by
  t.id, ch.created_at  -- this is what tells distinct on which record to choose


问:
Replace "/" in a string using shell script
```<code>PATH="/dir1/subdir1"
</code>```

Want to replace "/" with "-" from the above string
and the result should be

-dir1-subdir1

答:
You can use tr for that since you want to replace a single character with another one:

echo $PATH | tr "/" "-"
```

Result is: -dir1-subdir1

Body:
PATH="/dir1/subdir1"

Want to replace "/" with "-" from the above string
and the result should be

-dir1-subdir1

Body:
You can use tr for that since you want to replace a single character with another one:

echo $PATH | tr "/" "-"

Result is: -dir1-subdir1


问:
adding a pdf to a FancyBox gallery
The documentation states "fancybox attempts to automatically detect the type of content based on the given url. If it cannot be detected, the type can also be set manually using data-type attribute (or type option)."  What value should I assign to data-type for a pdf?

If I add a pdf file with an explicit extension of .pdf to a gallery on a webpage, it opens in the fancybox gallery.  But when referenced on a phpBB board by, say, href="./download/file.php?id=15184", I get the error message "The requested content cannot be loaded.  Please try again later."

答:
pdf.js has issues on iOS displaying certain pdf files; the pages appear blank.  I posted the issue on github:  https://github.com/mozilla/pdf.js/issues/11571

Someone suggested it has to do with canvas size; I don't know.  But heuristically, I have discovered that if I reprint any problematic pdf with CutePDF Writer, it generates a pdf that's palatable to pdf.js.  And pdf.js then renders html that's palatable to fancybox.  So now, the whole thing is wired!

Title: adding a pdf to a FancyBox gallery


问:
Pagination does not display the last two data from the database
This is where I set the number of pages and starting point:

    <?php
        $connection = mysqli_connect("localhost", "root");
        $db = mysqli_select_db($connection, 'db_hotelreservation');

        if(isset($_GET['page'])){
            $page = $_GET['page'];
        }
        else {
            $page = 1;
        }

        $number_per_page = 02;
        $start_from = ($page-1)*02;
        echo "$start_from";
        $query = "SELECT * FROM tbl_reservation WHERE room_status = 'Pending' OR room_status = 'Booked' LIMIT $start_from,$number_per_page";
        $query_run = mysqli_query($connection, $query);
        $resultCheck = mysqli_num_rows($query_run);
    ?>
```

<p>This is where the looping and the buttons:</p>

<pre class="lang-php prettyprint-override"><code>    <?php
        $query_result = "SELECT * FROM tbl_reservation WHERE room_status = 'Pending' OR room_status = 'Booked'";
        $result_query = mysqli_query($connection,$query_result);
        $total_records = mysqli_num_rows($result_query);
        echo "Total Records: $total_records <br>";
        $total_page = ceil($total_records/$number_per_page);
        echo "Total Pages: $total_page <br>";

        for($i=1;$i<$total_page;$i++){
            echo "$i";
        }
    ?>
</code>```

Total Records: 8

Total Pages: 4

But then it only prints 3 buttons, kinda confused where did I go wrong.

答:
my guess is you're starting from 1 instead of 0
or use

```<code>for($i=1;$i<=$total_page;$i++){
....
</code>```

instead

Body:
This is where I set the number of pages and starting point:

    <?php
        $connection = mysqli_connect("localhost", "root");
        $db = mysqli_select_db($connection, 'db_hotelreservation');

        if(isset($_GET['page'])){
            $page = $_GET['page'];
        }
        else {
            $page = 1;
        }

        $number_per_page = 02;
        $start_from = ($page-1)*02;
        echo "$start_from";
        $query = "SELECT * FROM tbl_reservation WHERE room_status = 'Pending' OR room_status = 'Booked' LIMIT $start_from,$number_per_page";
        $query_run = mysqli_query($connection, $query);
        $resultCheck = mysqli_num_rows($query_run);
    ?>

This is where the looping and the buttons:

    <?php
        $query_result = "SELECT * FROM tbl_reservation WHERE room_status = 'Pending' OR room_status = 'Booked'";
        $result_query = mysqli_query($connection,$query_result);
        $total_records = mysqli_num_rows($result_query);
        echo "Total Records: $total_records
";
        $total_page = ceil($total_records/$number_per_page);
        echo "Total Pages: $total_page
";

        for($i=1;$i<$total_page;$i++){
            echo "$i";
        }
    ?>

Total Records: 8

Total Pages: 4

But then it only prints 3 buttons, kinda confused where did I go wrong.

Body:
my guess is you're starting from 1 instead of 0
or use

for($i=1;$i<=$total_page;$i++){
....

instead


问:
Need Help - First Function
I'm trying to write my first function and am having some issues.  When I run the below I get no output.  I feel like I'm missing something obvious but I'm not sure what.

```<code>function findModifiedFiles {
    [CmdletBinding()]
    param (
        [string]$dir,
        [int]$days
    )
    Process {
        Write-Host "Directory: " $dir
        Write-Host "Days: "$days
    }
}
</code>```

Output:

答:
You ultimately need to load your function and then call the function to receive any output. Since your function is defined in a file, one way to load the function is by dot sourcing the file. Then you can simply call your function.

```<code>. .\modfilesTest.ps1
findModifiedFiles -dir c:\temp -days 7
</code>```

An alternative is to not use a function at all just run the script with parameters. If we edit your file to contain the following, we can just call the script afterwards.

```<code># modfilesTest.ps1 Contents
[CmdletBinding()]
param (
    [string]$dir,
    [int]$days
)
Process {
    Write-Host "Directory: " $dir
    Write-Host "Days: "$days
}
</code>```

Now call the script with your parameters.

```<code>.\modfilesTest.ps1 -dir c:\temp -days 7
</code>```

A third alternative is to just paste a function definition into your console. At that point, the function is loaded into your current scope. Then you can just call the function.

Title: Need Help - First Function

Body:
I'm trying to write my first function and am having some issues.  When I run the below I get no output.  I feel like I'm missing something obvious but I'm not sure what.

function findModifiedFiles {
    [CmdletBinding()]
    param (
        [string]$dir,
        [int]$days
    )
    Process {
        Write-Host "Directory: " $dir
        Write-Host "Days: "$days
    }
}

Output:

Body:
You ultimately need to load your function and then call the function to receive any output. Since your function is defined in a file, one way to load the function is by dot sourcing the file. Then you can simply call your function.

. .\modfilesTest.ps1
findModifiedFiles -dir c:\temp -days 7

An alternative is to not use a function at all just run the script with parameters. If we edit your file to contain the following, we can just call the script afterwards.

# modfilesTest.ps1 Contents
[CmdletBinding()]
param (
    [string]$dir,
    [int]$days
)
Process {
    Write-Host "Directory: " $dir
    Write-Host "Days: "$days
}

Now call the script with your parameters.

.\modfilesTest.ps1 -dir c:\temp -days 7

A third alternative is to just paste a function definition into your console. At that point, the function is loaded into your current scope. Then you can just call the function.


问:
Recursively add an extension to a group of files in PowerShell Version. 4
I'm looking at how to add an extension recursively to an entire folder structure. This line does what I need, but only for the current folder. I need to do the same for the subfolders structure.

```<code>Get-ChildItem -File | % { mv ($_.BaseName+"") ($_.BaseName+".png") }
</code>```

But I keep getting this error:

```<code>Cannot find path 'C:\Users\Jess...\' because it does not exist.
</code>```

I used the search, however I only founded a solution for the Bash, not the PowerShell. So I couldn't get the -Recurse to work in the same way.

```<code>Get-ChildItem -File -Recurse | % { mv ($_.BaseName+"") ($_.BaseName+".png") }
</code>```

答:
Here's a way to get the full pathname.  In powershell 6 this isn't an issue.

```<code>Get-ChildItem -File -Recurse | % { $_ | mv -destination ($_.Name + '.png' ) -whatif }
</code>```

Or

```<code>Get-ChildItem -File -Recurse | ? { ! $_.extension } |
  mv -destination { $_.Name + '.png' } -whatif
</code>```

Body:
I'm looking at how to add an extension recursively to an entire folder structure. This line does what I need, but only for the current folder. I need to do the same for the subfolders structure.

Get-ChildItem -File | % { mv ($_.BaseName+"") ($_.BaseName+".png") }

But I keep getting this error:

Cannot find path 'C:\Users\Jess...\' because it does not exist.

I used the search, however I only founded a solution for the Bash, not the PowerShell. So I couldn't get the -Recurse to work in the same way.

Get-ChildItem -File -Recurse | % { mv ($_.BaseName+"") ($_.BaseName+".png") }

Body:
Here's a way to get the full pathname.  In powershell 6 this isn't an issue.

Get-ChildItem -File -Recurse | % { $_ | mv -destination ($_.Name + '.png' ) -whatif }

Or

Get-ChildItem -File -Recurse | ? { ! $_.extension } |
  mv -destination { $_.Name + '.png' } -whatif


问:
PHP: Write to disk permission
I am trying to make a notepad application which saves files if you press save, but it gives an error. I think the script(or apache) doesn't have the permissions to write to the disk but I might be wrong.

Does anyone know what to change about my code or how to set the permissions? It would be heavily gracious and appreciated if someone could fix this problem for me.

Code(Yes I know this is spaghetti-code but this is how I learned html and php):

```<code><html>
<style>
button {
    display: inline-block;
    background-color: #4CAF50;
    padding: 15px 32px;
    font-size: 16px;
    font-size: 16px;
    color: white;
    text-align: center;
    border: none;

}
</style>
<style>
    input {
    display: inline-block;
    background-color: #4CAF50;
    padding: 15px 32px;
    font-size: 16px;
    font-size: 16px;
    color: white;
    text-align: center;
    border: none;

}
</style>
<center><b><font size="7">Notepad</font></b></center>
<br>
<center><form>
        <textarea rows="1" cols="50" name="filename">filename</textarea>
        <br>
        <textarea rows="1" cols="50" name="text">Lorem ipsum</textarea>
        <input type="submit" name="submit" value="save">
    </form></center>
<br>
</html>
<?php

if(isset($_GET['text'])) {
    $text = $_GET['text'];
    $filename = $_GET['filename'];

    $myfile = fopen("$filename", "w") or die("Unable to open file!");
    $txt = $text;
    fwrite($myfile, $txt);
    fclose($myfile);

    echo("<center>Your file is saved as $filename</center>");
}

?>
</code>```

BTW: I am hosting this script on my LinuxMint(Ubuntu linux) computer using Apache2 and PHP

答: Try chown -R www-data:www-data /path-to-root-directory

Title: PHP: Write to disk permission

Body:
I am trying to make a notepad application which saves files if you press save, but it gives an error. I think the script(or apache) doesn't have the permissions to write to the disk but I might be wrong.

Does anyone know what to change about my code or how to set the permissions? It would be heavily gracious and appreciated if someone could fix this problem for me.

Code(Yes I know this is spaghetti-code but this is how I learned html and php):

Notepad

<form>
        <textarea rows="1" cols="50" name="filename">filename</textarea>

        <textarea rows="1" cols="50" name="text">Lorem ipsum</textarea>
        <input type="submit" name="submit" value="save">
    </form>

<?php

if(isset($_GET['text'])) {
    $text = $_GET['text'];
    $filename = $_GET['filename'];

    $myfile = fopen("$filename", "w") or die("Unable to open file!");
    $txt = $text;
    fwrite($myfile, $txt);
    fclose($myfile);

    echo("Your file is saved as $filename");
}

?>

BTW: I am hosting this script on my LinuxMint(Ubuntu linux) computer using Apache2 and PHP


问:
Calling C# async method from F# results in a deadlock
I have a set of F# scripts that call various libraries that we have created, many of them exposing asynchronous methods originally written in C#. Recently I found out the scripts stopped working (I think it's about half a year since I used them last time and they worked back then).

I was trying to isolate the problem and came up with the following code that reproduces it:

First, let's consider a library containing the following C# class:

```<code>    public class AsyncClass
    {
        public async Task<string> GetStringAsync()
        {
            var uri = new Uri("https://www.google.com");
            var client = new HttpClient();
            var response = await client.GetAsync(uri);
            var body = await response.Content.ReadAsStringAsync();
            return body;
        }
    }
</code>```

Next, let's call the library from F# (FSX script) using the following code:

```<code>let asyncClient = AsyncClass()

let strval1 = asyncClient.GetStringAsync() |> Async.AwaitTask |> Async.RunSynchronously
printfn "%s" strval1

let strval2 =
    async {
        return! asyncClient.GetStringAsync() |> Async.AwaitTask
    } |> Async.RunSynchronously
printfn "%s" strval2
</code>```

Obtaining strval1 ends up with a deadlock, whereas strval2 is retrieved just fine (I am quite sure the first scenario used to work too a couple of months ago so it looks like some sort of an update might have caused this).

This is most likely a synchronisation context issue where the thread is basically "waiting for itself to finish", but I don't understand what exactly is wrong with the first call - I can't see anything wrong with it.

Similar issues on StackOverflow:

Why do I have to wrap an Async<T> into another async workflow and let! it? - this seems to be the same question, but not enough information is given and a simple reproducing example is missing

Why is Async.RunSynchronously hanging? - this is similar but there is an obvious mistake the author has made

答:
So a .net Task will start immediately, while F# async {} is lazy. So when you wrap a task inside an async { } it becomes lazy, and thus will have the characteristics that Async.RunSynchronously is expecting.

Generally I use async {} when I'm doing f# asynchronous operations only, and if I'm working with .net Tasks I'll use TaskBuilder.fs (available in nuget).  It's more aware of Task idiosyncrasies like ConfigureAwait(continueOnCapturedContext: false).

```<code>open FSharp.Control.Tasks.V2.ContextInsensitive

task {
    let! x = asyncClient.GetStringAsync()
    //do something with x
}
</code>```

Body:
I have a set of F# scripts that call various libraries that we have created, many of them exposing asynchronous methods originally written in C#. Recently I found out the scripts stopped working (I think it's about half a year since I used them last time and they worked back then).

I was trying to isolate the problem and came up with the following code that reproduces it:

First, let's consider a library containing the following C# class:

    public class AsyncClass
    {
        public async Task<string> GetStringAsync()
        {
            var uri = new Uri("https://www.google.com");
            var client = new HttpClient();
            var response = await client.GetAsync(uri);
            var body = await response.Content.ReadAsStringAsync();
            return body;
        }
    }

Next, let's call the library from F# (FSX script) using the following code:

let asyncClient = AsyncClass()

let strval1 = asyncClient.GetStringAsync() |> Async.AwaitTask |> Async.RunSynchronously
printfn "%s" strval1

let strval2 =
    async {
        return! asyncClient.GetStringAsync() |> Async.AwaitTask
    } |> Async.RunSynchronously
printfn "%s" strval2

Obtaining strval1 ends up with a deadlock, whereas strval2 is retrieved just fine (I am quite sure the first scenario used to work too a couple of months ago so it looks like some sort of an update might have caused this).

This is most likely a synchronisation context issue where the thread is basically "waiting for itself to finish", but I don't understand what exactly is wrong with the first call - I can't see anything wrong with it.

Similar issues on StackOverflow:

Why do I have to wrap an Async<T> into another async workflow and let! it? - this seems to be the same question, but not enough information is given and a simple reproducing example is missing

Why is Async.RunSynchronously hanging? - this is similar but there is an obvious mistake the author has made

Body:
So a .net Task will start immediately, while F# async {} is lazy. So when you wrap a task inside an async { } it becomes lazy, and thus will have the characteristics that Async.RunSynchronously is expecting.

Generally I use async {} when I'm doing f# asynchronous operations only, and if I'm working with .net Tasks I'll use TaskBuilder.fs (available in nuget).  It's more aware of Task idiosyncrasies like ConfigureAwait(continueOnCapturedContext: false).

open FSharp.Control.Tasks.V2.ContextInsensitive

task {
    let! x = asyncClient.GetStringAsync()
    //do something with x
}