text:
Q: Would showing primary key to the public be potential security risk? Well the question is self-explanatory. One more thing would be, if it is a security risk then please provide an example of what the user could do. In this case the primary key would be something like : "Product ID"
Thanks!

A: No more than showing any other piece of data. If you're vulnerable to SQL injection attacks then showing the primary key is probably the least of your concerns.
Think about it this way, if someone can execute arbitrary sql against your db, which is going to cause more harm: delete from users where id = 100 or delete from users where surname = 'smith'?

A: I don't think there is an inherent risk of exposing the primary key field, but I see no advantage to advertising it as such. (I know I may be reading deeper into your question than you intended)
If you have a ProductId that lets your client identify some product, that's fine to display. The security risk is minimal, IMO. I just would not expose the fact that you used ProductId as a primary key - implementation details should be hidden, even while exposing the content.

A: Not necessarily.  But if you ever wind up changing primary key types along the way (or database providers altogether necessitating the change), abstracting your primary keys to your application-level developers is a good idea.  What you do is create an interface which abstracts the primary key at that level, but the data layer knows about it via its implementation.  Here's an example:
namespace Aesop.DataAccess
{
    // System namespaces
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.Xml.Serialization;

    /// <summary>
    /// Represents an object's unique key in order to abstract out the
    /// underlying key generation/maintenance mechanism.
    /// </summary>
    /// <typeparam name="T">The type the key is representing.</typeparam>
    [ServiceContract]
    public interface IModelIdentifier<T> : ISerializable, IXmlSerializable
    {
        /// <summary>
        /// Gets a string representation of the domain the model originated
        /// from.
        /// </summary>
        string Origin
        {
            [OperationContract]
            get;
        }

        /// <summary>
        /// The model instance identifier for the model object that this
        /// <see cref="IModelIdentifier{T}"/> refers to.  Typically, this
        /// is a database key, file name, or some other unique identifier.
        /// </summary>
        /// <typeparam name="TKeyDataType">The expected data type of the
        /// identifier.</typeparam>
        /// <returns>The unique key as the data type specified.</returns>
        [OperationContract]
        TKeyDataType GetKey<TKeyDataType>();

        /// <summary>
        /// Performs an equality check on the two model identifiers and returns
        /// <c>true</c> if they are equal; otherwise <c>false</c> is returned.
        /// All implementations must also override the equal operator.
        /// </summary>
        /// <param name="obj">The identifier to compare against.</param>
        /// <returns>
        ///   <c>true</c> if the identifiers are equal; otherwise
        ///   <c>false</c> is returned.
        /// </returns>
        [OperationContract]
        bool Equals(IModelIdentifier<T> obj);
    }
}

And here's an implementation for a "standard" int primary key:
namespace Aesop.DataAccess
{
    // System namespaces
    using System;
    using System.Diagnostics;
    using System.Globalization;
    using System.Runtime.Serialization;
    using System.Security.Permissions;
    using System.Xml;
    using System.Xml.Schema;
    using System.Xml.Serialization;

    /// <summary>
    /// Represents an abstraction of the database key for a Model Identifier.
    /// </summary>
    /// <typeparam name="T">The expected owner data type for this identifier.
    /// </typeparam>
    [DebuggerDisplay("Integer Identifier={id}, Origin={Origin}")]
    [Serializable]
    public sealed class IntegerIdentifier<T> : IModelIdentifier<T> where T : class, ISerializable, IXmlSerializable
    {
        /// <summary>
        /// The unique ID.
        /// </summary>
        private int id;

        /// <summary>
        /// Initializes a new instance of the <see cref="IntegerIdentifier<T>"/> class.
        /// </summary>
        /// <param name="id">The unique ID.</param>
        public IntegerIdentifier(int id)
        {
            this.id = id;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="IntegerIdentifier<T>"/> class.
        /// </summary>
        /// <param name="info">The
        /// <see cref="T:System.Runtime.Serialization.SerializationInfo"/> from
        /// which to retrieve the data.</param>
        /// <param name="context">The source (see
        /// <see cref="T:System.Runtime.Serialization.StreamingContext"/>) for
        /// this deserialization.</param>
        [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
        private IntegerIdentifier(
            SerializationInfo info,
            StreamingContext context)
        {
            if (info == null)
            {
                throw new ArgumentNullException("info");
            }

            this.id = info.GetInt32("id");
        }

        /// <summary>
        /// Prevents a default instance of the <see cref="IntegerIdentifier<T>"/> class from being created.
        /// </summary>
        private IntegerIdentifier()
        {
        }

        /// <summary>
        /// Gets a string representation of the domain the model originated
        /// from.
        /// </summary>
        public string Origin
        {
            get
            {
                return this.GetType().Namespace;
            }
        }

        /// <summary>
        /// Implements the operator ==.
        /// </summary>
        /// <param name="integerIdentifier1">The first Model Identifier to
        /// compare.</param>
        /// <param name="integerIdentifier2">The second Model Identifier to
        /// compare.</param>
        /// <returns>
        ///   <c>true</c> if the instances are equal; otherwise
        ///   <c>false</c> is returned.
        /// </returns>
        public static bool operator ==(
            IntegerIdentifier<T> integerIdentifier1,
            IntegerIdentifier<T> integerIdentifier2)
        {
            return object.Equals(integerIdentifier1, integerIdentifier2);
        }

        /// <summary>
        /// Implements the operator !=.
        /// </summary>
        /// <param name="integerIdentifier1">The first Model Identifier to
        /// compare.</param>
        /// <param name="integerIdentifier2">The second Model Identifier to
        /// compare.</param>
        /// <returns>
        ///   <c>true</c> if the instances are equal; otherwise
        ///   <c>false</c> is returned.
        /// </returns>
        public static bool operator !=(
            IntegerIdentifier<T> integerIdentifier1,
            IntegerIdentifier<T> integerIdentifier2)
        {
            return !object.Equals(integerIdentifier1, integerIdentifier2);
        }

        /// <summary>
        /// Determines whether the specified <see cref="T:System.Object"/> is
        /// equal to the current <see cref="T:System.Object"/>.
        /// </summary>
        /// <param name="obj">The <see cref="T:System.Object"/> to compare with
        /// the current <see cref="T:System.Object"/>.</param>
        /// <returns>true if the specified <see cref="T:System.Object"/> is
        /// equal to the current <see cref="T:System.Object"/>; otherwise,
        /// false.</returns>
        /// <exception cref="T:System.NullReferenceException">The
        /// <paramref name="obj"/> parameter is null.</exception>
        public override bool Equals(object obj)
        {
            return this.Equals(obj as IModelIdentifier<T>);
        }

        /// <summary>
        /// Serves as a hash function for a particular type.
        /// </summary>
        /// <returns>
        /// A hash code for the current <see cref="T:System.Object"/>.
        /// </returns>
        public override int GetHashCode()
        {
            return this.id.GetHashCode();
        }

        /// <summary>
        /// Returns a <see cref="System.String"/> that represents this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String"/> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            return this.id.ToString(CultureInfo.InvariantCulture);
        }

        /// <summary>
        /// The model instance identifier for the model object that this
        /// <see cref="IModelIdentifier{T}"/> refers to.  Typically, this is a
        /// database key, file name, or some other unique identifier.
        /// </summary>
        /// <typeparam name="TKeyDataType">The expected data type of the
        /// identifier.</typeparam>
        /// <returns>The unique key as the data type specified</returns>
        public TKeyDataType GetKey<TKeyDataType>()
        {
            return (TKeyDataType)Convert.ChangeType(
               this.id,
               typeof(TKeyDataType),
               CultureInfo.InvariantCulture);
        }

        /// <summary>
        /// Performs an equality check on the two model identifiers and
        /// returns <c>true</c> if they are equal; otherwise <c>false</c>
        /// is returned.  All implementations must also override the equal
        /// operator.
        /// </summary>
        /// <param name="obj">The identifier to compare against.</param>
        /// <returns>
        ///   <c>true</c> if the identifiers are equal; otherwise
        ///   <c>false</c> is returned.
        /// </returns>
        public bool Equals(IModelIdentifier<T> obj)
        {
            if (obj == null)
            {
                return false;
            }

            return obj.GetKey<int>() == this.GetKey<int>();
        }

        /// <summary>
        /// Populates a
        /// <see cref="T:System.Runtime.Serialization.SerializationInfo"/> with
        /// the data needed to serialize the target object.
        /// </summary>
        /// <param name="info">The
        /// <see cref="T:System.Runtime.Serialization.SerializationInfo"/> to
        /// populate with data.</param>
        /// <param name="context">The destination (see
        /// <see cref="T:System.Runtime.Serialization.StreamingContext"/>) for
        /// this serialization.</param>
        /// <exception cref="T:System.Security.SecurityException">The caller
        /// does not have the required permission. </exception>
        [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
        public void GetObjectData(
            SerializationInfo info,
            StreamingContext context)
        {
            if (info == null)
            {
                throw new ArgumentNullException("info");
            }

            info.AddValue("id", this.id);
        }

        /// <summary>
        /// This method is reserved and should not be used. When implementing
        /// the IXmlSerializable interface, you should return null (Nothing in
        /// Visual Basic) from this method, and instead, if specifying a custom
        /// schema is required, apply the
        /// <see cref="T:System.Xml.Serialization.XmlSchemaProviderAttribute"/>
        /// to the class.
        /// </summary>
        /// <returns>
        /// An <see cref="T:System.Xml.Schema.XmlSchema"/> that describes the
        /// XML representation of the object that is produced by the
        /// <see cref="M:System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)"/>
        /// method and consumed by the
        /// <see cref="M:System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)"/>
        /// method.
        /// </returns>
        public XmlSchema GetSchema()
        {
            return null;
        }

        /// <summary>
        /// Generates an object from its XML representation.
        /// </summary>
        /// <param name="reader">The <see cref="T:System.Xml.XmlReader"/>
        /// stream from which the object is deserialized.</param>
        public void ReadXml(XmlReader reader)
        {
            if (reader != null)
            {
                this.id = Convert.ToInt32(
                    reader.GetAttribute("id"),
                    CultureInfo.InvariantCulture);
            }
        }

        /// <summary>
        /// Converts an object into its XML representation.
        /// </summary>
        /// <param name="writer">The <see cref="T:System.Xml.XmlWriter"/>
        /// stream to which the object is serialized.</param>
        public void WriteXml(XmlWriter writer)
        {
            if (writer != null)
            {
                writer.WriteAttributeString(
                    "id",
                    this.id.ToString(CultureInfo.InvariantCulture));
            }
        }

        /// <summary>
        /// Generates an object from its string representation.
        /// </summary>
        /// <param name="value">The value of the model's type.</param>
        /// <returns>A new instance of this class as it's interface containing
        /// the value from the string.</returns>
        internal static IModelIdentifier<T> FromString(string value)
        {
            int id;

            if (int.TryParse(
                value,
                NumberStyles.None,
                CultureInfo.InvariantCulture,
                out id))
            {
                return new IntegerIdentifier<T>(id);
            }

            return null;
        }

        /// <summary>
        /// Generates an object from its XML representation.
        /// </summary>
        /// <param name="reader">The <see cref="T:System.Xml.XmlReader"/>
        /// stream from which the object is deserialized.</param>
        /// <returns>A new instance of this class as it's interface containing
        /// the value from the XmlReader.</returns>
        internal static IModelIdentifier<T> FromXml(XmlReader reader)
        {
            if (reader != null)
            {
                return new IntegerIdentifier<T>(Convert.ToInt32(
                    reader.GetAttribute("id"),
                    CultureInfo.InvariantCulture));
            }

            return null;
        }
    }
}

A: if it includes readable information for some confidential data element, then yes.

A: Obviously that depends on what information the key contains. It's conceivable that it could be sensitive (an account number perhaps). Maybe Product ID is senstitive information in your application but I don't see why the fact that it's a primary key should make it any more or less of a security risk.


text:
Q: How to count business hour between timestamps excluding weekend in MATLAB? I wonder if anyone knows how to count business hour or minute between timestamps in MATLAB? Let's say I have two timestamps:
started: 22/06/2017 18:00
ended: 26/06/2017 09:00

I want to count the minutes between between 08:00 to 17:00 and exclude the weekend. It should be 600 minutes.
Does anyone know how to write a MATLAB function to do it?
I could also use python and/or R.
New request:
If the work time change to 9:30-11:30 and 13:00-15:00 for each working day. I wonder if anyone knows how to do it?
Thanks in advance!
Updates:
@gnovice I made some changes of your original code. It works fine for the use of two separate ranges! Wonder how do you feel about that?
function workMins = work_time(startTime, endTime)
  dateBlock = repmat((dateshift(startTime, 'start', 'day'):...
                      dateshift(endTime, 'start', 'day')).', 1, 4); %'
  dateBlock(:, 1) = dateBlock(:, 1)+hours(9)+minutes(30);
  dateBlock(:, 2) = dateBlock(:, 2)+hours(11)+minutes(30);
  dateBlock(:, 3) = dateBlock(:, 3)+hours(13)+minutes(00);
  dateBlock(:, 4) = dateBlock(:, 4)+hours(15);
  dateBlock(1, 1) = max(dateBlock(1, 1), startTime);
  dateBlock(1, 3) = max(dateBlock(1, 3), startTime);
  dateBlock(end, 2) = min(dateBlock(end, 2), endTime);
  dateBlock(end, 4) = min(dateBlock(end, 4), endTime);
  dateBlock((datestr(dateBlock(:, 1), 'd') == 'S'), :) = [];
  workMins = max(diff(dateBlock, 1, 2), 0);
  workMins(:,2) = [];
  workMins = minutes(sum(workMins(:)));
end

A: The MATLAB solution isn't as ugly as everyone assumes (although it could probably be simplified using the Financial Toolbox). To cut to the chase, here is the solution as a function that accepts two datetime values:
function workMins = work_time(startTime, endTime)
  dateBlock = repmat((dateshift(startTime, 'start', 'day'):...
                      dateshift(endTime, 'start', 'day')).', 1, 2); %'
  dateBlock(:, 1) = dateBlock(:, 1)+hours(8);
  dateBlock(:, 2) = dateBlock(:, 2)+hours(17);
  dateBlock(1, 1) = max(dateBlock(1, 1), startTime);
  dateBlock(end, 2) = min(dateBlock(end, 2), endTime);
  dateBlock((datestr(dateBlock(:, 1), 'd') == 'S'), :) = [];
  workMins = minutes(sum(max(diff(dateBlock, 1, 2), 0)));
end

And here's how it all works...
First, we have our starting and ending times as datetime values:
startTime = datetime('22/06/2017 18:00');
endTime = datetime('26/06/2017 09:00');

Now we can create an N-by-2 matrix of datetimes. Each row will be a day covered by the range from startTime to endTime, with the times set to 0:00:00 for now:
dateBlock = repmat((dateshift(startTime, 'start', 'day'):...
                    dateshift(endTime, 'start', 'day')).', 1, 2);

Now we set the first column times to 8:00:00 and the second column times to 17:00:00:
dateBlock(:, 1) = dateBlock(:, 1)+hours(8);
dateBlock(:, 2) = dateBlock(:, 2)+hours(17);

And now we add startTime and endTime as the first and last elements, respectively, clipping them to the 8:00:00 to 17:00:00 time range:
dateBlock(1, 1) = max(dateBlock(1, 1), startTime);
dateBlock(end, 2) = min(dateBlock(end, 2), endTime);

Next, we remove rows with a datestr day value of 'S' (i.e. a weekend day):
dateBlock((datestr(dateBlock(:, 1), 'd') == 'S'), :) = [];

And finally, we take the column differences, sum them (ignoring negative values), and convert to minutes:
workMins = minutes(sum(max(diff(dateBlock, 1, 2), 0)));

And we get the desired result:
workMins =

   600

EDIT:
Regarding the new request, you can change the function slightly to allow passing in the starting and ending times of a work day like so:
function workMins = work_time(startTime, endTime, workDayStart, workDayEnd)
  dateBlock = repmat((dateshift(startTime, 'start', 'day'):...
                      dateshift(endTime, 'start', 'day')).', 1, 2); %'
  dateBlock(:, 1) = dateBlock(:, 1)+hours(workDayStart);
  dateBlock(:, 2) = dateBlock(:, 2)+hours(workDayEnd);
  ...

And now you can call it with your separate work time ranges and add the results:
startTime = datetime('22/06/2017 18:00');
endTime = datetime('26/06/2017 09:00');
workTotal = work_time(startTime, endTime, 9.5, 11.5) ...
            + work_time(startTime, endTime, 13, 15);

Or subtract a subrange from a larger range:
workTotal = work_time(startTime, endTime, 9.5, 15) ...
            - work_time(startTime, endTime, 11.5, 13);

If you'd prefer instead to specify the work day times as character arrays, you can write the function like this:
function workMins = work_time(startTime, endTime, workDayStart, workDayEnd)
  dateBlock = repmat((dateshift(startTime, 'start', 'day'):...
                      dateshift(endTime, 'start', 'day')).', 1, 2); %'
  workDayStart = datevec(workDayStart);
  workDayEnd = datevec(workDayEnd);
  dateBlock(:, 1) = dateBlock(:, 1)+duration(workDayStart(4:6));
  dateBlock(:, 2) = dateBlock(:, 2)+duration(workDayEnd(4:6));
  ...

And use it like this:
workTotal = work_time(startTime, endTime, '9:30', '11:30') ...
            + work_time(startTime, endTime, '13:00', '15:00');

A: Here is a solution in R
DATA
start = "22/06/2017 18:00"
end = "26/06/2017 09:00"

FUNCTION
foo = function(start, end, filter_weekend = TRUE,
        daystart = "08:00:00", dayend = "17:00:00", units = "mins"){
#start and end should be POSIXct

    require(lubridate)

    #Get a sequence of all dates between start and end
    df = data.frame(col1 = seq.Date(from = as.Date(start),
                                    to = as.Date(end),
                                    by = "days"))

    #Set start of each day at daystart
    df$start = ymd_hms(paste(df$col1, daystart))

    #Set end of each day at dayend
    df$end = ymd_hms(paste(df$col1, dayend))
    df$days = weekdays(df$start)

    #Set the first day$start to be correct date and time
    df$start[1] = start
    #Set the last day$end to be correct date and time
    df$end[NROW(df)] = end

    if (filter_weekend == TRUE){
        #Remove weekends
        df = df[!df$days %in% c("Saturday", "Sunday"), ]
    }
    #Remove rows if end is smaller than start (relevant in first and last row)
    df = df[df$end > df$start, ]

    #Compute time difference for each row
    df$time = difftime(time1 = df$end, time2 = df$start, units = units)

    #Output
    return(sum(df$time))
}

USAGE
library(lubridate)
foo(start = dmy_hm(start), end = dmy_hm(end))
#Time difference of 600 mins

foo(start = dmy_hms("22/06/2017 14:21:19"),
        end = dmy_hms("26/06/2017 06:20:53"),
        units = "secs", filter_weekend = TRUE)
#Time difference of 41921 secs

A: This is not pretty and there must be a classier way, but this should do the trick in base R:
x <- seq(from = as.POSIXct("22/06/2017-18:00", format = '%d/%m/%Y-%H:%M'), to = as.POSIXct("26/06/2017-09:00", format = '%d/%m/%Y-%H:%M'), by= (60*60))
x <- x[!weekdays(x) %in% c('Saturday','Sunday')]
x <- x[x %in% as.POSIXct(unlist(lapply(unique(as.Date(x)), function(x){paste0(x, ' ', ifelse(nchar(8:16) == 1, as.character(paste0('0', 8:16)), 8:16))})), format = "%Y-%m-%d %H")]
(length(x)-1)*60

Thinking about it, it might be smarter to generate workdays with the desired timespan and add up the result of difftime for each day.

A: Here is a custom function that will work to calculate the minutes worked. It's a bit lengthy, but it has a few checks in it which help ensure values are being calculated properly. It also takes the unit as an argument, so you can calculate the total as secs, mins, hours, days, or weeks.
work.time <- function(Date1, Date2, work.start, work.end, unit){

  # If dates are equal return 0
  if(Date1 == Date2){
    return(0)
  }

  # Check to make sure Date1 is always before Date2
  if(Date1 > Date2){
    D <- Date1
    Date1 <- Date2
    Date2 <- D
    rm(D)
  }

  # Get workday start and end timestamps for both days
  D1.start <- as.POSIXct(format(Date1, format = paste("%d/%m/%Y", work.start)), format = "%d/%m/%Y %H:%M")
  D1.end <- as.POSIXct(format(Date1, format = paste("%d/%m/%Y", work.end)), format = "%d/%m/%Y %H:%M")

  D2.start <- as.POSIXct(format(Date2, format = paste("%d/%m/%Y", work.start)), format = "%d/%m/%Y %H:%M")
  D2.end <- as.POSIXct(format(Date2, format = paste("%d/%m/%Y", work.end)), format = "%d/%m/%Y %H:%M")

  # Calculate value for a full workday
  full.day <- as.numeric(difftime(D1.end, D1.start, units = unit))

  # Calculate value if dates fall on the same day
  if(as.Date(Date1) == as.Date(Date2)){
    if(weekdays(as.Date(Date1)) %in% c("Saturday", "Sunday")){
      val <- 0
    } else if(Date1 >= D1.start & Date2 <= D1.end){
      val <- as.numeric(difftime(Date2, Date1, units = unit))
    } else if(Date1 >= D1.start & Date2 > D1.end){
      val <- as.numeric(difftime(D1.end, Date1, units = unit))
    } else if(Date1 < D1.start & Date2 <= D1.end){
      val <- as.numeric(difftime(Date2, D1.start, units = unit))
    } else if(Date1 < D1.start & Date2 > D1.end){
      val <- full.day
    } else{
      val <- 0
    }
    return(val)
  }

  # Calculate value for first workday
  if(weekdays(as.Date(Date1)) %in% c("Saturday", "Sunday")){
    d1.val <- 0
  } else
    if(Date1 >= D1.start & Date1 <= D1.end){
    d1.val <- as.numeric(difftime(D1.end, Date1, units = unit))
  } else if(Date1 > D1.end){
    d1.val <- 0
  } else if(Date1 < D1.start){
    d1.val <- full.day
  }

  # Calculate value for last workday
  if(weekdays(as.Date(Date2)) %in% c("Saturday", "Sunday")){
    d2.val <- 0
  } else if(Date2 >= D2.start & Date2 <= D2.end){
    d2.val <- as.numeric(difftime(Date2, D2.start, units = unit))
  } else if(Date2 > D2.end){
    d2.val <- full.day
  } else if(Date2 < D2.start){
    d2.val <- 0
  }

  # Calculate work value for all workdays between Date1 and Date2
  work.days <- sum(!weekdays(seq(as.Date(Date1) + 1, as.Date(Date2) - 1, "days")) %in% c("Saturday", "Sunday"))

  # Add up final work value total
  work.val <- (work.days * full.day) + d1.val + d2.val

  return(work.val)
}

Date1 <- as.POSIXct("24/06/2017 18:00", format = "%d/%m/%Y %H:%M")
Date2 <- as.POSIXct("26/06/2017 09:00", format = "%d/%m/%Y %H:%M")

work.time(Date1, Date2, work.start = "08:00", work.end = "17:00", unit = "mins")

redpajama_set_name: RedPajamaStackExchange


text:
Q: Django, Display thumbs in Admin? how ill show in the admin section the user picture?, i was looking the template of the admin and i can't see how...
i think that Django show the fields in the section code (change_list template), but jeje ..how? jeje
{% block result_list %}
          {% if action_form and actions_on_top and cl.full_result_count %}{% admin_actions %}{% endif %}
          {% result_list cl %}
          {% if action_form and actions_on_bottom and cl.full_result_count %}{% admin_actions %}{% endif %}
      {% endblock %}

Thanks guys :)

A: We use Justin Driscoll's fabulous django-photologue.
If photologue is installed properly (recommend running python manage.py plinit as part of the installation) and the media is being served correctly the following should provide you with an easy-to-use admin_thumbnail() as follows:
models.py
from photologue.models import Photo

class Entry(models.Model):
    entry_photo = models.ForeignKey(Photo)
    ...

admin.py
def show_entry_thumbnail(item):
    return item.entry_photo.admin_thumbnail()
show_entry_thumbnail.short_description = _('Entry Photo')

class ItemAdmin(admin.ModelAdmin):
    list_display = (show_entry_thumbnail, ... )

A: There also appears to be an alternative method using sorl-thumbnail: it's mentioned here.


text:
Q: Complex number under Sqrt Is it possible that $\sqrt{a+ i \: b} $ could not be written as one of the below forms?
$ i \sqrt{-a-i\:b} $
or
$-i \sqrt{-a-i\:b}$
$a$ and $b$ are real constants.

A: set $$\sqrt{a+bi}=X+iY$$ and square it, then you will get
$$a+bi=X^2-Y^2+2XYi$$ and it must be $$a=X^2-Y^2,b=2XY$$ now you can calculate $$X,Y$$

A: $\displaystyle \sqrt{a+ i \: b}=\sqrt{-i^2(a+ i \: b)}=\sqrt{i^2} \cdot \sqrt{-(a+ i \: b)}=i\sqrt{-a-ib}$
Because: $\sqrt{i^2}=\sqrt{(\sqrt{-1})^2}=\sqrt{-1}=i$
Update: Thanks to Watson's comment as we can also find here we can't always separate the square roots but here we can.
If $|Arg(i^2)+Arg(a+ib)|≥π$, then $\sqrt{i^2 (a+ib)}=\sqrt {i^2} \sqrt {a+ib}$ does not hold,
but we have: $|Arg(i^2 \in \Bbb R)+Arg(a+ib)|=|0+Arg(a+ib)|=|Arg(z)|\leqπ$, So it is ok since always an argumnet of a complex number lies in the specified range.


text:
Q: [Content_Types].xml unknown error in ASP.NET Core 5 (EPPlus) I am trying to use EPPlus to manipulate my xlsm template and download to client. I believe there is no issue with excel package as I am able to save the package locally. But I need content disposition to download to client when it is live...
I have tried many different ways, return file, return filecontentresult, return streamcontentresult but all result in the same unknown error (attached in screenshot, as I could not translate it)..

A: Solved... you cannot use Ajax to call excel export function in controller. instead, call directly using html action link and return file ActionResult and it will initiate download in client browser.
similar resolution can be found here.
Response.WriteFile() -- not working asp net mvc 4.5


text:
Q: Android Retrofit 2 upload multiple image to server I'm new for the Android develop, I'm working on an App just like second hand tread, I have an activity is user can upload there items to the server(the text and image), but the problem is upload text is easy, I used Volley to upload the text to server, but I struggle long time to upload the multiple the images to server.
I saw the Retrofit 2 really good for multiple file upload but I have A lot problems.
Here is ApiService
public interface ApiService {
@Multipart
@POST("xxxxxxxxxx.php")
Call<ServerResponse> uploadFile(
                                @Part("uploadedfile")RequestBody uploadedfile,
                                @Part("itemID")RequestBody itemId,
                                @Part MultipartBody.Part file
);

public static final Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://xxxxxxxxxxxx/")
        .addConverterFactory(GsonConverterFactory.create())
        .build();
}

Here is serverResponse
    public class ServerResponse {
@SerializedName("message")
String message;
@SerializedName("error")
boolean error;

public String getMessage(){
    return message;
}

public boolean isError(){
    return error;
}
}

Here is Activity
public class upload extends AppCompatActivity {

public static final String UPLOAD_URL = "http://xxxxxxxxxxxxxxxxxxxxx.php";
public static final String KEY_Title = "title";
public static final String KEY_DESCRIPTION = "description";
public static final String KEY_ISBN = "ISBN";
public static final String KEY_PRICE = "price";
public static final String KEY_CONTECTNUMBER = "contectNumber";

private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
ProgressDialog progressDialog;
String data;

private EditText et_itemTitle;
private EditText et_ISBN;
private EditText et_itemPrice;
private EditText et_itemDescription;
private EditText et_phone;
private Button b_chooseImage;
private Button bPost;
String id = "4";

private LinearLayout lnrImages;
private ArrayList<String> imagesPathList;
private Bitmap yourbitmap;
private Bitmap resized;
private final int PICK_IMAGE_MULTIPLE = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_upload);

    et_itemTitle = (EditText) findViewById(R.id.et_itemTitle);
    et_ISBN = (EditText) findViewById(R.id.et_ISBN);
    et_itemPrice = (EditText) findViewById(R.id.et_itemPrice);
    et_itemDescription = (EditText) findViewById(R.id.et_itemDescription);
    et_phone = (EditText) findViewById(R.id.et_phone);
    b_chooseImage = (Button) findViewById(R.id.b_chooseImage);
    bPost = (Button) findViewById(R.id.bPost);

    lnrImages = (LinearLayout) findViewById(R.id.lnrImages);

    progressDialog = new ProgressDialog(this);
    progressDialog.setMessage("Uploading...");

    bPost.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final String itemTitle = imagesPathList.get(0).toString();
            final String ISBN = et_ISBN.getText().toString();
            final String itemPrice = et_itemPrice.getText().toString();
            final String itemDescription = et_itemDescription.getText().toString();
            final String contectNumber = et_phone.getText().toString();

            final String user = ((globalV) getApplication()).getUserID();
            final String session = ((globalV) getApplication()).getSessionID();
            StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonResponse = new JSONObject(response);
                        boolean error = jsonResponse.getBoolean("error");

                        if (error) {
                            String errorMessage = jsonResponse.getString("message");
                            AlertDialog.Builder builder = new AlertDialog.Builder(upload.this);
                            builder.setMessage(errorMessage)
                                    .setNegativeButton("Retry", null)
                                    .create()
                                    .show();
                        } else {
                            String successMessage = jsonResponse.getString("message");
                            System.out.println(successMessage+"---------------");
                            String itemID = jsonResponse.getString("itemID");

                            ((globalV) getApplication()).setItemID(itemID);
                            File file = new File(imagesPathList.get(0));
                            System.out.print(imagesPathList.get(0)+"====-=-=-=-=-=---=-=");

                            Gson gson = new GsonBuilder()
                                    .setLenient()
                                    .create();

                            RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"), file);
                            RequestBody uploadedfile = RequestBody.create(MediaType.parse("text/plain"), file.getName());
                            RequestBody itemId = RequestBody.create(MediaType.parse("text/plain"), file.getName());
                            MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("uploadedfile", file.getName(), requestBody);
                            System.out.print(file+"xxxxxxxxxx");

                            ApiService apiService =ApiService.retrofit.create(ApiService.class);
                            Call<ServerResponse> call = apiService.uploadFile(uploadedfile, itemId, fileToUpload);
                            call.enqueue(new Callback<ServerResponse>() {
                                @Override
                                public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {
                                    ServerResponse serverResponse = response.body();
                                    if (serverResponse != null) {
                                        if (serverResponse.isError()) {
                                            Toast.makeText(getApplicationContext(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
                                        }else {
                                            Toast.makeText(getApplicationContext(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
                                        }
                                    }else {
                                        assert  serverResponse != null;
                                        Log.v("Response", serverResponse.toString());
                                    }
                                    progressDialog.dismiss();
                                }

                                @Override
                                public void onFailure(Call<ServerResponse> call, Throwable t) {
                                    Log.v("OnFailure", t.toString());
                                }
                            });  //stop

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(upload.this, error.toString(), Toast.LENGTH_SHORT).show();
                }
            }) {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {

                    Map<String, String> map = new HashMap<String, String>();
                    map.put(KEY_Title, itemTitle);
                    map.put(KEY_ISBN, ISBN);
                    map.put(KEY_PRICE, itemPrice);
                    map.put(KEY_DESCRIPTION, itemDescription);
                    map.put(KEY_CONTECTNUMBER, contectNumber);
                    map.put("userID", user);
                    map.put("sessionID", session);
                    map.put("id", id);
                    return map;
                }
            };
            RequestQueue requestQueue = Volley.newRequestQueue(upload.this);
            requestQueue.add(stringRequest);

        }

    });
    b_chooseImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(upload.this, CustomPhotoGalleryActivity.class);
            startActivityForResult(intent, PICK_IMAGE_MULTIPLE);
            if (imagesPathList != null) {
                Toast.makeText(upload.this, " no images are selected", Toast.LENGTH_SHORT).show();
            }
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if (requestCode == PICK_IMAGE_MULTIPLE) {
            imagesPathList = new ArrayList<String>();
            String[] imagesPath = data.getStringExtra("data").split("\\|");
            try {
                lnrImages.removeAllViews();
            } catch (Throwable e) {
                e.printStackTrace();
            }
            for (int i = 0; i < imagesPath.length; i++) {
                imagesPathList.add(imagesPath[i]);
                yourbitmap = BitmapFactory.decodeFile(imagesPath[i]);
                ImageView imageView = new ImageView(this);
                imageView.setImageBitmap(yourbitmap);
                imageView.setAdjustViewBounds(true);
                lnrImages.addView(imageView);
            }
        }
    }
}
}

And I have other activity to select images
public class CustomPhotoGalleryActivity extends Activity {
private GridView grdImages;
private Button btnSelect;

private ImageAdapter imageAdapter;
private String[] arrPath;
private boolean[] thumbnailsselection;
private int ids[];
private int count;
int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.custom_gallery);
    grdImages = (GridView) findViewById(R.id.grdImages);
    btnSelect = (Button) findViewById(R.id.btnSelect);

    if (ContextCompat.checkSelfPermission(this,Manifest.permission.READ_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED){
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.READ_EXTERNAL_STORAGE)){

        }else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
        }
    }

    final String[] columns = {MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID};
    final String orderBy = MediaStore.Images.Media._ID;
    @SuppressWarnings("deprecation")
    Cursor imagecursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, orderBy);
    int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
    this.count = imagecursor.getCount();
    this.arrPath = new String[this.count];
    ids = new int[count];
    this.thumbnailsselection = new boolean[this.count];
    for (int i = 0; i < this.count; i++) {
        imagecursor.moveToPosition(i);
        ids[i] = imagecursor.getInt(image_column_index);
        int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
        arrPath[i] = imagecursor.getString(dataColumnIndex);
    }
    imageAdapter = new ImageAdapter();
    grdImages.setAdapter(imageAdapter);
    imagecursor.close();

    btnSelect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final int len = thumbnailsselection.length;
            int cnt = 0;
            String selectImages = "";
            for (int i = 0; i < len; i++) {
                if (thumbnailsselection[i]) {
                    cnt++;
                    selectImages = selectImages + arrPath[i] + "|";
                }
            }
            if (cnt == 0) {
                Toast.makeText(getApplicationContext(), "Please select at least one image", Toast.LENGTH_LONG).show();
            } else {

                Log.d("SelectedImages", selectImages);
                Intent i = new Intent();
                i.putExtra("data", selectImages);
                setResult(Activity.RESULT_OK, i);
                System.out.print("===="+selectImages);
                finish();
            }
        }
    });
}
    @Override
    public void onBackPressed() {
        setResult(Activity.RESULT_CANCELED);
        super.onBackPressed();
    }

private void setBitmap(final ImageView iv, final int id) {

    new AsyncTask<Void, Void, Bitmap>() {

        @Override
        protected Bitmap doInBackground(Void... params) {
            return MediaStore.Images.Thumbnails.getThumbnail(getApplicationContext().getContentResolver(), id, MediaStore.Images.Thumbnails.MICRO_KIND, null);
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            iv.setImageBitmap(result);
        }
    }.execute();

}

public class ImageAdapter extends BaseAdapter{
   private LayoutInflater mInflater;

    public ImageAdapter(){
        mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return count;
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.custom_gallery_item, null);
            holder.imgThumb = (ImageView) convertView.findViewById(R.id.imgThumb);
            holder.chkImage = (CheckBox) convertView.findViewById(R.id.chkImage);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.chkImage.setId(position);
        holder.imgThumb.setId(position);
        holder.chkImage.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                CheckBox cb = (CheckBox) v;
                int id = cb.getId();
                if (thumbnailsselection[id]) {
                    cb.setChecked(false);
                    thumbnailsselection[id] = false;
                } else {
                    cb.setChecked(true);
                    thumbnailsselection[id] = true;
                }
            }
        });
        holder.imgThumb.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                int id = holder.chkImage.getId();
                if (thumbnailsselection[id]) {
                    holder.chkImage.setChecked(false);
                    thumbnailsselection[id] = false;
                } else {
                    holder.chkImage.setChecked(true);
                    thumbnailsselection[id] = true;
                }
            }
        });
        try {
            setBitmap(holder.imgThumb, ids[position]);
        } catch (Throwable e) {
        }
        holder.chkImage.setChecked(thumbnailsselection[position]);
        holder.id = position;
        return convertView;
    }
}

class ViewHolder {
    ImageView imgThumb;
    CheckBox chkImage;
    int id;
}

}

Probably I need request the server at the same time, please can someone help me.............

A: If you want to upload multiple image with single key. Make MultipartBody.Part as Array.
Call<ServerResponse> uploadFile(
    @Part("uploadedfile")RequestBody uploadedfile,
    @Part("itemID")RequestBody itemId,
    @Part MultipartBody.Part[] file
);

MultipartBody.Part[] imageParts = new MultipartBody.Part[10];

for (int index = 0; index < 10; index++) {
    File file = new File(IMAGE_FILE[index]);
    RequestBody surveyBody = RequestBody.create(MediaType.parse("image/*"), file);
    imageParts[index] = MultipartBody.Part.createFormData("SurveyImage", file.getName(), uploadedfile);
}


text:
Q: How do we take second order of total differential? This is the total differential
$$df=dx\frac {\partial f}{\partial x}+dy\frac {\partial f}{\partial y}.$$
How do we take higher orders of total differential, $d^2 f=$?
Suppose I have $f(x,y)$ and I want the second order total differential $d^2f$?

A: $d=dx\frac{\partial}{\partial x}+dy\frac{\partial}{\partial y}$ is a differential operator that when applied to $f$ gives $df=dx\frac{\partial f}{\partial x}+dy\frac{\partial f}{\partial y}$
$d^2=\left(dx\frac{\partial}{\partial x}+dy\frac{\partial}{\partial y}\right)\left(dx\frac{\partial}{\partial x}+dy\frac{\partial}{\partial y}\right)$
$d^2f=\left(dx\frac{\partial}{\partial x}+dy\frac{\partial}{\partial y}\right)\left(dx\frac{\partial}{\partial x}+dy\frac{\partial}{\partial y}\right)f=\left(dx^2\frac{\partial^2}{\partial x^2}+dy^2\frac{\partial^2}{\partial y^2}+2dx dy\frac{\partial^2}{\partial x\partial y}\right)f=dx^2\frac{\partial^2 f}{\partial x^2}+dy^2\frac{\partial^2 f}{\partial y^2}+2dx dy\frac{\partial^2 f}{\partial x\partial y}$

A: I will assume that you are referring to the Fréchet derivative. If $U\subseteq\mathbb{R}^n$ is an open set and we have functions $\omega_{j_1,\dots,j_p}:U\to\mathbb{R}$, then $$
D\left(\sum_{j_1,\dots,j_p} \omega_{j_1,\dots,j_p} dx_{j_1}\otimes\cdots\otimes dx_{j_p}\right) = \sum_{j_1,\dots,j_p}\sum_{j=1}^n \frac{\partial\omega_{j_1,\dots,j_p}}{\partial x_{j}} dx_j\otimes dx_{j_1}\otimes\cdots\otimes dx_{j_p}.
$$
Here $dx_{i}$ is the projection onto the $i$th coordinate, and if $\alpha,\beta$ are multilinear forms then $\alpha\otimes\beta$ is the multilinear form defined by $(\alpha\otimes\beta)(x,y)=\alpha(x)\beta(y)$.
For example, let $f(x,y)=x^3+x^2 y^2+y^3$. Then \begin{align}
Df&=(3x^2+2xy^2)dx+(2x^2y+3y^2)dy; \\
D^2f&=(6x+2y^2)dx\otimes dx+4xy(dx\otimes dy+dy\otimes dx)+(2x^2+6y)dy\otimes dy; \\
D^3f&=6dx\otimes dx\otimes dx+4y(dx\otimes dx\otimes dy+dx\otimes dy\otimes dx+dy\otimes dx\otimes dx)\\
&\qquad+4x(dx\otimes dy\otimes dy+dy\otimes dx\otimes dy+dy\otimes dy\otimes dx) \\
&\qquad+6dy\otimes dy\otimes dy.
\end{align}
Since $D^p f(x)$ is always a symmetric multilinear map if $f$ is of class $C^p$, you might want to simplify the above by using the symmetric product (of tensors).

A: Edit: I interpret your $d^2 f$ as $d^2f=d(df)$.
If $f$ is $C^2(\Omega)$, with $(x,y)\in\Omega$, then
$$d(df)=dy\wedge dx \frac{\partial^2 f}{\partial y\partial x}+dx\wedge dy
\frac{\partial^2 f}{\partial x\partial y}=\left(\frac{\partial^2 f}{\partial x\partial y}- \frac{\partial^2 f}{\partial y\partial x} \right)dx\wedge dy=0,$$
as $dx \wedge dy=-dy\wedge dx$ and $\frac{\partial^2 f}{\partial x\partial y}= \frac{\partial^2 f}{\partial y\partial x}$ on $\Omega$.
If $f$ is not $C^2$ at $(x,y)$, then we arrive at
$$d(df)=\left(\frac{\partial^2 f}{\partial x\partial y}- \frac{\partial^2 f}{\partial y\partial x} \right)dx\wedge dy. $$


text:
Q: add parameter to dynamic EXECUTE in postgreSQL I have a procedure which contain this piece of code
SELECT query INTO query FROM temp_table_test WHERE id = whateverId;

EXECUTE query;

My query variable will contain something like
CALL Someprocedure (withSomeParameters)

How can i make the parameter dynamic in the first proc as they can change time to time and i can't make them static in the variable ?
in t-SQL there is something with
sp_executesql

But as I'm very new to postgres I don't know where to start.

A: assuming you are using pl/pgsql, you can pass parameters with the USING clause;
EXECUTE query USING $1, $2, $3, ...;

for example;
query = 'SELECT SUM( "field_a" ) FROM "table" WHERE "field_b" = $1 AND "field_c" = $2';
EXECUTE query USING 5, 10;

this will be equal to:
SELECT SUM( "field_a" ) FROM "table" WHERE "field_b" = 5 AND "field_c" = 10;


text:
Q: Q: Django - how to return data from other function on views.py I'm kind of working on string operation, here is what i want to do
- i created a functions gettext(request) for getting text from *.txt files, this is the code
def gettext(request):
  if request.method == 'POST':
    form = UploadFileForm(request.POST, request.FILES)
    if form.is_valid():
        f = request.FILES['file']
        for chunk in f.chunks():
            text = chunk

        return render(request, 'ecs/index.html', {'text': text, 'form': form})
    else:
        form = UploadFileForm()
return render_to_response('ecs/index.html', {'form': form})

and then i want to get the data that i stored on text variable to a functions, called preprocessing
def preprocessing(text):
    pp = Preprocess()

    wordTokenize = pp.tokenizing(text)

    return wordTokenize

how can i use the preprocessing(text) method to handle data from text variable on gettext method.
i tried some tricks, but still no progress.

A: import the preprocessing function from wherever you have it into the file that has gettext in it, and then do this:
def gettext(request):
  if request.method == 'POST':
    form = UploadFileForm(request.POST, request.FILES)
    if form.is_valid():
        f = request.FILES['file']
        for chunk in f.chunks():
            text = chunk
            text = preprocessing(text)
        return render(request, 'ecs/index.html', {'text': text, 'form': form})
    else:
        form = UploadFileForm()
return render_to_response('ecs/index.html', {'form': form})


text:
Q: Help evaluating this complex integral Compute the integral $$\int_{\gamma} (\overline{z})^2 dz$$ where $\gamma$ is the contour $y=x^2 +1$ with initial point $z=0$ and terminal point $z=1+2i$
where $\overline{z}$ is the conjugate of $z$
I think i might just be having trouble finding a good parameterization. Any hints or tips?

A: Hint. Let $z(t)=x(t)+iy(t)$, $y(t)=t^2+1$, and $x(t)=t$ with $t\in[0,1]$ then
$dz(t)=(x'(t)+iy'(t))dt$ and
$$\int_{\gamma} (\overline{z})^2 dz=\int_{0}^1(x(t)-iy(t))^2(x'(t)+iy'(t))dt=\int_{0}^1(t-i(t^2+1))^2(1+i2t)dt.$$
Now expand the integrand function and then evaluate the integral of the real part and the integral of the imaginary part.


text:
Q: Вычисление положения 3D-координаты методом нелинейной оптимизации Есть точка в 3D с неизвестными координатами. Она видна на изображениях, взятых со стерео камеры. Координаты на изображениях известны с погрешностью, так же известны параметры стереокамеры. Необходимо найти координаты точки в 3D, минимизируя суммарную среднеквадратичную ошибку репроекции, где эталонными координатами будут измеренные напрямую (то есть координаты проекций этой точки на левом и правом изображениях).
Для этого я думаю подойдёт библиотека ceres-solver. Однако не смог найти примера, как это реализовать. Да и в принципе, мало знаком с задачами нелинейной оптимизации.
При этом, я могу вычислить с приближенные значение положения точки в пространстве через длину базовой лини и значения диспарантности. Далее, как мне кажется, необходимо "уточнить" эти 3D координаты через среднеквадратичную ошибку репроекции. Буду рад любой помощи.


text:
Q: Why isn't my lock channel command working??? discord.py I created a lock channel command but when I test it, it gives me no error and doesn't lock the channel. I searched the internet but couldn't find any working lock commands. Here's my code.
@client.command(pass_context=True)
@commands.has_permissions(manage_channels=True)
async def lock(ctx, channel : discord.TextChannel=None):
    channel = channel or ctx.channel
    overwrite = channel.overwrites_for(ctx.guild.default_role)
    overwrite.send_messages = False
    await channel.set_permissions(ctx.guild.default_role, overwrite=overwrite)
    await ctx.send('Channel locked.')

A: You are using set_permissions wrongly, pass in the permissions name and its value.
Overwrites should be used if you want more than 1 target, here it is only 1 so we can directly use the permission name.
Below is the revised code:
@client.command(pass_context=True)
@commands.has_permissions(manage_channels=True)
async def lock(ctx, channel : discord.TextChannel=None):
    channel = channel or ctx.channel
    await channel.set_permissions(ctx.guild.default_role, send_messages=False)
    await ctx.send('Channel locked.')


text:
Q: Mclust (GMM) graphics are too tiny (matrix of graohics) It's just that I'm trying to know the number of clusters when I make use of GMM method in a dataset (specifically the dataset of asteroids of nasa) but I can't get to understand how to plot every graphic by themself and not in a matrix
For example in iris dataset https://programming.rhysshea.com/GMM_clustering/ (a matrix of graphics) but I want to watch to each individual graphic to understand what else I can do.
Also I want to make it like the examples and make my pc put colors for the points of each different cluster and not all of the same color
tbh I'm kind of lost here but I can't even advance if I can't plot correctly
set.seed(10)
library(dplyr)
library(tidyverse)
library(mclust)
columnas <-c("full_name", "spec_B", "neo", "pha","Danger")
asteroidesp2 <- na.omit(data_p2)
asteroidesp2 <- asteroidesp2[, ! names(asteroidesp2) %in% columnas, drop = F]

asteroides.gmm <- Mclust(asteroides.scale, centers = 4)
plot(asteroides.gmm)


text:
Q: Co-variance of beta coefficients for Dummy Variable regression with intercept If I have a dummy variable regression output with intercept included (base category as omitted category), and I have to do a hypothesis test for difference of means between two categories other than base category, I would need to set up the standard error as
$$
\mathrm{SE}(\beta_i - \beta_j) = \sqrt{\mathrm{Var}(\beta_i) + \mathrm{Var}(\beta_j) - 2 \mathrm{Cov}(\beta_i, \beta_j)}
$$
The $\mathrm{Var}(\beta_i)$ and $\mathrm{Var}(\beta_j)$ are reported in the regression output.
However, suppose I do not have the Covariance values reported in output because the var-covar matrix was not reported.
Is there a way that these co-variances between the betas (off-diagonal elements in the variance-covariance matrix) are directly calculated by knowing the diagonal elements and Mean Squared Error values?

A: Yes.
We have a dummy variable regression in which (without loss of generality) the last category serves as the base case,
$$
y_i=\alpha+\sum_{j=1}^{p-1}\beta_jD_{ij}+u_i
$$
Let there be $n$ observations in total, with $n_j$ observations such that $D_{ij}=1$. We need to look at what happens to the formula for the variance of the regression coefficients, $\sigma^2(X'X)^{-1}$. Here, the regressor matrix $X$ has unit entries in the first column and another unit entry in column $j+1$ if observation $i$ belongs to group $j$ (unless it belongs to group $p$).
Consider $X'X$, which can be written as a block matrix
$$
X'X=\begin{pmatrix}
A&B\\
B'&D
\end{pmatrix}
$$
where $A=n$, $B=(n_1,\cdots,n_{p-1})$ and $D$ a diagonal matrix with main diagonal $B$. This follows by direct multiplication, exploiting that no row of $X$ has more than one entry equal to one (except for the constant column)
To obtain $(X'X)^{-1}$, we use the formula for block inverses,
\begin{align}
(X'X)^{-1} &= \begin{pmatrix}
\hspace{2cm}A  &\hspace{4.3cm}B\\
\hspace{2cm}B' &\hspace{7cm}D
\hspace{2.8cm}\end{pmatrix}^{-1}  \\[5pt]
&=\begin{pmatrix}
(A-BD^{-1}B')^{-1}&-(A-BD^{-1}B')^{-1}BD^{-1}\\
-D^{-1}B'(A-BD^{-1}B')^{-1}&D^{-1}+D^{-1}B'(A-BD^{-1}B')^{-1}BD^{-1}
\end{pmatrix}
\end{align}
The inverse of the diagonal matrix $D$ simply is a diagonal matrix with entries $1/n_j$. Direct multiplication then yields
$$
(A-BD^{-1}B')^{-1}=\left(n-\sum_{j=1}^{p-1}n_j\right)^{-1}=\frac{1}{n_p}
$$
Further, $BD^{-1}=\iota'$, a unit row vector, and hence $D^{-1}B'=\iota$. Putting things together gives
\begin{align}
(X'X)^{-1} &=\begin{pmatrix}
\hspace{.5cm}A  &\hspace{.7cm}B\\
\hspace{.5cm}B' &\hspace{1.5cm}D
\hspace{.8cm}\end{pmatrix}^{-1}  \\[5pt]
&=\begin{pmatrix}
\frac{1}{n_p}&-\frac{1}{n_p}\iota'\\
-\frac{1}{n_p}\iota'&D^{-1}+\frac{1}{n_p}\iota\iota'
\end{pmatrix}
\end{align}
This means that all off-diagonal elements of the variance-covariance matrix only depend on $1/n_p$, which you know from the first squared standard error.
In fact, the derivation hence shows a little more than what you asked: to get the off-diagonal elements, you do not even need to all variances, but only that of the base category.
Here is a little numerical illustration.
n <- 100
y <- rnorm(n)   # this is the dependent variable
p <- 5
X <- matrix(0, nrow=n, ncol=p)
X[cbind(1:n, sample(1:p, n, replace=T))] <- 1 # insert an 1 into one of the columns for each row
reg3 <- summary(lm(y~X[,1:(p-1)])) # regression omitting the pth category
vcov(reg3)

                (Intercept) X[, 1:(p - 1)]1 X[, 1:(p - 1)]2 X[, 1:(p - 1)]3 X[, 1:(p - 1)]4
(Intercept)      0.05463828     -0.05463828     -0.05463828     -0.05463828     -0.05463828
X[, 1:(p - 1)]1 -0.05463828      0.14440116      0.05463828      0.05463828      0.05463828
X[, 1:(p - 1)]2 -0.05463828      0.05463828      0.13318080      0.05463828      0.05463828
X[, 1:(p - 1)]3 -0.05463828      0.05463828      0.05463828      0.10927656      0.05463828
X[, 1:(p - 1)]4 -0.05463828      0.05463828      0.05463828      0.05463828      0.10699996


text:
Q: Windows Phone 7 resolution - Is my emulator lying to me? All the talk on WP7 resolution = 800x480. I can create more than 480 and it shows up in the emulator - I just don't know if this means I do have more screen space than is promulgated or if my emulator is lying to me.
Putting a Silverlight app in Landscape only mode (SupportedOrientations="Landscape" Orientation="Landscape" in <phone:PhoneApplicationPage />). I'll have a width of 800 and height of 480 (d:DesignWidth="800" d:DesignHeight="480").
I change d:DesignHeight to d:DesignHeight="496" and then add as the only XAML inside the <phone:PhoneApplicationPage /> tag:
<Grid x:Name="LayoutRoot" Background="Blue">
    <TextBlock Text="bottom" VerticalAlignment="Bottom"></TextBlock>
</Grid>

See there? My "Bottom" text is still showing on the screen. Anything thoughts?

A: Your "design" sizes will be overridden at runtime. Your emulator isn't lying but your designer is (now) misleading.
You can data-bind some labels to ActualWidth and Actualheight to verify what's happening.

A: Assuming that you have mc:Ignorable="d" set as an attribute on the page, d:DesignHeight="496" only applies in the designer, it does not affect what happens on the emulator or device.


text:
Q: Compatibility between Dell Perc H730 and Seagate Constellation 4TB drives? I'm considering the purchase of a refurbished Dell R730xd with Perc H730 controller. Does anyone know if that controller will recognize and work with Seagate Constellation 4TB NL-SAS drives (ST4000NM0023)?  The configuration would be RAID 6.
I realize the drives are not officially listed by Dell as supported drives.  Reading around the net, it is unclear to me to what extent the Dell controller will only work with specific (signed?) drives.  On another system, with a Dell H710, I was able to buy 3rd-party disks and they worked fine, but I have no experience with the newer H730 controllers.

A: The DELL PERC H730 is based on the LSI 3108 Chipset, and since this chipset supports disks larger than 2TB and SAS3 communications I can't see reasons for this controller won't work with those Seagate NL-SAS 4TB discs.
What you should consider is the cabling used on this card, since SAS3 cards uses the new SFF8643 connector.


text:
Q: Is the probability that n and phi(n) (totient function) are coprime one for random squarefree n? The probability that a prime p does not divide a random integer n is (1-1/p), so for random n we could argue that the probability that n and φ(n) are coprime is
$\prod_{p|n} \left(1-1/p \right) = \phi(n)/n.$
The average order of φ(n)/n is given by
${ 1 \over N } \sum_{n=1}^N {\phi(n) / n} = 6/\pi^2 + O(\log N/N).$
Now the probability that a random integer is squarefree is $6/\pi^2$.
So my question is: does gcd(n,φ(n))=1 for almost all squarefree n? Or to put it another way, for random squarefree n is the probability that n and φ(n) are coprime one?
(Of course we have gcd(55,φ(55))=5, etc.)
I have not been able to find anything about this on the internet and so would like to know if this has been considered before. Thanks.
EDIT: Take integer N and let f(N) = number of squarefree n<=N such that gcd(n,φ(n))>1 (e.g. 21 or 55). Does f(N)/q(N) tend to zero as N tends to infinity, where q(N) is the number of squarefree numbers <= N?

A: Quite the reverse is true: The probability that $n$ and $\phi(n)$ are relatively prime is zero! More precisely, the ratio
$$\frac{1}{N} \cdot \# \{ n : \ n \leq N \ (n, \phi(n))=1 \}$$
goes to $0$ as $N$ goes to $\infty$.
Proof: Fix a positive real number $\epsilon$, we will prove that this ratio is less than $\epsilon$ for $N$ sufficiently large. The product $(1-1/2)(1-1/3)(1-1/5)(1-1/7)(1-1/11) \cdots$ is zero (because $\sum 1/p$ diverges); choose $P$ such that $\prod_{p < P} (1-1/p) < \epsilon/2$.
We claim that, for $N$ sufficiently large:

*

*The proportion of $n$ which are not divisible by some prime less than $P$ is $< \epsilon/2$.

*The proportion of $n$ for which $\prod_{p < P} p$ does not divide $\phi(n)$ is $< \epsilon /2$.
So, with probability $> 1-\epsilon$, the GCD of $n$ and $\phi(n)$ is divisible by some prime less than $P$.
The first bullet point is easy: The density of primes not divisible by some prime less than $P$ is $\prod_{p < P} (1-1/p) + O(1/N) < \epsilon/2 + O(1/N)$.
For the second part, fix a prime $p$ less than $P$. The sum
$$\sum_{\begin{smallmatrix} q \equiv 1 \mod p \\ q \ \mbox{prime} \end{smallmatrix}} \frac{1}{q}$$
diverges, by a quantitative version of Dirichlet's theorem. So we can find $Q$ such that
$$\prod_{\begin{smallmatrix} q \equiv 1 \mod p \\ q \ \mbox{prime} \\ q \leq Q \end{smallmatrix}} (1- 1/q)$$
is arbitrarily small. Letting $K$ be the number of primes less than $P$, choose $Q$ such that this product is less than $\epsilon/(2K)$.
The probability that $p$ does not divide $\phi(n)$ is bounded above by the probability that $n$ is divisible by none of the primes in the above product. We constructed that probability to be less than $\epsilon/(2K)$.
So, for each of the $K$ primes $p$ less than $P$, the probability that $p$ does not divide $\phi(n)$ is less than $\epsilon/(2K)$. This establishes the second bullet point.

A: I'm not sure what you mean by a random integer $n$, but would you
agree that the probability that a random squarefree integer be
divisible by $55$ is nonzero? For if $55\mid n$ then $5\mid\gcd(n,\phi(n))$.
Added
In Derek's new notation it's well-known that $q(N)\sim 6N/\pi^2$. This constant
arises via
$$\frac6{\pi^2}=\prod_p \left(1-\frac1{p^2}\right).$$
Sticking to the example of the number $55$, if $g_{55}(n)$
is the number of squarefree numbers up to $n$ that are divisible by $55$
then $g_{55}(n)=h_{55}(n/55)$ where $h_{55}(n)$
is the number of squarefree numbers up to $n$ that are not divisible by $55$.
But $h_{55}(n)\sim\alpha n$ where $\alpha$ is the same Euler product with
the $p=5$ and $p=11$ terms dropped:
$$\alpha=\frac6{\pi^2}\frac{5^2\times 11^2}{24\times 120}.$$
Thus
$$\frac{g_{55}(n)}{q(n)}\to\frac{55}{24\times 120}=\frac{11}{576}$$
as $n\to\infty$, but of course $f(n)/q(n)\ge g_{55}(n)/q(n)$.
Of course one can perform this argument with other numbers in place of $55$.

A: The asymptotics of the "cyclic numbers", i.e., numbers 'n' such that gcd(n,phi(n)) = 1 was worked out by Erdos in 1948. If I recall the numbers of such numbers less than n is asymptotically n*e^{-\gamma}/(log(log(n))).
The asymptotics of abelian and nilpotent numbers is not known. By the way, the term cyclic numbers was coined in our paper (Shankar and Pakianathan) although the problem of determining such numbers itself goes back to Burnside.

A: Also relevant is Sloane's A060679, orders of non-cyclic groups, which is $n$ such that $\gcd(n,\phi(n))>1$, and its complement A003277. Although the asymptotic density of the latter tends to zero, as David Speyer showed in one of the answers, they're not rare: one in 3 at 30,000, as the b-file shows.  This is denser than the primes at that point.  I wonder what asymptotic order they have?


text:
Q: C# excel Add in I created an excel add in in c# and when I run my code the add in custom buttons come up fine on the excel spreadsheet. But after I publish it and install the add in they dont show up. I am using excel 2013.
I created a group of buttons which should be under home tab
in my custom ribbon tab unde rthe home tab is 'my add in '. but that does not show up when i install the published add in
so i know one thing for sure that my code is fine but there is something messed up with my excel 2013 settings


text:
Q: How to combine groupby, rolling and multiple columns' creation in Python I have an issue that is easily solved with dplyr in R, yet can't seem to find an easy way in Python.
I have a df with id(=customerid), s(=store), m(=month) and ttl(=total purchase) as columns.
I would like to calculate multiple new columns on id+s - for example last 3 months purchase and minimum purchase.
Example (last two are new columns):
id  s         m   ttl ttl_3 min_id_s
1   A   1/1/2020    7   nan 3
1   A   2/1/2020    3   nan 3
1   A   3/1/2020    7   17  3
1   A   4/1/2020    6   16  3
1   A   5/1/2020    7   20  3
1   A   6/1/2020    7   20  3
1   B   1/1/2020    6   nan 6
1   B   2/1/2020    10  nan 6
1   B   3/1/2020    8   24  6
1   B   4/1/2020    8   26  6
1   B   5/1/2020    10  26  6
1   B   6/1/2020    8   26  6
2   A   1/1/2020    4   nan 1
2   A   2/1/2020    3   15  1
2   A   3/1/2020    10  17  1
2   A   4/1/2020    6   19  1
2   A   5/1/2020    4   20  1
2   A   6/1/2020    1   11  1

I've tried the following:
grp = df.groupby(['id','s'])
df = df.assign(ttl_3 = grp['ttl'].apply(lambda x: x.rolling(window=3)).sum(), min_id_s = grp['ttl'].min())

I get the following error:

Cannot access callable attribute 'assign' of 'DataFrameGroupBy'
objects, try using the 'apply' method

I know that it can be solved without assign, but then I'll have to have a line per each new column, and as I need plenty of these, I'm looking for a workaround.
I've also looked into add_columns with pyjanitor, but it doesn't seem to work with groupby.
In R, the following code solves the issue and in the mutate I can proceed adding columns:
df = df %>% group_by(id, s) %>% mutate(ttl_3 = runner(ttl, k=3, f=sum), min_id_s = min(ttl))

A: With python syntax and pandas the logic is nearly identical
t = '''
id  s         m   ttl
1   A   1/1/2020    7
1   A   2/1/2020    3
1   A   3/1/2020    7
1   A   4/1/2020    6
1   A   5/1/2020    7
1   A   6/1/2020    7
1   B   1/1/2020    6
1   B   2/1/2020    10
1   B   3/1/2020    8
1   B   4/1/2020    8
1   B   5/1/2020    10
1   B   6/1/2020    8
2   A   1/1/2020    4
2   A   2/1/2020    3
2   A   3/1/2020    10
2   A   4/1/2020    6
2   A   5/1/2020    4
2   A   6/1/2020    1 '''

import pandas as pd
import io

df = pd.read_csv(io.StringIO(t), sep='\s+')

Trying to come as close to dplyr as I could.
Group by id and s and compute the new columns. Multiple rolling columns could be computed with the agg method.
You can use assign, but you also have to write one line per aggregation.
group = df.groupby(['id','s'])['ttl']
df['ttl_3'] = group.rolling(3).sum().reset_index(level=(0,1), drop=True)
df['min_id_s'] = group.transform('min')
#df = df.assign(
#         ttl_3 = group.rolling(3).sum().reset_index(level=(0,1), drop=True),
#         min_id_s = group.transform('min'))
df

Out:
    id  s         m  ttl  ttl_3  min_id_s
0    1  A  1/1/2020    7    NaN         3
1    1  A  2/1/2020    3    NaN         3
2    1  A  3/1/2020    7   17.0         3
3    1  A  4/1/2020    6   16.0         3
4    1  A  5/1/2020    7   20.0         3
5    1  A  6/1/2020    7   20.0         3
6    1  B  1/1/2020    6    NaN         6
7    1  B  2/1/2020   10    NaN         6
8    1  B  3/1/2020    8   24.0         6
9    1  B  4/1/2020    8   26.0         6
10   1  B  5/1/2020   10   26.0         6
11   1  B  6/1/2020    8   26.0         6
12   2  A  1/1/2020    4    NaN         1
13   2  A  2/1/2020    3    NaN         1
14   2  A  3/1/2020   10   17.0         1
15   2  A  4/1/2020    6   19.0         1
16   2  A  5/1/2020    4   20.0         1
17   2  A  6/1/2020    1   11.0         1

Aggregate multiple columns for rolling with agg
group = df.groupby(['id','s'])['ttl']
df[['ttl_3_sum','ttl_3_mean']] = group.rolling(3).agg(['sum','mean']).reset_index(level=(0,1), drop=True)

Out:
    id  s         m  ttl  ttl_3_sum  ttl_3_mean
0    1  A  1/1/2020    7        NaN         NaN
1    1  A  2/1/2020    3        NaN         NaN
2    1  A  3/1/2020    7       17.0    5.666667
3    1  A  4/1/2020    6       16.0    5.333333
4    1  A  5/1/2020    7       20.0    6.666667
5    1  A  6/1/2020    7       20.0    6.666667
6    1  B  1/1/2020    6        NaN         NaN
7    1  B  2/1/2020   10        NaN         NaN
8    1  B  3/1/2020    8       24.0    8.000000
9    1  B  4/1/2020    8       26.0    8.666667
10   1  B  5/1/2020   10       26.0    8.666667
11   1  B  6/1/2020    8       26.0    8.666667
12   2  A  1/1/2020    4        NaN         NaN
13   2  A  2/1/2020    3        NaN         NaN
14   2  A  3/1/2020   10       17.0    5.666667
15   2  A  4/1/2020    6       19.0    6.333333
16   2  A  5/1/2020    4       20.0    6.666667
17   2  A  6/1/2020    1       11.0    3.666667

Aggregating multiple columns from multiple columns for rolling with agg. The columns have to be numerical. transform doesn't support multiple aggregations as far as I know.
Generate a random numerical column for a rolling aggregation
import numpy as np
df['ttl2'] = np.random.rand(len(df))

groupby without selected columns to aggregate from multiple columns. For example with a custom function
group = df.groupby(['id','s'])
df[['ttl_3_sum', 'ttl2_lambda']] = (group.rolling(3)
          .agg({'ttl':'sum', 'ttl2': lambda x: x.sum()/x.min()})
          .reset_index(level=(0,1), drop=True))
df

Out:
    id  s         m  ttl      ttl2  ttl_3_sum  ttl2_lambda
0    1  A  1/1/2020    7  0.032482        NaN          NaN
1    1  A  2/1/2020    3  0.998115        NaN          NaN
2    1  A  3/1/2020    7  0.689431       17.0    52.953016
3    1  A  4/1/2020    6  0.897444       16.0     3.749456
4    1  A  5/1/2020    7  0.484360       20.0     4.276231
5    1  A  6/1/2020    7  0.971768       20.0     4.859138
6    1  B  1/1/2020    6  0.238363        NaN          NaN
7    1  B  2/1/2020   10  0.740311        NaN          NaN
8    1  B  3/1/2020    8  0.641598       24.0     6.797507
9    1  B  4/1/2020    8  0.984911       26.0     3.688945
10   1  B  5/1/2020   10  0.043379       26.0    38.495141
11   1  B  6/1/2020    8  0.700253       26.0    39.847293
12   2  A  1/1/2020    4  0.437082        NaN          NaN
13   2  A  2/1/2020    3  0.465313        NaN          NaN
14   2  A  3/1/2020   10  0.698976       17.0     3.663777
15   2  A  4/1/2020    6  0.430087       19.0     3.707103
16   2  A  5/1/2020    4  0.949536       20.0     4.832976
17   2  A  6/1/2020    1  0.904986       11.0     5.311974


text:
Q: Stop threads before close my JavaFX program I'm having a problem with closing my application because some threads are still running after I close the application.
Somebody can help me with some method to stop all Threads being executed in background before killing the main thread???
[EDITED]
With my questions about javafx I have noticed that many newer developers are facing problem managing Threads. I would like to share what I have done to simplify my life about  managing threads on javafx. I've created an AsyncTask class based on AsyncTask from Android that basically do the same of Android's in a humble but effective way. You can find more information about it on Github project

A: Override your Application Class
//System.exit(0) This will close all timers and threads inside the Jar application...
@Override
public void stop() throws Exception {
    super.stop(); //To change body of generated methods, choose Tools | Templates.
    System.exit(0);
}

A: Executors from the java.util.concurrent package are the way to go. Explicitly:
ExecutorService executorService = Executors.newCachedThreadPool(new ThreadFactory() {
     @Override
     public Thread newThread(Runnable runnable) {
          Thread thread = Executors.defaultThreadFactory().newThread(runnable);
          thread.setDaemon(true);
          return thread;
    }
});

Java 8 version with fixed ScheduledExecutorService
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1, r -> {
    Thread thread = Executors.defaultThreadFactory().newThread(r);
    thread.setDaemon(true);
    return thread;
});

A: You have three options here - the easiest is to simply create your Threads as deamons, which means that when your main program ends all deamon threads will terminate too.
Thread thread = new Thread();
thread.setDaemon(true);

Thats easiest, but the downside is that you wont get a graceful shutdown (ie the threads will stop, you wont get a chance to peform resource management etc, which may or may not be a problem for you).
The alternative is to keep a hold on the spawned threads and when your program receives the signal to close you iterate over the threads and pass in a signal of some sort to signa that they too should terminate
volatile boolean shutdown = false;

public void shutdown() {
   shutdown = true;
}

public void run() {
    while(!shutdown) {
        ... do your work here
    }
    ... perform any cleanup work here

(Note: ignores any exception handling for clarity)
The last option is to use the Executor framework in java.util.concurrent
ExecutorService executorService = Executors.newFixedThreadPool(10);
... assign/invoke tasks etc

... at some point later your program is told to shutdown
... shutdown in executor too
executorService.shutdown();
executorService.awaitTermination(10, TimeUnit.SECONDS); // wait for 10s in this case
executorService.shutdownNow();

A: Better way to fix this is add the EventHandler on Close Request:
@Override
public void start(Stage primaryStage) {
    primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
       @Override
       public void handle(WindowEvent e) {
          Platform.exit();
          System.exit(0);
       }
    });
}

A: The method Platform.exit() belongs to the JavaFX context.
When you call Platform.exit(), the method javafx.application.Application#stop() is called before the context terminates.
Put inside the stop() method everything that needs to be executed before the JavaFX context terminates.
With the System.exit(0) method, the application terminate abruptly.
This method is not secure because if at the moment you call System.exit(0) and a Job is still running, maybe executing a write in the database,
the application will not wait the Job fihish resulting in a corrupted database.
I have an application running JavaFX with SpringBoot and a thread pool. That is how I handle it.
//...
import javafx.application.Application;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

@SpringBootApplication
public class Main extends Application {

    ConfigurableApplicationContext context;

    ScheduledExecutorService scheduledExecutorService;

    @Override
    public void init() {

        this.context = SpringApplication.run(getClass());

        this.context.getAutowireCapableBeanFactory().autowireBean(this);

        this.scheduledExecutorService = Executors.newScheduledThreadPool(10);

    }

    @Override
    public void stop() throws Exception {

        super.stop();

        this.context.close();

        this.scheduledExecutorService.shutdownNow();

    }

    // ...

}


text:
Q: How to get only the current thread number? This is the example code I am using
import time
import threading
import re

def do_action():
    while True:
        x = threading.current_thread()
        print(x)
        time.sleep(60)

for _ in range(1):
    threading.Thread(target=do_action).start()

The result of Print is as follows
<Thread(Thread-1, started 10160)>

I need to get only the number of the Thread which in this case is the number 1
I tried to use
thread_number = re.findall("(\d+)", x)[0]

But error occurs when using.

A: Try:
thread_number = re.findall("(\d+)", x.name)[0]

A: The 1 in the Thread-1 output is part of the default thread name generation if you don't explicitly give your thread a name. There is no guarantee that a thread will have such a number - the main thread won't, and explicitly named threads typically won't. Also, multiple threads can have the same number, if a thread is manually given a name that matches the Thread-n pattern.
If that's the number you want, you can get it by parsing the thread's name - int(thread.name.split('-')[1]) - but it's probably not the best tool for whatever job you plan to use it for.

If you're starting a bunch of threads and they each need to use a distinct number from 1 to n for some reason, maybe work allocation or something, just pass a number to their target function:
def do_stuff(n):
    # do stuff with n

threads = [threading.Thread(target=do_stuff, args=(i,)) for i in range(1, 11)]
for thread in threads:
    thread.start()

Threads also have ident and native_id attributes, which are None for threads that haven't been started yet and integers for threads that have started. These are identifiers that are guaranteed to be distinct for threads alive at the same time - this distinctness guarantee is process-wide for ident and system-wide for native_id. However, if one thread finishes before another starts, they may be assigned the same ident or native_id.


text:
Q: ActionBar with No TitleBar How to have a fullscreen application ( no title bar ) nad have actionbar for all devices?
When i use
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
             WindowManager.LayoutParams.FLAG_FULLSCREEN);

actionbar removed.and if i change it to
this.requestWindowFeature(Window.FEATURE_ACTION_BAR | Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
             WindowManager.LayoutParams.FLAG_FULLSCREEN);

i have a fullscreen application with action bar BUT output is look like

and myLayout.xml :
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="20dip">
<TextView
    android:id="@+id/text"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />
</LinearLayout>

By the way,i'm going to use Sherlock , and wanna ActionItems ( first item in sherlock's samples ) , but with no titlebar.

A: You have to change your parent style within abs_themes.xml
Go to@

Library>res>values>abs_themes.xml

open that file and replace a sort of code to@
<style name="Sherlock.__Theme" parent="android:Theme.NoTitleBar.Fullscreen">

instead
<style name="Sherlock.__Theme" parent="android:Theme.NoTitleBar">

Updated
Attaching output screen

A: What do you mean by all devices? ActionBar is introduced from Honeycomb, and it replaces the  TitleBar. You can't have ActionBar in pre-Honeycomb devices. In case if you are just targeting Honeycomb and later devices, Window.FEATURE_NO_TITLE actually removes the ActionBar, so please don't use Window.FEATURE_NO_TITLE for your ActionBar to be visible.

A: Maybe replacing the window feature settings Window.FEATURE_NO_TITLE by Window.FEATURE_ACTION_MODE_OVERLAY setting will do the trick.

A: Put it on style.xml:
<style name="MyTheme" parent="Theme.Sherlock.Light.DarkActionbar">
    <item name="android:windowFullScreen">true</item>
    <item name="android:windowContentOverlay">@null</item>
</style>

And use it in manifest like this:
<activity android:name="MainActivity" android:theme="@style/MyTheme"></activity>


text:
Q: C - Thread stuck indefinitely while waiting I'm having trouble with implementing the "dining philosopher" problem. Basically my program is stuck in an infinite loop while threads are waiting. I'am trying to implement it in a way so that it enforces the order of eating. so Philosopher 0 would eat first and then philosopher 1 and so on. The problem arises only when I try to enforce order of eating but not when I let the eating order be random.
Here is my implementation with order of eating emphasis (the one stuck in the infinite loop):
void *philosopherThread(void *threadIndex){
    int philID = (int)threadIndex;
    int nextIndex = 0;
    printf("This is philosopher %d\n", philID);

    // waiting status
    thinking(philID);
    pthread_mutex_lock(&lock);

    // when the ith philosopher thread completes "thinking," the thread should check whether it is the ith philosopher's turn to eat or not prior to obtaining the chopsticks
    // If nextIndex==philID, the ith philosopher will grab both chopsticks and begin eating
    if(philID ==nextIndex){
        pickUpChopsticks(philID);
        eating(philID);
        putDownChopsticks(philID);
    }
    // waits on conditional variable
    while(nextIndex != philID){
        pthread_cond_wait(&var, &lock);
    }

    pickUpChopsticks(philID);
    eating(philID);
    putDownChopsticks(philID);

    // after finished eating it will  increment the value of nextIndex and release the lock to wake up all threads that are waiting on the conditional variable
    nextIndex++;
    pthread_cond_broadcast(&var);
    return(NULL);
}

For reference, here is my implementation where order of eating isn't emphasize (this one works, no infinite loop)
void *philosopherThread(void *threadIndex){
    int philID = (int)threadIndex;
    printf("This is philosopher %d\n", philID);

    // waiting status
    thinking();

    // acquire locks
    pickUpChopsticks(philID);
    eating();

    // release lock
    putDownChopsticks(philID);

    return(NULL);
}

So I need help with the first code so that it isn't stuck in an infinite loop any longer. Any help with be appreciated.

A: Three problems:

*

*Each thread has its own nextIndex. There should only be one.

*The thread is still holding a lock on the mutex when it exits.

*The "distance" between mutex_lock and cond_wait is concerning. What's what in the middle???  You're waiting for your turn to eat, so there shouldn't be anything else performed.
static int nextIndex = 0;

void *philosopherThread(void *threadIndex){
    int philID = (intptr_t)threadIndex;           // Use intptr_t on the outside too.
    printf("This is philosopher %d\n", philID);

    // We're thinking.
    thinking(philID);

    // Wait for our turn.
    pthread_mutex_lock(&lock);
    while(nextIndex != philID)
        pthread_cond_wait(&var, &lock);

    // We're eating.
    pickUpChopsticks(philID);
    eating(philID);
    putDownChopsticks(philID);

    // We're back to thinking.
    thinking(philID);

    // Make it someone else's turn, and have all of the
    // waiting philosophers check if its their turn to eat.
    nextIndex++;
    pthread_cond_broadcast(&var);
    pthread_mutex_unlock(&lock);

    return NULL;
}


text:
Q: Win Server Domain/DNS name error - A.BxCx.org - vs.- A.Bx.Cx.org I just got a request asking if I could volunteer/help out a local shelter with their network. They're having a "bunch of issues" / slowness /etc. They had a SBS 2k3 server with about 40 domain clients. A consultant told them that 2k3 and exchange was the problem. They paid to move email to Google and upgrade the Server to 2012R2.. and guess what.. the issues are still there (and apparently things are worse). Could I please help?
Sure!...
Get there, fixed a bunch of things... but this last one is a head scratcher (for me at least)
They own the BxCx.org domain (names changed to protect the innocent). Their public website is www.BxCx.org. The last computer expert set their 2k3 AD domain name to Bx.Cx.org (notice that extra period...). Thus, the server registers as  Server.Bx.Cx.org. Each device on the network is registering on the network as Device1.Bx.Cx.org.... However, I'm watching domain requests at the firewall for Device1.Cx.org, Device2.Cx.org, Printer1.Cx.org, Switch1.Cx.org, etc... Somehow, there are DNS queries to devices that keep heading out to Cx.org trying to resolve until they error out. Its quite a fun mess..
FWIW, the don't own the domain Cx.org - thats a whole other organization.
I have a few ideas to fix this .. in linux. I -think- I have some ideas about how to fix this in Windows...
Should I just register Cx.org in DNS? Try to change the AD domain name? or ?
I'm sharp enough to know when its better to ask than assume I've an answer. Hopefully, someone might've seen this before or tell me that there is an easier/different fix?
My background - I was a Linux (mostly) & Windows admin for 20 years - but switched careers around 2010-2011. I admit to not being an expert on Windows Server 2012 or 2016 - Hence the plea for help.
Thanks in advance!
Charlie

A: The problem was attributable to migration from win2k3 AD to Win2k12 AD, during the process the AD domain Bx.Cx.org carried out successfully.  host.subdomain.TLD is acceptable even in Win2k12 while configuring a DC & AD domain.
Temporary fix is to add CNAME and domain controller (name server) entries in Domain regitrar's DNS entries (like : CNAME Bx.Cx.org -> www.BxCx.org)
Permanent remedy is to change the AD domain to BxCx.org and cleaning up DNS entries to reflect the change on domain controller on site.


text:
Q: use variable value as format name I have already defined fmtA and fmtB.
fmtA
1->1
2->2
fmtB
1->2
2->4
Input data:
x format y
1 fmtA
1 fmtB
2 fmtA
3 fmtA

I try to format column x to y based on column format.
Is it possible?

A: Yes, you can do this using the putn function, e.g.:
proc format;
value fmtA
1 = 1
2 = 2
;
value fmtB
1 = 2
2 = 4
;
run;

data have;
input x format $;
cards;
1 fmtA
1 fmtB
2 fmtA
3 fmtA
;
run;

data want;
set have;
y = putn(x,format);
run;

A: The PUTN and PUTC functions allow you to apply a format at DATA step run time. Try:
y=putn(x, cats(format,'.')) ;


text:
Q: query to find no of empty columns from a table along with the name of the column I am getting an error when i am trying to use define command otherwise the code works fine please let me know how to use this code using define command.                       Define b_table='&Please enter the table name';
                    declare
                    v_count number;
                    cursor c2 is select Column_name
                    from all_tab_columns
                     where table_name= '&b_table';

                    begin
                    for r1 in c2 loop
                    dbms_output.put_line(r1.column_name);
                    select count(r1.column_name) into v_count
                    from HR.'&b_table';
                    if v_count =0 then
                    dbms_output.put_line(v_count);
                    end if;
                    end loop;
                    end;
               old   5:  where table_name= '&b_table';
new   5:  where table_name= ' enter the table name';
old  11: from HR.'&b_table';
new  11: from HR.' enter the table name';
from HR.' enter the table name';
        *
ERROR at line 11:
ORA-06550: line 11, column 9:
PL/SQL: ORA-00903: invalid table name
ORA-06550: line 10, column 1:
PL/SQL: SQL Statement ignored

A: try this
    SET serveroutput ON;
    DECLARE
      v_count      NUMBER;
      v_table_name VARCHAR2(200);
      CURSOR c2(v_table VARCHAR2)
      IS
        SELECT Column_name FROM all_tab_columns WHERE table_name= v_table;
    BEGIN
      v_table_name := :table_name;
      FOR r1 IN c2(v_table_name)
      LOOP
        dbms_output.put_line(r1.column_name);
        EXECUTE immediate('SELECT COUNT('||r1.column_name||')  FROM HR'||'.'||v_table_name) INTO v_count;
        IF v_count =0 THEN
          dbms_output.put_line(v_count);
        END IF;
      END LOOP;
    END;


text:
Q: How do i manage certificates for xCode? I'm having trouble when trying to build a unity build for ios in xCode.
So, my friend made an account and add me to the proyect. I'm in charge of making the build and testing it. But i'm getting errors about certificates. He built every certificates and send them back to me, I install them but i keep getting errors like:

*

*Provisioning profile " Proyect Name" doesn't include signing certificate "apple development: "My friend Certificate".

*No signing certificate "iOS Development" found. Here if i try to "Manage certificates" it says: No account for team "team number". But in my account information it says i'm part of said team.

I've try a lot of options from the internet but none of those solutions worked for me. Maybe we are doing something wrong with the team configuration or something.
Thanks

A: If your friend owns an individual developer account, his certificate won't work on your mac, unless his account logged in on your mac.
He can add you into the project for tester..etc. However, he can't grant you the same license.
If you only need to test and build, you can register your own apple id as personal developer. With this free developer license, you can at least build and test the app first. The build will be expired within 7 days in current policy, which means that you have to deploy the app into your device again when it expires.
When you are using different developer account for build, you have to change the certificate too. If someone already submitted the app with your existed package name, you will have to change the product name and package name for your testing too.


text:
Q: How to use and when is good use memmove in C? I have two doubts about the use of memmove():

*

*When is it preferable to use this function instead of using another function (i.e. a created own function)? I'm not sure I have understood properly.

*The signature of the function is void *memmove(void *dest, const void *src, size_t n). If I have a simple array arr[N], how can I put it into the called function? arr[N] or &arr[N]? The difference is if the array is declared with an initial size or like a pointer? I have this doubt because I saw many examples where is used both.

I hope I explained my doubts in a good way.
edit: I have to delete an element from the array, and then I want to shift the following elements of the deleted one on the left.

A: memmove is like memcpy except the destination and source array can overlap.
With memcpy you promise that the regions are not overlapping which allows the implementation to perform some additional optimizations. So memcpy can be faster than memmove.
The memmove function takes a void * destination argument and a const void * source argument. It means you can call the function with destination and source argument of array type because they will be converted to pointer types. And as you can assign any non-qualified object pointer types to void * or const void *, you won't need any cast when calling the function.
char src[1024] = {0};
char dst[1024];

memmove(dst, src, sizeof dst);
/* src and dst don't overlap you should choose memcpy instead */
memcpy(dst, src, sizeof dst);

Now it's usually better to use memcpy or memmove than to code your own function. In glibc for example, depending on the MCU instruction set and the size to copy, memcpy can be replaced by the compiler with some fast inline assembly versions of memcpy.

A: *

*memmove may be faster but it probably will never be slower than your own function for copying data around (it's usually coded in carefully crafted assembly to move stuff around in the most efficient way possible on the current architecture);

*it depends on what you want to do with that array... if you want to copy its content to another array arr will suffice (and, as the length parameter, you should do sizeof(*arr)*N where N is the number of elements to copy).

By the way, if source and destination and the copy are nonoverlapping memcpy may be faster.

I want to delete an element from the array and shift left the element of the same array.

int arr[N];
/* ... */
/* Let's say you want to remove the element i (error checking on i omitted) */
memmove(arr+i, arr+i+1, (N-i-1)*sizeof(*arr));
/* or, if you prefer array indexing over pointer arithmetics: */
memmove(&arr[i], &arr[i+1], (N-i-1)*sizeof(*arr));

(sizeof(*arr) means "get the size of an element of the array")

A:
When is preferable use this function instead of use another function (i.e. a created own function)

It's faster than a "created own function".

the signature of the function is void *memmove(void *dest, const void *src, size_t n). If I have a simple array arr[N], how can I put it into the called function? arr[N] or &arr[N]

Just arr?