问:
% change of 2 time period calculations in SQL (GBQ)
Currently have multiple calculations similar to this:

SELECT SUM(A)/COUNT(B) AS CALCULATION
  FROM TABLE
  WHERE YEAR = 2019
```

But I want to find the percent change between Year 2019 and 2018,
like (Calculation1/Calculation2-1) where calc1 is 2019 and calc2 is 2018.

Is the best way a temp table or a subquery? What would be some base code to accomplish analysis?

答:
Using IF. A little bit ugly but a more generalized version:

```<code>with yearlyset as (
  select
     year,
     lag(year) over(order by 1) lastyear,
     coalesce(lag(calculation) over(order by 1), 0) lastyearcalculation,
     calculation from (
        select year, sum(a)/count(b) as calculation
        from `dataset.table`
        group by 1
     )
)

select
   year,
   if(
      year=2019 and lastyear=2018,
      calculation/lastyearcalculation-1,
      if(
         coalesce(lastyearcalculation, 0) = 0,
         0.0,
         calculation/lastyearcalculation
      )
   ) as percent_change
from yearlyset
</code>```

Body:
Currently have multiple calculations similar to this:

SELECT SUM(A)/COUNT(B) AS CALCULATION
  FROM TABLE
  WHERE YEAR = 2019

But I want to find the percent change between Year 2019 and 2018,
like (Calculation1/Calculation2-1) where calc1 is 2019 and calc2 is 2018.

Is the best way a temp table or a subquery? What would be some base code to accomplish analysis?

Body:
Using IF. A little bit ugly but a more generalized version:

with yearlyset as (
  select
     year,
     lag(year) over(order by 1) lastyear,
     coalesce(lag(calculation) over(order by 1), 0) lastyearcalculation,
     calculation from (
        select year, sum(a)/count(b) as calculation
        from `dataset.table`
        group by 1
     )
)

select
   year,
   if(
      year=2019 and lastyear=2018,
      calculation/lastyearcalculation-1,
      if(
         coalesce(lastyearcalculation, 0) = 0,
         0.0,
         calculation/lastyearcalculation
      )
   ) as percent_change
from yearlyset


来源: stackexchange

问:
Accessing Azure Storage Blob from an AKS cluster
A little context: I'm having to migrate a project from AWS, where I'm currently using ECS, to Azure, where I'll be using AKS since their ACS (ECS equivalent) is deprecated.

This is a regular Django app, with its configuration variables being fetched from a server-config.json hosted on a private S3 bucket, the EC2 instance has the correct role with S3FullAccess,

I've been looking into reproducing that same behavior but with Azure Blob Storage instead, having achieved no success whatsoever :-(.

I tried using the Service Principal concept and adding it to the AKS Cluster with Storage Blob Data Owner roles, but that doesn't seem to work. Overall it's been quite the frustrating experience - maybe I'm just having a hard time grasping the right way to use the permissions/scopes. The fact that the AKS Cluster creates its own resource group is something unfathomable - but I've attempted attaching the policies to it as well, to no avail. I then moved onto a solution indicated by Microsoft.

I managed to bind my AKS pods with the correct User Managed Identity through their indicated solution aad-pod-identity, but I feel like I'm missing something. I assigned Storage Blob Data Owner/Contributor to the identity, but still, when I enter the pods and try to access a Blob (using the python sdk), I get a resource not found message.

Is what I'm trying to achieve possible at all? Or will I have to change to a solution using Azure Keyvault/something along those lines?

答:
first off all, you can use AKS Engine which is more or less ACS for Kubernetes now.

As for the access to the blob storage, you dont have to use Managed Service Identity, you can just use account name\key ( which is a bit less secure, but a lot less error prone and more examples exist ). The fact that you are getting resource not found error most likely means your auth part is fine, you just dont have access to the resource, according to this storage blob contributor should be fine if you assigned it at a proper scope. For this to work 100% just give your identity contributor access at subscription level, this way its guaranteed to work.

I've found an example of using python with MSI (here). You should start with that (and grant your identity contributor access) and verify you can list resource groups. when that works making reading blobs working should be trivial.

ContentLicense: CC BY-SA 4.0


问:
Compare the content of two csv files in java
I am trying to compare the content of two csv files. I have the csv file test1.csv and test2.csv. The content from both should be the same.. if not , then I want to transfer the difference into a .txt file. If every thing is equal, everything is correct.

I just created two test csv files with columns and rows with content

The first column is a primary key of the respective table. I want to compare it by the identificator

```<code>test1.csv
1,Max,New York
2,David,Jersey
</code>```

```<code>test2.csv
1,Max,California
2,David,Jersey
</code>```

The Output here in the .txt should be the row "1,Max,New York"

I just have no code. And I am happy about every adivce and hint I can get. Thank you in advance.

答:
I will suggest the simplest approach will be compare two file contents using an online tool which will give you an idea about what is different. You can refer the following link.

https://www.diffchecker.com/diff

If you want, you can use tools like winmerge for which you need to download.

If you want to achieve in java, refer below the two links.

https://javaconceptoftheday.com/compare-two-text-files-in-java/

Comparing two files in java

Body:
I am trying to compare the content of two csv files. I have the csv file test1.csv and test2.csv. The content from both should be the same.. if not , then I want to transfer the difference into a .txt file. If every thing is equal, everything is correct.

I just created two test csv files with columns and rows with content

The first column is a primary key of the respective table. I want to compare it by the identificator

test1.csv
1,Max,New York
2,David,Jersey

test2.csv
1,Max,California
2,David,Jersey

The Output here in the .txt should be the row "1,Max,New York"

I just have no code. And I am happy about every adivce and hint I can get. Thank you in advance.


问:
Pivot table aggregation by index
I have two dataframes containing information about student grades and test scores. The first looks like this:

```<code>     ID    Test_Score    Class1    Class2    Class3
0    001   85            B-        A         C+
1    002   78            B         NaN       B+
2    003   93            A         B         NaN
...
</code>```

The second looks like this:

```<code>     0                1
0    Algebra          A
0    Calculus_1       B
0    Calculus_2       C-
1    Algebra          C+
1    Trig             F
1    Trig             C
1    Calculus_1       C-
...
</code>```

The indices in each dataframe refer to the same student. So the student at index 0 is the same in both dataframes.

What I want to do is create a pivot table from the second dataframe, where the rows correspond to students (i.e. indices), the columns are the math classes, and the values are the highest grade they made in each class (since it's possible for a student to have taken a class more than once). I will then concatenate this to the first dataframe.

I have already written an aggregation function that finds the highest grade.

I tried the following knowing it would fail:

```<code>p = pd.pivot_table(u, columns=0, values=1, aggfunc=highest)
</code>```

Instead of returning a dataframe with a row for each student, I get a single row that contains the highest grade that any student made in the given class:

```<code>     Algebra   Trig    Precalculus   Calculus_1   Calculus_2
1    A         A+      A+            A            A
</code>```

The way I've framed the problem in my mind, I just need to aggregate across the rows which share in index, which I am unsure how to do.

I'm also open to an entirely different approach.

Desired output:

```<code>     ID    Test_Score    Class1    Class2    Class3   Algebra   Trig ...
0    001   85            B-        A         C+       A         NaN
1    002   78            B         NaN       B+       C+        C
2    003   93            A         B         NaN      B         B-
...
</code>```

EDIT:
Here is the code for my 'highest' function:

```<code>def highest(x):
    q = 0
    z = None
    for g in x:
        if qpoints(g) > q:
            q = qpoints(g)
            z = g
    return z
</code>```

where qpoints is the following function that I was already using elsewhere:

```<code>def qpoints(x):
    qvalue = {'W': 0,
              'F': 0,
              'D': 1.0,
              'D+': 1.33,
              'C-': 1.67,
              'C': 2.0,
              'C+': 2.33,
              'B-': 2.67,
              'B': 3.0,
              'B+': 3.33,
              'A-': 3.84,
              'A': 4.0,
              'A+': 4.0}
    return qvalue[x]
</code>```

答:
You problem is that you need to keep the index values of the second dataframe when you pivot_table, see this answer for understanding. So if you do:

```<code>print (df2.reset_index().pivot_table(index='index', values=[1], columns=[0],
                                     aggfunc= lambda x: sorted(x)[0]))
                                     # I used my own idea of highest function
            1
0     Algebra Calculus_1 Calculus_2 Trig
index
0           A          B         C-  NaN
1          C+         C-        NaN    C
</code>```

then you can join such as:

```<code>df_p = df2.reset_index().pivot_table(index='index', values=[1], columns=[0],
                                                aggfunc= lambda x: sorted(x)[0])
df_p.columns = [col[1] for col in df_p.columns]
new_df = df1.join(df_p)

print (new_df)
    ID  Test_Score Class1 Class2 Class3 Algebra Calculus_1 Calculus_2 Trig
0  001          85     B-      A     C+       A          B         C-  NaN
1  002          78      B    NaN     B+      C+         C-        NaN    C
2  003          93      A      B    NaN     NaN        NaN        NaN  NaN
</code>```

Title: Pivot table aggregation by index

Body:
I have two dataframes containing information about student grades and test scores. The first looks like this:

     ID    Test_Score    Class1    Class2    Class3
0    001   85            B-        A         C+
1    002   78            B         NaN       B+
2    003   93            A         B         NaN
...

The second looks like this:

     0                1
0    Algebra          A
0    Calculus_1       B
0    Calculus_2       C-
1    Algebra          C+
1    Trig             F
1    Trig             C
1    Calculus_1       C-
...

The indices in each dataframe refer to the same student. So the student at index 0 is the same in both dataframes.

What I want to do is create a pivot table from the second dataframe, where the rows correspond to students (i.e. indices), the columns are the math classes, and the values are the highest grade they made in each class (since it's possible for a student to have taken a class more than once). I will then concatenate this to the first dataframe.

I have already written an aggregation function that finds the highest grade.

I tried the following knowing it would fail:

p = pd.pivot_table(u, columns=0, values=1, aggfunc=highest)

Instead of returning a dataframe with a row for each student, I get a single row that contains the highest grade that any student made in the given class:

     Algebra   Trig    Precalculus   Calculus_1   Calculus_2
1    A         A+      A+            A            A

The way I've framed the problem in my mind, I just need to aggregate across the rows which share in index, which I am unsure how to do.

I'm also open to an entirely different approach.

Desired output:

     ID    Test_Score    Class1    Class2    Class3   Algebra   Trig ...
0    001   85            B-        A         C+       A         NaN
1    002   78            B         NaN       B+       C+        C
2    003   93            A         B         NaN      B         B-
...

EDIT:
Here is the code for my 'highest' function:

def highest(x):
    q = 0
    z = None
    for g in x:
        if qpoints(g) > q:
            q = qpoints(g)
            z = g
    return z

where qpoints is the following function that I was already using elsewhere:

def qpoints(x):
    qvalue = {'W': 0,
              'F': 0,
              'D': 1.0,
              'D+': 1.33,
              'C-': 1.67,
              'C': 2.0,
              'C+': 2.33,
              'B-': 2.67,
              'B': 3.0,
              'B+': 3.33,
              'A-': 3.84,
              'A': 4.0,
              'A+': 4.0}
    return qvalue[x]

Body:
You problem is that you need to keep the index values of the second dataframe when you pivot_table, see this answer for understanding. So if you do:

print (df2.reset_index().pivot_table(index='index', values=[1], columns=[0],
                                     aggfunc= lambda x: sorted(x)[0]))
                                     # I used my own idea of highest function
            1
0     Algebra Calculus_1 Calculus_2 Trig
index
0           A          B         C-  NaN
1          C+         C-        NaN    C

then you can join such as:

df_p = df2.reset_index().pivot_table(index='index', values=[1], columns=[0],
                                                aggfunc= lambda x: sorted(x)[0])
df_p.columns = [col[1] for col in df_p.columns]
new_df = df1.join(df_p)

print (new_df)
    ID  Test_Score Class1 Class2 Class3 Algebra Calculus_1 Calculus_2 Trig
0  001          85     B-      A     C+       A          B         C-  NaN
1  002          78      B    NaN     B+      C+         C-        NaN    C
2  003          93      A      B    NaN     NaN        NaN        NaN  NaN


问:
UIPageViewController. How to set up the array of custom UIViewControllers
I have a set of 4 UIViewControllers, all have their own custom class, and I have delegates set up. As of now I have container views in my main view that get scrolled off-screen and thats how I'm doing a "pseudo-page view controller". However for the sake of training I wanted to convert this into an actual page-view controller using UIPageViewController.

I've seen a bunch of tutorials but most people just use one view controller and change the text inside it to display multiple ones. In my case I have 4 custom view controllers:

```<code>var glanceController: GlanceVC!
var goalsController: GoalsVC!
var commuteController: CommuteVC!
var compareController: CompareVC!
</code>```

On my previous pseudo-page view controller I initializzed them like this:

```<code>func loadVC() {
    glanceController = self.storyboard?.instantiateViewController(withIdentifier: "sbGlance") as? GlanceVC
    goalsController = self.storyboard?.instantiateViewController(withIdentifier: "sbGoals") as? GoalsVC
    commuteController = self.storyboard?.instantiateViewController(withIdentifier: "sbCommute") as? CommuteVC
    compareController = self.storyboard?.instantiateViewController(withIdentifier: "sbCompare") as? CompareVC
}
</code>```

Now from what I understand the UIPageViewController needs an array of UIViewControllers. However I can't create this array:

```<code>var VCArray: [UIViewController] = [glanceController, goalsController, commuteController, compareController]
</code>```

error: Cannot use instance member 'glancecontrolleer' within propery initializer.

I tried instead declaring a blank array var VCArray: [UIViewcontroller] = []
and then adding after

```<code>func loadVC() {
    glanceController = self.storyboard?.instantiateViewController(withIdentifier: "sbGlance") as? GlanceVC
    goalsController = self.storyboard?.instantiateViewController(withIdentifier: "sbGoals") as? GoalsVC
    commuteController = self.storyboard?.instantiateViewController(withIdentifier: "sbCommute") as? CommuteVC
    compareController = self.storyboard?.instantiateViewController(withIdentifier: "sbCompare") as? CompareVC
    VCArray += glanceController
}
</code>```

however that also has an error: "Argument Type @value glanceVC? does not conform to expected type "Sequence".

Can someone help me make this array of custom view controllers for my uipageview?

答:
Create a computed property and return the view controllers array</p>

```<code>var VCArray: [UIViewController] {
    if let glanceController = self.storyboard?.instantiateViewController(withIdentifier: "sbGlance") as? GlanceVC,
        let goalsController = self.storyboard?.instantiateViewController(withIdentifier: "sbGoals") as? GoalsVC,
        let commuteController = self.storyboard?.instantiateViewController(withIdentifier: "sbCommute") as? CommuteVC,
        let compareController = self.storyboard?.instantiateViewController(withIdentifier: "sbCompare") as? CompareVC {
            return [glanceController, goalsController, commuteController, compareController]
    }
    return []
}
</code>```

Body:
I have a set of 4 UIViewControllers, all have their own custom class, and I have delegates set up. As of now I have container views in my main view that get scrolled off-screen and thats how I'm doing a "pseudo-page view controller". However for the sake of training I wanted to convert this into an actual page-view controller using UIPageViewController.

I've seen a bunch of tutorials but most people just use one view controller and change the text inside it to display multiple ones. In my case I have 4 custom view controllers:

var glanceController: GlanceVC!
var goalsController: GoalsVC!
var commuteController: CommuteVC!
var compareController: CompareVC!

On my previous pseudo-page view controller I initializzed them like this:

func loadVC() {
    glanceController = self.storyboard?.instantiateViewController(withIdentifier: "sbGlance") as? GlanceVC
    goalsController = self.storyboard?.instantiateViewController(withIdentifier: "sbGoals") as? GoalsVC
    commuteController = self.storyboard?.instantiateViewController(withIdentifier: "sbCommute") as? CommuteVC
    compareController = self.storyboard?.instantiateViewController(withIdentifier: "sbCompare") as? CompareVC
}

Now from what I understand the UIPageViewController needs an array of UIViewControllers. However I can't create this array:

var VCArray: [UIViewController] = [glanceController, goalsController, commuteController, compareController]

error: Cannot use instance member 'glancecontrolleer' within propery initializer.

I tried instead declaring a blank array var VCArray: [UIViewcontroller] = []
and then adding after

func loadVC() {
    glanceController = self.storyboard?.instantiateViewController(withIdentifier: "sbGlance") as? GlanceVC
    goalsController = self.storyboard?.instantiateViewController(withIdentifier: "sbGoals") as? GoalsVC
    commuteController = self.storyboard?.instantiateViewController(withIdentifier: "sbCommute") as? CommuteVC
    compareController = self.storyboard?.instantiateViewController(withIdentifier: "sbCompare") as? CompareVC
    VCArray += glanceController
}

however that also has an error: "Argument Type @value glanceVC? does not conform to expected type "Sequence".

Can someone help me make this array of custom view controllers for my uipageview?

Body:
Create a computed property and return the view controllers array

var VCArray: [UIViewController] {
    if let glanceController = self.storyboard?.instantiateViewController(withIdentifier: "sbGlance") as? GlanceVC,
        let goalsController = self.storyboard?.instantiateViewController(withIdentifier: "sbGoals") as? GoalsVC,
        let commuteController = self.storyboard?.instantiateViewController(withIdentifier: "sbCommute") as? CommuteVC,
        let compareController = self.storyboard?.instantiateViewController(withIdentifier: "sbCompare") as? CompareVC {
            return [glanceController, goalsController, commuteController, compareController]
    }
    return []
}


问:
Modify XML content with XML Parser PHP
I have a pretty large XML file. I am parsing it with XML Parser using Php. XML parsing part is ok, i can read the data. However, i have no idea modifying a single tag's content. Should I read the whole data into a string and rewrite the file with modified one? Is there any other solutions? I dont want to use simplexml because of the size of the file.

For example, i would like to change Jack to another user's name.

Jack

Thanks..

So far:

```<code>$file = "5.xml";

function startElement($parser, $name, $attrs)
{
//do something

}

function contents($parser, $data){
//do something

}

function endElement($parser, $name)
{
//do something
}

$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "contents");
if (!($fp = fopen($file, "r"))) {
    die("could not open XML input");
}

while ($data = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
        die(sprintf("XML error: %s at line %d",
                    xml_error_string(xml_get_error_code($xml_parser)),
                    xml_get_current_line_number($xml_parser)));
    }
}
xml_parser_free($xml_parser);
</code>```

答:
Since it's a large XML file, XMLParser is the correct tool.

If you want to change a tag's content, you need to save the current tag name in startElement and output different content in contents when you encounter the tag you want to modify.

```<code>startElement: $this->currentTag = $name;
contents: $this->currentTag == 'myspecialtag' ? print(md5($data)) : print($data);
</code>```

ContentLicense: CC BY-SA 2.5

Title: Modify XML content with XML Parser PHP

Body:
I have a pretty large XML file. I am parsing it with XML Parser using Php. XML parsing part is ok, i can read the data. However, i have no idea modifying a single tag's content. Should I read the whole data into a string and rewrite the file with modified one? Is there any other solutions? I dont want to use simplexml because of the size of the file.

For example, i would like to change Jack to another user's name.

Jack

Thanks..

So far:

$file = "5.xml";

function startElement($parser, $name, $attrs)
{
//do something

}

function contents($parser, $data){
//do something

}

function endElement($parser, $name)
{
//do something
}

$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "contents");
if (!($fp = fopen($file, "r"))) {
    die("could not open XML input");
}

while ($data = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
        die(sprintf("XML error: %s at line %d",
                    xml_error_string(xml_get_error_code($xml_parser)),
                    xml_get_current_line_number($xml_parser)));
    }
}
xml_parser_free($xml_parser);

Body:
Since it's a large XML file, XMLParser is the correct tool.

If you want to change a tag's content, you need to save the current tag name in startElement and output different content in contents when you encounter the tag you want to modify.

startElement: $this->currentTag = $name;
contents: $this->currentTag == 'myspecialtag' ? print(md5($data)) : print($data);

ContentLicense: CC BY-SA 3.0


问:
How to show Firebase data in TextViews using UserInformation Class
I am having trouble showing the correct user information from my realtime database to the specific textviews. At the moment, none of them are showing

This application includes android studio and extracting user information based on email and userId.

My database structure is pretty simple as it looks like this:

My UserInformation class is types as such:

```<code>public class UserInformation {

private String name;
private String email;
private String campus;
private String twop_num;
private Timestamp expiration_date;
private Double meals;
private Double pfunds;

public UserInformation(){

}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getCampus() {
    return campus;
}

public void setCampus(String campus) {
    this.campus = campus;
}

public String getTwop_num() {
    return twop_num;
}

public void setTwop_num(String twop_num) {
    this.twop_num = twop_num;
}

public Timestamp getExpiration_date() {
    return expiration_date;
}

public void setExpiration_date(Timestamp expiration_date) {
    this.expiration_date = expiration_date;
}

public Double getMeals() {
    return meals;
}

public void setMeals(Double meals) {
    this.meals = meals;
}

public Double getpfunds() {
    return pfunds;
}

public void setpfunds(Double punds) {
    this.pfunds = punds;
}
</code>```

And I believe the problem is with pulling the data from the database of the 'append" method I am using when trying to show the information in the TextView. The code is:

```<code>    private TextView Email;
private TextView TwoPNum;
private TextView Meal;
private TextView PantherFunds;
private TextView Expiration;
private TextView Campus;
private Button logout;

//...

 Email = (TextView) findViewById(R.id.profileEmail);
 TwoPNum = (TextView) findViewById(R.id.profileUid);
 Meal = (TextView) findViewById(R.id.mealsNum);
 PantherFunds = (TextView) findViewById(R.id.pFundsNum);
 Expiration = (TextView) findViewById(R.id.expirationDate);
 Campus = (TextView) findViewById(R.id.campusText);

 //...

  private void showData(DataSnapshot dataSnapshot) {
    for (DataSnapshot ds : dataSnapshot.getChildren()) {
        UserInformation uInfo = new UserInformation();
        uInfo.setName(ds.child(userID).getValue(UserInformation.class).getName()); //set the name
        uInfo.setEmail(ds.child(userID).getValue(UserInformation.class).getEmail()); //set the email
        uInfo.setCampus(ds.child(userID).getValue(UserInformation.class).getCampus()); //set the phone_num
        uInfo.setExpiration_date(ds.child(userID).getValue(UserInformation.class).getExpiration_date());// set expiration date
        uInfo.setpfunds(ds.child(userID).getValue(UserInformation.class).getpfunds()); // get pantherfunds
        uInfo.setMeals(ds.child(userID).getValue(UserInformation.class).getMeals()); // get Meals
        uInfo.setTwop_num(ds.child(userID).getValue(UserInformation.class).getTwop_num()); // get Meals

        //display all the information
        Log.d(TAG, "showData: name: " + uInfo.getName());
        Log.d(TAG, "showData: email: " + uInfo.getEmail());
        Log.d(TAG, "showData: campus : " + uInfo.getCampus());
        Log.d(TAG, "showData: expiration_date: " + uInfo.getExpiration_date());
        Log.d(TAG, "showData: pfunds: " + uInfo.getpfunds());
        Log.d(TAG, "showData: : meals" + uInfo.getMeals());
        Log.d(TAG, "showData: twop_num: " + uInfo.getTwop_num());

        // Show Data in TextViews
        Email.append(uInfo.getEmail());
        TwoPNum.append(uInfo.getTwop_num());
        Meal.append(String.valueOf(uInfo.getMeals()));
        PantherFunds.append(String.valueOf(uInfo.getpfunds()));
        Expiration.append(String.valueOf(uInfo.getExpiration_date()));
        Campus.append(uInfo.getCampus());

    }
}
</code>```

答:
It seems you are using firestore and not realtime database, to retrieve data of the collection in firestore try the following:

```<code>db.collection("users")
    .get()
    .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (task.isSuccessful()) {
                for (QueryDocumentSnapshot document : task.getResult()) {
                    Log.d(TAG, document.getId() + " => " + document.getData());
                }
            } else {
                Log.d(TAG, "Error getting documents: ", task.getException());
            }
        }
    });
</code>```

Check the docs for more info:

https://firebase.google.com/docs/firestore/query-data/get-data

Body:
I am having trouble showing the correct user information from my realtime database to the specific textviews. At the moment, none of them are showing

This application includes android studio and extracting user information based on email and userId.

My database structure is pretty simple as it looks like this:

My UserInformation class is types as such:

public class UserInformation {

private String name;
private String email;
private String campus;
private String twop_num;
private Timestamp expiration_date;
private Double meals;
private Double pfunds;

public UserInformation(){

}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getCampus() {
    return campus;
}

public void setCampus(String campus) {
    this.campus = campus;
}

public String getTwop_num() {
    return twop_num;
}

public void setTwop_num(String twop_num) {
    this.twop_num = twop_num;
}

public Timestamp getExpiration_date() {
    return expiration_date;
}

public void setExpiration_date(Timestamp expiration_date) {
    this.expiration_date = expiration_date;
}

public Double getMeals() {
    return meals;
}

public void setMeals(Double meals) {
    this.meals = meals;
}

public Double getpfunds() {
    return pfunds;
}

public void setpfunds(Double punds) {
    this.pfunds = punds;
}

And I believe the problem is with pulling the data from the database of the 'append" method I am using when trying to show the information in the TextView. The code is:

    private TextView Email;
private TextView TwoPNum;
private TextView Meal;
private TextView PantherFunds;
private TextView Expiration;
private TextView Campus;
private Button logout;

//...

 Email = (TextView) findViewById(R.id.profileEmail);
 TwoPNum = (TextView) findViewById(R.id.profileUid);
 Meal = (TextView) findViewById(R.id.mealsNum);
 PantherFunds = (TextView) findViewById(R.id.pFundsNum);
 Expiration = (TextView) findViewById(R.id.expirationDate);
 Campus = (TextView) findViewById(R.id.campusText);

 //...

  private void showData(DataSnapshot dataSnapshot) {
    for (DataSnapshot ds : dataSnapshot.getChildren()) {
        UserInformation uInfo = new UserInformation();
        uInfo.setName(ds.child(userID).getValue(UserInformation.class).getName()); //set the name
        uInfo.setEmail(ds.child(userID).getValue(UserInformation.class).getEmail()); //set the email
        uInfo.setCampus(ds.child(userID).getValue(UserInformation.class).getCampus()); //set the phone_num
        uInfo.setExpiration_date(ds.child(userID).getValue(UserInformation.class).getExpiration_date());// set expiration date
        uInfo.setpfunds(ds.child(userID).getValue(UserInformation.class).getpfunds()); // get pantherfunds
        uInfo.setMeals(ds.child(userID).getValue(UserInformation.class).getMeals()); // get Meals
        uInfo.setTwop_num(ds.child(userID).getValue(UserInformation.class).getTwop_num()); // get Meals

        //display all the information
        Log.d(TAG, "showData: name: " + uInfo.getName());
        Log.d(TAG, "showData: email: " + uInfo.getEmail());
        Log.d(TAG, "showData: campus : " + uInfo.getCampus());
        Log.d(TAG, "showData: expiration_date: " + uInfo.getExpiration_date());
        Log.d(TAG, "showData: pfunds: " + uInfo.getpfunds());
        Log.d(TAG, "showData: : meals" + uInfo.getMeals());
        Log.d(TAG, "showData: twop_num: " + uInfo.getTwop_num());

        // Show Data in TextViews
        Email.append(uInfo.getEmail());
        TwoPNum.append(uInfo.getTwop_num());
        Meal.append(String.valueOf(uInfo.getMeals()));
        PantherFunds.append(String.valueOf(uInfo.getpfunds()));
        Expiration.append(String.valueOf(uInfo.getExpiration_date()));
        Campus.append(uInfo.getCampus());

    }
}

Body:
It seems you are using firestore and not realtime database, to retrieve data of the collection in firestore try the following:

db.collection("users")
    .get()
    .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (task.isSuccessful()) {
                for (QueryDocumentSnapshot document : task.getResult()) {
                    Log.d(TAG, document.getId() + " => " + document.getData());
                }
            } else {
                Log.d(TAG, "Error getting documents: ", task.getException());
            }
        }
    });

Check the docs for more info:

https://firebase.google.com/docs/firestore/query-data/get-data


问:
Selecting elements from "div" dropdown - Selenium
I have a "div" dropdown, not "select". So my function works fine everywhere except dropdows which open not from the dropdown button place, but from above (because dropdown is placed at the bottom of the page) to prevent... page scrolling i guess? Maybe the problem is that it opens too fast or too slow or what, so function usually clicks not the needed element but one of the closest to it. Mostly it works this way if element is not at the beginning of dropdown so it is scrolled to the element. Any suggestions what can be made?

The best way i found is to use actions, splitting moving to element and clicking into 2 rows (works much worse if writing in 1 row). By the way, "waitVisibilityOfElement(By)" is a function with webdriver wait for expected conditions

```<code>public void selectFromDropdown(By by) {
        Log.debug("selecting from dropdown by" + by);
        waitVisibilityOfElement(by);
        Actions actions = new Actions(wrappedWebDriver);
       actions.moveToElement(wrappedWebDriver.findElement(by)).perform();
        Log.debug("clicking dropdown item");
        wrappedWebDriver.findElement(by).click();
}
</code>```

I expect needed element to be clicked, But usually it clicks another one

Ok with some help i came to a final decision which is the best way to select dropdown filters without using any .sleep() functions if other simple ways do not work for you.

```<code>public void selectFromDropdown(By by) {
        Log.debug("selecting from dropdown by" + by);
        WebElement eleV = wrappedWebDriver.findElement(by);

        waitVisibilityOfElement(by);

        JavascriptExecutor js = (JavascriptExecutor) wrappedWebDriver;
        js.executeScript("arguments[0].scrollIntoView();", eleV);

        Actions actions = new Actions(wrappedWebDriver);
        actions.moveToElement(wrappedWebDriver.findElement(by)).perform();
        Log.debug("clicking dropdown item");
        wrappedWebDriver.findElement(by).click();
    }
</code>```

答:
Did you try to scroll to the expected element value before move mouse on it and click. Hope following code can help:</p>

```<code>public void selectFromDropdown(By by) {
    Log.debug("selecting from dropdown by" + by);
    var eleValue = wrappedWebDriver.findElement(by);
    Log.debug("Scroll to element");
    browser.executeScript("arguments[0].scrollIntoView();", eleValue);
    waitVisibilityOfElement(by);
    Actions actions = new Actions(wrappedWebDriver);
    actions.moveToElement(eleValue).perform();
    Log.debug("clicking dropdown item");
    eleValue.click();
}
</code>```

Body:
I have a "div" dropdown, not "select". So my function works fine everywhere except dropdows which open not from the dropdown button place, but from above (because dropdown is placed at the bottom of the page) to prevent... page scrolling i guess? Maybe the problem is that it opens too fast or too slow or what, so function usually clicks not the needed element but one of the closest to it. Mostly it works this way if element is not at the beginning of dropdown so it is scrolled to the element. Any suggestions what can be made?

The best way i found is to use actions, splitting moving to element and clicking into 2 rows (works much worse if writing in 1 row). By the way, "waitVisibilityOfElement(By)" is a function with webdriver wait for expected conditions

public void selectFromDropdown(By by) {
        Log.debug("selecting from dropdown by" + by);
        waitVisibilityOfElement(by);
        Actions actions = new Actions(wrappedWebDriver);
       actions.moveToElement(wrappedWebDriver.findElement(by)).perform();
        Log.debug("clicking dropdown item");
        wrappedWebDriver.findElement(by).click();
}

I expect needed element to be clicked, But usually it clicks another one

Ok with some help i came to a final decision which is the best way to select dropdown filters without using any .sleep() functions if other simple ways do not work for you.

public void selectFromDropdown(By by) {
        Log.debug("selecting from dropdown by" + by);
        WebElement eleV = wrappedWebDriver.findElement(by);

        waitVisibilityOfElement(by);

        JavascriptExecutor js = (JavascriptExecutor) wrappedWebDriver;
        js.executeScript("arguments[0].scrollIntoView();", eleV);

        Actions actions = new Actions(wrappedWebDriver);
        actions.moveToElement(wrappedWebDriver.findElement(by)).perform();
        Log.debug("clicking dropdown item");
        wrappedWebDriver.findElement(by).click();
    }

Body:
Did you try to scroll to the expected element value before move mouse on it and click. Hope following code can help:

public void selectFromDropdown(By by) {
    Log.debug("selecting from dropdown by" + by);
    var eleValue = wrappedWebDriver.findElement(by);
    Log.debug("Scroll to element");
    browser.executeScript("arguments[0].scrollIntoView();", eleValue);
    waitVisibilityOfElement(by);
    Actions actions = new Actions(wrappedWebDriver);
    actions.moveToElement(eleValue).perform();
    Log.debug("clicking dropdown item");
    eleValue.click();
}


问:
Format number to always show 2 decimal places
I would like to format my numbers to always display 2 decimal places, rounding where applicable.

Examples:

```<code>number     display
------     -------
1          1.00
1.341      1.34
1.345      1.35
</code>```

I have been using this:

```<code>parseFloat(num).toFixed(2);
</code>```

But it's displaying 1 as 1, rather than 1.00.

答:
Just run into this one of longest thread, below is my solution:

```<code>parseFloat(Math.round((parseFloat(num * 100)).toFixed(2)) / 100 ).toFixed(2)
</code>```

Let me know if anyone can poke a hole

Body:
I would like to format my numbers to always display 2 decimal places, rounding where applicable.

Examples:

number     display
------     -------
1          1.00
1.341      1.34
1.345      1.35

I have been using this:

parseFloat(num).toFixed(2);

But it's displaying 1 as 1, rather than 1.00.

Body:
Just run into this one of longest thread, below is my solution:

parseFloat(Math.round((parseFloat(num * 100)).toFixed(2)) / 100 ).toFixed(2)

Let me know if anyone can poke a hole


问:
How to update the value of the 2D vector at particular index in clojure?
I'm solving a finding treasure problem and I want to change my vector data value. So, How can I do that?

I tried so many things but nothing worked for me. I tried assoc, update, assoc-in, update-in and all.

(println (update-in data [row col] "+"))

(def data1 (-> data (assoc-in [0 0] \+)))

(println data1)
```

<p>So, my vector is like this</p>

<pre class="lang-clj prettyprint-override"><code>["---#--###----"
 "---#---#-#---"
 "-#-####---##-"
 "-#------#----"
 "-############"
 "------------@"]
</code>```

and I want change - with +.

答:
You're going to have to refine your data structure so that assoc-in works with it.  Functions like assoc-in and update-in operate on nested key-value data structures, such as maps and vectors.  I'd recommend an ingest function like the following:

```<code>(defn create-maze [m]
  (into [] (map vec) m))
</code>```

This provides you with a vector of vectors, similar in nature to a two-dimensional array.  You can then provide a helper function to print the maze to screen:

```<code>(defn print-maze [m]
  (doseq [line m]
    (->> line (apply str) println)))
</code>```

Now that you have a way of getting back and forth from a string representation, you can now use assoc-in on the intermediate form to create mazes with altered contents:

```<code>(->
  (create-maze data)
  (assoc-in [0 0] \+)
  (assoc-in [3 4] \+)
  print-maze)
</code>```

Body:
I'm solving a finding treasure problem and I want to change my vector data value. So, How can I do that?

I tried so many things but nothing worked for me. I tried assoc, update, assoc-in, update-in and all.

(println (update-in data [row col] "+"))

(def data1 (-> data (assoc-in [0 0] \+)))

(println data1)

So, my vector is like this

["---#--###----"
 "---#---#-#---"
 "-#-####---##-"
 "-#------#----"
 "-############"
 "------------@"]

and I want change - with +.

Body:
You're going to have to refine your data structure so that assoc-in works with it.  Functions like assoc-in and update-in operate on nested key-value data structures, such as maps and vectors.  I'd recommend an ingest function like the following:

(defn create-maze [m]
  (into [] (map vec) m))

This provides you with a vector of vectors, similar in nature to a two-dimensional array.  You can then provide a helper function to print the maze to screen:

(defn print-maze [m]
  (doseq [line m]
    (->> line (apply str) println)))

Now that you have a way of getting back and forth from a string representation, you can now use assoc-in on the intermediate form to create mazes with altered contents:

(->
  (create-maze data)
  (assoc-in [0 0] \+)
  (assoc-in [3 4] \+)
  print-maze)


问:
Laravel blade syntax for @if/@endif spacing issueif
what is the similar blade syntax for the following code?

```<code><?php if(...):?>abc<?php else:?>cde<?php endif;?>
</code>```

the code
@if(...) abc @else .... is no good as it ads a space before and after the "abc" the code @if(...)abc@endif (no spacing before and after html string) generates error ...

Thanks

答:
Solution

The correct solution for this problem would be following:

```<code>@if(1==1){{ '1' }}@endif
</code>```

This happens often and makes problem with "space sensitive" parts of code like values in <option> tags.

Having the @if(1==1) 1 @endif would be compiled to following which shows empty spaces around the number:

```<code><?php if(1==1): ?> 1 <?php endif; ?>
</code>```

Solution code would be compiled to this code:

```<code><?php if(1==1): ?><?php echo e('1'); ?><?php endif; ?>
</code>```

Which pretty much explains why this won't make additional spaces.

Body:
what is the similar blade syntax for the following code?

<?php if(...):?>abc<?php else:?>cde<?php endif;?>

the code
@if(...) abc @else .... is no good as it ads a space before and after the "abc" the code @if(...)abc@endif (no spacing before and after html string) generates error ...

Thanks

Body:
Solution

The correct solution for this problem would be following:

@if(1==1){{ '1' }}@endif

This happens often and makes problem with "space sensitive" parts of code like values in <option> tags.

Having the @if(1==1) 1 @endif would be compiled to following which shows empty spaces around the number:

<?php if(1==1): ?> 1 <?php endif; ?>

Solution code would be compiled to this code:

<?php if(1==1): ?><?php echo e('1'); ?><?php endif; ?>

Which pretty much explains why this won't make additional spaces.


问:
Updating versionCode for Android PhoneGap app
I have tried updating the config.xml file to include: versionCode="10002"

I've created a 'platforms/android/release-signing.properties' file and ran:

```<code>phonegap build --release android --versionCode=10002
</code>```

Nothing seems to make the versionCode=10002 stick. How can I fix this?

答:
I had tried it with both the "android-" prepended and without.
As well as with the parameters on separate lines rather than on the same line.

That did not help.

What did end up resolving it for me was creating a new PhoneGap Build app. That was created fine with the new version and I uploaded to the Google Play Store no problem. It seems to be a bug with PhoneGap's inability to update the version number. Too bad.

Body:
I have tried updating the config.xml file to include: versionCode="10002"

I've created a 'platforms/android/release-signing.properties' file and ran:

phonegap build --release android --versionCode=10002

Nothing seems to make the versionCode=10002 stick. How can I fix this?


问:
How Stateful DoFn determines key to partition states
In following documentation, it is noted that stateful DoFn's state is partitioned per key per window. How is this key determined by given DoFn?

For example, if we were to create our own custom CombinerFn, we would need to maintain CombiningState per key. Is this purely determined by the fact that input to DoFn is KV? Ex. Dofn<KV<Key, Value>, Out>

答:
That is correct. The KV value in Beam (along with tuples in the Python SDK) is a special type that is encoded to allow the runner to recognize the key for each element.

So: yes, Beam will perform any key-based operations based on the key in the KV.


问:
How to compare data from two tables using comparison operators stored in a database?
I'm looking for a way to build a script to compare data from two different tables, using comparison operators stored in database.

I achieved to solve by two ways:

using dynamic SQL

using case statements

but I would like to solve using something that not includes dynamic SQL or case statements.

This is my base data table:

```<code>    create table #BaseData
    (
        ID int identity (1,1),
        numR int,
        ALertCode varchar (10),
        numOp     int,
        BaseOrder int,
        Criteri varchar (50),
        Operator varchar (5),
        BaseValue int
    )

    insert into #BaseData (numR, AlertCode, numOp, BaseOrder, Criteri, Operator, BaseValue)
    select
    ROW_NUMBER() over (order by (select null)) numR,    ALertCode,
    ROW_NUMBER() over (partition by ALertCode order by AlertCode )numOp,
    DatosBase.BaseOrder, Criteri,           Operator, DatosBase.ComparisonValue BaseValue
    from
    (             select    'A_1_<1000 ' ALertCode , 1  BaseOrder, 'ES_CV_Basal                 'Criteri,   '='     Operator,    1     ComparisonValue
        union all select    'A_1_<1000 ' ALertCode , 2  BaseOrder, 'Carga_Viral_Basal           '        ,  '='             ,    19
        union all select    'A_1_<1000 ' ALertCode , 3  BaseOrder, 'Dias_CargaViralActual       '        ,  NULL            ,    NULL
        union all select    'A_1_<1000 ' ALertCode , 4  BaseOrder, 'Carga_Viral_VIH_Previa_01   '        ,  NULL            ,    NULL
        union all select    'A_1_<1000 ' ALertCode , 5  BaseOrder, 'ES_CV_Basal_01              '        ,  NULL            ,    NULL
        union all select    'A_1_<1000 ' ALertCode , 6  BaseOrder, 'Carga_Viral_VIH_Previa_02   '        ,  NULL            ,    NULL
        union all select    'A_1_<1000 ' ALertCode , 7  BaseOrder, 'DiasCVPrevia_02             '        ,  NULL            ,    NULL
        union all select    'A_1_<1000 ' ALertCode , 8  BaseOrder, 'Dif_CVe_CVp'                         ,  NULL            ,    NULL
        union all
                  select    'A_2_<1000'  ALertCode , 1  BaseOrder, 'ES_CV_Basal                 '        ,  '='             ,   1
        union all select    'A_2_<1000'  ALertCode , 2  BaseOrder, 'Carga_Viral_VIH             '        ,  '>'             ,   1000
        union all select    'A_2_<1000'  ALertCode , 3  BaseOrder, 'Dias_CargaViralActual       '        ,  NULL            ,   NULL
        union all select    'A_2_<1000'  ALertCode , 4  BaseOrder, 'Carga_Viral_VIH_Previa_01   '        ,  NULL            ,   NULL
        union all select    'A_2_<1000'  ALertCode , 5  BaseOrder, 'TDias_01                    '        ,  NULL            ,   NULL
        union all select    'A_2_<1000'  ALertCode , 6  BaseOrder, 'Carga_Viral_VIH_Previa_02   '        ,  NULL            ,   NULL
        union all select    'A_2_<1000'  ALertCode , 7  BaseOrder, 'TDias_02                    '        ,  NULL            ,   NULL
        union all select    'A_2_<1000'  ALertCode , 8  BaseOrder, 'Dif_CVe_CVp'                         ,  NULL            ,   NULL
        union all
                  select    'A_1000'  ALertCode , 1     BaseOrder, 'ES_CV_Basal                 '        ,  NULL            ,   NULL
        union all select    'A_1000'  ALertCode , 2     BaseOrder, 'Carga_Viral_VIH             '        ,  '>='            ,   1000
        union all select    'A_1000'  ALertCode , 3     BaseOrder, 'Dias_CargaViralActual       '        ,  '>='            ,   168
        union all select    'A_1000'  ALertCode , 4     BaseOrder, 'Carga_Viral_VIH_Previa_01   '        ,  '='             ,   19
        union all select    'A_1000'  ALertCode , 5     BaseOrder, 'TDias_01                    '        ,  '>='            ,   168
        union all select    'A_1000'  ALertCode , 6     BaseOrder, 'Carga_Viral_VIH_Previa_02   '        ,  NULL            ,   NULL
        union all select    'A_1000'  ALertCode , 7     BaseOrder, 'TDias_02                    '        ,  NULL            ,   NULL
        union all select    'A_1000'  ALertCode , 8     BaseOrder, 'Dif_CVe_CVp'                         ,  NULL            ,   NULL
    )BaseData
    order by ALertCode, BaseOrder
</code>```

and this is my comparison data table:

```<code>    create table #ComparisonData
    (
      ID int identity (1,1),
      ComparisonOrder int,
      EvaluationCriteri varchar(50),
      ComparisonValue decimal (10,6)
    )

    insert into #ComparisonData  (ComparisonOrder, EvaluationCriteri, ComparisonValue)
    select ComparisonOrder, EvaluationCriteri, ComparisonValue
    from
    (             select 1  ComparisonOrder,    'ES_CV_Basal'   EvaluationCriteri, 2        ComparisonValue
        union all select 2       ,  'Carga_Viral_VIH'   EvaluationCriteri, 1001     ComparisonValue
        union all select 3       ,  'TDias'             EvaluationCriteri, 169      ComparisonValue
        union all select 4       ,  'Carga_Viral_VIH'   EvaluationCriteri, 19       ComparisonValue
        union all select 5       ,  'TDias'             EvaluationCriteri, 169      ComparisonValue
        union all select 6       ,  'Carga_Viral_VIH'   EvaluationCriteri, 387      ComparisonValue
        union all select 7       ,  'TDias'             EvaluationCriteri, 265      ComparisonValue
        union all select 8       ,  'Dif_CVe_CVp'       EvaluationCriteri, -0.33    ComparisonValue
    )ComparisonData
</code>```

and this is my table to compare data:

```<code>    create table #AlertDetected
    (
        ID int identity (1,1),
        numR int,
        AlertCode   varchar (10),
        numOp       int,
        BaseOrder   int,
        Criteri varchar(50),
        Operator    varchar(5),
        BaseValue   int,
        ComparisonOrder     int,
        EvaluationCriteri varchar (50),
        ComparisonValue decimal(10,6)
    )

    insert into #AlertDetected (numR, AlertCode, numOp, BaseOrder, Criteri, Operator, BaseValue, ComparisonOrder,   EvaluationCriteri, ComparisonValue)
    select  ROW_NUMBER() over (order by (select null)) numR, ALertCode,
            ROW_NUMBER() over (partition by ALertCode order by AlertCode )numOp,
                                                                            BaseOrder, Criteri, Operator, BaseValue, dc.ComparisonOrder,EvaluationCriteri, ComparisonValue
    from #BaseData db
    left join #ComparisonData  dc
    on db.BaseOrder = dc.ComparisonOrder
    where db.BaseValue is not null
</code>```

This is my dynamic SQL solution:

```<code>    select  'select max(AlertResult)AlertResult  from ( ' + stuff(( select 'union all' + Operacion
    from
    (   select   stuff(( select  +  concat (   ' ' , Operacion)
        from
        (
            select numR, AlertCode,   BaseOrder,   concat (iif (numOp = 1 , '  select iif(  ', '  and  ' ),  ComparisonValue  ,  Operator , ' ', BaseValue)Operacion
            from
            ( select numR, AlertCode,   BaseOrder, numOp , BaseValue ,  Operator ,  case when numOp<> 8 then floor( ComparisonValue ) else  cast ( ComparisonValue as float ) end ComparisonValue --
              from #AlertDetected
            )t
        )x
        where x.AlertCode =  isc.AlertCode FOR XML PATH(''), TYPE ).value('.[1]', 'varchar(max)'), 1, 1, '')  + '  ,  '+''''+AlertCode+''''+ ', '+ ''''+'0'+ '''' + ' )   AlertResult   '   as Operacion
        from #AlertDetected  isc group by AlertCode
    )X
    FOR XML PATH(''), TYPE ).value('.[1]', 'varchar(max)'), 1, 9, '')  + ' ) Datos'as CamposInforme
</code>```

And this is my case statments solution:

```<code>select  iif (sum(Result)  = row_count , AlertCode, ' ')AlertDetected
from
( select  numR, AlertCode, numOp, BaseOrder, Criteri, ComparisonValue, Operator, BaseValue,
                    case    when Operator ='=' then iif (ComparisonValue = BaseValue, 1,0)
                            when Operator ='<' then iif (ComparisonValue < BaseValue, 1,0)
                            when Operator ='>' then iif (ComparisonValue > BaseValue, 1,0)
                            when Operator ='>=' then iif (ComparisonValue >= BaseValue, 1,0)
                            when Operator ='<=' then iif (ComparisonValue <= BaseValue, 1,0)  end Result , row_count
    from
    (   select  numR, a.AlertCode, Criteri,  BaseOrder, numOp , BaseValue ,  Operator ,
                case when numOp<> 8 then floor( ComparisonValue ) else  cast ( ComparisonValue as float ) end ComparisonValue , c.row_count
        from #AlertDetected  a
        inner join
    (       select AlertCode, COUNT(*) AS row_count
            FROM dbo.#AlertDetected
            group by  AlertCode
        )c on a.AlertCode = c.AlertCode
    )d
)d  group by AlertCode, row_count
</code>```

I need to compare the data between the ComparisonValue and BaseValue columns based on the comparison operators, and I must obtain the alert code that complies with exactly each one of the comparisons between ComparisonValue and BaseValue.

There will be some way to achieve it without using dynamic SQL or case statement ?

答:
You are using a Saw where you need a Hammer.
SQL is designed to very effectively persist data. It is not designed for this.
You should learn C# or Java. This could be done very easily in a proper language.

However, if you must use SQL then you should create a proc for each comparison. The procs should take an input of the two values you are comparing. That way, all the logic for doing that one comparison is contained in its own little capsule.

Call the proc you want dynamically by selecting the proc Name you will place in the table with the comparison operators.

If you want to do ">" , then the "GreaterThan" proc will get called as you pass in values to compare.

If you want to make this more efficient, create table types for kinds of things you will compare and then pass in a whole list of items at a time.

Body:
I'm looking for a way to build a script to compare data from two different tables, using comparison operators stored in database.

I achieved to solve by two ways:

using dynamic SQL

using case statements

but I would like to solve using something that not includes dynamic SQL or case statements.

This is my base data table:

    create table #BaseData
    (
        ID int identity (1,1),
        numR int,
        ALertCode varchar (10),
        numOp     int,
        BaseOrder int,
        Criteri varchar (50),
        Operator varchar (5),
        BaseValue int
    )

    insert into #BaseData (numR, AlertCode, numOp, BaseOrder, Criteri, Operator, BaseValue)
    select
    ROW_NUMBER() over (order by (select null)) numR,    ALertCode,
    ROW_NUMBER() over (partition by ALertCode order by AlertCode )numOp,
    DatosBase.BaseOrder, Criteri,           Operator, DatosBase.ComparisonValue BaseValue
    from
    (             select    'A_1_<1000 ' ALertCode , 1  BaseOrder, 'ES_CV_Basal                 'Criteri,   '='     Operator,    1     ComparisonValue
        union all select    'A_1_<1000 ' ALertCode , 2  BaseOrder, 'Carga_Viral_Basal           '        ,  '='             ,    19
        union all select    'A_1_<1000 ' ALertCode , 3  BaseOrder, 'Dias_CargaViralActual       '        ,  NULL            ,    NULL
        union all select    'A_1_<1000 ' ALertCode , 4  BaseOrder, 'Carga_Viral_VIH_Previa_01   '        ,  NULL            ,    NULL
        union all select    'A_1_<1000 ' ALertCode , 5  BaseOrder, 'ES_CV_Basal_01              '        ,  NULL            ,    NULL
        union all select    'A_1_<1000 ' ALertCode , 6  BaseOrder, 'Carga_Viral_VIH_Previa_02   '        ,  NULL            ,    NULL
        union all select    'A_1_<1000 ' ALertCode , 7  BaseOrder, 'DiasCVPrevia_02             '        ,  NULL            ,    NULL
        union all select    'A_1_<1000 ' ALertCode , 8  BaseOrder, 'Dif_CVe_CVp'                         ,  NULL            ,    NULL
        union all
                  select    'A_2_<1000'  ALertCode , 1  BaseOrder, 'ES_CV_Basal                 '        ,  '='             ,   1
        union all select    'A_2_<1000'  ALertCode , 2  BaseOrder, 'Carga_Viral_VIH             '        ,  '>'             ,   1000
        union all select    'A_2_<1000'  ALertCode , 3  BaseOrder, 'Dias_CargaViralActual       '        ,  NULL            ,   NULL
        union all select    'A_2_<1000'  ALertCode , 4  BaseOrder, 'Carga_Viral_VIH_Previa_01   '        ,  NULL            ,   NULL
        union all select    'A_2_<1000'  ALertCode , 5  BaseOrder, 'TDias_01                    '        ,  NULL            ,   NULL
        union all select    'A_2_<1000'  ALertCode , 6  BaseOrder, 'Carga_Viral_VIH_Previa_02   '        ,  NULL            ,   NULL
        union all select    'A_2_<1000'  ALertCode , 7  BaseOrder, 'TDias_02                    '        ,  NULL            ,   NULL
        union all select    'A_2_<1000'  ALertCode , 8  BaseOrder, 'Dif_CVe_CVp'                         ,  NULL            ,   NULL
        union all
                  select    'A_1000'  ALertCode , 1     BaseOrder, 'ES_CV_Basal                 '        ,  NULL            ,   NULL
        union all select    'A_1000'  ALertCode , 2     BaseOrder, 'Carga_Viral_VIH             '        ,  '>='            ,   1000
        union all select    'A_1000'  ALertCode , 3     BaseOrder, 'Dias_CargaViralActual       '        ,  '>='            ,   168
        union all select    'A_1000'  ALertCode , 4     BaseOrder, 'Carga_Viral_VIH_Previa_01   '        ,  '='             ,   19
        union all select    'A_1000'  ALertCode , 5     BaseOrder, 'TDias_01                    '        ,  '>='            ,   168
        union all select    'A_1000'  ALertCode , 6     BaseOrder, 'Carga_Viral_VIH_Previa_02   '        ,  NULL            ,   NULL
        union all select    'A_1000'  ALertCode , 7     BaseOrder, 'TDias_02                    '        ,  NULL            ,   NULL
        union all select    'A_1000'  ALertCode , 8     BaseOrder, 'Dif_CVe_CVp'                         ,  NULL            ,   NULL
    )BaseData
    order by ALertCode, BaseOrder

and this is my comparison data table:

    create table #ComparisonData
    (
      ID int identity (1,1),
      ComparisonOrder int,
      EvaluationCriteri varchar(50),
      ComparisonValue decimal (10,6)
    )

    insert into #ComparisonData  (ComparisonOrder, EvaluationCriteri, ComparisonValue)
    select ComparisonOrder, EvaluationCriteri, ComparisonValue
    from
    (             select 1  ComparisonOrder,    'ES_CV_Basal'   EvaluationCriteri, 2        ComparisonValue
        union all select 2       ,  'Carga_Viral_VIH'   EvaluationCriteri, 1001     ComparisonValue
        union all select 3       ,  'TDias'             EvaluationCriteri, 169      ComparisonValue
        union all select 4       ,  'Carga_Viral_VIH'   EvaluationCriteri, 19       ComparisonValue
        union all select 5       ,  'TDias'             EvaluationCriteri, 169      ComparisonValue
        union all select 6       ,  'Carga_Viral_VIH'   EvaluationCriteri, 387      ComparisonValue
        union all select 7       ,  'TDias'             EvaluationCriteri, 265      ComparisonValue
        union all select 8       ,  'Dif_CVe_CVp'       EvaluationCriteri, -0.33    ComparisonValue
    )ComparisonData

and this is my table to compare data:

    create table #AlertDetected
    (
        ID int identity (1,1),
        numR int,
        AlertCode   varchar (10),
        numOp       int,
        BaseOrder   int,
        Criteri varchar(50),
        Operator    varchar(5),
        BaseValue   int,
        ComparisonOrder     int,
        EvaluationCriteri varchar (50),
        ComparisonValue decimal(10,6)
    )

    insert into #AlertDetected (numR, AlertCode, numOp, BaseOrder, Criteri, Operator, BaseValue, ComparisonOrder,   EvaluationCriteri, ComparisonValue)
    select  ROW_NUMBER() over (order by (select null)) numR, ALertCode,
            ROW_NUMBER() over (partition by ALertCode order by AlertCode )numOp,
                                                                            BaseOrder, Criteri, Operator, BaseValue, dc.ComparisonOrder,EvaluationCriteri, ComparisonValue
    from #BaseData db
    left join #ComparisonData  dc
    on db.BaseOrder = dc.ComparisonOrder
    where db.BaseValue is not null

This is my dynamic SQL solution:

    select  'select max(AlertResult)AlertResult  from ( ' + stuff(( select 'union all' + Operacion
    from
    (   select   stuff(( select  +  concat (   ' ' , Operacion)
        from
        (
            select numR, AlertCode,   BaseOrder,   concat (iif (numOp = 1 , '  select iif(  ', '  and  ' ),  ComparisonValue  ,  Operator , ' ', BaseValue)Operacion
            from
            ( select numR, AlertCode,   BaseOrder, numOp , BaseValue ,  Operator ,  case when numOp<> 8 then floor( ComparisonValue ) else  cast ( ComparisonValue as float ) end ComparisonValue --
              from #AlertDetected
            )t
        )x
        where x.AlertCode =  isc.AlertCode FOR XML PATH(''), TYPE ).value('.[1]', 'varchar(max)'), 1, 1, '')  + '  ,  '+''''+AlertCode+''''+ ', '+ ''''+'0'+ '''' + ' )   AlertResult   '   as Operacion
        from #AlertDetected  isc group by AlertCode
    )X
    FOR XML PATH(''), TYPE ).value('.[1]', 'varchar(max)'), 1, 9, '')  + ' ) Datos'as CamposInforme

And this is my case statments solution:

select  iif (sum(Result)  = row_count , AlertCode, ' ')AlertDetected
from
( select  numR, AlertCode, numOp, BaseOrder, Criteri, ComparisonValue, Operator, BaseValue,
                    case    when Operator ='=' then iif (ComparisonValue = BaseValue, 1,0)
                            when Operator ='<' then iif (ComparisonValue < BaseValue, 1,0)
                            when Operator ='>' then iif (ComparisonValue > BaseValue, 1,0)
                            when Operator ='>=' then iif (ComparisonValue >= BaseValue, 1,0)
                            when Operator ='<=' then iif (ComparisonValue <= BaseValue, 1,0)  end Result , row_count
    from
    (   select  numR, a.AlertCode, Criteri,  BaseOrder, numOp , BaseValue ,  Operator ,
                case when numOp<> 8 then floor( ComparisonValue ) else  cast ( ComparisonValue as float ) end ComparisonValue , c.row_count
        from #AlertDetected  a
        inner join
    (       select AlertCode, COUNT(*) AS row_count
            FROM dbo.#AlertDetected
            group by  AlertCode
        )c on a.AlertCode = c.AlertCode
    )d
)d  group by AlertCode, row_count

I need to compare the data between the ComparisonValue and BaseValue columns based on the comparison operators, and I must obtain the alert code that complies with exactly each one of the comparisons between ComparisonValue and BaseValue.

There will be some way to achieve it without using dynamic SQL or case statement ?


问:
Is there a way to paste display_errors code in another file than php.ini
Hi I was trying to comment on this for advice

Wordpress - The Jetpack server could not communicate with your site’s XML-RPC URL

But It was suggested I ask a new question.
So here goes:

Is there any way to paste the code you suggested in the .htaccess file?
Or in another php file?

Because I can't find the php.ini file anywhere, tried to look everywhere.
(Yes, I searched in SO and google and youtube for answers, and tried it all)

So is there any way to edit the error_reporting somewehere else?

This is what I want to do to help with the connection between jetpack and website as delboy1978uk suggests.

set error_reporting to -1, turn display_errors off, and set a custom error_log. Then in the terminal, type tail -f /path/to/error_log

Thanks in advance for any advice you could give.
Reshma

答:
Okay, so the statement about something being a temporary measure got me thinking.
I already entered the following code to the www/.htaccess file to whitelist jetpack:

```<code><Files xmlrpc.php>
Order Allow,deny
Deny from all
Allow from 192.0.78.24
Allow from 192.0.78.25
Satisfy all
</Files>
</code>```

Now I copied it to the cms .htaccess file as well.
This solved the connection problem!

Of course now the slider on my website stopped working:(
So I deleted the code from the cms .htaccess file but left it in the www.htaccess file and I not only got my slider back up but the jetpack connection to my website did not get lost.
I tried to disconnect and connect again, and the connection was established again.
The jetpack debug page gives no errors anymore.

Still, there's nothing on the jetpacks dashboard page when I want to access it from my websites backend. I can only configure settings from the wordpress account.
But I will contact jetpack support for this.

Thank you for all your help.
Reshma

Body:
Okay, so the statement about something being a temporary measure got me thinking.
I already entered the following code to the www/.htaccess file to whitelist jetpack:

<Files xmlrpc.php>
Order Allow,deny
Deny from all
Allow from 192.0.78.24
Allow from 192.0.78.25
Satisfy all
</Files>

Now I copied it to the cms .htaccess file as well.
This solved the connection problem!

Of course now the slider on my website stopped working:(
So I deleted the code from the cms .htaccess file but left it in the www.htaccess file and I not only got my slider back up but the jetpack connection to my website did not get lost.
I tried to disconnect and connect again, and the connection was established again.
The jetpack debug page gives no errors anymore.

Still, there's nothing on the jetpacks dashboard page when I want to access it from my websites backend. I can only configure settings from the wordpress account.
But I will contact jetpack support for this.

Thank you for all your help.
Reshma


问:
Angular CLI 6 Custom Webpack SCSS loader
I am trying to write a custom webpack module to override or extend the current SCSS build in angular 6 with cli 6, with the intention of being able to pass in a 'brand' and  match it to any overrides e.g "somemodule/'brand'/filename.override.scss" and replace the file in parent folder "somemodule/filename.scss" but I am making no progress.

Set up:
@angular/cli": "6.2.2", with
@angular-builders/custom-webpack": "^2.4.1"

I have updated my projects build to reflect that I am using custom webpack, and the location of of override/extention

```<code>     "build": {
      "builder": "@angular-builders/custom-webpack:browser",
      "options": {
        "customWebpackConfig": {
          "path": "./extra-webpack.config.js"
        },
</code>```

My extra-webpack.config.js looks like this, just a basic hello world style I have seen over many sites

```<code>module.exports = {
    module:{
        rules: [{
            test: /\.scss$/,
            use: [{
                loader: "style-loader"
            }, {
                loader: "css-loader"
            }, {
                loader: "sass-loader",
                options: {
                    includePaths: ["src"]
                }
            }]
        }]
    }
};
</code>```

however running my build with this

```<code>ng run websitename:build
</code>```

throws this error

```<code>    Module build failed (from ./node_modules/sass-
</code>```

loader/lib/loader.js):

```<code>^
  Invalid CSS after "": expected 1 selector or at-
 rule, was "var content = requi"
</code>```

From my understand this can be caused when trying to redefine the scss rule, however I can not see any other references to this rule to remove. I have also attempted some methods for completely override the old rule but no luck.

Solutions and guides i have been mainly focused on
https://dev.to/meltedspark/customizing-angular-cli-6-buildan-alternative-to-ng-eject-1oc4
https://medium.com/a-beginners-guide-for-webpack-2/webpack-loaders-css-and-sass-2cc0079b5b3a
https://www.npmjs.com/package/@angular-builders/custom-webpack#custom-webpack-config-object
https://github.com/webpack-contrib/sass-loader/blob/master/test/bootstrapSass/webpack.config.js
https://github.com/webpack-contrib/sass-loader/issues/536
https://github.com/meltedspark/angular-builders

答:
I had the same problem, I have tried mergeStrategies but didn't work.I have changed my custom webpack into a function, that solved the issue, I was able extend sass options.</p>

```<code>module.exports = function(config) {
    const rules = config.module.rules || [];
    rules.forEach(rule => {
        if (String(rule.test) === String(/\.scss$|\.sass$/)) {
        const loaders = rule.use;
        const transformedLoaders = loaders.map(l => {
            if (l.loader === 'sass-loader') {
                // here you can override options or replace or add.
            }
            return l;
        });
        rule.use = transformedLoaders;
        }
    });
    return config;
};

</code>```

Body:
I am trying to write a custom webpack module to override or extend the current SCSS build in angular 6 with cli 6, with the intention of being able to pass in a 'brand' and  match it to any overrides e.g "somemodule/'brand'/filename.override.scss" and replace the file in parent folder "somemodule/filename.scss" but I am making no progress.

Set up:
@angular/cli": "6.2.2", with
@angular-builders/custom-webpack": "^2.4.1"

I have updated my projects build to reflect that I am using custom webpack, and the location of of override/extention

     "build": {
      "builder": "@angular-builders/custom-webpack:browser",
      "options": {
        "customWebpackConfig": {
          "path": "./extra-webpack.config.js"
        },

My extra-webpack.config.js looks like this, just a basic hello world style I have seen over many sites

module.exports = {
    module:{
        rules: [{
            test: /\.scss$/,
            use: [{
                loader: "style-loader"
            }, {
                loader: "css-loader"
            }, {
                loader: "sass-loader",
                options: {
                    includePaths: ["src"]
                }
            }]
        }]
    }
};

however running my build with this

ng run websitename:build

throws this error

    Module build failed (from ./node_modules/sass-

loader/lib/loader.js):

^
  Invalid CSS after "": expected 1 selector or at-
 rule, was "var content = requi"

From my understand this can be caused when trying to redefine the scss rule, however I can not see any other references to this rule to remove. I have also attempted some methods for completely override the old rule but no luck.

Solutions and guides i have been mainly focused on
https://dev.to/meltedspark/customizing-angular-cli-6-buildan-alternative-to-ng-eject-1oc4
https://medium.com/a-beginners-guide-for-webpack-2/webpack-loaders-css-and-sass-2cc0079b5b3a
https://www.npmjs.com/package/@angular-builders/custom-webpack#custom-webpack-config-object
https://github.com/webpack-contrib/sass-loader/blob/master/test/bootstrapSass/webpack.config.js
https://github.com/webpack-contrib/sass-loader/issues/536
https://github.com/meltedspark/angular-builders

Body:
I had the same problem, I have tried mergeStrategies but didn't work.I have changed my custom webpack into a function, that solved the issue, I was able extend sass options.

module.exports = function(config) {
    const rules = config.module.rules || [];
    rules.forEach(rule => {
        if (String(rule.test) === String(/\.scss$|\.sass$/)) {
        const loaders = rule.use;
        const transformedLoaders = loaders.map(l => {
            if (l.loader === 'sass-loader') {
                // here you can override options or replace or add.
            }
            return l;
        });
        rule.use = transformedLoaders;
        }
    });
    return config;
};


问:
Is there a way to put calculated column in ALL()?
I'm trying to remove filters from a calculated column with ALL(), and the measure seems to ignore it

"Class" is a calculated column.
I want to add measure always showing 100 (the grand total)
There are outer filters on the table so I don't want to use ALL(TABLE)
However, CALCULATE(SUM([Total Sales]), ALL(Product, Class)) doesn't work.

答:
You can use the ALL() function on a list of columns like this:

```<code>CALCULATE ( SUM ( Table1[Sales] ), ALL ( Table1[Product], Table1[Class] ) )
</code>```

This should work fine even if Class is a calculated column.

Body:
You can use the ALL() function on a list of columns like this:

CALCULATE ( SUM ( Table1[Sales] ), ALL ( Table1[Product], Table1[Class] ) )

This should work fine even if Class is a calculated column.


问:
How do I add more data to the same user without updating or creating a new row?
Let's say in the database I have the following table:

Table - workers

With the following fields

name

origin

destination

date

worker_id (PK)(AI)

What I want to do here is have let's say the first user with more than 1 record on  origin,destinations and date filled out.

So essentially, say I have user "Mike" and I want to insert several "origin" and "destination" and "date" information without always repeating  his name on the table that is going to display the data.

What I need here is for a single "worker_id" (let's say worker_id is 1) to have more than 1 single information on each field.

I've tried the following query (only using the origin field for testing purposes):

"INSERT INTO workers(origin) SELECT FROM workers WHERE worker_id ='$worker_id'";

What I wanted to end up with would be something like:

Worker ID - 1 Origin - Brazil

Worker ID - 1 Origin - Japan

Worker ID - 1 Origin - Australia

If it's just my logical thinking that is wrong, then I'd highly appreciate if someone could point me in the right way. For one ID, have several information for a single field.

答:
The most easier solution would be normalising the database schema.
In your case that would mean following tables (I assumed the origin and destination is some sort of travel log data).

user

```<code>id
name
</code>```

travel_log

```<code>id
worker_id
origin
destination
date
</code>```

And then you would join them to get your desired (mentioned) data:

SELECT u.id, u.name, t.origin, t.destination, t.date
FROM user u
JOIN travel_log t ON u.id = t.worker_id
```

Hope that helps.

Body:
The most easier solution would be normalising the database schema.
In your case that would mean following tables (I assumed the origin and destination is some sort of travel log data).

user

id
name

travel_log

id
worker_id
origin
destination
date

And then you would join them to get your desired (mentioned) data:

SELECT u.id, u.name, t.origin, t.destination, t.date
FROM user u
JOIN travel_log t ON u.id = t.worker_id

Hope that helps.


问:
Firebase messaging failing on flutter after some time
I'm having an issue with FCM on flutter. I have implemented messaging from my  server so I'm storing my phone token for each user.

The thing is that when a user logs in for the very first time everything works properly, messages are being sent and user gets notified.

If I do not use the app during the weekend, on Monday I try to send a message by doing some actions on my app but messages are not being sent. I can see my token stored properly in my database.

I'm using firebase_messaging 2.1.0 for flutter.

This is how I get my token

```<code> _fireBaseMessaging.getToken().then((token){
  _myPhoneToken = token;
});
</code>```

1-I know token may change when:

App deletes Instance ID

App is restored on a new device

User uninstalls/reinstall the app

User clears app data

But none of this happens.

Any advice on how to handle this scenario? thanks in advance.

UPDATE

答:
Some networks/router/mobile can cut the connection between firebase library and firebase server due to inactivity (5min without message). This cut may be detected by the library up to 30min (FCM heatbeat interval).

These are some links discussing this issue:

https://github.com/firebase/quickstart-android/issues/307

Android: Delay in Receiving message in FCM(onMessageReceived)

I contacted firebase support but they told that since the issue is caused by external part they cannot fix it (I suggest decreasing heartbeat interval ...)

I fixed it in android using an interval job which apply these instructions:

context.sendBroadcast(new Intent("com.google.android.intent.action.GTALK_HEARTBEAT"));
context.sendBroadcast(new Intent("com.google.android.intent.action.MCS_HEARTBEAT"));

You may write this specific code for Android side and should find something similar for ios side.

Body:
I'm having an issue with FCM on flutter. I have implemented messaging from my  server so I'm storing my phone token for each user.

The thing is that when a user logs in for the very first time everything works properly, messages are being sent and user gets notified.

If I do not use the app during the weekend, on Monday I try to send a message by doing some actions on my app but messages are not being sent. I can see my token stored properly in my database.

I'm using firebase_messaging 2.1.0 for flutter.

This is how I get my token

 _fireBaseMessaging.getToken().then((token){
  _myPhoneToken = token;
});

1-I know token may change when:

App deletes Instance ID

App is restored on a new device

User uninstalls/reinstall the app

User clears app data

But none of this happens.

Any advice on how to handle this scenario? thanks in advance.

UPDATE


问:
The state information is invalid for this page and might be corrupted. (Only in IE)
Can anybody help me out with this exception. I have tried couple of fixes but nothing worked. I am getting this exception only in IE(7, 8 and 9).

When i load the page first time, it brings up a dropdown. where i select a specific vendor and it makes a page post back and returns the required information. If i change the vendor it will still load the information. When i load a control onto page using $.ajax request dynamically and than go back and change the dropdown selection(select a different vendor), it craps out and gave me the following exception. Again it only happens in the IE.

```<code>The state information is invalid for this page and might be corrupted.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: The state information is invalid for this page and might be corrupted.

Source Error:

[No relevant source lines]

Source File: c:\Users\tmalik\AppData\Local\Temp\Temporary ASP.NET Files\root\6691c708\751e6443\App_Web_a3kdfsht.2.cs    Line: 0

Stack Trace:

[FormatException: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters. ]
   System.Convert.FromBase64String(String s) +0
   System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) +77
   System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState) +4
   System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String serializedState) +37
   System.Web.UI.HiddenFieldPageStatePersister.Load() +147

[ViewStateException: Invalid viewstate.
    Client IP: 127.0.0.1
    Port:
    Referer: http://localhost:57289/vendor.aspx
    Path: /vendor.aspx
    User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; MDDR)
    ViewState: 2D1IMRanPXfVARbRp1ooiwD71WHybNzxSNLbbA0G3MxKeo7m52dHWLBPGdnMH5JthTnPVt7UES/PVx39dfZYHbr0/DL7J58mvA2I4wRUSdDShVxvZqC7ZPZWcatowpZ7VYaD9PFKW7OkgppCwmePFuYnpU8kWDT5TvSLqN50Flrqpv0zCM9YoCKemfesa68rqBkkSTijcxnxdDCgvzSl72giI4ZhwK92wD22Ma6scW4PFjRZeTsKoowJq+JqJGuBMEepwKguFUy4dX86UIULnJ7NQsgZW1aQvpZdnfSRCSYrWhFWPhKTPsS622eaQYShsxddPs/mfEB26f54WS+iBYuk3mWm8jr6sWvsOIRtwH8b3E/5UujbgAxTNVg8BhzpSFvmE4KwGKo0tKuuqOFtP0pjpaAI7fV3EQ1M7BVQSAVrtBevRFJ0PlCPrU2aQms2LVeE5POqTJGtY+74xWkdCtLzT04Ug4R+SMBRElQBqX/5A54OHj2ghYjJ/3tgg4ToGUX2xrQ/c70lrphP+kabGVM2Op4DFjZAaOZj/CDVUurH2BYXKuJdUvzbf2zHngoOnqZGqrw3n6V6HGcnHNKxfuGQ20MPdxJYCbYHGiRqixzV1NxJoHFHbYCVx3IlrqF0W44AFKm2gzzk3V8zu9lUjyFNvUNBMjNaZeekLtcWpszhKrm8WhVnWQAk1CXxKJqyK0RC3...]

[HttpException (0x80004005): The state information is invalid for this page and might be corrupted.]
   System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) +235
   System.Web.UI.ViewStateException.ThrowViewStateError(Exception inner, String persistedState) +14
   System.Web.UI.HiddenFieldPageStatePersister.Load() +251
   System.Web.UI.Page.LoadPageStateFromPersistenceMedium() +106
   System.Web.UI.Page.LoadAllState() +43
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +8431
   System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +253
   System.Web.UI.Page.ProcessRequest() +78
   System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) +21
   System.Web.UI.Page.ProcessRequest(HttpContext context) +49
   ASP.vendor_aspx.ProcessRequest(HttpContext context) in c:\Users\tmalik\AppData\Local\Temp\Temporary ASP.NET Files\root\6691c708\751e6443\App_Web_a3kdfsht.2.cs:0
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +100
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
</code>```

答:
Empty the div you loaded "on hiddden". I found that emptying the div or setting it back to the original text (mine was a loading message) both worked.</p>

```<code><a class="popmodal" href="YOUR HREF HERE">View History</a>

    $('.popmodal').on('click', function (e) {
                e.preventDefault();
                $('#modalViewBenefitsHistory').modal('show').find('.modal-content').load($(this).attr('href'));
            });

    $('#modalViewBenefitsHistory').on('hidden.bs.modal', function (e) {
                $('.modal-content').empty();
            })

--OR

$('#modalViewBenefitsHistory').on('hidden.bs.modal', function (e) {
            $('.modal-content').text(" Loading your benefits history...please wait a moment.");
        })

<div id="modalViewBenefitsHistory" aria-hidden="true" class="modal fade">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
             Loading your benefits history...please wait a moment.
        </div>
    </div>
</div>
</code>```

Body:
Can anybody help me out with this exception. I have tried couple of fixes but nothing worked. I am getting this exception only in IE(7, 8 and 9).

When i load the page first time, it brings up a dropdown. where i select a specific vendor and it makes a page post back and returns the required information. If i change the vendor it will still load the information. When i load a control onto page using $.ajax request dynamically and than go back and change the dropdown selection(select a different vendor), it craps out and gave me the following exception. Again it only happens in the IE.

The state information is invalid for this page and might be corrupted.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: The state information is invalid for this page and might be corrupted.

Source Error:

[No relevant source lines]

Source File: c:\Users\tmalik\AppData\Local\Temp\Temporary ASP.NET Files\root\6691c708\751e6443\App_Web_a3kdfsht.2.cs    Line: 0

Stack Trace:

[FormatException: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters. ]
   System.Convert.FromBase64String(String s) +0
   System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) +77
   System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState) +4
   System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String serializedState) +37
   System.Web.UI.HiddenFieldPageStatePersister.Load() +147

[ViewStateException: Invalid viewstate.
    Client IP: 127.0.0.1
    Port:
    Referer: http://localhost:57289/vendor.aspx
    Path: /vendor.aspx
    User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; MDDR)
    ViewState: 2D1IMRanPXfVARbRp1ooiwD71WHybNzxSNLbbA0G3MxKeo7m52dHWLBPGdnMH5JthTnPVt7UES/PVx39dfZYHbr0/DL7J58mvA2I4wRUSdDShVxvZqC7ZPZWcatowpZ7VYaD9PFKW7OkgppCwmePFuYnpU8kWDT5TvSLqN50Flrqpv0zCM9YoCKemfesa68rqBkkSTijcxnxdDCgvzSl72giI4ZhwK92wD22Ma6scW4PFjRZeTsKoowJq+JqJGuBMEepwKguFUy4dX86UIULnJ7NQsgZW1aQvpZdnfSRCSYrWhFWPhKTPsS622eaQYShsxddPs/mfEB26f54WS+iBYuk3mWm8jr6sWvsOIRtwH8b3E/5UujbgAxTNVg8BhzpSFvmE4KwGKo0tKuuqOFtP0pjpaAI7fV3EQ1M7BVQSAVrtBevRFJ0PlCPrU2aQms2LVeE5POqTJGtY+74xWkdCtLzT04Ug4R+SMBRElQBqX/5A54OHj2ghYjJ/3tgg4ToGUX2xrQ/c70lrphP+kabGVM2Op4DFjZAaOZj/CDVUurH2BYXKuJdUvzbf2zHngoOnqZGqrw3n6V6HGcnHNKxfuGQ20MPdxJYCbYHGiRqixzV1NxJoHFHbYCVx3IlrqF0W44AFKm2gzzk3V8zu9lUjyFNvUNBMjNaZeekLtcWpszhKrm8WhVnWQAk1CXxKJqyK0RC3...]

[HttpException (0x80004005): The state information is invalid for this page and might be corrupted.]
   System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) +235
   System.Web.UI.ViewStateException.ThrowViewStateError(Exception inner, String persistedState) +14
   System.Web.UI.HiddenFieldPageStatePersister.Load() +251
   System.Web.UI.Page.LoadPageStateFromPersistenceMedium() +106
   System.Web.UI.Page.LoadAllState() +43
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +8431
   System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +253
   System.Web.UI.Page.ProcessRequest() +78
   System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) +21
   System.Web.UI.Page.ProcessRequest(HttpContext context) +49
   ASP.vendor_aspx.ProcessRequest(HttpContext context) in c:\Users\tmalik\AppData\Local\Temp\Temporary ASP.NET Files\root\6691c708\751e6443\App_Web_a3kdfsht.2.cs:0
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +100
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75

Body:
Empty the div you loaded "on hiddden". I found that emptying the div or setting it back to the original text (mine was a loading message) both worked.

<a class="popmodal" href="YOUR HREF HERE">View History</a>

    $('.popmodal').on('click', function (e) {
                e.preventDefault();
                $('#modalViewBenefitsHistory').modal('show').find('.modal-content').load($(this).attr('href'));
            });

    $('#modalViewBenefitsHistory').on('hidden.bs.modal', function (e) {
                $('.modal-content').empty();
            })

--OR

$('#modalViewBenefitsHistory').on('hidden.bs.modal', function (e) {
            $('.modal-content').text("&nbsp;Loading your benefits history...please wait a moment.");
        })

<div id="modalViewBenefitsHistory" aria-hidden="true" class="modal fade">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            &nbsp;Loading your benefits history...please wait a moment.
        </div>
    </div>
</div>


问:
Compare the content of two csv files in java
I am trying to compare the content of two csv files. I have the csv file test1.csv and test2.csv. The content from both should be the same.. if not , then I want to transfer the difference into a .txt file. If every thing is equal, everything is correct.

I just created two test csv files with columns and rows with content

The first column is a primary key of the respective table. I want to compare it by the identificator

```<code>test1.csv
1,Max,New York
2,David,Jersey
</code>```

```<code>test2.csv
1,Max,California
2,David,Jersey
</code>```

The Output here in the .txt should be the row "1,Max,New York"

I just have no code. And I am happy about every adivce and hint I can get. Thank you in advance.

答:
If you have record identifier at the front. In that case you need to sort the one or both files if they are not already sorted and start reading line by line from file one and searching equal Id in the second file. There are various strategies for optimization here sorting being the most generic. Since the second one is sorted esentialy the search can be very fast if you use an index.

An example naive solution that will work with small to medium files would be to read the second file in memory and arrange it in a TreeMap(this will implicitly sort it) where the key is the ID and the value is the line.

Then you strat reading the source file line by line and test against the treemap if the line is equal or not. If not you decide what to do with the two lines.

Body:
I am trying to compare the content of two csv files. I have the csv file test1.csv and test2.csv. The content from both should be the same.. if not , then I want to transfer the difference into a .txt file. If every thing is equal, everything is correct.

I just created two test csv files with columns and rows with content

The first column is a primary key of the respective table. I want to compare it by the identificator

test1.csv
1,Max,New York
2,David,Jersey

test2.csv
1,Max,California
2,David,Jersey

The Output here in the .txt should be the row "1,Max,New York"

I just have no code. And I am happy about every adivce and hint I can get. Thank you in advance.


问:
Tweepy: tweepy.error.tweeperror 'code' 215 'message' 'bad authentication data.'
I'm unsure what is going wrong in here. The following code was working until 2 days ago. I'm using tweepy version number 3.6.0 on python3 in jupyter notebook. Now, when I execute the code given below, I keep getting the error, TweepError: [{'code': 215, 'message': 'Bad Authentication data.'}]. What am I doing wrong? I've already looked at similar posts 1, 2,3,4,5 and 6 but no solution. Note, I have also regenerated the keys, still the error persists.

The code is;

```<code>import tweepy
ckey = 'xxx'
csecret = 'xxx'
atoken = 'xxx'
asecret = 'xxx'

# OAuth process, using the keys and tokens
auth = tweepy.OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
# Creation of the actual interface, using authentication
api = tweepy.API(auth)
# collect tweets on #MRT
for tweet in tweepy.Cursor(api.search,q="MRT",count=100,
                           lang="en",rpp=100,
                           since="2017-04-03").items():
  print (tweet.created_at, tweet.text)
</code>```

On executing this code returns the following errors,

```<code>---------------------------------------------------------------------------
TweepError                                Traceback (most recent call last)
<ipython-input-11-b3e4ffb2d94f> in <module>()
      2 for tweet in tweepy.Cursor(api.search,q="MRT",count=100,
      3                            lang="en",rpp=100,
----> 4                            since="2017-04-03").items():
      5     print (tweet.created_at, tweet.text)

~\Miniconda3\lib\site-packages\tweepy\cursor.py in __next__(self)
     47
     48     def __next__(self):
---> 49         return self.next()
     50
     51     def next(self):

~\Miniconda3\lib\site-packages\tweepy\cursor.py in next(self)
    195         if self.current_page is None or self.page_index == len(self.current_page) - 1:
    196             # Reached end of current page, get the next page...
--> 197             self.current_page = self.page_iterator.next()
    198             self.page_index = -1
    199         self.page_index += 1

~\Miniconda3\lib\site-packages\tweepy\cursor.py in next(self)
    106
    107         if self.index >= len(self.results) - 1:
--> 108             data = self.method(max_id=self.max_id, parser=RawParser(), *self.args, **self.kargs)
    109
    110             if hasattr(self.method, '__self__'):

~\Miniconda3\lib\site-packages\tweepy\binder.py in _call(*args, **kwargs)
    248             return method
    249         else:
--> 250             return method.execute()
    251
    252     # Set pagination mode

~\Miniconda3\lib\site-packages\tweepy\binder.py in execute(self)
    232                     raise RateLimitError(error_msg, resp)
    233                 else:
--> 234                     raise TweepError(error_msg, resp, api_code=api_error_code)
    235
    236             # Parse the response payload

TweepError: Twitter error response: status code = 400
</code>```

Any advice will be helpful.

答:
I solved the problem using double quotes, I see that you used single quotes

CONSUMER_KEY = "xxx";

Body:
I'm unsure what is going wrong in here. The following code was working until 2 days ago. I'm using tweepy version number 3.6.0 on python3 in jupyter notebook. Now, when I execute the code given below, I keep getting the error, TweepError: [{'code': 215, 'message': 'Bad Authentication data.'}]. What am I doing wrong? I've already looked at similar posts 1, 2,3,4,5 and 6 but no solution. Note, I have also regenerated the keys, still the error persists.

The code is;

import tweepy
ckey = 'xxx'
csecret = 'xxx'
atoken = 'xxx'
asecret = 'xxx'

# OAuth process, using the keys and tokens
auth = tweepy.OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
# Creation of the actual interface, using authentication
api = tweepy.API(auth)
# collect tweets on #MRT
for tweet in tweepy.Cursor(api.search,q="MRT",count=100,
                           lang="en",rpp=100,
                           since="2017-04-03").items():
  print (tweet.created_at, tweet.text)

On executing this code returns the following errors,

---------------------------------------------------------------------------
TweepError                                Traceback (most recent call last)
<ipython-input-11-b3e4ffb2d94f> in <module>()
      2 for tweet in tweepy.Cursor(api.search,q="MRT",count=100,
      3                            lang="en",rpp=100,
----> 4                            since="2017-04-03").items():
      5     print (tweet.created_at, tweet.text)

~\Miniconda3\lib\site-packages\tweepy\cursor.py in __next__(self)
     47
     48     def __next__(self):
---> 49         return self.next()
     50
     51     def next(self):

~\Miniconda3\lib\site-packages\tweepy\cursor.py in next(self)
    195         if self.current_page is None or self.page_index == len(self.current_page) - 1:
    196             # Reached end of current page, get the next page...
--> 197             self.current_page = self.page_iterator.next()
    198             self.page_index = -1
    199         self.page_index += 1

~\Miniconda3\lib\site-packages\tweepy\cursor.py in next(self)
    106
    107         if self.index >= len(self.results) - 1:
--> 108             data = self.method(max_id=self.max_id, parser=RawParser(), *self.args, **self.kargs)
    109
    110             if hasattr(self.method, '__self__'):

~\Miniconda3\lib\site-packages\tweepy\binder.py in _call(*args, **kwargs)
    248             return method
    249         else:
--> 250             return method.execute()
    251
    252     # Set pagination mode

~\Miniconda3\lib\site-packages\tweepy\binder.py in execute(self)
    232                     raise RateLimitError(error_msg, resp)
    233                 else:
--> 234                     raise TweepError(error_msg, resp, api_code=api_error_code)
    235
    236             # Parse the response payload

TweepError: Twitter error response: status code = 400

Any advice will be helpful.


问:
Is NULL necessary?
Is NULL or NOT NULL necessary for Adding a column in SQL Server? (If you are going to run UPDATE statement after)

I tested without it locally, and it seems to work fine both in SQL and on the website; but I wanted to make sure before running release/production.

I looked up some other articles, including microsoft website. Some show it with, some without. SO articles say some benefits of NULL, like if you have information that may be added later. But assuming I am going to run UPDATE to add values after, will it matter?

I am guessing it does not matter from what I've tested and read.

```<code>ALTER TABLE [dbo].[MyTable] ADD NewColumn varchar(150);
UPDATE [dbo].[MyTable] SET NewColumn ='Math' WHERE ID = 1
UPDATE [dbo].[MyTable] SET NewColumn ='Science' WHERE ID = 2
</code>```

答:
You can skip it, and by default the column will be created as NULL. However it is more legible if you indicate it explicitly.

Keep in mind that if your table already has data, you CANNOT add the column as NOT NULL. For this, you should firstly add the column as NULL, then UPDATE the values with non-null valid data and then alter column to NOT NULL.

Edit: Assuming the default behavior of the sql server when adding columns.

Title: Is NULL necessary?

Body:
Is NULL or NOT NULL necessary for Adding a column in SQL Server? (If you are going to run UPDATE statement after)

I tested without it locally, and it seems to work fine both in SQL and on the website; but I wanted to make sure before running release/production.

I looked up some other articles, including microsoft website. Some show it with, some without. SO articles say some benefits of NULL, like if you have information that may be added later. But assuming I am going to run UPDATE to add values after, will it matter?

I am guessing it does not matter from what I've tested and read.

ALTER TABLE [dbo].[MyTable] ADD NewColumn varchar(150);
UPDATE [dbo].[MyTable] SET NewColumn ='Math' WHERE ID = 1
UPDATE [dbo].[MyTable] SET NewColumn ='Science' WHERE ID = 2


问:
How to remove cubbyhole engine from Vault
Cubbyhole is enabled in Vault by default, but I dont really use it.

Is there any way to remove "cubbyhole" engine from Vault, or even better, is it possible to hide it for specific users?

答:
Cubbyhole is enabled by default and cannot be disabled.

Cubbyhole is used for response wrapping. You can read more about it here