问:
Unable to pass "this" pointer to another class and calling any methods of that class in CPP
Here I am trying to pass the instance of ATMMachine using "this" keyword to the HasCard class and trying to call any method of ATMMachine from HasClass using that instance. But I am not able to call any of the methods of ATMMachine.
For example unable to call machine->insertCard();
Could someone please help me to find out where the problem is?
Is there any better approach in CPP to communicate between classes?

```<code>class ATMState{
    virtual void insertCard() = 0;
    virtual void ejectCard() = 0;
    virtual void insertPin(int pinNumber) = 0;
    virtual void withdrawCash(int amount) = 0;
};

class ATMMachine;

class HasCard: public ATMState {
private:
    ATMMachine* machine;
public:
    HasCard(ATMMachine* _machine) {
        machine = _machine;
        machine->insertCard();
    }
    void insertCard() {

    }

    void ejectCard() {

    }

    void insertPin(int pinNumber) {

    }

    void withdrawCash(int amount) {

    }
};

class ATMMachine{
    public:
    int balance;
    ATMState* currentState;
    ATMState* hasCard;
    ATMState* noCard;
    ATMState* hasPin;
    ATMState* noCash;

    ATMMachine() {
        hasCard =  new HasCard(this);
//        noCard =  new NoCard();
//        noCash =  new NoCash();
//        hasPin =  new HasPin();
        currentState = hasCard;
    }

    void insertCard() {
        cout<<"Card has been inserted" <<endl;
    }

    void ejectCard() {

    }

    void insertPin(int pinNumber) {

    }

    void withdrawCash(int amount) {

    }
};
</code>```

答:
But I am not able to call any of the methods of ATMMachine. with the forward declaration class ATMMachine; you only tell that this class exists, but the compiler does not know anything of its member functions until the full class definition is reached.

That's why you get an error like this:

```<code>   invalid use of incomplete type 'class ATMMachine'
       machine->insertCard();
   note: forward declaration of 'class ATMMachine'
       class ATMMachine;
</code>```

If you have this kind of cross dependencies you need to split the declaration of the member functions, constructors, or destructors and their definitions.

```<code>class ATMState {
  virtual void insertCard() = 0;
  virtual void ejectCard() = 0;
  virtual void insertPin(int pinNumber) = 0;
  virtual void withdrawCash(int amount) = 0;
};

class ATMMachine;

class HasCard : public ATMState {
private:
  ATMMachine *machine;

public:
  // only declare the constructor here
  HasCard(ATMMachine *_machine);

  void insertCard() {}

  void ejectCard() {}

  void insertPin(int pinNumber) {}

  void withdrawCash(int amount) {}
};

class ATMMachine {
public:
  int balance;
  ATMState *currentState;
  ATMState *hasCard;
  ATMState *noCard;
  ATMState *hasPin;
  ATMState *noCash;

  ATMMachine() {
    hasCard = new HasCard(this);
    //        noCard =  new NoCard();
    //        noCash =  new NoCash();
    //        hasPin =  new HasPin();
    currentState = hasCard;
  }

  void insertCard() { cout << "Card has been inserted" << endl; }

  void ejectCard() {}

  void insertPin(int pinNumber) {}

  void withdrawCash(int amount) {}
};

// move the definition of the HasCard constructor after the declaration of ATMMachine
HasCard::HasCard(ATMMachine *_machine){
    machine = _machine;
    machine->insertCard();
}
</code>```

Is there any better approach in CPP to communicate between classes? Having the need to do something like that is often an indication that you should restructure your code. There are various ways how to solve such issues each with their pros and cons. But that's something to ask on codereview.

Body:
Here I am trying to pass the instance of ATMMachine using "this" keyword to the HasCard class and trying to call any method of ATMMachine from HasClass using that instance. But I am not able to call any of the methods of ATMMachine.
For example unable to call machine->insertCard();
Could someone please help me to find out where the problem is?
Is there any better approach in CPP to communicate between classes?

class ATMState{
    virtual void insertCard() = 0;
    virtual void ejectCard() = 0;
    virtual void insertPin(int pinNumber) = 0;
    virtual void withdrawCash(int amount) = 0;
};

class ATMMachine;

class HasCard: public ATMState {
private:
    ATMMachine* machine;
public:
    HasCard(ATMMachine* _machine) {
        machine = _machine;
        machine->insertCard();
    }
    void insertCard() {

    }

    void ejectCard() {

    }

    void insertPin(int pinNumber) {

    }

    void withdrawCash(int amount) {

    }
};

class ATMMachine{
    public:
    int balance;
    ATMState* currentState;
    ATMState* hasCard;
    ATMState* noCard;
    ATMState* hasPin;
    ATMState* noCash;

    ATMMachine() {
        hasCard =  new HasCard(this);
//        noCard =  new NoCard();
//        noCash =  new NoCash();
//        hasPin =  new HasPin();
        currentState = hasCard;
    }

    void insertCard() {
        cout<<"Card has been inserted" <<endl;
    }

    void ejectCard() {

    }

    void insertPin(int pinNumber) {

    }

    void withdrawCash(int amount) {

    }
};

Body:
But I am not able to call any of the methods of ATMMachine. with the forward declaration class ATMMachine; you only tell that this class exists, but the compiler does not know anything of its member functions until the full class definition is reached.

That's why you get an error like this:

   invalid use of incomplete type 'class ATMMachine'
       machine->insertCard();
   note: forward declaration of 'class ATMMachine'
       class ATMMachine;

If you have this kind of cross dependencies you need to split the declaration of the member functions, constructors, or destructors and their definitions.

class ATMState {
  virtual void insertCard() = 0;
  virtual void ejectCard() = 0;
  virtual void insertPin(int pinNumber) = 0;
  virtual void withdrawCash(int amount) = 0;
};

class ATMMachine;

class HasCard : public ATMState {
private:
  ATMMachine *machine;

public:
  // only declare the constructor here
  HasCard(ATMMachine *_machine);

  void insertCard() {}

  void ejectCard() {}

  void insertPin(int pinNumber) {}

  void withdrawCash(int amount) {}
};

class ATMMachine {
public:
  int balance;
  ATMState *currentState;
  ATMState *hasCard;
  ATMState *noCard;
  ATMState *hasPin;
  ATMState *noCash;

  ATMMachine() {
    hasCard = new HasCard(this);
    //        noCard =  new NoCard();
    //        noCash =  new NoCash();
    //        hasPin =  new HasPin();
    currentState = hasCard;
  }

  void insertCard() { cout << "Card has been inserted" << endl; }

  void ejectCard() {}

  void insertPin(int pinNumber) {}

  void withdrawCash(int amount) {}
};

// move the definition of the HasCard constructor after the declaration of ATMMachine
HasCard::HasCard(ATMMachine *_machine){
    machine = _machine;
    machine->insertCard();
}

Is there any better approach in CPP to communicate between classes? Having the need to do something like that is often an indication that you should restructure your code. There are various ways how to solve such issues each with their pros and cons. But that's something to ask on codereview.


来源: stackexchange

问:
Retrieving Firebase Child Value in Javascript
```<code>function sontinue() {
    var user = firebase.auth().currentUser;
    var uid = user.uid;

    var adaRef = firebase.database().ref("User/" + uid);
    if (adaRef.orderByChild("Role").equalTo("admin")) {
        location.href = "DB.html";
    } else {
        location.href = "index.html";
    }

}
</code>```

I would like to link my "admin" account to DB.html and "user" account to index.html but i think i always failed in Retrieving the Child Value.

答:
You're not retrieving the data from the server. Remember you need to call .once('value') to get your query and then iterate through the remaining code based onw hether their value is of admin or user. Firebase Docs has more explination  I've amended your code and put it below

```<code>  function sontinue() {
            var user = firebase.auth().currentUser;
            var uid = user.uid;

            var adaRef = firebase.database().ref("User/" + uid).orderByChild("Role");
            //you now need to retrieve the data

            return adaRef.once('value').then((snapshot)=>{
                return snapshot.forEach(snapshot=>{
                if (snapshot.child("Role").val()==="admin") {
                location.href = "DB.html";
                 } else {
                location.href = "index.html";
                }
                return console.log("added");
                })

            })

        }
</code>```

If you just wanted to find out who was of the user type admin...i'd use this below...much more efficient.

```<code>   function sontinue() {
        var user = firebase.auth().currentUser;
        var uid = user.uid;

        var adaRef = firebase.database().ref("User/" + uid).orderByChild("Role").equalTo("admin");
        //you now need to retrieve the data

        return adaRef.once('value').then((snapshot)=>{
            //you now have all the users that are just admins
            return snapshot.forEach(snapshot=>{
            location.href = "DB.html";
            return console.log("added");
            })

        })

    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
function sontinue() {
    var user = firebase.auth().currentUser;
    var uid = user.uid;

    var adaRef = firebase.database().ref("User/" + uid);
    if (adaRef.orderByChild("Role").equalTo("admin")) {
        location.href = "DB.html";
    } else {
        location.href = "index.html";
    }

}

I would like to link my "admin" account to DB.html and "user" account to index.html but i think i always failed in Retrieving the Child Value.

Body:
You're not retrieving the data from the server. Remember you need to call .once('value') to get your query and then iterate through the remaining code based onw hether their value is of admin or user. Firebase Docs has more explination  I've amended your code and put it below

  function sontinue() {
            var user = firebase.auth().currentUser;
            var uid = user.uid;

            var adaRef = firebase.database().ref("User/" + uid).orderByChild("Role");
            //you now need to retrieve the data

            return adaRef.once('value').then((snapshot)=>{
                return snapshot.forEach(snapshot=>{
                if (snapshot.child("Role").val()==="admin") {
                location.href = "DB.html";
                 } else {
                location.href = "index.html";
                }
                return console.log("added");
                })

            })

        }

If you just wanted to find out who was of the user type admin...i'd use this below...much more efficient.

   function sontinue() {
        var user = firebase.auth().currentUser;
        var uid = user.uid;

        var adaRef = firebase.database().ref("User/" + uid).orderByChild("Role").equalTo("admin");
        //you now need to retrieve the data

        return adaRef.once('value').then((snapshot)=>{
            //you now have all the users that are just admins
            return snapshot.forEach(snapshot=>{
            location.href = "DB.html";
            return console.log("added");
            })

        })

    }


问:
What is a .dbml.layout file for?
What is a .dbml.layout file for? Is it important? Or, maybe, it just stores the placing of blocks in the designer and can be deleted?

I've got this question because I want to edit the .dbml file manually and need to know if I must edit .dbml.layout accordingly or can just delete it to get it recreated automatically. Luckily it seems for me that it is indeed autogenerated.

答:
not quite.  the designer file stores the code generated by the designer that you use to access the database it literally is the linq to SQL classes the designer the dbml file is just an XML document that you can actually open and edit manually tho this not recommended
for a beginner </p>

ContentLicense: CC BY-SA 3.0

Title: What is a .dbml.layout file for?


问:
Cross Tabulation with R Markdown
I have struggle creating a simple nice looking cross tabulation for a PDF knitted R Markdown document. I have a data set that is similar to this example:

```<code>library(tidyverse)
fakeData <- tibble(id = c(1,2,3,4,5,6,7,8,9,10),
                   bmi = c("normal", "overweighted", "underweighted", "normal", "normal", "overweighted",
                           "normal", "overweighted", "underweighted","normal"),
                   gender = c("M", "F", "M", "M", "F", "F", "M", "F", "F", "F"))
</code>```

I want to get an output like this one:

Have anyone a trick/ a known good package to do this? Thanks a lot!

答:
I think the janitor-package can help you out here...

note: the percentages in the 'total' column do not match your desired output... That is because you are mixing colwise and rowwise percentage calculation in your output.. Is that really what you want?

```<code>library( janitor )

fakeTable <- fakeData %>%
  tabyl( gender, bmi ) %>%
  adorn_totals( where = c("row", "col") ) %>%
  adorn_percentages("row") %>%
  adorn_pct_formatting() %>%
  adorn_ns( position = "front" ) %>%
  adorn_title("combined")

# gender/bmi    normal overweighted underweighted       Total
#          F 2 (33.3%)    3 (50.0%)     1 (16.7%)  6 (100.0%)
#          M 3 (75.0%)    0  (0.0%)     1 (25.0%)  4 (100.0%)
#      Total 5 (50.0%)    3 (30.0%)     2 (20.0%) 10 (100.0%)
</code>```

knitted

```<code>library(knitr)
library(kableExtra)
fakeTable %>%
  kable() %>%
  kable_styling(bootstrap_options = c("condensed", "striped", "bordered"))
</code>```

Title: Cross Tabulation with R Markdown

Body:
I have struggle creating a simple nice looking cross tabulation for a PDF knitted R Markdown document. I have a data set that is similar to this example:

library(tidyverse)
fakeData <- tibble(id = c(1,2,3,4,5,6,7,8,9,10),
                   bmi = c("normal", "overweighted", "underweighted", "normal", "normal", "overweighted",
                           "normal", "overweighted", "underweighted","normal"),
                   gender = c("M", "F", "M", "M", "F", "F", "M", "F", "F", "F"))

I want to get an output like this one:

Have anyone a trick/ a known good package to do this? Thanks a lot!

Body:
I think the janitor-package can help you out here...

note: the percentages in the 'total' column do not match your desired output... That is because you are mixing colwise and rowwise percentage calculation in your output.. Is that really what you want?

library( janitor )

fakeTable <- fakeData %>%
  tabyl( gender, bmi ) %>%
  adorn_totals( where = c("row", "col") ) %>%
  adorn_percentages("row") %>%
  adorn_pct_formatting() %>%
  adorn_ns( position = "front" ) %>%
  adorn_title("combined")

# gender/bmi    normal overweighted underweighted       Total
#          F 2 (33.3%)    3 (50.0%)     1 (16.7%)  6 (100.0%)
#          M 3 (75.0%)    0  (0.0%)     1 (25.0%)  4 (100.0%)
#      Total 5 (50.0%)    3 (30.0%)     2 (20.0%) 10 (100.0%)

knitted

library(knitr)
library(kableExtra)
fakeTable %>%
  kable() %>%
  kable_styling(bootstrap_options = c("condensed", "striped", "bordered"))


问:
How to get the member count in discord.py rewrite?
I wanted to make an command to show the membercount but it doesn't work.

This is what I have:

```<code>@bot.command(name='membercount')
async def membercount(ctx):
    await ctx.send(len(guild.member_count))
</code>```

and this is the error i get:
Module 'discord.guild' has no 'member_count' member

I tried searching on the internet but didn't find a working option.

答:
Although Ron's example does work, it is not a very elegant way considering that ctx.guild.members is just a list, meaning you can use len() on it as such:

```<code>member_count = len(ctx.guild.members) # includes bots

true_member_count = len([m for m in ctx.guild.members if not m.bot]) # doesn't include bots
</code>```

Also don't forget that if an answer solved your problem, you should mark it as "accepted" with that checkmark next to it, as to show other users coming from search machines to this question, what worked for you.

Body:
I wanted to make an command to show the membercount but it doesn't work.

This is what I have:

@bot.command(name='membercount')
async def membercount(ctx):
    await ctx.send(len(guild.member_count))

and this is the error i get:
Module 'discord.guild' has no 'member_count' member

I tried searching on the internet but didn't find a working option.

Body:
Although Ron's example does work, it is not a very elegant way considering that ctx.guild.members is just a list, meaning you can use len() on it as such:

member_count = len(ctx.guild.members) # includes bots

true_member_count = len([m for m in ctx.guild.members if not m.bot]) # doesn't include bots

Also don't forget that if an answer solved your problem, you should mark it as "accepted" with that checkmark next to it, as to show other users coming from search machines to this question, what worked for you.


问:
map over nested array in react
I want to display the values of the following data which is received when i make fetch request:

data: Array

```<code>0: Object
  title: "html"
  description: Array
  name: "xyz"
  class: "c"

1: Object
  title: "html1"
  description: Array
  name: "xyz1"
  class: "c1"
</code>```

I have tried following code:

```<code><div>
  {
    data.map((item, index) => {
      <h1 key={index}>{item.title}/</h1>
      { item.description.map((c, i) =>
        <div>
          <h3 key={i}>{c.name} {c.class}</h3>
        </div>
      )}
    })
  }
</div>
</code>```

The above code displays only the title value. It's not displaying name and class value. Please help me.

答:
If description is an object then you don't need to map over description again
this alone should do

   {
   data.map((item, index) => {

{item.title}/

{item.description.name} {item.description.class}

  })
}

```

Title: map over nested array in react

Body:
I want to display the values of the following data which is received when i make fetch request:

data: Array

0: Object
  title: "html"
  description: Array
  name: "xyz"
  class: "c"

1: Object
  title: "html1"
  description: Array
  name: "xyz1"
  class: "c1"

I have tried following code:

  {
    data.map((item, index) => {

{item.title}/

      { item.description.map((c, i) =>

{c.name} {c.class}

      )}
    })
  }

The above code displays only the title value. It's not displaying name and class value. Please help me.

Body:
If description is an object then you don't need to map over description again
this alone should do

   <div>
   {
   data.map((item, index) => {

        <h1 key={index}>{item.title}/</h1>
        <div>
            <h3>{item.description.name} {item.description.class}</h3>
        </div>
  })
}
</div>


问:
Check path folder by vb
I am trying to get folderpath and then looping for Excel sheet in this folder

```<code>Imports Excel= Microsoft.Office.Interop.Excel

Public Sub Combine()

    Dim objApp As Excel.Application
    Dim objBook As Excel.Workbook
    Dim objSheet As Excel.Worksheet
    Dim myrange As Excel.Range
    Dim folderPath As String
    Dim fileName As String

    folderPath = @"FolderPath"
    fileName = Dir(folderPath & "*.xls")

    Do While (fileName <> "")

        objBook = objApp.Workbooks.Open(Filename:=Txt_GetPath.Text & fileName = True)
        objBook.Activate()

        For Each objSheet In objBook.Sheets
            objSheet.Copy(After:=objBook.Sheets(1))
        Next objSheet

        objBook.Close()

    Loop

End Sub
</code>```

But at the line objBook =objApp.Workbooks.open(...) I get an error of

The path must be full

What is wrong with the code?

答:
```<code>    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim strFileName As String
    Dim xl As New Excel.Application
    Dim wb As Excel.Workbook
    Dim ws As Excel.Worksheet
    If FolderBrowserDialog1.ShowDialog = System.Windows.Forms.DialogResult.OK Then
        Dim Directory = FolderBrowserDialog1.SelectedPath
        Dim Files() As System.IO.FileInfo
        Dim DirInfo As New System.IO.DirectoryInfo(Directory)
        Files = DirInfo.GetFiles("*", IO.SearchOption.AllDirectories)
        For Each File In Files
            wb = xl.Workbooks.Open(File.FullName)
            For Each ws In wb.Sheets
                strFileName = Microsoft.VisualBasic.Left(File.Name,
        (InStrRev(File.Name, ".", -1, vbTextCompare) - 1))
                If ws.Name = "SCHEDULE" Then
                    ws.Range("S7", "S50").Value2 = strFileName
                End If
            Next
            wb.Close()
        Next
        xl.Quit()
    End If
    End Sub
</code>```

Title: Check path folder by vb

Body:
I am trying to get folderpath and then looping for Excel sheet in this folder

Imports Excel= Microsoft.Office.Interop.Excel

Public Sub Combine()

    Dim objApp As Excel.Application
    Dim objBook As Excel.Workbook
    Dim objSheet As Excel.Worksheet
    Dim myrange As Excel.Range
    Dim folderPath As String
    Dim fileName As String

    folderPath = @"FolderPath"
    fileName = Dir(folderPath & "*.xls")

    Do While (fileName <> "")

        objBook = objApp.Workbooks.Open(Filename:=Txt_GetPath.Text & fileName = True)
        objBook.Activate()

        For Each objSheet In objBook.Sheets
            objSheet.Copy(After:=objBook.Sheets(1))
        Next objSheet

        objBook.Close()

    Loop

End Sub

But at the line objBook =objApp.Workbooks.open(...) I get an error of

The path must be full

What is wrong with the code?


问:
How to make a row into column in PENTAHO
I have a file like this:

```<code>COUNTRY | 2008 | 2009 | 2010 | 2011 | 2012 | TYPE
SPAIN      5      41     8      12      5     T1
SPAIN      4      6       2      7      14    T2
SPAIN      7      8      9       6      2     T3
FRANCE     4      5      7       9      66    T1
FRANCE     14     3      4       12     12    T2
FRANCE     5      8      11       3      6    T3
...
</code>```

And I need to convert it into a format like:

```<code>COUNTRY | YEAR | T1 | T2 | T3
SPAIN     2008   5    4    7
SPAIN     2009   41   6    8
....
</code>```

Thanks

答:
If you're talking about Pentaho Data Integration you can use the Row Normalizer step. It allows you to define the columns that hold measure types, and convert them into a single "type" column.

Check the documentation for examples of usage.

Body:
I have a file like this:

COUNTRY | 2008 | 2009 | 2010 | 2011 | 2012 | TYPE
SPAIN      5      41     8      12      5     T1
SPAIN      4      6       2      7      14    T2
SPAIN      7      8      9       6      2     T3
FRANCE     4      5      7       9      66    T1
FRANCE     14     3      4       12     12    T2
FRANCE     5      8      11       3      6    T3
...

And I need to convert it into a format like:

COUNTRY | YEAR | T1 | T2 | T3
SPAIN     2008   5    4    7
SPAIN     2009   41   6    8
....

Thanks


问:
try/except issue statement in python 3
Hello I am new to Python and learning basics. I am curious to understand try/except statements in Python and I want to ask whether I should keep as little as possible in try block/portion as mentioned below (Please refer Following Code Working Properly) or try to keep as much in try block/portion (Please refer Following Code Not Working Properly When I Enter Any String but it works when I enter float/integer).

So, these are the two scenarios almost the same but the other code (in which I am keeping minimum code) is giving me an error when I enter a string.

Why is that doing it? What should I do in that case if I want to keep as little as possible in try/except blocks? Any leads would be highly appreciated. What's the alternate correct solution of my second code in which I am keeping minimum lines of code?  - What adjustment I am supposed to make in it to work for me? Please help.

```<code>NameError: name 'fahr' is not defined
</code>```

```<code>***# Following Code Working Properly:***
inp = input('Enter Fahrenheit Temperature:')
try:
    fahr = float(inp)
    cel = (fahr - 32.0) * 5.0 / 9.0
    print(cel)
except:
    print('Please enter a number')
</code>```

```<code>***# Following Code Not Working Properly:***
inp = input('Enter Fahrenheit Temperature:')

try:
    fahr = float(inp)
except:
    print('Please enter a number')

fahr = float(inp) # Even if I comment it, it doesn't make any difference when it comes to entering float in an input but it raises red flag if I enter string.
cel = (fahr - 32.0) * 5.0 / 9.0
print(cel)
</code>```

答:
Your first set of code is fine, but it doesn't recover from the error.  If you'd like the program to gracefully recover and ask again for an input, you'll need to continually loop the input and try until it passes, like such.</p>

```<code>while True:
    inp = input('Enter Fahrenheit Temperature:')
    try:
        fahr = float(inp)
        break
    except:
        print('Please enter a number')

fahr = float(inp) # Even if I comment it, it doesn't make any difference when it comes to entering float in an input but it raises red flag if I enter string.
cel = (fahr - 32.0) * 5.0 / 9.0
print(cel)
</code>```

Title: try/except issue statement in python 3

Body:
Hello I am new to Python and learning basics. I am curious to understand try/except statements in Python and I want to ask whether I should keep as little as possible in try block/portion as mentioned below (Please refer Following Code Working Properly) or try to keep as much in try block/portion (Please refer Following Code Not Working Properly When I Enter Any String but it works when I enter float/integer).

So, these are the two scenarios almost the same but the other code (in which I am keeping minimum code) is giving me an error when I enter a string.

Why is that doing it? What should I do in that case if I want to keep as little as possible in try/except blocks? Any leads would be highly appreciated. What's the alternate correct solution of my second code in which I am keeping minimum lines of code?  - What adjustment I am supposed to make in it to work for me? Please help.

NameError: name 'fahr' is not defined

***# Following Code Working Properly:***
inp = input('Enter Fahrenheit Temperature:')
try:
    fahr = float(inp)
    cel = (fahr - 32.0) * 5.0 / 9.0
    print(cel)
except:
    print('Please enter a number')

***# Following Code Not Working Properly:***
inp = input('Enter Fahrenheit Temperature:')

try:
    fahr = float(inp)
except:
    print('Please enter a number')

fahr = float(inp) # Even if I comment it, it doesn't make any difference when it comes to entering float in an input but it raises red flag if I enter string.
cel = (fahr - 32.0) * 5.0 / 9.0
print(cel)

Body:
Your first set of code is fine, but it doesn't recover from the error.  If you'd like the program to gracefully recover and ask again for an input, you'll need to continually loop the input and try until it passes, like such.

while True:
    inp = input('Enter Fahrenheit Temperature:')
    try:
        fahr = float(inp)
        break
    except:
        print('Please enter a number')

fahr = float(inp) # Even if I comment it, it doesn't make any difference when it comes to entering float in an input but it raises red flag if I enter string.
cel = (fahr - 32.0) * 5.0 / 9.0
print(cel)


问:
Dynamically changing the height of a div

Possible Duplicate:

  Height of a div

Hello,

I have a DIV where I want the height to be based on the viewable area of the browser - 100px. Is there a way that I can make this happen so that the DIV height is set correctly in the first place and then adjusted if the user goes in and resizes the browser. I imagine this would involve javascript.

Thanks,

答:
CSS only solution:

```<code>.foo {
    position: absolute;
    left: 50px;
    top: 50px;
    right: 50px;
    bottom: 50px;
    background-color: lime;
}
</code>```

Demo here

Body:
CSS only solution:

.foo {
    position: absolute;
    left: 50px;
    top: 50px;
    right: 50px;
    bottom: 50px;
    background-color: lime;
}

Demo here


问:
how to type define a zip function in typescript
Say I want to create a zip function:

function zip(arrays){
    // assume more than 1 array is given and all arrays
    // share the same length
    const len = arrays[0].length;
    const toReturn = new Array(len);
    for (let i = 0; i < len; i++){
        toReturn[i] = arrays.map(array=>array[i]);
    }
    return toReturn;
}

console.log(zip([
    [1,2,3],
    [4,5,6],
    [7,8,9],
    [10,11,12],
]));
/*
Output:
(3) [Array(4), Array(4), Array(4)]
0: (4) [1, 4, 7, 10]
1: (4) [2, 5, 8, 11]
2: (4) [3, 6, 9, 12]
*/
```

<p>In order to type define this function when all arrays hold the same type of elements:</p>

<pre class="lang-js prettyprint-override"><code>    function zip<T>(arrays: T[][]): T[][]{/* codes omited here */}
</code>```

However, when arrays are of different types of elements, I get confused about how to use generic type to finish the type definition.

    const zipedResult = zip([[1,2,3],[true,false,true],['a','b','c']]);
    // error raises: Type 'false' is not assignable to type 'number'.(2322)
```

<p>what I want is </p>

<pre class="lang-js prettyprint-override"><code>    [[1,2,3],[true,false,true],['a','b','c']]
</code>```

could be automatically infered as (number|boolean|string)[][] without writing as (number|boolean|string)[][]
or EVEN
infered as [number[],boolean[],string[]] and result of zip infered as [number, boolean, string][]

How should I correctly type define zip to fullfill such features?

答:
I believe this is one of the few times when you see the complications of TS not being useful. I can only think of relaxing the type to just any and do manual type checking when necessary.

```<code>function zip(arrays: any[][]): any[][]{
    // assume more than 1 array is given and all arrays
    // share the same length
    const len = arrays[0].length;
    const toReturn = new Array(len);
    for (let i = 0; i < len; i++){
        toReturn[i] = arrays.map(array => array[i]);
    }
    return toReturn;
}

const zipedResult = zip([[1,2,3],[true,false,true],['a','b','c']]);
console.log(zipedResult); // [[1, true, "a"], [2, false, "b"], [3, true, "c" ]]
</code>```

Body:
Say I want to create a zip function:

function zip(arrays){
    // assume more than 1 array is given and all arrays
    // share the same length
    const len = arrays[0].length;
    const toReturn = new Array(len);
    for (let i = 0; i < len; i++){
        toReturn[i] = arrays.map(array=>array[i]);
    }
    return toReturn;
}

console.log(zip([
    [1,2,3],
    [4,5,6],
    [7,8,9],
    [10,11,12],
]));
/*
Output:
(3) [Array(4), Array(4), Array(4)]
0: (4) [1, 4, 7, 10]
1: (4) [2, 5, 8, 11]
2: (4) [3, 6, 9, 12]
*/

In order to type define this function when all arrays hold the same type of elements:

    function zip<T>(arrays: T[][]): T[][]{/* codes omited here */}

However, when arrays are of different types of elements, I get confused about how to use generic type to finish the type definition.

    const zipedResult = zip([[1,2,3],[true,false,true],['a','b','c']]);
    // error raises: Type 'false' is not assignable to type 'number'.(2322)

what I want is

    [[1,2,3],[true,false,true],['a','b','c']]

could be automatically infered as (number|boolean|string)[][] without writing as (number|boolean|string)[][]
or EVEN
infered as [number[],boolean[],string[]] and result of zip infered as [number, boolean, string][]

How should I correctly type define zip to fullfill such features?

Body:
I believe this is one of the few times when you see the complications of TS not being useful. I can only think of relaxing the type to just any and do manual type checking when necessary.

function zip(arrays: any[][]): any[][]{
    // assume more than 1 array is given and all arrays
    // share the same length
    const len = arrays[0].length;
    const toReturn = new Array(len);
    for (let i = 0; i < len; i++){
        toReturn[i] = arrays.map(array => array[i]);
    }
    return toReturn;
}

const zipedResult = zip([[1,2,3],[true,false,true],['a','b','c']]);
console.log(zipedResult); // [[1, true, "a"], [2, false, "b"], [3, true, "c" ]]


问:
Weird git error: failed to run prune
I've had a corrupt git repo, which I apparently managed to restore (by rsyncing .git/objects from the remote), since I got down to this:

```<code>$ git fsck --full
Checking object directories: 100% (256/256), done.
Checking objects: 100% (7628/7628), done.
dangling blob ac27b1087864e0b313fed793521090cfc03c82cb
dangling blob 22aae8babcc61b3048557531c1550cb4fe33de93
dangling blob 62bd6159a9e19187a778c0ae5e7ef4f0b227197b
</code>```

The dangling blobs at this point are seemingly these:

```<code>$ tree -p .git/objects/
.git/objects/
├── [drwxrwsr-x]  22
│   └── [-r--r--r--]  aae8babcc61b3048557531c1550cb4fe33de93
├── [drwxrwsr-x]  62
│   └── [-r--r--r--]  bd6159a9e19187a778c0ae5e7ef4f0b227197b
├── [drwxrwsr-x]  ac
│   └── [-r--r--r--]  27b1087864e0b313fed793521090cfc03c82cb
├── [drwxrwsrwt]  info
│   └── [-rw-rw-r--]  packs
└── [drwxrwsrwt]  pack
    ├── [-r--r--r--]  pack-65f501f2463a843b574db1ac1bde89b44e9acf38.idx
    └── [-r--r--r--]  pack-65f501f2463a843b574db1ac1bde89b44e9acf38.pack

5 directories, 6 files
</code>```

However, when I try git gc --prune=today, I get this:

```<code>$ git gc --prune=today
Counting objects: 7628, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (1993/1993), done.
Writing objects: 100% (7628/7628), done.
Total 7628 (delta 5234), reused 7628 (delta 5234)
usage: git prune [-n] [-v] [--expire <time>] [--] [<head>...]

    -n, --dry-run         do not remove, show only
    -v, --verbose         report pruned objects
    --progress            show progress
    --expire <expiry date>
                          expire objects older than <time>

error: failed to run prune
</code>```

It's as if git gc ... called git prune with a syntax error ?! EDIT: note that git gc without further arguments succeeds without a problem...

Is there a quick way to get git gc --prune=today to succeed in this repo? The local git version is:

```<code>$ git --version
git version 1.9.1
</code>```

EDIT: I removed the dangling blob files:

```<code>$ rm -rf .git/objects/{22,62,ac}
</code>```

... and I got to this:

```<code>$ git gc
Counting objects: 7628, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (1993/1993), done.
Writing objects: 100% (7628/7628), done.
Total 7628 (delta 5234), reused 7628 (delta 5234)

$ git fsck --full
Checking object directories: 100% (256/256), done.
Checking objects: 100% (7628/7628), done.
</code>```

... but git gc --prune=today still fails in the same way. Is it because it finds no object files to "prune"?

答:
Fix : run git gc --prune=now

git prune understands --expire now but not --expire today.

Which is a bit odd since git prune understands yesterday, and 0 day ago (which acts as now).

This question is old, one improvement has been brought to the error message.

As of version 2.18 (released in june 2018) :

Git 2.18 Release Notes

[...]

"git gc --prune=nonsense" spent long time repacking and then
  silently failed when underlying "git prune --expire=nonsense"
  failed to parse its command line.  This has been corrected.

Error message now looks like :

```<code>$ git gc --prune=today
fatal: failed to parse prune expiry value today
</code>```

Title: Weird git error: failed to run prune

Body:
I've had a corrupt git repo, which I apparently managed to restore (by rsyncing .git/objects from the remote), since I got down to this:

$ git fsck --full
Checking object directories: 100% (256/256), done.
Checking objects: 100% (7628/7628), done.
dangling blob ac27b1087864e0b313fed793521090cfc03c82cb
dangling blob 22aae8babcc61b3048557531c1550cb4fe33de93
dangling blob 62bd6159a9e19187a778c0ae5e7ef4f0b227197b

The dangling blobs at this point are seemingly these:

$ tree -p .git/objects/
.git/objects/
├── [drwxrwsr-x]  22
│   └── [-r--r--r--]  aae8babcc61b3048557531c1550cb4fe33de93
├── [drwxrwsr-x]  62
│   └── [-r--r--r--]  bd6159a9e19187a778c0ae5e7ef4f0b227197b
├── [drwxrwsr-x]  ac
│   └── [-r--r--r--]  27b1087864e0b313fed793521090cfc03c82cb
├── [drwxrwsrwt]  info
│   └── [-rw-rw-r--]  packs
└── [drwxrwsrwt]  pack
    ├── [-r--r--r--]  pack-65f501f2463a843b574db1ac1bde89b44e9acf38.idx
    └── [-r--r--r--]  pack-65f501f2463a843b574db1ac1bde89b44e9acf38.pack

5 directories, 6 files

However, when I try git gc --prune=today, I get this:

$ git gc --prune=today
Counting objects: 7628, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (1993/1993), done.
Writing objects: 100% (7628/7628), done.
Total 7628 (delta 5234), reused 7628 (delta 5234)
usage: git prune [-n] [-v] [--expire <time>] [--] [...]

    -n, --dry-run         do not remove, show only
    -v, --verbose         report pruned objects
    --progress            show progress
    --expire <expiry date>
                          expire objects older than <time>

error: failed to run prune

It's as if git gc ... called git prune with a syntax error ?! EDIT: note that git gc without further arguments succeeds without a problem...

Is there a quick way to get git gc --prune=today to succeed in this repo? The local git version is:

$ git --version
git version 1.9.1

EDIT: I removed the dangling blob files:

$ rm -rf .git/objects/{22,62,ac}

... and I got to this:

$ git gc
Counting objects: 7628, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (1993/1993), done.
Writing objects: 100% (7628/7628), done.
Total 7628 (delta 5234), reused 7628 (delta 5234)

$ git fsck --full
Checking object directories: 100% (256/256), done.
Checking objects: 100% (7628/7628), done.

... but git gc --prune=today still fails in the same way. Is it because it finds no object files to "prune"?

Body:
Fix : run git gc --prune=now

git prune understands --expire now but not --expire today.

Which is a bit odd since git prune understands yesterday, and 0 day ago (which acts as now).

This question is old, one improvement has been brought to the error message.

As of version 2.18 (released in june 2018) :

Git 2.18 Release Notes

[...]

"git gc --prune=nonsense" spent long time repacking and then
  silently failed when underlying "git prune --expire=nonsense"
  failed to parse its command line.  This has been corrected.

Error message now looks like :

$ git gc --prune=today
fatal: failed to parse prune expiry value today


问:
How do I set the background color of my dashboard that include pivot tables also?
I selected the whole worksheet and set the fill color value as yellow, removed the grid lines and expected the extended rows to have the yellow color, but it becomes white when the rows are collapsed.
check the pictures

答:
But.... unfortunately, this will not work if your pivot area changes sizes depending on the data, it will also fill the areas INSIDE of the pivot table that do not contain data...

You will have to do right click the pivot table
Pivot Table > PivotTable Tools > Options > Options > Layout & Format > Format > For empty cells show: -

Upon further investigation, I have to correct myself... Even that does not do it..

It looks as if Excel is deleting the cells including the formating when it collapses. I set the pivot table condition so it had no data (only headers) Then set conditional formating for the rows below. -> looks good.

Expand pivot table with data and then collapse it again.

-> rules for the same cells are gone...

There probably is a VBA way to get the area of the pivot table and then paint around it, then you need the resize event... the usual rabbit hole.


问:
Using User Form to update specific cells
I created a user form with two combo boxes ("cmb1" and "cmb2"), each referring to a range of values. I need to:

1) Permanently show this user form on a specific worksheet (let's call with "ws")

2) Update values of ws.Cells(B,4) to match the value chosen by user on cmb1 and similarly, ws.Cells(A,2) to the value chosen by user on cmb2.

I have created a CommandButton ("Enter")on the user form as well. The updates need to happen once that button is clicked.

My code is giving me a run-time error on me.cmb1

```<code>Private Sub Enter_Click()

Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("ws")

ws.Cells(B, 4) = Me.cmb1
ws.Cells(A, 2) = Me.cmb2
End Sub
</code>```

Please help. Thanks!

答:
You're using .Cells which requires a number for both the row and column reference. The run-time error is being triggered because you are using a letter for your column reference.

You have two options to save the values from the comboboxes (probably more, but two simple ways).

Option 1 - .Cells (note that it is row first, then column)

```<code>ws.Cells(4,2) = Me.cmb1.Value
ws.Cells(2,1) = Me.cmb.value
</code>```

Option 2 - .Range

```<code>ws.Range("B4") = Me.cmb1.Value
ws.Cells("A2") = Me.cmb.value
</code>```

See http://excelmatters.com/referring-to-ranges-in-vba/ for more info

Body:
I created a user form with two combo boxes ("cmb1" and "cmb2"), each referring to a range of values. I need to:

1) Permanently show this user form on a specific worksheet (let's call with "ws")

2) Update values of ws.Cells(B,4) to match the value chosen by user on cmb1 and similarly, ws.Cells(A,2) to the value chosen by user on cmb2.

I have created a CommandButton ("Enter")on the user form as well. The updates need to happen once that button is clicked.

My code is giving me a run-time error on me.cmb1

Private Sub Enter_Click()

Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("ws")

ws.Cells(B, 4) = Me.cmb1
ws.Cells(A, 2) = Me.cmb2
End Sub

Please help. Thanks!

Body:
You're using .Cells which requires a number for both the row and column reference. The run-time error is being triggered because you are using a letter for your column reference.

You have two options to save the values from the comboboxes (probably more, but two simple ways).

Option 1 - .Cells (note that it is row first, then column)

ws.Cells(4,2) = Me.cmb1.Value
ws.Cells(2,1) = Me.cmb.value

Option 2 - .Range

ws.Range("B4") = Me.cmb1.Value
ws.Cells("A2") = Me.cmb.value

See http://excelmatters.com/referring-to-ranges-in-vba/ for more info


问:
Problem with credential chaining sequence in Windows and .NET

Problem Summary

When run in batch mode, my user identity is lost but (like a really good cliffhanger) not until the very last moment.

Problem Details

I have a PowerShell script running on WinXpSp3 that runs a script block (via Invoke-Command) on a remote machine as a particular test user (via -Session parameter) in the background (via -AsJob parameter). The session is created with this:

```<code>New-PSSession -computername $myServer -credential $myCredential
</code>```

The script block performs a number of actions, culminating in running the NUnit test framework. The C# code under test records the "myTestUser" username (via Environment.UserName) so the credentials provided by PowerShell are properly received that far. This is further confirmed by Process Explorer: examining properties of nunit-console running the batch tests shows it is owned by myTestUser.

The test includes accessing a Sql Server 2008 R2 database; the connection string is set via a new SqlConnection(connectionString) call. The connection string is set up for Windows Authentication and uses this form:

```<code>Data Source=<my_db_server_name>;Initial Catalog=<my_db_name>;Integrated Security=True;Persist Security Info=True
</code>```

Even though I have conclusively pushed the myTestUser credentials all the way to the C# code under test, the DB access attempt is not seeing these credentials, resulting in this error: Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'

Some supplemental info:

I have confirmed that the test user (myTestUser) has DB permissions and the NUnit test is capable of accessing the DB: When I run the NUnit test manually (via NUnit GUI) logged in as myTestUser, the test works properly and SqlProfiler clearly shows this activity with myTestUser appearing in the NTUserName column.

The same error occurs if I run locally rather than on a remote machine.

The same error occurs if I run as myself on my local machine (i.e. omitting the -credential parameter).

Question

How can I rescue myTestUser from the brink of doom and get him DB access?

2011.05.16 Update

Here is a simplified example exhibiting the same problem.

First, my test program DBFetchVersion that prints the name of the current user and the results of a simple query:

```<code>class Program
{
    const string connString = ...your connection string here... ;
    const string query = "SELECT getdate() [Date], substring(@@version,1,charindex('-',@@version)-1) +convert(varchar(100),SERVERPROPERTY('edition'))+ ' ' +convert(varchar(100),SERVERPROPERTY('productlevel')) [SQL Server Version], @@servicename [Service Name], @@servername [Server Host], db_name() [Database], user_name() [User], host_name() [Client]";

    static void Main(string[] args)
    {
        DataView dataView;
        using (var connection = new SqlConnection(connString))
        {
            Console.WriteLine("user = " + Environment.UserName);
            using (var dataAdapter = new SqlDataAdapter(query, connection))
            {
                var dataSet = new DataSet();
                try
                {
                    connection.Open();
                    dataAdapter.SelectCommand.CommandType = CommandType.Text;
                    dataAdapter.Fill(dataSet, query);
                }
                finally { if (connection.State == ConnectionState.Open) connection.Close(); }
                dataView = dataSet.Tables[0].DefaultView;
            }
            foreach (var item in dataView.Table.Rows[0].ItemArray)
                Console.WriteLine(item);
        }
    }
}
</code>```

And here is the Powershell script that calls the above program.

```<code>$scriptBlock = {
    & "...path to my executable...\DBFetchVersion\bin\Debug\DBFetchVersion.exe"
}

$serverName = ... my server name ...
$username = "testuser"
$password = ... my user password ...
$adjPwd = $password | ConvertTo-SecureString -asPlainText -Force
$testCred = (New-Object System.Management.Automation.PSCredential($username,$adjPwd))
$mySession = New-PSSession -computername $serverName  -credential $testCred

# Test Scenarios:
Invoke-Command $scriptBlock
#Invoke-Command $scriptBlock -computername $serverName
#Invoke-Command $scriptBlock -computername $serverName  -credential $testCred
#Invoke-Command $scriptBlock -Session $mySession
</code>```

In the list of four test scenarios at the end, the uncommented one works, printing my user name and the results of the query.
DBFetchVersion still reports I am the user with the second line, but the DB connection fails with the " Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON' " error.
The remaining two lines report the "testuser" user name, but both report the same login failure for the DB connection.

What this isolated example tells me is not that I think there is anything buggy about Powershell, .NET, or my code, but there is something with the authentication mechanism that I do not yet understand, since specifying another computer or a session both involve a path that should, in some sense, have stronger protection.

2011.08.03 Update - Eureka!

Well, Matt was correct in identifying the double-hop issue as the culprit and CredSSP authentication as the solution. Unfortunately, as I quickly found out, CredSSP requires Windows 7, so I went about setting up a couple VMs as a sandbox. CredSSP, however, was not one to easily relinquish its secrets (at least to me) as I detailed in this post on ServerFault: Cannot get CredSSP authentication to work in PowerShell

I finally was able to get CredSSP authentication to work so I could then come back to the problem I posed here in this thread. As a test, I used these 3 script blocks plugged into the PowerShell script I provided above:

```<code>$scriptBlockA = {
    Write-Host ("hello, world: {0}, {1}" -f $env:USERNAME, (hostname))
}

# Simple DB test, but requires SqlServer installed!
$scriptBlockB = {
    if (! (Get-PSSnapin | ? { $_.name -eq "SqlServerCmdletSnapin100" } ) )
    { Add-PSSnapin SqlServerCmdletSnapin100; }
    Invoke-Sqlcmd -Query "SELECT getdate() as [Now]" -ServerInstance CinDevDB5
}

# Indirect DB test; requires .NET but not SqlServer,
# plus DBFetchVersion in home dir for targeted user.
$scriptBlockC = {
    & ".\DBFetchVersion.exe"
}
</code>```

Block A worked with or without CredSSP, since there is no double-hop. Blocks B and C would only work with CredSSP because they both attempt to access a remote database. QED.

答:
Initially i read this and thought of the "double hop" issue, but the supplemental info maybe me question that though.

When you run it locally (as yourself or the testuser) what commands do you use? this:

```<code>& "...path to my executable...\DBFetchVersion\bin\Debug\DBFetchVersion.exe"
</code>```

also does this work from your local machine (as either yourself or the user):

```<code>Add-PSSnapin SqlServerCmdletSnapin100;
Invoke-Sqlcmd -Query "SELECT getdate()" -ServerInstance Server
</code>```

Also what OS are you using? If it is Windows 2008 and the issue is double hop you may be able to us CredSSP to avoid it.

Body:
Problem Summary

When run in batch mode, my user identity is lost but (like a really good cliffhanger) not until the very last moment.

Problem Details

I have a PowerShell script running on WinXpSp3 that runs a script block (via Invoke-Command) on a remote machine as a particular test user (via -Session parameter) in the background (via -AsJob parameter). The session is created with this:

New-PSSession -computername $myServer -credential $myCredential

The script block performs a number of actions, culminating in running the NUnit test framework. The C# code under test records the "myTestUser" username (via Environment.UserName) so the credentials provided by PowerShell are properly received that far. This is further confirmed by Process Explorer: examining properties of nunit-console running the batch tests shows it is owned by myTestUser.

The test includes accessing a Sql Server 2008 R2 database; the connection string is set via a new SqlConnection(connectionString) call. The connection string is set up for Windows Authentication and uses this form:

Data Source=<my_db_server_name>;Initial Catalog=<my_db_name>;Integrated Security=True;Persist Security Info=True

Even though I have conclusively pushed the myTestUser credentials all the way to the C# code under test, the DB access attempt is not seeing these credentials, resulting in this error: Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'

Some supplemental info:

I have confirmed that the test user (myTestUser) has DB permissions and the NUnit test is capable of accessing the DB: When I run the NUnit test manually (via NUnit GUI) logged in as myTestUser, the test works properly and SqlProfiler clearly shows this activity with myTestUser appearing in the NTUserName column.

The same error occurs if I run locally rather than on a remote machine.

The same error occurs if I run as myself on my local machine (i.e. omitting the -credential parameter).

Question

How can I rescue myTestUser from the brink of doom and get him DB access?

2011.05.16 Update

Here is a simplified example exhibiting the same problem.

First, my test program DBFetchVersion that prints the name of the current user and the results of a simple query:

class Program
{
    const string connString = ...your connection string here... ;
    const string query = "SELECT getdate() [Date], substring(@@version,1,charindex('-',@@version)-1) +convert(varchar(100),SERVERPROPERTY('edition'))+ ' ' +convert(varchar(100),SERVERPROPERTY('productlevel')) [SQL Server Version], @@servicename [Service Name], @@servername [Server Host], db_name() [Database], user_name() [User], host_name() [Client]";

    static void Main(string[] args)
    {
        DataView dataView;
        using (var connection = new SqlConnection(connString))
        {
            Console.WriteLine("user = " + Environment.UserName);
            using (var dataAdapter = new SqlDataAdapter(query, connection))
            {
                var dataSet = new DataSet();
                try
                {
                    connection.Open();
                    dataAdapter.SelectCommand.CommandType = CommandType.Text;
                    dataAdapter.Fill(dataSet, query);
                }
                finally { if (connection.State == ConnectionState.Open) connection.Close(); }
                dataView = dataSet.Tables[0].DefaultView;
            }
            foreach (var item in dataView.Table.Rows[0].ItemArray)
                Console.WriteLine(item);
        }
    }
}

And here is the Powershell script that calls the above program.

$scriptBlock = {
    & "...path to my executable...\DBFetchVersion\bin\Debug\DBFetchVersion.exe"
}

$serverName = ... my server name ...
$username = "testuser"
$password = ... my user password ...
$adjPwd = $password | ConvertTo-SecureString -asPlainText -Force
$testCred = (New-Object System.Management.Automation.PSCredential($username,$adjPwd))
$mySession = New-PSSession -computername $serverName  -credential $testCred

# Test Scenarios:
Invoke-Command $scriptBlock
#Invoke-Command $scriptBlock -computername $serverName
#Invoke-Command $scriptBlock -computername $serverName  -credential $testCred
#Invoke-Command $scriptBlock -Session $mySession

In the list of four test scenarios at the end, the uncommented one works, printing my user name and the results of the query.
DBFetchVersion still reports I am the user with the second line, but the DB connection fails with the " Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON' " error.
The remaining two lines report the "testuser" user name, but both report the same login failure for the DB connection.

What this isolated example tells me is not that I think there is anything buggy about Powershell, .NET, or my code, but there is something with the authentication mechanism that I do not yet understand, since specifying another computer or a session both involve a path that should, in some sense, have stronger protection.

2011.08.03 Update - Eureka!

Well, Matt was correct in identifying the double-hop issue as the culprit and CredSSP authentication as the solution. Unfortunately, as I quickly found out, CredSSP requires Windows 7, so I went about setting up a couple VMs as a sandbox. CredSSP, however, was not one to easily relinquish its secrets (at least to me) as I detailed in this post on ServerFault: Cannot get CredSSP authentication to work in PowerShell

I finally was able to get CredSSP authentication to work so I could then come back to the problem I posed here in this thread. As a test, I used these 3 script blocks plugged into the PowerShell script I provided above:

$scriptBlockA = {
    Write-Host ("hello, world: {0}, {1}" -f $env:USERNAME, (hostname))
}

# Simple DB test, but requires SqlServer installed!
$scriptBlockB = {
    if (! (Get-PSSnapin | ? { $_.name -eq "SqlServerCmdletSnapin100" } ) )
    { Add-PSSnapin SqlServerCmdletSnapin100; }
    Invoke-Sqlcmd -Query "SELECT getdate() as [Now]" -ServerInstance CinDevDB5
}

# Indirect DB test; requires .NET but not SqlServer,
# plus DBFetchVersion in home dir for targeted user.
$scriptBlockC = {
    & ".\DBFetchVersion.exe"
}

Block A worked with or without CredSSP, since there is no double-hop. Blocks B and C would only work with CredSSP because they both attempt to access a remote database. QED.

Body:
Initially i read this and thought of the "double hop" issue, but the supplemental info maybe me question that though.

When you run it locally (as yourself or the testuser) what commands do you use? this:

& "...path to my executable...\DBFetchVersion\bin\Debug\DBFetchVersion.exe"

also does this work from your local machine (as either yourself or the user):

Add-PSSnapin SqlServerCmdletSnapin100;
Invoke-Sqlcmd -Query "SELECT getdate()" -ServerInstance Server

Also what OS are you using? If it is Windows 2008 and the issue is double hop you may be able to us CredSSP to avoid it.


问:
No internet connection for Visual Studio Android Emulator
I'm using Android Emulator that comes with Visual Studio 2015. When I run it, in Wi-Fi settings of Android this status appears Obtaining IP Address.. for Wired eth1 network. But it fails after a long time.

What I've tried:

Removed all the virtual switches in Virtual Switch Manager of Hyper-V before running the emulator.

Unchecked automatic detect settings in proxy settings

Tried different API levels (19,22,..)

Windows Phone Emulator doesn't have this problem and has internet connection.

Restarted my PC!

What I guess:

When I diagnose vEthernet (Internal Ethernet Port Windows Phone Emulator Internal Switch) it says it has an invalid IP address. Also inside android emulator it tries to obtain an IP. Obviously I need to give the emulator a valid IP, but I don't know how or where or what value.

How to give the Android emulator internet access?
Thanks in advance.

答: Thought this might help someone out there. Mine had an internet connection, but suddenly it stopped connecting. I resolved it by restarting my emulator with factory settings.


问:
Button click issue
I am trying to refer the button to another page using :to. It doesn't do anything at the moment. For testing purposes I'm now trying to refer to the existing /learn page.

My code:

```<code>  <b-navbar-item tag="div">
                <div class="buttons">
                    <a class="button is-primary"
                v-for="item in menuItems"
                :key="item.title"
                :to="item.link">
                        {{item.title}}
                        </a>
                </div>
            </b-navbar-item>
</code>```

```<code>export default {
    data() {
      return {
           menuItems: [
       { title: 'Login', link: '/learn'},
       { title: 'Sign up', link: '/learn'},
       { title: 'Logout', link: '/learn'},

      ]
      }
</code>```

答:
For this to work you need to use VueRouter and instead of the  tag you need to use the <router-link> component.
If you really need to use a  tag you can also use the scoped-slot  of <router-link>

```<code><router-link
  to="/foo"
  v-slot="{ href, route, navigate, isActive, isExactActive }"
>
  <li
    :class="[isActive && 'router-link-active', isExactActive && 'router-link-exact-active']"
  >
    <a :href="href" @click="navigate">{{ route.fullPath }}</a>
  </li>
</router-link>
</code>```

Title: Button click issue

Body:
I am trying to refer the button to another page using :to. It doesn't do anything at the moment. For testing purposes I'm now trying to refer to the existing /learn page.

My code:

                        {{item.title}}

export default {
    data() {
      return {
           menuItems: [
       { title: 'Login', link: '/learn'},
       { title: 'Sign up', link: '/learn'},
       { title: 'Logout', link: '/learn'},

      ]
      }

Body:
For this to work you need to use VueRouter and instead of the <a> tag you need to use the <router-link> component.
If you really need to use a <a> tag you can also use the scoped-slot  of <router-link>

<router-link
  to="/foo"
  v-slot="{ href, route, navigate, isActive, isExactActive }"
>
  <li
    :class="[isActive && 'router-link-active', isExactActive && 'router-link-exact-active']"
  >
    <a :href="href" @click="navigate">{{ route.fullPath }}</a>
  </li>
</router-link>


问:
Extract data from another workbook using VLOOKUP
I am busy creating my own function in VBA to extract data from another workbook in the same directory. However, when I call it as a function from within the destination workbook (Workbook A), it gives me a VALUE!# error. When I call the function from within a sub procedure where I test my code, it successfully extracts the correct data.

Within Excel I call my function like this =CALCULATE_METERS("D1"), and to test it using the sub procedure I call it like this from within the same module:

```<code>Sub test()
  CALCULATE_METERS ("D1")
  CALCULATE_METERS ("D1,2")
  CALCULATE_METERS ("D1-3")
  CALCULATE_METERS ("D1-5,8,9")
  CALCULATE_METERS ("D1(2),4(2),23(1),24-28")
  CALCULATE_METERS ("D1,4(2),23-25,26-28(2);E1-4;A1-2")
End Sub
</code>```

The function containing the VLOOKUP code is (this is called within the CALCULATE_METERS function):

```<code>Private Function GetSquareMeters(block As String, r As Integer) As Integer
  Dim result As String
  Dim meters As String
  Dim wrkb As Workbook
  Dim wrks As Worksheet
  Dim rng As Range
  Dim directory As String
  Dim filename As String
  filename = "DATA REFERENCE.xlsx"
  directory = ActiveWorkbook.Path
  filename = directory & "\" & filename
  Debug.Print (filename)

  Set wrkb = Workbooks.Open(filename)

  meters = Application.WorksheetFunction.VLookup(block, wrkb.Worksheets("Lande").Range("$A$2:$F$120"), 5)

  GetSquareMeters = CInt(meters) * r / 7
End Function
</code>```

Everything prints in the immediate window up until the filename in the above function, but I believe the value error is generated on the lookup function. Why is it that calling the same function with the same arguments (one within excel, the other one within a sub procedure) gives different answers? How can I correct this so that I can use the function within an Excel cell?

Thanks!

答:
Try to use Find isntead of VLookup:</p>

```<code>Function GetSquareMeters(block As String, r As Integer) As Integer
  Dim result As String
  Dim meters As String
  Dim wrkb As Workbook
  Dim wrks As Worksheet
  Dim rng As Range
  Dim directory As String
  Dim filename As String
  filename = "DATA REFERENCE.xlsx"
  directory = ActiveWorkbook.Path
  filename = directory & "\" & filename
  Debug.Print (filename)

 For Each wb In Workbooks
    If wb.FullName = Filename Then
    Set wrkb = Workbooks(Filename)
    Else
    Set wrkb = Workbooks.Open(Filename)
    End If
 Next

    meters = wrkb.Sheets("Lande").Range("$A$2:$F$120").Find(block).Offset(0, 4).Value

  GetSquareMeters = CInt(meters) * r / 7
End Function
</code>```

Body:
I am busy creating my own function in VBA to extract data from another workbook in the same directory. However, when I call it as a function from within the destination workbook (Workbook A), it gives me a VALUE!# error. When I call the function from within a sub procedure where I test my code, it successfully extracts the correct data.

Within Excel I call my function like this =CALCULATE_METERS("D1"), and to test it using the sub procedure I call it like this from within the same module:

Sub test()
  CALCULATE_METERS ("D1")
  CALCULATE_METERS ("D1,2")
  CALCULATE_METERS ("D1-3")
  CALCULATE_METERS ("D1-5,8,9")
  CALCULATE_METERS ("D1(2),4(2),23(1),24-28")
  CALCULATE_METERS ("D1,4(2),23-25,26-28(2);E1-4;A1-2")
End Sub

The function containing the VLOOKUP code is (this is called within the CALCULATE_METERS function):

Private Function GetSquareMeters(block As String, r As Integer) As Integer
  Dim result As String
  Dim meters As String
  Dim wrkb As Workbook
  Dim wrks As Worksheet
  Dim rng As Range
  Dim directory As String
  Dim filename As String
  filename = "DATA REFERENCE.xlsx"
  directory = ActiveWorkbook.Path
  filename = directory & "\" & filename
  Debug.Print (filename)

  Set wrkb = Workbooks.Open(filename)

  meters = Application.WorksheetFunction.VLookup(block, wrkb.Worksheets("Lande").Range("$A$2:$F$120"), 5)

  GetSquareMeters = CInt(meters) * r / 7
End Function

Everything prints in the immediate window up until the filename in the above function, but I believe the value error is generated on the lookup function. Why is it that calling the same function with the same arguments (one within excel, the other one within a sub procedure) gives different answers? How can I correct this so that I can use the function within an Excel cell?

Thanks!

Body:
Try to use Find isntead of VLookup:

Function GetSquareMeters(block As String, r As Integer) As Integer
  Dim result As String
  Dim meters As String
  Dim wrkb As Workbook
  Dim wrks As Worksheet
  Dim rng As Range
  Dim directory As String
  Dim filename As String
  filename = "DATA REFERENCE.xlsx"
  directory = ActiveWorkbook.Path
  filename = directory & "\" & filename
  Debug.Print (filename)

 For Each wb In Workbooks
    If wb.FullName = Filename Then
    Set wrkb = Workbooks(Filename)
    Else
    Set wrkb = Workbooks.Open(Filename)
    End If
 Next

    meters = wrkb.Sheets("Lande").Range("$A$2:$F$120").Find(block).Offset(0, 4).Value

  GetSquareMeters = CInt(meters) * r / 7
End Function


答:
First, do not use a general catch clause. This would be considered bad practice.

In your case, it would make sense to catch ValueErrors in case a user enters letters instead of numbers in example:

```<code>while True:
    inp = input('Enter Fahrenheit Temperature:')
    try:
        fahr = float(inp)
        break # Break loop to get to main program
    except ValueError:
        print('Please enter a number')

fahr = float(inp) # Even if I comment it, it doesn't make any difference when it comes to entering float in an input but it raises red flag if I enter string.
cel = (fahr - 32.0) * 5.0 / 9.0
print(cel)
</code>```

One alternative would be a recursive input if you really want to avoid the loop:

```<code>def force_input(prompt):
    inp = input(prompt)
    try:
        fahr = float(inp)
        return fahr
    except ValueError:
        print('Please enter a number')
        force_input(prompt)
        return False

fahr = force_input("Enter Fahrenheit Temperature:")
cel = (fahr - 32.0) * 5.0 / 9.0
print(cel)
</code>```

Title: try/except issue statement in python 3

Body:
First, do not use a general catch clause. This would be considered bad practice.

In your case, it would make sense to catch ValueErrors in case a user enters letters instead of numbers in example:

while True:
    inp = input('Enter Fahrenheit Temperature:')
    try:
        fahr = float(inp)
        break # Break loop to get to main program
    except ValueError:
        print('Please enter a number')

fahr = float(inp) # Even if I comment it, it doesn't make any difference when it comes to entering float in an input but it raises red flag if I enter string.
cel = (fahr - 32.0) * 5.0 / 9.0
print(cel)

One alternative would be a recursive input if you really want to avoid the loop:

def force_input(prompt):
    inp = input(prompt)
    try:
        fahr = float(inp)
        return fahr
    except ValueError:
        print('Please enter a number')
        force_input(prompt)
        return False

fahr = force_input("Enter Fahrenheit Temperature:")
cel = (fahr - 32.0) * 5.0 / 9.0
print(cel)


问:
PostgreSQL allocated column length
I have an issue where I have one column in a database that might be anything from 10 to 10,000 bytes in size. Do you know if PostgreSQL supports sparse data (i.e. will it always set aside the 10,000 bytes fore every entry in the column ... or only the space that is required for each entry)?</p>

答: use varchar or text types - these use only the space actually required to store the data (plus a small overhead of 2 bytes for each value to store the length)

Title: PostgreSQL allocated column length


问:
Compare two object arrays and get the difference in Javascript
I have two arrays of objects:

```<code>\\offers
[
{DeskUID: "B11A13", Day: 06 Jun 2020}
{DeskUID: "B11A13", Day: 07 Jun 2020}
{DeskUID: "B12B34", Day: 23 Jun 2020}
]

\\reservations
[
{DeskUID: "B11A13", Day: 06 Jun 2020, Name: "Mike"}
{DeskUID: "B12B34", Day: 23 Jun 2020, Name: "Ali"}
]
</code>```

I would like to have a result where are available offers, that means only the offers without already reserved desks.

```<code>\\result
[
{DeskUID: "B11A13", Day: 07 Jun 2020}
]
</code>```

How to get the difference between two arrays of objects in JavaScript

I already tried solutions on the link above but without success, I just got a result array as sum of all objects from the two arrays.

```<code>            function comparer(otherArray){
                return function(current){
                var reserveDay = new Date (current.Day)
                    return otherArray.filter(function(other){
                        var offerDay = new Date (other.Day)
                        return other.DeskUID == current.DeskUID && offerDay == reserveDay
                    }).length == 0;
                }
            }

            var onlyInA = offers.filter(comparer(reservations));
            var onlyInB = reservations.filter(comparer(offers));

            result = onlyInA.concat(onlyInB);
</code>```

答:
You can do in a single function, like:

```<code>const available = offers.filter(offer => {
  return reservations.findIndex(reservation => reservation.DeskUID === offer.DeskUID && sameDay(new Date(reservation.Day), new Date(offer.Day))) === -1;
});

function sameDay(d1, d2) {
  return (
    d1.getFullYear() === d2.getFullYear() &&
    d1.getMonth() === d2.getMonth() &&
    d1.getDate() === d2.getDate()
  );
}

console.log(available);
</code>```

So, what is exactly happening...

offers.filter runs a check for each element in the offers array.

reservations.findIndex will try to find if there is already a reservation for that offer. It does by going into the reservations array and checking if there is the same unique ID and same date for the offer that is currently filtering.

If the result is equal to -1 it means that there is no reservation for that offer. Therefore it is available.

I've used the dates as string for the sake of simplicity, you can just alter to Date object. Hope it helps!

EDIT

I've added a small helper function for you to compare if the dates are from the same day. You can check this answer for a more detailed explanation: how to tell if two dates are in the same day?

Body:
I have two arrays of objects:

\\offers
[
{DeskUID: "B11A13", Day: 06 Jun 2020}
{DeskUID: "B11A13", Day: 07 Jun 2020}
{DeskUID: "B12B34", Day: 23 Jun 2020}
]

\\reservations
[
{DeskUID: "B11A13", Day: 06 Jun 2020, Name: "Mike"}
{DeskUID: "B12B34", Day: 23 Jun 2020, Name: "Ali"}
]

I would like to have a result where are available offers, that means only the offers without already reserved desks.

\\result
[
{DeskUID: "B11A13", Day: 07 Jun 2020}
]

How to get the difference between two arrays of objects in JavaScript

I already tried solutions on the link above but without success, I just got a result array as sum of all objects from the two arrays.

            function comparer(otherArray){
                return function(current){
                var reserveDay = new Date (current.Day)
                    return otherArray.filter(function(other){
                        var offerDay = new Date (other.Day)
                        return other.DeskUID == current.DeskUID && offerDay == reserveDay
                    }).length == 0;
                }
            }

            var onlyInA = offers.filter(comparer(reservations));
            var onlyInB = reservations.filter(comparer(offers));

            result = onlyInA.concat(onlyInB);

Body:
You can do in a single function, like:

const available = offers.filter(offer => {
  return reservations.findIndex(reservation => reservation.DeskUID === offer.DeskUID && sameDay(new Date(reservation.Day), new Date(offer.Day))) === -1;
});

function sameDay(d1, d2) {
  return (
    d1.getFullYear() === d2.getFullYear() &&
    d1.getMonth() === d2.getMonth() &&
    d1.getDate() === d2.getDate()
  );
}

console.log(available);

So, what is exactly happening...

offers.filter runs a check for each element in the offers array.

reservations.findIndex will try to find if there is already a reservation for that offer. It does by going into the reservations array and checking if there is the same unique ID and same date for the offer that is currently filtering.

If the result is equal to -1 it means that there is no reservation for that offer. Therefore it is available.

I've used the dates as string for the sake of simplicity, you can just alter to Date object. Hope it helps!

EDIT

I've added a small helper function for you to compare if the dates are from the same day. You can check this answer for a more detailed explanation: how to tell if two dates are in the same day?


问:
Convert a series of 2D XY-line plots into a 2D heatmap plot
I'm pretty new to python coding, so apologies if this question has been asked before.

I have a piece of code, written by another person, which I cannot show here, but it produces a series of line plots (like this ).

What I would like to do is basically collapse these plots into one heatmap plot, wherein the colour shows the density of the lines in that location.

Could anyone point me in the right direction for producing these plots?

答:
It looks like you are trying to draw a 2d histogram, would you like help with that?

```<code>N=200
t = np.linspace(0, 2*np.pi, N)
r = 5
x = r*np.cos(t)
y = r*np.sin(t)
x+=np.random.random(N)
y+=np.random.random(N)

fig, (ax1, ax2) = plt.subplots(1,2, figsize=(8,4))
ax1.plot(x,y, 'c-')
ax2.hist2d(x,y)
</code>```

Alternatively, you can use a 2D kernel density estimate plot (provided by seaborn)

```<code>fig, (ax1, ax2) = plt.subplots(1,2, figsize=(8,4))
ax1.plot(x,y, 'c-')
sns.kdeplot(x, y, ax=ax2, shade=True, cmap='viridis')
</code>```

Body:
It looks like you are trying to draw a 2d histogram, would you like help with that?

N=200
t = np.linspace(0, 2*np.pi, N)
r = 5
x = r*np.cos(t)
y = r*np.sin(t)
x+=np.random.random(N)
y+=np.random.random(N)

fig, (ax1, ax2) = plt.subplots(1,2, figsize=(8,4))
ax1.plot(x,y, 'c-')
ax2.hist2d(x,y)

Alternatively, you can use a 2D kernel density estimate plot (provided by seaborn)

fig, (ax1, ax2) = plt.subplots(1,2, figsize=(8,4))
ax1.plot(x,y, 'c-')
sns.kdeplot(x, y, ax=ax2, shade=True, cmap='viridis')


问:
Method that expands into
...
 expression
Let's suppose I have the following in a 'cshtml' file:

```<code><li class="nav-item">
    <a class="nav-link text-white" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
</li>

<li class="nav-item">
    <a class="nav-link text-white" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</li>
</code>```

I'd like to setup a method Link so that I can do the following instead of the above:

```<code>@Link("nav-link text-white", "Home", "Index", "Home")
@Link("nav-link text-white", "Home", "Privacy", "Privacy")
</code>```

Here's one approach that I tried:

```<code>@{
    void Link(string a_class, string controller, string action, string text)
    {
        <li class="nav-item">
            <a class="@a_class" asp-area="" asp-controller="@controller" asp-action="@action">@text</a>
        </li>
    }

}
</code>```

However, this leads the following error message:

What's a good way to implement the above Link method?

答:
Let me assume you want to achieve reusablility. If thats the case then you will have a better option of creating a partial view for that

this will be your partial view

```<code>@model MyPartialModel
<li class="nav-item">
    <a class="@Model.Class" asp-area="@Model.Area" asp-controller="@Model.Controller" asp-action="@Model.Action">@Model.Text</a>
</li>

//Then you can call it anywhere
@await Html.PartialAsync("NameOfFile", new { Text ="whatever" Controller="MyController" Action=MyAction" className ="the-class"})
//Or even replace the anonymous object with a model rather
</code>```

And.....that's it

Title: Method that expands into <li>...</li> expression

Body:
Let's suppose I have the following in a 'cshtml' file:

    Home

    Privacy

I'd like to setup a method Link so that I can do the following instead of the above:

@Link("nav-link text-white", "Home", "Index", "Home")
@Link("nav-link text-white", "Home", "Privacy", "Privacy")

Here's one approach that I tried:

@{
    void Link(string a_class, string controller, string action, string text)
    {

            @text

    }

}

However, this leads the following error message:

What's a good way to implement the above Link method?

Body:
Let me assume you want to achieve reusablility. If thats the case then you will have a better option of creating a partial view for that

this will be your partial view

@model MyPartialModel
<li class="nav-item">
    <a class="@Model.Class" asp-area="@Model.Area" asp-controller="@Model.Controller" asp-action="@Model.Action">@Model.Text</a>
</li>

//Then you can call it anywhere
@await Html.PartialAsync("NameOfFile", new { Text ="whatever" Controller="MyController" Action=MyAction" className ="the-class"})
//Or even replace the anonymous object with a model rather

And.....that's it


问:
add variable to json
So there are many questions on here about this and I tried quite a few without success. </p>

<p>I am trying to add a php variable to a javascript variable and then put it in json. </p>

```<code><?php $symbol_json =  $row['symbol_json']; echo $symbol_json; ?> <!--This is OK!-->
</div>
</center>
<center>
<!-- Widget BEGIN -->
<div class="widget-container">
  <div class="widget-container__widget"></div>
  <div class="widget-copyright"><a href="https://aaaaaaa.com/symbols/<?php echo $row['symbol_html']; ?>/" rel="noopener" target="_blank"><span class="blue-text"><?php echo $row['symbol']?> Symbol Info</span></a></div>

  <script>
    var myVar = '<?php echo $symbol_json ?>'; alert(myVar); //This works ok!

    var myObject = JSON.parse('<?php echo json_encode($symbol_json) ?>'); alert(myObject); //Alert works ok!
  </script>

  <script type="text/javascript" src="https://aaaaaaa.com/external-embedding/symbol-info.js" async>
  {
  //"symbol": "SDT", //This how it is at present and it works. I need to change it to a variable like below.
  "symbol": myObject, //Whether I use myObject or myVar (which both contain SDT) the widget loads a different symbol.
  "width": 1000,
  "locale": "uk",
  "colorTheme": "light",
  "isTransparent": false
}
  </script>
</div>
<!-- Widget END -->
</code>```

答:
Why don't you put your variables into the same script tag? As a general advice, please, please, please don't mix up PHP with Javascript or HTML. It's the best way to make your code smell.  You must parse yout JSON in order to use it as a variable, so

```<code> var myObject = '<?php echo json_encode($symbol_json) ?>';
</code>```

becames

```<code> var myObject = JSON.parse('<?php echo json_encode($symbol_json) ?>');
</code>```

Title: add variable to json

Body:
So there are many questions on here about this and I tried quite a few without success.

I am trying to add a php variable to a javascript variable and then put it in json.

<?php $symbol_json =  $row['symbol_json']; echo $symbol_json; ?>

<a href="https://aaaaaaa.com/symbols/<?php echo $row['symbol_html']; ?>/" rel="noopener" target="_blank"><?php echo $row['symbol']?> Symbol Info

Body:
Why don't you put your variables into the same script tag? As a general advice, please, please, please don't mix up PHP with Javascript or HTML. It's the best way to make your code smell.  You must parse yout JSON in order to use it as a variable, so

 var myObject = '<?php echo json_encode($symbol_json) ?>';

becames

 var myObject = JSON.parse('<?php echo json_encode($symbol_json) ?>');


问:
addEventListener not working in custom element
I'm making a monopoly game for my website, and I have a problem that I can't add event listeners for "i" element in a custom element

Here's my custom element:

class Popup extends HTMLElement {
  constructor() {
    super();
    var that = this;

    var shadow = this.attachShadow({mode: 'open'});
    var wrapper = document.createElement('div');
    wrapper.setAttribute("class","popup-wrapper");
    var popup = document.createElement('div');
    popup.setAttribute('class','popup');

    let exitButton = document.createElement('i');
    exitButton.className = "fas fa-times fa-lg exit";

    exitButton.addEventListener("click", function () {
      console.log('a');
    });

    // styles
    var style = document.createElement('style');
    style.textContent = `
      @import url("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css");
      @import url("https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css");

      .popup-wrapper {
        position: fixed;
        top: 0; left: 0; right: 0; bottom: 0;
        background-color: rgba(0, 0, 0, .6);
        z-index: 9999;
        visibility: visible;
      }

      .popup {
        position: fixed;
        top: 50%; left: 50%;
        transform: translate(-50%, -50%);
        border: 1px solid #d6d6d6;
        background-color: #fff;
        border-radius: .25rem;
        padding: 1rem 2rem;
      }

      /* .exit {
        position: absolute;
        top: .5rem; right: .5rem;
        cursor: pointer;
      } */
    `;

    popup.appendChild(exitButton);

    wrapper.appendChild(popup);

    shadow.appendChild(style);
    shadow.appendChild(wrapper);

    this.isOpen = false;
    this.popup_wrapper = wrapper;
    this.popup = popup;
    this.exitButton = exitButton;
  }

  close() {
    console.log('a');
    this.remove();
  }
}

class TextPopup extends Popup {
  constructor() {
    super();

  }

  show() {
    this.exitButton.addEventListener("click", function () {
      console.log('a');
    });

    this.heading = this.getAttribute("heading");
    this.text = this.getAttribute("text");

    this.popup.innerHTML += `

${this.heading}

${this.text}

    `;
  }
}

customElements.define('text-popup', TextPopup);
```

<p>I had tried to place it in multiple locations but it is still not working</p>

<p>I also have another custom element where addEventListener working:</p>

```class Copy extends HTMLElement {
  constructor() {
    super();

    if (!this.hasAttribute('text')) return console.error("Text is not specified");

    this.text = this.getAttribute('text');
    this.style.cursor = "pointer";
    var that = this;
    this.addEvents(["click", "touchend"], () => {
      that.copy(that.text)
    });
  }

  copy(text) {
    navigator.clipboard.writeText(text).then(function() {
      // successfull
    }, function(err) {
      // unsuccessfull
    });
  }
}

customElements.define('copy-button', Copy);
```

<p>PS: addEvents prototype:</p>

```Element.prototype.addEvents = Document.prototype.addEvents = Window.prototype.addEvents = function (events, callback) {
  for (var i = 0; i < events.length; i++) this.addEventListener(events[i], callback);
};
```

I'm on the last version of chrome

答:
So thanks to @Jared Smith and @Ken yo, I have this solution:

I have found that there is path, which is an array with all of the path of the click

class TextPopup extends Popup {
  constructor() {
    super();
  }

  connectedCallback() {
    document.body.addEventListener("click", function (e) {
      if (e.path[0].classList.contains("exit")) {
        console.log("exitButton was clicked!");
      }
    });
  }

  show() {
    this.heading = this.getAttribute("heading");
    this.text = this.getAttribute("text");

    this.popup.innerHTML += `

${this.heading}

${this.text}

    `;
  }
}
```

Body:
I'm making a monopoly game for my website, and I have a problem that I can't add event listeners for "i" element in a custom element

Here's my custom element:

class Popup extends HTMLElement {
  constructor() {
    super();
    var that = this;

    var shadow = this.attachShadow({mode: 'open'});
    var wrapper = document.createElement('div');
    wrapper.setAttribute("class","popup-wrapper");
    var popup = document.createElement('div');
    popup.setAttribute('class','popup');

    let exitButton = document.createElement('i');
    exitButton.className = "fas fa-times fa-lg exit";

    exitButton.addEventListener("click", function () {
      console.log('a');
    });

    // styles
    var style = document.createElement('style');
    style.textContent = `
      @import url("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css");
      @import url("https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css");

      .popup-wrapper {
        position: fixed;
        top: 0; left: 0; right: 0; bottom: 0;
        background-color: rgba(0, 0, 0, .6);
        z-index: 9999;
        visibility: visible;
      }

      .popup {
        position: fixed;
        top: 50%; left: 50%;
        transform: translate(-50%, -50%);
        border: 1px solid #d6d6d6;
        background-color: #fff;
        border-radius: .25rem;
        padding: 1rem 2rem;
      }

      /* .exit {
        position: absolute;
        top: .5rem; right: .5rem;
        cursor: pointer;
      } */
    `;

    popup.appendChild(exitButton);

    wrapper.appendChild(popup);

    shadow.appendChild(style);
    shadow.appendChild(wrapper);

    this.isOpen = false;
    this.popup_wrapper = wrapper;
    this.popup = popup;
    this.exitButton = exitButton;
  }

  close() {
    console.log('a');
    this.remove();
  }
}

class TextPopup extends Popup {
  constructor() {
    super();

  }

  show() {
    this.exitButton.addEventListener("click", function () {
      console.log('a');
    });

    this.heading = this.getAttribute("heading");
    this.text = this.getAttribute("text");

    this.popup.innerHTML += `

${this.heading}

${this.text}

    `;
  }
}

customElements.define('text-popup', TextPopup);

I had tried to place it in multiple locations but it is still not working

I also have another custom element where addEventListener working:

class Copy extends HTMLElement {
  constructor() {
    super();

    if (!this.hasAttribute('text')) return console.error("Text is not specified");

    this.text = this.getAttribute('text');
    this.style.cursor = "pointer";
    var that = this;
    this.addEvents(["click", "touchend"], () => {
      that.copy(that.text)
    });
  }

  copy(text) {
    navigator.clipboard.writeText(text).then(function() {
      // successfull
    }, function(err) {
      // unsuccessfull
    });
  }
}

customElements.define('copy-button', Copy);

PS: addEvents prototype:

Element.prototype.addEvents = Document.prototype.addEvents = Window.prototype.addEvents = function (events, callback) {
  for (var i = 0; i < events.length; i++) this.addEventListener(events[i], callback);
};

I'm on the last version of chrome

Body:
So thanks to @Jared Smith and @Ken yo, I have this solution:

I have found that there is path, which is an array with all of the path of the click

class TextPopup extends Popup {
  constructor() {
    super();
  }

  connectedCallback() {
    document.body.addEventListener("click", function (e) {
      if (e.path[0].classList.contains("exit")) {
        console.log("exitButton was clicked!");
      }
    });
  }

  show() {
    this.heading = this.getAttribute("heading");
    this.text = this.getAttribute("text");

    this.popup.innerHTML += `
      <h1>${this.heading}</h1>
      <p>${this.text}</p>
    `;
  }
}


问:
React Native Maps (Mapview Marker) not working
Following is my code segment. Please refer to MapView.Marker, even on giving the coordinates for my current location nothing is displayed, same behavior is observed when i map service locations array and provide latitude,longitude values using it.

When i use mapview marker like this , a single marker is displayed but as for this component i have to display multiple markers on the map with different coordinates i have to go with Mapview.Marker. Please point out what am i missing here.

```<code>    export default class index extends Component {
      constructor(props) {
        super(props);
        this.state = {
          text: "",
          source: require("../../Image/User_default.png"),
          location: {
            latitude: 0,
            latitudeDelta: 0,
            longitude: 0,
            longitudeDelta: 0,
          },
          serviceLocations: [],
        };
      }

      componentDidMount() {
        this._getLocationAsync();
        this._getServices();
      }

      _getServices = () => {
        create_service
          .getAllServices()
          .then((res) => {
            this.setState({
              serviceLocations: res,
            });
          })
          .catch((error) => {
            console.log(error);
          });
      };

      _getLocationAsync = async () => {
        let { status } = await Permissions.askAsync(Permissions.LOCATION);
        if (status !== "granted") {
          Alert.alert("Error", "Permission to access location was denied", [
            { text: "OK" },
          ]);
        } else {
          let location = await Location.getCurrentPositionAsync({});
          location_service
            .setCurrentUserLocation(location)
            .then(async (res) => {
              // console.log("_getLocationAsync:", res);
            })
            .catch((err) => console.log(err));
        }
      };

      render() {
        const { serviceLocations } = this.state;
        return (
          <View style={style.container}>
            <MapView
              style={style.mapStyle}
              provider={PROVIDER_GOOGLE}
              region={{
                latitude: 33.650073,
                longitude: 73.153164,
                latitudeDelta: 0.0921,
                longitudeDelta: 0.0421,
              }}
              showsUserLocation={true}
            />
            <Marker/>
            {serviceLocations.length
              ? serviceLocations.map((serviceLocation,key) => {
                  return (
                    <MapView.Marker
                      coordinate={{
                        latitude: 33.650073,
                        longitude: 73.153164,
                      }}
                      key={key}
                      // image={require("../../Image/location-pin.png")}
                    />
                  );
                })
              : null}
          </View>
        );
      }
    }
</code>```

答:
Sorted the solution myself. Actually what i was doing wrong in this code was that i was using the <Marker> outside the scope of <MapView> which is why markers were not displayed on my maps.
As soon as i corrected the scope issue my problem was solved.

Body:
Following is my code segment. Please refer to MapView.Marker, even on giving the coordinates for my current location nothing is displayed, same behavior is observed when i map service locations array and provide latitude,longitude values using it.

When i use mapview marker like this , a single marker is displayed but as for this component i have to display multiple markers on the map with different coordinates i have to go with Mapview.Marker. Please point out what am i missing here.

    export default class index extends Component {
      constructor(props) {
        super(props);
        this.state = {
          text: "",
          source: require("../../Image/User_default.png"),
          location: {
            latitude: 0,
            latitudeDelta: 0,
            longitude: 0,
            longitudeDelta: 0,
          },
          serviceLocations: [],
        };
      }

      componentDidMount() {
        this._getLocationAsync();
        this._getServices();
      }

      _getServices = () => {
        create_service
          .getAllServices()
          .then((res) => {
            this.setState({
              serviceLocations: res,
            });
          })
          .catch((error) => {
            console.log(error);
          });
      };

      _getLocationAsync = async () => {
        let { status } = await Permissions.askAsync(Permissions.LOCATION);
        if (status !== "granted") {
          Alert.alert("Error", "Permission to access location was denied", [
            { text: "OK" },
          ]);
        } else {
          let location = await Location.getCurrentPositionAsync({});
          location_service
            .setCurrentUserLocation(location)
            .then(async (res) => {
              // console.log("_getLocationAsync:", res);
            })
            .catch((err) => console.log(err));
        }
      };

      render() {
        const { serviceLocations } = this.state;
        return (
          <View style={style.container}>
            <MapView
              style={style.mapStyle}
              provider={PROVIDER_GOOGLE}
              region={{
                latitude: 33.650073,
                longitude: 73.153164,
                latitudeDelta: 0.0921,
                longitudeDelta: 0.0421,
              }}
              showsUserLocation={true}
            />
            <Marker/>
            {serviceLocations.length
              ? serviceLocations.map((serviceLocation,key) => {
                  return (
                    <MapView.Marker
                      coordinate={{
                        latitude: 33.650073,
                        longitude: 73.153164,
                      }}
                      key={key}
                      // image={require("../../Image/location-pin.png")}
                    />
                  );
                })
              : null}
          </View>
        );
      }
    }


问:
Changing CSS properties using jQuery for a markup and different CSS files
I've a HTML markup and I've several CSS files with different properties assigned for the HTML elements which will act as the theme of the markup. Say the Markup is something like

```<code><div id=main>
    <div>{More HTML elements, divs, spans etc}</div>
    <div>{More HTML elements, divs, spans etc}</div>
</div>
</code>```

And the css is like

```<code>/*first.css*/
#main{
    someProperty: values;
}

#main div, #main ul li {
    someProperty: values;
}
</code>```

Another css file

```<code>/*second.css*/
#main{
    someProperty: some other values;
}

#main div, #main ul li {
    someProperty: some other values;
}
</code>```

There are more css files with different properties and values.

What I want to do is, at the click of a button, I want to change the CSS of the markup without changing the markup. So it will be something like

```<code>$('.btn').click(function(){
    var file = $(this).attr('id');
    //remove the previous css file
    //add the new css file (filename is the js var file+'.css')
});
</code>```

I cannot keep doing $('#someId').css({ /* properties */}); as there are many properties in the CSS file.

So how do I best handle this??

答: Keep information about layout independent of the color, images etc.If possible, create one css styling for body tag which has information of color in it.</p>

Body:
I've a HTML markup and I've several CSS files with different properties assigned for the HTML elements which will act as the theme of the markup. Say the Markup is something like

{More HTML elements, divs, spans etc}

{More HTML elements, divs, spans etc}

And the css is like

/*first.css*/
#main{
    someProperty: values;
}

#main div, #main ul li {
    someProperty: values;
}

Another css file

/*second.css*/
#main{
    someProperty: some other values;
}

#main div, #main ul li {
    someProperty: some other values;
}

There are more css files with different properties and values.

What I want to do is, at the click of a button, I want to change the CSS of the markup without changing the markup. So it will be something like

$('.btn').click(function(){
    var file = $(this).attr('id');
    //remove the previous css file
    //add the new css file (filename is the js var file+'.css')
});

I cannot keep doing $('#someId').css({ /* properties */}); as there are many properties in the CSS file.

So how do I best handle this??