问:
Prior to purchasing, how do I know if I'll be able to control an Android phone's camera focus?
I know that the setFocusMode function in Camera.Parameters allows a programmer to control the camera focus.

But how do you know if that function will work on any particular phone? It might return NULL, meaning that the phone does not support focus control for its camera.

Its easy to tell which Android phones on the market have autofocus.

But if a manufacturer says their phone has autofocus, does that mean I can control the camera focus using setFocusMode?

I just don't want to buy a phone, and then find out setFocusMode does not change the focus.

If you are curious about what exactly I'm trying to do:  I'd like to switch between FOCUS_MODE_INFINITY and FOCUS_MODE_MACRO and take two different pictures of an object.

thanks,
SJK

答:
The most straightforward solution would be:

Make a app that just prints "This phone has autofocus" or "This phone doesn't have autofocus" on the screen, depending on whether the result of setFocusMode.

Publish the app on the android market.

Ask the vendor to allow you to test that one app on the phone before purchasing.

If your vendor doesn't allow you to do so, then the next better thing is asking in forums. Something like "Hey guys, can anyone having this phone tell me what this app (link to app on Market) returns on it?

I suppose you could also ask the IT support for an specific phone to try the app for you. The results will depend on whether they have an app available for testing these things.

That's all I can think about.


来源: stackexchange

问:
How to pass the specific object my form is editing into django?
If I have multiple objects of the same database model displayed on my page, and I want to have an edit button for each of them that allows you to edit the data of said object, how could I pass the data of which one I'm editing to my view so I could edit the fields of that specific database entry.

Right now I have only one form

```<code><form method="POST" action="." id="projectForm">
            {% csrf_token %}
            <legend class="border-bottom mb-4 formheader">Edit Assumption</legend>
                {{ form }}
            <div class="form-group" style="display: flex; justify-content: center; align-items: center;">
                <button type="submit" class="createbutton" name="editassumptionformbutton">Save</button>
            </div>
        </form>
</code>```

I can make the onclick trigger the display of the form like this:

```<code><a onclick="toggleVisibilityEdit()">Edit</a>
</code>```

(which is a javascript function that displays the form)

These are my model entries that are being listed:

```<code>{% for assumption in assumptions reversed %}
        <div class="card existingcard assumption">
            <h2>{{ assumption }}</h2>
            <div class="assumptionbtns">
                <a onclick="toggleVisibilityEdit()">Edit</a>
                <a href="{% url 'problemdashboard:dashboard-assumption' project.pk need.pk assumption.id%}">View</a>
            </div>
        </div>
        {% endfor %}
</code>```

But I have no idea how to tell the view which of the objects I'm currently editing, how could I do that?

答: While listing your models, add their Ids in the edit Url. So when you click on any item, its ID will automatically be passed</p>

ContentLicense: CC BY-SA 4.0

Body:
If I have multiple objects of the same database model displayed on my page, and I want to have an edit button for each of them that allows you to edit the data of said object, how could I pass the data of which one I'm editing to my view so I could edit the fields of that specific database entry.

Right now I have only one form

<form method="POST" action="." id="projectForm">
            {% csrf_token %}
            <legend class="border-bottom mb-4 formheader">Edit Assumption</legend>
                {{ form }}

                <button type="submit" class="createbutton" name="editassumptionformbutton">Save</button>

        </form>

I can make the onclick trigger the display of the form like this:

Edit

(which is a javascript function that displays the form)

These are my model entries that are being listed:

{% for assumption in assumptions reversed %}

{{ assumption }}

                Edit
                View

        {% endfor %}

But I have no idea how to tell the view which of the objects I'm currently editing, how could I do that?


问:
Execute commands from stdin to stdout without print statement like in REPL
What's the easiest way to make this work:

```<code>> echo 1+1 | [run python in REPL and exit with capturing all statement values to stdout ]
2
</code>```

Yes, we can do echo "print(1+1)" | python but that requires to write print. The point is to make python behave like PowerShell:

```<code>> echo 1+1 | powershell -c -
2
</code>```

Yes, we can do echo 1+1 | python -i but that output some noise (python version etc.).

答:
The following is not a recommended practice, since it uses the unsafe eval function. However, in the context of what you are asking for, where you seem to have control of all the steps in the process, it will do.

Write the following simple Python program (my_program.py):

```<code>import sys

sys.stdout.write(str(eval(sys.stdin.read())))
</code>```

Then, use:

```<code>> echo 1+1 | python my_program.py
2
</code>```

Body:
What's the easiest way to make this work:

> echo 1+1 | [run python in REPL and exit with capturing all statement values to stdout ]
2

Yes, we can do echo "print(1+1)" | python but that requires to write print. The point is to make python behave like PowerShell:

> echo 1+1 | powershell -c -
2

Yes, we can do echo 1+1 | python -i but that output some noise (python version etc.).

Body:
The following is not a recommended practice, since it uses the unsafe eval function. However, in the context of what you are asking for, where you seem to have control of all the steps in the process, it will do.

Write the following simple Python program (my_program.py):

import sys

sys.stdout.write(str(eval(sys.stdin.read())))

Then, use:

> echo 1+1 | python my_program.py
2


问:
How to Check if a Generic Type is IComparable then Compare if so?
I'm trying to figure out how to do something like the pseudo-code below:

```<code>private void test<T>(T a, T b)
{
    if (a is IComparable<T> && b is IComparable<T>)
    {
        int result = a.CompareTo(b);
        // do something with the result
    }
    else
    {
        // do something else
    }
}
</code>```

How can I achieve that in C# ?

答:
You can use is type pattern to assign the result to a variable and use it to call Compare. You also don't need to cast b to IComparable<T>, since CompareTo accepts parameter of T type (and b is T already)

if (a is IComparable<T> comparable)
{
    int result = comparable.CompareTo(b);
    // do something with the result
}
```
<p>Another option is to apply a generic constraint with <code>IComparable<T></code> interface</p>
<pre class="lang-cs prettyprint-override"><code>private void test<T>(T a, T b) where T : IComparable<T>
{
    var result = a.CompareTo(b);
    // do something with the result
}
</code>```

Body:
I'm trying to figure out how to do something like the pseudo-code below:

private void test<T>(T a, T b)
{
    if (a is IComparable<T> && b is IComparable<T>)
    {
        int result = a.CompareTo(b);
        // do something with the result
    }
    else
    {
        // do something else
    }
}

How can I achieve that in C# ?

Body:
You can use is type pattern to assign the result to a variable and use it to call Compare. You also don't need to cast b to IComparable<T>, since CompareTo accepts parameter of T type (and b is T already)

if (a is IComparable<T> comparable)
{
    int result = comparable.CompareTo(b);
    // do something with the result
}

Another option is to apply a generic constraint with IComparable<T> interface

private void test<T>(T a, T b) where T : IComparable<T>
{
    var result = a.CompareTo(b);
    // do something with the result
}


问:
How do I compare values of BigInteger to be used as a condition in a loop?
I am trying to compare if the value of one BigInteger(base) is > (greater than) the value of another BigInteger(prime) and if the value of 'a' is not equal to one. If value of a is not 1, it should break out of the loop. How should I compare them?

Random ran = new Random();
BigInteger prime = new BigInteger(16,ran);
BigInteger base,a,one;
one = new BigInteger("1");

for (int i = 0; i < 65535; i++){

    while (base>prime){
        base = new BigInteger(16,ran);
    }
    a = base.modPow(prime.subtract(one),prime);
    System.out.println("a: "+a);
    if (a != one){
        break;
    }
}
```

答:
You can compare them using BigInteger.compareTo(BigInteger).

In your case, this would be while (base.compareTo(prime) > 0) {...}.

Also, your termination condition should be changed from if (a != one) to if (!a.equals(one)) since two BigInteger variables with the same integer value are not necessarily referencing the same object (which is all that == and != test).

ContentLicense: CC BY-SA 3.0


问:
How to set the value of a variable defined outside in an arrow function (Axios, react, javascript)
I created a React component which fetches data from a server using Axios and renders it in a
 element.

Here's my code:

```<code>import React from "react";
import Axios from "axios";

class Abc extends React.Component {
    getUser = () => {
        let r;
        Axios.get("...").then(res => {
            r = res.data();
        });
        return r
    }

    render() {
        return <p>User: {getUser()}</p>
    }
}

</code>```

But the above code returns user as undefined. How can I fix this?

EDIT: For those of you asking me to use componentDidMount() and state, I need to use this user variable multiple times, and all times, the user will be different. What do I do now?

UPDATE: Fixed it. I just created a separate component for every user. Thanks all!

答:
React can't render asynchronously component.
In your component, axios is used to fetch data from server.
This is performed asynchronously.
So you mustn't render your component asynchronously.
Solution is here:

Make a variable in your redux for user data.

Then do axios in your redux(action)

Finally, connect your redux store to your component and use it.

Body:
I created a React component which fetches data from a server using Axios and renders it in a
 element.

Here's my code:

import React from "react";
import Axios from "axios";

class Abc extends React.Component {
    getUser = () => {
        let r;
        Axios.get("...").then(res => {
            r = res.data();
        });
        return r
    }

    render() {
        return
User: {getUser()}

    }
}

But the above code returns user as undefined. How can I fix this?

EDIT: For those of you asking me to use componentDidMount() and state, I need to use this user variable multiple times, and all times, the user will be different. What do I do now?

UPDATE: Fixed it. I just created a separate component for every user. Thanks all!


问:
what does that mean? [Baseclass] [name] = new [Subclass]
I actually learn c# and i stuck at this theme:

what does this mean: [Baseclass] [name] = new [Subclass]

i only understand that i can use that as a parameter like

```<code>    public void DoSomething(Book _book)
    {
        if (_book is PokemonBook)
        {
            Console.WriteLine("It's a Pokemon-Book!");
        }
        else
        {
            Console.WriteLine("idk");
        }
    }
</code>```

but i dont understand this [Baseclass] [name] = new [Subclass], when do is use this and what does it do?

and yes, it's a stupid question

答:
i think this link can help you to learn all about class

https://learn.microsoft.com/en-us/dotnet/csharp/tutorials/inheritance

and dont ask some question like this other Guys Use negative Point and with negative point you cant ask your Question here...
why negative Point ? Bcs you must first try little Improve You Skill then try find you Answer With Search in GooGle or this site then if you are not find your Answer you must Qustion here and try to Read Question Rule

you can learn C# in Microsoft Site Easy ( you can find many Simple Example ) then you can come here and read many many many Code and ask and Answer and you Grow Faster

i hope my answer help you
and dont forgot learn about OOP

Body:
I actually learn c# and i stuck at this theme:

what does this mean: [Baseclass] [name] = new [Subclass]

i only understand that i can use that as a parameter like

    public void DoSomething(Book _book)
    {
        if (_book is PokemonBook)
        {
            Console.WriteLine("It's a Pokemon-Book!");
        }
        else
        {
            Console.WriteLine("idk");
        }
    }

but i dont understand this [Baseclass] [name] = new [Subclass], when do is use this and what does it do?

and yes, it's a stupid question


问:
How do I extract data from a main table based on this specific scenario?
I am using SQL Server 2014. I have a table (T1) which contains the list of IDs of cancelled bookings and their equivalent re-bookings.

Extract of table T1:

```<code>CancelledID       Re-bookingID
  301                754
  387                801
  400                900
  ...
</code>```

Each CancelledID has a unique equivalent in the Re-bookingID column.

I have another table (T2) which contains the list of ALL BookingIDs with additional information related to each ID. An extract of this table is shown below:

```<code>BookingID     MonthOfStay      RoomNights
...
301             2019-03-01        10
387             2019-04-01         7
400             2019-03-01         5
754             2019-08-01        10
801             2019-09-01         3
900             2019-07-01         5
900             2019-08-01         4
...
</code>```

I need a  t-sql query which will me the following output:

```<code>  BookingID       Cancelled_MonthOfStay     Re-booking_MonthOfStay     RoomNights
    301                2019-03-01                                           10
    387                2019-04-01                                            7
    400                2019-03-01                                            5
    754                                           2019-08-01                10
    801                                           2019-09-01                 3
    900                                           2019-07-01                 5
    900                                           2019-08-01                 4
</code>```

As you can see, a re-booking can span over 2 months with additional room nights.

I am thinking about "Joins" between the 2 tables but I am stuck at the logic to be used for the "Joins" (if that is the right way of tackling the problem).

Note: The end in mind is to use this data to build a matrix with Cancelled_MonthOfStay as rows and Re-booking_MonthOfStay as columns. The value inside this matrix will be the total RoomNights.

Any help would be appreciated.

答:
You can LEFT JOIN the T1 table twice to your T2 table. And then use CASE to leave the right columns empty.</p>

```<code>SELECT T2.bookingID,
    case when canc.CancelledID is not null then t2.monthOfSTay end as cancelled_MonthOfStay,
    case when reb.rebookingID is not null then t2.monthOfStay end as rebooking_MonthOfStay

FROM T2
LEFT JOIN T1 as canc
    on T2.bookingID = canc.CancelledID
LEFT JOIN T1 as reb
    on T2.bookingID = reb.rebookingID
</code>```

Body:
I am using SQL Server 2014. I have a table (T1) which contains the list of IDs of cancelled bookings and their equivalent re-bookings.

Extract of table T1:

CancelledID       Re-bookingID
  301                754
  387                801
  400                900
  ...

Each CancelledID has a unique equivalent in the Re-bookingID column.

I have another table (T2) which contains the list of ALL BookingIDs with additional information related to each ID. An extract of this table is shown below:

BookingID     MonthOfStay      RoomNights
...
301             2019-03-01        10
387             2019-04-01         7
400             2019-03-01         5
754             2019-08-01        10
801             2019-09-01         3
900             2019-07-01         5
900             2019-08-01         4
...

I need a  t-sql query which will me the following output:

  BookingID       Cancelled_MonthOfStay     Re-booking_MonthOfStay     RoomNights
    301                2019-03-01                                           10
    387                2019-04-01                                            7
    400                2019-03-01                                            5
    754                                           2019-08-01                10
    801                                           2019-09-01                 3
    900                                           2019-07-01                 5
    900                                           2019-08-01                 4

As you can see, a re-booking can span over 2 months with additional room nights.

I am thinking about "Joins" between the 2 tables but I am stuck at the logic to be used for the "Joins" (if that is the right way of tackling the problem).

Note: The end in mind is to use this data to build a matrix with Cancelled_MonthOfStay as rows and Re-booking_MonthOfStay as columns. The value inside this matrix will be the total RoomNights.

Any help would be appreciated.

Body:
You can LEFT JOIN the T1 table twice to your T2 table. And then use CASE to leave the right columns empty.

SELECT T2.bookingID,
    case when canc.CancelledID is not null then t2.monthOfSTay end as cancelled_MonthOfStay,
    case when reb.rebookingID is not null then t2.monthOfStay end as rebooking_MonthOfStay

FROM T2
LEFT JOIN T1 as canc
    on T2.bookingID = canc.CancelledID
LEFT JOIN T1 as reb
    on T2.bookingID = reb.rebookingID


问:
What's the difference between the ApplicationServices (root) IServiceProvider and an injected IServiceProvider?
I have a hard time understanding why the behaviour is different to apply the service locator pattern in the Startup Configure method when using the IApplicationBuilder.ApplicationServices in stead of IServiceProvider.

When I use IApplicationBuilder.ApplicationServices (which sets the IServiceProvider that provides access to the application's service container) I get the following error:

Cannot resolve scoped service '...' from root provider

In contrast, when I use the injected IServiceProvider directly it works like a charm:

```<code>public void Configure(
    IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider sp)
{
  // 1 : resolving a scoped service directly from application services container
  // IServiceProvider throws 'Cannot resolve scoped service from root provider'
  var test1 = app.ApplicationServices.GetRequiredService<IMyScopedService>();

  // 2 : works like a charm
  var test2 = sp.GetRequiredService<IMyScopedService>();

  // 3 : also works like a charm
  var scope = app.ApplicationServices.CreateScope();
  var test3 = scope.ServiceProvider.GetRequiredService<IMyScopedService>();
}
</code>```

Why is this? Why does the injected IServiceProvider behave like it has "service scope" and IApplicationBuilder.ApplicationServices like it has a sort of "application scope" outside of service scopes?

In a way the injected IServiceProvider works the same as creating a scope first with IApplicationBuilder and only then resolving the scoped service from the scope's service provider.

My head is spinning now.

Obviously it seems that the scope of IApplicationBuilder (does one name it like this?) is outside of service scopes. But when I look up IApplicationBuilder I can't find anything about the root provider.

Can anyone clarify this? Did I miss an obvious beginners tutorial somewhere that explains this root provider or application's service container?

答:
This is by design.

ASP.NET runtime instantiate IServiceProvider in such way that it prohibits scoped services resolved from the root:

serviceCollection.BuildServiceProvider(validateScopes: true);
```
<p><code>app.ApplicationServices</code> is root <code>IServiceProvider</code>. <code>sp</code> is child of <code>app.ApplicationServices</code>.</p>
<p>You can check this using following line of code in <code>Immediate Window</code> of Visual Studio, while on a break point (that way you can access internal <code>ServiceProviderEngineScope</code> directly):</p>
<pre class="lang-cs prettyprint-override"><code>app.ApplicationServices == ((Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope)sp).Engine.Root
// true
</code>```

So only children of  app.ApplicatoinServices can resolve scoped services. One child sp was provided as input parameter, 2nd one you created manually.

UPDATE:
I gave a very detailed answer on MVC Core ServiceProvider and Scope default behavior here.

Body:
I have a hard time understanding why the behaviour is different to apply the service locator pattern in the Startup Configure method when using the IApplicationBuilder.ApplicationServices in stead of IServiceProvider.

When I use IApplicationBuilder.ApplicationServices (which sets the IServiceProvider that provides access to the application's service container) I get the following error:

Cannot resolve scoped service '...' from root provider

In contrast, when I use the injected IServiceProvider directly it works like a charm:

public void Configure(
    IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider sp)
{
  // 1 : resolving a scoped service directly from application services container
  // IServiceProvider throws 'Cannot resolve scoped service from root provider'
  var test1 = app.ApplicationServices.GetRequiredService<IMyScopedService>();

  // 2 : works like a charm
  var test2 = sp.GetRequiredService<IMyScopedService>();

  // 3 : also works like a charm
  var scope = app.ApplicationServices.CreateScope();
  var test3 = scope.ServiceProvider.GetRequiredService<IMyScopedService>();
}

Why is this? Why does the injected IServiceProvider behave like it has "service scope" and IApplicationBuilder.ApplicationServices like it has a sort of "application scope" outside of service scopes?

In a way the injected IServiceProvider works the same as creating a scope first with IApplicationBuilder and only then resolving the scoped service from the scope's service provider.

My head is spinning now.

Obviously it seems that the scope of IApplicationBuilder (does one name it like this?) is outside of service scopes. But when I look up IApplicationBuilder I can't find anything about the root provider.

Can anyone clarify this? Did I miss an obvious beginners tutorial somewhere that explains this root provider or application's service container?

Body:
This is by design.

ASP.NET runtime instantiate IServiceProvider in such way that it prohibits scoped services resolved from the root:

serviceCollection.BuildServiceProvider(validateScopes: true);

app.ApplicationServices is root IServiceProvider. sp is child of app.ApplicationServices.

You can check this using following line of code in Immediate Window of Visual Studio, while on a break point (that way you can access internal ServiceProviderEngineScope directly):

app.ApplicationServices == ((Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope)sp).Engine.Root
// true

So only children of  app.ApplicatoinServices can resolve scoped services. One child sp was provided as input parameter, 2nd one you created manually.

UPDATE:
I gave a very detailed answer on MVC Core ServiceProvider and Scope default behavior here.


问:
Notification not showing in Oreo
Normal Notification Builder doesn't show notifications on Android O.

How could I show notification on Android 8 Oreo?

Is there any new piece of code to add for showing notification on Android O?

答:
You Need to create a notification channel for API level above 26(oreo).

```<code>`NotificationChannel channel = new NotificationChannel(STRING_ID,CHANNEL_NAME,NotificationManager.IMPORTANCE_HIGH);
</code>```

STRING_ID = string notification channelid is the same as in Notification.Builder like this

```<code>`Notification notification = new Notification.Builder(this,STRING_ID)
            .setSmallIcon(android.R.drawable.ic_menu_help)
            .setContentTitle("Hello Notification")
            .setContentText("It is Working")
            .setContentIntent(pendingIntent)
            .build();`
</code>```

Channel id in the notification and in the notification should be same
Whole code is like this..
`

```<code>@RequiresApi(api = Build.VERSION_CODES.O)
  private void callNotification2() {

    Intent intent = new Intent(getApplicationContext(),MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,11,
    intent,PendingIntent.FLAG_UPDATE_CURRENT);
    Notification notification = new Notification.Builder(this,"22")
            .setSmallIcon(android.R.drawable.ic_menu_help)
            .setContentTitle("Hello Notification")
            .setContentText("It is Working")
            .setContentIntent(pendingIntent)
            .build();
    NotificationChannel channel = new
    NotificationChannel("22","newName",NotificationManager.IMPORTANCE_HIGH);
    NotificationManager manager = (NotificationManager)
    getSystemService(NOTIFICATION_SERVICE);
    manager.createNotificationChannel(channel);
    manager.notify(11,notification);

    }'
</code>```

Title: Notification not showing in Oreo

Body:
You Need to create a notification channel for API level above 26(oreo).

`NotificationChannel channel = new NotificationChannel(STRING_ID,CHANNEL_NAME,NotificationManager.IMPORTANCE_HIGH);

STRING_ID = string notification channelid is the same as in Notification.Builder like this

`Notification notification = new Notification.Builder(this,STRING_ID)
            .setSmallIcon(android.R.drawable.ic_menu_help)
            .setContentTitle("Hello Notification")
            .setContentText("It is Working")
            .setContentIntent(pendingIntent)
            .build();`

Channel id in the notification and in the notification should be same
Whole code is like this..
`

@RequiresApi(api = Build.VERSION_CODES.O)
  private void callNotification2() {

    Intent intent = new Intent(getApplicationContext(),MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,11,
    intent,PendingIntent.FLAG_UPDATE_CURRENT);
    Notification notification = new Notification.Builder(this,"22")
            .setSmallIcon(android.R.drawable.ic_menu_help)
            .setContentTitle("Hello Notification")
            .setContentText("It is Working")
            .setContentIntent(pendingIntent)
            .build();
    NotificationChannel channel = new
    NotificationChannel("22","newName",NotificationManager.IMPORTANCE_HIGH);
    NotificationManager manager = (NotificationManager)
    getSystemService(NOTIFICATION_SERVICE);
    manager.createNotificationChannel(channel);
    manager.notify(11,notification);

    }'


问:
Add DropDown without refreshing page
Good Evening, </p>

<p>Could one of you suggest a way to add a dropdown box dynamically without refreshing the page? The dropdown box must not be visible at first, it must then become visible later based on a choice made by the user.  However one constraint is it can only be Javascript, Php, and/or html  </p>

答:
Add the dropdown to the page like normal, only set its css to display:none, then when a box is clicked, you can do something like this in javascript:

```<code>$("#MyBox").click(function(){
    $("#dropdown").show('fast');
});
</code>```

This jquery function will add a smooth transition to show the box

I also agree with @Mohsen

BUUUT... it's best to Google it and
  learn more about this stuff. There is
  lots of cool stuff about this out
  there.

You might just be on the edge of learning some really neat stuff! Be adventurous and enjoy this stage of the learning process.

Title: Add DropDown without refreshing page

Body:
Good Evening,

Could one of you suggest a way to add a dropdown box dynamically without refreshing the page? The dropdown box must not be visible at first, it must then become visible later based on a choice made by the user.  However one constraint is it can only be Javascript, Php, and/or html

Body:
Add the dropdown to the page like normal, only set its css to display:none, then when a box is clicked, you can do something like this in javascript:

$("#MyBox").click(function(){
    $("#dropdown").show('fast');
});

This jquery function will add a smooth transition to show the box

I also agree with @Mohsen

BUUUT... it's best to Google it and
  learn more about this stuff. There is
  lots of cool stuff about this out
  there.

You might just be on the edge of learning some really neat stuff! Be adventurous and enjoy this stage of the learning process.


问:
How to write a custom loss function in Keras/Tensorflow that uses loops/iterations with reference numpy code
I saw this question: Implementing custom loss function in keras with condition And I need to do the same thing but with code that seems to need loops.

I have a custom numpy function which calculates the mean Euclid distance from the mean vector. I wrote this based on the paper https://arxiv.org/pdf/1801.05365.pdf:

```<code>import numpy as np

def mean_euclid_distance_from_mean_vector(n_vectors):

    dists = []

    for (i, v) in enumerate(n_vectors):
        n_vectors_rest = n_vectors[np.arange(len(n_vectors)) != i]

        print("rest of vectors: ")
        print(n_vectors_rest)

        # calculate mean vector
        mean_rest = n_vectors_rest.mean(axis=0)

        print("mean rest vector")
        print(mean_rest)

        dist = v - mean_rest

        print("dist vector")
        print(dist)
        dists.append(dist)

    # dists is now a matrix of distance vectors (distance from the mean vector)
    dists = np.array(dists)

    print("distance vector matrix")
    print(dists)

    # here we matmult each vector
    # sum them up
    # and divide by the total number of elements
    result = np.sum([np.matmul(d, d) for d in dists]) / dists.size

    return result

features = np.array([
    [1,2,3,4],
    [4,3,2,1]
])

c = mean_euclid_distance_from_mean_vector(features)

print(c)
</code>```

I need this function however to work inside tensorflow with Keras. So a custom lambda https://www.tensorflow.org/api_docs/python/tf/keras/layers/Lambda

However, I'm not sure how to implement the above in Keras/Tensorflow since it has loops, and the way the paper talked about calculating the m_i seems to require loops like the way I implemented the above.

For reference, the PyTorch version of this code is here: https://github.com/PramuPerera/DeepOneClass

答:
Given a feature map like:

features = np.array([
    [1, 2, 3, 4],
    [2, 4, 4, 3],
    [3, 2, 1, 4],
], dtype=np.float64)
```

<p>reflecting a <code>batch_size</code> of</p>

<pre class="lang-py prettyprint-override"><code>batch_size = features.shape[0]
</code>```

and

k = features.shape[1]
```

<p>One has that implementing the above Formulas in Tensorflow could be expressed (prototyped) by:</p>

<pre class="lang-py prettyprint-override"><code>dim = (batch_size, features.shape[1])
def zero(i):
    arr = np.ones(dim)
    arr[i] = 0
    return arr

mapper = [zero(i) for i in range(batch_size)]
elems = (features, mapper)
m = (1 / (batch_size - 1)) * tf.map_fn(lambda x: tf.math.reduce_sum(x[0] * x[1], axis=0), elems, dtype=tf.float64)
pairs = tf.map_fn(lambda x: tf.concat(x, axis=0) , tf.stack([features, m], 1), dtype=tf.float64)
compactness_loss = (1 / (batch_size * k)) * tf.map_fn(lambda x: tf.math.reduce_euclidean_norm(x), pairs, dtype=tf.float64)

with tf.Session() as sess:
    print("loss value output is: ", compactness_loss.eval())
</code>```

Which yields:

loss value output is:  [0.64549722 0.79056942 0.64549722]
```

<p>However a single measure is required for the batch, therefore it is necessary to reduce it; by the summation of all values.</p>

<p>The wanted Compactness Loss function à la Tensorflow is:</p>

<pre class="lang-sh prettyprint-override"><code>def compactness_loss(actual, features):
    features = Flatten()(features)
    k = 7 * 7 * 512
    dim = (batch_size, k)

    def zero(i):
        z = tf.zeros((1, dim[1]), dtype=tf.dtypes.float32)
        o = tf.ones((1, dim[1]), dtype=tf.dtypes.float32)
        arr = []
        for k in range(dim[0]):
            arr.append(o if k != i else z)
        res = tf.concat(arr, axis=0)
        return res

    masks = [zero(i) for i in range(batch_size)]
    m = (1 / (batch_size - 1)) * tf.map_fn(
        # row-wise summation
        lambda mask: tf.math.reduce_sum(features * mask, axis=0),
        masks,
        dtype=tf.float32,
    )
    dists = features - m
    sqrd_dists = tf.pow(dists, 2)
    red_dists = tf.math.reduce_sum(sqrd_dists, axis=1)
    compact_loss = (1 / (batch_size * k)) * tf.math.reduce_sum(red_dists)
    return compact_loss
</code>```

Of course the Flatten() could be moved back into the model for convenience and the k could be derived directly from the feature map; this answers your question. You may just have some trouble finding out the the expected values for the model are - feature maps from the VGG16 (or any other architechture) trained against the imagenet for instance?

The paper says:

In  our  formulation  (shown  in  Figure  2  (e)),  starting  froma  pre-trained  deep  model,  we  freeze  initial  features  (gs)  and learn  (gl)  and  (hc).  Based  on  the  output  of  the  classification sub-network (hc),  two  losses compactness  loss and descriptiveness  loss are  evaluated.  These  two  losses,  introduced  in the subsequent sections, are used to assess the quality of the learned  deep  feature.  We  use  the  provided  one-class  dataset to  calculate  the compactness  loss.  An  external  multi-class reference  dataset  is  used  to  evaluate  the descriptiveness  loss.As  shown  in  Figure  3,  weights  of gl and hc are  learned in  the  proposed  method  through  back-propagation  from  the composite loss. Once training is converged, system shown in setup  in  Figure  2(d)  is  used  to  perform  classification  where the resulting model is used as the pre-trained model.

then looking at the "Framework" backbone here plus:

AlexNet   Binary   and   VGG16   Binary   (Baseline). A  binary  CNN  is  trained  by  having  ImageNet  samples  and  one-class  image  samples  as  the  two  classes  using  AlexNet  andVGG16 architectures, respectively. Testing is performed using k-nearest neighbor, One-class SVM [43], Isolation Forest [3]and Gaussian Mixture Model [3] classifiers.

Makes me wonder whether it would not be reasonable to add suggested the dense layers to both the Secondary and the Reference Networks to a single class output (Sigmoid) or even and binary class output (using Softmax) and using the mean_squared_error as the so called Compactness Loss and binary_cross_entropy as the Descriptveness Loss.

Body:
I saw this question: Implementing custom loss function in keras with condition And I need to do the same thing but with code that seems to need loops.

I have a custom numpy function which calculates the mean Euclid distance from the mean vector. I wrote this based on the paper https://arxiv.org/pdf/1801.05365.pdf:

import numpy as np

def mean_euclid_distance_from_mean_vector(n_vectors):

    dists = []

    for (i, v) in enumerate(n_vectors):
        n_vectors_rest = n_vectors[np.arange(len(n_vectors)) != i]

        print("rest of vectors: ")
        print(n_vectors_rest)

        # calculate mean vector
        mean_rest = n_vectors_rest.mean(axis=0)

        print("mean rest vector")
        print(mean_rest)

        dist = v - mean_rest

        print("dist vector")
        print(dist)
        dists.append(dist)

    # dists is now a matrix of distance vectors (distance from the mean vector)
    dists = np.array(dists)

    print("distance vector matrix")
    print(dists)

    # here we matmult each vector
    # sum them up
    # and divide by the total number of elements
    result = np.sum([np.matmul(d, d) for d in dists]) / dists.size

    return result

features = np.array([
    [1,2,3,4],
    [4,3,2,1]
])

c = mean_euclid_distance_from_mean_vector(features)

print(c)

I need this function however to work inside tensorflow with Keras. So a custom lambda https://www.tensorflow.org/api_docs/python/tf/keras/layers/Lambda

However, I'm not sure how to implement the above in Keras/Tensorflow since it has loops, and the way the paper talked about calculating the m_i seems to require loops like the way I implemented the above.

For reference, the PyTorch version of this code is here: https://github.com/PramuPerera/DeepOneClass

Body:
Given a feature map like:

features = np.array([
    [1, 2, 3, 4],
    [2, 4, 4, 3],
    [3, 2, 1, 4],
], dtype=np.float64)

reflecting a batch_size of

batch_size = features.shape[0]

and

k = features.shape[1]

One has that implementing the above Formulas in Tensorflow could be expressed (prototyped) by:

dim = (batch_size, features.shape[1])
def zero(i):
    arr = np.ones(dim)
    arr[i] = 0
    return arr

mapper = [zero(i) for i in range(batch_size)]
elems = (features, mapper)
m = (1 / (batch_size - 1)) * tf.map_fn(lambda x: tf.math.reduce_sum(x[0] * x[1], axis=0), elems, dtype=tf.float64)
pairs = tf.map_fn(lambda x: tf.concat(x, axis=0) , tf.stack([features, m], 1), dtype=tf.float64)
compactness_loss = (1 / (batch_size * k)) * tf.map_fn(lambda x: tf.math.reduce_euclidean_norm(x), pairs, dtype=tf.float64)

with tf.Session() as sess:
    print("loss value output is: ", compactness_loss.eval())

Which yields:

loss value output is:  [0.64549722 0.79056942 0.64549722]

However a single measure is required for the batch, therefore it is necessary to reduce it; by the summation of all values.

The wanted Compactness Loss function à la Tensorflow is:

def compactness_loss(actual, features):
    features = Flatten()(features)
    k = 7 * 7 * 512
    dim = (batch_size, k)

    def zero(i):
        z = tf.zeros((1, dim[1]), dtype=tf.dtypes.float32)
        o = tf.ones((1, dim[1]), dtype=tf.dtypes.float32)
        arr = []
        for k in range(dim[0]):
            arr.append(o if k != i else z)
        res = tf.concat(arr, axis=0)
        return res

    masks = [zero(i) for i in range(batch_size)]
    m = (1 / (batch_size - 1)) * tf.map_fn(
        # row-wise summation
        lambda mask: tf.math.reduce_sum(features * mask, axis=0),
        masks,
        dtype=tf.float32,
    )
    dists = features - m
    sqrd_dists = tf.pow(dists, 2)
    red_dists = tf.math.reduce_sum(sqrd_dists, axis=1)
    compact_loss = (1 / (batch_size * k)) * tf.math.reduce_sum(red_dists)
    return compact_loss

Of course the Flatten() could be moved back into the model for convenience and the k could be derived directly from the feature map; this answers your question. You may just have some trouble finding out the the expected values for the model are - feature maps from the VGG16 (or any other architechture) trained against the imagenet for instance?

The paper says:

In  our  formulation  (shown  in  Figure  2  (e)),  starting  froma  pre-trained  deep  model,  we  freeze  initial  features  (gs)  and learn  (gl)  and  (hc).  Based  on  the  output  of  the  classification sub-network (hc),  two  losses compactness  loss and descriptiveness  loss are  evaluated.  These  two  losses,  introduced  in the subsequent sections, are used to assess the quality of the learned  deep  feature.  We  use  the  provided  one-class  dataset to  calculate  the compactness  loss.  An  external  multi-class reference  dataset  is  used  to  evaluate  the descriptiveness  loss.As  shown  in  Figure  3,  weights  of gl and hc are  learned in  the  proposed  method  through  back-propagation  from  the composite loss. Once training is converged, system shown in setup  in  Figure  2(d)  is  used  to  perform  classification  where the resulting model is used as the pre-trained model.

then looking at the "Framework" backbone here plus:

AlexNet   Binary   and   VGG16   Binary   (Baseline). A  binary  CNN  is  trained  by  having  ImageNet  samples  and  one-class  image  samples  as  the  two  classes  using  AlexNet  andVGG16 architectures, respectively. Testing is performed using k-nearest neighbor, One-class SVM [43], Isolation Forest [3]and Gaussian Mixture Model [3] classifiers.

Makes me wonder whether it would not be reasonable to add suggested the dense layers to both the Secondary and the Reference Networks to a single class output (Sigmoid) or even and binary class output (using Softmax) and using the mean_squared_error as the so called Compactness Loss and binary_cross_entropy as the Descriptveness Loss.


问:
Webdav link resource
Is it possible to create Webdav resource, that would act as a symbolic link on unixes? I.e. client would understand that this resource is a link, and that it should in fact work with some other resource?</p>

答:
If your symbolic link is a directory you can have a simple hack.

Instead of a symbolic link you make a normal folder that is empty (my_empty_folder), then on the Apache configuration you point the empty folder to the real location (/opt/my_full_folder/) using Alias and Virtual Directory

Something like:

```<code>Alias /webdav/my_empty_folder /opt/my_full_folder/
<Directory /opt/my_full_folder >
  Options +Indexes
   <RequireAll>
        Require all granted
   </RequireAll>
</Directory>
</code>```

mod_dav will report the folder and when you click/follow it Apache will use the content from the destination folder.

This hack will allow for webdav clients to properly see the folder and follow the contents, but also browser using apache's index

ContentLicense: CC BY-SA 2.5

Title: Webdav link resource

Body:
If your symbolic link is a directory you can have a simple hack.

Instead of a symbolic link you make a normal folder that is empty (my_empty_folder), then on the Apache configuration you point the empty folder to the real location (/opt/my_full_folder/) using Alias and Virtual Directory

Something like:

Alias /webdav/my_empty_folder /opt/my_full_folder/
<Directory /opt/my_full_folder >
  Options +Indexes
   <RequireAll>
        Require all granted
   </RequireAll>
</Directory>

mod_dav will report the folder and when you click/follow it Apache will use the content from the destination folder.

This hack will allow for webdav clients to properly see the folder and follow the contents, but also browser using apache's index


问:
Merge two sorted lists and preserve order
Given two lists e.g.

```<code>l1 = ["A","D","B","C"]
l2 = ["X","A","Y","B"]
</code>```

I want the result to preserve the order given by both input lists i.e.

```<code>["X","A","D","Y","B","C"]
</code>```

The result is not unique as "D" and "Y" could also be switched (but if it is not clear lexicographic order should handle the conflict)
Also if I had smth. like

```<code>l1 = ["B","A"]
l2 = ["X","A","Y","B"]
</code>```

positions of either B or A should be treated interchangeably (i.e. no unique order can be constructed and the order of B A should be treated as A=B) which would lead to accepted results

```<code>["X","A","Y","B"]
</code>```

(preferably as it is in deterministic lexicographic order of A and B) or

```<code>["X","B","Y","A"]
</code>```

Put in another way I want the combination of lists to preserve the order where unique and where it's not, the result should be deterministic e.g. according to lexicographic ordering.

Is there a library for python that accomplishes that or would I have to implement it on my own?
I looked at OrderedDict and OrderedSet but both do not handle the merge as I want.

答:
You might want to use to use topological sorting. If you don't want to implement the algorithm from scratch, you can use the NetworkX Python package:

```<code>from itertools import chain
from networkx import DiGraph, topological_sort

l1 = ["A", "D", "B", "C"]
l2 = ["X", "A", "Y", "B"]

# Build the graph
G = DiGraph(chain(zip(l1[:-1], l1[1:]), zip(l2[:-1], l2[1:])))

# Return a list of nodes in topological sort order
result = list(topological_sort(G))

# result: ['X', 'A', 'Y', 'D', 'B', 'C']
</code>```

Basically, you build a graph where every directed edge from vertex u to vertex v implies that u comes before v in the ordering. In this specific example, "A" comes before "D", "D" comes before "B" etc:

```<code>>>> G.edges
[('A', 'D'), ('A', 'Y'), ('D', 'B'), ('B', 'C'), ('X', 'A'), ('Y', 'B')]
</code>```

Body:
Given two lists e.g.

l1 = ["A","D","B","C"]
l2 = ["X","A","Y","B"]

I want the result to preserve the order given by both input lists i.e.

["X","A","D","Y","B","C"]

The result is not unique as "D" and "Y" could also be switched (but if it is not clear lexicographic order should handle the conflict)
Also if I had smth. like

l1 = ["B","A"]
l2 = ["X","A","Y","B"]

positions of either B or A should be treated interchangeably (i.e. no unique order can be constructed and the order of B A should be treated as A=B) which would lead to accepted results

["X","A","Y","B"]

(preferably as it is in deterministic lexicographic order of A and B) or

["X","B","Y","A"]

Put in another way I want the combination of lists to preserve the order where unique and where it's not, the result should be deterministic e.g. according to lexicographic ordering.

Is there a library for python that accomplishes that or would I have to implement it on my own?
I looked at OrderedDict and OrderedSet but both do not handle the merge as I want.

Body:
You might want to use to use topological sorting. If you don't want to implement the algorithm from scratch, you can use the NetworkX Python package:

from itertools import chain
from networkx import DiGraph, topological_sort

l1 = ["A", "D", "B", "C"]
l2 = ["X", "A", "Y", "B"]

# Build the graph
G = DiGraph(chain(zip(l1[:-1], l1[1:]), zip(l2[:-1], l2[1:])))

# Return a list of nodes in topological sort order
result = list(topological_sort(G))

# result: ['X', 'A', 'Y', 'D', 'B', 'C']

Basically, you build a graph where every directed edge from vertex u to vertex v implies that u comes before v in the ordering. In this specific example, "A" comes before "D", "D" comes before "B" etc:

>>> G.edges
[('A', 'D'), ('A', 'Y'), ('D', 'B'), ('B', 'C'), ('X', 'A'), ('Y', 'B')]


问:
Iterators without STL containers
At first sorry about my English.
Im preparing for my exam and I need to practice iterators, that dont work with containers.
I would like to input some symbols right to the symbol like '\n' and I have no clue how can I do that.
The problem is I am not able to stop entering symbols.
Hope you can help me.
Sincerely thank you!

```<code>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <fstream>
using namespace std;
int main()
{
    ofstream out("name.txt");
    istream_iterator<char> it(cin);
    istream_iterator<char> end_of_stream;
    ostream_iterator<char> fout(out, " ");
    copy (it, end_of_stream, fout);
}

</code>```

答:
There's no algorithm to copy until you get a particular value (I think) so instead you have to write your own loop.

Like this

```<code>while (it != end_of_stream && *it != '\n')
{
    fout << *it;
    ++it;
}
</code>```

Title: Iterators without STL containers

Body:
At first sorry about my English.
Im preparing for my exam and I need to practice iterators, that dont work with containers.
I would like to input some symbols right to the symbol like '\n' and I have no clue how can I do that.
The problem is I am not able to stop entering symbols.
Hope you can help me.
Sincerely thank you!

#include <iostream>
#include <iterator>
#include <algorithm>
#include <fstream>
using namespace std;
int main()
{
    ofstream out("name.txt");
    istream_iterator<char> it(cin);
    istream_iterator<char> end_of_stream;
    ostream_iterator<char> fout(out, " ");
    copy (it, end_of_stream, fout);
}

Body:
There's no algorithm to copy until you get a particular value (I think) so instead you have to write your own loop.

Like this

while (it != end_of_stream && *it != '\n')
{
    fout << *it;
    ++it;
}


问:
SELECT column based on conditions
I have a table similar to the following:

```<code>+---------+--------------+
| user_id | distance     |
+---------+--------------+
|     101 | 12.05        |
|     103 | 4.8          |
|     207 | 37.1         |
|     991 | 3.51         |
|     215 | 15.9         |
+---------+--------------+
</code>```

Then I want the number of users that cover different range of distances: 0-5km as short_distance, 5-10km as medium_distance, >10km as long_distance.

I'm kind of confused when aggregating.

答:
use a CASE expression:</p>

```<code>select user_id,
       case
         when distance <= 5 then 'short distance'
         when distance <= 10 then 'medium distance'
         else 'long distance'
       end as what
from the_table;
</code>```

Title: SELECT column based on conditions

Body:
I have a table similar to the following:

+---------+--------------+
| user_id | distance     |
+---------+--------------+
|     101 | 12.05        |
|     103 | 4.8          |
|     207 | 37.1         |
|     991 | 3.51         |
|     215 | 15.9         |
+---------+--------------+

Then I want the number of users that cover different range of distances: 0-5km as short_distance, 5-10km as medium_distance, >10km as long_distance.

I'm kind of confused when aggregating.

Body:
use a CASE expression:

select user_id,
       case
         when distance <= 5 then 'short distance'
         when distance <= 10 then 'medium distance'
         else 'long distance'
       end as what
from the_table;


问:
Unable to get data from populated sqlite database in asset folder
The bug is that when I run my code on emulator the app is stopping with an error (java.lang.RuntimeException: Unable to start activity :
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getDatabasePath(java.lang.String)' on a null object reference) in the code String dbpath =mcontext.getDatabasePath(DATABASE_NAME).getPath();

myfragment :

```<code>public class FragmentHome extends Fragment {
    private List<ItemRecipe> itemList = new ArrayList<>();
    private RecyclerView recyclerView;
    private RecipeAdapter mAdapter;
    private AppCompatActivity appCompatActivity;
    databaseHelper db = new databaseHelper(getActivity());

    public FragmentHome() {
        setHasOptionsMenu(true);
    }

    public void onCreate(Bundle a) {
        super.onCreate(a);
        setHasOptionsMenu(true);
    }
</code>```

sqldatabasehelper :

```<code>public class databaseHelper extends SQLiteOpenHelper {
    public static final String DATABASE_NAME = "recipes.db";
    public static final String DATABASE_location = Environment.getDataDirectory()+"data/com.recipes.cook/databases/";
private Context mcontext ;
private SQLiteDatabase mdatabase;

    public databaseHelper( Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }

    public  void openDatabase(){

String dbpath =mcontext.getDatabasePath(DATABASE_NAME).getPath();
if (mdatabase != null && mdatabase.isOpen()){
    return;
}
mdatabase=SQLiteDatabase.openDatabase(dbpath,null,SQLiteDatabase.OPEN_READWRITE);

    }

public void closeDatabase() {

    if (mdatabase != null) {

        mdatabase.close();
    }
}

    public ArrayList<ItemRecipe> get_all_name (){
        ItemRecipe itemRecipe=null;
  ArrayList<ItemRecipe> recipslist=new ArrayList<>();
openDatabase();
        Cursor res = mdatabase.rawQuery("select * from recipes",null);
        res.moveToFirst();
        while(!res.isAfterLast()){
           String recipe =res.getString(res.getColumnIndex("name"));
           String img=res.getString(res.getColumnIndex("image"));
           String time = res.getString(res.getColumnIndex("time"));
            int rating = res.getInt(res.getColumnIndex("rating"));

res.moveToNext();
            recipslist.add(

                    new ItemRecipe(

recipe,img,time,rating
                    )

            );

        }

        res.close();
        closeDatabase();
        return recipslist;

        }
</code>```

答:
When you call getActivity() method it return null because the fragment is not attached yet. Open the database in onCreate.

```<code>public class FragmentHome extends Fragment {
    private List<ItemRecipe> itemList = new ArrayList<>();
    private RecyclerView recyclerView;
    private RecipeAdapter mAdapter;
    private AppCompatActivity appCompatActivity;

    public FragmentHome() {
        setHasOptionsMenu(true);
    }

    public void onCreate(Bundle a) {
        super.onCreate(a);
        setHasOptionsMenu(true);
        databaseHelper db = new databaseHelper(getActivity());
    }
}
</code>```

Body:
The bug is that when I run my code on emulator the app is stopping with an error (java.lang.RuntimeException: Unable to start activity :
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getDatabasePath(java.lang.String)' on a null object reference) in the code String dbpath =mcontext.getDatabasePath(DATABASE_NAME).getPath();

myfragment :

public class FragmentHome extends Fragment {
    private List<ItemRecipe> itemList = new ArrayList<>();
    private RecyclerView recyclerView;
    private RecipeAdapter mAdapter;
    private AppCompatActivity appCompatActivity;
    databaseHelper db = new databaseHelper(getActivity());

    public FragmentHome() {
        setHasOptionsMenu(true);
    }

    public void onCreate(Bundle a) {
        super.onCreate(a);
        setHasOptionsMenu(true);
    }

sqldatabasehelper :

public class databaseHelper extends SQLiteOpenHelper {
    public static final String DATABASE_NAME = "recipes.db";
    public static final String DATABASE_location = Environment.getDataDirectory()+"data/com.recipes.cook/databases/";
private Context mcontext ;
private SQLiteDatabase mdatabase;

    public databaseHelper( Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }

    public  void openDatabase(){

String dbpath =mcontext.getDatabasePath(DATABASE_NAME).getPath();
if (mdatabase != null && mdatabase.isOpen()){
    return;
}
mdatabase=SQLiteDatabase.openDatabase(dbpath,null,SQLiteDatabase.OPEN_READWRITE);

    }

public void closeDatabase() {

    if (mdatabase != null) {

        mdatabase.close();
    }
}

    public ArrayList<ItemRecipe> get_all_name (){
        ItemRecipe itemRecipe=null;
  ArrayList<ItemRecipe> recipslist=new ArrayList<>();
openDatabase();
        Cursor res = mdatabase.rawQuery("select * from recipes",null);
        res.moveToFirst();
        while(!res.isAfterLast()){
           String recipe =res.getString(res.getColumnIndex("name"));
           String img=res.getString(res.getColumnIndex("image"));
           String time = res.getString(res.getColumnIndex("time"));
            int rating = res.getInt(res.getColumnIndex("rating"));

res.moveToNext();
            recipslist.add(

                    new ItemRecipe(

recipe,img,time,rating
                    )

            );

        }

        res.close();
        closeDatabase();
        return recipslist;

        }

Body:
When you call getActivity() method it return null because the fragment is not attached yet. Open the database in onCreate.

public class FragmentHome extends Fragment {
    private List<ItemRecipe> itemList = new ArrayList<>();
    private RecyclerView recyclerView;
    private RecipeAdapter mAdapter;
    private AppCompatActivity appCompatActivity;

    public FragmentHome() {
        setHasOptionsMenu(true);
    }

    public void onCreate(Bundle a) {
        super.onCreate(a);
        setHasOptionsMenu(true);
        databaseHelper db = new databaseHelper(getActivity());
    }
}


问:
How to convert Selenium By object to a CSS selector?
It is very common to locate objects using By in selenium webdriver. I am currently using a ByChained selector and I am wondering is there a way to convert a By object to a CSS selector? For example:

```<code>By selector = By.id('something');
String cssSelector = selector.toCSSselector();
// now cssSelector = "#something"
</code>```

答:
It's a hack, but it works (in most cases). So if you really need to, you can go with something like this:

```<code>    public String convertToCssSelectorString(By by) {
        String byString = by.toString();
        if (byString.startsWith("By.id: ")) {
            return "#" + byString.replaceFirst("By\\.id: ", "");
        } else if (byString.startsWith("By.className: ")) {
            return "." + byString.replaceFirst("By\\.className: ", "");
        } else if (byString.startsWith("By.cssSelector: ")) {
            return byString.replaceFirst("By\\.cssSelector: ", "");
        } else {
            throw new RuntimeException("Unsupported selector type: " + byString);
        }
    }
</code>```

It does not cover all possible selector types but you can add them in the same way. Except for xpath selector, I don't think it would be possible.

Body:
It is very common to locate objects using By in selenium webdriver. I am currently using a ByChained selector and I am wondering is there a way to convert a By object to a CSS selector? For example:

By selector = By.id('something');
String cssSelector = selector.toCSSselector();
// now cssSelector = "#something"

Body:
It's a hack, but it works (in most cases). So if you really need to, you can go with something like this:

    public String convertToCssSelectorString(By by) {
        String byString = by.toString();
        if (byString.startsWith("By.id: ")) {
            return "#" + byString.replaceFirst("By\\.id: ", "");
        } else if (byString.startsWith("By.className: ")) {
            return "." + byString.replaceFirst("By\\.className: ", "");
        } else if (byString.startsWith("By.cssSelector: ")) {
            return byString.replaceFirst("By\\.cssSelector: ", "");
        } else {
            throw new RuntimeException("Unsupported selector type: " + byString);
        }
    }

It does not cover all possible selector types but you can add them in the same way. Except for xpath selector, I don't think it would be possible.


问:
can't connect slots in QT
I have a main window with slots mainwindow.h

```<code>class MainWindow : public QMainWindow
public:
    MainWindow();
    ~MainWindow() {}

private slots:
    void open();
    void quit();
private:
    QTextEdit *textEdit;
    QAction *openAction;
    QAction *exitAction;
    QMenu *fileMenu;
};
MainWindow::MainWindow()
{
    openAction = new QAction("&Open", this);
    exitAction = new QAction("E&xit", this);

    connect(openAction, SIGNAL(triggered()), this, SLOT(open()));
    connect(exitAction, SIGNAL(triggered()), qApp, SLOT(quit()));

    fileMenu = menuBar()->addMenu("&File");
    fileMenu->addAction(openAction);
    fileMenu->addSeparator();
    fileMenu->addAction(exitAction);

    textEdit = new QTextEdit;
}
</code>```

In the mainwidnow.cpp file I realize this slot. Also I include .h filee in the .cpp file:

```<code>void MainWindow::open()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), "",
                                                tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));

    if (fileName != "") {
        QFile file(fileName);
        if (!file.open(QIODevice::ReadOnly)) {
            QMessageBox::critical(this, tr("Error"), tr("Could not open file"));
            return;
        }
        QTextStream in(&file);
        textEdit->setText(in.readAll());
        file.close();
    }
}
</code>```

I have successfully compiled. But when  I try to run program, I have this error

```<code>QObject::connect: No such slot QMainWindow::open()
</code>```

What is the problem?

答:
Add the Q_OBJECT macro to MainWindow:

```<code>class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    MainWindow();
    ~MainWindow() {}

private slots:
    void open();
    void quit();
private:
    QTextEdit *textEdit;
    QAction *openAction;
    QAction *exitAction;
    QMenu *fileMenu;
};
</code>```

Title: can't connect slots in QT

Body:
I have a main window with slots mainwindow.h

class MainWindow : public QMainWindow
public:
    MainWindow();
    ~MainWindow() {}

private slots:
    void open();
    void quit();
private:
    QTextEdit *textEdit;
    QAction *openAction;
    QAction *exitAction;
    QMenu *fileMenu;
};
MainWindow::MainWindow()
{
    openAction = new QAction("&Open", this);
    exitAction = new QAction("E&xit", this);

    connect(openAction, SIGNAL(triggered()), this, SLOT(open()));
    connect(exitAction, SIGNAL(triggered()), qApp, SLOT(quit()));

    fileMenu = menuBar()->addMenu("&File");
    fileMenu->addAction(openAction);
    fileMenu->addSeparator();
    fileMenu->addAction(exitAction);

    textEdit = new QTextEdit;
}

In the mainwidnow.cpp file I realize this slot. Also I include .h filee in the .cpp file:

void MainWindow::open()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), "",
                                                tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));

    if (fileName != "") {
        QFile file(fileName);
        if (!file.open(QIODevice::ReadOnly)) {
            QMessageBox::critical(this, tr("Error"), tr("Could not open file"));
            return;
        }
        QTextStream in(&file);
        textEdit->setText(in.readAll());
        file.close();
    }
}

I have successfully compiled. But when  I try to run program, I have this error

QObject::connect: No such slot QMainWindow::open()

What is the problem?

Body:
Add the Q_OBJECT macro to MainWindow:

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    MainWindow();
    ~MainWindow() {}

private slots:
    void open();
    void quit();
private:
    QTextEdit *textEdit;
    QAction *openAction;
    QAction *exitAction;
    QMenu *fileMenu;
};


问:
Converting Hex to RGB value in Python
Working off Jeremy's response here: Converting hex color to RGB and vice-versa I was able to get a python program to convert preset colour hex codes (example #B4FBB8), however from an end-user perspective we can't ask people to edit code & run from there. How can one prompt the user to enter a hex value and then have it spit out a RGB value from there?

Here's the code I have thus far:

```<code>def hex_to_rgb(value):
    value = value.lstrip('#')
    lv = len(value)
    return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))

def rgb_to_hex(rgb):
    return '#%02x%02x%02x' % rgb

hex_to_rgb("#ffffff")              # ==> (255, 255, 255)
hex_to_rgb("#ffffffffffff")        # ==> (65535, 65535, 65535)
rgb_to_hex((255, 255, 255))        # ==> '#ffffff'
rgb_to_hex((65535, 65535, 65535))  # ==> '#ffffffffffff'

print('Please enter your colour hex')

hex == input("")

print('Calculating...')
print(hex_to_rgb(hex()))
</code>```

Using the line print(hex_to_rgb('#B4FBB8')) I'm able to get it to spit out the correct RGB value which is (180, 251, 184)

It's probably super simple - I'm still pretty rough with Python.

答:
As HEX codes can be like "#FFF", "#000", "#0F0" or even "#ABC" that only use three digits. These are just the shorthand version of writing a code, which are the three pairs of identical digits "#FFFFFF", "#000000", "#00FF00" or "#AABBCC".

This function is made in such a way that it can work with both shorthands as well as the full length of HEX codes. Returns RGB values if the argument hsl = False else return HSL values.

import re

def hex_to_rgb(hx, hsl=False):
    """Converts a HEX code into RGB or HSL.
    Args:
        hx (str): Takes both short as well as long HEX codes.
        hsl (bool): Converts the given HEX code into HSL value if True.
    Return:
        Tuple of length 3 consisting of either int or float values.
    Raise:
        ValueError: If given value is not a valid HEX code."""
    if re.compile(r'#[a-fA-F0-9]{3}(?:[a-fA-F0-9]{3})?$').match(hx):
        div = 255.0 if hsl else 0
        if len(hx) <= 4:
            return tuple(int(hx[i]*2, 16) / div if div else
                         int(hx[i]*2, 16) for i in (1, 2, 3))
        return tuple(int(hx[i:i+2], 16) / div if div else
                     int(hx[i:i+2], 16) for i in (1, 3, 5))
    raise ValueError(f'"{hx}" is not a valid HEX code.')
```
<hr />
<p><em>Here are some IDLE outputs.</em></p>
<pre class="lang-py prettyprint-override"><code>>>> hex_to_rgb('#FFB6C1')
(255, 182, 193)

>>> hex_to_rgb('#ABC')
(170, 187, 204)

>>> hex_to_rgb('#FFB6C1', hsl=True)
(1.0, 0.7137254901960784, 0.7568627450980392)

>>> hex_to_rgb('#ABC', hsl=True)
(0.6666666666666666, 0.7333333333333333, 0.8)

>>> hex_to_rgb('#00FFFF')
(0, 255, 255)

>>> hex_to_rgb('#0FF')
(0, 255, 255)

>>> hex_to_rgb('#0FFG')  # When invalid hex is given.
ValueError: "#0FFG" is not a valid HEX code.
</code>```

Title: Converting Hex to RGB value in Python

Body:
Working off Jeremy's response here: Converting hex color to RGB and vice-versa I was able to get a python program to convert preset colour hex codes (example #B4FBB8), however from an end-user perspective we can't ask people to edit code & run from there. How can one prompt the user to enter a hex value and then have it spit out a RGB value from there?

Here's the code I have thus far:

def hex_to_rgb(value):
    value = value.lstrip('#')
    lv = len(value)
    return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))

def rgb_to_hex(rgb):
    return '#%02x%02x%02x' % rgb

hex_to_rgb("#ffffff")              # ==> (255, 255, 255)
hex_to_rgb("#ffffffffffff")        # ==> (65535, 65535, 65535)
rgb_to_hex((255, 255, 255))        # ==> '#ffffff'
rgb_to_hex((65535, 65535, 65535))  # ==> '#ffffffffffff'

print('Please enter your colour hex')

hex == input("")

print('Calculating...')
print(hex_to_rgb(hex()))

Using the line print(hex_to_rgb('#B4FBB8')) I'm able to get it to spit out the correct RGB value which is (180, 251, 184)

It's probably super simple - I'm still pretty rough with Python.

Body:
As HEX codes can be like "#FFF", "#000", "#0F0" or even "#ABC" that only use three digits. These are just the shorthand version of writing a code, which are the three pairs of identical digits "#FFFFFF", "#000000", "#00FF00" or "#AABBCC".

This function is made in such a way that it can work with both shorthands as well as the full length of HEX codes. Returns RGB values if the argument hsl = False else return HSL values.

import re

def hex_to_rgb(hx, hsl=False):
    """Converts a HEX code into RGB or HSL.
    Args:
        hx (str): Takes both short as well as long HEX codes.
        hsl (bool): Converts the given HEX code into HSL value if True.
    Return:
        Tuple of length 3 consisting of either int or float values.
    Raise:
        ValueError: If given value is not a valid HEX code."""
    if re.compile(r'#[a-fA-F0-9]{3}(?:[a-fA-F0-9]{3})?$').match(hx):
        div = 255.0 if hsl else 0
        if len(hx) <= 4:
            return tuple(int(hx[i]*2, 16) / div if div else
                         int(hx[i]*2, 16) for i in (1, 2, 3))
        return tuple(int(hx[i:i+2], 16) / div if div else
                     int(hx[i:i+2], 16) for i in (1, 3, 5))
    raise ValueError(f'"{hx}" is not a valid HEX code.')

Here are some IDLE outputs.

>>> hex_to_rgb('#FFB6C1')
(255, 182, 193)

>>> hex_to_rgb('#ABC')
(170, 187, 204)

>>> hex_to_rgb('#FFB6C1', hsl=True)
(1.0, 0.7137254901960784, 0.7568627450980392)

>>> hex_to_rgb('#ABC', hsl=True)
(0.6666666666666666, 0.7333333333333333, 0.8)

>>> hex_to_rgb('#00FFFF')
(0, 255, 255)

>>> hex_to_rgb('#0FF')
(0, 255, 255)

>>> hex_to_rgb('#0FFG')  # When invalid hex is given.
ValueError: "#0FFG" is not a valid HEX code.


问:
Using enums as status returned status indicators in C#
Just wondering what the general consensus was about returning enums from methods indicating the status. The notion of returning codes (ints) is pretty innate in oldschool systems programming (C) but I am wondering if the methodology for indicating the status has changed.

thanks

Edit: I am aware that enums are basically int values. I'm inquiring about the sheer practice of having methods start throwing around status codes (be them enums or ints) to indicate statuses altogether. It seems like a good practice but I was wondering if there is any negative feelings about the idea.

I would always choose an enum over an int return for a status code.

答:
If you are returning enums to indicate errors instead of throwing exceptions you are, of course, in a state of sin.

Are callers really interested in the state of something? I've generally found that sort of thing in C-style function libraries where there are no objects to represent state. This depends on what you are trying to do, but if you are (say) creating code to manage communication sockets, I'd strongly recommend wrapping them in classes and allow client code to detect their state through properties rather than as the result of an Open() method.

OwnerDisplayName: Chance

LastEditorDisplayName: Chance

OwnerDisplayName: Pontus Gagge


问:
Prior to purchasing, how do I know if I'll be able to control an Android phone's camera focus?
I know that the setFocusMode function in Camera.Parameters allows a programmer to control the camera focus.

But how do you know if that function will work on any particular phone? It might return NULL, meaning that the phone does not support focus control for its camera.

Its easy to tell which Android phones on the market have autofocus.

But if a manufacturer says their phone has autofocus, does that mean I can control the camera focus using setFocusMode?

I just don't want to buy a phone, and then find out setFocusMode does not change the focus.

If you are curious about what exactly I'm trying to do:  I'd like to switch between FOCUS_MODE_INFINITY and FOCUS_MODE_MACRO and take two different pictures of an object.

thanks,
SJK

答:
Check whether it reports the autofocus feature: http://developer.android.com/reference/android/content/pm/PackageManager.html#FEATURE_CAMERA_AUTOFOCUS

This is the same feature used by Market to filter apps that require autofocus.


问:
How to execute promises sequentially, passing the parameters from an array?
```<code>var myArray = [1, 2, 3, 4, 5, 6]

function myPromise(num){
  return new Promise(res => {
    window.setTimeout(()=>{
      res(  console.log("done: " + num)  )
    },2000)
  })
}

myPromise(myArray[0])
  .then(x => myPromise(myArray[1]))
  .then(x => myPromise(myArray[2]))
  .then(x => myPromise(myArray[3]))
  .then(x => myPromise(myArray[4]))
  .then(x => myPromise(myArray[5]))
</code>```

Right now, if I execute the statement above, it will run sequentially. In my actual use case the array is dynamically populated and I need to execute the myPromise() function for each member in myArray.

How can I make a "pauseable loop" that will loop for each item in the array, execute myPromise and wait for the promise to be resolved before continuing to the next iteration?

答:
Sequential:

you can use async await features to run promises sequentially . here's a snippet

```<code>async function chainPromiseCalls(asyncFunctions=[],respectiveParams=[]){

    for(let i=0;i<asyncFunctions.length;i++){
        const eachResult = await asyncFunctions[i](...respectiveParams[i]);
        // do what you want to do with each result

    }

    return ;
}

</code>```

Parallel:

for parallel you can just call each async function once in a loop , but if you do want to get their combined result , you can use Promise.all

```<code>function parallelPromiseCalls(asyncFunctions=[],respectiveParams=[]){
    return Promise.all(asyncFunctions.map((func,index)=>func(...respectiveParams[index])))
       .then(resultsList=>{
        resultsList.forEach((result,index)=>{
           // do what you want to do with each result in the list
        })
        return ;
    })
}

</code>```

note : I am considering respective parameters as an list of lists since multiple parameters should be passed to any one of the function , else if you have to pass only a single parameter to each then you can remove the spread operator.

Body:
var myArray = [1, 2, 3, 4, 5, 6]

function myPromise(num){
  return new Promise(res => {
    window.setTimeout(()=>{
      res(  console.log("done: " + num)  )
    },2000)
  })
}

myPromise(myArray[0])
  .then(x => myPromise(myArray[1]))
  .then(x => myPromise(myArray[2]))
  .then(x => myPromise(myArray[3]))
  .then(x => myPromise(myArray[4]))
  .then(x => myPromise(myArray[5]))

Right now, if I execute the statement above, it will run sequentially. In my actual use case the array is dynamically populated and I need to execute the myPromise() function for each member in myArray.

How can I make a "pauseable loop" that will loop for each item in the array, execute myPromise and wait for the promise to be resolved before continuing to the next iteration?

Body:
Sequential:

you can use async await features to run promises sequentially . here's a snippet

async function chainPromiseCalls(asyncFunctions=[],respectiveParams=[]){

    for(let i=0;i<asyncFunctions.length;i++){
        const eachResult = await asyncFunctions[i](...respectiveParams[i]);
        // do what you want to do with each result

    }

    return ;
}

Parallel:

for parallel you can just call each async function once in a loop , but if you do want to get their combined result , you can use Promise.all

function parallelPromiseCalls(asyncFunctions=[],respectiveParams=[]){
    return Promise.all(asyncFunctions.map((func,index)=>func(...respectiveParams[index])))
       .then(resultsList=>{
        resultsList.forEach((result,index)=>{
           // do what you want to do with each result in the list
        })
        return ;
    })
}

note : I am considering respective parameters as an list of lists since multiple parameters should be passed to any one of the function , else if you have to pass only a single parameter to each then you can remove the spread operator.


问:
Return a value inside a function after getting value from firebase storage closure Swift
I have a function which downloads data from firebase:

```<code>func downloadData(path: String) -> Data? {
    let data: Data?

    let storage = Storage.storage()
    storage.reference(forURL: path).getData(maxSize: 1024 * 1024) { (result, error) in

    if let error = error {
        print("\(error)")
    } else {
        data = result
        print("finished")
    }

    return data // <-- this is called before closue ends
}
</code>```

but it is not returning the value from storage closure.
I tried using a dispatch group

```<code> func downloadData(path: String) -> Data? {
     ...
     let group = DispatchGroup()
     group.enter()
     storage.reference(forURL: path).getData(maxSize: 1024 * 1024) { (result, error) in
         ...
         ...
         group.leave()
     }

    group.notify(queue: .main) {
        return data // <-- build time error! the function doesn't return a value
    }
}
</code>```

so I tried a different approach: instead of group.notify() I used:

```<code>group.wait()
</code>```

but it didn't work also. the whole app was frozen and nothing happened

and I tried another one:

```<code>let semaphore = DispatchSemaphore(value: 0)

storage.reference(forURL: path).getData(maxSize: 1024 * 1024) { (result, error) in
    ...
    ...
    semaphore.signal()
}

semaphore.wait()

return data // <-- nothing happens... it is not being executed
</code>```

Any ideas on how to figure this out?

UPDATE

I tried using the completion option but it still didn't wait until it is downloded.

this is my outerFunction:

```<code>    var soundData: Data?
    var imageData: Data?
    downloadData(path: soundPath) { sound in
        soundData = sound

        downloadData(path: imageData) { image in
             imageData = image
        }

    }

    doMoreStuff() // <-- called before completeion blocks executed
</code>```

答:
Use completion instead of returning ->

func downloadData(path: String, _ completion: @escaping (Data?) -> Void) {
    let data: Data?

    let storage = Storage.storage()
    storage.reference(forURL: path).getData(maxSize: 1024 * 1024) { (result, error) in

        if let error = error {
            print("\(error)")
        } else {
            data = result
            print("finished")
        }
        completion(data)
    }
}
```

<hr>

<p>Usage of the <code>downloadData(path:,_)</code></p>

<pre class="lang-swift prettyprint-override"><code>downloadData(path: "") { data in
    // Your data is in here
    print("Data is:", data)
}
</code>```

Body:
I have a function which downloads data from firebase:

func downloadData(path: String) -> Data? {
    let data: Data?

    let storage = Storage.storage()
    storage.reference(forURL: path).getData(maxSize: 1024 * 1024) { (result, error) in

    if let error = error {
        print("\(error)")
    } else {
        data = result
        print("finished")
    }

    return data // <-- this is called before closue ends
}

but it is not returning the value from storage closure.
I tried using a dispatch group

 func downloadData(path: String) -> Data? {
     ...
     let group = DispatchGroup()
     group.enter()
     storage.reference(forURL: path).getData(maxSize: 1024 * 1024) { (result, error) in
         ...
         ...
         group.leave()
     }

    group.notify(queue: .main) {
        return data // <-- build time error! the function doesn't return a value
    }
}

so I tried a different approach: instead of group.notify() I used:

group.wait()

but it didn't work also. the whole app was frozen and nothing happened

and I tried another one:

let semaphore = DispatchSemaphore(value: 0)

storage.reference(forURL: path).getData(maxSize: 1024 * 1024) { (result, error) in
    ...
    ...
    semaphore.signal()
}

semaphore.wait()

return data // <-- nothing happens... it is not being executed

Any ideas on how to figure this out?

UPDATE

I tried using the completion option but it still didn't wait until it is downloded.

this is my outerFunction:

    var soundData: Data?
    var imageData: Data?
    downloadData(path: soundPath) { sound in
        soundData = sound

        downloadData(path: imageData) { image in
             imageData = image
        }

    }

    doMoreStuff() // <-- called before completeion blocks executed

Body:
Use completion instead of returning ->

func downloadData(path: String, _ completion: @escaping (Data?) -> Void) {
    let data: Data?

    let storage = Storage.storage()
    storage.reference(forURL: path).getData(maxSize: 1024 * 1024) { (result, error) in

        if let error = error {
            print("\(error)")
        } else {
            data = result
            print("finished")
        }
        completion(data)
    }
}

Usage of the downloadData(path:,_)

downloadData(path: "") { data in
    // Your data is in here
    print("Data is:", data)
}


问:
Regex Match greedy, optional, non-capturing groups
I'm trying to capture two chunks of a string but ignoring anything after if one of two tokens are found.

Examples:

a/b/c would match (1) a/b/ and (2) c
a/b would match (1) a/ and (2) b
a would match (1) <nil> and (2) a

So ^(.*/)*(.*)$ will do what I want there.

Where it gets complicated, If one of two tokens (foo or bar) are found, ignore everything afterwards.

Examples:

a/b/c/foo/d would ignore /foo/d and match (1) a/b/ and (2) c
a/b/c/bar/d would ignore /bar/d and match (1) a/b/ and (2) c

So I tried this: ^(.*/)*(.*)(?:/(?:foo|bar)/.*)$ and the second set of examples matches but the first doesn't... because I didn't make the second half optional.

Then I tried making it optional ^(.*/)*(.*)(?:/(?:foo|bar)/.*)?$: and now the greediness of the first part takes over and nothing matches.

Is there a way to make this work?

答:
It seems you may use

```<code>^((?:(?!/(?:foo|bar)/).)*/)?([^/]*)(?:/(?:foo|bar)/.*)?$
</code>```

See the regex demo

Details

^ - start of string

((?:(?!/(?:foo|bar)/).)*/)? - Optional capturing group #1:

(?:(?!/(?:foo|bar)/).)* - any char, 0 or more occurrences (as many as possible), that does not start (i.e. is not the first char of) a /foo/ or /bar/ character sequence

/ - a / char

([^/]*) - Group 2: any zero or more chars other than / char

(?:/(?:foo|bar)/.*)? - an optional non-capturing group matching 1 or 0 occurrences of

/(?:foo|bar)/ - /foo/ or /bar/

.* - any 0 or more chars other than line break chars as many as possible

$ - end of string.

Body:
It seems you may use

^((?:(?!/(?:foo|bar)/).)*/)?([^/]*)(?:/(?:foo|bar)/.*)?$

See the regex demo

Details

^ - start of string

((?:(?!/(?:foo|bar)/).)*/)? - Optional capturing group #1:

(?:(?!/(?:foo|bar)/).)* - any char, 0 or more occurrences (as many as possible), that does not start (i.e. is not the first char of) a /foo/ or /bar/ character sequence

/ - a / char

([^/]*) - Group 2: any zero or more chars other than / char

(?:/(?:foo|bar)/.*)? - an optional non-capturing group matching 1 or 0 occurrences of

/(?:foo|bar)/ - /foo/ or /bar/

.* - any 0 or more chars other than line break chars as many as possible

$ - end of string.


问:
How to print a string before using "*" to unpack list
Is it possible to print a string before using the * operator when unpacking a tuple:

```<code>m = ['b', 'a', 'e']
print(*m, sep = ',')

b, a, e
</code>```

I tried to print something before it:

```<code>print("String: " + *m, sep = ",")
</code>```

My desired output would be:

```<code>String: b, a, e
</code>```

Is it possible to have a string print before this, and what would be the correct syntax?

答:
*m unpacks the list m into separate arguments. It's equivalent to:

```<code>print('b', 'a', 'e')
</code>```

You can add additional arguments before and after that:

```<code>print('string', *m, sep=',')
</code>```

is it possible to print that without the comma being after the string, and only having the comma apply to the items in the list?

Take your pick:

```<code>print(f'String: {", ".join(m)}')

print('String:', ', '.join(m), sep=' ')

print('String:', end=' ')
print(*m, sep=', ')
</code>```

Body:
Is it possible to print a string before using the * operator when unpacking a tuple:

m = ['b', 'a', 'e']
print(*m, sep = ',')

b, a, e

I tried to print something before it:

print("String: " + *m, sep = ",")

My desired output would be:

String: b, a, e

Is it possible to have a string print before this, and what would be the correct syntax?

Body:
*m unpacks the list m into separate arguments. It's equivalent to:

print('b', 'a', 'e')

You can add additional arguments before and after that:

print('string', *m, sep=',')

is it possible to print that without the comma being after the string, and only having the comma apply to the items in the list?

Take your pick:

print(f'String: {", ".join(m)}')

print('String:', ', '.join(m), sep=' ')

print('String:', end=' ')
print(*m, sep=', ')


问:
Getting 500 error after adding '/' in the URL path
I have a web app which is written in PHP and using apache ubuntu server.

Whenever I try to visit any URL with '/' in the end, it shows 500 Internal Error.

Eg: "https://webapp.com/features" - Works fine

"https://webapp.com/features/" - Throws 500 Error

This is my .htaccess

```<code>RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php

RewriteRule ^([a-zA-Z0-9\-\_]+)$ index.php?profile=$1 [NC]

# Return 404 if original request is .php
RewriteCond %{THE_REQUEST} "^[^ ]* .*?\.php[? ].*$"
RewriteRule .* - [L,R=404]
</code>```

I tried removeing some parts from .htaccess file, but still does not work.

Is it something to do with Apache config?

Appreciate your help!

答:
Solved!

Removed Trailing Slash From The URL With Permanent Redirect

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]
</code>```

Add this to your .htaccess file.

Body:
I have a web app which is written in PHP and using apache ubuntu server.

Whenever I try to visit any URL with '/' in the end, it shows 500 Internal Error.

Eg: "https://webapp.com/features" - Works fine

"https://webapp.com/features/" - Throws 500 Error

This is my .htaccess

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php

RewriteRule ^([a-zA-Z0-9\-\_]+)$ index.php?profile=$1 [NC]

# Return 404 if original request is .php
RewriteCond %{THE_REQUEST} "^[^ ]* .*?\.php[? ].*$"
RewriteRule .* - [L,R=404]

I tried removeing some parts from .htaccess file, but still does not work.

Is it something to do with Apache config?

Appreciate your help!

Body:
Solved!

Removed Trailing Slash From The URL With Permanent Redirect

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

Add this to your .htaccess file.


问:
Implement Redis point-to-point queue to guarantee message processing once by any consumer
Redis has very good implementation for PUBSUB where a message published on a channel will be received by multiple receivers registered for the topic.

What is the ideal way to implement point-to-point (i.e. queue) semantics where e.g. multiple receivers are registered with a single queue and as soon as a message is pushed to the queue it will be processed by only 1 receiver (listener)? Any Java reference example would help.

Here the idea is to a read huge file containing transaction records and hence each transaction should be processed only once.

I could see Redis Streams is advised, but I do not see a sound Java reference implementation

答:
Note that there is no direct implementation like for PUBSUB topic . Another reason to use Queue here is that there is no Durable Subscription in Publish Subscribve as well i.e. when subscriber is not up when the message sent your message will be lost. but below Queue implementation would save bit here.

Final Answer

LPUSH TEST_QUEUE Test message
LLEN TEST_QUEUE
BRPOP TEST_QUEUE 0

Java Implementation

```<code>while(true){
redisTemplate.opsForList().leftPop("TEST_QUEUE",0, TimeUnit.SECONDS);
int keySize =this.pushOperation.size("TEST_QUEUE");
//iterate keySize {
redisTemplate.opsForList().leftPop("TEST_QUEUE",0, TimeUnit.SECONDS);
}
}
</code>```

Body:
Note that there is no direct implementation like for PUBSUB topic . Another reason to use Queue here is that there is no Durable Subscription in Publish Subscribve as well i.e. when subscriber is not up when the message sent your message will be lost. but below Queue implementation would save bit here.

Final Answer

LPUSH TEST_QUEUE Test message
LLEN TEST_QUEUE
BRPOP TEST_QUEUE 0

Java Implementation

while(true){
redisTemplate.opsForList().leftPop("TEST_QUEUE",0, TimeUnit.SECONDS);
int keySize =this.pushOperation.size("TEST_QUEUE");
//iterate keySize {
redisTemplate.opsForList().leftPop("TEST_QUEUE",0, TimeUnit.SECONDS);
}
}


问:
run java server from python and wait until it is up
So I run java server from terminal calling it with:

java =Xmx12G - jar jar.jar --build ../foo --inMemory

then it takes some time for the server to step up, sometimes a minute sometime more.

I want to wait until it is up.

I used subprocess.call() but then it does not terminate, so it waits forever.
How can I wait until there is an output:

16:53:28.315 INFO (GrizzlyServer.java:153) Grizzly server running.

答:
There are 2 problems:

1.) subprocess.call() waits until the java server exits.

2.) When the parent (Python) process stops usually the child process gets killed.

In case you still need to make it via Python script, you could run the java server in a separate process group, so it's decoupled from the parent (Python process) - that just works on *nix OSes:

```<code>import os
import time
import subprocess

p = subprocess.Popen(
    ['nohup', 'java', '=Xmx12G', '-jar', 'jar.jar', '--build', '../foo', '--inMemory']
    stdout=open('/tmp/logOut.log', 'w'),
    stderr=open('/tmp/logErr.log', 'w'),
    preexec_fn=os.setpgrp
)

while True:
    if 'Grizzly server running' in open('/tmp/logOut.log').read():
        break
    time.sleep(1)
</code>```

Note: You need to pipe into files and read them in Python, if you would pipe into the Python script and the script exits the child process gets killed (no matter if the processes are decoupled)

Body:
There are 2 problems:

1.) subprocess.call() waits until the java server exits.

2.) When the parent (Python) process stops usually the child process gets killed.

In case you still need to make it via Python script, you could run the java server in a separate process group, so it's decoupled from the parent (Python process) - that just works on *nix OSes:

import os
import time
import subprocess

p = subprocess.Popen(
    ['nohup', 'java', '=Xmx12G', '-jar', 'jar.jar', '--build', '../foo', '--inMemory']
    stdout=open('/tmp/logOut.log', 'w'),
    stderr=open('/tmp/logErr.log', 'w'),
    preexec_fn=os.setpgrp
)

while True:
    if 'Grizzly server running' in open('/tmp/logOut.log').read():
        break
    time.sleep(1)

Note: You need to pipe into files and read them in Python, if you would pipe into the Python script and the script exits the child process gets killed (no matter if the processes are decoupled)


问:
How to animate tab bar's items
In my Swift app I have this class that handles a UITabBar.

```<code>class CustomTabBar: UITabBar {
    override func awakeFromNib() {
        super.awakeFromNib()
    }
}
</code>```

How can I animate the items when the user tap their?
I mean a CGAffine(scaleX: 1.1, y: 1.1)
So how I can animate the tab bar's items?

答:
This do the trick for me:</p>

```<code>class MyCustomTabController: UITabBarController {

    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        guard let barItemView = item.value(forKey: "view") as? UIView else { return }

        let timeInterval: TimeInterval = 0.3
        let propertyAnimator = UIViewPropertyAnimator(duration: timeInterval, dampingRatio: 0.5) {
            barItemView.transform = CGAffineTransform.identity.scaledBy(x: 0.9, y: 0.9)
        }
        propertyAnimator.addAnimations({ barItemView.transform = .identity }, delayFactor: CGFloat(timeInterval))
        propertyAnimator.startAnimation()
    }

}
</code>```

Title: How to animate tab bar's items

Body:
In my Swift app I have this class that handles a UITabBar.

class CustomTabBar: UITabBar {
    override func awakeFromNib() {
        super.awakeFromNib()
    }
}

How can I animate the items when the user tap their?
I mean a CGAffine(scaleX: 1.1, y: 1.1)
So how I can animate the tab bar's items?

Body:
This do the trick for me:

class MyCustomTabController: UITabBarController {

    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        guard let barItemView = item.value(forKey: "view") as? UIView else { return }

        let timeInterval: TimeInterval = 0.3
        let propertyAnimator = UIViewPropertyAnimator(duration: timeInterval, dampingRatio: 0.5) {
            barItemView.transform = CGAffineTransform.identity.scaledBy(x: 0.9, y: 0.9)
        }
        propertyAnimator.addAnimations({ barItemView.transform = .identity }, delayFactor: CGFloat(timeInterval))
        propertyAnimator.startAnimation()
    }

}


问:
Moq throws exceptions stating that an expression tree may not contain a call or invocation that uses optional arguments
I am writing NUnit test cases. I am writing test cases to get some values. Below is my setup.

```<code>[Test]
public async Task GetGeographyList_StateUnderTest_ExpectedBehavior()
{
    // Arrange
    var geographyBusinessLogic = this.CreateGeographyBusinessLogic();

    Geography geographyObj = new Geography() { Id = 101, Country = "India", Region = "APAC", SubRegion = "Asia South" };
    IEnumerable<Geography> geographyObjList =  new List<Geography>() { geographyObj };
    //this.geographyRepository.setupGetAsync<Geography>(geographyObjList);
    this.geographyRepository.Setup(
        x => x.GetAsync()).ReturnsAsync(geographyObjList);

    // Act
    var result = await geographyBusinessLogic.GetGeographyList();

    // Assert
    Assert.IsNotNull(result);
}
</code>```

In the above code, x => x.GetAsync() throws an error:

An expression tree may not contain a call or invocation that uses optional arguments

Below is my implementation of geographyBusinessLogic.GetGeographyList():

```<code>public async Task<IEnumerable<GeographyEntity>> GetGeographyList()
{
    var listOfGeographies = await this.GeographyRepository.GetAsync().ConfigureAwait(false);

    IEnumerable<GeographyEntity> result = from o in listOfGeographies
                                          select new GeographyEntity
                                          {
                                            Id = o.Id,
                                            Country = o.Country,
                                            Region = o.Region,
                                            SubRegion = o.SubRegion
                                          };
    return result;
}
</code>```

Below is the implementation of the GetAsync method:

```<code>public async Task<IEnumerable<T>> GetAsync(Expression<Func<T, bool>> filter = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, params Expression<Func<T, object>>[] includes)
{
    IQueryable<T> query = this.dbSet;
    foreach (Expression<Func<T, object>> include in includes)
    {
        query = query.Include(include);
    }

    if (filter != null)
    {
        query = query.Where(filter);
    }

    if (orderBy != null)
    {
        query = orderBy(query);
    }

    return await query.ToListAsync().ConfigureAwait(false);
}
</code>```

Can someone help me understand this error and can someone tell me what I am missing here? Any help would be greatly appreciated.

答:
You need to fill in all the optional arguments when you setup the mock. For example:

this.geographyRepository.Setup(x => x.GetAsync(
    It.IsAny<Expression<Func<Geography, bool>>>(),
    It.IsAny<Func<IQueryable<Geography>, IOrderedQueryable<Geography>>>(),
    It.IsAny<Expression<Func<Geography, object>>[]>())).ReturnsAsync(geographyObjList);
```

Body:
I am writing NUnit test cases. I am writing test cases to get some values. Below is my setup.

[Test]
public async Task GetGeographyList_StateUnderTest_ExpectedBehavior()
{
    // Arrange
    var geographyBusinessLogic = this.CreateGeographyBusinessLogic();

    Geography geographyObj = new Geography() { Id = 101, Country = "India", Region = "APAC", SubRegion = "Asia South" };
    IEnumerable<Geography> geographyObjList =  new List<Geography>() { geographyObj };
    //this.geographyRepository.setupGetAsync<Geography>(geographyObjList);
    this.geographyRepository.Setup(
        x => x.GetAsync()).ReturnsAsync(geographyObjList);

    // Act
    var result = await geographyBusinessLogic.GetGeographyList();

    // Assert
    Assert.IsNotNull(result);
}

In the above code, x => x.GetAsync() throws an error:

An expression tree may not contain a call or invocation that uses optional arguments

Below is my implementation of geographyBusinessLogic.GetGeographyList():

public async Task<IEnumerable<GeographyEntity>> GetGeographyList()
{
    var listOfGeographies = await this.GeographyRepository.GetAsync().ConfigureAwait(false);

    IEnumerable<GeographyEntity> result = from o in listOfGeographies
                                          select new GeographyEntity
                                          {
                                            Id = o.Id,
                                            Country = o.Country,
                                            Region = o.Region,
                                            SubRegion = o.SubRegion
                                          };
    return result;
}

Below is the implementation of the GetAsync method:

public async Task<IEnumerable<T>> GetAsync(Expression<Func<T, bool>> filter = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, params Expression<Func<T, object>>[] includes)
{
    IQueryable<T> query = this.dbSet;
    foreach (Expression<Func<T, object>> include in includes)
    {
        query = query.Include(include);
    }

    if (filter != null)
    {
        query = query.Where(filter);
    }

    if (orderBy != null)
    {
        query = orderBy(query);
    }

    return await query.ToListAsync().ConfigureAwait(false);
}

Can someone help me understand this error and can someone tell me what I am missing here? Any help would be greatly appreciated.