问:
Logging the data in Trace.axd to a text/xml file
In trying to track down a performance issue that is only occurring in our production environment, we have enabled tracing within the app so see method calls and page load times.

This is working well and there is lots of information that helps to track down issues. However, the only way of viewing this information is to browse to the Trace.axd and then view each request individually.

It is also only possible to track the first X requests in this way and X has a maximum limit of 10,000.

Is there a way to direct this trace information to a file or database? I believe this can be done using System.Diagnostics, however, I am not having much luck.

I have enabled tracing using

```<code><trace enabled="true" writeToDiagnosticsTrace="true" />
</code>```

I have tried using the XmlWriterTraceListener using

```<code>  <system.diagnostics>
    <trace autoflush="true">
      <listeners>
        <add
          name="XmlWriterTraceListener"
          type="System.Diagnostics.XmlWriterTraceListener"
          initializeData="c:\trace.xml"
          />
      </listeners>
    </trace>
  </system.diagnostics>
</code>```

This results in an xml file containing the timestamps and data for the trace items such as "Begin Load", "End Load", etc.

However, it only seems to log a single request and does not log all requests. In addition, whilst the load times are useful, ideally I would like to have available all of the information that can be seen in the Trace.axd, such as request data, post data, session data, etc.

Is this possible at all without any major code changes? Ideally I would like to enable this using only web.config changes.

Alternatively, I have looked into other applications such as RedGate and Equatec's profiling tools, however, I would like to exhaust the non invasive tracing options first.

The application is written in ASP.Net 3.5 and C#.

答:
I have a standard HttpModule i use for all my web applications to monitor performance. The logger used can be changed, also can do things like remove white space from source, compress, or send emails if certain limits are reached. Its easier than trawling through asp.net traces as you get only the information you decide is importent.

```<code>public class PerfHttpModule : IHttpModule {

    private static Common.Logging.ILog log = Common.Logging.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    public static readonly string CONTEXT_RequestStart = "PerfHttpModule_RequestStart";
    public static readonly string CONTEXT_RequestId = "PerfHttpModule_RequestId";

    public void Init(HttpApplication context) {
        context.BeginRequest += new EventHandler(context_BeginRequest);
        context.EndRequest += new EventHandler(context_EndRequest);
    }

    private void context_BeginRequest(object sender, EventArgs e) {
        try {
            if (HttpContext.Current != null) {
                HttpContext.Current.Items[CONTEXT_RequestStart] = DateTime.Now;
                HttpContext.Current.Items[CONTEXT_RequestId] = random.Next(999999).ToString("D6");
                log.Info("Url: " + HttpContext.Current.Request.Url + " (" + HttpContext.Current.Request.ContentLength + ")");
            }
        } catch {
        }
    }

    private void context_EndRequest(object sender, EventArgs e) {
        if (HttpContext.Current.Items.Contains(CONTEXT_RequestStart)) {
            DateTime time1 = (DateTime)HttpContext.Current.Items[CONTEXT_RequestStart];
            DateTime time2 = DateTime.Now;
            double ms = (time2 - time1).TotalMilliseconds;
            log.Info("TotalMilliseconds: " + ms);
            if (ms > AppSettings.SlowPage || ms > AppSettings.ErrorSlowPage) {
                StringBuilder sb = new StringBuilder();
                sb.Append("Slow page detected." + "\t");
                sb.Append("TotalMilliseconds: " + ms + "\t");
                sb.Append("Url: " + HttpContext.Current.Request.Url.ToString());
                if (ms > AppSettings.ErrorSlowPage) {
                    log.Error(sb.ToString());
                } else if (ms > AppSettings.SlowPage) {
                    log.Warn(sb.ToString());
                }
            }
        }
    }
}
</code>```

UPDATE

```<code>        if (HttpContext.Current != null) {
                NameValueCollection tmp = new NameValueCollection(HttpContext.Current.Request.ServerVariables);
                foreach (string i in tmp.Keys) {

                }
            if (HttpContext.Current.Server != null) {
                if (HttpContext.Current.Server.GetLastError() != null) {

                }
            }
            if (HttpContext.Current.Session != null) {
                foreach (string i in HttpContext.Current.Session.Keys) {

                }
            }
            if (HttpContext.Current.Request.Cookies != null) {
                foreach (string i in HttpContext.Current.Request.Cookies.Keys) {

                }
            }
            if (HttpContext.Current.Response.Cookies != null) {
                foreach (string i in HttpContext.Current.Response.Cookies.Keys) {

                }
            }
            if (HttpContext.Current.Items != null) {
                foreach (string i in HttpContext.Current.Items.Keys) {

                }
            }
            if (HttpContext.Current.Request.Form != null) {
                foreach (string i in HttpContext.Current.Request.Form.Keys) {

                }
            }
        }
</code>```

Body:
In trying to track down a performance issue that is only occurring in our production environment, we have enabled tracing within the app so see method calls and page load times.

This is working well and there is lots of information that helps to track down issues. However, the only way of viewing this information is to browse to the Trace.axd and then view each request individually.

It is also only possible to track the first X requests in this way and X has a maximum limit of 10,000.

Is there a way to direct this trace information to a file or database? I believe this can be done using System.Diagnostics, however, I am not having much luck.

I have enabled tracing using

<trace enabled="true" writeToDiagnosticsTrace="true" />

I have tried using the XmlWriterTraceListener using

  <system.diagnostics>
    <trace autoflush="true">
      <listeners>
        <add
          name="XmlWriterTraceListener"
          type="System.Diagnostics.XmlWriterTraceListener"
          initializeData="c:\trace.xml"
          />
      </listeners>
    </trace>
  </system.diagnostics>

This results in an xml file containing the timestamps and data for the trace items such as "Begin Load", "End Load", etc.

However, it only seems to log a single request and does not log all requests. In addition, whilst the load times are useful, ideally I would like to have available all of the information that can be seen in the Trace.axd, such as request data, post data, session data, etc.

Is this possible at all without any major code changes? Ideally I would like to enable this using only web.config changes.

Alternatively, I have looked into other applications such as RedGate and Equatec's profiling tools, however, I would like to exhaust the non invasive tracing options first.

The application is written in ASP.Net 3.5 and C#.

Body:
I have a standard HttpModule i use for all my web applications to monitor performance. The logger used can be changed, also can do things like remove white space from source, compress, or send emails if certain limits are reached. Its easier than trawling through asp.net traces as you get only the information you decide is importent.

public class PerfHttpModule : IHttpModule {

    private static Common.Logging.ILog log = Common.Logging.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    public static readonly string CONTEXT_RequestStart = "PerfHttpModule_RequestStart";
    public static readonly string CONTEXT_RequestId = "PerfHttpModule_RequestId";

    public void Init(HttpApplication context) {
        context.BeginRequest += new EventHandler(context_BeginRequest);
        context.EndRequest += new EventHandler(context_EndRequest);
    }

    private void context_BeginRequest(object sender, EventArgs e) {
        try {
            if (HttpContext.Current != null) {
                HttpContext.Current.Items[CONTEXT_RequestStart] = DateTime.Now;
                HttpContext.Current.Items[CONTEXT_RequestId] = random.Next(999999).ToString("D6");
                log.Info("Url: " + HttpContext.Current.Request.Url + " (" + HttpContext.Current.Request.ContentLength + ")");
            }
        } catch {
        }
    }

    private void context_EndRequest(object sender, EventArgs e) {
        if (HttpContext.Current.Items.Contains(CONTEXT_RequestStart)) {
            DateTime time1 = (DateTime)HttpContext.Current.Items[CONTEXT_RequestStart];
            DateTime time2 = DateTime.Now;
            double ms = (time2 - time1).TotalMilliseconds;
            log.Info("TotalMilliseconds: " + ms);
            if (ms > AppSettings.SlowPage || ms > AppSettings.ErrorSlowPage) {
                StringBuilder sb = new StringBuilder();
                sb.Append("Slow page detected." + "\t");
                sb.Append("TotalMilliseconds: " + ms + "\t");
                sb.Append("Url: " + HttpContext.Current.Request.Url.ToString());
                if (ms > AppSettings.ErrorSlowPage) {
                    log.Error(sb.ToString());
                } else if (ms > AppSettings.SlowPage) {
                    log.Warn(sb.ToString());
                }
            }
        }
    }
}

UPDATE

        if (HttpContext.Current != null) {
                NameValueCollection tmp = new NameValueCollection(HttpContext.Current.Request.ServerVariables);
                foreach (string i in tmp.Keys) {

                }
            if (HttpContext.Current.Server != null) {
                if (HttpContext.Current.Server.GetLastError() != null) {

                }
            }
            if (HttpContext.Current.Session != null) {
                foreach (string i in HttpContext.Current.Session.Keys) {

                }
            }
            if (HttpContext.Current.Request.Cookies != null) {
                foreach (string i in HttpContext.Current.Request.Cookies.Keys) {

                }
            }
            if (HttpContext.Current.Response.Cookies != null) {
                foreach (string i in HttpContext.Current.Response.Cookies.Keys) {

                }
            }
            if (HttpContext.Current.Items != null) {
                foreach (string i in HttpContext.Current.Items.Keys) {

                }
            }
            if (HttpContext.Current.Request.Form != null) {
                foreach (string i in HttpContext.Current.Request.Form.Keys) {

                }
            }
        }


来源: stackexchange

问:
Three.js | Vertex's distance from center doesn't change after applying displacement map on sphereGeometry
I'm trying to calculate the distance (from origin) of displaced vertices after applying displacement map on a sphere geometry(positioned at origin only).

As the displacement map changes the position of the vertex, the distance should differ in both the cases ( before and after applying displacement map ), but somehow the distance from center of the sphere ( here origin ) doesn't change.

Any views on this?
Thanks in advance :)

答:
Your displacement map does not affect the geometry as it is defined. Instead, it affects it at render time, where the shaders use the map to adjust the vertex positions and fragment shading. This information is not shared back to the main program.

I believe the easiest way to get what you want is to calculate it manually. This means that for each vertex, you would look at its UV coordinate, read the value of that coordinate from the displacement map image, and then perform the calculation for how the displacement value affects the vertex. You already know that all your vertices are a certain radius from the origin, so this is easy:

```<code>totalDistance = radius + ( displacementRange * displacementFactor )
</code>```

You can also pull values closer to the center by segmenting your displacement values (e.g. 1 is full push, 0.5 is no change, 0 is full pull):

```<code>totalDistance = radius + ( displacementRange * displacementFactor * ((displacementFactor < 0.5)? -1 : 1))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Your displacement map does not affect the geometry as it is defined. Instead, it affects it at render time, where the shaders use the map to adjust the vertex positions and fragment shading. This information is not shared back to the main program.

I believe the easiest way to get what you want is to calculate it manually. This means that for each vertex, you would look at its UV coordinate, read the value of that coordinate from the displacement map image, and then perform the calculation for how the displacement value affects the vertex. You already know that all your vertices are a certain radius from the origin, so this is easy:

totalDistance = radius + ( displacementRange * displacementFactor )

You can also pull values closer to the center by segmenting your displacement values (e.g. 1 is full push, 0.5 is no change, 0 is full pull):

totalDistance = radius + ( displacementRange * displacementFactor * ((displacementFactor < 0.5)? -1 : 1))


问:
Defining a Python Class
I'm attempting to learn Python on my own,so, I got a piece of software I had written in C#, and attempted to re-write it in Python. Given the following class I have a few questions:

C#

```<code>sealed class Message
{
    private int messageID;
    private string message;
    private ConcurrentBag <Employee> messageFor;
    private Person messageFrom;
    private string calltype;
    private string time;

    public Message(int iden,string message, Person messageFrom, string calltype,string time)
    {
        this.MessageIdentification = iden;
        this.messageFor = new ConcurrentBag<Employee>();
        this.Note = message;
        this.MessageFrom = messageFrom;
        this.CallType = calltype;
        this.MessageTime = time;
    }

    public ICollection<Employee> ReturnMessageFor
    {
        get
        {
            return messageFor.ToArray();
        }

    }
</code>```

In my class I have a thread-safe collection called messageFor, is there an equivalent in Python? If so, how do I implement it in a python class?

I also have a getter for my thread-safe collection? How would I go about doing the same in Python?

Does Python have an EqualsTo method to test equality between objects? Or the
equivalent of this in Python?

```<code>    public override bool Equals(object obj)
    {
        if (obj == null)
        {
            return false;
        }

        Message testEquals = obj as Message;

        if((System.Object)testEquals == null)
        {
            return false;
        }

        return (this.messageID == testEquals.messageID) && (this.message == testEquals.message) && (this.messageFor == testEquals.messageFor) && (this.messageFrom == testEquals.messageFrom) && (this.calltype == testEquals.calltype);

    }

    public bool Equals(Message p)
    {
        if ((Object)p == null)
        {
            return false;
        }

        return (this.messageID == p.messageID) && (this.message == p.message) && (this.messageFor == p.messageFor) && (this.messageFrom == p.messageFrom) && (this.calltype == p.calltype);

    }
</code>```

Can you make it sealed, so that no one can inherit from it?

What I've got so far:

```<code>class Message:

   def __init__(self, messageID, message, callType):

      self.messageID = messageID
      self.message = message
      self.callType = callType
</code>```

答:
You have several questions, so let us take a look at them in the order they were asked:

The closest thing to a Bag that you can find in Python's standard library is collections.Counter. However, it is not designed for concurrent usage and has different methods than the ConcurrentBag class you are familiar with. By inheriting from collection.Counter and specifying a custom metaclass designed to make classes thread-safe, it is possible to easily recreate the ConcurrentBag class for use in Python.

The getter for your thread-safe collection can be duplicated in Python using the property decorator. Since you are making the information read-only, this is the easiest method to implement. You can see the property in the code below just below the initializer for the Message class.

Yes, it is possible to check if two objects are equal to each other in Python. You have to define a special __eq__ method as part of the class. The version shown in the example code is just below the aforementioned property. It first checks the type of the instance being compared, and then looks through all the other attributes of each instance except for __time.

Python has no native concept of sealing a class, but a simple metaclass can provide very similar functionality. By setting the metaclass of a class to SealedMeta, any classes that try to inherit from from the "sealed" class will cause a RuntimeError to be raised. Please be aware, though, that anyone with access to the source code of your class could remove its sealed designation.

The following classes and metaclasses should solve the issues you were facing. They are as follows:

SealedMeta is a metaclass that can be used to mark a class as being sealed. Any class that tries to inherit from a sealed class will fail to be constructed since a RuntimeError exception will be generated. Because the requirements are so simple, this metaclass is significantly simpler than the second shown in the example code.

Message is an attempt at recreating the class you wrote in C#. The arguments and attributes have slightly different names, but the same basic idea is present. Since types are not statically specified in Python, only one equality-checking method is needed in this class. Note how the class is marked as sealed with (metaclass=SealedMeta) at the top.

AtomicMeta was a challenging metaclass to write, and I am not sure that it is completely correct. Not only does it have to make the methods of a class thread-safe, it must process all bases that the class inherits from. Since old-style super calls may be present in those bases, the metaclass attempts to fix the modules they are located in.

ConcurrentBag inherits from collections.Counter since it is most like a bag from other languages. Since you wanted the class to be thread-safe, it must use the AtomicMeta metaclass so that the methods of it and its parents are changed into atomic operations. A to_array method is introduced to improve its API.

Without further delay, here is the code referenced above. Hopefully, it will be a help both to you and others:

```<code>#! /usr/bin/env python3
import builtins
import collections
import functools
import inspect
import threading

class SealedMeta(type):
    """SealedMeta(name, bases, dictionary) -> new sealed class"""
    __REGISTRY = ()

    def __new__(mcs, name, bases, dictionary):
        """Create a new class only if it is not related to a sealed class."""
        if any(issubclass(base, mcs.__REGISTRY) for base in bases):
            raise RuntimeError('no class may inherit from a sealed class')
        mcs.__REGISTRY += (super().__new__(mcs, name, bases, dictionary),)
        return mcs.__REGISTRY[-1]

class Message(metaclass=SealedMeta):
    """Message(identifier, message, source, kind, time) -> Message instance"""

    def __init__(self, identifier, message, source, kind, time):
        """Initialize all the attributes in a new Message instance."""
        self.__identifier = identifier
        self.__message = message
        self.__source = source
        self.__kind = kind
        self.__time = time
        self.__destination = ConcurrentBag()

    @property
    def destination(self):
        """Destination property containing serialized Employee instances."""
        return self.__destination.to_array()

    def __eq__(self, other):
        """Return if this instance has the same data as the other instance."""
        # noinspection PyPep8
        return isinstance(other, type(self)) and \
               self.__identifier == other.__identifier and \
               self.__message == other.__message and \
               self.__source == other.__source and \
               self.__kind == other.__kind and \
               self.__destination == other.__destination

class AtomicMeta(type):
    """AtomicMeta(name, bases, dictionary) -> new thread-safe class"""
    __REGISTRY = {}

    def __new__(mcs, name, bases, dictionary, parent=None):
        """Create a new class while fixing bases and all callable items."""
        final_bases = []
        # Replace bases with those that are safe to use.
        for base in bases:
            fixed = mcs.__REGISTRY.get(base)
            if fixed:
                final_bases.append(fixed)
            elif base in mcs.__REGISTRY.values():
                final_bases.append(base)
            elif base in vars(builtins).values():
                final_bases.append(base)
            else:
                final_bases.append(mcs(
                    base.__name__, base.__bases__, dict(vars(base)), base
                ))
        class_lock = threading.Lock()
        # Wrap all callable attributes so that they are thread-safe.
        for key, value in dictionary.items():
            if callable(value):
                dictionary[key] = mcs.__wrap(value, class_lock)
        new_class = super().__new__(mcs, name, tuple(final_bases), dictionary)
        # Register the class and potentially replace parent references.
        if parent is None:
            mcs.__REGISTRY[object()] = new_class
        else:
            mcs.__REGISTRY[parent] = new_class
            source = inspect.getmodule(parent)
            *prefix, root = parent.__qualname__.split('.')
            for name in prefix:
                source = getattr(source, name)
            setattr(source, root, new_class)
        return new_class

    # noinspection PyUnusedLocal
    def __init__(cls, name, bases, dictionary, parent=None):
        """Initialize the new class while ignoring any potential parent."""
        super().__init__(name, bases, dictionary)

    @staticmethod
    def __wrap(method, class_lock):
        """Ensure that all method calls are run as atomic operations."""

        @functools.wraps(method)
        def atomic_wrapper(self, *args, **kwargs):
            with class_lock:
                try:
                    instance_lock = self.__lock
                except AttributeError:
                    instance_lock = self.__lock = threading.RLock()
            with instance_lock:
                return method(self, *args, **kwargs)

        return atomic_wrapper

# noinspection PyAbstractClass
class ConcurrentBag(collections.Counter, metaclass=AtomicMeta):
    """ConcurrentBag() -> ConcurrentBag instance"""

    def to_array(self):
        """Serialize the data in the ConcurrentBag instance."""
        return tuple(key for key, value in self.items() for _ in range(value))
</code>```

After doing a little research, you might find that there are alternatives for sealing a class. In Java, classes are marked final instead of using a sealed keyword. Searching for the alternative keyword could bring you to Martijn Pieters' answer which introduces a slightly simpler metaclass for sealing classes in Python. You can use the following metaclass inspired by his the same way that SealedMeta is currently used in the code:

```<code>class Final(type):
    """Final(name, bases, dictionary) -> new final class"""

    def __new__(mcs, name, bases, dictionary):
        """Create a new class if none of its bases are marked as final."""
        if any(isinstance(base, mcs) for base in bases):
            raise TypeError('no class may inherit from a final class')
        return super().__new__(mcs, name, bases, dictionary)
</code>```

The Final metaclass is useful if you want to seal a class and prevent others from inheriting from it, but a different approach is needed if attributes of a class are intended to be final instead. In such a case, the Access metaclass can be rather useful. It was inspired by this answer to the question Prevent function overriding in Python. A modified approach is taken in the metaclass shown below that is designed to take into account attributes of all kinds.

```<code>import collections
import threading

# noinspection PyProtectedMember
class RLock(threading._RLock):
    """RLock() -> RLock instance with count property"""

    @property
    def count(self):
        """Count property showing current level of lock ownership."""
        return self._count

class Access(type):
    """Access(name, bases, dictionary) -> class supporting final attributes"""
    __MUTEX = RLock()
    __FINAL = []

    @classmethod
    def __prepare__(mcs, name, bases, **keywords):
        """Begin construction of a class and check for possible deadlocks."""
        if not mcs.__MUTEX.acquire(True, 10):
            raise RuntimeError('please check your code for deadlocks')
        # noinspection PyUnresolvedReferences
        return super().__prepare__(mcs, name, bases, **keywords)

    @classmethod
    def final(mcs, attribute):
        """Record an attribute as being final so it cannot be overridden."""
        with mcs.__MUTEX:
            if any(attribute is final for final in mcs.__FINAL):
                raise SyntaxError('attributes may be marked final only once')
            mcs.__FINAL.append(attribute)
            return attribute

    def __new__(mcs, class_name, bases, dictionary):
        """Create a new class that supports the concept of final attributes."""
        classes, visited, names = collections.deque(bases), set(), set()
        # Find all attributes marked as final in base classes.
        while classes:
            base = classes.popleft()
            if base not in visited:
                visited.add(base)
                classes.extend(base.__bases__)
                names.update(getattr(base, '__final_attributes__', ()))
        # Verify that the current class does not override final attributes.
        if any(name in names for name in dictionary):
            raise SyntaxError('final attributes may not be overridden')
        names.clear()
        # Collect the names of all attributes that are marked as final.
        for name, attribute in dictionary.items():
            for index, final in enumerate(mcs.__FINAL):
                if attribute is final:
                    del mcs.__FINAL[index]
                    names.add(name)
                    break
        # Do a sanity check to ensure this metaclass is being used properly.
        if mcs.__MUTEX.count == 1 and mcs.__FINAL:
            raise RuntimeError('final decorator has not been used correctly')
        mcs.__MUTEX.release()
        dictionary['__final_attributes__'] = frozenset(names)
        return super().__new__(mcs, class_name, bases, dictionary)
</code>```

As a demonstration of how to use the Access metaclass, this example will raise a SyntaxError:

```<code>class Parent(metaclass=Access):
    def __init__(self, a, b):
        self.__a = a
        self.__b = b

    @Access.final
    def add(self):
        return self.__a + self.__b

    def sub(self):
        return self.__a - self.__b

class Child(Parent):
    def __init__(self, a, b, c):
        super().__init__(a, b)
        self.__c = c

    def add(self):
        return super().add() + self.__c
</code>```

Title: Defining a Python Class

Body:
I'm attempting to learn Python on my own,so, I got a piece of software I had written in C#, and attempted to re-write it in Python. Given the following class I have a few questions:

C#

sealed class Message
{
    private int messageID;
    private string message;
    private ConcurrentBag <Employee> messageFor;
    private Person messageFrom;
    private string calltype;
    private string time;

    public Message(int iden,string message, Person messageFrom, string calltype,string time)
    {
        this.MessageIdentification = iden;
        this.messageFor = new ConcurrentBag<Employee>();
        this.Note = message;
        this.MessageFrom = messageFrom;
        this.CallType = calltype;
        this.MessageTime = time;
    }

    public ICollection<Employee> ReturnMessageFor
    {
        get
        {
            return messageFor.ToArray();
        }

    }

In my class I have a thread-safe collection called messageFor, is there an equivalent in Python? If so, how do I implement it in a python class?

I also have a getter for my thread-safe collection? How would I go about doing the same in Python?

Does Python have an EqualsTo method to test equality between objects? Or the
equivalent of this in Python?

    public override bool Equals(object obj)
    {
        if (obj == null)
        {
            return false;
        }

        Message testEquals = obj as Message;

        if((System.Object)testEquals == null)
        {
            return false;
        }

        return (this.messageID == testEquals.messageID) && (this.message == testEquals.message) && (this.messageFor == testEquals.messageFor) && (this.messageFrom == testEquals.messageFrom) && (this.calltype == testEquals.calltype);

    }

    public bool Equals(Message p)
    {
        if ((Object)p == null)
        {
            return false;
        }

        return (this.messageID == p.messageID) && (this.message == p.message) && (this.messageFor == p.messageFor) && (this.messageFrom == p.messageFrom) && (this.calltype == p.calltype);

    }

Can you make it sealed, so that no one can inherit from it?

What I've got so far:

class Message:

   def __init__(self, messageID, message, callType):

      self.messageID = messageID
      self.message = message
      self.callType = callType

Body:
You have several questions, so let us take a look at them in the order they were asked:

The closest thing to a Bag that you can find in Python's standard library is collections.Counter. However, it is not designed for concurrent usage and has different methods than the ConcurrentBag class you are familiar with. By inheriting from collection.Counter and specifying a custom metaclass designed to make classes thread-safe, it is possible to easily recreate the ConcurrentBag class for use in Python.

The getter for your thread-safe collection can be duplicated in Python using the property decorator. Since you are making the information read-only, this is the easiest method to implement. You can see the property in the code below just below the initializer for the Message class.

Yes, it is possible to check if two objects are equal to each other in Python. You have to define a special __eq__ method as part of the class. The version shown in the example code is just below the aforementioned property. It first checks the type of the instance being compared, and then looks through all the other attributes of each instance except for __time.

Python has no native concept of sealing a class, but a simple metaclass can provide very similar functionality. By setting the metaclass of a class to SealedMeta, any classes that try to inherit from from the "sealed" class will cause a RuntimeError to be raised. Please be aware, though, that anyone with access to the source code of your class could remove its sealed designation.

The following classes and metaclasses should solve the issues you were facing. They are as follows:

SealedMeta is a metaclass that can be used to mark a class as being sealed. Any class that tries to inherit from a sealed class will fail to be constructed since a RuntimeError exception will be generated. Because the requirements are so simple, this metaclass is significantly simpler than the second shown in the example code.

Message is an attempt at recreating the class you wrote in C#. The arguments and attributes have slightly different names, but the same basic idea is present. Since types are not statically specified in Python, only one equality-checking method is needed in this class. Note how the class is marked as sealed with (metaclass=SealedMeta) at the top.

AtomicMeta was a challenging metaclass to write, and I am not sure that it is completely correct. Not only does it have to make the methods of a class thread-safe, it must process all bases that the class inherits from. Since old-style super calls may be present in those bases, the metaclass attempts to fix the modules they are located in.

ConcurrentBag inherits from collections.Counter since it is most like a bag from other languages. Since you wanted the class to be thread-safe, it must use the AtomicMeta metaclass so that the methods of it and its parents are changed into atomic operations. A to_array method is introduced to improve its API.

Without further delay, here is the code referenced above. Hopefully, it will be a help both to you and others:

#! /usr/bin/env python3
import builtins
import collections
import functools
import inspect
import threading

class SealedMeta(type):
    """SealedMeta(name, bases, dictionary) -> new sealed class"""
    __REGISTRY = ()

    def __new__(mcs, name, bases, dictionary):
        """Create a new class only if it is not related to a sealed class."""
        if any(issubclass(base, mcs.__REGISTRY) for base in bases):
            raise RuntimeError('no class may inherit from a sealed class')
        mcs.__REGISTRY += (super().__new__(mcs, name, bases, dictionary),)
        return mcs.__REGISTRY[-1]

class Message(metaclass=SealedMeta):
    """Message(identifier, message, source, kind, time) -> Message instance"""

    def __init__(self, identifier, message, source, kind, time):
        """Initialize all the attributes in a new Message instance."""
        self.__identifier = identifier
        self.__message = message
        self.__source = source
        self.__kind = kind
        self.__time = time
        self.__destination = ConcurrentBag()

    @property
    def destination(self):
        """Destination property containing serialized Employee instances."""
        return self.__destination.to_array()

    def __eq__(self, other):
        """Return if this instance has the same data as the other instance."""
        # noinspection PyPep8
        return isinstance(other, type(self)) and \
               self.__identifier == other.__identifier and \
               self.__message == other.__message and \
               self.__source == other.__source and \
               self.__kind == other.__kind and \
               self.__destination == other.__destination

class AtomicMeta(type):
    """AtomicMeta(name, bases, dictionary) -> new thread-safe class"""
    __REGISTRY = {}

    def __new__(mcs, name, bases, dictionary, parent=None):
        """Create a new class while fixing bases and all callable items."""
        final_bases = []
        # Replace bases with those that are safe to use.
        for base in bases:
            fixed = mcs.__REGISTRY.get(base)
            if fixed:
                final_bases.append(fixed)
            elif base in mcs.__REGISTRY.values():
                final_bases.append(base)
            elif base in vars(builtins).values():
                final_bases.append(base)
            else:
                final_bases.append(mcs(
                    base.__name__, base.__bases__, dict(vars(base)), base
                ))
        class_lock = threading.Lock()
        # Wrap all callable attributes so that they are thread-safe.
        for key, value in dictionary.items():
            if callable(value):
                dictionary[key] = mcs.__wrap(value, class_lock)
        new_class = super().__new__(mcs, name, tuple(final_bases), dictionary)
        # Register the class and potentially replace parent references.
        if parent is None:
            mcs.__REGISTRY[object()] = new_class
        else:
            mcs.__REGISTRY[parent] = new_class
            source = inspect.getmodule(parent)
            *prefix, root = parent.__qualname__.split('.')
            for name in prefix:
                source = getattr(source, name)
            setattr(source, root, new_class)
        return new_class

    # noinspection PyUnusedLocal
    def __init__(cls, name, bases, dictionary, parent=None):
        """Initialize the new class while ignoring any potential parent."""
        super().__init__(name, bases, dictionary)

    @staticmethod
    def __wrap(method, class_lock):
        """Ensure that all method calls are run as atomic operations."""

        @functools.wraps(method)
        def atomic_wrapper(self, *args, **kwargs):
            with class_lock:
                try:
                    instance_lock = self.__lock
                except AttributeError:
                    instance_lock = self.__lock = threading.RLock()
            with instance_lock:
                return method(self, *args, **kwargs)

        return atomic_wrapper

# noinspection PyAbstractClass
class ConcurrentBag(collections.Counter, metaclass=AtomicMeta):
    """ConcurrentBag() -> ConcurrentBag instance"""

    def to_array(self):
        """Serialize the data in the ConcurrentBag instance."""
        return tuple(key for key, value in self.items() for _ in range(value))

After doing a little research, you might find that there are alternatives for sealing a class. In Java, classes are marked final instead of using a sealed keyword. Searching for the alternative keyword could bring you to Martijn Pieters' answer which introduces a slightly simpler metaclass for sealing classes in Python. You can use the following metaclass inspired by his the same way that SealedMeta is currently used in the code:

class Final(type):
    """Final(name, bases, dictionary) -> new final class"""

    def __new__(mcs, name, bases, dictionary):
        """Create a new class if none of its bases are marked as final."""
        if any(isinstance(base, mcs) for base in bases):
            raise TypeError('no class may inherit from a final class')
        return super().__new__(mcs, name, bases, dictionary)

The Final metaclass is useful if you want to seal a class and prevent others from inheriting from it, but a different approach is needed if attributes of a class are intended to be final instead. In such a case, the Access metaclass can be rather useful. It was inspired by this answer to the question Prevent function overriding in Python. A modified approach is taken in the metaclass shown below that is designed to take into account attributes of all kinds.

import collections
import threading

# noinspection PyProtectedMember
class RLock(threading._RLock):
    """RLock() -> RLock instance with count property"""

    @property
    def count(self):
        """Count property showing current level of lock ownership."""
        return self._count

class Access(type):
    """Access(name, bases, dictionary) -> class supporting final attributes"""
    __MUTEX = RLock()
    __FINAL = []

    @classmethod
    def __prepare__(mcs, name, bases, **keywords):
        """Begin construction of a class and check for possible deadlocks."""
        if not mcs.__MUTEX.acquire(True, 10):
            raise RuntimeError('please check your code for deadlocks')
        # noinspection PyUnresolvedReferences
        return super().__prepare__(mcs, name, bases, **keywords)

    @classmethod
    def final(mcs, attribute):
        """Record an attribute as being final so it cannot be overridden."""
        with mcs.__MUTEX:
            if any(attribute is final for final in mcs.__FINAL):
                raise SyntaxError('attributes may be marked final only once')
            mcs.__FINAL.append(attribute)
            return attribute

    def __new__(mcs, class_name, bases, dictionary):
        """Create a new class that supports the concept of final attributes."""
        classes, visited, names = collections.deque(bases), set(), set()
        # Find all attributes marked as final in base classes.
        while classes:
            base = classes.popleft()
            if base not in visited:
                visited.add(base)
                classes.extend(base.__bases__)
                names.update(getattr(base, '__final_attributes__', ()))
        # Verify that the current class does not override final attributes.
        if any(name in names for name in dictionary):
            raise SyntaxError('final attributes may not be overridden')
        names.clear()
        # Collect the names of all attributes that are marked as final.
        for name, attribute in dictionary.items():
            for index, final in enumerate(mcs.__FINAL):
                if attribute is final:
                    del mcs.__FINAL[index]
                    names.add(name)
                    break
        # Do a sanity check to ensure this metaclass is being used properly.
        if mcs.__MUTEX.count == 1 and mcs.__FINAL:
            raise RuntimeError('final decorator has not been used correctly')
        mcs.__MUTEX.release()
        dictionary['__final_attributes__'] = frozenset(names)
        return super().__new__(mcs, class_name, bases, dictionary)

As a demonstration of how to use the Access metaclass, this example will raise a SyntaxError:

class Parent(metaclass=Access):
    def __init__(self, a, b):
        self.__a = a
        self.__b = b

    @Access.final
    def add(self):
        return self.__a + self.__b

    def sub(self):
        return self.__a - self.__b

class Child(Parent):
    def __init__(self, a, b, c):
        super().__init__(a, b)
        self.__c = c

    def add(self):
        return super().add() + self.__c


问:
how to link a url to neo4j node
I have some nodes and properties in neo4j.Below is my sample neo4j graph.

When we click on the TheAct node it will open a browser tab and display TheAct related properties or we have to show that TheAct related properties in a iframe.In the same way we have to achieve same feature for all nodes.
Is it possible with neo4j or can i goto another technology.
Thanks

答:
Consulting documentation, it can be seen that we can set related properties on any node using simple Cypher Query:

```<code>MATCH (n { name: 'Andres' })
SET n.surname = 'Taylor'
RETURN n
</code>```

Reference: https://neo4j.com/docs/developer-manual/current/cypher/clauses/set/

Title: how to link a url to neo4j node

Body:
Consulting documentation, it can be seen that we can set related properties on any node using simple Cypher Query:

MATCH (n { name: 'Andres' })
SET n.surname = 'Taylor'
RETURN n

Reference: https://neo4j.com/docs/developer-manual/current/cypher/clauses/set/


问:
Method Not Allowed HTTP Exception in Laravel 5.4
I have a form with two text fields and two buttons (edit and delete), when I press edit button, it works fine but when I press delete button, it gives the 'MethodNotAllowedHttp' exception. My code is as follows:

```<code><form action="/laboratory/doctors/update" method="POST">
    {{ csrf_field() }}
    {{ method_field('DELETE') }}
    <div class="form-group">
        <label for="name">Name:</label>
        <input type="text" class="form-control" id="name" aria-describedby="name" value="{{ $doctor->name }}">
    </div>
    <div class="form-group">
        <label for="percentage">Percentage:</label>
        <input type="text" class="form-control" id="percentage" value="{{ $doctor->percentage }}">
    </div>
     <button type="submit" class="btn btn-success">Save Changes</button>
    <a href="/laboratory/doctors/{{ $doctor->id }}/delete" class="btn btn-danger">Delete</a>
</form>
</code>```

My Routes are as follows:

```<code>Route::post('/doctors/update', 'DoctorsController@update');
Route::delete('/doctors/{doctor}/delete', 'DoctorsController@destroy');
</code>```

Any help is appreciated.

答:
```<code>@if(isset($doctor))
<form action="/laboratory/doctors/{{$doctor->id}}/delete" method="POST">
@else
<form action="/laboratory/doctors/update" method="POST">
@endif
    {{ csrf_field() }}
    @if(isset($doctor))
    {{ method_field('DELETE') }}
    @endif
    <div class="form-group">
        <label for="name">Name:</label>
        <input type="text" class="form-control" id="name" aria-describedby="name" value="{{ $doctor->name }}">
    </div>
    <div class="form-group">
        <label for="percentage">Percentage:</label>
        <input type="text" class="form-control" id="percentage" value="{{ $doctor->percentage }}">
    </div>
     <button type="submit" class="btn btn-success">Save Changes</button>
    <a href="/laboratory/doctors/{{ $doctor->id }}/delete" class="btn btn-danger">Delete</a>
</form>
</code>```

The problem is in your action.. when you click delete button, the button run the destroy function, but the form run the update function. So, you have to separate the form action, or you can delete it by using ajax

Body:
I have a form with two text fields and two buttons (edit and delete), when I press edit button, it works fine but when I press delete button, it gives the 'MethodNotAllowedHttp' exception. My code is as follows:

<form action="/laboratory/doctors/update" method="POST">
    {{ csrf_field() }}
    {{ method_field('DELETE') }}

        Name:
        <input type="text" class="form-control" id="name" aria-describedby="name" value="{{ $doctor->name }}">

        Percentage:
        <input type="text" class="form-control" id="percentage" value="{{ $doctor->percentage }}">

     <button type="submit" class="btn btn-success">Save Changes</button>
    id }}/delete" class="btn btn-danger">Delete
</form>

My Routes are as follows:

Route::post('/doctors/update', 'DoctorsController@update');
Route::delete('/doctors/{doctor}/delete', 'DoctorsController@destroy');

Any help is appreciated.

Body:
@if(isset($doctor))
<form action="/laboratory/doctors/{{$doctor->id}}/delete" method="POST">
@else
<form action="/laboratory/doctors/update" method="POST">
@endif
    {{ csrf_field() }}
    @if(isset($doctor))
    {{ method_field('DELETE') }}
    @endif
    <div class="form-group">
        <label for="name">Name:</label>
        <input type="text" class="form-control" id="name" aria-describedby="name" value="{{ $doctor->name }}">
    </div>
    <div class="form-group">
        <label for="percentage">Percentage:</label>
        <input type="text" class="form-control" id="percentage" value="{{ $doctor->percentage }}">
    </div>
     <button type="submit" class="btn btn-success">Save Changes</button>
    <a href="/laboratory/doctors/{{ $doctor->id }}/delete" class="btn btn-danger">Delete</a>
</form>

The problem is in your action.. when you click delete button, the button run the destroy function, but the form run the update function. So, you have to separate the form action, or you can delete it by using ajax


问:
history of programming language names?
do anyone know the history of programming language names? where they come from?
a,b,c, java, python, scheme, prolog, ada, fortran, algol, cobol, assembly, pascal, lisp, perl, haskell, php, javascript, c#, ruby, c++ and so on.</p>

答:
Often the name is inspired by a previous lagnuage (that's the case of C++, which derives from C, which in turn has been named after B ...), but more often language inventor just picked a name he was liking for some reason.

Maybe you could be interested in the genealogy of programming languages.

ContentLicense: CC BY-SA 2.5

Title: history of programming language names?


问:
How to check existence of tiles attribute before inserting it into the page
I am using tiles in struts2 application. While defining base layout I have defined an attribute "scriptFile".

```<code><definition name="baseLayout" template="/application/base-layout.jsp" >
    ...
</definition>

<definition name="custom.tiles" extends="baseLayout">
    <put-attribute name="scriptFile" value="js/custom-script.js"></put-attribute>
</definition>
</code>```

If developer provides "scriptFile" in tiles definition file, "tiles.xml", this script file should be included using following line

```<code><script language="javascript" src="<tiles:insertAttribute name="scriptFile"></tiles:insertAttribute>"></script>
</code>```

But if scriptFile attribute is not defined, this line must be skipped.

How can I check the existence of "scriptFile" attribute in tiles. Is there any better way to do this thing?

答:
I used the following code to solve that problem (just according to the info I got from tags description:
ignore - If this attribute is set to true, and the attribute specified by the
         name does not exist, simply return without writing anything. The
         default value is false, which will cause a runtime exception to be
         thrown. ): </p>

```<code><tiles:importAttribute name="stylesheets" ignore="${true}"/>
</code>```

<p>P.S. Be careful, use ${true} intead of only "true" value. </p>

Body:
I am using tiles in struts2 application. While defining base layout I have defined an attribute "scriptFile".

<definition name="baseLayout" template="/application/base-layout.jsp" >
    ...
</definition>

<definition name="custom.tiles" extends="baseLayout">
    <put-attribute name="scriptFile" value="js/custom-script.js"></put-attribute>
</definition>

If developer provides "scriptFile" in tiles definition file, "tiles.xml", this script file should be included using following line

But if scriptFile attribute is not defined, this line must be skipped.

How can I check the existence of "scriptFile" attribute in tiles. Is there any better way to do this thing?

Body:
I used the following code to solve that problem (just according to the info I got from tags description:
ignore - If this attribute is set to true, and the attribute specified by the
         name does not exist, simply return without writing anything. The
         default value is false, which will cause a runtime exception to be
         thrown. ):

<tiles:importAttribute name="stylesheets" ignore="${true}"/>

P.S. Be careful, use ${true} intead of only "true" value.


问:
byte array (string) to string javascript
I have a model which has a bytearray as a property,

```<code>public byte[] bytearraytest{ get; set; }
</code>```

when I get this model via javascript GET request it is a string.

```<code>tgwBAQ==
</code>```

How can i decode it now ?

答:
The string tgwBAQ== is Base64-encoded (easily discernible via the tell-tale == at the end). To get a byte array from that, you would use:

```<code>var bytes = Convert.FromBase64String(value);
</code>```

If you're directly binding that to a byte[], it's most likely creating a char[], by splitting the string, i.e.:

```<code>[ 't', 'g', 'w', 'B', 'A', 'Q', '=', '=' ]
</code>```

That's fairly obviously useless to you, so first and foremost, you need to accept the value as a string, so you can manipulate it as a string.

Once, you've got a real byte[] representation of the string, getting back to the IP address string, depends on what occurred previously to Base64-encoding it in the first place. For example, if the provided string was created by doing something like:

```<code>var base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(ipAddress));
</code>```

Then, you would simply reverse that:

```<code>var ipAddress = Encoding.UTF8.GetString(Convert.FromBase64String(base64));
</code>```

However, if encryption was involved, you'd need to decrypt it first, using the same cryptographic algorithm it was encrypted in and the decrypt "key", either an actual shared key, a private key, etc.

Long and short, there's no enough info here to help you with that last piece of the puzzle, so you'll either need to update your question with more information regarding what you're doing or simply take this guidance and run with it on your own.

Body:
I have a model which has a bytearray as a property,

public byte[] bytearraytest{ get; set; }

when I get this model via javascript GET request it is a string.

tgwBAQ==

How can i decode it now ?

Body:
The string tgwBAQ== is Base64-encoded (easily discernible via the tell-tale == at the end). To get a byte array from that, you would use:

var bytes = Convert.FromBase64String(value);

If you're directly binding that to a byte[], it's most likely creating a char[], by splitting the string, i.e.:

[ 't', 'g', 'w', 'B', 'A', 'Q', '=', '=' ]

That's fairly obviously useless to you, so first and foremost, you need to accept the value as a string, so you can manipulate it as a string.

Once, you've got a real byte[] representation of the string, getting back to the IP address string, depends on what occurred previously to Base64-encoding it in the first place. For example, if the provided string was created by doing something like:

var base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(ipAddress));

Then, you would simply reverse that:

var ipAddress = Encoding.UTF8.GetString(Convert.FromBase64String(base64));

However, if encryption was involved, you'd need to decrypt it first, using the same cryptographic algorithm it was encrypted in and the decrypt "key", either an actual shared key, a private key, etc.

Long and short, there's no enough info here to help you with that last piece of the puzzle, so you'll either need to update your question with more information regarding what you're doing or simply take this guidance and run with it on your own.


问:
ng-click on user defined $mdDialog with external template are not working
working the first time with $mdDialog I am used to create a dialog with an external HTML Template.

So far, so good,... it works template can get opened, but ng-click in the html wont work anymore.

And I cannot find the reason for it.

The mdDialog gets called in userController like this:

```<code><md-icon
        layout="row"
        flex md-font-set="material-icons"
        class="active"
        ng-click="vm.showMenu($event)">
    menu
</md-icon>
</code>```

The method to open the $mdDialog in userController:

```<code>vm.showMenu = function showMenu(ev){

    $mdDialog.show({
        controller: MenuDialogController,
        templateUrl: 'app/components/head/user/menu.dialog.html',
        parent: angular.element($document.body),
        targetEvent: ev,
        clickOutsideToClose:true,
        fullscreen: $scope.customFullscreen // Only for -xs, -sm breakpoints.
    })
        .then(function(answer) {
            $scope.status = 'You said the information was "' + answer + '".';
        }, function() {
            $scope.status = 'You cancelled the dialog.';
        });
};
</code>```

And this is the dialog controller for the dialog, where the buttons are not working:

```<code>angular
    .module('trax')
    .controller('MenuDialogController', MenuDialogController);

function MenuDialogController() {

    var vm = this;

    vm.close = function close(){
        alert('close clicked');
    }

    vm.ok = function ok(){
        alert('ok clicked');
    }

}
</code>```

And this is the html code for the dialogController:

```<code><md-dialog aria-label="User Menu">
    <form ng-cloak>
        <md-toolbar>
            <div class="md-toolbar-tools">
                <h2>User Menu</h2>
                <span flex></span>
                <md-button class="md-icon-button" ng-click="vm.close($event)">
                    <md-icon md-font-set="material-icons">close</md-icon>
                </md-button>
            </div>
        </md-toolbar>

        <md-dialog-content>
            <div class="md-dialog-content">
                <h2>Dialog Title</h2>
                <p>Dialog Text....</p>
                <p ng-click="vm.test($event)">test</p>
            </div>
        </md-dialog-content>

        <md-dialog-actions layout="row">
            <md-button href="http://en.wikipedia.org/wiki/Mango" target="_blank" md-autofocus>
                More on Wikipedia
            </md-button>
            <span flex></span>
            <md-button ng-click="vm.close($event)">
                cancel
            </md-button>
            <md-button ng-click="vm.ok($event)">
                ok
            </md-button>
        </md-dialog-actions>
    </form>
</md-dialog>
</code>```

None of the ng-clicks is working!

Any hint for me?

答:
To leave your code unmodified you have to add after

```<code>var vm = this;
</code>```

with

```<code>var vm = this;
$scope.vm = vm;
</code>```

In this way you can use it in your template.

Another way is declare the methods directly in $scope as

```<code>$scope.close = function() { ... };
$scope.ok = function() { ... };
</code>```

The first method is equal to declare controllerAs: "vm" in $mdDialog.show helper method

Body:
working the first time with $mdDialog I am used to create a dialog with an external HTML Template.

So far, so good,... it works template can get opened, but ng-click in the html wont work anymore.

And I cannot find the reason for it.

The mdDialog gets called in userController like this:

<md-icon
        layout="row"
        flex md-font-set="material-icons"
        class="active"
        ng-click="vm.showMenu($event)">
    menu
</md-icon>

The method to open the $mdDialog in userController:

vm.showMenu = function showMenu(ev){

    $mdDialog.show({
        controller: MenuDialogController,
        templateUrl: 'app/components/head/user/menu.dialog.html',
        parent: angular.element($document.body),
        targetEvent: ev,
        clickOutsideToClose:true,
        fullscreen: $scope.customFullscreen // Only for -xs, -sm breakpoints.
    })
        .then(function(answer) {
            $scope.status = 'You said the information was "' + answer + '".';
        }, function() {
            $scope.status = 'You cancelled the dialog.';
        });
};

And this is the dialog controller for the dialog, where the buttons are not working:

angular
    .module('trax')
    .controller('MenuDialogController', MenuDialogController);

function MenuDialogController() {

    var vm = this;

    vm.close = function close(){
        alert('close clicked');
    }

    vm.ok = function ok(){
        alert('ok clicked');
    }

}

And this is the html code for the dialogController:

<md-dialog aria-label="User Menu">
    <form ng-cloak>
        <md-toolbar>

User Menu

                <md-button class="md-icon-button" ng-click="vm.close($event)">
                    <md-icon md-font-set="material-icons">close</md-icon>
                </md-button>

        </md-toolbar>

        <md-dialog-content>

Dialog Title

Dialog Text....

test

        </md-dialog-content>

        <md-dialog-actions layout="row">
            <md-button href="http://en.wikipedia.org/wiki/Mango" target="_blank" md-autofocus>
                More on Wikipedia
            </md-button>

            <md-button ng-click="vm.close($event)">
                cancel
            </md-button>
            <md-button ng-click="vm.ok($event)">
                ok
            </md-button>
        </md-dialog-actions>
    </form>
</md-dialog>

None of the ng-clicks is working!

Any hint for me?

Body:
To leave your code unmodified you have to add after

var vm = this;

with

var vm = this;
$scope.vm = vm;

In this way you can use it in your template.

Another way is declare the methods directly in $scope as

$scope.close = function() { ... };
$scope.ok = function() { ... };

The first method is equal to declare controllerAs: "vm" in $mdDialog.show helper method


问:
Card flip Animation not looking good on Android 7 Nougat
thank you for reading my question.
The problem I have only occurs in android 7.0 (Nougat) and what it's happening is that the card (a fragment with Image views) when it rotates in the animation, it suddenly crops part of the image, Look:

Android 7 Nougat Screenshoot

Card in rotation

Android 4.4 Kitkat Screenshoot

Card in rotation

I'm using Animation (not objectAnimator yet), Here's my code:

```<code>@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
    // Angle around the y-axis of the rotation at the given time
    // calculated both in radians and degrees.
    final double radians = Math.PI * interpolatedTime;
    float degrees = (float) (180.0 * radians / Math.PI);

    Log.d(LOG_TAG," "+interpolatedTime);

    // Once we reach the midpoint in the animation, we need to hide the
    // source view and show the destination view. We also need to change
    // the angle by 180 degrees so that the destination does not come in
    // flipped around
    if (interpolatedTime >= 0.5f) {
        degrees -= 180.f;
        fromView.setVisibility(View.GONE);
        toView.setVisibility(View.VISIBLE);

    }

    if (forward)
        degrees = -degrees; //determines direction of rotation when flip begins

    //computing
    final Matrix matrix = t.getMatrix();
    camera.save();
    camera.translate(0, 0, Math.abs(degrees) * 3f);
    camera.rotateY(degrees);
    camera.getMatrix(matrix);
    camera.restore();
    matrix.preTranslate(-centerX, -centerY);
    matrix.postTranslate(centerX, centerY);
}
</code>```

Thank you so much for sharing your ideas. :)

答:
Read the https://developer.android.com/reference/android/view/View.html#setCameraDistance(float)

You have to set the camera distance.
I know that this question is old, but I hope that will help somebody.

Body:
thank you for reading my question.
The problem I have only occurs in android 7.0 (Nougat) and what it's happening is that the card (a fragment with Image views) when it rotates in the animation, it suddenly crops part of the image, Look:

Android 7 Nougat Screenshoot

Card in rotation

Android 4.4 Kitkat Screenshoot

Card in rotation

I'm using Animation (not objectAnimator yet), Here's my code:

@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
    // Angle around the y-axis of the rotation at the given time
    // calculated both in radians and degrees.
    final double radians = Math.PI * interpolatedTime;
    float degrees = (float) (180.0 * radians / Math.PI);

    Log.d(LOG_TAG," "+interpolatedTime);

    // Once we reach the midpoint in the animation, we need to hide the
    // source view and show the destination view. We also need to change
    // the angle by 180 degrees so that the destination does not come in
    // flipped around
    if (interpolatedTime >= 0.5f) {
        degrees -= 180.f;
        fromView.setVisibility(View.GONE);
        toView.setVisibility(View.VISIBLE);

    }

    if (forward)
        degrees = -degrees; //determines direction of rotation when flip begins

    //computing
    final Matrix matrix = t.getMatrix();
    camera.save();
    camera.translate(0, 0, Math.abs(degrees) * 3f);
    camera.rotateY(degrees);
    camera.getMatrix(matrix);
    camera.restore();
    matrix.preTranslate(-centerX, -centerY);
    matrix.postTranslate(centerX, centerY);
}

Thank you so much for sharing your ideas. :)


问:
Getting an array from the redux store puts it inside another array
So what I am doing is the following:

An action fetches a .json file from a url and dispatches another action. The value for pilots is [Array(278)].

```<code>export const pilotsFetchDataSucces = (pilots) => {
  return {
    type: 'PILOTS_FETCH_DATA_SUCCES',
    pilots
  }
};

export const pilotsFetchData = (url) => (dispatch) => {
  fetch(url)
  .then((response) => {return response.json()})
  .then((pilots) => {
    dispatch(pilotsFetchDataSucces(pilots))
  })
  .catch((e) => {console.log('Error in pilotsFetchData', e)});
};
</code>```

This is the reducer:

```<code>const pilotsReducer = (state = [], action) => {
  switch(action.type){
    case 'PILOTS_FETCH_DATA_SUCCES':
    console.log('pilotsReducer', action.pilots);
    return [
      ...state,
      action.pilots
    ];

    default:
    return state;
  }
}

export default pilotsReducer;
</code>```

Later in my component I want to access this data. I'm using mapStateToProps.

```<code>import React from 'react';
import { connect } from 'react-redux';
import SinglePilot from './SinglePilot.js';
import { pilotsFetchData } from '../actions/pilots';

class Pilots extends React.Component {

  componentDidMount () {
 this.props.fetchData('https://raw.githubusercontent.com/guidokessels/xwing-data/master/data/pilots.js');
  }

  render(){
    return (
      <div>
        <h1>Title</h1>
        {this.props.query && <p>You searched for: {this.props.query}</p>}
        {
          //iterate over all objects in this.props.pilots
          this.props.pilots.map( (pilot) => {
            return (
            <SinglePilot
              key={pilot.id}
              name={pilot.name}
           />
          )})
        }
      </div>
    );
  }
}

const mapStateToProps = (state) => ({
      pilots: state.pilots // is [[Array(278)]] instead of [Array(278)]
    });

const mapDispatchToProps = (dispatch) => ({
  fetchData: (url) => dispatch(pilotsFetchData(url))
});

export default connect(mapStateToProps, mapDispatchToProps)(Pilots);
</code>```

The problem I have is that the value of state.pilots is now an array of length 1 and the array that I want (with a length of 278) is inside this array.

I know I could fix this by using state.pilots[0], but I don't like that.
What is causing my initial pilots array to be wrapped inside another array?

Many thanks for any assistance!

Edit: added the code for the reducer.

答:
there's an error when using the spread operator , inside the reducer

```<code>return [
      ...state,
      action.pilots
    ];
</code>```

should be

```<code>return [
      ...state,
      ...action.pilots
    ];
</code>```

Body:
So what I am doing is the following:

An action fetches a .json file from a url and dispatches another action. The value for pilots is [Array(278)].

export const pilotsFetchDataSucces = (pilots) => {
  return {
    type: 'PILOTS_FETCH_DATA_SUCCES',
    pilots
  }
};

export const pilotsFetchData = (url) => (dispatch) => {
  fetch(url)
  .then((response) => {return response.json()})
  .then((pilots) => {
    dispatch(pilotsFetchDataSucces(pilots))
  })
  .catch((e) => {console.log('Error in pilotsFetchData', e)});
};

This is the reducer:

const pilotsReducer = (state = [], action) => {
  switch(action.type){
    case 'PILOTS_FETCH_DATA_SUCCES':
    console.log('pilotsReducer', action.pilots);
    return [
      ...state,
      action.pilots
    ];

    default:
    return state;
  }
}

export default pilotsReducer;

Later in my component I want to access this data. I'm using mapStateToProps.

import React from 'react';
import { connect } from 'react-redux';
import SinglePilot from './SinglePilot.js';
import { pilotsFetchData } from '../actions/pilots';

class Pilots extends React.Component {

  componentDidMount () {
 this.props.fetchData('https://raw.githubusercontent.com/guidokessels/xwing-data/master/data/pilots.js');
  }

  render(){
    return (

Title

        {this.props.query &&
You searched for: {this.props.query}
}
        {
          //iterate over all objects in this.props.pilots
          this.props.pilots.map( (pilot) => {
            return (
            <SinglePilot
              key={pilot.id}
              name={pilot.name}
           />
          )})
        }

    );
  }
}

const mapStateToProps = (state) => ({
      pilots: state.pilots // is [[Array(278)]] instead of [Array(278)]
    });

const mapDispatchToProps = (dispatch) => ({
  fetchData: (url) => dispatch(pilotsFetchData(url))
});

export default connect(mapStateToProps, mapDispatchToProps)(Pilots);

The problem I have is that the value of state.pilots is now an array of length 1 and the array that I want (with a length of 278) is inside this array.

I know I could fix this by using state.pilots[0], but I don't like that.
What is causing my initial pilots array to be wrapped inside another array?

Many thanks for any assistance!

Edit: added the code for the reducer.

Body:
there's an error when using the spread operator , inside the reducer

return [
      ...state,
      action.pilots
    ];

should be

return [
      ...state,
      ...action.pilots
    ];


问:
How to dynamicallly pass component to a parent component
I am struggling with the passing dynamically component to a parent component here is my issue,

My template and component

```<code><tabset [justified]="true">
  <tab heading="Test 1 ">
      // Default
  </tab>
  // Dynamic tabs
  <tab *ngFor="let tab of tabs" [heading]="tab.title" >
     // Dynamic contents
  </tab>
</tabset>

import {
  Component, OnInit
} from '@angular/core';

@Component({
  selector: 'app-container',
  templateUrl: './container.component.html',
  styleUrls: ['./container.component.scss']
})
export class ContainerComponent implements OnInit {
  tabs: any[] = [
    {
      title: 'Test 2',
      content: AnyComponent
    },
    {
      title: 'Test 3',
      content: SomeOtherComponent
    }
  ];

  constructor() {

  }

  ngOnInit() {
  }

  addTab(tab: any) {
    this.tabs.push(tab);
  }

}
</code>```

What I need ... When I click the menu item from other Component(Navigator) it will use addTab() function to pass to container a dynamic component.It can be AComponent BComponent etc etc,
I tried to use NGX Bootstrap to solve this but Ngx doesnt pass the component just html or something else (or I just couldn't)
https://valor-software.com/ngx-bootstrap/#/tabs

答:
First what  Günter Zöchbauer said is true, second if you know all the components there is, i mean the type (AnyComponent, OtherComponent, SomeotherComponent) then use

```<code><anycomponent *ngFor=" let any of anycomponentsarray"><anycomponent>
</code>```

same for the other

```<code><Othercomponent *ngFor=" let any of othercomponentsarray"><Othercomponent>
</code>```

if you whant to use tab array instead used like this

```<code><tab *ngFor="let tab of tabs" [heading]="tab.title" >

<div *ngIf="tab.content === anycomponent">
<anycomponent><anycomponent>
<div>

<div *ngIf="tab.content === othercomponent">
<othercomponent><othercomponent>
<div>
  </tab>
</code>```

anyway component shouldnt be use as variable like this if you can avoid it.
Use a service for communication between components

this for more information

Body:
I am struggling with the passing dynamically component to a parent component here is my issue,

My template and component

<tabset [justified]="true">
  <tab heading="Test 1 ">
      // Default
  </tab>
  // Dynamic tabs
  <tab *ngFor="let tab of tabs" [heading]="tab.title" >
     // Dynamic contents
  </tab>
</tabset>

import {
  Component, OnInit
} from '@angular/core';

@Component({
  selector: 'app-container',
  templateUrl: './container.component.html',
  styleUrls: ['./container.component.scss']
})
export class ContainerComponent implements OnInit {
  tabs: any[] = [
    {
      title: 'Test 2',
      content: AnyComponent
    },
    {
      title: 'Test 3',
      content: SomeOtherComponent
    }
  ];

  constructor() {

  }

  ngOnInit() {
  }

  addTab(tab: any) {
    this.tabs.push(tab);
  }

}

What I need ... When I click the menu item from other Component(Navigator) it will use addTab() function to pass to container a dynamic component.It can be AComponent BComponent etc etc,
I tried to use NGX Bootstrap to solve this but Ngx doesnt pass the component just html or something else (or I just couldn't)
https://valor-software.com/ngx-bootstrap/#/tabs

Body:
First what  Günter Zöchbauer said is true, second if you know all the components there is, i mean the type (AnyComponent, OtherComponent, SomeotherComponent) then use

<anycomponent *ngFor=" let any of anycomponentsarray"><anycomponent>

same for the other

<Othercomponent *ngFor=" let any of othercomponentsarray"><Othercomponent>

if you whant to use tab array instead used like this

<tab *ngFor="let tab of tabs" [heading]="tab.title" >

<div *ngIf="tab.content === anycomponent">
<anycomponent><anycomponent>
<div>

<div *ngIf="tab.content === othercomponent">
<othercomponent><othercomponent>
<div>
  </tab>

anyway component shouldnt be use as variable like this if you can avoid it.
Use a service for communication between components

this for more information


问:
auto f = bind(dist<>,gen) fails in C++ member declaration. Not recognized as a function
Some example code in Stroustrup's "C++ Programming Language" fails to compile using GCC 6.4.1 std=C11.

```<code>#include <random>
#include <functional>

// From Stroustrup C++11 4th Edition section 40.7
// error: non-static data member declared ‘auto’
class Rand_int {
public:    // public: Added to text from original
    Rand_int(int lo, int hi) : p{lo,hi} { }
    int operator()() const { return r(); }
private:
    std::uniform_int_distribution<>::param_type p;
    auto r = std::bind(std::uniform_int_distribution<>{p},std::default_random_engine{});
};
</code>```

The compiler fails with "error: non-static data member declared ‘auto’". Hence it sees this definition as that of a data member and not a member function. The return from bind is supposed to allow declaration auto.

This quote from Stroustrup follows immediately after the code above "I store the parameters using the distribution’s standard param_type alias (§40.7.3) so that I can use
auto to avoid having to name the result of the bind() ."

default_random_engine is a typedef of a stdlib template function. How to fix?

答:
Hence it sees this definition as that of a data member and not a member function.

You have couple issues with this approach:

std::bind() returns a "function object" aka functor, not function

From std::bind documentation:

A function object of unspecified type T, for which std::is_bind_expression::value == true

even if you put a function on the right side of assignment it would not make it a function

For example:

```<code> void foobar();
 auto r = foobar;
</code>```

this would make r a pointer to function foobar() with type void (*)(); not a function. It is not possible to declare a method or standalone function this way. The fact, that later in code you can call it like a function with r(); does not make that a function.

Body:
Some example code in Stroustrup's "C++ Programming Language" fails to compile using GCC 6.4.1 std=C11.

#include <random>
#include <functional>

// From Stroustrup C++11 4th Edition section 40.7
// error: non-static data member declared ‘auto’
class Rand_int {
public:    // public: Added to text from original
    Rand_int(int lo, int hi) : p{lo,hi} { }
    int operator()() const { return r(); }
private:
    std::uniform_int_distribution<>::param_type p;
    auto r = std::bind(std::uniform_int_distribution<>{p},std::default_random_engine{});
};

The compiler fails with "error: non-static data member declared ‘auto’". Hence it sees this definition as that of a data member and not a member function. The return from bind is supposed to allow declaration auto.

This quote from Stroustrup follows immediately after the code above "I store the parameters using the distribution’s standard param_type alias (§40.7.3) so that I can use
auto to avoid having to name the result of the bind() ."

default_random_engine is a typedef of a stdlib template function. How to fix?

Body:
Hence it sees this definition as that of a data member and not a member function.

You have couple issues with this approach:

std::bind() returns a "function object" aka functor, not function

From std::bind documentation:

A function object of unspecified type T, for which std::is_bind_expression::value == true

even if you put a function on the right side of assignment it would not make it a function

For example:

 void foobar();
 auto r = foobar;

this would make r a pointer to function foobar() with type void (*)(); not a function. It is not possible to declare a method or standalone function this way. The fact, that later in code you can call it like a function with r(); does not make that a function.


答:
As pilots is also an array, you need to spread it as well.

Instead of

```<code>return [
  ...state,
  action.pilots
]
</code>```

return your new state as

```<code>return [
  ...state,
  ...action.pilots
]
</code>```

Title: Getting an array from the redux store puts it inside another array

Body:
As pilots is also an array, you need to spread it as well.

Instead of

return [
  ...state,
  action.pilots
]

return your new state as

return [
  ...state,
  ...action.pilots
]


问:
lombok @Builder vs constructor
Could someone explain me the advantages of using lombok @Builder to create an object instead of constructor call?

```<code>MyObject o1 = MyObject.builder()
              .id(1)
              .name("name")
              .build();

MyObject o2 = new MyObject(1, "name")
</code>```

Is it just a question of better visibility?

答:
This is not a lombok specific feature, this is called a builder pattern.

Imagine you have a class with 20 parameters, and 10 of them are optional. You could somehow make tons of constructors taking care of this logic, or make a constructor with all those arguments and pass nulls in some places. Isn't builder pattern simply easier?

ContentLicense: CC BY-SA 4.0

Title: lombok @Builder vs constructor

Body:
Could someone explain me the advantages of using lombok @Builder to create an object instead of constructor call?

MyObject o1 = MyObject.builder()
              .id(1)
              .name("name")
              .build();

MyObject o2 = new MyObject(1, "name")

Is it just a question of better visibility?


问:
How to get random value of attribute of Enum on each iteration?
I have created such Enum object:

```<code>class Gender(Enum):
    FEMALE = 'female'
    MALE = 'male'
    RANDOM = random.choice([FEMALE, MALE])
</code>```

and i want to get really random value each time, but it does not work:

```<code>>>> class Gender(Enum):
...    MALE = 'male'
...    FEMALE = 'female'
...    RANDOM = choice([MALE, FEMALE])
...
>>> Gender.RANDOM
<Gender.MALE: 'male'>
>>> Gender.RANDOM
<Gender.MALE: 'male'>
>>> Gender.RANDOM
<Gender.MALE: 'male'>
>>> Gender.RANDOM
<Gender.MALE: 'male'>
</code>```

I have also tried use lambda, but it's looks not so good, although it works:

```<code>Gender.RANDOM()
</code>```

Are there other way to get random values each time, without using lambda expressions?

We use this enum object as default value of the argument of the some method that's why it should be an attribute, not a function, because when we use Gender.FEMALE it is not a function, it's an attribute and Gender.RANDOM should be an attribute too:

```<code>def full_name(gender=Gender.FEMALE):
    ...

def full_name(gender=Gender.RANDOM):
    ...
</code>```

答:
As RANDOM is not really an item in your enumeration, I think a more coherent approach would be to keep it precisely as a method and not an attribute (it isn't after all!).

```<code>import random
import enum

class Gender(enum.Enum):
    MALE = 'male'
    FEMALE = 'female'

    @staticmethod
    def random():
        return random.choice(list(Gender))
</code>```

Then, you could transfer the "I'm not choosing" behaviour to the function where it actually makes more sense.

```<code>def full_name(gender=None):
    if gender is None:
        gender = Gender.random()
    # ...
</code>```

Body:
I have created such Enum object:

class Gender(Enum):
    FEMALE = 'female'
    MALE = 'male'
    RANDOM = random.choice([FEMALE, MALE])

and i want to get really random value each time, but it does not work:

>>> class Gender(Enum):
...    MALE = 'male'
...    FEMALE = 'female'
...    RANDOM = choice([MALE, FEMALE])
...
>>> Gender.RANDOM
<Gender.MALE: 'male'>
>>> Gender.RANDOM
<Gender.MALE: 'male'>
>>> Gender.RANDOM
<Gender.MALE: 'male'>
>>> Gender.RANDOM
<Gender.MALE: 'male'>

I have also tried use lambda, but it's looks not so good, although it works:

Gender.RANDOM()

Are there other way to get random values each time, without using lambda expressions?

We use this enum object as default value of the argument of the some method that's why it should be an attribute, not a function, because when we use Gender.FEMALE it is not a function, it's an attribute and Gender.RANDOM should be an attribute too:

def full_name(gender=Gender.FEMALE):
    ...

def full_name(gender=Gender.RANDOM):
    ...

Body:
As RANDOM is not really an item in your enumeration, I think a more coherent approach would be to keep it precisely as a method and not an attribute (it isn't after all!).

import random
import enum

class Gender(enum.Enum):
    MALE = 'male'
    FEMALE = 'female'

    @staticmethod
    def random():
        return random.choice(list(Gender))

Then, you could transfer the "I'm not choosing" behaviour to the function where it actually makes more sense.

def full_name(gender=None):
    if gender is None:
        gender = Gender.random()
    # ...


问:
How to require non-anonymous user in .Net Core?
In .Net Core, the controller attribute [AllowAnonymous] lets you set a controller to allow non-logged in users to access the controller.

Is there a way to do the opposite, to require a user to be logged in? Without giving all users a role and then checking every single controller with [Authorize(Roles = "WarmBody")], I can't see how to require a login?

答:
You should add custom policy filter

```<code>public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc(config =>
        {
            var policy = new AuthorizationPolicyBuilder()
                         .RequireAuthenticatedUser()
                         .Build();
            config.Filters.Add(new AuthorizeFilter(policy));
        });

        //other code ...
    }

    //other code ...
}
</code>```

Or set [Authorize] Attribute for each controller

Body:
You should add custom policy filter

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc(config =>
        {
            var policy = new AuthorizationPolicyBuilder()
                         .RequireAuthenticatedUser()
                         .Build();
            config.Filters.Add(new AuthorizeFilter(policy));
        });

        //other code ...
    }

    //other code ...
}

Or set [Authorize] Attribute for each controller


问:
Any simple php lib to auth with Google, FB, Twitter
Is there something like Hybridauth3, Loginza, or uLogin (but not those as I understand they are not supported by the teams anymore)? Hybridauth is too complex for me for simple auth.</p>

答:
I have used auth libraries from here
opauth and they work quite well.

Libraries from oauthlogin, are also pointed to be reliable but not free


问:
C# Dynamic extends a object
is it possible to extends a existing object ?

i have the code

```<code>var record = new
{
    id,
    name
};
</code>```

and have a list of anonymous objects

```<code>var list = new List<object>(){ object1, object2 };
</code>```

Can i add them later to the object ?
Like something as

```<code>foreach (var o in list)
{
    record.add(o);
}
</code>```

that i will get this as result

```<code>var record = new
{
    id,
    name,
    object1,
    object2
};
</code>```

答:
In short, no. At least, not with anonymous types. There are two approaches here; dynamic might give you what you want, but is fiddly for combining. Other than that, a basic property bag - even simply Dictionary<string,object> would do. The only difference being that:

```<code>obj.id
</code>```

becomes

```<code>obj["id"]
</code>```

There is a more fundamental problem, though, in trying to combine a list (each of which is largely anonymous) with properties in a single step. You can do this for data-binding purpose via custom property models, but it is... tricky.

Title: C# Dynamic extends a object

Body:
is it possible to extends a existing object ?

i have the code

var record = new
{
    id,
    name
};

and have a list of anonymous objects

var list = new List<object>(){ object1, object2 };

Can i add them later to the object ?
Like something as

foreach (var o in list)
{
    record.add(o);
}

that i will get this as result

var record = new
{
    id,
    name,
    object1,
    object2
};

Body:
In short, no. At least, not with anonymous types. There are two approaches here; dynamic might give you what you want, but is fiddly for combining. Other than that, a basic property bag - even simply Dictionary<string,object> would do. The only difference being that:

obj.id

becomes

obj["id"]

There is a more fundamental problem, though, in trying to combine a list (each of which is largely anonymous) with properties in a single step. You can do this for data-binding purpose via custom property models, but it is... tricky.


问:
Iterate java set for first 1000 objects to create custom sql query
I'm trying to write an sql query which runs over a set and sees if the id is in the set but it gives the error that only 1000 items can be in the array. I'm trying to solve it but I got stuck here:

```<code>        for (int i = 0; i < e.getEmployeeSet().size(); i+=1000) {
                sqlQuery.append("AND employee.id");
            if(!e.incudeEmployee()){
                sqlQuery.append("NOT ");
            }
            sqlQuery.append("IN (");
            for(Employee employee: e.getEmployeeSet().){
                sqlQuery.append(employee.getEmployeeId())
                        .append(",");
            }
            sqlQuery.deleteCharAt(sqlQuery.length()-1)
                    .append(") ");
        }
</code>```

I still have to figure out that the first time it has to be AND id.., the other times it has to be OR ... and I have to go over the set in a way that the first time I only go over the first 1000 employee's and so on. Any clean way to fix this?

答:
Sql allows upto 1000 list values in SQL statements. And it is not an efficient way of including the list in IN clause.

Better store data in a temporary table and add join in your query.

Temporary table creation :

create table temp_emprecords as
select * from a, b,c
where clause...;

Now add the temp_emprecords table in your query and join with employee id.

select *
  from employee emp,
       temp_emprecords tmp
 where emp.id = tmp.id;

Body:
I'm trying to write an sql query which runs over a set and sees if the id is in the set but it gives the error that only 1000 items can be in the array. I'm trying to solve it but I got stuck here:

        for (int i = 0; i < e.getEmployeeSet().size(); i+=1000) {
                sqlQuery.append("AND employee.id");
            if(!e.incudeEmployee()){
                sqlQuery.append("NOT ");
            }
            sqlQuery.append("IN (");
            for(Employee employee: e.getEmployeeSet().){
                sqlQuery.append(employee.getEmployeeId())
                        .append(",");
            }
            sqlQuery.deleteCharAt(sqlQuery.length()-1)
                    .append(") ");
        }

I still have to figure out that the first time it has to be AND id.., the other times it has to be OR ... and I have to go over the set in a way that the first time I only go over the first 1000 employee's and so on. Any clean way to fix this?


问:
Tensorflow: Inspecting Hash buckets for Categorical and Feature Columns
I am fitting Linear Classifier for pretty wide and sparse data using number of Categorical Columns with hash bucket and Crossed Feature Columns as Feature Columns.

Later I want to use the weights/coefficients of the model in a custom serving infrastructure. I know how to extract the weights from the model, but obviously, for aforementioned columns, they come for an already hashed feature values.

I can reconstruct a Hashtable (value -> hashed value) for a simple categorical columns using tf.string_to_hash_bucket_fast, but I am getting trouble doing that for Crossed Feature Columns.

For a pair of values of two categorical columns building up a Crossed Column - how can I understand which bucket they will get into?

答:
After inspecting the source code I found out that the simplest way would be to construct an Input Layer for input data consisting of the all the distinct values (or their combinations) in the column.

As a result you get a DenseTensor consisting of 0 and 1, each row corresponds to a distinct value and where 1s are sitting in the columns corresponding to the actual hash bucket number (I've verified that for Categorical Columns, should be the same for CrossedColumns).

Here is the example code (for both Categorical Column and Crossed Column):

```<code>import tensorflow as tf
from tensorflow.python.feature_column import feature_column as fc

actual_sex = {'sex': tf.Variable(['male', 'female', 'female', 'male'], tf.string)}
actual_nationality = {'nationality': tf.Variable(['belgian', 'french', 'belgian', 'belgian'], tf.string)}
actual_sex_nationality = dict(actual_sex, **actual_nationality)

# hashed_column
sex_hashed_raw = fc.categorical_column_with_hash_bucket("sex", 10)
sex_hashed = fc.indicator_column(sex_hashed_raw)

# crossed column
crossed_sn_raw = fc.crossed_column(['sex', 'nationality'], hash_bucket_size = 20)
crossed_sn = fc.indicator_column(crossed_sn_raw)

layer_s = tf.feature_column.input_layer(actual_sex_nationality, sex_hashed)
layer_sn = tf.feature_column.input_layer(actual_sex_nationality, crossed_sn)

sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)

print(sess.run(layer_s))
print(sess.run(layer_sn))
</code>```

Body:
After inspecting the source code I found out that the simplest way would be to construct an Input Layer for input data consisting of the all the distinct values (or their combinations) in the column.

As a result you get a DenseTensor consisting of 0 and 1, each row corresponds to a distinct value and where 1s are sitting in the columns corresponding to the actual hash bucket number (I've verified that for Categorical Columns, should be the same for CrossedColumns).

Here is the example code (for both Categorical Column and Crossed Column):

import tensorflow as tf
from tensorflow.python.feature_column import feature_column as fc

actual_sex = {'sex': tf.Variable(['male', 'female', 'female', 'male'], tf.string)}
actual_nationality = {'nationality': tf.Variable(['belgian', 'french', 'belgian', 'belgian'], tf.string)}
actual_sex_nationality = dict(actual_sex, **actual_nationality)

# hashed_column
sex_hashed_raw = fc.categorical_column_with_hash_bucket("sex", 10)
sex_hashed = fc.indicator_column(sex_hashed_raw)

# crossed column
crossed_sn_raw = fc.crossed_column(['sex', 'nationality'], hash_bucket_size = 20)
crossed_sn = fc.indicator_column(crossed_sn_raw)

layer_s = tf.feature_column.input_layer(actual_sex_nationality, sex_hashed)
layer_sn = tf.feature_column.input_layer(actual_sex_nationality, crossed_sn)

sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)

print(sess.run(layer_s))
print(sess.run(layer_sn))


问:
Change font size for categories in a Xceed PropertyGrid
How do I change the font size of a category header in Xceed's PropertyGrid for WPF?

答:
Set the FontSize property of the control itself and define an implicit TrimmedTextBlock style that sets (preserves) the FontSize of the header:

```<code><xctk:PropertyGrid ... FontSize="20">
    <xctk:PropertyGrid.Resources>
        <Style TargetType="xctk:TrimmedTextBlock">
            <Setter Property="FontSize" Value="12" />
        </Style>
        ...
    </xctk:PropertyGrid.Resources>
</xctk:PropertyGrid>
</code>```

Body:
Set the FontSize property of the control itself and define an implicit TrimmedTextBlock style that sets (preserves) the FontSize of the header:

<xctk:PropertyGrid ... FontSize="20">
    <xctk:PropertyGrid.Resources>
        <Style TargetType="xctk:TrimmedTextBlock">
            <Setter Property="FontSize" Value="12" />
        </Style>
        ...
    </xctk:PropertyGrid.Resources>
</xctk:PropertyGrid>


问:
ASP.NET MVC, One Role for two user, and little different behavior for each user
We have implemented custom roleprovider. This provide us to restricts access to parts of our site using roles. Now we have situation when two users have role Administrator. But one user1 can add comments, and user2 can not add comments(user1 and user2 have role Administrator).

What the best way to solve this problem?

Can we add roles like it Administrator.AddComment and put it in controller action?

答:
How about using a Commentors role:

```<code>[HttpPost]
[Authorize(Roles = "Commentors")]
public ActionResult Create(Comment comment)
{
    ...
}
</code>```

Body:
How about using a Commentors role:

[HttpPost]
[Authorize(Roles = "Commentors")]
public ActionResult Create(Comment comment)
{
    ...
}


答:
Since .net4 you could use ExpandoObject to do stuff like that.

For example:

```<code>        var objs = new List<ExpandoObject>();

        for (var i = 0; i < 10; i++)
        {
            dynamic eObj = new ExpandoObject();
            eObj.Property = i;
            objs.Add(eObj);
        }

        foreach (dynamic obj in objs)
        {
            obj.Property2 = "bubuValue" + obj.Property;
            obj.Property3 = "bubuValue" + obj.Property2;
        }

        foreach (dynamic obj in objs)
        {
            Console.WriteLine(obj.Property3);
        }
</code>```

Title: C# Dynamic extends a object

Body:
Since .net4 you could use ExpandoObject to do stuff like that.

For example:

        var objs = new List<ExpandoObject>();

        for (var i = 0; i < 10; i++)
        {
            dynamic eObj = new ExpandoObject();
            eObj.Property = i;
            objs.Add(eObj);
        }

        foreach (dynamic obj in objs)
        {
            obj.Property2 = "bubuValue" + obj.Property;
            obj.Property3 = "bubuValue" + obj.Property2;
        }

        foreach (dynamic obj in objs)
        {
            Console.WriteLine(obj.Property3);
        }


问:
Running a lambda function slot on instance of a QWidgets Thread
Currently I am creating a thread.

If that thread wants to communicate with the main thread in order to interact with the GUI, It emits signals that are connected to slots on the main widget thread.This works all fine.

However for this solution I have to go back to my original GUI form and add slots to it.

I wanted to know if I could simply do this using lambda functions.
For instance in the following example class foo is launched on a separate thread. Like this

```<code>QObject::connect(this,&myclass::someSignal,
                 [](std::string msg)
                 {
                     QMessageBox::information(mptr,"Some title",
                     msg.c_str(),QMessageBox::StandardButton::Ok);
                 });
</code>```

This gives an error that Widget must be created in GUI thread. And I understand that.

I wanted to know if there was a way for me to specify to run this slot on mptr instance. Like we do using the old Qt QObject::connect signal slot parameter

答:
Just like the classic signal/slot connection where you specify the sender and the receiver, you can specify a QObject context to connect to a lambda :

```<code>QObject::connect(this, &myclass::someSignal,
                 mptr, // Slot/lambda will be executed in this QObject's context
                 [](std::string msg)
                 {
                     QMessageBox::information(mptr,"Some title",
                     msg.c_str(),QMessageBox::StandardButton::Ok);
                 });
</code>```

Meaning that the slot/lambda will be queued in the event loop of the context you specify :

https://doc.qt.io/qt-5/qobject.html#connect-5

Body:
Currently I am creating a thread.

If that thread wants to communicate with the main thread in order to interact with the GUI, It emits signals that are connected to slots on the main widget thread.This works all fine.

However for this solution I have to go back to my original GUI form and add slots to it.

I wanted to know if I could simply do this using lambda functions.
For instance in the following example class foo is launched on a separate thread. Like this

QObject::connect(this,&myclass::someSignal,
                 [](std::string msg)
                 {
                     QMessageBox::information(mptr,"Some title",
                     msg.c_str(),QMessageBox::StandardButton::Ok);
                 });

This gives an error that Widget must be created in GUI thread. And I understand that.

I wanted to know if there was a way for me to specify to run this slot on mptr instance. Like we do using the old Qt QObject::connect signal slot parameter

Body:
Just like the classic signal/slot connection where you specify the sender and the receiver, you can specify a QObject context to connect to a lambda :

QObject::connect(this, &myclass::someSignal,
                 mptr, // Slot/lambda will be executed in this QObject's context
                 [](std::string msg)
                 {
                     QMessageBox::information(mptr,"Some title",
                     msg.c_str(),QMessageBox::StandardButton::Ok);
                 });

Meaning that the slot/lambda will be queued in the event loop of the context you specify :

https://doc.qt.io/qt-5/qobject.html#connect-5