问:
Loop through rows and assign value based on condition
I have dates for each row in my dataframe and want to assign a value to a new column based on a condition of the date.

Normally if I assign a value to a new column, I would do something like this:

```<code>def get_mean(df):
   return df.assign(
     grouped_mean = lambda df: df.groupby('group')['X']
       .transform(lambda df: df.mean())
   )
</code>```

No I am looking for a solution like that, since the solution I have now is very slow and not beautiful.

Is there a better way than my current solution and use assign?

I currently came up with this solution:

```<code>def set_season(df):
    df = df.copy()
    for i in df.index:
        if (df.loc[i, 'Date'] >= pd.Timestamp('2008-08-30')) & (df.loc[i, 'Date'] <= pd.Timestamp('2009-05-31')):
            df.at[i, 'season'] = '08-09'
        elif  (df.loc[i, 'Date'] >= pd.Timestamp('2009-08-22')) & (df.loc[i, 'Date'] <= pd.Timestamp('2010-05-16')):
            df.at[i, 'season'] = '09-10'
        elif  (df.loc[i, 'Date'] >= pd.Timestamp('2010-08-28')) & (df.loc[i, 'Date'] <= pd.Timestamp('2011-05-22')):
            df.at[i, 'season'] = '10-11'

    return df
</code>```

答:
In pandas and in most cases in Python general, we want to avoid looping over our data because it can be slower up to factors 1000x. Pandas and numpy provide lot of vectorized solutions, for most of our problem cases. Read more about it here

In your case we can use np.select which lets us define multiple conditions and based on those conditions we define choices.

Plus we can make your code more elegant by using Series.between with the inclusive=True argument.

```<code>conditions = [
    df['Date'].between('2008-08-30', '2009-05-31', inclusive=True),
    df['Date'].between('2009-08-22', '2010-05-16', inclusive=True),
    df['Date'].between('2010-08-28', '2011-05-22', inclusive=True)
]

choices = ['08-09', '09-10', '10-11']

df['season'] = np.select(conditions, choices, default='99-99')
</code>```

Sidenote

We can also rewrite your first function better with removing the two lambda functions and simply assigning the new column with groupby and transform and also taking extra arguments: group & mean_col

```<code>def get_mean(df, group, mean_col):

    df['mean'] = df.groupby(group)[mean_col].transform('mean')

    return df
</code>```

Example

```<code># Example dataframe
df = pd.DataFrame({'Fruit':['Banana', 'Strawberry', 'Apple', 'Banana', 'Apple'],
                   'Weight':[10, 12, 8, 9, 14]})

        Fruit  Weight
0      Banana      10
1  Strawberry      12
2       Apple       8
3      Banana       9
4       Apple      14

get_mean(df, 'Fruit', 'Weight')

        Fruit  Weight  mean
0      Banana      10   9.5
1  Strawberry      12  12.0
2       Apple       8  11.0
3      Banana       9   9.5
4       Apple      14  11.0
</code>```

Body:
I have dates for each row in my dataframe and want to assign a value to a new column based on a condition of the date.

Normally if I assign a value to a new column, I would do something like this:

def get_mean(df):
   return df.assign(
     grouped_mean = lambda df: df.groupby('group')['X']
       .transform(lambda df: df.mean())
   )

No I am looking for a solution like that, since the solution I have now is very slow and not beautiful.

Is there a better way than my current solution and use assign?

I currently came up with this solution:

def set_season(df):
    df = df.copy()
    for i in df.index:
        if (df.loc[i, 'Date'] >= pd.Timestamp('2008-08-30')) & (df.loc[i, 'Date'] <= pd.Timestamp('2009-05-31')):
            df.at[i, 'season'] = '08-09'
        elif  (df.loc[i, 'Date'] >= pd.Timestamp('2009-08-22')) & (df.loc[i, 'Date'] <= pd.Timestamp('2010-05-16')):
            df.at[i, 'season'] = '09-10'
        elif  (df.loc[i, 'Date'] >= pd.Timestamp('2010-08-28')) & (df.loc[i, 'Date'] <= pd.Timestamp('2011-05-22')):
            df.at[i, 'season'] = '10-11'

    return df

Body:
In pandas and in most cases in Python general, we want to avoid looping over our data because it can be slower up to factors 1000x. Pandas and numpy provide lot of vectorized solutions, for most of our problem cases. Read more about it here

In your case we can use np.select which lets us define multiple conditions and based on those conditions we define choices.

Plus we can make your code more elegant by using Series.between with the inclusive=True argument.

conditions = [
    df['Date'].between('2008-08-30', '2009-05-31', inclusive=True),
    df['Date'].between('2009-08-22', '2010-05-16', inclusive=True),
    df['Date'].between('2010-08-28', '2011-05-22', inclusive=True)
]

choices = ['08-09', '09-10', '10-11']

df['season'] = np.select(conditions, choices, default='99-99')

Sidenote

We can also rewrite your first function better with removing the two lambda functions and simply assigning the new column with groupby and transform and also taking extra arguments: group & mean_col

def get_mean(df, group, mean_col):

    df['mean'] = df.groupby(group)[mean_col].transform('mean')

    return df

Example

# Example dataframe
df = pd.DataFrame({'Fruit':['Banana', 'Strawberry', 'Apple', 'Banana', 'Apple'],
                   'Weight':[10, 12, 8, 9, 14]})

        Fruit  Weight
0      Banana      10
1  Strawberry      12
2       Apple       8
3      Banana       9
4       Apple      14

get_mean(df, 'Fruit', 'Weight')

        Fruit  Weight  mean
0      Banana      10   9.5
1  Strawberry      12  12.0
2       Apple       8  11.0
3      Banana       9   9.5
4       Apple      14  11.0


来源: stackexchange

问:
would return 0 using C++ in a class outside of main close the application?
I'm currently working on implementing patch files in some code, and apparently one of the patch files uses return 0 in a class outside of the main. I know return 0 would close the application if it was in the main function, however I'm not sure about how it would function in a class outside of the main function. Basically the code could be summed up like this in pseudocode:

```<code>boost::uint64_t
namespace::class(etc. etc.)
{

   if (method.isValid)
   {
      //do stuff
   }
return 0;
}
</code>```

Normally when I think of return 0 in C++, I think of exiting the application by calling it in main, however in this case, I'm not sure if this would exit the application, or just the class's functionality/the class it self. Could someone please explain what the return 0 would actually be doing in this situation?

Thanks,
Flyboy

答: Returning from main exits the application (regardless of the value being returned -- though the standard only defines meanings for 0, EXIT_SUCCESS, and EXIT_FAILURE). Returning from some other function just returns the designated value (if any) to the caller. The control flow doesn't change just because the value being returned happens to be zero.

ContentLicense: CC BY-SA 3.0

Body:
I'm currently working on implementing patch files in some code, and apparently one of the patch files uses return 0 in a class outside of the main. I know return 0 would close the application if it was in the main function, however I'm not sure about how it would function in a class outside of the main function. Basically the code could be summed up like this in pseudocode:

boost::uint64_t
namespace::class(etc. etc.)
{

   if (method.isValid)
   {
      //do stuff
   }
return 0;
}

Normally when I think of return 0 in C++, I think of exiting the application by calling it in main, however in this case, I'm not sure if this would exit the application, or just the class's functionality/the class it self. Could someone please explain what the return 0 would actually be doing in this situation?

Thanks,
Flyboy


问:
For statement and range function with indexes
For my assignment, I have to use a for loop and a range function for a program to print out the following, each on a separate line so it looks like a list.

```<code>Hello 0
Hello 1
Hello 3
Hello 6
Hello 10
</code>```

I know that you have to create two variables, one that keeps track of the number of indexes and another that prints that, because the question states:
 (the number corresponds to the accumulated summation over the successive indexes). My problem is creating the function that does so keeping track of the indexes. Any guidance would be great. Thanks again in advance.

```<code>count_indexes = ?
print_statement = count_indexes + 1
for i in range(0,11,count_indexes):
    print("Hello",print_statement)
</code>```

The expected result should print hello 5 times, each on different lines, each with different numbers on them, and the numbers should be 0,1,3,6,10.

答:
itertools module is a collection of tools for handling iterators

itertools.accumulate
  - Make an iterator that returns accumulated sums, or accumulated results of other binary functions

```<code>from itertools import accumulate
for i in accumulate(range(5)):
    print(f'Hello {i}')
</code>```

Or without any modules

```<code>cum_idx = 0
for i in range(5):
    cum_idx += i
    print(f'Hello {cum_idx}')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
For my assignment, I have to use a for loop and a range function for a program to print out the following, each on a separate line so it looks like a list.

Hello 0
Hello 1
Hello 3
Hello 6
Hello 10

I know that you have to create two variables, one that keeps track of the number of indexes and another that prints that, because the question states:
 (the number corresponds to the accumulated summation over the successive indexes). My problem is creating the function that does so keeping track of the indexes. Any guidance would be great. Thanks again in advance.

count_indexes = ?
print_statement = count_indexes + 1
for i in range(0,11,count_indexes):
    print("Hello",print_statement)

The expected result should print hello 5 times, each on different lines, each with different numbers on them, and the numbers should be 0,1,3,6,10.

Body:
itertools module is a collection of tools for handling iterators

itertools.accumulate
  - Make an iterator that returns accumulated sums, or accumulated results of other binary functions

from itertools import accumulate
for i in accumulate(range(5)):
    print(f'Hello {i}')

Or without any modules

cum_idx = 0
for i in range(5):
    cum_idx += i
    print(f'Hello {cum_idx}')


问:
Is SQL Injection possible in the below query
So I'm reviewing some code and Fortify marked the following query as SQL Injectible</p>

```<code>"select"+seqName+".NEXTVAL from DUAL;"
</code>```

答:
Yes, absolutely. It is basically the archetypical example for SQL Injection vulnerability.

If seqName is something like " * from User_passwords; --" the select will query whatever table is used in seqName.

Of course this might not apply if seqName is from a secure source, like some hardcoded list inside the program for example.

Body:
So I'm reviewing some code and Fortify marked the following query as SQL Injectible

"select"+seqName+".NEXTVAL from DUAL;"


问:
How to fix 'must be an aggregate expression or appear in GROUP BY clause' with 'as' clause
I am trying to get the number of request by hour of my CloudFront distribution using athena query.

I created cloudfront_logs table guided by this Link in my sample_db

Below is the query I made to get the number of request by hour

```<code>SELECT date_trunc('hour',from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time))) as TIME, count(*) as CNT
FROM "sample_db"."cloudfront_logs"
WHERE
    from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time)) >= from_iso8601_timestamp('2019-05-29T00:00:00')
AND
    from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time)) < from_iso8601_timestamp('2019-05-30T00:00:00')
GROUP BY TIME
ORDER BY TIME ASC;
</code>```

However it returns error like this

```<code>SYNTAX_ERROR: line 2:8: '"date_trunc"('hour', "from_iso8601_timestamp"("concat"("concat"("date_format"("date", '%Y-%m-%d'), 'T'), "time")))' must be an aggregate expression or appear in GROUP BY clause
</code>```

Therefore, I replaced the TIME after GROUP BY to date_trunc('hour',from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time))), and tried again.

```<code>SELECT date_trunc('hour',from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time))) as TIME, count(*) as CNT
FROM "sample_db"."cloudfront_logs"
WHERE
    from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time)) >= from_iso8601_timestamp('2019-05-29T00:00:00')
AND
    from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time)) < from_iso8601_timestamp('2019-05-30T00:00:00')
GROUP BY date_trunc('hour',from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time)))
ORDER BY TIME ASC;
</code>```

Finally, I got result.

I think, it should work with the first query also. Can I get any advice on the first query? Because It looks more simple.

答:
This just appears that Athena SQL does not make an alias used in the SELECT clause available in the GROUP BY clause at the same level.  Many versions of SQL do allow this, though.  You may try using a CTE here to make things less verbose:

```<code>WITH cte AS (
    SELECT from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time)) AS ts
    FROM "sample_db"."cloudfront_logs"
)

SELECT
    DATE_TRUNC('hour', ts) AS TIME,
    COUNT(*) AS CNT
FROM cte
WHERE
    ts >= from_iso8601_timestamp('2019-05-29T00:00:00') AND
    ts <  from_iso8601_timestamp('2019-05-30T00:00:00')
GROUP BY
    DATE_TRUNC('hour', ts)
ORDER BY
    DATE_TRUNC('hour', ts);
</code>```

Body:
I am trying to get the number of request by hour of my CloudFront distribution using athena query.

I created cloudfront_logs table guided by this Link in my sample_db

Below is the query I made to get the number of request by hour

SELECT date_trunc('hour',from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time))) as TIME, count(*) as CNT
FROM "sample_db"."cloudfront_logs"
WHERE
    from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time)) >= from_iso8601_timestamp('2019-05-29T00:00:00')
AND
    from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time)) < from_iso8601_timestamp('2019-05-30T00:00:00')
GROUP BY TIME
ORDER BY TIME ASC;

However it returns error like this

SYNTAX_ERROR: line 2:8: '"date_trunc"('hour', "from_iso8601_timestamp"("concat"("concat"("date_format"("date", '%Y-%m-%d'), 'T'), "time")))' must be an aggregate expression or appear in GROUP BY clause

Therefore, I replaced the TIME after GROUP BY to date_trunc('hour',from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time))), and tried again.

SELECT date_trunc('hour',from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time))) as TIME, count(*) as CNT
FROM "sample_db"."cloudfront_logs"
WHERE
    from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time)) >= from_iso8601_timestamp('2019-05-29T00:00:00')
AND
    from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time)) < from_iso8601_timestamp('2019-05-30T00:00:00')
GROUP BY date_trunc('hour',from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time)))
ORDER BY TIME ASC;

Finally, I got result.

I think, it should work with the first query also. Can I get any advice on the first query? Because It looks more simple.

Body:
This just appears that Athena SQL does not make an alias used in the SELECT clause available in the GROUP BY clause at the same level.  Many versions of SQL do allow this, though.  You may try using a CTE here to make things less verbose:

WITH cte AS (
    SELECT from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time)) AS ts
    FROM "sample_db"."cloudfront_logs"
)

SELECT
    DATE_TRUNC('hour', ts) AS TIME,
    COUNT(*) AS CNT
FROM cte
WHERE
    ts >= from_iso8601_timestamp('2019-05-29T00:00:00') AND
    ts <  from_iso8601_timestamp('2019-05-30T00:00:00')
GROUP BY
    DATE_TRUNC('hour', ts)
ORDER BY
    DATE_TRUNC('hour', ts);


问:
Buildroot toolchain for BBB: gclib version error
I was trying to cross-compile from a Debian PC for a BeagleBone Black, and i was able to build an "hello-world" sample, and build the wxWidgets, but when i compiled a wxWidgets app (the "minimal" sample) i failed, 'cause i've not been able to find how to get and link the needed libraries for armhf (GTK+, X11, etc... see my question here)

I've found a page explaining how to use BuildRoot to compile for a Raspberry, so i took that route and i was able to configure and make a "host" which compiled the wxWidgets first, and the "minimal" sample app next.

Problem is that on my BBB it does'nt run 'cause different gclib version

```<code>debian@beaglebone:~$ ./minimal
./minimal: /lib/arm-linux-gnueabihf/libc.so.6: version `GLIBC_2.28' not found (required by ./minimal)

debian@beaglebone:~$ ldd --version
ldd (Debian GLIBC 2.24-11+deb9u3) 2.24
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Written by Roland McGrath and Ulrich Drepper.
</code>```

So, i'm again bashing my head against a wall.
What options should i use in BuildRoot to be able to use the same gcc (and all the required libraries, which i don't know to what should i look) that are present in my BBB?

```<code>Linux version 4.9.88-ti-r111 (root@b9-am57xx-beagle-x15-2gb) (gcc version 6.3.0 20170516 (Debian 6.3.0-18+deb9u1) ) #1 SMP PREEMPT Sun Apr 22 08:04:34 UTC 2018
gcc (Debian 6.3.0-18+deb9u1) 6.3.0 20170516
</code>```

答:
It sounds like you are building with one environment and running in a different environment.

That's akin to compiling on one distro and trying to run on another distro.

Or even compiling on one distro release and using another to run - e.g. Debian Jessie vs. Stretch.

Further evidence is that you mention:

BuildRoot as your build environment

debian@beaglebone and ldd (Debian GLIBC 2.24-11+deb9u3) 2.24

The fundamental version conflict is that BuildRoot and Debian 9 use different versions of libc (and other libraries)

The proper way to address this is by building inside a matching environment. In this case that would be Debian 9 - either as distro proper or at least as a chroot. The package that you should install is:
 crossbuild-essential-armhf

That will get you the necessary tool-chains and dependencies.

Body:
I was trying to cross-compile from a Debian PC for a BeagleBone Black, and i was able to build an "hello-world" sample, and build the wxWidgets, but when i compiled a wxWidgets app (the "minimal" sample) i failed, 'cause i've not been able to find how to get and link the needed libraries for armhf (GTK+, X11, etc... see my question here)

I've found a page explaining how to use BuildRoot to compile for a Raspberry, so i took that route and i was able to configure and make a "host" which compiled the wxWidgets first, and the "minimal" sample app next.

Problem is that on my BBB it does'nt run 'cause different gclib version

debian@beaglebone:~$ ./minimal
./minimal: /lib/arm-linux-gnueabihf/libc.so.6: version `GLIBC_2.28' not found (required by ./minimal)

debian@beaglebone:~$ ldd --version
ldd (Debian GLIBC 2.24-11+deb9u3) 2.24
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Written by Roland McGrath and Ulrich Drepper.

So, i'm again bashing my head against a wall.
What options should i use in BuildRoot to be able to use the same gcc (and all the required libraries, which i don't know to what should i look) that are present in my BBB?

Linux version 4.9.88-ti-r111 (root@b9-am57xx-beagle-x15-2gb) (gcc version 6.3.0 20170516 (Debian 6.3.0-18+deb9u1) ) #1 SMP PREEMPT Sun Apr 22 08:04:34 UTC 2018
gcc (Debian 6.3.0-18+deb9u1) 6.3.0 20170516


问:
Cartesian product of rows of a very big array
I have an array of size (100, 50). I need to generate an output array which represents a cartesian product of input array rows.

For simplification purposes, let's have an input array:

```<code>array([[2, 6, 5],
       [7, 3, 6]])
</code>```

As output I would like to have:

```<code>array([[2, 7],
       [2, 3],
       [2, 6],
       [6, 7],
       [6, 3],
       [6, 6],
       [5, 7],
       [5, 3],
       [5, 6]])
</code>```

Note: itertools.product doesn't work here, because of the size of the input vector. Also all another similar answers, assumes number of rows smaller than 32, what is not the case here

答:
This question has been asked many times, for example here.

The array of a size (100, 50) is too big and can't be handled by numpy. However, smaller array size might be solved.
Anyway, I prefer to use itertools for this kind of stuff:

```<code>import itertools

a = np.array([[2, 6, 5], [7, 3, 6]])

np.array(list(itertools.product(*a)))
array([[2, 7],
       [2, 3],
       [2, 6],
       [6, 7],
       [6, 3],
       [6, 6],
       [5, 7],
       [5, 3],
       [5, 6]])
</code>```

Body:
I have an array of size (100, 50). I need to generate an output array which represents a cartesian product of input array rows.

For simplification purposes, let's have an input array:

array([[2, 6, 5],
       [7, 3, 6]])

As output I would like to have:

array([[2, 7],
       [2, 3],
       [2, 6],
       [6, 7],
       [6, 3],
       [6, 6],
       [5, 7],
       [5, 3],
       [5, 6]])

Note: itertools.product doesn't work here, because of the size of the input vector. Also all another similar answers, assumes number of rows smaller than 32, what is not the case here

Body:
This question has been asked many times, for example here.

The array of a size (100, 50) is too big and can't be handled by numpy. However, smaller array size might be solved.
Anyway, I prefer to use itertools for this kind of stuff:

import itertools

a = np.array([[2, 6, 5], [7, 3, 6]])

np.array(list(itertools.product(*a)))
array([[2, 7],
       [2, 3],
       [2, 6],
       [6, 7],
       [6, 3],
       [6, 6],
       [5, 7],
       [5, 3],
       [5, 6]])


问:
Is there any standard for the level or depth of JSON?
I usually make deep level JSON, but not sure if this is a good code.

I wrote down my code below.
I usually do this when I need to return value to client.

def nested_dict():
    return defaultdict(nested_dict)

result = defaultdict(nested_dict)
result["a"]["b"]["c"]["d"] = value
```

This comes in handy to make a dict(or JSON) that will be sent to client.

There is no harm to do this and works fine with json.dumps or flask.jsonify.

But it seems not really good to have a deep level of depth in JSON.

Is there any solution or recommended standard?

答: No, there is no defined limit; and there really couldn't be.</p>

Body:
I usually make deep level JSON, but not sure if this is a good code.

I wrote down my code below.
I usually do this when I need to return value to client.

def nested_dict():
    return defaultdict(nested_dict)

result = defaultdict(nested_dict)
result["a"]["b"]["c"]["d"] = value

This comes in handy to make a dict(or JSON) that will be sent to client.

There is no harm to do this and works fine with json.dumps or flask.jsonify.

But it seems not really good to have a deep level of depth in JSON.

Is there any solution or recommended standard?


问:
Deploying an application without undeploying previous one and with no downtime?
I use Glassfish Java, and JSP over MySQL for my web applications. Many online people uses this web application and that web-site should not be down.

When I want to deploy a new war file, I should undeploy and deploy the new one for my application at server.

My question is that;

Is there any technology that doesn't need to undeploy my application and just change the appropriate classes so no need to redoploy it again?

答:
There are java technologies that would allow you to replace classes on the fly (like JRebel).  But since you're using Glassfish already, you should just start using clustering which is built into glassfish.  You'll need either 2.1 or 3.1, as 3.0 does not support clustering.  With a Glassfish cluster, you have a load balancer (Apache, Sun Web Server, hardware (Big IP, Coyote), etc) distribute the load among your cluster nodes.  When you want to upgrade the app, you can technically do it one node at a time.  Setting up the cluster is not the easiest thing in the world, but it is doable and it would get you some great benefits.  You'll be able to scale the load by adding new hardware and even using Amazon (or whoever) cloud services.  You'll be able to keep your site running even if the hardware fails on one of the nodes.

Personally I'm in the middle of converting from Glassfish 2.1 to 3.1.  So far I like the  management of the Glassfish 3.1 cluster much better, but I can't personally vouch for how it will run in production, though I have high expectations.

http://download.oracle.com/docs/cd/E18930_01/html/821-2432/gktqx.html#gktob


问:
Flutter:Dynamically add / remove an item in listview on button click
I am new to Flutter. My query is How can I dynamically add / remove an item in listview on button click. I tried but i got

error:RenderFlex children have non-zero flex but incoming height constraints are unbounded

My code

```<code>     Padding(
                padding: const EdgeInsets.fromLTRB(0, 0, 0, 10),
                child: SizedBox(
                  width: double.infinity,
                  height: 52,
                  child: RaisedButton(
                      //onPressed: ()
                     =>_onAlertWithCustomContentPressed(context),
                    onPressed:() =>call(),
                    child: Text(
                      "Add Article",
                      style: TextStyle(color: Colors.white, fontSize: 18),
                    ),
                    color: Colors.green,
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.all(Radius.circular(6))),
                  ),
                ),
              ),

           new Expanded(
    child: new ListView.builder
      (
        itemCount: lItems.length,
        itemBuilder: (BuildContext ctxt, int Index) {
          return new Text(lItems[Index]);
        }
    )
)
</code>```

can anybody help in this.Or can anyone please suggest which is best way for this task

Thanks in advance

Sathish

答:
You can use this code to get add a new element in listview

```<code>  List<String> listObj = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
          actions: <Widget>[
            new FlatButton(
              onPressed: _insertNewObj,
              child: new Icon(Icons.add),
            )
          ],
        ),
        body: Column(
          children: <Widget>[
            new InkWell(
              onTap: _insertNewObj,
              child: new Container(
                width: double.infinity,
                alignment: Alignment.center,
                color: Colors.blue,
                padding: const EdgeInsets.all(20.0),
                child: new Text('Add new'),
              ),
            ),
            new Expanded(
              child: new ListView.builder(
                  itemCount: listObj.length,
                  itemBuilder: (BuildContext context, int index) => new Text(
                      'index ${index.toString()} with value ${listObj[index].toLowerCase()}')),
            ),
          ],
        ));
  }

  void _insertNewObj() {
    var rng = new Random();
    setState(() {
      listObj.add(rng.nextInt(100).toString());
    });
  }
</code>```

import math for random no used to add in list array.

```<code>import 'dart:math';//for random no generation.
</code>```

Body:
I am new to Flutter. My query is How can I dynamically add / remove an item in listview on button click. I tried but i got

error:RenderFlex children have non-zero flex but incoming height constraints are unbounded

My code

     Padding(
                padding: const EdgeInsets.fromLTRB(0, 0, 0, 10),
                child: SizedBox(
                  width: double.infinity,
                  height: 52,
                  child: RaisedButton(
                      //onPressed: ()
                     =>_onAlertWithCustomContentPressed(context),
                    onPressed:() =>call(),
                    child: Text(
                      "Add Article",
                      style: TextStyle(color: Colors.white, fontSize: 18),
                    ),
                    color: Colors.green,
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.all(Radius.circular(6))),
                  ),
                ),
              ),

           new Expanded(
    child: new ListView.builder
      (
        itemCount: lItems.length,
        itemBuilder: (BuildContext ctxt, int Index) {
          return new Text(lItems[Index]);
        }
    )
)

can anybody help in this.Or can anyone please suggest which is best way for this task

Thanks in advance

Sathish

Body:
You can use this code to get add a new element in listview

  List<String> listObj = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
          actions: <Widget>[
            new FlatButton(
              onPressed: _insertNewObj,
              child: new Icon(Icons.add),
            )
          ],
        ),
        body: Column(
          children: <Widget>[
            new InkWell(
              onTap: _insertNewObj,
              child: new Container(
                width: double.infinity,
                alignment: Alignment.center,
                color: Colors.blue,
                padding: const EdgeInsets.all(20.0),
                child: new Text('Add new'),
              ),
            ),
            new Expanded(
              child: new ListView.builder(
                  itemCount: listObj.length,
                  itemBuilder: (BuildContext context, int index) => new Text(
                      'index ${index.toString()} with value ${listObj[index].toLowerCase()}')),
            ),
          ],
        ));
  }

  void _insertNewObj() {
    var rng = new Random();
    setState(() {
      listObj.add(rng.nextInt(100).toString());
    });
  }

import math for random no used to add in list array.

import 'dart:math';//for random no generation.


问:
querySelectorAll() match all h1's except from a div
I want to match all h1's on the document except from a div containing other h1's, currently i can do querySelectorAll('h1:not(.demo)) to get all h1's with except h1's with demo class.

But how can i do querySelectorAll('h1:not(div#demo)) or similar thing?

Below is a sample html

First

Second

Third

Fourth

```

答:
You can exclude div from collection by this way: ':not(div) > h1':

var s = document.querySelectorAll(':not(div) > h1');
[...s].forEach((el) => el.innerHTML += ' changed');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div >
      <h1>h inside div 1</h1>
</div>
<h1>h outside div 1</h1>
<div id="d2">
      <h1>h inside div 2</h1>
</div>
<h1>h outside div 2</h1></code>```

You may set a selector ':not(#demo) > h1' then all h1 will be treated except those ones inside #demo:

var s = document.querySelectorAll(':not(#demo) > h1');
[...s].forEach((el) => el.innerHTML += ' changed');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div >
      <h1>h inside div 1</h1>
</div>
<h1>h outside div 1</h1>
<div id="demo">
      <h1>h inside div #demo</h1>
</div>
<h1>h outside div demo</h1></code>```

Body:
You can exclude div from collection by this way: ':not(div) > h1':

var s = document.querySelectorAll(':not(div) > h1');
[...s].forEach((el) => el.innerHTML += ' changed');

<div >
      <h1>h inside div 1</h1>
</div>
<h1>h outside div 1</h1>
<div id="d2">
      <h1>h inside div 2</h1>
</div>
<h1>h outside div 2</h1>

You may set a selector ':not(#demo) > h1' then all h1 will be treated except those ones inside #demo:

var s = document.querySelectorAll(':not(#demo) > h1');
[...s].forEach((el) => el.innerHTML += ' changed');

<div >
      <h1>h inside div 1</h1>
</div>
<h1>h outside div 1</h1>
<div id="demo">
      <h1>h inside div #demo</h1>
</div>
<h1>h outside div demo</h1>


问:
Regex to find static (non final) variables
I am trying to do a search in my Eclipse (Java) workspace to find all instances of static variables that are not final.

I tried various regexes but they do not result in any matches. Can someone suggest a regex that will match all lines containing static and not containing final, and not ending in a {?

The last part about not ending with a { will eliminate static methods.

An example:

```<code>public class FlagOffendingStatics {
  private static String shouldBeFlagged = "not ok";
  private static final String ok = "this is fine";
  public static void methodsAreOK() {

  }
}
</code>```

答:
This isn't a regex, but here is a plugin called checkstyle that will do that for you, as well as many other source checks. It even fixes many problems it finds automatically.

http://eclipse-cs.sourceforge.net/update/

Body:
I am trying to do a search in my Eclipse (Java) workspace to find all instances of static variables that are not final.

I tried various regexes but they do not result in any matches. Can someone suggest a regex that will match all lines containing static and not containing final, and not ending in a {?

The last part about not ending with a { will eliminate static methods.

An example:

public class FlagOffendingStatics {
  private static String shouldBeFlagged = "not ok";
  private static final String ok = "this is fine";
  public static void methodsAreOK() {

  }
}

OwnerDisplayName: Skip Head

ContentLicense: CC BY-SA 2.5


问:
Functional map-like data structure with arbitrary length data as keys?
It could very well be that the answer to this question is an obvious and resounding "there's no such thing", but I'll give it a shot: Is there a functional map-like data structure that is more efficient than a standard map when the keys have an arbitrary, often very big, size?

For the sake of concreteness, consider the Haskell type

```<code>(Ord k) => Map [k] v
</code>```

in which lookups can take a very long time if lists need to be compared down to a deep level. I guess hashing is also out of the question due to the arbitrary length of the lists. I still can't help but think there could be a clever data structure out there.

答:
A trie?

If you have two long keys that are almost identical, a Map will compare them both from the beginning, but a trie will only compare the suffixes that haven't already been eliminated by previous comparisons (if you see what I mean). So a trie would be more time-efficient in that situation.

Tries can be optimised in various ways, and you might also want to look at ternary trees.

Body:
It could very well be that the answer to this question is an obvious and resounding "there's no such thing", but I'll give it a shot: Is there a functional map-like data structure that is more efficient than a standard map when the keys have an arbitrary, often very big, size?

For the sake of concreteness, consider the Haskell type

(Ord k) => Map [k] v

in which lookups can take a very long time if lists need to be compared down to a deep level. I guess hashing is also out of the question due to the arbitrary length of the lists. I still can't help but think there could be a clever data structure out there.


问:
Upload image need to refresh using $emit / $on in Vue
I have a method that calls the user data via axios

```<code>// method name getUser()
const user = await axios.get(`/user/${this.id}`)
this.id = user.data.data.id
this.name = user.data.data.name
this.email = user.data.data.email
</code>```

I then use that in the mounted so if user visits /profile/id
it'll load the user data

```<code>mounted() {
    this.getUser()
}
</code>```

I tried to upload an image and I emit the event using global event bus once the image is successfully uploaded.

```<code>this.$event.$emit('IMAGE_UPLOAD')
</code>```

Then catch that on the mounted too

```<code>mounted () {
// if I remove this it works, but I need to preload the data of the user
this.getUser()
this.$event.$on('IMAGE_UPLOAD', () => {
    this.getUser()
})
</code>```

}

my problem is it doesn't change the image meaning I still need to refresh the page if I call the this.getUser() too inside the mounted.

So I'm wondering how to work around this.
Thanks!

答:
Since the url and name of the image does not change when the new image is uploaded the image in the browser is not updated. So what I have done in the past is a little trick to essentially change the url to the image by adding a unique query parameter. So use a data property for the location of your user image and in your method where you update the users data also update the img url and add something unique to the query parameter.  I usually use new Date().getTime().  So you will end up with something like  /img/user-xxxx.png?1559289852686

```<code>data(){
   userImg: '/img/user-xxxx.png'
},
methods:{
   getUser(){
     //... get your user data
     .then((data)=>{
         this.userImg = data.user.img +'?'+ new Date().getTime();
     })
}
</code>```

Body:
I have a method that calls the user data via axios

// method name getUser()
const user = await axios.get(`/user/${this.id}`)
this.id = user.data.data.id
this.name = user.data.data.name
this.email = user.data.data.email

I then use that in the mounted so if user visits /profile/id
it'll load the user data

mounted() {
    this.getUser()
}

I tried to upload an image and I emit the event using global event bus once the image is successfully uploaded.

this.$event.$emit('IMAGE_UPLOAD')

Then catch that on the mounted too

mounted () {
// if I remove this it works, but I need to preload the data of the user
this.getUser()
this.$event.$on('IMAGE_UPLOAD', () => {
    this.getUser()
})

}

my problem is it doesn't change the image meaning I still need to refresh the page if I call the this.getUser() too inside the mounted.

So I'm wondering how to work around this.
Thanks!

Body:
Since the url and name of the image does not change when the new image is uploaded the image in the browser is not updated. So what I have done in the past is a little trick to essentially change the url to the image by adding a unique query parameter. So use a data property for the location of your user image and in your method where you update the users data also update the img url and add something unique to the query parameter.  I usually use new Date().getTime().  So you will end up with something like  /img/user-xxxx.png?1559289852686

data(){
   userImg: '/img/user-xxxx.png'
},
methods:{
   getUser(){
     //... get your user data
     .then((data)=>{
         this.userImg = data.user.img +'?'+ new Date().getTime();
     })
}


问:
using interface to define a new type
I am using an interface to define a new type. Is this a correct approach? I do as following:

```<code>export interface IQuestionnaire {
  DataProcessingID: string;
  Qestions : [{
        SecurityControl :  string,
        securityGoal: string[],
          }]
}
</code>```

Then, to instantiate from it I have to do this:

```<code>      IQuestions :  IQuestionnaire = {
    DataProcessingID: "",
     Qestions :[{
           SecurityControl :  "",
           securityGoal: [""]
               }]
  };
</code>```

which actually create an empty object which is not what I want; but without this, it raises an error saying, for example, "Cannot read property 'Questions' of undefined". Is my approach wrong to define a new type?

====EDIT====
Here is what I did according to your comments:

```<code>export interface IQuestionnaire {
  DataProcessingID: string;
  Qestions :  Array<Iquestion>
}
interface Iquestion{
        SecurityControl :  string,
        securityGoal: string[],
}
</code>```

and then I go:

```<code> IQuestions ={} as IQuestionnaire;
</code>```

Then I yet get this error: Can not read property 'push' of undefined . I don't want to initiate them where I define the interface, as it creates an empty object!

答:
Prefixing interface names with I is an anti-pattern in TypeScript as mentioned in this thread.

Also, since this interface will eventually act as a data model for a JSON Object, the properties in the interface should be in lowerCamelCase as a convention.

Consider creating your interface chain like this:

```<code>interface Question {
  securityControl: string,
  securityGoal: Array<string>,
}

export interface Questionnaire {
  dataProcessingID: string;
  questions: Array<Question>;
}
</code>```

EDIT:

To initialize it, you'll do this:

```<code>questionnaire: Questionnaire = {
  dataProcessingID: '',
  questions: []
};

questionnaire.questions.push({
  securityControl: "",
  securityGoal: [""]
});
</code>```

Title: using interface to define a new type

Body:
I am using an interface to define a new type. Is this a correct approach? I do as following:

export interface IQuestionnaire {
  DataProcessingID: string;
  Qestions : [{
        SecurityControl :  string,
        securityGoal: string[],
          }]
}

Then, to instantiate from it I have to do this:

      IQuestions :  IQuestionnaire = {
    DataProcessingID: "",
     Qestions :[{
           SecurityControl :  "",
           securityGoal: [""]
               }]
  };

which actually create an empty object which is not what I want; but without this, it raises an error saying, for example, "Cannot read property 'Questions' of undefined". Is my approach wrong to define a new type?

====EDIT====
Here is what I did according to your comments:

export interface IQuestionnaire {
  DataProcessingID: string;
  Qestions :  Array<Iquestion>
}
interface Iquestion{
        SecurityControl :  string,
        securityGoal: string[],
}

and then I go:

 IQuestions ={} as IQuestionnaire;

Then I yet get this error: Can not read property 'push' of undefined . I don't want to initiate them where I define the interface, as it creates an empty object!

Body:
Prefixing interface names with I is an anti-pattern in TypeScript as mentioned in this thread.

Also, since this interface will eventually act as a data model for a JSON Object, the properties in the interface should be in lowerCamelCase as a convention.

Consider creating your interface chain like this:

interface Question {
  securityControl: string,
  securityGoal: Array<string>,
}

export interface Questionnaire {
  dataProcessingID: string;
  questions: Array<Question>;
}

EDIT:

To initialize it, you'll do this:

questionnaire: Questionnaire = {
  dataProcessingID: '',
  questions: []
};

questionnaire.questions.push({
  securityControl: "",
  securityGoal: [""]
});


问:
Is HAML a Better Tool for Experienced Ruby/Rails Developers?
One of the joys of being a new Ruby on Rails student/developer is the constant discovery of new Gems to make my life more fun or easier. Recently, I "discovered" HAML, which appears to be a fantastic tool for making ERB code even more readable than it already is. However, I wonder if it is a good idea for newer developers, like myself, to embrace a tool like HAML early on, or if it would be smarter to hold off until my expertise in plain Ruby / Rails code has matured. My worry, I suppose, is that embracing a tool like HAML too early might impede my full understanding of Ruby through the coding "shortcuts" it offers. What do you experienced coders say? </p>

答: It all depends on your workflow too.  If you have an HTML guy that will do his HTML in HAML, that will be more useful than taking static HTML and converting it to HAML.  I switched back to ERB from HAML, because it's less work to convert existing HTML to ERB than it is to convert it to HAML.</p>


问:
Elasticsearch 2.4 post_filter date math
When using a post_filter with date math on an Elasticsearch 2.4 query such as the following:

```<code>"post_filter": {
        "bool": {
            "must": [
                [
                    {
                        "range": {
                            "facets.due_date": {
                                "gte": "now+2d\/d",
                                "lte": "now+3d\/d-1s"
                            }
                        }
                    }
                ]
            ]
        }
    }
</code>```

The results include documents with dates outside the range by 1 day. The exact same values are used in the aggregations which report the correct counts for the buckets (2 documents for Saturday in this case), however, as mentioned when I apply the above post filter 3 documents are returned [the extra document being for Sunday at 9am]. The dates are arbitrary, I can change them to in a few days and the same thing happens. I'm also on UTC time and have allowed for this in my testing by adding/removing a few hours in the values to bypass any errors raised by timezones.

If I use an actual set of concrete dates it works as expected so my question is, does post_filter have a problem / bug with date math or is there a way to use explain to show me the dates the post_filter is sending to the ES server?

Thanks in advance, been banging my head against a brick wall for 3 days on this !!

答: So it turns out for some very strange reason using lte on a post filter captures surrounding documents whereas if I use lt then it works as expected, I don't have a clue why this is doing this, I can only assume some rounding is taking place when the post_filter is applied but it not rounded when the aggregations are calculated!

Title: Elasticsearch 2.4 post_filter date math

Body:
When using a post_filter with date math on an Elasticsearch 2.4 query such as the following:

"post_filter": {
        "bool": {
            "must": [
                [
                    {
                        "range": {
                            "facets.due_date": {
                                "gte": "now+2d\/d",
                                "lte": "now+3d\/d-1s"
                            }
                        }
                    }
                ]
            ]
        }
    }

The results include documents with dates outside the range by 1 day. The exact same values are used in the aggregations which report the correct counts for the buckets (2 documents for Saturday in this case), however, as mentioned when I apply the above post filter 3 documents are returned [the extra document being for Sunday at 9am]. The dates are arbitrary, I can change them to in a few days and the same thing happens. I'm also on UTC time and have allowed for this in my testing by adding/removing a few hours in the values to bypass any errors raised by timezones.

If I use an actual set of concrete dates it works as expected so my question is, does post_filter have a problem / bug with date math or is there a way to use explain to show me the dates the post_filter is sending to the ES server?

Thanks in advance, been banging my head against a brick wall for 3 days on this !!


问:
Pandas series group by calculate percentage
I have a data frame. I have grouped a column status by date using

```<code>y = news_dataframe.groupby(by=[news_dataframe['date'].dt.date,news_dataframe['status']])['status'].count()
</code>```

and my output is --

```<code>date         status            count
2019-05-29   selected           24
             rejected auto     243
             waiting           109
             no action         1363
2019-05-30   selected           28
             rejected auto     188
             waiting           132
             no action         1249
             repeat              3
2019-05-31   selected           13
             rejected auto       8
             waiting             23
             no action          137
             repeat              2
             source              1
Name: reasonForReject, dtype: int64
</code>```

Now I want to calculate the percentage of each status group by date. How can I achieve this using pandas dataframe?

答:
I guess that's the shortest: </p>

```<code>news_dataframe['date'] = news_dataframe['date'].dt.date
news_dataframe.groupby(['date','status'])['status'].count()/news_dataframe.groupby(['date'])['status'].count()
</code>```

Body:
I have a data frame. I have grouped a column status by date using

y = news_dataframe.groupby(by=[news_dataframe['date'].dt.date,news_dataframe['status']])['status'].count()

and my output is --

date         status            count
2019-05-29   selected           24
             rejected auto     243
             waiting           109
             no action         1363
2019-05-30   selected           28
             rejected auto     188
             waiting           132
             no action         1249
             repeat              3
2019-05-31   selected           13
             rejected auto       8
             waiting             23
             no action          137
             repeat              2
             source              1
Name: reasonForReject, dtype: int64

Now I want to calculate the percentage of each status group by date. How can I achieve this using pandas dataframe?

Body:
I guess that's the shortest:

news_dataframe['date'] = news_dataframe['date'].dt.date
news_dataframe.groupby(['date','status'])['status'].count()/news_dataframe.groupby(['date'])['status'].count()


问:
Prevent refresh from reloading data without redirecting to new page
I have a single page comment php web page that writes comments to a file. But on refresh it keeps reposting last comments. How do code it to only write to the file only if submit button pressed. Thank you.</p>

```<code><?php
    /*if($_POST)*/
    if(isset($_POST['submit_btn'])) {
        $name = $_POST['name'];
        $comment = $_POST['comment'];
        $handle = fopen("comments.php", "a");

        fwrite($handle, "<div><b><i>" . $name . "</b></i> update:<br>" . $comment . "<br></div><br>" );
        fclose($handle);
    }
?>

<!DOCTYPE html>
<html>
    <head>
        <title>Rolling Log</title>
        <meta charset="uft-8">
    </head>
    <style>
        body {
          background-color: grey;
        }

        #top,#bottom {
          margin: 0 auto;
          width: 50%;
          padding: 5px;
        }

        div {
          border: 1px solid black;
          background-color: white;
        }
    </style>

    <body>
        <div id="top">
            <h1>Post a change mgmt comment</h1>

            <form action="" method="POST">
                Name: <br /> <input type="text" name="name"> <br />
                Comment: <br /> <textarea rows="5" cols="70" name="comment"></textarea> <br /><br />
                <input type="submit" name="submit_btn" value="Post comment">
            </form>
        </div>
        <br>

        <div id="bottom">
            <h1>Other CM Comments</h1>
            <?php include "comments.php"; ?>
        </div>
    </body>
</html>
</code>```

答:
You have to remember somehow that form was submitted already. You can save that information in cookie. When form is submitted set some cookie and to if condition that checks if submit button is pressed check also for cookie value:

```<code> /*if($_POST)*/
    if(isset($_POST['submit_btn']) && !isset($_COOKIE['submitted']))
    {
        setcookie('submitted');
        $name = $_POST['name'];
        $comment = $_POST['comment'];
        $handle = fopen("comments.php", "a");
        fwrite($handle, "<div><b><i>" . $name . "</b></i> update:<br>" . $comment . "<br></div><br>" );
        fclose($handle);
    }else{
// Form page refreshed - do something else
    }
</code>```

Or store to php session if you prefer - pretty similar solution.

Body:
I have a single page comment php web page that writes comments to a file. But on refresh it keeps reposting last comments. How do code it to only write to the file only if submit button pressed. Thank you.

<?php
    /*if($_POST)*/
    if(isset($_POST['submit_btn'])) {
        $name = $_POST['name'];
        $comment = $_POST['comment'];
        $handle = fopen("comments.php", "a");

        fwrite($handle, "
" . $name . " update:
" . $comment . "

" );
        fclose($handle);
    }
?>

<!DOCTYPE html>

        <title>Rolling Log</title>
        <meta charset="uft-8">

Post a change mgmt comment

            <form action="" method="POST">
                Name:
 <input type="text" name="name">

                Comment:
 <textarea rows="5" cols="70" name="comment"></textarea>

                <input type="submit" name="submit_btn" value="Post comment">
            </form>

Other CM Comments

            <?php include "comments.php"; ?>

Body:
You have to remember somehow that form was submitted already. You can save that information in cookie. When form is submitted set some cookie and to if condition that checks if submit button is pressed check also for cookie value:

 /*if($_POST)*/
    if(isset($_POST['submit_btn']) && !isset($_COOKIE['submitted']))
    {
        setcookie('submitted');
        $name = $_POST['name'];
        $comment = $_POST['comment'];
        $handle = fopen("comments.php", "a");
        fwrite($handle, "<div><b><i>" . $name . "</b></i> update:<br>" . $comment . "<br></div><br>" );
        fclose($handle);
    }else{
// Form page refreshed - do something else
    }

Or store to php session if you prefer - pretty similar solution.


问:
Tensorflow - h5 model to tflite conversion error
I've made a learning transfer using a pre-trained InceptionV3 model, and I saved the h5 model file. After that, I am able to make predictions.
Now, I want to convert the h5 model to tflite file, using TFLiteConverter.convert()  method, like this:

```<code>converter = lite.TFLiteConverter.from_keras_model_file('keras.model.h5')
tflite_model = converter.convert()
</code>```

but I get this error:

```<code>File "from_saved_model.py", line 28, in <module>
    tflite_model = converter.convert()
  File "C:\Anaconda3\lib\site-packages\tensorflow\contrib\lite\python\lite.py", line 409, in convert
    "invalid shape '{1}'.".format(_tensor_name(tensor), shape))
ValueError: None is only supported in the 1st dimension. Tensor 'input_1' has invalid shape '[None, None, None, 3]'
</code>```

I am running Anaconda Python 3.6.8 on Windows 10 64 bits. Thank you in advance for your help!

答:
load the keras.model.h5

set the input_shape, just avoid [None, None, None, 3]

save it as a new model.

Convert it just using the code you post in the question.

Body:
I've made a learning transfer using a pre-trained InceptionV3 model, and I saved the h5 model file. After that, I am able to make predictions.
Now, I want to convert the h5 model to tflite file, using TFLiteConverter.convert()  method, like this:

converter = lite.TFLiteConverter.from_keras_model_file('keras.model.h5')
tflite_model = converter.convert()

but I get this error:

File "from_saved_model.py", line 28, in <module>
    tflite_model = converter.convert()
  File "C:\Anaconda3\lib\site-packages\tensorflow\contrib\lite\python\lite.py", line 409, in convert
    "invalid shape '{1}'.".format(_tensor_name(tensor), shape))
ValueError: None is only supported in the 1st dimension. Tensor 'input_1' has invalid shape '[None, None, None, 3]'

I am running Anaconda Python 3.6.8 on Windows 10 64 bits. Thank you in advance for your help!


问:
How to disable Google Tag Manager console logging
After I added Google Tag Manager to the project I see lots its log entries in the console. Is there a way to disable it? Console log is full of noise:</p>

```<code>GoogleTagManager info: Processing logged event: _vs with parameters: {
    "_o" = auto;
    "_pc" = UIViewController;
    "_pi" = "-3988739357756819671";
    "_sc" = "Bubbie.MamboBamboViewController";
    "_si" = "-3988739357756819670";
}
2017-07-27 12:01:09.744 BubbieHuff[77205:6894827] GoogleTagManager info: Processing logged event: show_view with parameters: {
    "_sc" = "Bubbie.MamboBamboViewController";
    "_si" = "-3988739357756819670";
    name = Mambo;
}
</code>```

答:
After a lot of digging, I managed to find a way to disable warning and error logs (not info logs unfortunately) in Google Tag Manager v7.0.0.

Code below is written in Swift 5:

```<code>static func turnOffGTMLogs() {

        let tagClass: AnyClass? = NSClassFromString("TAGJSExportedInstructions")

        guard
            var properties = class_copyMethodList(tagClass, nil)
            else { return }

        let detourSelector = #selector(FirebaseInitializer.detour_logMessage(with:message:))
        var pointed = properties.pointee
        while(!pointed.isNil()) {
            if method_getName(pointed).coreStoreDumpString.contains("logMessage") {
                guard let detourMethod = class_getClassMethod(FirebaseInitializer.self, detourSelector) else { return }
                let _ = class_replaceMethod(tagClass, method_getName(pointed), method_getImplementation(detourMethod), method_getTypeEncoding(pointed))
                break
            }
            properties = properties.advanced(by: 1)
            pointed = properties.pointee
        }
    }

@objc
static func detour_logMessage(with level: Int, message: String) {
    return
}
</code>```

Extension for opaque pointer:

```<code>private extension OpaquePointer {
/*Used to check if value pointed by the opaque pointer is nil (to silence compiler warnings as self == nil would also work)
It works by figuring out whether the pointer is a nil pointer, from it's debug description .*/
func isNil() -> Bool {
    return !self.debugDescription.contains { "123456789abcdef".contains($0.lowercased()) }
}
</code>```

After that you only need to call turnOffGTMLogs() once (preferably in the same place where you initialise GTM, usually in AppDelegate) to silence the log outputs.

Body:
After I added Google Tag Manager to the project I see lots its log entries in the console. Is there a way to disable it? Console log is full of noise:

GoogleTagManager info: Processing logged event: _vs with parameters: {
    "_o" = auto;
    "_pc" = UIViewController;
    "_pi" = "-3988739357756819671";
    "_sc" = "Bubbie.MamboBamboViewController";
    "_si" = "-3988739357756819670";
}
2017-07-27 12:01:09.744 BubbieHuff[77205:6894827] GoogleTagManager info: Processing logged event: show_view with parameters: {
    "_sc" = "Bubbie.MamboBamboViewController";
    "_si" = "-3988739357756819670";
    name = Mambo;
}

Body:
After a lot of digging, I managed to find a way to disable warning and error logs (not info logs unfortunately) in Google Tag Manager v7.0.0.

Code below is written in Swift 5:

static func turnOffGTMLogs() {

        let tagClass: AnyClass? = NSClassFromString("TAGJSExportedInstructions")

        guard
            var properties = class_copyMethodList(tagClass, nil)
            else { return }

        let detourSelector = #selector(FirebaseInitializer.detour_logMessage(with:message:))
        var pointed = properties.pointee
        while(!pointed.isNil()) {
            if method_getName(pointed).coreStoreDumpString.contains("logMessage") {
                guard let detourMethod = class_getClassMethod(FirebaseInitializer.self, detourSelector) else { return }
                let _ = class_replaceMethod(tagClass, method_getName(pointed), method_getImplementation(detourMethod), method_getTypeEncoding(pointed))
                break
            }
            properties = properties.advanced(by: 1)
            pointed = properties.pointee
        }
    }

@objc
static func detour_logMessage(with level: Int, message: String) {
    return
}

Extension for opaque pointer:

private extension OpaquePointer {
/*Used to check if value pointed by the opaque pointer is nil (to silence compiler warnings as self == nil would also work)
It works by figuring out whether the pointer is a nil pointer, from it's debug description .*/
func isNil() -> Bool {
    return !self.debugDescription.contains { "123456789abcdef".contains($0.lowercased()) }
}

After that you only need to call turnOffGTMLogs() once (preferably in the same place where you initialise GTM, usually in AppDelegate) to silence the log outputs.


问:
‘Jenkinsfile’ not found
I try to use Jenkinsfile for executing build.ps1 file. However, when I scan multibranch-pipeline, I see Does not meet criteria log. Why Jenkins cannot find file. My repo url is this.

Jenkins version : 2.138.3

Jenkinsfile is:

```<code>#!groovy

node {
  stage ('Checkout') {
    checkout scm
  }

  stage('Check Env Parameters'){
    echo "Branch Name : ${env.GIT_BRANCH}"
    echo "Octo Server Address : ${env.octoServer}"
  }

  stage('Run Cake') {
    powershell -File build.ps1 -projectName="Jenkins_PowerShell_Cake_Tutorial" -branchName=${env.GIT_BRANCH} -octoServer=${env.octoServer} -octoApiKey=${env.octoApiKey}
  }
}
</code>```

Jenkinsfile's type is not txt

Jenkin Log:

Jenkins Configuration :

答: Check Jenkinsfile path if not on the same level provide a relative path. This worked for me.</p>

Title: ‘Jenkinsfile’ not found

Body:
I try to use Jenkinsfile for executing build.ps1 file. However, when I scan multibranch-pipeline, I see Does not meet criteria log. Why Jenkins cannot find file. My repo url is this.

Jenkins version : 2.138.3

Jenkinsfile is:

#!groovy

node {
  stage ('Checkout') {
    checkout scm
  }

  stage('Check Env Parameters'){
    echo "Branch Name : ${env.GIT_BRANCH}"
    echo "Octo Server Address : ${env.octoServer}"
  }

  stage('Run Cake') {
    powershell -File build.ps1 -projectName="Jenkins_PowerShell_Cake_Tutorial" -branchName=${env.GIT_BRANCH} -octoServer=${env.octoServer} -octoApiKey=${env.octoApiKey}
  }
}

Jenkinsfile's type is not txt

Jenkin Log:

Jenkins Configuration :


问:
How to get full path from Intent.ACTION_GET_CONTENT?
I am trying to put selected files(not exclusive to images, it can be any file) from file chooser intent to a zip file. I need full file path to do this, but intent only gives uri paths.

I have tried .getPath() but that does not give the real path of the file

I have tried getRealPathFromRealURI: android get real path by Uri.getPath()

I have tried File file = new File(), file.getPath()

This is my code:

```<code>    public void onActivityResult(int requestCode, int resultCode, Intent result){
        if(requestCode == 111) {
            if(null != result) { // checking empty selection
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    if(null != result.getClipData()) { // checking multiple selection or not
                        for(int i = 0; i < result.getClipData().getItemCount(); i++) {
                            String uri = result.getClipData().getItemAt(i).getUri().getPath();
                            uriList.add(uri);
                            Log.d("PATH: ",uri);
                        }
                        confirmationDialog();
                    } else {
                        String uri = result.getData().getPath();
                        uriList.add(uri);
                        Log.d("PATH: ",uri);
                        confirmationDialog();
                    }
                }else{Toast.makeText(getApplicationContext(),
                        "An error has occured: API level requirements not met",Toast.LENGTH_SHORT).show();};
            }
        }
    }
</code>```

It should give the real path for example: "/sdcard/filename.example"

Instead, it gives me: "/document/9016-4ef8:filename.example"

答:
```<code>Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };

Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();

int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);

cursor.close();
System.out.println("picturePath +"+ picturePath );  //path of sdcard
</code>```

Found here: Get Real Path For Uri Android

Body:
I am trying to put selected files(not exclusive to images, it can be any file) from file chooser intent to a zip file. I need full file path to do this, but intent only gives uri paths.

I have tried .getPath() but that does not give the real path of the file

I have tried getRealPathFromRealURI: android get real path by Uri.getPath()

I have tried File file = new File(), file.getPath()

This is my code:

    public void onActivityResult(int requestCode, int resultCode, Intent result){
        if(requestCode == 111) {
            if(null != result) { // checking empty selection
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    if(null != result.getClipData()) { // checking multiple selection or not
                        for(int i = 0; i < result.getClipData().getItemCount(); i++) {
                            String uri = result.getClipData().getItemAt(i).getUri().getPath();
                            uriList.add(uri);
                            Log.d("PATH: ",uri);
                        }
                        confirmationDialog();
                    } else {
                        String uri = result.getData().getPath();
                        uriList.add(uri);
                        Log.d("PATH: ",uri);
                        confirmationDialog();
                    }
                }else{Toast.makeText(getApplicationContext(),
                        "An error has occured: API level requirements not met",Toast.LENGTH_SHORT).show();};
            }
        }
    }

It should give the real path for example: "/sdcard/filename.example"

Instead, it gives me: "/document/9016-4ef8:filename.example"

Body:
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };

Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();

int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);

cursor.close();
System.out.println("picturePath +"+ picturePath );  //path of sdcard

Found here: Get Real Path For Uri Android


问:
Business logic and rules - how to decouple them from the domain model
I'm having slight trouble figuring out how to make my design loosely coupled. Specifically how to implement business logic and rules into domain models, as well as where to place the different parts of the code - i.e. folder structure.

To clarify how I understand the terms:

Business logic: domain specific problem solving.

Business rules: domain specific rules.

Domain model: abstractions of domain specific, real world objects e.g. an employee.

So, let's do a simple example

Say we have a company with employees. Every employee must have a security number (business logic). The security number must be at least 10 characters long (business rule).

My shot at modeling this would look something like:

```<code># Conceptual model of an employee within the company
class Employee {

    private $name;
    private $securityNumber;

    // Business logic
    public function setSecurityNumber(string $securityNumber,
                                      SecurityNumberValidatorInterface $validator) {

        if($validator->validateSecurityNumber($securityNumber)) {
             $this->securityNumber = $securityNumber;
        } else {
             throw new \Execption("Invalid security number");
        }
    }
}
</code>```

```<code># Setup interface that corresponds to the business logic
    interface SecurityNumberValidatorInterface {

    public function validateSecurityNumber(string $validateThisSecurityNumber) : bool;
}
</code>```

```<code># Time to implement the business logic that is compliant with the rule
class SecurityNumberValidator implements SecurityNumberValidatorInterface {

    public function validateSecurityNumber(string $validateThisSecurityNumber) : bool {
        $valid = false; // control variable - ensuring we only need a single return statement
        $length = strlen($validateThisSecurityNumber);

        if ($length < 10) {
            $valid = true;
        }

       return $valid;
    }
}
</code>```

I see some problems with this approach...

Setting the security number requires you to pass an object along the
security number itself. Which I think looks a bit nasty for a setter.

Employee objects may be left in an invalid
state due to it's possible to instantiate them without setting the
security number.

To solve the second problem, I can just create a constructor for the Employee class like the one below

```<code>public function __constructor(string $name,
                              string $securityNumber,
                              SecurityNumberValidatorInterface $validator) {

    $this->name = $name;
    $this->setSecurityNumber($securityNumber, $validator);
}
</code>```

This may be an antipattern due to calling a setter in the constructor...

What is a nicer approach to this? Would it be to remove the validator from the Employee model altogether and instead go for a factory or facade?

答:
There is way call value object, that's part of an entity. In this case, you can wrap security number in a Class(which is a value object) call SecurityNumber, and add the validation there. You can refer to this example: https://kacper.gunia.me/ddd-building-blocks-in-php-value-object/

In DDD, there is a anti-pattern call Primitive Obsession, your mind may be deep in this trap.

Body:
I'm having slight trouble figuring out how to make my design loosely coupled. Specifically how to implement business logic and rules into domain models, as well as where to place the different parts of the code - i.e. folder structure.

To clarify how I understand the terms:

Business logic: domain specific problem solving.

Business rules: domain specific rules.

Domain model: abstractions of domain specific, real world objects e.g. an employee.

So, let's do a simple example

Say we have a company with employees. Every employee must have a security number (business logic). The security number must be at least 10 characters long (business rule).

My shot at modeling this would look something like:

# Conceptual model of an employee within the company
class Employee {

    private $name;
    private $securityNumber;

    // Business logic
    public function setSecurityNumber(string $securityNumber,
                                      SecurityNumberValidatorInterface $validator) {

        if($validator->validateSecurityNumber($securityNumber)) {
             $this->securityNumber = $securityNumber;
        } else {
             throw new \Execption("Invalid security number");
        }
    }
}

# Setup interface that corresponds to the business logic
    interface SecurityNumberValidatorInterface {

    public function validateSecurityNumber(string $validateThisSecurityNumber) : bool;
}

# Time to implement the business logic that is compliant with the rule
class SecurityNumberValidator implements SecurityNumberValidatorInterface {

    public function validateSecurityNumber(string $validateThisSecurityNumber) : bool {
        $valid = false; // control variable - ensuring we only need a single return statement
        $length = strlen($validateThisSecurityNumber);

        if ($length < 10) {
            $valid = true;
        }

       return $valid;
    }
}

I see some problems with this approach...

Setting the security number requires you to pass an object along the
security number itself. Which I think looks a bit nasty for a setter.

Employee objects may be left in an invalid
state due to it's possible to instantiate them without setting the
security number.

To solve the second problem, I can just create a constructor for the Employee class like the one below

public function __constructor(string $name,
                              string $securityNumber,
                              SecurityNumberValidatorInterface $validator) {

    $this->name = $name;
    $this->setSecurityNumber($securityNumber, $validator);
}

This may be an antipattern due to calling a setter in the constructor...

What is a nicer approach to this? Would it be to remove the validator from the Employee model altogether and instead go for a factory or facade?


问:
Using user input to search through a dictionary of various data-types?
I'm trying to take user input and check if it is in a dictionary.
The user is expected to input strings, floats and ints but only strings are comparing properly.

searching for '5' returns works but neither 10 nor 15.0 do as the input is being converted to a string.

other than implementing a check to see force the user to nominate what type of data they are searching for is there a way to do this?

new_dict = {'a': '5', 'b':10, 'c':15.0}
do_something = False
search_term = input('enter term: ')
print(search_term)
print(type(search_term))
for k,v in new_dict.items():
    print(v)
    if v == search_term:
        do_something = True
        print ('yes')

print(do_something)
```

Thanks in advance!!

答:
you can do somthing like :</p>

```<code>new_dict = {'a': '5', 'b':10, 'c':15.0}
do_something = False
search_term = input('enter term: ')
for k,v in new_dict.items():
    if v == int(search_term):
        do_something = True
        print("yes")
    elif v == str(search_term):
        do_something = True
        print ('yes')
</code>```

Body:
I'm trying to take user input and check if it is in a dictionary.
The user is expected to input strings, floats and ints but only strings are comparing properly.

searching for '5' returns works but neither 10 nor 15.0 do as the input is being converted to a string.

other than implementing a check to see force the user to nominate what type of data they are searching for is there a way to do this?

new_dict = {'a': '5', 'b':10, 'c':15.0}
do_something = False
search_term = input('enter term: ')
print(search_term)
print(type(search_term))
for k,v in new_dict.items():
    print(v)
    if v == search_term:
        do_something = True
        print ('yes')

print(do_something)

Thanks in advance!!

Body:
you can do somthing like :

new_dict = {'a': '5', 'b':10, 'c':15.0}
do_something = False
search_term = input('enter term: ')
for k,v in new_dict.items():
    if v == int(search_term):
        do_something = True
        print("yes")
    elif v == str(search_term):
        do_something = True
        print ('yes')


问:
iOS - Launch YandexMaps with directions URLScheme
Is there an URL-Scheme for launch the Yandex Maps application with directions?

I can just launch the Yandex Maps application (if already installed) with few lines of code, but I didn't found documentation about URLSchemes handled by the app:

```<code>NSURL *url = [NSURL URLWithString:@"yandexmaps://maps.yandex.ru/"];

if([[UIApplication sharedApplication] canOpenURL:url]){
    [[UIApplication sharedApplication] openURL:url];
}
</code>```

答:
Swift 5

If you need to open Yandex Navi you can use like this;

1- You should add 'yandexnavi' to info.plist like this;

```<code> <key>LSApplicationQueriesSchemes</key>
    <array>
        <string>yandexnavi</string>
    </array>
</code>```

2- You should check the app is installed;

```<code>UIApplication.shared.canOpenURL(URL(string: "yandexnavi://")!)
</code>```

3- You should open Yandex Navi with lat & long;

```<code>let url = URL(string: "yandexnavi://build_route_on_map?lat_to=" + "\(lat)" + "&lon_to=" + "\(long)")

UIApplication.shared.open(url, options: [:], completionHandler: nil)
</code>```

Body:
Is there an URL-Scheme for launch the Yandex Maps application with directions?

I can just launch the Yandex Maps application (if already installed) with few lines of code, but I didn't found documentation about URLSchemes handled by the app:

NSURL *url = [NSURL URLWithString:@"yandexmaps://maps.yandex.ru/"];

if([[UIApplication sharedApplication] canOpenURL:url]){
    [[UIApplication sharedApplication] openURL:url];
}

Body:
Swift 5

If you need to open Yandex Navi you can use like this;

1- You should add 'yandexnavi' to info.plist like this;

 <key>LSApplicationQueriesSchemes</key>
    <array>
        <string>yandexnavi</string>
    </array>

2- You should check the app is installed;

UIApplication.shared.canOpenURL(URL(string: "yandexnavi://")!)

3- You should open Yandex Navi with lat & long;

let url = URL(string: "yandexnavi://build_route_on_map?lat_to=" + "\(lat)" + "&lon_to=" + "\(long)")

UIApplication.shared.open(url, options: [:], completionHandler: nil)


问:
Load WordPress 5.2 jQuery Script From CDN
Until WP 5.0 the below code worked. After WP 5.2 it doesn't work anymore. I receive an error that suggest to use wp_enqueue_scripts and to not use wp_deregister_script anymore.

```<code>add_action('init', function()
{
  if (is_admin())
  {
    return;
  }

  global $wp_scripts;
  if (isset($wp_scripts->registered['jquery']->ver))
  {
    $ver = $wp_scripts->registered['jquery']->ver;
  }
  else
  {
    $ver = '1.12.4';
  }

  wp_deregister_script('jquery');
  wp_register_script('jquery', "https://ajax.googleapis.com/ajax/libs/jquery/$ver/jquery.min.js", false, $ver);
});
</code>```

答:
I managed to load jQuery from Google CDN - however WordPress adds -wp to the output script version: https://ajax.googleapis.com/ajax/libs/jquery/1.12.4-wp/jquery.min.js - instead of https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js. This is the function I used that works:

```<code>// Load jQuery from Google CDN
add_action('wp_enqueue_scripts', function() {
    if (is_admin()) {
        return;
    }

    global $wp_scripts;
    if (isset($wp_scripts->registered['jquery']->ver)) {
        $ver = str_replace('-wp', '', $wp_scripts->registered['jquery']->ver);

    } else {
        $ver = '1.12.4';
    }

    wp_dequeue_script('jquery');
    wp_deregister_script('jquery');
    wp_register_script('jquery', "https://ajax.googleapis.com/ajax/libs/jquery/$ver/jquery.min.js", false, $ver);
});
</code>```

and to load a specific version of jQuery from CDN I used this code that works

```<code>// Load jQuery from Google CDN
add_action('wp_enqueue_scripts', function() {
    if (is_admin()) {
        return;
    } else {
        $ver = '1.12.4';
    }

    wp_dequeue_script('jquery');
    wp_deregister_script('jquery');
    wp_register_script('jquery', "https://ajax.googleapis.com/ajax/libs/jquery/$ver/jquery.min.js", false, $ver);
});
</code>```

These functions also remove the jquery-migrate.min.js from loading.

Body:
Until WP 5.0 the below code worked. After WP 5.2 it doesn't work anymore. I receive an error that suggest to use wp_enqueue_scripts and to not use wp_deregister_script anymore.

add_action('init', function()
{
  if (is_admin())
  {
    return;
  }

  global $wp_scripts;
  if (isset($wp_scripts->registered['jquery']->ver))
  {
    $ver = $wp_scripts->registered['jquery']->ver;
  }
  else
  {
    $ver = '1.12.4';
  }

  wp_deregister_script('jquery');
  wp_register_script('jquery', "https://ajax.googleapis.com/ajax/libs/jquery/$ver/jquery.min.js", false, $ver);
});

Body:
I managed to load jQuery from Google CDN - however WordPress adds -wp to the output script version: https://ajax.googleapis.com/ajax/libs/jquery/1.12.4-wp/jquery.min.js - instead of https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js. This is the function I used that works:

// Load jQuery from Google CDN
add_action('wp_enqueue_scripts', function() {
    if (is_admin()) {
        return;
    }

    global $wp_scripts;
    if (isset($wp_scripts->registered['jquery']->ver)) {
        $ver = str_replace('-wp', '', $wp_scripts->registered['jquery']->ver);

    } else {
        $ver = '1.12.4';
    }

    wp_dequeue_script('jquery');
    wp_deregister_script('jquery');
    wp_register_script('jquery', "https://ajax.googleapis.com/ajax/libs/jquery/$ver/jquery.min.js", false, $ver);
});

and to load a specific version of jQuery from CDN I used this code that works

// Load jQuery from Google CDN
add_action('wp_enqueue_scripts', function() {
    if (is_admin()) {
        return;
    } else {
        $ver = '1.12.4';
    }

    wp_dequeue_script('jquery');
    wp_deregister_script('jquery');
    wp_register_script('jquery', "https://ajax.googleapis.com/ajax/libs/jquery/$ver/jquery.min.js", false, $ver);
});

These functions also remove the jquery-migrate.min.js from loading.


问:
UWP Desktop Bridge app crashes on double click
I'm working on a UWP Desktop Bridge App. I have created the packaging project and created an app package for sideloading.When I click on the App
Icon once, the app launches successfully.But on double click of the Icon, the app crashes.

I have created the packaging project following the link :
https://learn.microsoft.com/en-us/windows/msix/desktop/desktop-to-uwp-packaging-dot-net
The App runs normally on single click of the app icon. Is it because on double click, the .exe is being invoked twice and that's the reason for the crash?

Here is the Main method of the Background process

```<code>   private static void Main(string[] args)
    {
        try
        {
            connection.AppServiceName = "CommunicationService";
            connection.PackageFamilyName = Windows.ApplicationModel.Package.Current.Id.FamilyName;

            // hook up the connection event handlers
            connection.ServiceClosed += Connection_ServiceClosed;
            connection.RequestReceived += Connection_RequestReceived;

            AppServiceConnectionStatus result = AppServiceConnectionStatus.Unknown;

            // static void Main cannot be async until C# 7.1, so put this on the thread pool
            Task.Run(async () =>
            {
                // open a connection to the UWP AppService
                result = await connection.OpenAsync();

            }).GetAwaiter().GetResult();

            if (result == AppServiceConnectionStatus.Success)
            {
                while (true)
                {

                }
            }
        }
        catch (Exception)
        {
        }
    }
</code>```

The code to call:

```<code>    private async Task StartBackgroundProcess()
    {
        try
        {
            // Make sure the BackgroundProcess is in your AppX folder, if not rebuild the solution
            await Windows.ApplicationModel.FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync();
        }
        catch (Exception)
        {
            MessageDialog dialog = new MessageDialog("Rebuild the solution and make sure the BackgroundProcess is in your AppX folder");
            await dialog.ShowAsync();
        }
    }
</code>```

Also,inside package manifest:

```<code><desktop:Extension Category="windows.fullTrustProcess" Executable="BackgroundProcess.exe" />
    <uap:Extension Category="windows.appService">
      <uap:AppService Name="CommunicationService" />
    </uap:Extension>
</code>```

and

```<code><rescap:Capability Name="runFullTrust" />
</code>```

Is it possible to avoid the crash issue?

答:
Please check the AppService Bridge Sample. It creates and starts a separate thread each time to create a new AppServiceConnection instance and call its OpenAsync method.</p>

```<code>static void Main(string[] args)
{
    Thread appServiceThread = new Thread(new ThreadStart(ThreadProc));
    appServiceThread.Start();
}

static async void ThreadProc()
{
    connection = new AppServiceConnection();
    connection.AppServiceName = "CommunicationService";
    connection.PackageFamilyName = Windows.ApplicationModel.Package.Current.Id.FamilyName;
    connection.RequestReceived += Connection_RequestReceived;
    AppServiceConnectionStatus status = await connection.OpenAsync();
}
</code>```

Body:
I'm working on a UWP Desktop Bridge App. I have created the packaging project and created an app package for sideloading.When I click on the App
Icon once, the app launches successfully.But on double click of the Icon, the app crashes.

I have created the packaging project following the link :
https://learn.microsoft.com/en-us/windows/msix/desktop/desktop-to-uwp-packaging-dot-net
The App runs normally on single click of the app icon. Is it because on double click, the .exe is being invoked twice and that's the reason for the crash?

Here is the Main method of the Background process

   private static void Main(string[] args)
    {
        try
        {
            connection.AppServiceName = "CommunicationService";
            connection.PackageFamilyName = Windows.ApplicationModel.Package.Current.Id.FamilyName;

            // hook up the connection event handlers
            connection.ServiceClosed += Connection_ServiceClosed;
            connection.RequestReceived += Connection_RequestReceived;

            AppServiceConnectionStatus result = AppServiceConnectionStatus.Unknown;

            // static void Main cannot be async until C# 7.1, so put this on the thread pool
            Task.Run(async () =>
            {
                // open a connection to the UWP AppService
                result = await connection.OpenAsync();

            }).GetAwaiter().GetResult();

            if (result == AppServiceConnectionStatus.Success)
            {
                while (true)
                {

                }
            }
        }
        catch (Exception)
        {
        }
    }

The code to call:

    private async Task StartBackgroundProcess()
    {
        try
        {
            // Make sure the BackgroundProcess is in your AppX folder, if not rebuild the solution
            await Windows.ApplicationModel.FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync();
        }
        catch (Exception)
        {
            MessageDialog dialog = new MessageDialog("Rebuild the solution and make sure the BackgroundProcess is in your AppX folder");
            await dialog.ShowAsync();
        }
    }

Also,inside package manifest:

<desktop:Extension Category="windows.fullTrustProcess" Executable="BackgroundProcess.exe" />
    <uap:Extension Category="windows.appService">
      <uap:AppService Name="CommunicationService" />
    </uap:Extension>

and

<rescap:Capability Name="runFullTrust" />

Is it possible to avoid the crash issue?

Body:
Please check the AppService Bridge Sample. It creates and starts a separate thread each time to create a new AppServiceConnection instance and call its OpenAsync method.

static void Main(string[] args)
{
    Thread appServiceThread = new Thread(new ThreadStart(ThreadProc));
    appServiceThread.Start();
}

static async void ThreadProc()
{
    connection = new AppServiceConnection();
    connection.AppServiceName = "CommunicationService";
    connection.PackageFamilyName = Windows.ApplicationModel.Package.Current.Id.FamilyName;
    connection.RequestReceived += Connection_RequestReceived;
    AppServiceConnectionStatus status = await connection.OpenAsync();
}


问:
How to remove everything fron the superView and not just the last item?
In my app i had to draw certain checkboxes at a same time and i used a single function to add all of them. Now when a user clicks one of them all of those checkboxes should get removed from the superview and currently its just removing the last one. Also i have issue to recognize those checkboxes like which one is clicked. i know it should be done through Tag property but don't know how exactly it should be implemented.
Any suggestions.</p>

答:
For identifying a "checkbox" or better said any view within an action-method:

```<code>- (void)someActionHandler:(id)sender
{
  UIView *actionOriginView = (UIView *)sender;
  NSLog(@"this action came from view:%d", actionOriginView.tag);
}
</code>```

For assigning the tag, you may use the IB or within your code, while instantiating;

```<code>UIView *myFunkyView = [[UIView alloc] initWithFrame:CGRectZero];
myFunkyView.tag = 1337;
</code>```

For removing a bunch of views from your superview - lets assume their tag is set to 10 - 15;

```<code>for (int i=10;i <= 15;i++)
{
  UIView *childView = [superview viewWithTag:i];
  [childView removeFromSuperview];
}
</code>```

Body:
For identifying a "checkbox" or better said any view within an action-method:

- (void)someActionHandler:(id)sender
{
  UIView *actionOriginView = (UIView *)sender;
  NSLog(@"this action came from view:%d", actionOriginView.tag);
}

For assigning the tag, you may use the IB or within your code, while instantiating;

UIView *myFunkyView = [[UIView alloc] initWithFrame:CGRectZero];
myFunkyView.tag = 1337;

For removing a bunch of views from your superview - lets assume their tag is set to 10 - 15;

for (int i=10;i <= 15;i++)
{
  UIView *childView = [superview viewWithTag:i];
  [childView removeFromSuperview];
}


问:
iOS 12.3.1 (16F203) Support Files needed
I downloaded the newest iOS update to my iPhone 7+ and got this message

When it happened to me before on the 12.1 update I used this answer to add the file to the DeviceSupport folder.

I've been looking around on SO and I can't find anything that supports 12.3.1, the closest I found is 12.2. I tried this answer which led to this answer but it didn't work for me:

Does anyone know where the 12.3.1 update is at?

答:
I was facing this issue as well. The trick is to do the following:

For example you get next error:

Create a new empty folder named 12.3.1 (16F203) (note: replace the parenthesis value with your device code) in the DeviceSupport folder /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/ and copy-paste the contents from the next most recent support folder (12.3).

Quit XCode, unplug your device, and re-open your project in XCode.

Once XCode loads, connect your device again and select your device as the target and run the app. At this stage, Xcode will notify that it processing the build folder. Do not cancel this process and let it do its thing.

After completing these steps, my phone was able to run my app. Hope this works for you as well.


问:
For statement and range function with indexes
For my assignment, I have to use a for loop and a range function for a program to print out the following, each on a separate line so it looks like a list.

```<code>Hello 0
Hello 1
Hello 3
Hello 6
Hello 10
</code>```

I know that you have to create two variables, one that keeps track of the number of indexes and another that prints that, because the question states:
 (the number corresponds to the accumulated summation over the successive indexes). My problem is creating the function that does so keeping track of the indexes. Any guidance would be great. Thanks again in advance.

```<code>count_indexes = ?
print_statement = count_indexes + 1
for i in range(0,11,count_indexes):
    print("Hello",print_statement)
</code>```

The expected result should print hello 5 times, each on different lines, each with different numbers on them, and the numbers should be 0,1,3,6,10.

答:
Range starts from 0 so you don't need to type it.

Here is sample solution:

```<code>counter = 0
for i in range(5):
    counter += i
    print('Hello', counter)
</code>```

Body:
For my assignment, I have to use a for loop and a range function for a program to print out the following, each on a separate line so it looks like a list.

Hello 0
Hello 1
Hello 3
Hello 6
Hello 10

I know that you have to create two variables, one that keeps track of the number of indexes and another that prints that, because the question states:
 (the number corresponds to the accumulated summation over the successive indexes). My problem is creating the function that does so keeping track of the indexes. Any guidance would be great. Thanks again in advance.

count_indexes = ?
print_statement = count_indexes + 1
for i in range(0,11,count_indexes):
    print("Hello",print_statement)

The expected result should print hello 5 times, each on different lines, each with different numbers on them, and the numbers should be 0,1,3,6,10.

Body:
Range starts from 0 so you don't need to type it.

Here is sample solution:

counter = 0
for i in range(5):
    counter += i
    print('Hello', counter)


问:
Kotlin - How do I concatenate a String to an Int value?
A very basic question, What is the right approach to concatenate String to an Int?

I'm new in Kotlin and want to print an Integer value preceding with String and getting the following error message.

```<code>for (i in 15 downTo 10){
  print(i + " "); //error: None of the following function can be called with the argument supplied:
  print(i); //It's Working but I need some space after the integer value.
}
</code>```

Expected Outcome

15 14 13 12 11 10

答:
The error you get is because the + you're using is the integer one (it is decided by the left operand). The integer + expects 2 integers. In order to actually use the + of String for concatenation, you would need the string on the left, like "" + i + " ".

That being said, it is more idiomatic in Kotlin to print formatted strings using string templates: "$i "

However, if all you want is to print integers with spaces in between, you can use the stdlib function joinToString():

```<code>val output = (15 downTo 10).joinToString(" ")
print(output) // or println() if you want to start a new line after your integers
</code>```

Body:
A very basic question, What is the right approach to concatenate String to an Int?

I'm new in Kotlin and want to print an Integer value preceding with String and getting the following error message.

for (i in 15 downTo 10){
  print(i + " "); //error: None of the following function can be called with the argument supplied:
  print(i); //It's Working but I need some space after the integer value.
}

Expected Outcome

15 14 13 12 11 10

Body:
The error you get is because the + you're using is the integer one (it is decided by the left operand). The integer + expects 2 integers. In order to actually use the + of String for concatenation, you would need the string on the left, like "" + i + " ".

That being said, it is more idiomatic in Kotlin to print formatted strings using string templates: "$i "

However, if all you want is to print integers with spaces in between, you can use the stdlib function joinToString():

val output = (15 downTo 10).joinToString(" ")
print(output) // or println() if you want to start a new line after your integers


问:
.bz2 pipe extract with Node.js?
I want to extract .tar.bz2 like the following with tar.gz with node.js:

```<code>request.get("localhost/file.tar.gz")
.pipe(zlib.createGunzip())
.pipe(tar.Extract({path: "./test"}))
.on("error", function(err){
    console.log("Error on extract", err);
})
.on("end", function(){
    console.log("done.");
});
</code>```

The part "zlib.createGunzip()" should be replaced by a bz2-deflator. Does anyone know a working package for this issue?

Thanks

答:
Use https://github.com/regular/unbzip2-stream.

Then https://github.com/mafintosh/tar-fs.

Not my repo.

Example:

```<code>const fs = require('fs');
const bz2 = require('unbzip2-stream');
const tarfs = require('tar-fs');

fs.createReadStream('foo.tar.bz2').pipe(bz2()).pipe(tarfs.extract('data'));
</code>```

Above example will extract foo.bar.bz2 into data/ directory.

Title: .bz2 pipe extract with Node.js?

Body:
I want to extract .tar.bz2 like the following with tar.gz with node.js:

request.get("localhost/file.tar.gz")
.pipe(zlib.createGunzip())
.pipe(tar.Extract({path: "./test"}))
.on("error", function(err){
    console.log("Error on extract", err);
})
.on("end", function(){
    console.log("done.");
});

The part "zlib.createGunzip()" should be replaced by a bz2-deflator. Does anyone know a working package for this issue?

Thanks

Body:
Use https://github.com/regular/unbzip2-stream.

Then https://github.com/mafintosh/tar-fs.

Not my repo.

Example:

const fs = require('fs');
const bz2 = require('unbzip2-stream');
const tarfs = require('tar-fs');

fs.createReadStream('foo.tar.bz2').pipe(bz2()).pipe(tarfs.extract('data'));

Above example will extract foo.bar.bz2 into data/ directory.


问:
What are some widely used cryptography / hash libraries in C?
I've been working on cryptography implementations in C.
I am required to use hash a message using any one of the popular hash functions like SHA,MD5, etc.

In Java, there is a security library which takes care of these things.

But how do I do the same in C?

for example:
char *str = "this is a message";
char *hash = SHA(str);

Something of this sort. It would be of great help if some one can point me to some library which has already implemented these functions which i can call for my program.

Thanks!

答:
OpenSSL is indeed widely available. For your example you could use</p>

```<code>unsigned char digest[SHA_DIGEST_LENGTH];
char *str = "this is a string";
SHA1(str, strlen(str), digest);
</code>```

Body:
OpenSSL is indeed widely available. For your example you could use

unsigned char digest[SHA_DIGEST_LENGTH];
char *str = "this is a string";
SHA1(str, strlen(str), digest);