问:
How to access a service in ASP.NET Core before building the WebHost?
Let's assume that we have the following Program.cs:

public static class Program
{
    public static async Task Main(string[] args)
    {
        await CreateWebHostBuilder(args).Build().RunAsync();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args)
    {
        return WebHost
            .CreateDefaultBuilder(args)
            .ConfigureKestrel(options => { options.AllowSynchronousIO = false; })
            .ConfigureFanciness()
            .ConfigureLogging(ConfigureApplicationLogging)
            .UseStartup<Startup>();
    }

    private static void ConfigureApplicationLogging(WebHostBuilderContext context, ILoggingBuilder loggingBuilder)
    {
        var loggingConfiguration = context.Configuration.GetSection("Logging");

        loggingBuilder.AddConfiguration(loggingConfiguration);

        // var fancyService = SomehowGet<IFancyService>();
        // if (fancyService.IsEnabled)
        //     loggingBuilder.AddEventLog(loggingConfiguration);
    }

    public static IWebHostBuilder ConfigureFanciness(this IWebHostBuilder hostBuilder)
    {
        return hostBuilder.ConfigureServices(delegate (WebHostBuilderContext context, IServiceCollection services)
        {
            var fancinessConfiguration = context.Configuration.GetSection("Fanciness");
            services.Configure<FancinessSettings>(fancinessConfiguration);
            services.AddSingleton<IFancyService, FancyService>();

            // var fancyService = SomehowGet<IFancyService>();
            // fancyService.Initialize();
        });
    }
}
```

<p>And the following <code>FancyService.cs</code>:</p>

<pre class="lang-cs prettyprint-override"><code>public sealed class FancyService : IFancyService
{
    private readonly ILogger<FancyService> logger;
    private readonly IOptions<FancinessSettings> settings;

    public FancyService(ILogger<FancyService> logger, IOptions<FancinessSettings> settings)
    {
        this.logger = logger;
        this.settings = settings;
    }

    public bool IsEnabled { get; private set; }

    public void Initialize()
    {
        // do the initialization work and set IsEnabled to some value
    }
}

</code>```

As demonstrated in the example files, loggingBuilder.AddEventLog(loggingConfiguration) depends on IFancyService.IsEnabled that is set when IFancyService.Initialize() is called.

To do that, I need access to an instance of IFancyService; is there a way to achieve this?

答:
Once services.AddSingleton<IFancyService, FancyService>() has been called, you can get the instance of FancyService by building a ServiceProvider:

```<code>private static void ConfigureApplicationLogging(WebHostBuilderContext context, ILoggingBuilder loggingBuilder)
{
    var fancyService = loggingBuilder.Services.BuildServiceProvider().GetService<IFancyService>();
    fancyService.Initialize();
    var loggingConfiguration = context.Configuration.GetSection("Logging");

    loggingBuilder.AddConfiguration(loggingConfiguration);

    if (fancyService.IsEnabled)
        loggingBuilder.AddEventLog(loggingConfiguration);
}
</code>```

Body:
Let's assume that we have the following Program.cs:

public static class Program
{
    public static async Task Main(string[] args)
    {
        await CreateWebHostBuilder(args).Build().RunAsync();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args)
    {
        return WebHost
            .CreateDefaultBuilder(args)
            .ConfigureKestrel(options => { options.AllowSynchronousIO = false; })
            .ConfigureFanciness()
            .ConfigureLogging(ConfigureApplicationLogging)
            .UseStartup<Startup>();
    }

    private static void ConfigureApplicationLogging(WebHostBuilderContext context, ILoggingBuilder loggingBuilder)
    {
        var loggingConfiguration = context.Configuration.GetSection("Logging");

        loggingBuilder.AddConfiguration(loggingConfiguration);

        // var fancyService = SomehowGet<IFancyService>();
        // if (fancyService.IsEnabled)
        //     loggingBuilder.AddEventLog(loggingConfiguration);
    }

    public static IWebHostBuilder ConfigureFanciness(this IWebHostBuilder hostBuilder)
    {
        return hostBuilder.ConfigureServices(delegate (WebHostBuilderContext context, IServiceCollection services)
        {
            var fancinessConfiguration = context.Configuration.GetSection("Fanciness");
            services.Configure<FancinessSettings>(fancinessConfiguration);
            services.AddSingleton<IFancyService, FancyService>();

            // var fancyService = SomehowGet<IFancyService>();
            // fancyService.Initialize();
        });
    }
}

And the following FancyService.cs:

public sealed class FancyService : IFancyService
{
    private readonly ILogger<FancyService> logger;
    private readonly IOptions<FancinessSettings> settings;

    public FancyService(ILogger<FancyService> logger, IOptions<FancinessSettings> settings)
    {
        this.logger = logger;
        this.settings = settings;
    }

    public bool IsEnabled { get; private set; }

    public void Initialize()
    {
        // do the initialization work and set IsEnabled to some value
    }
}

As demonstrated in the example files, loggingBuilder.AddEventLog(loggingConfiguration) depends on IFancyService.IsEnabled that is set when IFancyService.Initialize() is called.

To do that, I need access to an instance of IFancyService; is there a way to achieve this?

Body:
Once services.AddSingleton<IFancyService, FancyService>() has been called, you can get the instance of FancyService by building a ServiceProvider:

private static void ConfigureApplicationLogging(WebHostBuilderContext context, ILoggingBuilder loggingBuilder)
{
    var fancyService = loggingBuilder.Services.BuildServiceProvider().GetService<IFancyService>();
    fancyService.Initialize();
    var loggingConfiguration = context.Configuration.GetSection("Logging");

    loggingBuilder.AddConfiguration(loggingConfiguration);

    if (fancyService.IsEnabled)
        loggingBuilder.AddEventLog(loggingConfiguration);
}


来源: stackexchange

问:
Why do we need to put self as the argument while calling another class function
I understand that while defining functions we have to use self as the first argument but in my particular coding example for insert_node method I got an error while calling insert_node(node,new_node) saying 3 arguments expected when I did not use self as the first argument in insert_node</p>

```<code>class Node:
    def __init__(self,value=None):
        self.value = value
        self.left = None
        self.right = None
class BST:
    def __init__(self,value=None):
        self.root = Node(value)
    def insert(self,value):
        if self.root == None:
            self.root = Node(value)
            return
        curr = self.root
        new_node = Node(value)
        def insert_node(self,node,new_node):
            if node.value == new_node.value:
                return
            if node.value > new_node.value:
                if node.left is None:
                    node.left = new_node
                    return
                else:
                    insert_node(self,node.left,new_node)
            else:
                if node.right is None:
                    node.right = new_node
                    return
                else:
                    insert_node(self,node.right,new_node)
        insert_node(self,curr,new_node)
</code>```

答:
insert_node() is not a method, it is a function nested inside insert(). You don't need to use self in this function, at all, because it makes no use of that argument, and even if it did, it could access the self reference from the parent insert() method as a closure.

Removing the self argument altogether works:

```<code>class BST:
    def __init__(self,value=None):
        self.root = Node(value)

    def insert(self,value):
        if self.root == None:
            self.root = Node(value)
            return
        curr = self.root
        new_node = Node(value)

        def insert_node(node, new_node):
            if node.value == new_node.value:
                return
            if node.value > new_node.value:
                if node.left is None:
                    node.left = new_node
                    return
                else:
                    insert_node(node.left, new_node)
            else:
                if node.right is None:
                    node.right = new_node
                    return
                else:
                    insert_node(node.right, new_node)

        insert_node(curr, new_node)
</code>```

You can move that function out of the insert() method too, it doesn't need to be nested there:

```<code>def insert_node(node, new_node):
    if node.value == new_node.value:
        return
    if node.value > new_node.value:
        if node.left is None:
            node.left = new_node
            return
        else:
            insert_node(node.left, new_node)
    else:
        if node.right is None:
            node.right = new_node
            return
        else:
            insert_node(node.right, new_node)

class BST:
    def __init__(self,value=None):
        self.root = Node(value)

    def insert(self,value):
        if self.root == None:
            self.root = Node(value)
            return
        curr = self.root
        new_node = Node(value)
        insert_node(curr, new_node)
</code>```

However, this really should be a method on the Node class:

```<code>class Node:
    def __init__(self, value=None):
        self.value = value
        self.left = None
        self.right = None

    def insert_node(self, new_node):
        if self.value == new_node.value:
            return
        if self.value > new_node.value:
            if self.left is None:
                self.left = new_node
                return
            else:
                self.left.insert_node(new_node)
        else:
            if self.right is None:
                self.right = new_node
                return
            else:
                self.right.insert_node(new_node)

class BST:
    def __init__(self,value=None):
        self.root = Node(value)

    def insert(self,value):
        if self.root == None:
            self.root = Node(value)
            return
        curr = self.root
        new_node = Node(value)
        curr.insert_node(new_node)
</code>```

Because you access insert_node() on Node instances (via curr.insert_node(...), self.left.insert_node(...) and self.right.insert_node(...), it is bound to that instance for you by Python, and passed into the method as self.

ContentLicense: CC BY-SA 4.0

Body:
I understand that while defining functions we have to use self as the first argument but in my particular coding example for insert_node method I got an error while calling insert_node(node,new_node) saying 3 arguments expected when I did not use self as the first argument in insert_node

class Node:
    def __init__(self,value=None):
        self.value = value
        self.left = None
        self.right = None
class BST:
    def __init__(self,value=None):
        self.root = Node(value)
    def insert(self,value):
        if self.root == None:
            self.root = Node(value)
            return
        curr = self.root
        new_node = Node(value)
        def insert_node(self,node,new_node):
            if node.value == new_node.value:
                return
            if node.value > new_node.value:
                if node.left is None:
                    node.left = new_node
                    return
                else:
                    insert_node(self,node.left,new_node)
            else:
                if node.right is None:
                    node.right = new_node
                    return
                else:
                    insert_node(self,node.right,new_node)
        insert_node(self,curr,new_node)

Body:
insert_node() is not a method, it is a function nested inside insert(). You don't need to use self in this function, at all, because it makes no use of that argument, and even if it did, it could access the self reference from the parent insert() method as a closure.

Removing the self argument altogether works:

class BST:
    def __init__(self,value=None):
        self.root = Node(value)

    def insert(self,value):
        if self.root == None:
            self.root = Node(value)
            return
        curr = self.root
        new_node = Node(value)

        def insert_node(node, new_node):
            if node.value == new_node.value:
                return
            if node.value > new_node.value:
                if node.left is None:
                    node.left = new_node
                    return
                else:
                    insert_node(node.left, new_node)
            else:
                if node.right is None:
                    node.right = new_node
                    return
                else:
                    insert_node(node.right, new_node)

        insert_node(curr, new_node)

You can move that function out of the insert() method too, it doesn't need to be nested there:

def insert_node(node, new_node):
    if node.value == new_node.value:
        return
    if node.value > new_node.value:
        if node.left is None:
            node.left = new_node
            return
        else:
            insert_node(node.left, new_node)
    else:
        if node.right is None:
            node.right = new_node
            return
        else:
            insert_node(node.right, new_node)

class BST:
    def __init__(self,value=None):
        self.root = Node(value)

    def insert(self,value):
        if self.root == None:
            self.root = Node(value)
            return
        curr = self.root
        new_node = Node(value)
        insert_node(curr, new_node)

However, this really should be a method on the Node class:

class Node:
    def __init__(self, value=None):
        self.value = value
        self.left = None
        self.right = None

    def insert_node(self, new_node):
        if self.value == new_node.value:
            return
        if self.value > new_node.value:
            if self.left is None:
                self.left = new_node
                return
            else:
                self.left.insert_node(new_node)
        else:
            if self.right is None:
                self.right = new_node
                return
            else:
                self.right.insert_node(new_node)

class BST:
    def __init__(self,value=None):
        self.root = Node(value)

    def insert(self,value):
        if self.root == None:
            self.root = Node(value)
            return
        curr = self.root
        new_node = Node(value)
        curr.insert_node(new_node)

Because you access insert_node() on Node instances (via curr.insert_node(...), self.left.insert_node(...) and self.right.insert_node(...), it is bound to that instance for you by Python, and passed into the method as self.


问:
Adding exactly 100 values to database using ajax
What is the easiest/fastest way to add 100 points to a database? Please assume all writes will not work due to duplicates, bad data, etc.

I'm trying to update a database with exactly 100 values.

Once I have a good piece of data, I need to add it to the database and I use a function called updateDB.

This function just writes a lat/lng coordinate to the database.  If there is a duplicate or the write fails, I send "error" from php and the loop should continue collecting data until I have exactly 100 points to the database.  Here's the function I'm using.

cct is used for xss prevention, please ignore it, this works fine.

```<code>////more above this
if(100-completed > dispatched)
    dispatched++;
    updateDB(lat,lng);
/// more junk and then this function
function updateDB(lat,lng)
{
    var cct = $("input[name=csrf_mysite]").val();
    $.ajax({
        type: "POST",
        url: "/form",
        data: {
            'lat': lat,
            'lng': lng,
            'id_set': id_set,
            'csrf_complexity': cct },
        success: function(result) {
            var obj = jQuery.parseJSON(result);
            if( obj.status === "OK" )
            {
                completed++;
                var marker = new google.maps.Marker(
                {
                    icon: markerIcon,
                    position: new google.maps.LatLng(lat, lng),
                    map: map
                });
                $( "#progressbar" ).progressbar( "option", {
                    value: completed,
                    max: 100
                });
                $("#amount").text("Getting image " + completed + " of 100");
            }
        },
        error: function(data){
            //alert(data.responseText);
            },
        complete: function(data){
            if(completed == 100)
                window.location = "/start/curate";
            dispatched--;
        }
    });
}
</code>```

This function does not work.  So any idea why?

It should work simply.  Call updateDB until it either reaches 100 added values and only call updateDB when there is no possibility that there will be extra calls.  Dispatch does not decrement properly so I'm assuming complete isn't called on every event.

Ideas?  Or any other way to do this would be awesome.

答:
It's strange. I've been able to load about 1000 DB loaded map markers in less than one second. </p>

<p>You shoud load all 100 server side and add them in one request. The request cost is usually quite big (for simple task like connect to db and load one item it may be like 70% time spent on request and 30% on actual work). </p>

Body:
What is the easiest/fastest way to add 100 points to a database? Please assume all writes will not work due to duplicates, bad data, etc.

I'm trying to update a database with exactly 100 values.

Once I have a good piece of data, I need to add it to the database and I use a function called updateDB.

This function just writes a lat/lng coordinate to the database.  If there is a duplicate or the write fails, I send "error" from php and the loop should continue collecting data until I have exactly 100 points to the database.  Here's the function I'm using.

cct is used for xss prevention, please ignore it, this works fine.

////more above this
if(100-completed > dispatched)
    dispatched++;
    updateDB(lat,lng);
/// more junk and then this function
function updateDB(lat,lng)
{
    var cct = $("input[name=csrf_mysite]").val();
    $.ajax({
        type: "POST",
        url: "/form",
        data: {
            'lat': lat,
            'lng': lng,
            'id_set': id_set,
            'csrf_complexity': cct },
        success: function(result) {
            var obj = jQuery.parseJSON(result);
            if( obj.status === "OK" )
            {
                completed++;
                var marker = new google.maps.Marker(
                {
                    icon: markerIcon,
                    position: new google.maps.LatLng(lat, lng),
                    map: map
                });
                $( "#progressbar" ).progressbar( "option", {
                    value: completed,
                    max: 100
                });
                $("#amount").text("Getting image " + completed + " of 100");
            }
        },
        error: function(data){
            //alert(data.responseText);
            },
        complete: function(data){
            if(completed == 100)
                window.location = "/start/curate";
            dispatched--;
        }
    });
}

This function does not work.  So any idea why?

It should work simply.  Call updateDB until it either reaches 100 added values and only call updateDB when there is no possibility that there will be extra calls.  Dispatch does not decrement properly so I'm assuming complete isn't called on every event.

Ideas?  Or any other way to do this would be awesome.

Body:
It's strange. I've been able to load about 1000 DB loaded map markers in less than one second.

You shoud load all 100 server side and add them in one request. The request cost is usually quite big (for simple task like connect to db and load one item it may be like 70% time spent on request and 30% on actual work).

ContentLicense: CC BY-SA 3.0


问:
Could not connect to eureka server from docker
I'm trying connection to eureka server from docker container.

The eureka server is running via "java -jar eureka-server.jar" command.
The eureka client is running on docker container.

Eureka server configuration is:

```<code>eureka:
  instance:
    hostname: eurekaserver
  client:
    registerWithEureka: true
    fetchRegistry: true
    serviceUrl:
      defaultZone: http://eurekaserver:8080/eureka/
</code>```

Eureka client configuration is:

```<code>spring:
  application:
    name: client-application
server:
  port: 8081
eureka:
  client:
    serviceUrl:
      defaultZone: http://eurekaserver:8080/eureka/
</code>```

I also tried to setup directly ip-address for example

```<code>eureka:
  client:
    serviceUrl:
      defaultZone: http://1.2.3.4:8080/eureka/
</code>```

But, unfortunately, I'm facing with stack trace:

```<code>[2019-05-26 09:44:14.714] slf4j - 1  INFO [main] --- o.a.h.i.c.DefaultHttpClient: Retrying connect to {}-> http://eurekaserver:8080
[2019-05-26 09:44:15.717] slf4j - 1 ERROR [main] --- c.n.d.s.t.d.RedirectingEurekaHttpClient: Request execution error
com.sun.jersey.api.client.ClientHandlerException: java.net.NoRouteToHostException: No route to host (Host unreachable)
    at com.sun.jersey.client.apache4.ApacheHttpClient4Handler.handle(ApacheHttpClient4Handler.java:187)
    at com.sun.jersey.api.client.filter.GZIPContentEncodingFilter.handle(GZIPContentEncodingFilter.java:123)
    at com.netflix.discovery.EurekaIdentityHeaderFilter.handle(EurekaIdentityHeaderFilter.java:27)
    at com.sun.jersey.api.client.Client.handle(Client.java:652)
    at com.sun.jersey.api.client.WebResource.handle(WebResource.java:682)
    at com.sun.jersey.api.client.WebResource.access$200(WebResource.java:74)
    at com.sun.jersey.api.client.WebResource$Builder.get(WebResource.java:509)
    ...
Caused by: java.net.NoRouteToHostException: No route to host (Host unreachable)
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:120)
    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:179)
    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:144)
    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:134)
    at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:612)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:447)
    at org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:884)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:117)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:55)
    at com.sun.jersey.client.apache4.ApacheHttpClient4Handler.handle(ApacheHttpClient4Handler.java:173)
    ... 72 common frames omitted
</code>```

And it is cause of

```<code>com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known server
</code>```

So my question is how to resolve connectivity?
Docker and eureka are placed on the same machine, because the command curl "http://1.2.3.4:8080/eureka/apps" returns app to me

How can I do some investigating, why a docker cannot resolve the host?

p.s. I've known about issue, when eureka-client looks at localhost hostname, but looks like my issue another.

Thank you.

答:
Resolved.
The cause of the issue was, don't use

```<code>registerWithEureka: true
fetchRegistry: true
</code>```

More about, find at first links after typing properties name in google

But if you use them, then you have to set serviceUrl as hostname and also add
instance.preferUseIpAddress: true

p.s. Not sure that is fully can solve this problem, but that, I have changed at application config.

Body:
I'm trying connection to eureka server from docker container.

The eureka server is running via "java -jar eureka-server.jar" command.
The eureka client is running on docker container.

Eureka server configuration is:

eureka:
  instance:
    hostname: eurekaserver
  client:
    registerWithEureka: true
    fetchRegistry: true
    serviceUrl:
      defaultZone: http://eurekaserver:8080/eureka/

Eureka client configuration is:

spring:
  application:
    name: client-application
server:
  port: 8081
eureka:
  client:
    serviceUrl:
      defaultZone: http://eurekaserver:8080/eureka/

I also tried to setup directly ip-address for example

eureka:
  client:
    serviceUrl:
      defaultZone: http://1.2.3.4:8080/eureka/

But, unfortunately, I'm facing with stack trace:

[2019-05-26 09:44:14.714] slf4j - 1  INFO [main] --- o.a.h.i.c.DefaultHttpClient: Retrying connect to {}-> http://eurekaserver:8080
[2019-05-26 09:44:15.717] slf4j - 1 ERROR [main] --- c.n.d.s.t.d.RedirectingEurekaHttpClient: Request execution error
com.sun.jersey.api.client.ClientHandlerException: java.net.NoRouteToHostException: No route to host (Host unreachable)
    at com.sun.jersey.client.apache4.ApacheHttpClient4Handler.handle(ApacheHttpClient4Handler.java:187)
    at com.sun.jersey.api.client.filter.GZIPContentEncodingFilter.handle(GZIPContentEncodingFilter.java:123)
    at com.netflix.discovery.EurekaIdentityHeaderFilter.handle(EurekaIdentityHeaderFilter.java:27)
    at com.sun.jersey.api.client.Client.handle(Client.java:652)
    at com.sun.jersey.api.client.WebResource.handle(WebResource.java:682)
    at com.sun.jersey.api.client.WebResource.access$200(WebResource.java:74)
    at com.sun.jersey.api.client.WebResource$Builder.get(WebResource.java:509)
    ...
Caused by: java.net.NoRouteToHostException: No route to host (Host unreachable)
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:120)
    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:179)
    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:144)
    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:134)
    at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:612)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:447)
    at org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:884)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:117)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:55)
    at com.sun.jersey.client.apache4.ApacheHttpClient4Handler.handle(ApacheHttpClient4Handler.java:173)
    ... 72 common frames omitted

And it is cause of

com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known server

So my question is how to resolve connectivity?
Docker and eureka are placed on the same machine, because the command curl "http://1.2.3.4:8080/eureka/apps" returns app to me

How can I do some investigating, why a docker cannot resolve the host?

p.s. I've known about issue, when eureka-client looks at localhost hostname, but looks like my issue another.

Thank you.

Body:
Resolved.
The cause of the issue was, don't use

registerWithEureka: true
fetchRegistry: true

More about, find at first links after typing properties name in google

But if you use them, then you have to set serviceUrl as hostname and also add
instance.preferUseIpAddress: true

p.s. Not sure that is fully can solve this problem, but that, I have changed at application config.


问:
My database isn't connecting, sqlite3.OperationalError
I'm trying to connect a database to make a self learning chatbot. However, I keep getting this error,

```<code>line 8, in <module>
    connection = sqlite3.connect('{}.db'.format(timeframe))
sqlite3.OperationalError: unable to open database file
</code>```

I've looked over the location of the database and tried to rewrite it. However it is, to my knowledge, written correctly.

```<code>with open("/Users/name/Desktop/fileName/RC_{}".format(timeframe.split('-')[0], timeframe), buffering=1000) as f:
</code>```

Below is where the error is saying I'm wrong at.

```<code>import sqlite3
import json
from datetime import datetime

timeframe = '2011-08'
sql_transaction = []

connection = sqlite3.connect('{}.db'.format(timeframe))
c = connection.cursor()
</code>```

The date, '2011-08' is supposed to be part of the database file 'RC_2011-08'.

答:
```<code>connection = sqlite3.connect('{}.db'.format(timeframe))
</code>```

should be

```<code>connection = sqlite3.connect('RC_{}'.format(timeframe.split('-')[0]))
</code>```

according to

```<code>with open("/Users/name/Desktop/fileName/RC_{}".format(timeframe.split('-')[0], timeframe), buffering=1000) as f:
</code>```

^^ your format() has two parameters but you only use the first one...

timeframe becomes "2011" because of

```<code>timeframe.split('-')[0]
</code>```

Body:
I'm trying to connect a database to make a self learning chatbot. However, I keep getting this error,

line 8, in <module>
    connection = sqlite3.connect('{}.db'.format(timeframe))
sqlite3.OperationalError: unable to open database file

I've looked over the location of the database and tried to rewrite it. However it is, to my knowledge, written correctly.

with open("/Users/name/Desktop/fileName/RC_{}".format(timeframe.split('-')[0], timeframe), buffering=1000) as f:

Below is where the error is saying I'm wrong at.

import sqlite3
import json
from datetime import datetime

timeframe = '2011-08'
sql_transaction = []

connection = sqlite3.connect('{}.db'.format(timeframe))
c = connection.cursor()

The date, '2011-08' is supposed to be part of the database file 'RC_2011-08'.

Body:
connection = sqlite3.connect('{}.db'.format(timeframe))

should be

connection = sqlite3.connect('RC_{}'.format(timeframe.split('-')[0]))

according to

with open("/Users/name/Desktop/fileName/RC_{}".format(timeframe.split('-')[0], timeframe), buffering=1000) as f:

^^ your format() has two parameters but you only use the first one...

timeframe becomes "2011" because of

timeframe.split('-')[0]


问:
How to write an algorithm that finds out in which lines specific word appear (I am using std::map)
I am writing code which calculate how many times each word appears in text ( I DID THIS TASK), but I can't find a way to calculate in which lines these words appeared.

I don't know where to start.

#include "header.h"
int main()
{
     //read the input, keeping track of each word and how often we see it
     std::ifstream in("tekstas.txt"); // input file

    std::string input;
    std::map<std::string, int> counters; // store each word and an associated counter
    std::vector<char>CharVect; // vector that stores symbols i want to replace
    formuojuChar(CharVect); // pushbacking that vector with symbols
     for (unsigned int i = 0; !in.eof(); i++)
    {
        std::getline(in, input);
        std::transform(input.begin(), input.end(), input.begin(), ::tolower); // lowering letters so for example "Mom"= "mom"
        Replace(input,CharVect, ' '); // replace symbols with space
        std::stringstream read(input);
        std::string word;
        while (read >> word)
        {
            ++counters[word];
        }
     }
     std::ofstream out("isvestis.txt");
    std::cout<<"Words that appear more than once in the text: "<<std::endl;
    std::cout<<std::endl;
     for (std::map<std::string, int>::const_iterator it = counters.begin();it != counters.end(); ++it)
        {
            if((it->second)>1)
            {

                std::cout<<"'" <<it->first<<"' " <<"appears "<<it->second <<" times in lines: " ;
                /*
                 ANY IDEAS ?
                 */
                std::cout<<std::endl;

            }
        }
        return 0;

}

```

I expect output to show me in which .txt file lines that word appears. TY

答:
This looks like a learning exercise that you want to do on your own, and I have a policy of not writing code for those.

However, one thing you could do is count the number of newlines you’ve encountered (which tells you the line you’re on) and, whenever you see the text you’re searching for, insert the current line number into a std::set<unsigned> or std::vector<unsigned>.

You would want to do this in a single loop, perhaps reading in a line at a time.  Whever you encounter the search term, update both the word counter and the set of line numbers.

Body:
I am writing code which calculate how many times each word appears in text ( I DID THIS TASK), but I can't find a way to calculate in which lines these words appeared.

I don't know where to start.

#include "header.h"
int main()
{
     //read the input, keeping track of each word and how often we see it
     std::ifstream in("tekstas.txt"); // input file

    std::string input;
    std::map<std::string, int> counters; // store each word and an associated counter
    std::vector<char>CharVect; // vector that stores symbols i want to replace
    formuojuChar(CharVect); // pushbacking that vector with symbols
     for (unsigned int i = 0; !in.eof(); i++)
    {
        std::getline(in, input);
        std::transform(input.begin(), input.end(), input.begin(), ::tolower); // lowering letters so for example "Mom"= "mom"
        Replace(input,CharVect, ' '); // replace symbols with space
        std::stringstream read(input);
        std::string word;
        while (read >> word)
        {
            ++counters[word];
        }
     }
     std::ofstream out("isvestis.txt");
    std::cout<<"Words that appear more than once in the text: "<<std::endl;
    std::cout<<std::endl;
     for (std::map<std::string, int>::const_iterator it = counters.begin();it != counters.end(); ++it)
        {
            if((it->second)>1)
            {

                std::cout<<"'" <<it->first<<"' " <<"appears "<<it->second <<" times in lines: " ;
                /*
                 ANY IDEAS ?
                 */
                std::cout<<std::endl;

            }
        }
        return 0;

}

I expect output to show me in which .txt file lines that word appears. TY


问:
My program is not working. Main is not returning a value
Why is it saying main must return a value?
I have tried almost nothing because i dont know much about c++ and I dont understand the meaning behind the error msg</p>

```<code>#include<iostream>
using namespace std;

int main()
{
    // one acre equals 43560 square feet

    double oneacre = 43560;

    // one square meter equals 10.7639 square feet
    double squaremeter = 10.7639;

    double halfacre = 0.5;

    double sfiha = oneacre * halfacre;

    double smiha = sfiha * squaremeter;

    cout << "in half acre there is" << sfiha << "square feet" << endl;

    cout << "in half acre there is" << smiha << "square meters" << endl;
}
</code>```

答:
The main function returns an int (as declared in the prototype int main().

This becomes the exit status of your program after it's run. You just need to add a line before the end of your main function to return an int.

Returning a 0 normally means no error so simply add return 0; after the last cout line.

Body:
Why is it saying main must return a value?
I have tried almost nothing because i dont know much about c++ and I dont understand the meaning behind the error msg

#include<iostream>
using namespace std;

int main()
{
    // one acre equals 43560 square feet

    double oneacre = 43560;

    // one square meter equals 10.7639 square feet
    double squaremeter = 10.7639;

    double halfacre = 0.5;

    double sfiha = oneacre * halfacre;

    double smiha = sfiha * squaremeter;

    cout << "in half acre there is" << sfiha << "square feet" << endl;

    cout << "in half acre there is" << smiha << "square meters" << endl;
}


问:
Generating an index of values to compound, but ignoring initial value in a scalable way
I am trying to generate an index that is derived from return data.

The new column I want to generate would be derived by taking 100 and then compounding this.  For this example:

first value = 100

second value = first value*(1+10/100) = 110

third value = second value *(1+20/100) = 132 and so on

Note that the first return value of 5 needs to be ignored.  I know I can just overwrite it to accomplish what I want, but I was wondering if there is a more elegant way to get the desired output.

I come close to getting what I want, but I need to ignore the first return of 5.  The expected output of the new_col would be 100, 110, 132.

```<code>**Reproducible example**

    # Load package
    library(tidyverse)

    # Create data
    df <- data.frame(asset = c("A", "A", "A"), return = c(5,10,20))
    df

# Generate new column
test <- df %>%
  mutate(new_col = 100) %>%   #initialize
  mutate(new_col = ifelse(row_number(new_col) == 1,
                          new_col,
                          lag(new_col, 1) * cumprod((1 + return/100))
                          )
         )
test
</code>```

Thanks in advance!

答:
An option would be accumulate

```<code>library(tidyverse)
df %>%
   mutate(newcol = accumulate(return[-1], ~ .x* (1 + .y/100), .init = 100))
#  asset return newcol
#1     A      5    100
#2     A     10    110
#3     A     20    132
</code>```

Or using cumprod

```<code>df %>%
    mutate(newcol = cumprod( c(100, 1 + return[-1]/100)))
</code>```

Or similar option in base R

```<code>Reduce(function(x, y) x * (1 + y/100), df$return[-1], init = 100, accumulate = TRUE)
#[1] 100 110 132
</code>```

Or with a for loop

```<code>df$newcol[1] <- 100
for(i in 2:nrow(df)) df$newcol[i] <- df$newcol[i-1] * (1 + df$return[i]/100)
</code>```

For multiple columns, use mutate_at

```<code>df1 %>%
    mutate_at(vars(starts_with('return')),
      list(newcol = ~  accumulate(.[-1], ~ .x * (1+ .y/100), .init = 100)))
#   asset return return2 return_newcol return2_newcol
#1     A      5      15           100            100
#2     A     10      12           110            112
#3     A     20      25           132            140
</code>```

data

```<code>df1 <- data.frame(asset = c("A", "A", "A"),
      return = c(5,10,20), return2 = c(15, 12, 25))
</code>```

Body:
I am trying to generate an index that is derived from return data.

The new column I want to generate would be derived by taking 100 and then compounding this.  For this example:

first value = 100

second value = first value*(1+10/100) = 110

third value = second value *(1+20/100) = 132 and so on

Note that the first return value of 5 needs to be ignored.  I know I can just overwrite it to accomplish what I want, but I was wondering if there is a more elegant way to get the desired output.

I come close to getting what I want, but I need to ignore the first return of 5.  The expected output of the new_col would be 100, 110, 132.

**Reproducible example**

    # Load package
    library(tidyverse)

    # Create data
    df <- data.frame(asset = c("A", "A", "A"), return = c(5,10,20))
    df

# Generate new column
test <- df %>%
  mutate(new_col = 100) %>%   #initialize
  mutate(new_col = ifelse(row_number(new_col) == 1,
                          new_col,
                          lag(new_col, 1) * cumprod((1 + return/100))
                          )
         )
test

Thanks in advance!

Body:
An option would be accumulate

library(tidyverse)
df %>%
   mutate(newcol = accumulate(return[-1], ~ .x* (1 + .y/100), .init = 100))
#  asset return newcol
#1     A      5    100
#2     A     10    110
#3     A     20    132

Or using cumprod

df %>%
    mutate(newcol = cumprod( c(100, 1 + return[-1]/100)))

Or similar option in base R

Reduce(function(x, y) x * (1 + y/100), df$return[-1], init = 100, accumulate = TRUE)
#[1] 100 110 132

Or with a for loop

df$newcol[1] <- 100
for(i in 2:nrow(df)) df$newcol[i] <- df$newcol[i-1] * (1 + df$return[i]/100)

For multiple columns, use mutate_at

df1 %>%
    mutate_at(vars(starts_with('return')),
      list(newcol = ~  accumulate(.[-1], ~ .x * (1+ .y/100), .init = 100)))
#   asset return return2 return_newcol return2_newcol
#1     A      5      15           100            100
#2     A     10      12           110            112
#3     A     20      25           132            140

data

df1 <- data.frame(asset = c("A", "A", "A"),
      return = c(5,10,20), return2 = c(15, 12, 25))


问:
How to start a Process and make its main window modal to the starting process's window?
I have a C# WinForms program thats starts another Process. The program then waits until the Process has finished.

Currently I use Process.WaitForExit(), but this means that while my program waits for the Process to end, it doesn't repaint and "looks" like it's not responding.

Is there any way for the Window of the Process that my program starts, be modal to my main form (i.e. you can't switch back to my program & the window repaints)?

Basically I want to do something like Form.ShowDialog(), except using the Process's Window as the Form to be shown as a dialog.

答: Another way that is a little non-standard but it works. Define a variable ProcessActive. On each of the controls visible in the app, check the variable and if set, don't process the controls event. Before launching the process, set the ProcessActive variable to True and launch the process with events. Define the Exited event on the process so that it sets the ProcessActive to False. They can switch back to the launching application and everything looks good. It just won't do anything until the process has exited. You might want to set the cursor to the hourglass so they know that the app is busy.</p>

ContentLicense: CC BY-SA 2.5


问:
How to name tkinter entry widgets created from a for loop?
I am new to python and tkinter, so I am having trouble with naming entry widgets that are created inside a for loop.  The goal is for my GUI to solve the user's linear programming optimization problem for fun.  I first ask the user how many variables there are in their problem, lets say n variables is inputted.  Then I create a for loop that creates n entry widgets corresponding to each variable to store the coefficient value of that variable.  I know how to create a single entry widget and name it so I can access it via name.get().  In my code, I tried to create a string name = "x" + str(i) where i is the for loop incrementing variable.  But then when I for example call x1.get() I get an error that x1 is not defined.  How do I fix this?  And thanks for the help in advance.

import tkinter as tkr

def objCos():
    x1Co = x1.get()
    print(x1Co)

def objFunction():
    global varFrame

    numOfVars = ofEntry.get()
    numOfVars = int(numOfVars)

    varFrame.destroy()
    varFrame = tkr.Frame(root)
    varFrame.pack(side = tkr.BOTTOM)

    varLabel = tkr.Label(varFrame, text = "Enter Objective Function Coefficients: ")
    varLabel.grid(row = 0, columnspan = 2)

    for i in range(1,numOfVars+1):
        strName = 'x' + str(i)
        strName = tkr.Entry(varFrame)
        strName.grid(row = i, column = 1)

        lbName = "varLabel" + str(i)
        lbName = tkr.Label(varFrame, text = "x"+ str(i) + " = ")
        lbName.grid(row = i, column = 0)

    varButton = tkr.Button(varFrame, text = "Update Objective Function Coefficients",
                           bg = "light grey", command = objCos)
    varButton.grid(row = numOfVars + 1, columnspan = 2)

root = tkr.Tk()

ofFrame = tkr.Frame(root)
ofFrame.pack(side = tkr.TOP)

global varFrame
varFrame = tkr.Frame(root)
varFrame.pack(side = tkr.BOTTOM)

ofLabel = tkr.Label(ofFrame, text = "Enter Number of Variables: ")
ofLabel.grid(row = 0, column = 0)

ofEntry = tkr.Entry(ofFrame)
ofEntry.grid(row =0, column = 1)

ofButton = tkr.Button(ofFrame, text = "Update Number of Variables",
                      bg = "light grey", command = objFunction)
ofButton.grid(row = 1, columnspan = 2)

root.mainloop()
```

答:
You can have a list of Entry widgets.  Below I've amended part of your code to append each Entry to entries as it's created.

```<code>entries = []
for i in range(1,numOfVars+1):
    entries.append(tkr.Entry(varFrame))
    entries[-1].grid(row = i, column = 1) # Grid the last item in entries

    lbName = "varLabel" + str(i)
    lbName = tkr.Label(varFrame, text = "x"+ str(i) + " = ")
    lbName.grid(row = i, column = 0)
</code>```

You can use the list to access the data entered later.

As an aside tkinter is generally imported as tk not as tkr.  It doesn't affect the operation but helps others understand what you've done.

Body:
You can have a list of Entry widgets.  Below I've amended part of your code to append each Entry to entries as it's created.

entries = []
for i in range(1,numOfVars+1):
    entries.append(tkr.Entry(varFrame))
    entries[-1].grid(row = i, column = 1) # Grid the last item in entries

    lbName = "varLabel" + str(i)
    lbName = tkr.Label(varFrame, text = "x"+ str(i) + " = ")
    lbName.grid(row = i, column = 0)

You can use the list to access the data entered later.

As an aside tkinter is generally imported as tk not as tkr.  It doesn't affect the operation but helps others understand what you've done.


问:
Unity overlap sphere detecting no collidiers
I have a problem concerning the overlap between two cubes. I have a level that is populated with many 1x1x1 cubes in 3D, the positions of which are changing. I want to test if, for a given position, two of the cubes are overlapping. To do this, I called Phsyics.OverlapSphereNonAlloc with a radius of .25 at the position (which is at the center of the overlapping cubes) to return a list of colliders. If more than one collider is returned, then two of the colliders are overlapping. That was the idea. The call instead returned no colliders. Here is a 2D cross-sectional illustration of what I am doing:

I believe that no colliders are found because the entire overlap sphere lies inside of the cube collider. But the unity docs say that Phsyics.OverlapSphere...

Returns an array with all colliders touching or inside the sphere.

I would've thought that, although Physics.OverlapSphere lies inside the cube collider, the cube collider is still technically inside the overlap sphere. Can anyone explain this to me or offer a workaround method to find an array of all the colliders at a given point?

答:
The issue stems from the way Unity has worded the docs. In your case the sphere is inside the collider, where overlapsphere returns colliders inside the sphere.

I am not sure what kind of scale we are operating on here, but one approach would be to use Vector3.Distance to compare all the blocks to your position. If you have thousands of blocks you could consider merging the two methods, where you have a large overlapsphere that then takes the result and narrows it down using the distance formula.

Hopefully this helps! :)


问:
Image float problems with Internet Explorer < 8
I've noticed a very annoying problem with the "float" css attribute and Internet Explorer 6 & 7.

I have an html with 2 simple images:

```<code><img src="aa.jpg">
<img src="bb.jpg" class="alignright">
</code>```

Here is the (very simple) CSS:

```<code>.alignright { float: right;}
</code>```

With explorer the first image (without any float attribute):
http://img5.imageshack.us/img5/2505/schermata4t.png

Is there any way to fix this problem with CSS ?

答:
For IE7 / IE6 you have to...

float the first image left

float the second image right (or left also)

add "clear:both" to the following text block (if you want it to appear after the images)

http://jsfiddle.net/Kyq5u/

I used spans to simulate images.

CSS...

```<code>
.img-a {
    background-color: red;
    padding: 100px;
    float: left;
}
.img-b {
    background-color: blue;
    padding: 100px;
    float: right;
}
p {
    clear: both;
}
</code>```

HTML...

```<code><span class="img-a"></span>
<span class="img-b"></span>

<p>
 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus eu  dolor et arcu dapibus cursus.
</p>
</code>```

Body:
I've noticed a very annoying problem with the "float" css attribute and Internet Explorer 6 & 7.

I have an html with 2 simple images:

Here is the (very simple) CSS:

.alignright { float: right;}

With explorer the first image (without any float attribute):
http://img5.imageshack.us/img5/2505/schermata4t.png

Is there any way to fix this problem with CSS ?

Body:
For IE7 / IE6 you have to...

float the first image left

float the second image right (or left also)

add "clear:both" to the following text block (if you want it to appear after the images)

http://jsfiddle.net/Kyq5u/

I used spans to simulate images.

CSS...

.img-a {
    background-color: red;
    padding: 100px;
    float: left;
}
.img-b {
    background-color: blue;
    padding: 100px;
    float: right;
}
p {
    clear: both;
}

HTML...

<span class="img-a"></span>
<span class="img-b"></span>

<p>
 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus eu  dolor et arcu dapibus cursus.
</p>


问:
Need help getting hello world app to work
I am trying to figure out how to get javascript to work with html in a separate file so that I can follow this tutorial https://www.w3schools.com/howto/howto_css_modals.asp and I'm having trouble getting my alert to pop up.

Here is my code.

So far I've only been able to get a button that doesn't do anything.

var hellobutton = document.getElementById("hello");
hellobutton.onclick = function() {
alert("Hello World")
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="/static/main.css">
    <script type="text/javascript" src="/static/main.js"></script>
    <title>Title</title>
</head>
<body>
<div class="content-section">
<h1>Page</h1>
    <input type = "button" id="hello" value = "Say Hello" />
</div>
</body>
</html></code>```

The code works here but not on my computer.

答:
It throws an error at line 2 because it couldn't find any element with that criteria already loaded and so it returns null at line 1. The value null is "nothing" so you can't set the onclick event of "nothing".
One way to fix this is to load the js after the html element is loaded(no need to edit the js file):

```<code><!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="/static/main.css">
  <title>Title</title>
 </head>
 <body>
  <div class="content-section">
  <h1>Page</h1>
  <input type = "button" id="hello" value = "Say Hello" />
  </div>
  <script type="text/javascript" src="/static/main.js"></script>
 </body>
</html>
</code>```

Or also by calling the js code only when the document is loaded(no need to edit html file):

```<code>document.addEventListener('DOMContentLoaded', function() {
   var hellobutton = document.getElementById("hello");
   hellobutton.onclick = function() {
          alert("Hello World")
   }
}, false);
</code>```

I found this code here.

Body:
I am trying to figure out how to get javascript to work with html in a separate file so that I can follow this tutorial https://www.w3schools.com/howto/howto_css_modals.asp and I'm having trouble getting my alert to pop up.

Here is my code.

So far I've only been able to get a button that doesn't do anything.

var hellobutton = document.getElementById("hello");
hellobutton.onclick = function() {
alert("Hello World")
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="/static/main.css">

    <title>Title</title>

Page

    <input type = "button" id="hello" value = "Say Hello" />

The code works here but not on my computer.

Body:
It throws an error at line 2 because it couldn't find any element with that criteria already loaded and so it returns null at line 1. The value null is "nothing" so you can't set the onclick event of "nothing".
One way to fix this is to load the js after the html element is loaded(no need to edit the js file):

<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="/static/main.css">
  <title>Title</title>
 </head>
 <body>
  <div class="content-section">
  <h1>Page</h1>
  <input type = "button" id="hello" value = "Say Hello" />
  </div>
  <script type="text/javascript" src="/static/main.js"></script>
 </body>
</html>

Or also by calling the js code only when the document is loaded(no need to edit html file):

document.addEventListener('DOMContentLoaded', function() {
   var hellobutton = document.getElementById("hello");
   hellobutton.onclick = function() {
          alert("Hello World")
   }
}, false);

I found this code here.


问:
why does boost::noncopyable require inheritance
Adding any noncopyable member to a class would prevent the automatic generation of copy construction and assignment operator. Why does boost require inheritance to use noncopyable?

I think I am not alone in my stylistic preference for

```<code>class MyUtility : public MyBase
{
   noncopyable guard;
   ...
};
</code>```

as opposed to

```<code>class MyUtility : public MyBase , private noncopyable
{
   ...
};
</code>```

Dave Abrahams is a smart guy, so he probably considered this possibility.  What am I missing? What does inheritence accomplish?

答:
I have run into this design decision myself and am thinking that the extra self documentation of having it as a member could actually be worth it. For example, someone might question "why is the class non-copyable?".

```<code>class VertexBuffer
{
   std::sr1::noncopyable<GLint> m_vbo;
   ...
};
</code>```

This now specifically tells me that the class is non-copyable because if the OpenGL VBO gets freed twice, it would be an error.

For example, in the example previous; I can copy a dog so why is your car so special that I cannot copy it?

I couple this with things like zeroinitialized / valueinitialized again for the additional documentation that I don't need to ensure these variable have been assigned before I use them.

```<code>class VertexBuffer
{
   std::sr1::noncopyable<GLint> m_vbo;
   std::sr1::zeroinitialized<int> m_vertexCount;
};
</code>```

I am a bit late to this party but does anyone have any more suggestions?

Body:
Adding any noncopyable member to a class would prevent the automatic generation of copy construction and assignment operator. Why does boost require inheritance to use noncopyable?

I think I am not alone in my stylistic preference for

class MyUtility : public MyBase
{
   noncopyable guard;
   ...
};

as opposed to

class MyUtility : public MyBase , private noncopyable
{
   ...
};

Dave Abrahams is a smart guy, so he probably considered this possibility.  What am I missing? What does inheritence accomplish?

Body:
I have run into this design decision myself and am thinking that the extra self documentation of having it as a member could actually be worth it. For example, someone might question "why is the class non-copyable?".

class VertexBuffer
{
   std::sr1::noncopyable<GLint> m_vbo;
   ...
};

This now specifically tells me that the class is non-copyable because if the OpenGL VBO gets freed twice, it would be an error.

For example, in the example previous; I can copy a dog so why is your car so special that I cannot copy it?

I couple this with things like zeroinitialized / valueinitialized again for the additional documentation that I don't need to ensure these variable have been assigned before I use them.

class VertexBuffer
{
   std::sr1::noncopyable<GLint> m_vbo;
   std::sr1::zeroinitialized<int> m_vertexCount;
};

I am a bit late to this party but does anyone have any more suggestions?


问:
How the below python code's time complexity is calculated as 0(n log n)?
I was understanding how Big O calculation works, after watching few videos when I started practicing few problems, I came to this code , where I thing the code time complexity is O(n^2) because outer loop will run O(n) and inner loop will also run O(n). Because inner loop has to iterate through all the list to find the unique name.
But the blog explains it as O(n log n), How?

```<code>def list_unique_names(phonebook):
    unique_names = []
    for name, phonenumber in phonebook:             # 1
        first_name, last_name = name.split(" ", 1)
        for unique in unique_names:                 # 2
            if unique == first_name:
                break
        else:
            unique_names.append(first_name)
    return len(unique_names)

phonebook = [
    ("John Doe", "555-555-5555"),
    ("Albert Einstein", "212-555-5555"),
    ("John Murphey", "202-555-5555"),
    ("Albert Rutherford", "647-555-5555"),
    ("Elaine Bodian", "301-555-5555"),
]
</code>```

I am expecting the complexity as O(n^2) but blog owner says its O(n log n).

答:
You are correct, the code you posted runs in O(n^2).

With the use of a set, you can do the same operation in amortized O(n):

```<code>def list_unique_names(phonebook):
    unique_names = set()
    for name, phonenumber in phonebook:
        first_name, _ = name.split(" ", 1)
        unique_names.add(first_name)
    return len(unique_names)
</code>```

Body:
I was understanding how Big O calculation works, after watching few videos when I started practicing few problems, I came to this code , where I thing the code time complexity is O(n^2) because outer loop will run O(n) and inner loop will also run O(n). Because inner loop has to iterate through all the list to find the unique name.
But the blog explains it as O(n log n), How?

def list_unique_names(phonebook):
    unique_names = []
    for name, phonenumber in phonebook:             # 1
        first_name, last_name = name.split(" ", 1)
        for unique in unique_names:                 # 2
            if unique == first_name:
                break
        else:
            unique_names.append(first_name)
    return len(unique_names)

phonebook = [
    ("John Doe", "555-555-5555"),
    ("Albert Einstein", "212-555-5555"),
    ("John Murphey", "202-555-5555"),
    ("Albert Rutherford", "647-555-5555"),
    ("Elaine Bodian", "301-555-5555"),
]

I am expecting the complexity as O(n^2) but blog owner says its O(n log n).

Body:
You are correct, the code you posted runs in O(n^2).

With the use of a set, you can do the same operation in amortized O(n):

def list_unique_names(phonebook):
    unique_names = set()
    for name, phonenumber in phonebook:
        first_name, _ = name.split(" ", 1)
        unique_names.add(first_name)
    return len(unique_names)


问:
How do I prevent a subversion user accessing part of the repository?
I'm using a Subversion repository hosted on Dreamhost for a project.

I would like to allow access to some users on a restricted basis. At the very least I would like to allow read-only access to some users, but ideally I would like to prevent some users seeing some parts of repository at all. I can't find user permissions mentioned in the web docs for Subversion though I assume it is there?

I'm used to using Perforce, so what I want is what p4 protect does for Perforce.

Thanks.

答:
See the accepted answer above. However, for Dreamhost specifics, in ~/svn directory there are two files for each repository repo_name.access and repo_name.passwd. Where repo_name is the name you gave your repository. You can edit the repo_name.access file as described in the accepted answer.

Don't forget to chmod 644 repo_name.access after you edit it so that apache can access it.

OwnerDisplayName: dave


问:
Convert Collection(java.util.Collection) to Observable(io.reactivex.Observable) in java 8
Is there any API method to convert Collection (java.util.Collection) to Observable (io.reactivex.Observable) ?

Let's say I have one collection, I want to convert the same to Observable. How can I do the same?

```<code>Collection<SchoolList> s = new ArrayList<>();
 s.addAll(sl);
</code>```

答: The observable factory method Observable.fromIterable(collection) is likely what your looking to use. See also the docs

Body:
Is there any API method to convert Collection (java.util.Collection) to Observable (io.reactivex.Observable) ?

Let's say I have one collection, I want to convert the same to Observable. How can I do the same?

Collection<SchoolList> s = new ArrayList<>();
 s.addAll(sl);


问:
Appending to instance variable also appends to init argument that was assigned to instance variable?
I have a recursive class (it has a method that puts an instance of itself in a dict that is a class variable), allowing me to iteratively chain objects together and make a sort of tree structure.  I've found that sometimes my data has some circularity to it and in an attempt to avoid getting lost in loops in the data, I'm trying to carry a list of nodes I've been to on the current branch, but things are not working at all as I expected.  Consider the following:

```<code>class test(object):
    a = 2
    def __init__(self, prevChain):
        self.chain = prevChain
        print("prevChain:", prevChain)
        print("self.chain:", self.chain)
        self.chain.append(self.a)
        print("prevChain:", prevChain)
        print("self.chain:", self.chain)

>>>test([1])
prevChain: [1]
self.chain: [1]
prevChain: [1, 2]
self.chain: [1, 2]
<__main__.test object at 0x00000027CCF1CEB00>
</code>```

How is the 2 getting added to prevChain and how can I prevent that from happening?  Is this the wrong way to go about tracking my location within my recursive objects?

答:
In the parameter, prevChain is passed as a reference. So, when you do this-

```<code>self.chain = prevChain
</code>```

you are actually setting the reference of prevChain to self.chain. Thus, prevChain and self.chain are the same variables.
To keep them separate, use deepcopy to create a new object of prevChain using the copy lib and then assign it to self.chain.

```<code>self.chain = copy.deepcopy(prevChain)
</code>```

Body:
I have a recursive class (it has a method that puts an instance of itself in a dict that is a class variable), allowing me to iteratively chain objects together and make a sort of tree structure.  I've found that sometimes my data has some circularity to it and in an attempt to avoid getting lost in loops in the data, I'm trying to carry a list of nodes I've been to on the current branch, but things are not working at all as I expected.  Consider the following:

class test(object):
    a = 2
    def __init__(self, prevChain):
        self.chain = prevChain
        print("prevChain:", prevChain)
        print("self.chain:", self.chain)
        self.chain.append(self.a)
        print("prevChain:", prevChain)
        print("self.chain:", self.chain)

>>>test([1])
prevChain: [1]
self.chain: [1]
prevChain: [1, 2]
self.chain: [1, 2]
<__main__.test object at 0x00000027CCF1CEB00>

How is the 2 getting added to prevChain and how can I prevent that from happening?  Is this the wrong way to go about tracking my location within my recursive objects?

Body:
In the parameter, prevChain is passed as a reference. So, when you do this-

self.chain = prevChain

you are actually setting the reference of prevChain to self.chain. Thus, prevChain and self.chain are the same variables.
To keep them separate, use deepcopy to create a new object of prevChain using the copy lib and then assign it to self.chain.

self.chain = copy.deepcopy(prevChain)


问:
How to redirect my user after posting a comment
So I just learned how to add comments on my blog. Now the problem is that I can't redirect my user to the concerned blog post. That's really frustrating because I see a lot of people on the Internet talking about get_absolute_url and it confuses me a lot. </p>

```<code>from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import Annonce, Comments
from django.shortcuts import get_object_or_404
from django.core.paginator import Paginator

def annonceView(request, annonce_id):
    annonce = get_object_or_404(Annonce, pk=annonce_id)
    comments = Comments.objects.filter(auteur=annonce_id)
    if request.method == "POST":
        content = request.POST["add_comment"]
        if content:
        new_comment = Comments.objects.create(content=content, auteur=annonce)
        new_comment.save()
        return redirect(annonce)

    context = {
        "annonce": annonce,
        "comments": comments,
    }

    return render(request, "annonces/annonce.html", context)
</code>```

答:
You are passing a object to redirect.

```<code>return redirect(annonce)
</code>```

But the function accepts a string:

```<code>return redirect("https://www.google.com")
</code>```

If you have a specific url in urls that you wanna redirect:

```<code>urlpatterns = [ path("example/", views.ExampleView.as_view(), name="example_view") ]

return redirect(reverse("example_view"))
</code>```

Body:
So I just learned how to add comments on my blog. Now the problem is that I can't redirect my user to the concerned blog post. That's really frustrating because I see a lot of people on the Internet talking about get_absolute_url and it confuses me a lot.

from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import Annonce, Comments
from django.shortcuts import get_object_or_404
from django.core.paginator import Paginator

def annonceView(request, annonce_id):
    annonce = get_object_or_404(Annonce, pk=annonce_id)
    comments = Comments.objects.filter(auteur=annonce_id)
    if request.method == "POST":
        content = request.POST["add_comment"]
        if content:
        new_comment = Comments.objects.create(content=content, auteur=annonce)
        new_comment.save()
        return redirect(annonce)

    context = {
        "annonce": annonce,
        "comments": comments,
    }

    return render(request, "annonces/annonce.html", context)

Body:
You are passing a object to redirect.

return redirect(annonce)

But the function accepts a string:

return redirect("https://www.google.com")

If you have a specific url in urls that you wanna redirect:

urlpatterns = [ path("example/", views.ExampleView.as_view(), name="example_view") ]

return redirect(reverse("example_view"))


问:
How can I select the second element from a group of divs with the same class?
I have 4 divs with the same class and I want to select with javaScript only the second one</p>

```<code><div class='container'></div>
<div class='container'></div>
<div class='container'></div>
<div class='container'></div>
</code>```

答:
For future reference, you can easily find the CSS selector for any element by inspecting it. For example, in Firefox, right-click the element on the page and click Inspect Element. Then in the inspector right-click the element's tag and click Copy->CSS Selector. In this case it will give you div.container:nth-child(2). You can then use that directly with document.querySelector:

let second = document.querySelector('div.container:nth-child(2)')
console.log(second)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='container'>1</div>
<div class='container'>2</div>
<div class='container'>3</div>
<div class='container'>4</div></code>```

Body:
For future reference, you can easily find the CSS selector for any element by inspecting it. For example, in Firefox, right-click the element on the page and click Inspect Element. Then in the inspector right-click the element's tag and click Copy->CSS Selector. In this case it will give you div.container:nth-child(2). You can then use that directly with document.querySelector:

let second = document.querySelector('div.container:nth-child(2)')
console.log(second)

<div class='container'>1</div>
<div class='container'>2</div>
<div class='container'>3</div>
<div class='container'>4</div>


问:
How to use async pipe with RxJS interval on dynamically created component?
I was wondering if it's somehow possible to use async pipe with RxJS interval() on dynamically created components like in this example . Because if I apply async pipe inside of it, then when the components will change the interval will be mostly ignored.

Let's say I want to get data every 15 minutes but the components change every 15 seconds.

The only way I found is to take data from one Observable and save it to another one but I don't think that this is the best practice. Is there some other way on how to achieve this or this practice is ok?

The Observable looks like this:

```<code>interval(1000 * 60 * 15).pipe(startWith(0), switchMap(() => this.http.get('someUrl')));
</code>```

Solution I found working:

```<code>interval(1000 * 60 * 15).pipe(startWith(0), switchMap(() => this.http.get('someUrl'))).subscribe((data) => {
  this.someUrlData = scheduled([data], asapScheduler);
});
</code>```

答:
The solution you have looks like it will work and is an acceptable way of doing it. If I were a new developer looking it over, though, I'd probably get confused about it and might attempt an ill-advised re-factor (unless you heavily commented it).

For that reason, I'd try a more readable approach (and forgive me if I'm misunderstanding your use case):

```<code>getData = new Subject<void>();

// UI Observable (referenced via the async pipe)
someData$ = this.getData.pipe(
    switchMap(() => this.http.get('someUrl')),
    shareReplay(1)
)

// Subscriptions (inside ngOnInit)
timer(0, 1000 * 60 * 15).subscribe(() => this.getData.next())
</code>```

The advantage here is you also maintain control over when you get data. You could easily add a "refresh" button to the screen and have it just next on the getData subject.

Just be sure to clean up your subscription on the timer, otherwise it will go forever.

Update:

To answer your original question, it's 100% best practice to take a value from one Observable and save it to another one. To get around the component being destroyed, though, the best practice is to put this in a service, that way it stays intact.

Body:
I was wondering if it's somehow possible to use async pipe with RxJS interval() on dynamically created components like in this example . Because if I apply async pipe inside of it, then when the components will change the interval will be mostly ignored.

Let's say I want to get data every 15 minutes but the components change every 15 seconds.

The only way I found is to take data from one Observable and save it to another one but I don't think that this is the best practice. Is there some other way on how to achieve this or this practice is ok?

The Observable looks like this:

interval(1000 * 60 * 15).pipe(startWith(0), switchMap(() => this.http.get('someUrl')));

Solution I found working:

interval(1000 * 60 * 15).pipe(startWith(0), switchMap(() => this.http.get('someUrl'))).subscribe((data) => {
  this.someUrlData = scheduled([data], asapScheduler);
});

Body:
The solution you have looks like it will work and is an acceptable way of doing it. If I were a new developer looking it over, though, I'd probably get confused about it and might attempt an ill-advised re-factor (unless you heavily commented it).

For that reason, I'd try a more readable approach (and forgive me if I'm misunderstanding your use case):

getData = new Subject<void>();

// UI Observable (referenced via the async pipe)
someData$ = this.getData.pipe(
    switchMap(() => this.http.get('someUrl')),
    shareReplay(1)
)

// Subscriptions (inside ngOnInit)
timer(0, 1000 * 60 * 15).subscribe(() => this.getData.next())

The advantage here is you also maintain control over when you get data. You could easily add a "refresh" button to the screen and have it just next on the getData subject.

Just be sure to clean up your subscription on the timer, otherwise it will go forever.

Update:

To answer your original question, it's 100% best practice to take a value from one Observable and save it to another one. To get around the component being destroyed, though, the best practice is to put this in a service, that way it stays intact.


问:
nhibernate disable unicode
in our company we are using nhibernate as our default mapper. I write queries using nhibernate criteria - I noticed that all parameters are send as unicode like this:

```<code>exec sp_executesql N'SELECT this_.ID as ID23_0_, this_.Nazwa as Nazwa23_0_, this_.Opis as Opis23_0_, this_.TypGrupy as TypGrupy23_0_, this_.CzyDystrybuowana as CzyDystr5_23_0_, this_.CzyAktywna as CzyAktywna23_0_ FROM Grupa this_ WHERE this_.Nazwa like @p0',N'@p0 nvarchar(50)',@p0=N'%something%'
</code>```

This is not the desired behavior. Is it possible to disable unicode in nhibernate queries?
Thanks

Romek

答:
I guess you have to match the mapping files to use Ansi String instead of Unicode whcih is probably the default value.

Check this mapping table between Database and Nhibernate, and the sections between 5.2.2 and 5.4 on Nhibernate - the Basic O/R Mapping, notice the type attribute i guess you can explicit define ANSIString in there.

Hope this help.

Title: nhibernate disable unicode

Body:
in our company we are using nhibernate as our default mapper. I write queries using nhibernate criteria - I noticed that all parameters are send as unicode like this:

exec sp_executesql N'SELECT this_.ID as ID23_0_, this_.Nazwa as Nazwa23_0_, this_.Opis as Opis23_0_, this_.TypGrupy as TypGrupy23_0_, this_.CzyDystrybuowana as CzyDystr5_23_0_, this_.CzyAktywna as CzyAktywna23_0_ FROM Grupa this_ WHERE this_.Nazwa like @p0',N'@p0 nvarchar(50)',@p0=N'%something%'

This is not the desired behavior. Is it possible to disable unicode in nhibernate queries?
Thanks

Romek


问:
Create URL based on values from model
I want to create a blog page and it works perfectly but I want to change the URL for the specific blog post. Currently the URL to the specific blog post is myurl.com/blog/pk , but I want it to be myurl.com/blog/category/title instead. How can I do this? Also appreciate any kind of critique to the code, if you feel like it.

Models.py

```<code>from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=20)

class Post(models.Model):
    title = models.SlugField(max_length = 250, null = True, blank = True)
    body = models.TextField()
    created_on = models.DateTimeField(null=True)
    last_modified = models.DateTimeField(null=True)
    categories = models.ManyToManyField('Category', related_name='posts')

class Comment(models.Model):
    author = models.CharField(max_length=60)
    body = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    post = models.ForeignKey('Post', on_delete=models.CASCADE)
</code>```

Views.py

```<code>from django.shortcuts import render
from .models import Post
from .models import Comment
from .forms import CommentForm
from django.http import HttpResponse

def blog_index(request):
    posts = Post.objects.all().order_by('-created_on')
    context = {
        "posts": posts,
    }
    return render(request, "blog_index.html", context)

def blog_category(request, category):
    posts = Post.objects.filter(
        categories__name__contains=category
    ).order_by(
        '-created_on'
    )
    if not posts:
        return HttpResponse(status=404)

    context = {
        "category": category,
        "posts": posts
    }
    return render(request, "blog_category.html", context)

def blog_detail(request, pk):
    post = Post.objects.get(pk=pk)

    form = CommentForm()
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = Comment(
                author=form.cleaned_data["author"],
                body=form.cleaned_data["body"],
                post=post
            )
            comment.save()

    comments = Comment.objects.filter(post=post)
    context = {
        "post": post,
        "comments": comments,
        "form": form,
    }
    return render(request, "blog_detail.html", context)
</code>```

App urls.py

```<code>from django.urls import path
from . import views

urlpatterns = [
    path("", views.blog_index, name="blog_index"),
    path("<int:pk>/", views.blog_detail, name="blog_detail"),
    path("<category>/", views.blog_category, name="blog_category"),
]
</code>```

Project URL

```<code>path('blog/', include('blog.urls')),
</code>```

答:
I am quite convinced that you do not want to use a title. Titles can usually contain spaces (), punctuations (~!#.?, etc.), and special characters. A URL can not contain most of these characters. One can indeed escape these characters, but then the URL looks quite ugly like:

```<code>myurl.com/some%20title%20containing%20spaces
</code>```

Now that is not very readable.

You can however use a slug, with a SlugField [Django-doc]. A SlugField is a CharField, but it does some cleaning to avoid ugly URLs. For example 'some title containing spaces' will be converted to some-title-containing-spaces.

You can add a SlugField to your CategoryModel like:

```<code>from django.utils.text import <b>slugify</b>

class Category(models.Model):
    name = models.CharField(max_length=20)
    <b>slug = models.SlugField(unique=True, blank=True)</b>

    def save(self, *args, **kwargs):
        <b>self.slug = slugify(self.name)</b>
        super().save(*args, **kwargs)</code>```

In the urlpatterns we can specify a slug as:

```<code># app/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.blog_index, name='blog_index'),
    path('<int:pk>/', views.blog_detail, name='blog_detail'),
    path('category/<b><slug:category_slug></b>/', views.blog_category, name='blog_category'),
]</code>```

We can then filter in our view on the slug:

```<code>from django.shortcuts import get_list_or_404
from .models import Post

def blog_category(request, category_slug):
    posts = get_list_or_404(Post.objects.filter(
        <b>categories__slug=category_slug</b>
    ).order_by(
        '-created_on'
    ))

    context = {
        'category': category,
        'posts': posts
    }
    return render(request, 'blog_category.html', context)</code>```

Generating unique slugs

It might sometimes happen that the slug already exists for another Category object, we can use a script to generate a unique slug, for example:

```<code>from django.utils.text import slugify
from itertools import count

class Category(models.Model):
    name = models.CharField(max_length=20)
    <b>slug = models.SlugField(unique=True, blank=True)</b>

    def save(self, *args, **kwargs):
        for i in count():
            slug = slugify('{}{}'.format(self.title, i or ''))
            if not Category.objects.filter(slug=slug).exists():
                break
        self.slug = slug
        super().save(*args, **kwargs)</code>```

Title: Create URL based on values from model

Body:
I want to create a blog page and it works perfectly but I want to change the URL for the specific blog post. Currently the URL to the specific blog post is myurl.com/blog/pk , but I want it to be myurl.com/blog/category/title instead. How can I do this? Also appreciate any kind of critique to the code, if you feel like it.

Models.py

from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=20)

class Post(models.Model):
    title = models.SlugField(max_length = 250, null = True, blank = True)
    body = models.TextField()
    created_on = models.DateTimeField(null=True)
    last_modified = models.DateTimeField(null=True)
    categories = models.ManyToManyField('Category', related_name='posts')

class Comment(models.Model):
    author = models.CharField(max_length=60)
    body = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    post = models.ForeignKey('Post', on_delete=models.CASCADE)

Views.py

from django.shortcuts import render
from .models import Post
from .models import Comment
from .forms import CommentForm
from django.http import HttpResponse

def blog_index(request):
    posts = Post.objects.all().order_by('-created_on')
    context = {
        "posts": posts,
    }
    return render(request, "blog_index.html", context)

def blog_category(request, category):
    posts = Post.objects.filter(
        categories__name__contains=category
    ).order_by(
        '-created_on'
    )
    if not posts:
        return HttpResponse(status=404)

    context = {
        "category": category,
        "posts": posts
    }
    return render(request, "blog_category.html", context)

def blog_detail(request, pk):
    post = Post.objects.get(pk=pk)

    form = CommentForm()
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = Comment(
                author=form.cleaned_data["author"],
                body=form.cleaned_data["body"],
                post=post
            )
            comment.save()

    comments = Comment.objects.filter(post=post)
    context = {
        "post": post,
        "comments": comments,
        "form": form,
    }
    return render(request, "blog_detail.html", context)

App urls.py

from django.urls import path
from . import views

urlpatterns = [
    path("", views.blog_index, name="blog_index"),
    path("<int:pk>/", views.blog_detail, name="blog_detail"),
    path("<category>/", views.blog_category, name="blog_category"),
]

Project URL

path('blog/', include('blog.urls')),

Body:
I am quite convinced that you do not want to use a title. Titles can usually contain spaces (), punctuations (~!#.?, etc.), and special characters. A URL can not contain most of these characters. One can indeed escape these characters, but then the URL looks quite ugly like:

myurl.com/some%20title%20containing%20spaces

Now that is not very readable.

You can however use a slug, with a SlugField [Django-doc]. A SlugField is a CharField, but it does some cleaning to avoid ugly URLs. For example 'some title containing spaces' will be converted to some-title-containing-spaces.

You can add a SlugField to your CategoryModel like:

from django.utils.text import slugify

class Category(models.Model):
    name = models.CharField(max_length=20)
    slug = models.SlugField(unique=True, blank=True)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super().save(*args, **kwargs)

In the urlpatterns we can specify a slug as:

# app/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.blog_index, name='blog_index'),
    path('<int:pk>/', views.blog_detail, name='blog_detail'),
    path('category/<slug:category_slug>/', views.blog_category, name='blog_category'),
]

We can then filter in our view on the slug:

from django.shortcuts import get_list_or_404
from .models import Post

def blog_category(request, category_slug):
    posts = get_list_or_404(Post.objects.filter(
        categories__slug=category_slug
    ).order_by(
        '-created_on'
    ))

    context = {
        'category': category,
        'posts': posts
    }
    return render(request, 'blog_category.html', context)

Generating unique slugs

It might sometimes happen that the slug already exists for another Category object, we can use a script to generate a unique slug, for example:

from django.utils.text import slugify
from itertools import count

class Category(models.Model):
    name = models.CharField(max_length=20)
    slug = models.SlugField(unique=True, blank=True)

    def save(self, *args, **kwargs):
        for i in count():
            slug = slugify('{}{}'.format(self.title, i or ''))
            if not Category.objects.filter(slug=slug).exists():
                break
        self.slug = slug
        super().save(*args, **kwargs)


问:
How can I convert columns to rows in Pandas?
I have something like this:

```<code>Values     Time
  22        0
  45        1
  65        2
  78        0
  12        1
  45        2
</code>```

and I want this:

```<code>Time    0    1    2
Val1    22   45   65
Val2    78   12   45
</code>```

How can I do it?

答:
This is pivot creating the index with cumcount

```<code>df['idx'] = 'Val' + (df.groupby('Time').cumcount()+1).astype(str)
df.pivot(index='idx', columns='Time', values='Values').rename_axis(None)
</code>```

Output:

```<code>Time   0   1   2
Val1  22  45  65
Val2  78  12  45
</code>```

Body:
I have something like this:

Values     Time
  22        0
  45        1
  65        2
  78        0
  12        1
  45        2

and I want this:

Time    0    1    2
Val1    22   45   65
Val2    78   12   45

How can I do it?

Body:
This is pivot creating the index with cumcount

df['idx'] = 'Val' + (df.groupby('Time').cumcount()+1).astype(str)
df.pivot(index='idx', columns='Time', values='Values').rename_axis(None)

Output:

Time   0   1   2
Val1  22  45  65
Val2  78  12  45


问:
How to fake a datacontext method with TypeMock Isolator
I want to test a class that uses Linq to SQL.
I have faked the datacontext with TypeMock Isolator, but the datacontext also has a function that I don't know how to fake.
This function is used in Linq to Sql-queries.

The function passes two arguments (int? a, string b), and returns an integer;
DC.MyMethod(int? a, string b)

How to I fake this?

```<code>//Fake datacontext
var fakeDC = Isolate.Fake.Instance<MyDataContext>();

//Fake --> this doesn't work
Isolate.WhenCalled((int? a, string b) => fakeDC.MyFunction(a,b).... ?
</code>```

Hope anyone can help

答:
Isolator by default ignores arguments passed to functions. To fake yours, you could simply use:

```<code>Isolate.WhenCalled(() => fakeDC.MyFunction(null, null)).WillReturn(...)
</code>```

If you need to make sure it was called with specific arguments, add WithExactArguments(), like this:

```<code>int? id = 10;
string name = "David";

Isolate.WhenCalled(() => fakeDC.MyFunction(id, name)).WithExactArguments().WillReturn(...);
</code>```

Hope that helps.

Body:
I want to test a class that uses Linq to SQL.
I have faked the datacontext with TypeMock Isolator, but the datacontext also has a function that I don't know how to fake.
This function is used in Linq to Sql-queries.

The function passes two arguments (int? a, string b), and returns an integer;
DC.MyMethod(int? a, string b)

How to I fake this?

//Fake datacontext
var fakeDC = Isolate.Fake.Instance<MyDataContext>();

//Fake --> this doesn't work
Isolate.WhenCalled((int? a, string b) => fakeDC.MyFunction(a,b).... ?

Hope anyone can help

Body:
Isolator by default ignores arguments passed to functions. To fake yours, you could simply use:

Isolate.WhenCalled(() => fakeDC.MyFunction(null, null)).WillReturn(...)

If you need to make sure it was called with specific arguments, add WithExactArguments(), like this:

int? id = 10;
string name = "David";

Isolate.WhenCalled(() => fakeDC.MyFunction(id, name)).WithExactArguments().WillReturn(...);

Hope that helps.


问:
Minimal example using LLVM's C API yields error: function and module have different contexts
I'm trying to implement a small example using the C API. I get an error message that the function context doesn't match the module context, which I can't figure out.

Here's my code:

#include <stdio.h>

#include <llvm-c/Analysis.h>
#include <llvm-c/Core.h>
#include <llvm-c/Target.h>
#include <llvm-c/TargetMachine.h>

int
main() {
    LLVMInitializeNativeTarget();
    LLVMInitializeNativeAsmPrinter();
    char* triple = LLVMGetDefaultTargetTriple();
    char* error;
    LLVMTargetRef target_ref;
    if (LLVMGetTargetFromTriple(triple, &target_ref, &error)) {
        printf("Error: %s\n", error);
        return 1;
    }
    LLVMTargetMachineRef tm_ref = LLVMCreateTargetMachine(
      target_ref,
      triple,
      "",
      "",
      LLVMCodeGenLevelDefault,
      LLVMRelocStatic,
      LLVMCodeModelJITDefault);
    LLVMDisposeMessage(triple);

    LLVMContextRef context = LLVMContextCreate();
    LLVMModuleRef module = LLVMModuleCreateWithNameInContext("module_name", context);
    // LLVMModuleRef module = LLVMModuleCreateWithName("module_name");

    LLVMTypeRef param_types[] = {LLVMIntType(32), LLVMIntType(32)};
    LLVMTypeRef func_type = LLVMFunctionType(LLVMIntType(32), param_types, 2, 0);

    LLVMValueRef func = LLVMAddFunction(module, "function_name", func_type);
    LLVMBasicBlockRef entry = LLVMAppendBasicBlock(func, "entry");

    LLVMBuilderRef builder = LLVMCreateBuilderInContext(context);
    // LLVMBuilderRef builder = LLVMCreateBuilder();
    LLVMPositionBuilderAtEnd(builder, entry);
    LLVMValueRef tmp = LLVMBuildAdd(builder, LLVMGetParam(func, 0), LLVMGetParam(func, 1), "add");
    LLVMBuildRet(builder, tmp);

    LLVMVerifyModule(module, LLVMAbortProcessAction, &error);
    LLVMDisposeMessage(error);
}
```

<p>And then my execution:</p>

<pre class="lang-sh prettyprint-override"><code>$ llvm-config --version
8.0.0
$ clang++ trash.cpp `llvm-config --cflags --ldflags` `llvm-config --libs` `llvm-config --system-libs`
$ ./a.out
Function context does not match Module context!
i32 (i32, i32)* @function_name
LLVM ERROR: Broken module found, compilation aborted!
</code>```

This is not an API that lends itself to very small examples; consequently, there's a decent chunk of code here.

If I use the currently commented out code which doesn't reference context, everything works fine. It's not clear to me why, when I call LLVMAddFunction, it doesn't just take its context from the module I passed in.

答: Well, I found the answer. Rather than LLVMIntType, I should be using LLVMIntTypeInContext. And rather than LLVMAppendBasicBlock, I should be using LLVMAppendBasicBlockInContext. I didn't realize previously such functions existed.

Body:
I'm trying to implement a small example using the C API. I get an error message that the function context doesn't match the module context, which I can't figure out.

Here's my code:

#include <stdio.h>

#include <llvm-c/Analysis.h>
#include <llvm-c/Core.h>
#include <llvm-c/Target.h>
#include <llvm-c/TargetMachine.h>

int
main() {
    LLVMInitializeNativeTarget();
    LLVMInitializeNativeAsmPrinter();
    char* triple = LLVMGetDefaultTargetTriple();
    char* error;
    LLVMTargetRef target_ref;
    if (LLVMGetTargetFromTriple(triple, &target_ref, &error)) {
        printf("Error: %s\n", error);
        return 1;
    }
    LLVMTargetMachineRef tm_ref = LLVMCreateTargetMachine(
      target_ref,
      triple,
      "",
      "",
      LLVMCodeGenLevelDefault,
      LLVMRelocStatic,
      LLVMCodeModelJITDefault);
    LLVMDisposeMessage(triple);

    LLVMContextRef context = LLVMContextCreate();
    LLVMModuleRef module = LLVMModuleCreateWithNameInContext("module_name", context);
    // LLVMModuleRef module = LLVMModuleCreateWithName("module_name");

    LLVMTypeRef param_types[] = {LLVMIntType(32), LLVMIntType(32)};
    LLVMTypeRef func_type = LLVMFunctionType(LLVMIntType(32), param_types, 2, 0);

    LLVMValueRef func = LLVMAddFunction(module, "function_name", func_type);
    LLVMBasicBlockRef entry = LLVMAppendBasicBlock(func, "entry");

    LLVMBuilderRef builder = LLVMCreateBuilderInContext(context);
    // LLVMBuilderRef builder = LLVMCreateBuilder();
    LLVMPositionBuilderAtEnd(builder, entry);
    LLVMValueRef tmp = LLVMBuildAdd(builder, LLVMGetParam(func, 0), LLVMGetParam(func, 1), "add");
    LLVMBuildRet(builder, tmp);

    LLVMVerifyModule(module, LLVMAbortProcessAction, &error);
    LLVMDisposeMessage(error);
}

And then my execution:

$ llvm-config --version
8.0.0
$ clang++ trash.cpp `llvm-config --cflags --ldflags` `llvm-config --libs` `llvm-config --system-libs`
$ ./a.out
Function context does not match Module context!
i32 (i32, i32)* @function_name
LLVM ERROR: Broken module found, compilation aborted!

This is not an API that lends itself to very small examples; consequently, there's a decent chunk of code here.

If I use the currently commented out code which doesn't reference context, everything works fine. It's not clear to me why, when I call LLVMAddFunction, it doesn't just take its context from the module I passed in.


问:
How to make random pick python differently?
I want to make a bot that sending 3 emoji but its different emoji , but when im running it , the bot took one emoji and sending a same 3 emoji, how do i make it take the different 3 emoji?

```<code>list  = ['', '', '', '', '', '', '', '', '', '', '', '', '', '']
text = random.choice(list)
</code>```

that the code

edit : can you tell me whats wrong in this one?

```<code>import discord
import requests
import random
import sys

token = sys.argv[1]
chan = sys.argv[2]
client = discord.Client()
list = requests.get('emoji.txt').text.split("\n")

@client.event
async def on_ready():
    txtchan = client.get_channel(int(chan))
    while not client.is_closed():
        message = ''
        for x in range(5):
            message += random.choice(list)
        await txtchan.send(message)
client.run(token, bot=False)
</code>```

Body:
I want to make a bot that sending 3 emoji but its different emoji , but when im running it , the bot took one emoji and sending a same 3 emoji, how do i make it take the different 3 emoji?

list  = ['', '', '', '', '', '', '', '', '', '', '', '', '', '']
text = random.choice(list)

that the code

edit : can you tell me whats wrong in this one?

import discord
import requests
import random
import sys

token = sys.argv[1]
chan = sys.argv[2]
client = discord.Client()
list = requests.get('emoji.txt').text.split("\n")

@client.event
async def on_ready():
    txtchan = client.get_channel(int(chan))
    while not client.is_closed():
        message = ''
        for x in range(5):
            message += random.choice(list)
        await txtchan.send(message)
client.run(token, bot=False)

Body:
You can make a generator that yields from a random.sample in a loop. Every time it's used up all of the sample the loop will continue and make a new sample. Then use itertools.slice to grab however many you want for as long as you want.

from itertools import islice
import random

def ran(l):
    while True:
        yield from random.sample(l, len(l))

l  = ['', '', '', '', '', '', '', '', '', '', '', '', '', '']

randIter = ran(l)
for i in range(20):
    print(list(islice(randIter, 7))) # pull off 7 at a time to make it easy to verify:

Result

['', '', '', '', '', '', '']
['', '', '', '', '', '', '']
['', '', '', '', '', '', '']
['', '', '', '', '', '', '']
['', '', '', '', '', '', '']
['', '', '', '', '', '', '']
['', '', '', '', '', '', '']
['', '', '', '', '', '', '']
['', '', '', '', '', '', '']
['', '', '', '', '', '', '']
['', '', '', '', '', '', '']
['', '', '', '', '', '', '']
['', '', '', '', '', '', '']
['', '', '', '', '', '', '']
['', '', '', '', '', '', '']
['', '', '', '', '', '', '']
['', '', '', '', '', '', '']
['', '', '', '', '', '', '']
['', '', '', '', '', '', '']
['', '', '', '', '', '', '']

This uses all 14 in random order before repeating and each repeat gets a new order.


问:
Kotlin: open new Activity inside of a Fragment
How can I open a new Activity inside of a fragment when using a button?

I tried this

```<code>override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    LogOut_btn.setOnClickListener {
        //FirebaseAuth.getInstance().signOut()
        val intent = Intent (this, Main::class.java)
        startActivity(intent)
    }
}
</code>```

val intent = Intent doesn't seem to work in a fragment.

Any idea how I can start a new activity inside a fragment?

答:
Also an option (for kotlin).
In onCreateView set onClickListener for a button:</p>

```<code>button.setOnClickListener {
    requireActivity().run {
        startActivity(Intent(this, MainActivity::class.java))
        finish() // If activity no more needed in back stack
    }
}
</code>```

Body:
How can I open a new Activity inside of a fragment when using a button?

I tried this

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    LogOut_btn.setOnClickListener {
        //FirebaseAuth.getInstance().signOut()
        val intent = Intent (this, Main::class.java)
        startActivity(intent)
    }
}

val intent = Intent doesn't seem to work in a fragment.

Any idea how I can start a new activity inside a fragment?

Body:
Also an option (for kotlin).
In onCreateView set onClickListener for a button:

button.setOnClickListener {
    requireActivity().run {
        startActivity(Intent(this, MainActivity::class.java))
        finish() // If activity no more needed in back stack
    }
}