问:
Call Swift enum case within same enum function
I'm trying to get my head around Swift enums and in doing so have taken myself off a tutorial track by trying to return a string from a function within the same enum...

```<code>enum topFiveBands: Int {
    case led_zeppilin = 1, queen, rush, pink_floyd, acdc

    func printRating() {
        print("The band \(???) has been ranked no.\(self.rawValue) of all time")
    }
}

var myFavBand = topFiveBands.acdc
myFavBand.printRating()
</code>```

My code starts with a implicit assignment which lists the top 5 bands of all time (some of you may disagree with me on this..). Within the same enum I have a function which will print:

```<code>The band \(???) has been ranked no.\(self.rawValue) of all time
</code>```

I've chosen .acdc so I'm looking for the function to return:

```<code>The band acdc has been ranked no.5 of all time
</code>```

Whilst I can pull the rawValue (5) I can't seem to find a way to get the acdc into the string.

答:
While you can use self, I would advise against it because with enum names you have limitations, like having to use pink_floyd.

Instead I would recommend adding a String property that returns a display name depending on the value of the enum

```<code>var displayName: String {
    switch self {
    case .pink_floyd: return "Pink Floyd"
    case ...: // The rest
    }
}

func printRating() {
    print("The band \(displayName) has been ranked no.\(rawValue) of all time")
}
</code>```

Body:
I'm trying to get my head around Swift enums and in doing so have taken myself off a tutorial track by trying to return a string from a function within the same enum...

enum topFiveBands: Int {
    case led_zeppilin = 1, queen, rush, pink_floyd, acdc

    func printRating() {
        print("The band \(???) has been ranked no.\(self.rawValue) of all time")
    }
}

var myFavBand = topFiveBands.acdc
myFavBand.printRating()

My code starts with a implicit assignment which lists the top 5 bands of all time (some of you may disagree with me on this..). Within the same enum I have a function which will print:

The band \(???) has been ranked no.\(self.rawValue) of all time

I've chosen .acdc so I'm looking for the function to return:

The band acdc has been ranked no.5 of all time

Whilst I can pull the rawValue (5) I can't seem to find a way to get the acdc into the string.

Body:
While you can use self, I would advise against it because with enum names you have limitations, like having to use pink_floyd.

Instead I would recommend adding a String property that returns a display name depending on the value of the enum

var displayName: String {
    switch self {
    case .pink_floyd: return "Pink Floyd"
    case ...: // The rest
    }
}

func printRating() {
    print("The band \(displayName) has been ranked no.\(rawValue) of all time")
}


来源: stackexchange

问:
Why am I getting syntax error 22-322 and error 76-322
My code is the below.  I am not advanced in SAS or SQL my statement is below from SAS Enterprise Guide 8.2 using Proc sql.
What I want to do is by unique PrescriberID to have the RX_PMPM, DrugCost_PMPM,PDL Rate GDR Rate  right next to each PresriberID

I am getting syntax error
ERROR 22-322
ERROR 76-322

```<code>proc sql;
create table work.ABC_2020_out as
select  Distinct PrescriberId,
from work.VitMDKPI_Report
        sum(PaidAmt)/count(distinct CardholderId) as RX_PMPM,
        sum(DrugCost)/count(distinct PrescriptionNumber) as DrugCost_PMPM,
            Count (PDL) as Total_NONANDPDL,
        Count (BrandGenericCode) as Total_BrandGeneric,
        Case when PDL=Y then 'PREFPDL'
        Case when BrandGenericCode=G then 'Generic'
        End
        PDL/Total_NONANDPDL as PDL Rate
        Generic/Total_BrandGeneric as GDR Rate
        Group by PrescriberId;

quit;
</code>```

答:
The first error that the parser will see is that this section is invalid.

```<code>select Distinct PrescriberId,
from work.VitMDKPI_Report
</code>```

Because of the comma at the end of the first line you are asking to select the variable named from and name it work.VitMDKPI_Report, which is not a valid name for a variable because of the period and the syntax is not valid because PROC SQL needs the as keyword when setting the name for a variable.

You seem to have put the FROM clause into the middle of the list of variables.  It should go after the list of variables and before the GROUP BY clause.

There are other issues including what looks like a mal formed CASE clause, attempts to reference a variable created in the SELECT clause without using the CALCULATED keyword and possibly invalid variable names.  But those will be harder to diagnosis without some example data and expected output for that data.

ContentLicense: CC BY-SA 4.0

Body:
My code is the below.  I am not advanced in SAS or SQL my statement is below from SAS Enterprise Guide 8.2 using Proc sql.
What I want to do is by unique PrescriberID to have the RX_PMPM, DrugCost_PMPM,PDL Rate GDR Rate  right next to each PresriberID

I am getting syntax error
ERROR 22-322
ERROR 76-322

proc sql;
create table work.ABC_2020_out as
select  Distinct PrescriberId,
from work.VitMDKPI_Report
        sum(PaidAmt)/count(distinct CardholderId) as RX_PMPM,
        sum(DrugCost)/count(distinct PrescriptionNumber) as DrugCost_PMPM,
            Count (PDL) as Total_NONANDPDL,
        Count (BrandGenericCode) as Total_BrandGeneric,
        Case when PDL=Y then 'PREFPDL'
        Case when BrandGenericCode=G then 'Generic'
        End
        PDL/Total_NONANDPDL as PDL Rate
        Generic/Total_BrandGeneric as GDR Rate
        Group by PrescriberId;

quit;

Body:
The first error that the parser will see is that this section is invalid.

select Distinct PrescriberId,
from work.VitMDKPI_Report

Because of the comma at the end of the first line you are asking to select the variable named from and name it work.VitMDKPI_Report, which is not a valid name for a variable because of the period and the syntax is not valid because PROC SQL needs the as keyword when setting the name for a variable.

You seem to have put the FROM clause into the middle of the list of variables.  It should go after the list of variables and before the GROUP BY clause.

There are other issues including what looks like a mal formed CASE clause, attempts to reference a variable created in the SELECT clause without using the CALCULATED keyword and possibly invalid variable names.  But those will be harder to diagnosis without some example data and expected output for that data.


问:
Flutter: Firebase: Crashlytics: How to decode crashes caused by Cloud_Firestore? 100% of my crashes are caused by 'CloudFirestorePlugin.java'
Over the past two months, my app has become significantly more complex. I use Transactions to complete 90% of all document writes client side. I have added quite a few listeners recently as well. Over the apps development, a linear increase in transaction and listener usage has caused an exponential spike in crashes. These crashes are just from testing using one device! Furthermore, the crashes happen exclusively on Android devices...

These are the four causes of every crash my app has seen:

io.flutter.plugins.firebase.cloudfirestore.CloudFirestorePlugin$5.doInBackground(CloudFirestorePlugin.java:613)

io.flutter.plugins.firebase.cloudfirestore.CloudFirestorePlugin$DocumentObserver.onEvent (CloudFirestorePlugin.java:429)

io.flutter.plugins.firebase.cloudfirestore.CloudFirestorePlugin$EventObserver.onEvent (CloudFirestorePlugin.java:451)

io.flutter.plugins.firebase.cloudfirestore.CloudFirestorePlugin$5.doInBackground (CloudFirestorePlugin.java:633)

The information provided doesn't help in narrowing down the problem. I would normally assume that I am doing something wrong, but the fact that this occurs exclusively on android devices leads me to believe something is wrong at the package level. Digging online through forums and documentation it appears I am not alone with this Firestore Transaction/Listener related issue.

Has anybody had similar issues and found a solution? This isn't only a problem for me, it's a show stopper.

Is it possible that since introducing listeners I have created this problem?

答:
This seems to be a known issue on github, please confirm but the issue only occurs on Android -Fluter with the listeners.

They mentioned:

Just waiting for the green signal to make sure this doesn't catch some other edge cases and I can go ahead with a fix patch.

You shoudl post that your are being affected also and followup there.


问:
Javascript Web Scraping couple urls
I want to get some data from couple urls and write to csv file. But a result is not satisfied for me, because I'm getting not all data (should be 10 in this case) and fetched data is not in right order. Should be 1, 2, 3 and so on, but I am getting it randomly, 6, 10, 5, 1.... From this code I am getting sometimes six h3 values, sometimes five, it is happening randomly. My url addresses are on 100% good. I am using async await syntax, but it doesn't help. I am beginner. Here is my code:

```<code>const request = require('request');
const cheerio = require('cheerio');
const fs = require('fs');
const writeSteam = fs.createWriteStream('data.csv');

let data= '';
const numOfFetchData = 10;
const numbers = Array.from(Array(numOfFetchData + 1).keys());

async function getData() {
    for await (const number of numbers) {
        request('randomURL/' + (number+1), (err, res, html) => {
            if(!err && res.statusCode == 200 && (number+1) <= numOfFetchData) {
                const $ = cheerio.load(html);
                const h3Tag = $("h3")[0].children[0].data;
                data += (number + 1) + ' ' + h3Tag + '\n'
            } else {
                writeSteam.write(`${data}`);
            }
        });
    };
};

getData();
</code>```

What should I improve in my code?

Thanks and Best Regards!

答:
After taking another look at your code it seems like the request library doesn't return promises, but works w/ callbacks (making async/await not usable). If you really want your code fetched in order you can

Use recursion to only fire the next request after the first one is finished:

```<code>async function getData(numbers) {
    request('randomURL/' + (numbers[numbers.length - 1] + 1), (err, res, html) => {
        numbers.pop()
        if(!err && res.statusCode == 200 && (number+1) <= numOfFetchData) {
                const $ = cheerio.load(html);
                const h3Tag = $("h3")[0].children[0].data;
                data += (number + 1) + ' ' + h3Tag + '\n'
        } else {
                writeSteam.write(`${data}`);
        }
        if (numbers.length > 0) getData(numbers);
    });
};

getData(numbers);
</code>```

In case that the order of which you get the data doesn't as long as the results are in the same order as the initial number array I'd suggest using fetch (a promise library) instead of request:

```<code>async function getData() {
    let fetchPromises = numbers.map(number => fetch('randomURL/' + (number+1)));
    const results = await Promise.all(fetchPromises); // results in order
    // Handle results
};
</code>```

Title: Javascript Web Scraping couple urls

Body:
I want to get some data from couple urls and write to csv file. But a result is not satisfied for me, because I'm getting not all data (should be 10 in this case) and fetched data is not in right order. Should be 1, 2, 3 and so on, but I am getting it randomly, 6, 10, 5, 1.... From this code I am getting sometimes six h3 values, sometimes five, it is happening randomly. My url addresses are on 100% good. I am using async await syntax, but it doesn't help. I am beginner. Here is my code:

const request = require('request');
const cheerio = require('cheerio');
const fs = require('fs');
const writeSteam = fs.createWriteStream('data.csv');

let data= '';
const numOfFetchData = 10;
const numbers = Array.from(Array(numOfFetchData + 1).keys());

async function getData() {
    for await (const number of numbers) {
        request('randomURL/' + (number+1), (err, res, html) => {
            if(!err && res.statusCode == 200 && (number+1) <= numOfFetchData) {
                const $ = cheerio.load(html);
                const h3Tag = $("h3")[0].children[0].data;
                data += (number + 1) + ' ' + h3Tag + '\n'
            } else {
                writeSteam.write(`${data}`);
            }
        });
    };
};

getData();

What should I improve in my code?

Thanks and Best Regards!

Body:
After taking another look at your code it seems like the request library doesn't return promises, but works w/ callbacks (making async/await not usable). If you really want your code fetched in order you can

Use recursion to only fire the next request after the first one is finished:

async function getData(numbers) {
    request('randomURL/' + (numbers[numbers.length - 1] + 1), (err, res, html) => {
        numbers.pop()
        if(!err && res.statusCode == 200 && (number+1) <= numOfFetchData) {
                const $ = cheerio.load(html);
                const h3Tag = $("h3")[0].children[0].data;
                data += (number + 1) + ' ' + h3Tag + '\n'
        } else {
                writeSteam.write(`${data}`);
        }
        if (numbers.length > 0) getData(numbers);
    });
};

getData(numbers);

In case that the order of which you get the data doesn't as long as the results are in the same order as the initial number array I'd suggest using fetch (a promise library) instead of request:

async function getData() {
    let fetchPromises = numbers.map(number => fetch('randomURL/' + (number+1)));
    const results = await Promise.all(fetchPromises); // results in order
    // Handle results
};


问:
How can I check if vars are equal 0?
On php documentation we can see:

```<code>"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
</code>```

If I have for example $var1 = 0; and $var2 = 0; on php I can do:

```<code>if (empty($var1)){
echo "empty";
}
</code>```

But I cant do this:

```<code>if (empty($var1 && $var2)){
echo "empty";
}
</code>```

How can I do for check if the two vars are equal to 0 on the same if?

Title: How can I check if vars are equal 0?

Body:
On php documentation we can see:

"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)

If I have for example $var1 = 0; and $var2 = 0; on php I can do:

if (empty($var1)){
echo "empty";
}

But I cant do this:

if (empty($var1 && $var2)){
echo "empty";
}

How can I do for check if the two vars are equal to 0 on the same if?

Body:
if($var1==="0" &&  $var2==="0"){
  echo"empty";
}


问:
Create a string from object array
I have two arrays as below:

var product1 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "One Plus"
    }
  ];
var product2 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "Apple"
    }
  ];
```

<p>I want to loop through the array and print the following:</p>

<ol>
<li>If product 1, output <code>you have 2 One Plus</code></li>
<li>If product 2, output <code>you have 1 One Plus and 1 Apple</code></li>
</ol>

<p>Below is the code that I tried.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var product1 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "One Plus"
    }
  ];
var product2 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "Apple"
    }
  ];

counter1 = {}
product1.forEach(function(obj) {
    var key = JSON.stringify(obj)
    counter1[key] = (counter1[key] || 0) + 1
});
console.log(counter1);
counter2 = {}
product2.forEach(function(obj) {
    var key = JSON.stringify(obj)
    counter2[key] = (counter2[key] || 0) + 1
});
console.log(counter2);</code>```

I’m able to get the JSON output, but how can I get it in the sentence format?

答:
const order1 = [
  {
    "Brand": "One Plus",
    "test" : "test"
  },
  {
    "Brand": "One Plus"
  },
  {
   "Bar": "Foo"
  }
];
const order2 = [
  {
    "Brand": "One Plus"
  },
  {
    "Brand": "Apple"
  }
];

const orderToString = (order) => {
  if(order == null) return;

  const productsWithBrand = order.filter(product => Object.keys(product).includes('Brand'));
  const productBrandCounter = (counter, product) => (counter[product.Brand] = (counter[product.Brand] || 0) + 1, counter);
  const countPerProduct = productsWithBrand.reduce(productBrandCounter, {});
  const stringPerProduct = Object.keys(countPerProduct).map(brand => `${countPerProduct[brand]} ${brand}`);

  return `You have ${stringPerProduct.join(' and ')}`;
}

console.log(orderToString(order1));```

Title: Create a string from object array

Body:
I have two arrays as below:

var product1 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "One Plus"
    }
  ];
var product2 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "Apple"
    }
  ];

I want to loop through the array and print the following:

If product 1, output you have 2 One Plus

If product 2, output you have 1 One Plus and 1 Apple

Below is the code that I tried.

var product1 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "One Plus"
    }
  ];
var product2 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "Apple"
    }
  ];

counter1 = {}
product1.forEach(function(obj) {
    var key = JSON.stringify(obj)
    counter1[key] = (counter1[key] || 0) + 1
});
console.log(counter1);
counter2 = {}
product2.forEach(function(obj) {
    var key = JSON.stringify(obj)
    counter2[key] = (counter2[key] || 0) + 1
});
console.log(counter2);

I’m able to get the JSON output, but how can I get it in the sentence format?


问:
How to write Inline/Lambda for appending or not appending to a list
I feel this a noob question but I haven't used lambda functions that much and I couldn't find what I needed online.
I wanted to write a lambda function which takes a series as an input, and returns a list without any 'None's in it
Basically I want a lambda function for the followinf function:

```<code>def get_path(x):
  toRet = []
  for item in x.tolist():
    if item is not None:
      toret.append(item)
  return toRet
</code>```

Is it possible to get an inline lambda function which does what get_path() does.
Yes I do know that I can do the following:

```<code>lambda x: get_path(x)
</code>```

It solves the problem but I would really love to know how to make an inline function for this.

答:
As others have pointed out, you can use filter() but be careful of what function you provide for the filter-check.

If function is None , the identity function is assumed, that is, all elements of iterable that are false are removed.

list(filter(None, something)) won't work correctly because it will filter out False-ish values too, not just None. Example:

```<code>>>> mylist = [1, 2, 3, 0, None, '', tuple(), 'last']
>>> list(filter(None, mylist))  # not the expected behaviour
[1, 2, 3, 'last']
</code>```

OP had an explicit if item is not None check, rather than just if item - so the two are not equivalent. Only None needs to be filtered out. To get the correct filtering behaviour, provide an actual check for the function provided to filter:

```<code>>>> list(filter(lambda i: i is not None, mylist))
[1, 2, 3, 0, '', (), 'last']
</code>```

Replace mylist with x.tolist(). And when you put that into a lambda, it gets messy:

```<code>get_path = lambda x: list(filter(lambda i: i is not None, x.tolist()))
</code>```

Instead of all that, the list comprehension option is better:

```<code>get_path = lambda x: [i for i in x.tolist() if i is not None]
</code>```

with an explicit is not None check.

Body:
I feel this a noob question but I haven't used lambda functions that much and I couldn't find what I needed online.
I wanted to write a lambda function which takes a series as an input, and returns a list without any 'None's in it
Basically I want a lambda function for the followinf function:

def get_path(x):
  toRet = []
  for item in x.tolist():
    if item is not None:
      toret.append(item)
  return toRet

Is it possible to get an inline lambda function which does what get_path() does.
Yes I do know that I can do the following:

lambda x: get_path(x)

It solves the problem but I would really love to know how to make an inline function for this.

Body:
As others have pointed out, you can use filter() but be careful of what function you provide for the filter-check.

If function is None , the identity function is assumed, that is, all elements of iterable that are false are removed.

list(filter(None, something)) won't work correctly because it will filter out False-ish values too, not just None. Example:

>>> mylist = [1, 2, 3, 0, None, '', tuple(), 'last']
>>> list(filter(None, mylist))  # not the expected behaviour
[1, 2, 3, 'last']

OP had an explicit if item is not None check, rather than just if item - so the two are not equivalent. Only None needs to be filtered out. To get the correct filtering behaviour, provide an actual check for the function provided to filter:

>>> list(filter(lambda i: i is not None, mylist))
[1, 2, 3, 0, '', (), 'last']

Replace mylist with x.tolist(). And when you put that into a lambda, it gets messy:

get_path = lambda x: list(filter(lambda i: i is not None, x.tolist()))

Instead of all that, the list comprehension option is better:

get_path = lambda x: [i for i in x.tolist() if i is not None]

with an explicit is not None check.


问:
cant create a trigger - sql server 2008
I'm trying the following :

```<code>CREATE TRIGGER checkgrade ON
[Homework4part3].[dbo].[Enrollment]
FOR INSERT
AS
    IF (NEW.grade > 20)
    BEGIN
    grade = 3
    END

GO
</code>```

and my table looks like :

Enrollment(course#, QYear, SUID,
  units, Grade)

dont know why this error showing :

```<code>Msg 102, Level 15, State 1, Procedure checkgrade, Line 7
Incorrect syntax near 'grade'.
</code>```

答:
I'm going to try to read between the lines a bit. Obviously I've made a best guess on the join condition. I think this is what you're trying to achieve.</p>

```<code>CREATE TRIGGER checkgrade ON
[Homework4part3].[dbo].[Enrollment]
FOR INSERT
AS
    UPDATE e
        SET grade = 3
        FROM inserted i
            INNER JOIN enrollment e
                ON i.coursenum = e.coursenum
                    AND i.QYear = e.QYear
                    AND I.SUID = e.SUID
        WHERE i.grade > 20

GO
</code>```

ContentLicense: CC BY-SA 3.0

Title: cant create a trigger - sql server 2008

Body:
I'm trying the following :

CREATE TRIGGER checkgrade ON
[Homework4part3].[dbo].[Enrollment]
FOR INSERT
AS
    IF (NEW.grade > 20)
    BEGIN
    grade = 3
    END

GO

and my table looks like :

Enrollment(course#, QYear, SUID,
  units, Grade)

dont know why this error showing :

Msg 102, Level 15, State 1, Procedure checkgrade, Line 7
Incorrect syntax near 'grade'.

Body:
I'm going to try to read between the lines a bit. Obviously I've made a best guess on the join condition. I think this is what you're trying to achieve.

CREATE TRIGGER checkgrade ON
[Homework4part3].[dbo].[Enrollment]
FOR INSERT
AS
    UPDATE e
        SET grade = 3
        FROM inserted i
            INNER JOIN enrollment e
                ON i.coursenum = e.coursenum
                    AND i.QYear = e.QYear
                    AND I.SUID = e.SUID
        WHERE i.grade > 20

GO


问:
Nativescript vue navigateTo outside tab
I'm new to Nativescript Vue. I have Login page and then page with BottomNavigation tabs. When I try to logout from Profile Tab I'm not able to navigateTo login page. It opens login page inside the tab.

On app load it opens Login. When user login he is redirected to App.vue where are tabs. And I need to logout and redirect inside tab.

How can I open login page not inside tab?

Login.vue

```<code><template>
    <Page>
        <FlexboxLayout class="page">
            <StackLayout class="form">
                <Image class="logo" src="~/assets/images/logo.png" />

                <StackLayout class="input-field" marginBottom="25">
                    <TextField class="input"
                               hint="E-mail"
                               keyboardType="email"
                               autocorrect="false"
                               autocapitalizationType="none"
                               v-model="user.email"
                               returnKeyType="next"
                               fontSize="18"
                    />
                    <StackLayout class="hr-light" />
                </StackLayout>

                <StackLayout class="input-field" marginBottom="25">
                    <TextField ref="password"
                               class="input"
                               hint="Password"
                               secure="true"
                               v-model="user.password"
                               :returnKeyType="'done'"
                               fontSize="18"
                    />
                    <StackLayout class="hr-light" />
                </StackLayout>

                <Button :text="'Log In'"
                        @tap="submit"
                        class="btn btn-primary m-t-20"
                />
                <Label text="Forgot your password?"
                       class="login-label"
                       @tap="forgotPassword"
                />
            </StackLayout>
        </FlexboxLayout>
    </Page>
</template>
</code>```

App.vue

```<code><template lang="html">
    <Page>
        <ActionBar>
            <NavigationButton visibility="collapsed"></NavigationButton>
            <StackLayout orientation="horizontal">
                <Image src="~/assets/images/test.png"></Image>
                <Label text="Telematics"></Label>
            </StackLayout>
        </ActionBar>

        <BottomNavigation>
            <TabStrip>
                <TabStripItem class="navigation__item">
                    <Label text="Tracking"></Label>
                    <Image src.decode="font://" class="fas t-36"></Image>
                </TabStripItem>
                <TabStripItem class="navigation__item">
                    <Label text="Browse"></Label>
                    <Image src.decode="font://" class="far t-36"></Image>
                </TabStripItem>
                <TabStripItem class="navigation__item">
                    <Label text="Profile"></Label>
                    <Image src.decode="font://" class="fas t-36"></Image>
                </TabStripItem>
            </TabStrip>

            <TabContentItem>
                <Frame>
                    <Items />
                </Frame>
            </TabContentItem>

            <TabContentItem>
                <Frame>
                    <Browse />
                </Frame>
            </TabContentItem>

            <TabContentItem>
                <Frame>
                    <Profile />
                </Frame>
            </TabContentItem>

        </BottomNavigation>
    </Page>
</template>
</code>```

Profile.vue

```<code><template lang="html">
    <Page actionBarHidden="true">
        <GridLayout class="page__content">
            <Label class="page__content-placeholder"
                   v-if="getEmail"
                   :text="getEmail"
            ></Label>
            <Label class="page__content-icon fas" text.decode=""></Label>
            <Button :text="'Log Out'"
                    @tap="logout"
                    class="btn btn-primary m-t-20"
            />
        </GridLayout>
    </Page>
</template>
</code>```

Logout method

```<code>logout() {
                this.tryLogout()
                    .then(() => {
                        console.log('LOGING OUT...');
                        this.$navigateTo(Login, {
                            clearHistory: true
                        });
                    })
                    .catch(() => {
                        this.alert("An error occured!");
                    });

            },
</code>```

答:
Solution is to specify frame in navigateTo:</p>

```<code>this.$navigateTo(Login, {
   frame: 'main',
   clearHistory: true
});
</code>```

Title: Nativescript vue navigateTo outside tab

Body:
I'm new to Nativescript Vue. I have Login page and then page with BottomNavigation tabs. When I try to logout from Profile Tab I'm not able to navigateTo login page. It opens login page inside the tab.

On app load it opens Login. When user login he is redirected to App.vue where are tabs. And I need to logout and redirect inside tab.

How can I open login page not inside tab?

Login.vue

<template>
    <Page>
        <FlexboxLayout class="page">
            <StackLayout class="form">
                <Image class="logo" src="~/assets/images/logo.png" />

                <StackLayout class="input-field" marginBottom="25">
                    <TextField class="input"
                               hint="E-mail"
                               keyboardType="email"
                               autocorrect="false"
                               autocapitalizationType="none"
                               v-model="user.email"
                               returnKeyType="next"
                               fontSize="18"
                    />
                    <StackLayout class="hr-light" />
                </StackLayout>

                <StackLayout class="input-field" marginBottom="25">
                    <TextField ref="password"
                               class="input"
                               hint="Password"
                               secure="true"
                               v-model="user.password"
                               :returnKeyType="'done'"
                               fontSize="18"
                    />
                    <StackLayout class="hr-light" />
                </StackLayout>

                <Button :text="'Log In'"
                        @tap="submit"
                        class="btn btn-primary m-t-20"
                />

            </StackLayout>
        </FlexboxLayout>
    </Page>
</template>

App.vue

<template lang="html">
    <Page>
        <ActionBar>
            <NavigationButton visibility="collapsed"></NavigationButton>
            <StackLayout orientation="horizontal">
                <Image src="~/assets/images/test.png"></Image>

            </StackLayout>
        </ActionBar>

        <BottomNavigation>
            <TabStrip>
                <TabStripItem class="navigation__item">

                    <Image src.decode="font://" class="fas t-36"></Image>
                </TabStripItem>
                <TabStripItem class="navigation__item">

                    <Image src.decode="font://" class="far t-36"></Image>
                </TabStripItem>
                <TabStripItem class="navigation__item">

                    <Image src.decode="font://" class="fas t-36"></Image>
                </TabStripItem>
            </TabStrip>

            <TabContentItem>
                <Frame>
                    <Items />
                </Frame>
            </TabContentItem>

            <TabContentItem>
                <Frame>
                    <Browse />
                </Frame>
            </TabContentItem>

            <TabContentItem>
                <Frame>
                    <Profile />
                </Frame>
            </TabContentItem>

        </BottomNavigation>
    </Page>
</template>

Profile.vue

<template lang="html">
    <Page actionBarHidden="true">
        <GridLayout class="page__content">

            <Button :text="'Log Out'"
                    @tap="logout"
                    class="btn btn-primary m-t-20"
            />
        </GridLayout>
    </Page>
</template>

Logout method

logout() {
                this.tryLogout()
                    .then(() => {
                        console.log('LOGING OUT...');
                        this.$navigateTo(Login, {
                            clearHistory: true
                        });
                    })
                    .catch(() => {
                        this.alert("An error occured!");
                    });

            },

Body:
Solution is to specify frame in navigateTo:

this.$navigateTo(Login, {
   frame: 'main',
   clearHistory: true
});


问:
Change ListView status when found new result
Could anybody help me I already spent about 2 hours just for fixing my problem with ListView

what I did is, if the text (from lbloutputName.text) found in ListView item, it will highlight and will show the status of Processing...

Here's my question. How I can change the status to Done if the searchItem found new text from my output logs?

Here's what I'm thinking but I don't know how to do it.

For example, if I found STRING1 the status will be Processing... and it will highlight the item in the ListView and then if found new STRING2, STRING1 status must change to Done. and then STRING2 will be Processing again.

Here's the code:

Dim searchItem As String = lblOutputName.Text

For Each lvi As ListViewItem In LV.Items
    For Each lvisub As ListViewItem.ListViewSubItem In lvi.SubItems
        If lvisub.Text = searchItem Then
            lvi.BackColor = Color.SteelBlue
            lvi.ForeColor = Color.White
            lvi.SubItems.Add("Processing...")
            LV.Focus()
            Exit For
        End If
    Next
Next
```

Here's my screenshot for my tool:

答:
To search the ListViewItem and ListViewItem.ListViewSubItem objects, use the ListView.FindItemWithText method:

Dim lvi = LV.FindItemWithText(searchItem)
```

<p>If you want to search the sub items only (as I understand from your code snippet) and return the first match, you can do instead:</p>

<pre class="lang-vb prettyprint-override"><code>Dim lvi = LV.Items.Cast(Of ListViewItem).
    FirstOrDefault(Function(x) x.SubItems.Cast(Of ListViewItem.ListViewSubItem).
    Skip(1).Any(Function(y) y.Text.ToLower = searchItem.ToLower))
</code>```

Note: ToLower for case-insensitive search.

Back to your main issue, you need to find a way to identify the already processed items to set their new state (Done), and set the state (Processing) of the item that you get from the search query if any:

If lvi IsNot Nothing Then
    LV.Items.Cast(Of ListViewItem).
    Where(Function(x) x IsNot lvi AndAlso x.BackColor = Color.SteelBlue).
    ToList().ForEach(Sub(x)
                         x.BackColor = SystemColors.Window
                         x.ForeColor = SystemColors.WindowText
                         x.SubItems(x.SubItems.Count - 1).Text = "Done..."
                     End Sub)

    lvi.BackColor = Color.SteelBlue
    lvi.ForeColor = Color.White
    lvi.SubItems(lvi.SubItems.Count - 1).Text = "Processing..."
End If
```

<p>You can use the <code>Tag</code> property instead to identify the processed items.</p>

<pre class="lang-vb prettyprint-override"><code>If lvi IsNot Nothing Then
    LV.Items.Cast(Of ListViewItem).
        Where(Function(x) x IsNot lvi AndAlso x.Tag?.ToString = "p").
        ToList().ForEach(Sub(x)
                             x.BackColor = SystemColors.Window
                             x.ForeColor = SystemColors.WindowText
                             x.SubItems(x.SubItems.Count - 1).Text = "Done..."
                             x.Tag = "d"
                         End Sub)

    lvi.Tag = "p"
    lvi.BackColor = Color.SteelBlue
    lvi.ForeColor = Color.White
    lvi.SubItems(lvi.SubItems.Count - 1).Text = "Processing..."
End If
</code>```

Body:
Could anybody help me I already spent about 2 hours just for fixing my problem with ListView

what I did is, if the text (from lbloutputName.text) found in ListView item, it will highlight and will show the status of Processing...

Here's my question. How I can change the status to Done if the searchItem found new text from my output logs?

Here's what I'm thinking but I don't know how to do it.

For example, if I found STRING1 the status will be Processing... and it will highlight the item in the ListView and then if found new STRING2, STRING1 status must change to Done. and then STRING2 will be Processing again.

Here's the code:

Dim searchItem As String = lblOutputName.Text

For Each lvi As ListViewItem In LV.Items
    For Each lvisub As ListViewItem.ListViewSubItem In lvi.SubItems
        If lvisub.Text = searchItem Then
            lvi.BackColor = Color.SteelBlue
            lvi.ForeColor = Color.White
            lvi.SubItems.Add("Processing...")
            LV.Focus()
            Exit For
        End If
    Next
Next

Here's my screenshot for my tool:

Body:
To search the ListViewItem and ListViewItem.ListViewSubItem objects, use the ListView.FindItemWithText method:

Dim lvi = LV.FindItemWithText(searchItem)

If you want to search the sub items only (as I understand from your code snippet) and return the first match, you can do instead:

Dim lvi = LV.Items.Cast(Of ListViewItem).
    FirstOrDefault(Function(x) x.SubItems.Cast(Of ListViewItem.ListViewSubItem).
    Skip(1).Any(Function(y) y.Text.ToLower = searchItem.ToLower))

Note: ToLower for case-insensitive search.

Back to your main issue, you need to find a way to identify the already processed items to set their new state (Done), and set the state (Processing) of the item that you get from the search query if any:

If lvi IsNot Nothing Then
    LV.Items.Cast(Of ListViewItem).
    Where(Function(x) x IsNot lvi AndAlso x.BackColor = Color.SteelBlue).
    ToList().ForEach(Sub(x)
                         x.BackColor = SystemColors.Window
                         x.ForeColor = SystemColors.WindowText
                         x.SubItems(x.SubItems.Count - 1).Text = "Done..."
                     End Sub)

    lvi.BackColor = Color.SteelBlue
    lvi.ForeColor = Color.White
    lvi.SubItems(lvi.SubItems.Count - 1).Text = "Processing..."
End If

You can use the Tag property instead to identify the processed items.

If lvi IsNot Nothing Then
    LV.Items.Cast(Of ListViewItem).
        Where(Function(x) x IsNot lvi AndAlso x.Tag?.ToString = "p").
        ToList().ForEach(Sub(x)
                             x.BackColor = SystemColors.Window
                             x.ForeColor = SystemColors.WindowText
                             x.SubItems(x.SubItems.Count - 1).Text = "Done..."
                             x.Tag = "d"
                         End Sub)

    lvi.Tag = "p"
    lvi.BackColor = Color.SteelBlue
    lvi.ForeColor = Color.White
    lvi.SubItems(lvi.SubItems.Count - 1).Text = "Processing..."
End If


问:
jQuery Cycle Effect on Tabs
Hi I have a built this Jquery code.

I want the buttons to auto cycle insted of hovering can anyone help please?

Jquery code is as follows:

```<code>$(function() {
  var $items = $('#vtab>ul>li');
  $items.click(function() {
    $items.removeClass('selected');
    $(this).addClass('selected');
    var index = $items.index($(this));
    $('#vtab>div').hide().eq(index).show();
  }).eq(1).mouseover();
});
</code>```

The Html is as follows:

```<code><div id="vtab">
  <ul>
    <li class="home selected"></li>
    <li class="login"></li>
    <li class="support"></li>
  </ul>
  <div>
    <h4>Home Insurance</h4>
  </div>
  <div>
    <h4>Secure Login</h4>
    <form id="loginForm" action="">
      <fieldset>
        <legend>You need to sign in with your Email & Password to continue.</legend>
        <div>
          <label for="email">Email:</label>
          <input type="text" name="email" id="email" />
        </div>
        <div>
          <label for="password">Password:</label>
          <input type="password" name="password" id="password" />
        </div>
        <div>
          <input id="login" type="submit" value="Fake Login" />
        </div>
      </fieldset>
    </form>
  </div>
  <div>
    <h4>Online Support</h4>
    Maecenas in varius nulla....
  </div>
</div>
</code>```

I want the buttons to cycle through rather than just when you hover

答:
It appears you want to automatically cycle through a set of tabs. Fortunately, the jQuery UI team has provided us with a great tool call Tabs that can do just this. More specifically, there's a method in Tabs called .rotate() which will allow you to provide and interval (in ms) and a command to repeat the cycle once it has finished.

The example code provided on the Tabs page resembles your code very closely, which should make it relatively painless to implement the jQuery UI solution.

Title: jQuery Cycle Effect on Tabs

Body:
Hi I have a built this Jquery code.

I want the buttons to auto cycle insted of hovering can anyone help please?

Jquery code is as follows:

$(function() {
  var $items = $('#vtab>ul>li');
  $items.click(function() {
    $items.removeClass('selected');
    $(this).addClass('selected');
    var index = $items.index($(this));
    $('#vtab>div').hide().eq(index).show();
  }).eq(1).mouseover();
});

The Html is as follows:

Home Insurance

Secure Login

    <form id="loginForm" action="">
      <fieldset>
        <legend>You need to sign in with your Email & Password to continue.</legend>

          Email:
          <input type="text" name="email" id="email" />

          Password:
          <input type="password" name="password" id="password" />

          <input id="login" type="submit" value="Fake Login" />

      </fieldset>
    </form>

Online Support

    Maecenas in varius nulla....

I want the buttons to cycle through rather than just when you hover


问:
How to evaluate the code provided by user?
I need to process some user-provided code on the server using PHP. The code is about to cover some very basic programming capabilities, for example: variables, literals, (preferably) functions, and some associated operations.

An option is to use the dangerous function of eval(). For my specific case, it's overwhelmingly & redundantly full featured, apart from its security issues and performance bottlenecks. Sanitizing the tokens using token_get_all() protects against Murphy, not Machiavelli! Regardless of its downsides, it's truly capable of what I'm tiring to achieve.

I've also checked the Symphony's ExpressionLanguage; it has some shortcomings:

it cannot detect the "variables" on its own (they should be introduced and known beforehand)

it lacks basic variable functionalities (only initializes them: no assignment functionality)

it's designed only for "one liner" expressions

Alas! a more sophisticated ExpressionLanguage would've sufficed.

I'm looking for something that allows some very basic "programming" capability to the users. Is there such a thing, if so, what is it? (even though it's written in another language, but is utilizable somehow on a server.)
If such a thing is not around, then how should I treat the eval() to not to drawn me?! Or, as a last-resort, how may I design a such a simple programming capability? (Please elaborate on the matters :)

As per comments below, here is a list of "programming" features the code syntax needs to support. It would've sufficed if the followings were supported in addition to what the ExpressionLanguage systax provides:

The sequence flow: executing the instruction one after another (contrary to the "one liner" nature of the ExpressionLanguage)

Local variable declaration (and their detections afterwards, of course)

Variable assignments from expressions (any composition of literals, function invocations, operators)

Passing variables to functions

Flow control constructs: at least a conditional construct (e.g: if) and a repetition construct (e.g: for loop)

答:
One thing that comes to mind is Twig, which is the template engine used by Symfony. It has a sandbox mode that you can enable, making it safe to evaluate untrusted code. I used it before to allow users to write their own templates.

Take a look at these resources:

https://twig.symfony.com/doc/3.x/api.html

https://twig.symfony.com/doc/3.x/api.html#sandbox-extension

An example of what is possible:

https://twig.symfony.com/doc/3.x/templates.html#setting-variables

So although it's meant for templating, I think you could adapt it to achieve what you want.

Good luck!


问:
compare two text files then update the specific values based on the matching first column. (python)
I have two files. File1 needs to grab values from file2 only if they have the same ID number. I only want to grab the LATITUDE and LONGITUDE values from file2. I need to update these values. I am not sure why the code below is not showing the output I want.

```<code>File1.txt

#ID CAT CHN LC SC LATITUDE LONGITUDE
20022 CX 21 --   4  32.739000  -114.635700
01711 CX 21 --   3  32.779700  -115.567500
08433 CX 21 --   2  31.919930  -123.321000

File2.txt

20022,32.45,-114.88
01192,32.839,-115.487
01711,32.88,-115.45
01218,32.717,-115.637

output
#ID CAT CHN LC SC LATITUDE LONGITUDE
20022 CX 21 --   4  32.45  -114.88
01711 CX 21 --   3  32.88  -115.45
08433 CX 21 --   2  31.919930  -123.321000
</code>```

The code I have so far.

```<code>file1_data = []

file1_headers = []

with open("File1.txt") as file1:
    for line in file1:
        file1_data.append(line.strip().split("\n"))
    file1_headers = file1_data[0]
    del file1_data[0]

file2_data = []

with open("File2.txt") as file2:
    for line in file2:
        file2_data.append(line.strip().split("\n"))

file2_ids = [x[0] for x in file2_data]

final_data = [file1_headers] + file1_data

for i in range(1, len(final_data)):
    if final_data[i][0] in file2_ids:
        match = [x for x in file2_data if x[0] == final_data[i][0]]
        final_data[i] = [match[0] + [final_data[i][3]]]

with open("output.txt", "w") as output:
    output.writelines("\n".join(["\n".join(x) for x in final_data]))
</code>```

答:
You can try this script.

```<code>from collections import defaultdict

# load data:
data1, data2 = defaultdict(list), {}
with open('File1.txt', 'r') as f_in1, open('File2.txt', 'r') as f_in2:
    for line in f_in1:
        if line.strip() and not line.startswith('#'):
            d = line.strip().split()
            data1[d[0]].append(d)

    for line in f_in2:
        if line.strip() and not line.startswith('#'):
            d = line.strip().split(',')
            data2[d[0]] = d

# change data:
for k, v in data2.items():
    if k not in data1:
        continue
    for vv in data1[k]:
        vv[5] = v[1]
        vv[6] = v[2]

# write data to file
with open('output.txt', 'w') as f_out:
    print('#ID\tCAT\tCHN\tLC\tSC\tLATITUDE\tLONGITUDE', file=f_out)
    for d in data1.values():
        for line in d:
            print(*line, sep='\t', file=f_out)
</code>```

Produces output.txt:

```<code>#ID CAT CHN LC  SC  LATITUDE    LONGITUDE
20022   CX  21  --  4   32.45   -114.88
01711   CX  21  --  3   32.88   -115.45
08433   CX  21  --  2   31.919930   -123.321000
</code>```

Body:
I have two files. File1 needs to grab values from file2 only if they have the same ID number. I only want to grab the LATITUDE and LONGITUDE values from file2. I need to update these values. I am not sure why the code below is not showing the output I want.

File1.txt

#ID CAT CHN LC SC LATITUDE LONGITUDE
20022 CX 21 --   4  32.739000  -114.635700
01711 CX 21 --   3  32.779700  -115.567500
08433 CX 21 --   2  31.919930  -123.321000

File2.txt

20022,32.45,-114.88
01192,32.839,-115.487
01711,32.88,-115.45
01218,32.717,-115.637

output
#ID CAT CHN LC SC LATITUDE LONGITUDE
20022 CX 21 --   4  32.45  -114.88
01711 CX 21 --   3  32.88  -115.45
08433 CX 21 --   2  31.919930  -123.321000

The code I have so far.

file1_data = []

file1_headers = []

with open("File1.txt") as file1:
    for line in file1:
        file1_data.append(line.strip().split("\n"))
    file1_headers = file1_data[0]
    del file1_data[0]

file2_data = []

with open("File2.txt") as file2:
    for line in file2:
        file2_data.append(line.strip().split("\n"))

file2_ids = [x[0] for x in file2_data]

final_data = [file1_headers] + file1_data

for i in range(1, len(final_data)):
    if final_data[i][0] in file2_ids:
        match = [x for x in file2_data if x[0] == final_data[i][0]]
        final_data[i] = [match[0] + [final_data[i][3]]]

with open("output.txt", "w") as output:
    output.writelines("\n".join(["\n".join(x) for x in final_data]))

Body:
You can try this script.

from collections import defaultdict

# load data:
data1, data2 = defaultdict(list), {}
with open('File1.txt', 'r') as f_in1, open('File2.txt', 'r') as f_in2:
    for line in f_in1:
        if line.strip() and not line.startswith('#'):
            d = line.strip().split()
            data1[d[0]].append(d)

    for line in f_in2:
        if line.strip() and not line.startswith('#'):
            d = line.strip().split(',')
            data2[d[0]] = d

# change data:
for k, v in data2.items():
    if k not in data1:
        continue
    for vv in data1[k]:
        vv[5] = v[1]
        vv[6] = v[2]

# write data to file
with open('output.txt', 'w') as f_out:
    print('#ID\tCAT\tCHN\tLC\tSC\tLATITUDE\tLONGITUDE', file=f_out)
    for d in data1.values():
        for line in d:
            print(*line, sep='\t', file=f_out)

Produces output.txt:

#ID CAT CHN LC  SC  LATITUDE    LONGITUDE
20022   CX  21  --  4   32.45   -114.88
01711   CX  21  --  3   32.88   -115.45
08433   CX  21  --  2   31.919930   -123.321000


问:
Does unique.data.table with by behave like dplyr::distinct with .keep_all = TRUE?
I want to get unique rows in a data frame based on one variable, while still choosing which rows (based on other variables) are included.

Example:

```<code>dt <- as.data.table(list(group = c("A", "A", "B", "B", "C", "C"), number = c(1, 2, 1, 2, 2, 1)))
</code>```

I would normally do this, as it allows me to always keep the row where number == 1.

```<code>dt %>%
arrange(group, number) %>%
distinct(group, .keep_all = TRUE)
</code>```

This is now too slow, and I'm hoping the data.table equivalent will be faster.

This seems to work:

```<code>dt <- dt[order(group, number)]
unique(dt, by = c("group"))
</code>```

But I couldn't find anything in the unique.data.table documentation which says that the first row per group is the one which is kept. Is it safe to assume it is?

答:
According to documentation

unique returns a data.table with duplicated rows removed, by columns specified in by argument. When no by then duplicated rows by all columns are removed.

We can reason from that it does return the first row by each unique group.

To complement options provided by @Ian here is another one which will probably be the fastest one.

setkeyv(dt, c("group","number"))
unique(dt, by="group")
```

At least as of now, because there are possible improvements coming. An example of reducing time from 3.544s to 0.075s, it needs an index rather than key, can be found in unique can be optimized on keyed data.tables #2947.

Body:
I want to get unique rows in a data frame based on one variable, while still choosing which rows (based on other variables) are included.

Example:

dt <- as.data.table(list(group = c("A", "A", "B", "B", "C", "C"), number = c(1, 2, 1, 2, 2, 1)))

I would normally do this, as it allows me to always keep the row where number == 1.

dt %>%
arrange(group, number) %>%
distinct(group, .keep_all = TRUE)

This is now too slow, and I'm hoping the data.table equivalent will be faster.

This seems to work:

dt <- dt[order(group, number)]
unique(dt, by = c("group"))

But I couldn't find anything in the unique.data.table documentation which says that the first row per group is the one which is kept. Is it safe to assume it is?

Body:
According to documentation

unique returns a data.table with duplicated rows removed, by columns specified in by argument. When no by then duplicated rows by all columns are removed.

We can reason from that it does return the first row by each unique group.

To complement options provided by @Ian here is another one which will probably be the fastest one.

setkeyv(dt, c("group","number"))
unique(dt, by="group")

At least as of now, because there are possible improvements coming. An example of reducing time from 3.544s to 0.075s, it needs an index rather than key, can be found in unique can be optimized on keyed data.tables #2947.


问:
Python's new `functools.cached_property` bug or limitation?
Since Python 3.8, functools has a cached_property.
I've been using a similar lazyprop decorator based on Beazley's cookbook (code below), but when I replace by the builtin, I get problems. Here's one of them.

When I use the decorator within the class definition, using the @ operator, it doesn't complain.

But if I use it with setattr, I get:

```<code>TypeError: Cannot use cached_property instance without calling __set_name__ on it.
</code>```

Beazley's simple version works fine though.

from functools import cached_property

class lazyprop:
    """Based on code from David Beazley's "Python Cookbook"."""
    def __init__(self, func):
        self.__doc__ = getattr(func, '__doc__')
        self.func = func

    def __get__(self, instance, cls):
        if instance is None:
            return self
        else:
            value = instance.__dict__[self.func.__name__] = self.func(instance)
            return value

class D:
    def __init__(self, greeting='Hello'):
        self.greeting = greeting

def greet(self):
    return self.greeting + " world!"

# Beazley's version works...
D.greet = lazyprop(greet)
assert D().greet == "Hello world!"

# ... but the builtin version will fail
D.greet = cached_property(greet)
# D().greet  # this will fail
```

答:
This is neither a bug nor a limitation. Using __set_name__ is merely a different means to deduce the property name - one that is more robust when used with regular class syntax.

For example, __set_name__ also works for anonymous functions with only the cached_property bound directly to a name:

```<code>from functools import cached_property
import random

class Bar:
    foo = cached_property(lambda self: random.random())

bar = bar()
print(bar.foo)  # 0.9901613829744336
print(bar.foo)  # 0.9901613829744336
</code>```

When using cached_property.cached_property instead, the value is stored improperly – namely as bar.<lambda> – preventing it from shadowing the property.

```<code>>>> functools_bar.__dict__
{'foo': 0.9901613829744336}
>>> cached_property_bar.__dict__
{'<lambda>': 0.7003011051281254}
</code>```

Body:
Since Python 3.8, functools has a cached_property.
I've been using a similar lazyprop decorator based on Beazley's cookbook (code below), but when I replace by the builtin, I get problems. Here's one of them.

When I use the decorator within the class definition, using the @ operator, it doesn't complain.

But if I use it with setattr, I get:

TypeError: Cannot use cached_property instance without calling __set_name__ on it.

Beazley's simple version works fine though.

from functools import cached_property

class lazyprop:
    """Based on code from David Beazley's "Python Cookbook"."""
    def __init__(self, func):
        self.__doc__ = getattr(func, '__doc__')
        self.func = func

    def __get__(self, instance, cls):
        if instance is None:
            return self
        else:
            value = instance.__dict__[self.func.__name__] = self.func(instance)
            return value

class D:
    def __init__(self, greeting='Hello'):
        self.greeting = greeting

def greet(self):
    return self.greeting + " world!"

# Beazley's version works...
D.greet = lazyprop(greet)
assert D().greet == "Hello world!"

# ... but the builtin version will fail
D.greet = cached_property(greet)
# D().greet  # this will fail

Body:
This is neither a bug nor a limitation. Using __set_name__ is merely a different means to deduce the property name - one that is more robust when used with regular class syntax.

For example, __set_name__ also works for anonymous functions with only the cached_property bound directly to a name:

from functools import cached_property
import random

class Bar:
    foo = cached_property(lambda self: random.random())

bar = bar()
print(bar.foo)  # 0.9901613829744336
print(bar.foo)  # 0.9901613829744336

When using cached_property.cached_property instead, the value is stored improperly – namely as bar.<lambda> – preventing it from shadowing the property.

>>> functools_bar.__dict__
{'foo': 0.9901613829744336}
>>> cached_property_bar.__dict__
{'<lambda>': 0.7003011051281254}


问:
How to sort only selected columns in pandas dataframe
I want to sort some columns in large Pandas dataframe. Those columns are in the middle of df and in end. They start with "R"

```<code>columns_list = df.columns.tolist()
columns_list
Out[17]:
['Id', 'Name', 'Surname', 'Radius', 'Ship', 'Country', 'Spacecraft', 'Planet', 'ExtraterrestialSupplier', 'R5', 'R2', 'R1', 'R4', 'R3', 'S3', 'S2', 'S4', 'S1', 'S6', 'S5', 'R5S3', 'R5S2', 'R5S4','R1S4']
</code>```

I would like to re-order like that:

```<code>['Id', 'Name', 'Surname', 'Radius', 'Ship', 'Country', 'Spacecraft', 'Planet', 'ExtraterrestialSupplier', 'R1', 'R2','R3', 'R4', 'R5', 'S3', 'S2', 'S4', 'S1', 'S6', 'S5', 'R1S4', 'R5S2', 'R5S3','R5S4']
</code>```

Until now I did it manually:

```<code>df= df['Id', 'Name', 'Surname', 'Radius', 'Ship', 'Country', 'Spacecraft', 'Planet', 'ExtraterrestialSupplier', 'R1', 'R2','R3', 'R4', 'R5', 'S3', 'S2', 'S4', 'S1', 'S6', 'S5', 'R1S4', 'R5S2', 'R5S3','R5S4']
</code>```

but new input data have more R columns and in every file it is different.

I would appreciate your advice.

答:
This should work, assuming the non "R" and "S" column names are not changing.  If they are, I think you would have to do a regex thing to find the names of the columns you want to sort.

I am sorting the names here by length and then alphabetically, which I think looks like how you are doing it.

```<code>new_df_columns = ['Id', 'Name', 'Surname', 'Radius', 'Ship', 'Country', 'Spacecraft',
               'Planet', 'ExtraterrestialSupplier', 'R5', 'R2', 'R1', 'R4', 'R3',
               'S3', 'S2', 'S4', 'S1', 'S6', 'S5', 'R5S3', 'R5S2', 'R5S4','R1S4']
df = pd.DataFrame(columns=new_df_columns)

base_columns = ['Id', 'Name', 'Surname', 'Radius', 'Ship', 'Country', 'Spacecraft',
               'Planet', 'ExtraterrestialSupplier',]
extra_cols = [name for name in new_df_columns if name not in base_columns]
sorted_extra = sorted(extra_cols, key = lambda x: (len(x),x))

df = df[base_columns + sorted_extra]
</code>```

Body:
I want to sort some columns in large Pandas dataframe. Those columns are in the middle of df and in end. They start with "R"

columns_list = df.columns.tolist()
columns_list
Out[17]:
['Id', 'Name', 'Surname', 'Radius', 'Ship', 'Country', 'Spacecraft', 'Planet', 'ExtraterrestialSupplier', 'R5', 'R2', 'R1', 'R4', 'R3', 'S3', 'S2', 'S4', 'S1', 'S6', 'S5', 'R5S3', 'R5S2', 'R5S4','R1S4']

I would like to re-order like that:

['Id', 'Name', 'Surname', 'Radius', 'Ship', 'Country', 'Spacecraft', 'Planet', 'ExtraterrestialSupplier', 'R1', 'R2','R3', 'R4', 'R5', 'S3', 'S2', 'S4', 'S1', 'S6', 'S5', 'R1S4', 'R5S2', 'R5S3','R5S4']

Until now I did it manually:

df= df['Id', 'Name', 'Surname', 'Radius', 'Ship', 'Country', 'Spacecraft', 'Planet', 'ExtraterrestialSupplier', 'R1', 'R2','R3', 'R4', 'R5', 'S3', 'S2', 'S4', 'S1', 'S6', 'S5', 'R1S4', 'R5S2', 'R5S3','R5S4']

but new input data have more R columns and in every file it is different.

I would appreciate your advice.

Body:
This should work, assuming the non "R" and "S" column names are not changing.  If they are, I think you would have to do a regex thing to find the names of the columns you want to sort.

I am sorting the names here by length and then alphabetically, which I think looks like how you are doing it.

new_df_columns = ['Id', 'Name', 'Surname', 'Radius', 'Ship', 'Country', 'Spacecraft',
               'Planet', 'ExtraterrestialSupplier', 'R5', 'R2', 'R1', 'R4', 'R3',
               'S3', 'S2', 'S4', 'S1', 'S6', 'S5', 'R5S3', 'R5S2', 'R5S4','R1S4']
df = pd.DataFrame(columns=new_df_columns)

base_columns = ['Id', 'Name', 'Surname', 'Radius', 'Ship', 'Country', 'Spacecraft',
               'Planet', 'ExtraterrestialSupplier',]
extra_cols = [name for name in new_df_columns if name not in base_columns]
sorted_extra = sorted(extra_cols, key = lambda x: (len(x),x))

df = df[base_columns + sorted_extra]


问:
Flutter Google Sign in data save to Firebase Cloud Firestore
I've implemented google_sign_in package in my flutter application.
I'm registering with google and saving the data in Cloud Firestore Database. I can save the data properly.

What I want is that, the next time someone try use register with google again with the same email it will check from database and show that he already have an account and ask to 'login' with google instead.

The reason I'm trying to do this is that, I will update the user data and logout.

And if I login/register again with the same Google email it replaces my updated data with details from google profile. I want the updated data in the Firestore to stay, not update each time I login.

Can anyone help me with this please. Thanks!

答:
there are basically several methods, I will describe ones I know here

1) firebase_auth

Actually it should be handled automatically by Firebase (unless you use the second option, http requests)

But generally firebase_auth should do the trick

```<code>authResult = await _auth.createUserWithEmailAndPassword(
          email: email,
          password: password,
        );
</code>```

Then if you put that in try {} on PlatformException catch(error) {} block you can tap into it by error.message to get the human readable message

2) http request

Or, if you like to do it through http request

You will need to handle it manually

```<code>await Provider.of<Auth>(context, listen: false).signup(
          _authData['email'],
          _authData['password'],
        );
</code>```

Also, if you put that in try {} on HttpExceptions catch(error) {} block you can tap into it by error.toString().contains(ERROR_TYPE) (where ERROR_TYPE can be ERROR_INVALID_EMAIL, INVALID_EMAIL, or ERROR_EMAIL_ALREADY_IN_USE, etc.) and define your cases manually.

All in all, I would recommend the first option as it removes many burdens from you

Hope it helps!

Body:
there are basically several methods, I will describe ones I know here

1) firebase_auth

Actually it should be handled automatically by Firebase (unless you use the second option, http requests)

But generally firebase_auth should do the trick

authResult = await _auth.createUserWithEmailAndPassword(
          email: email,
          password: password,
        );

Then if you put that in try {} on PlatformException catch(error) {} block you can tap into it by error.message to get the human readable message

2) http request

Or, if you like to do it through http request

You will need to handle it manually

await Provider.of<Auth>(context, listen: false).signup(
          _authData['email'],
          _authData['password'],
        );

Also, if you put that in try {} on HttpExceptions catch(error) {} block you can tap into it by error.toString().contains(ERROR_TYPE) (where ERROR_TYPE can be ERROR_INVALID_EMAIL, INVALID_EMAIL, or ERROR_EMAIL_ALREADY_IN_USE, etc.) and define your cases manually.

All in all, I would recommend the first option as it removes many burdens from you

Hope it helps!


问:
`for/in` loop contains weird indices
I am running Electron 4.0.6 and react-scripts 3.0.1, which, I believe, includes babel. I wrote this code:

```<code>const data = [1, 2, 3]
for( const idx in data ) console.log(idx)
</code>```

Expected output is:

0

  1

  2

Actual output is:

0

  1

  2

  peek

  last

with the last two indices mapping to functions. I have a large program written using for/in loops, and I am daunted by the possibility of putting in error checking in every one of my loops to make sure I'm not accidentally consuming a function index.

My questions:

Why am I seeing this?

How do I fix it?

Edit:

Thanks for everyone's input. To be clear, the program used to work until I reinstalled it on a new computer. I used to be able to use for/in to iterate over only the non-default indices in an array. I'm not sure why I can't do that anymore, and I'm wondering what changed that made it work the way it does now. Do I need to install an older version of react-scripts? Simply rewriting the whole program to use of loops doesn't work, either, because I already do that when I can. I use for/in loops when I need the index.

Edit 2:

I appreciate everybody's help. Thanks to the accepted answer, I was able to track down that the npm package dirty-json is overriding all arrays with .peek and .last without setting them as non-enumerable. I am now able to address this issue.

Final edit: dirty-json is fixed, so this exact problem should no longer occur. If you have arrived here because of a similar issue, check your packages; it is not dirty-json as of version 0.9.0.

答:
You are seeing this because for-in does not do what you expect. You should use for-of instead.

From MDN "The for...in statement iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols), including inherited enumerable properties."

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

For the record everyone who learns javascript eventually get bit by this as its very non intuitive. It even used to work in browsers because they recognized that people make this mistake.

Title: `for/in` loop contains weird indices

Body:
I am running Electron 4.0.6 and react-scripts 3.0.1, which, I believe, includes babel. I wrote this code:

const data = [1, 2, 3]
for( const idx in data ) console.log(idx)

Expected output is:

0

  1

  2

Actual output is:

0

  1

  2

  peek

  last

with the last two indices mapping to functions. I have a large program written using for/in loops, and I am daunted by the possibility of putting in error checking in every one of my loops to make sure I'm not accidentally consuming a function index.

My questions:

Why am I seeing this?

How do I fix it?

Edit:

Thanks for everyone's input. To be clear, the program used to work until I reinstalled it on a new computer. I used to be able to use for/in to iterate over only the non-default indices in an array. I'm not sure why I can't do that anymore, and I'm wondering what changed that made it work the way it does now. Do I need to install an older version of react-scripts? Simply rewriting the whole program to use of loops doesn't work, either, because I already do that when I can. I use for/in loops when I need the index.

Edit 2:

I appreciate everybody's help. Thanks to the accepted answer, I was able to track down that the npm package dirty-json is overriding all arrays with .peek and .last without setting them as non-enumerable. I am now able to address this issue.

Final edit: dirty-json is fixed, so this exact problem should no longer occur. If you have arrived here because of a similar issue, check your packages; it is not dirty-json as of version 0.9.0.


问:
How does react keep variables value in useCallback?
```<code>const { useState, useCallback } = React;
let globalValue = 0;
const ComponentA = ({ propValue }) => {
    const [sum, setSum] = useState(propValue);
    const [stateValue, setStateValue] = useState(0);
    const onClick = useCallback(() => {
        console.log(propValue, stateValue, globalValue);
        setSum(propValue + stateValue + globalValue);
    }, []);
    return (
        <div>
            <p>State value is {stateValue}</p>
            <p>Sum is {sum}</p>
            <button onClick={() => setStateValue(stateValue + 1)}>
                Set stateValue
              </button>
            <button onClick={() => globalValue += 1}>
                Set globalValue
            </button>
            <button onClick={onClick}>
                Get Sum
            </button>
        </div>
    );
};
const Parent = () => {
    const [propValue, setPropValue] = useState(0);

    return (
        <div>
            <p>Prop value is {propValue}</p>
            <button onClick={() => setPropValue(propValue + 1)}>
                Set PropValue
            </button>
            <ComponentA propValue={propValue} />
        </div>
    );
};
</code>```

If the dependencies list for useCallback in ComponentA is set to [], when the console.log is executed, no matter what the current propValue and stateValue are, they will always be 0. But the globalValue will always use the latest. When I check the __proto__ of propValue and stateValue, both of them are just primitive type.

How does useCallback hook keep the variables' original values? Shouldn't it respect the rule that if a variable is not defined in the current scope, it will look up to its parent and use the value from there (like globalValue)?

I understand that's the point of useCallback/useMemo but how is this implemented?

答:
I found the answer from this blog https://dmitripavlutin.com/react-hooks-stale-closures/

Here is the simulate code for useCallback.

```<code>(function () {
    const ReactDomTree = {};
    const memo = {};
    const getButtonElement = () => { return ReactDomTree.buttonA };
    function useMemo(create) {
        if (!memo.result) {
            memo.result = create();
        }

        return memo.result;
    };

    const useCallback = function (callback) {
        return useMemo(() => callback);
    }

    function component() {
        let propValue = Math.floor(Math.random() * 100); // mimic prop update
        let stateValue = Math.floor(Math.random() * 100); // mimic state update
        console.log('component render', propValue, stateValue);

        const onClick = useCallback(() => {
            console.log('onclick', propValue, stateValue);
        });

        if (!ReactDomTree.buttonA) {
            ReactDomTree.buttonA = {};
            ReactDomTree.buttonA.onClick = onClick;
        }
    }

    component(); // component render
    let button = getButtonElement()
    button.onClick();
    component(); // component render
    button = getButtonElement()
    button.onClick() // This log result is same as the previous one

})();
</code>```

Body:
const { useState, useCallback } = React;
let globalValue = 0;
const ComponentA = ({ propValue }) => {
    const [sum, setSum] = useState(propValue);
    const [stateValue, setStateValue] = useState(0);
    const onClick = useCallback(() => {
        console.log(propValue, stateValue, globalValue);
        setSum(propValue + stateValue + globalValue);
    }, []);
    return (

State value is {stateValue}

Sum is {sum}

            <button onClick={() => setStateValue(stateValue + 1)}>
                Set stateValue
              </button>
            <button onClick={() => globalValue += 1}>
                Set globalValue
            </button>
            <button onClick={onClick}>
                Get Sum
            </button>

    );
};
const Parent = () => {
    const [propValue, setPropValue] = useState(0);

    return (

Prop value is {propValue}

            <button onClick={() => setPropValue(propValue + 1)}>
                Set PropValue
            </button>
            <ComponentA propValue={propValue} />

    );
};

If the dependencies list for useCallback in ComponentA is set to [], when the console.log is executed, no matter what the current propValue and stateValue are, they will always be 0. But the globalValue will always use the latest. When I check the __proto__ of propValue and stateValue, both of them are just primitive type.

How does useCallback hook keep the variables' original values? Shouldn't it respect the rule that if a variable is not defined in the current scope, it will look up to its parent and use the value from there (like globalValue)?

I understand that's the point of useCallback/useMemo but how is this implemented?

Body:
I found the answer from this blog https://dmitripavlutin.com/react-hooks-stale-closures/

Here is the simulate code for useCallback.

(function () {
    const ReactDomTree = {};
    const memo = {};
    const getButtonElement = () => { return ReactDomTree.buttonA };
    function useMemo(create) {
        if (!memo.result) {
            memo.result = create();
        }

        return memo.result;
    };

    const useCallback = function (callback) {
        return useMemo(() => callback);
    }

    function component() {
        let propValue = Math.floor(Math.random() * 100); // mimic prop update
        let stateValue = Math.floor(Math.random() * 100); // mimic state update
        console.log('component render', propValue, stateValue);

        const onClick = useCallback(() => {
            console.log('onclick', propValue, stateValue);
        });

        if (!ReactDomTree.buttonA) {
            ReactDomTree.buttonA = {};
            ReactDomTree.buttonA.onClick = onClick;
        }
    }

    component(); // component render
    let button = getButtonElement()
    button.onClick();
    component(); // component render
    button = getButtonElement()
    button.onClick() // This log result is same as the previous one

})();


问:
How to validate start date and end date in angular formly
I have two simple fields (input) of the start date and end date I just want that end date should not be less than the start date

I am using angular 8
I am using ng module

so from myfile.json file I have created two text fields validated them with my date function (validation.ts) in HTML formly code is there

now I want to validate two dates I am new angular developer please help

```<code>json code
{
              "className": "col-md-6 col-xs-12",
              "key": "graduationstartdate",
              "type": "input",
              "templateOptions": {
                "label": "Course start Date",
                  "appearance": "outline"

              }
            },

            {
              "className": "col-md-6 col-xs-12",
              "key": "graduationenddate",
              "type": "input",
              "templateOptions": {
                "label": "Course End Date",
                "appearance": "outline"
              }
</code>```

```<code>validation.ts
it contains a function to validate the date
</code>```

```<code>form.html
contains formly code of form
</code>```

答:
You can use Angular material date picker

https://material.angular.io/components/datepicker/examples

and go to this section

Datepicker with min & max validation

here you can add Datepicker with min & max validation.

The other way is you can use a custom validator that will check end date should not be less than the start date

```<code>constructor(private formBuilder: FormBuilder) {
  this.formGroup= this.formBuilder.group({
    startDate: [''],
    endDate: ['']
  }, {validator: this.checkDates});
}
</code>```

If you are getting your values for variable unavailability at a later stage, you can use patchValue or setValue to assign the values to your form controls:

```<code>this.formGroup.setValue({
  startDate: this.formGorup.startDate;
  endDate: this.formGroup.endDate;
})
</code>```

The custom validator simply checks that the end date is a later date than the startdate and returns null if it is valid, or then a custom validation error:

```<code>checkDates(group: FormGroup) {
  if(group.controls.endDate.value < group.controls.startDate.value) {
    return { notValid:true }
  }
  return null;
}
</code>```

and then you can display this custom error in template with:

```<code><small *ngIf="formGroup.hasError('notValid')">Not valid</small>
</code>```

Also, remember to mark this formgroup in your form tag:

```<code><form [formGroup]="formGroup">
</code>```

Body:
I have two simple fields (input) of the start date and end date I just want that end date should not be less than the start date

I am using angular 8
I am using ng module

so from myfile.json file I have created two text fields validated them with my date function (validation.ts) in HTML formly code is there

now I want to validate two dates I am new angular developer please help

json code
{
              "className": "col-md-6 col-xs-12",
              "key": "graduationstartdate",
              "type": "input",
              "templateOptions": {
                "label": "Course start Date",
                  "appearance": "outline"

              }
            },

            {
              "className": "col-md-6 col-xs-12",
              "key": "graduationenddate",
              "type": "input",
              "templateOptions": {
                "label": "Course End Date",
                "appearance": "outline"
              }

validation.ts
it contains a function to validate the date

form.html
contains formly code of form

Body:
You can use Angular material date picker

https://material.angular.io/components/datepicker/examples

and go to this section

Datepicker with min & max validation

here you can add Datepicker with min & max validation.

The other way is you can use a custom validator that will check end date should not be less than the start date

constructor(private formBuilder: FormBuilder) {
  this.formGroup= this.formBuilder.group({
    startDate: [''],
    endDate: ['']
  }, {validator: this.checkDates});
}

If you are getting your values for variable unavailability at a later stage, you can use patchValue or setValue to assign the values to your form controls:

this.formGroup.setValue({
  startDate: this.formGorup.startDate;
  endDate: this.formGroup.endDate;
})

The custom validator simply checks that the end date is a later date than the startdate and returns null if it is valid, or then a custom validation error:

checkDates(group: FormGroup) {
  if(group.controls.endDate.value < group.controls.startDate.value) {
    return { notValid:true }
  }
  return null;
}

and then you can display this custom error in template with:

<small *ngIf="formGroup.hasError('notValid')">Not valid</small>

Also, remember to mark this formgroup in your form tag:

<form [formGroup]="formGroup">


问:
how to parse xml with php
I am trying to read a weather feed from Yahoo to my site.
Using the code below I was able to print the xml.
What I really want to achieve now is to put the temperature and image in two different variables</p>

```<code> $zipCode = "44418";
 $url = "http://weather.yahooapis.com/forecastrss";
 $zip = "?w=$zipCode";
 $fullUrl = $url . $zip.'&u=c';
 $curlObject = curl_init();
 curl_setopt($curlObject,CURLOPT_URL,$fullUrl);
 curl_setopt($curlObject,CURLOPT_HEADER,false);
 curl_setopt($curlObject,CURLOPT_RETURNTRANSFER,true);
 $returnYahooWeather = curl_exec($curlObject);
 curl_close($curlObject);
 print "yahooWeather". $returnYahooWeather;

//$temperature
//$image
</code>```

答:
I find it easiest to SimpleXML with PHP.

```<code>$xml = simplexml_load_string($returnYahooWeather);
echo $xml->Path->To->Temperature;
</code>```

It's easy enough, and you can use XPath with SimpleXML :). There are other ways of parsing XML too, as previously mentioned DOMDocument is one of them.

Title: how to parse xml with php

Body:
I am trying to read a weather feed from Yahoo to my site.
Using the code below I was able to print the xml.
What I really want to achieve now is to put the temperature and image in two different variables

 $zipCode = "44418";
 $url = "http://weather.yahooapis.com/forecastrss";
 $zip = "?w=$zipCode";
 $fullUrl = $url . $zip.'&u=c';
 $curlObject = curl_init();
 curl_setopt($curlObject,CURLOPT_URL,$fullUrl);
 curl_setopt($curlObject,CURLOPT_HEADER,false);
 curl_setopt($curlObject,CURLOPT_RETURNTRANSFER,true);
 $returnYahooWeather = curl_exec($curlObject);
 curl_close($curlObject);
 print "yahooWeather". $returnYahooWeather;

//$temperature
//$image

Body:
I find it easiest to SimpleXML with PHP.

$xml = simplexml_load_string($returnYahooWeather);
echo $xml->Path->To->Temperature;

It's easy enough, and you can use XPath with SimpleXML :). There are other ways of parsing XML too, as previously mentioned DOMDocument is one of them.


答: Try using a for ... of ... loop instead. for in loops over all enumerable properties of an object, even those inherited from the prototype chain, whereas for of only iterates over the object's own properties, in this case, array indices.

Title: `for/in` loop contains weird indices


问:
Mapbox Studio: landuse=residential not available?
I try to build a map for my stormchasing community. It is very important to see urban areas on the map. I tried to add a landuse=residential layer/filter but it seems Mapbox does not support this at all.

Any ideas or solutions on this?

答:
You are correct that the Mapbox Streets v8 tileset does not contain a landuse=residential field. However, this type of data is available in OSM as shown here and can be downloaded using Overpass Turbo - you can refer to the "Add OpenStreetMap data to your Mapbox project" tutorial for steps on how to do that.

Once you've downloaded this data, you can upload it to your Mapbox account, add it as a new layer to your map, and style it accordingly.


问:
Timing Events in Application Insight (Azure)
I was looking for a way to time events and have them graphed on Azure. Looking for hot spots where the events are slower for further analysis.

I can currently do the following, for instance:

```<code>var p = new Dictionary<string, string> {{ "StartTime", startTime.Value.ToString("g") }, { "EndTime", endTime.Value.ToString("g") }};
var m = new Dictionary<string, double> {{ "ElapsedSeconds", (endTime.Value - startTime.Value).TotalSeconds }};

ai.TrackEvent(eventName, p, m);
</code>```

This will allow me to see one event at a time and know how long it took. But there's no easy way to view it charted. However, I noticed that he javascript library has a startTrackEvent and stopTrackEvent (AI docs) which would seem ideal.

Has anyone seen a built-in way or an existing way to track timed server events?

答:
After looking for a while, I think that what you were looking for was TrackDependency method. </p>

<p>It shows nicely on the dependency graph how long does the program spends on each part of the code. </p>

Body:
I was looking for a way to time events and have them graphed on Azure. Looking for hot spots where the events are slower for further analysis.

I can currently do the following, for instance:

var p = new Dictionary<string, string> {{ "StartTime", startTime.Value.ToString("g") }, { "EndTime", endTime.Value.ToString("g") }};
var m = new Dictionary<string, double> {{ "ElapsedSeconds", (endTime.Value - startTime.Value).TotalSeconds }};

ai.TrackEvent(eventName, p, m);

This will allow me to see one event at a time and know how long it took. But there's no easy way to view it charted. However, I noticed that he javascript library has a startTrackEvent and stopTrackEvent (AI docs) which would seem ideal.

Has anyone seen a built-in way or an existing way to track timed server events?

Body:
After looking for a while, I think that what you were looking for was TrackDependency method.

It shows nicely on the dependency graph how long does the program spends on each part of the code.


问:
Olingo with Spring Boot
I am using this tutorial and it works for a simple java web application. Now I want to convert it to Spring Boot. I remove the web.xml and add the following two annotations to DemoServlet

```<code>@RestController
public class DemoServlet extends DispatcherServlet {
    private static final long serialVersionUID = 1L;
    private static final Logger LOG = LoggerFactory.getLogger(DemoServlet.class);

    @RequestMapping("/DemoService.svc/*")
    protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
        try {
            // create odata handler and configure it with CsdlEdmProvider and Processor
            OData odata = OData.newInstance();
            ServiceMetadata edm = odata.createServiceMetadata(new DemoEdmProvider(), new ArrayList<EdmxReference>());
            ODataHttpHandler handler = odata.createHandler(edm);
            handler.register(new DemoEntityCollectionProcessor());

            // let the handler do the work
            handler.process(req, resp);
        } catch (RuntimeException e) {
            LOG.error("Server Error occurred in ExampleServlet", e);
            throw new ServletException(e);
        }
    }
}
</code>```

I also change the HTTPServlet to DispatcherServlet.

Now I am only able to access one end point. i.e.

```<code>http://localhost:8080/DemoService.svc/
</code>```

The metadata end point is not working. It returns the service document instead of xml content.

```<code>http://localhost:8080/DemoService.svc/$metadata
</code>```

Can somebody explain what is going on here?

答: The best implementation of olingo2 and spring-boot can be found here. I would suggest to take a look at this repository, it is very straight forward and easy. </p>

Title: Olingo with Spring Boot

Body:
I am using this tutorial and it works for a simple java web application. Now I want to convert it to Spring Boot. I remove the web.xml and add the following two annotations to DemoServlet

@RestController
public class DemoServlet extends DispatcherServlet {
    private static final long serialVersionUID = 1L;
    private static final Logger LOG = LoggerFactory.getLogger(DemoServlet.class);

    @RequestMapping("/DemoService.svc/*")
    protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
        try {
            // create odata handler and configure it with CsdlEdmProvider and Processor
            OData odata = OData.newInstance();
            ServiceMetadata edm = odata.createServiceMetadata(new DemoEdmProvider(), new ArrayList<EdmxReference>());
            ODataHttpHandler handler = odata.createHandler(edm);
            handler.register(new DemoEntityCollectionProcessor());

            // let the handler do the work
            handler.process(req, resp);
        } catch (RuntimeException e) {
            LOG.error("Server Error occurred in ExampleServlet", e);
            throw new ServletException(e);
        }
    }
}

I also change the HTTPServlet to DispatcherServlet.

Now I am only able to access one end point. i.e.

http://localhost:8080/DemoService.svc/

The metadata end point is not working. It returns the service document instead of xml content.

http://localhost:8080/DemoService.svc/$metadata

Can somebody explain what is going on here?


问:
Build condition comparison for if statement
Is this possible?

```<code>$var_1 = 1;
$var_2 = 10;
$comparison = '>';

if($var_1 $comparison $var_2) {
    // do something...
}
</code>```

The syntax right now is not valid but is there a way to do this?

答:
You probably should use eval(). As like in other programming languages, PHP’s eval() is also powerful and dangerous — be careful.

If you write something like the following code:

```<code>if (eval("$var_1 $comparison $var_2")) {
    // ...
}
</code>```

It won’t work. Because PHP’s eval() doesn’t evaluate an expression, but just execute a statement. So you should do like:

```<code>eval("\$condition = $var_1 $comparison $var_2;"); // semicolon required!
if ($condition) {
    // ...
}
</code>```

It would work well except $var_1 or $var_2 is not number. For example, if $var_1 is a string like 'hello', the code eval() executes becomes:

```<code>eval("\$condition = hello > 2;");
</code>```

To avoid breaking this code, you should escape dollar signs of $var_1 and $var_2:

```<code>eval("\$condition = \$var_1 $comparison \$var_2;"); // don't escape $comparison's.
</code>```

Body:
Is this possible?

$var_1 = 1;
$var_2 = 10;
$comparison = '>';

if($var_1 $comparison $var_2) {
    // do something...
}

The syntax right now is not valid but is there a way to do this?

Body:
You probably should use eval(). As like in other programming languages, PHP’s eval() is also powerful and dangerous — be careful.

If you write something like the following code:

if (eval("$var_1 $comparison $var_2")) {
    // ...
}

It won’t work. Because PHP’s eval() doesn’t evaluate an expression, but just execute a statement. So you should do like:

eval("\$condition = $var_1 $comparison $var_2;"); // semicolon required!
if ($condition) {
    // ...
}

It would work well except $var_1 or $var_2 is not number. For example, if $var_1 is a string like 'hello', the code eval() executes becomes:

eval("\$condition = hello > 2;");

To avoid breaking this code, you should escape dollar signs of $var_1 and $var_2:

eval("\$condition = \$var_1 $comparison \$var_2;"); // don't escape $comparison's.


问:
Can't click button on tkinter
I am new to tkinter and I am having trouble with buttons on the python GUI. I create the buttons and the function behind it but I am unable to click the button. Can someone tell me what I am doing wrong? The UI comes up and I can see the button I just can't click it.</p>

```<code>import tkinter as tk

from tkinter import filedialog, Text

import os

#main
root = tk.Tk()

def addApp():
    filename = filedialog.askopenfilename(initialir= "/", title= "Select File",
                                          filetypes = (("executables", "*.exe"),
                                                        ("all files", "*.*")))

canvas = tk.Canvas(root, height=700, width=700, bg="#33F9FF")

canvas.pack()

frame = tk.Frame(root, bg="white")
frame.place(relwidth=0.8, relheight=0.8, relx = 0.1, rely = 0.1)

openFile = tk.Button(root, text = "Open File", padx = 10, pady = 5, fg="black",
                     bg="#33F9FF", command="addApp")

openFile.pack()

runApps = tk.Button(root, text = "Run Apps", padx = 10, pady = 5, fg="black",
                    bg="#33F9FF")

runApps.pack()

root.mainloop()
</code>```

答:
Very, small mistake. You added command argument as a string and not a function

```<code>openFile = tk.Button(root, text = "Open File", padx = 10, pady = 5, fg="black",
                     bg="#33F9FF", command=addApp)
</code>```

EDIT:
there is a small typo at initialdir argument in openfiledialogbox

```<code>filename = filedialog.askopenfilename(initialdir= "/", title= "Select File",
                                          filetypes = (("executables", "*.exe"),
                                                        ("all files", "*.*")))
</code>```

Title: Can't click button on tkinter

Body:
I am new to tkinter and I am having trouble with buttons on the python GUI. I create the buttons and the function behind it but I am unable to click the button. Can someone tell me what I am doing wrong? The UI comes up and I can see the button I just can't click it.

import tkinter as tk

from tkinter import filedialog, Text

import os

#main
root = tk.Tk()

def addApp():
    filename = filedialog.askopenfilename(initialir= "/", title= "Select File",
                                          filetypes = (("executables", "*.exe"),
                                                        ("all files", "*.*")))

canvas = tk.Canvas(root, height=700, width=700, bg="#33F9FF")

canvas.pack()

frame = tk.Frame(root, bg="white")
frame.place(relwidth=0.8, relheight=0.8, relx = 0.1, rely = 0.1)

openFile = tk.Button(root, text = "Open File", padx = 10, pady = 5, fg="black",
                     bg="#33F9FF", command="addApp")

openFile.pack()

runApps = tk.Button(root, text = "Run Apps", padx = 10, pady = 5, fg="black",
                    bg="#33F9FF")

runApps.pack()

root.mainloop()

Body:
Very, small mistake. You added command argument as a string and not a function

openFile = tk.Button(root, text = "Open File", padx = 10, pady = 5, fg="black",
                     bg="#33F9FF", command=addApp)

EDIT:
there is a small typo at initialdir argument in openfiledialogbox

filename = filedialog.askopenfilename(initialdir= "/", title= "Select File",
                                          filetypes = (("executables", "*.exe"),
                                                        ("all files", "*.*")))


问:
Aria-live content read twice by Mac - Chrome - VoiceOver
Aria-live content read twice by Mac - Chrome - VoiceOver, when the content is in the iframe. Below links are the example by "developer mozilla". I want to know whether this is an issue or not, If so, is there any solution to fix this?

Links

Aria-live in iframe In this link aria-live content reads twice.

Aria-live not in iframe In this link aria-live reads content only once.

答:
It's a known issue and a bug in VoiceOver, with apparently no known solution.

Read:  VoiceOver duplicates alerts in iframes

According to that page, a bug report has been sent to Apple

A Twitter User, Ryan Seddon says that the bug only appear with aria-live=polite and not assertive


问:
R - Repetitions of an array in other array
From a dataframe I get a new array, sliced from a dataframe.
I want to get the amount of times a certain repetition appears on it.

For example

```<code>main <- c(A,B,C,A,B,V,A,B,C,D,E)
p <- c(A,B,C)
q <- c(A,B)

someFunction(main,p)
2

someFunction(main,q)
3
</code>```

I've been messing around with rle but it counts every subrepetion also, undersirable.

Is there a quick solution I'm missing?

答:
Using sapply:

```<code>find_x_in_y <- function(x, y){
  sum(sapply(
      seq_len(length(y)-length(x)),
      function(i)as.numeric(all(y[i:(i+length(x)-1)]==x))
  ))
}

find_x_in_y(c("A", "B", "C"), main)
[1] 2

find_x_in_y(c("A", "B"), main)
[1] 3
</code>```

Body:
From a dataframe I get a new array, sliced from a dataframe.
I want to get the amount of times a certain repetition appears on it.

For example

main <- c(A,B,C,A,B,V,A,B,C,D,E)
p <- c(A,B,C)
q <- c(A,B)

someFunction(main,p)
2

someFunction(main,q)
3

I've been messing around with rle but it counts every subrepetion also, undersirable.

Is there a quick solution I'm missing?

Body:
Using sapply:

find_x_in_y <- function(x, y){
  sum(sapply(
      seq_len(length(y)-length(x)),
      function(i)as.numeric(all(y[i:(i+length(x)-1)]==x))
  ))
}

find_x_in_y(c("A", "B", "C"), main)
[1] 2

find_x_in_y(c("A", "B"), main)
[1] 3


问:
Error in R: The subscript var has the wrong type quosure/formula. It must be numeric or character
Code:

```<code>GeoSeparate <- function(Dataset, GeoColumn) {
  GeoColumn <- enquo(GeoColumn)
  Dataset %>%
    separate(GeoColumn, into = c("Section1", "Section2"), sep = "\\(")%>%
    separate(Section1, into = c("Section3", "Section4"), sep = ",")%>%
    separate(Section2, into = c("GeoColumn", "Section5"), sep = "\\)")%>%
    separate(GeoColumn, into = c("GeoColumnLat", "GeoColumnLon"), sep = ",")%>%
    select(-Section3, -Section4, -Section5) #remove sections we don't need
}
</code>```

Test:

```<code>GeoSeparate(df3, DeathCityGeo)
</code>```

Error:

Must extract column with a single subscript.
x The subscriptvarhas the wrong typequosure/formula.
ℹ It must be numeric or character.

My function separates a column that has the format: "Norwalk, CT\n(41.11805, -73.412906)" so that the latitude and longitude are all that remain and they are in two separate columns. It worked for a while, but now I get the error message described above. It may be because I updated my libraries but I'm not sure. Any help would be amazing! Thank you.

答:
We need to evaluate (!!)

```<code>GeoSeparate <- function(Dataset, GeoColumn) {
    GeoColumn <- enquo(GeoColumn)
    Dataset %>%
        separate(!!GeoColumn, into = c("Section1", "Section2"), sep = "\\(")%>%
        separate(Section1, into = c("Section3", "Section4"), sep = ",")%>%
        separate(Section2, into = c("GeoColumn", "Section5"), sep = "\\)")%>%
        separate(!!GeoColumn, into = c("GeoColumnLat", "GeoColumnLon"), sep = ",")%>%
        select(-Section3, -Section4, -Section5) #remove sections we don't need
    }
</code>```

Or another option is curly-curly ({{}})

```<code>GeoSeparate <- function(Dataset, GeoColumn) {

        Dataset %>%
            separate({{GeoColumn}}, into = c("Section1", "Section2"), sep = "\\(")%>%
            separate(Section1, into = c("Section3", "Section4"), sep = ",")%>%
            separate(Section2, into = c("GeoColumn", "Section5"), sep = "\\)")%>%
            separate({{GeoColumn}}, into = c("GeoColumnLat", "GeoColumnLon"), sep = ",")%>%
            select(-Section3, -Section4, -Section5) #remove sections we don't need
        }
</code>```

Body:
Code:

GeoSeparate <- function(Dataset, GeoColumn) {
  GeoColumn <- enquo(GeoColumn)
  Dataset %>%
    separate(GeoColumn, into = c("Section1", "Section2"), sep = "\\(")%>%
    separate(Section1, into = c("Section3", "Section4"), sep = ",")%>%
    separate(Section2, into = c("GeoColumn", "Section5"), sep = "\\)")%>%
    separate(GeoColumn, into = c("GeoColumnLat", "GeoColumnLon"), sep = ",")%>%
    select(-Section3, -Section4, -Section5) #remove sections we don't need
}

Test:

GeoSeparate(df3, DeathCityGeo)

Error:

Must extract column with a single subscript.
x The subscriptvarhas the wrong typequosure/formula.
ℹ It must be numeric or character.

My function separates a column that has the format: "Norwalk, CT\n(41.11805, -73.412906)" so that the latitude and longitude are all that remain and they are in two separate columns. It worked for a while, but now I get the error message described above. It may be because I updated my libraries but I'm not sure. Any help would be amazing! Thank you.

Body:
We need to evaluate (!!)

GeoSeparate <- function(Dataset, GeoColumn) {
    GeoColumn <- enquo(GeoColumn)
    Dataset %>%
        separate(!!GeoColumn, into = c("Section1", "Section2"), sep = "\\(")%>%
        separate(Section1, into = c("Section3", "Section4"), sep = ",")%>%
        separate(Section2, into = c("GeoColumn", "Section5"), sep = "\\)")%>%
        separate(!!GeoColumn, into = c("GeoColumnLat", "GeoColumnLon"), sep = ",")%>%
        select(-Section3, -Section4, -Section5) #remove sections we don't need
    }

Or another option is curly-curly ({{}})

GeoSeparate <- function(Dataset, GeoColumn) {

        Dataset %>%
            separate({{GeoColumn}}, into = c("Section1", "Section2"), sep = "\\(")%>%
            separate(Section1, into = c("Section3", "Section4"), sep = ",")%>%
            separate(Section2, into = c("GeoColumn", "Section5"), sep = "\\)")%>%
            separate({{GeoColumn}}, into = c("GeoColumnLat", "GeoColumnLon"), sep = ",")%>%
            select(-Section3, -Section4, -Section5) #remove sections we don't need
        }