Q: How to use std::transform with a lambda function that takes additional parameters In C++ 11 (or higher) can I use std::transform and a lambda function to transform a vector that also takes other parameters?  For example, how do I pass param to the lambda function below?
std::vector<double> a{ 10.0, 11.0, 12.0 };
std::vector<double> b{ 20.0, 30.0, 40.0 };
std::vector<double> c;
double param = 1.5;
//The desired function is c = (a-b)/param
transform(a.begin(), a.end(), b.begin(), std::back_inserter(c),
          [](double x1, double x2) {return(x1 - x2)/param; });

std::transform wants a function with two input parameters. Do I need to use std::bind?

A: You just need to capture param in your capture list:
transform(a.begin(), a.end(), b.begin(), std::back_inserter(c),
          [param](double x1, double x2) {return(x1 - x2)/param; });

Capturing it by reference also works - and would be correct if param was a big class. But for a double param is fine.

A: This is what the lambda capture is for.  You need to specify & or = or param in the capture block ([]) of the lambda.
std::vector<double> a{ 10.0, 11.0, 12.0 };
std::vector<double> b{ 20.0, 30.0, 40.0 };
std::vector<double> c;
double param = 1.5;
//The desired function is c = (a-b)/param
transform(a.begin(), a.end(), b.begin(), std::back_inserter(c),
          [=](double x1, double x2) {return(x1 - x2)/param; });
//         ^ capture all external variables used in the lambda by value

In the above code we just capture by value since copying a double and having a reference is pretty much the same thing performance wise and we don't need reference semantics.


Q: How can I add an intranet-only endpoint to my IIS hosted WCF service? I have a WCF service hosted in IIS that uses basicHttpBindings. I'm adding a new method to the ServiceContract that will be called from a console app to perform an administrative task. I got to thinking, well wouldn't it be nice if I gave this method its own endpoint. Then I thought and what if that endpoint wasn't even publicly accessible. It would be much better if only a computer on our LAN could access it. It might even be cool if only an AD administrator was authorized to use it, but I don't want to get too elaborate. So I added a new ServiceContract interface that includes my new method. How can I restrict it to LAN access only? Do I need a NetTcpBinding? Networking is not my strong suit and I'm a little confused, conceptually, on how a TCP endpoint could be hosted from IIS. Additionally, when hosting multiple endpoints, does each have to have its own address or can they be at the same address?

A: I am gonna answer some of your questions

*

*there is no binding that would limit access to LAN network though you can use windows authentication to allow users from your network to use the service

*the nettcpbinding is only a tcp connection and you can host it on IIS pof course
check this link for more information hosting nettcp on IIS

*you can have one base address for multiple endpoints , example:
https://localhost:8080/calculator.svc
net.tccp://localhost:8080/calculator.svc


Q: A Quickselect C Algorithm faster than C Qsort I have tried to implement a C QuickSelect algorithm as described in this post (3 way quicksort (C implementation)).
However, all I get are performances 5 to 10 times less than the default qsort (even with an initial shuffling).
I tried to dig into the original qsort source code as provide here (https://github.com/lattera/glibc/blob/master/stdlib/qsort.c), but it's too complex.
Does anybody have a simpler, and better algorithm?
Any idea is welcomed.
Thanks,
NB: my original problem is to try to get the Kth smallest values of an array to the first Kth indices. So I planned to call quickselect K times
EDIT 1: Here is the Cython Code as copied and adapted from the link above
cdef void qswap(void* a, void* b, const size_t size) nogil:
    cdef char temp[size]# C99, use malloc otherwise
    #char serves as the type for "generic" byte arrays

    memcpy(temp, b,    size)
    memcpy(b,    a,    size)
    memcpy(a,    temp, size)

cdef void qshuffle(void* base, size_t num, size_t size) nogil: #implementation of Fisher
    cdef int i, j, tmp# create local variables to hold values for shuffle

    for i in range(num - 1, 0, -1): # for loop to shuffle
        j = c_rand() % (i + 1)#randomise j for shuffle with Fisher Yates
        qswap(base + i*size, base + j*size, size)

cdef void partition3(void* base,
                      size_t *low, size_t *high, size_t size,
                      QComparator compar) nogil:
    # Modified median-of-three and pivot selection.
    cdef void *ptr = base
    cdef size_t lt = low[0]
    cdef size_t gt = high[0] # lt is the pivot
    cdef size_t i = lt + 1# (+1 !) we don't compare pivot with itself
    cdef int c = 0

    while (i <= gt):
        c = compar(ptr + i * size, ptr + lt * size)
        if (c < 0):# base[i] < base[lt] => swap(i++,lt++)
            qswap(ptr + lt * size, ptr + i * size, size)
            i += 1
            lt += 1
        elif (c > 0):#base[i] > base[gt] => swap(i, gt--)
            qswap(ptr + i * size, ptr + gt* size, size)
            gt -= 1
        else:#base[i] == base[gt]
            i += 1
    #base := [<<<<<lt=====gt>>>>>>]
    low[0] = lt
    high[0] = gt

cdef void qselectk3(void* base, size_t lo, size_t hi,
   size_t size, size_t k,
   QComparator compar) nogil:
    cdef size_t low = lo
    cdef size_t high = hi

    partition3(base, &low, &high,  size, compar)

    if ((k - 1) < low): #k lies in the less-than-pivot partition
        high = low - 1
        low = lo
    elif ((k - 1) >= low and  (k - 1) <= high): #k lies in the equals-to-pivot partition
        qswap(base, base + size*low, size)
        return
    else: # k > high => k lies in the greater-than-pivot partition
        low = high + 1
        high = hi
    qselectk3(base, low, high, size, k, compar)

"""
 A selection algorithm to find the nth smallest elements in an unordered list.
 these elements ARE placed at the nth positions of the input array
"""
cdef void qselect(void* base, size_t num, size_t size,
                              size_t n,
                              QComparator compar) nogil:
    cdef int k
    qshuffle(base, num, size)
    for k in range(n):
        qselectk3(base + size*k, 0, num - k - 1, size, 1, compar)

I use python timeit to get the performance of both method pyselect(with N=50) and pysort.
Like this
def testPySelect():
    A = np.random.randint(16, size=(10000), dtype=np.int32)
    pyselect(A, 50)
timeit.timeit(testPySelect, number=1)

def testPySort():
    A = np.random.randint(16, size=(10000), dtype=np.int32)
    pysort(A)
timeit.timeit(testPySort, number=1)

A: The answer by @chqrlie is the good and final answer, yet to complete the post, I am posting the Cython version along with the benchmarking results.
In short, the proposed solution is 2 times faster than qsort on long vectors!

    cdef void qswap2(void *aptr, void *bptr, size_t size) nogil:
        cdef uint8_t* ac = <uint8_t*>aptr
        cdef uint8_t* bc = <uint8_t*>bptr
        cdef uint8_t t
        while (size > 0): t = ac[0]; ac[0] = bc[0]; bc[0] = t; ac += 1; bc += 1; size -= 1

    cdef struct qselect2_stack:
        uint8_t *base
        uint8_t *last

    cdef void qselect2(void *base, size_t nmemb, size_t size,
                      size_t k, QComparator compar) nogil:
        cdef qselect2_stack stack[64]
        cdef qselect2_stack *sp = &stack[0]

        cdef uint8_t *lb
        cdef uint8_t*ub
        cdef uint8_t *p
        cdef uint8_t *i
        cdef uint8_t *j
        cdef uint8_t *top

        if (nmemb < 2 or size <= 0):
            return

        top = <uint8_t *>base
        if(k < nmemb):
            top += k*size
        else:
            top += nmemb*size

        sp.base = <uint8_t *>base
        sp.last = <uint8_t *>base + (nmemb - 1) * size
        sp += 1

        cdef size_t offset

        while (sp > stack):
            sp -= 1
            lb = sp.base
            ub = sp.last

            while (lb < ub and lb < top):
                #select middle element as pivot and exchange with 1st element
                offset = (ub - lb) >> 1
                p = lb + offset - offset % size
                qswap2(lb, p, size)

                #partition into two segments
                i = lb + size
                j = ub
                while 1:
                    while (i < j and compar(lb, i) > 0):
                        i += size
                    while (j >= i and compar(j, lb) > 0):
                        j -= size
                    if (i >= j):
                        break
                    qswap2(i, j, size)
                    i += size
                    j -= size

                # move pivot where it belongs
                qswap2(lb, j, size)

                # keep processing smallest segment, and stack largest
                if (j - lb <= ub - j):
                    sp.base = j + size
                    sp.last = ub
                    sp += 1
                    ub = j - size
                else:
                    sp.base = lb
                    sp.last = j - size
                    sp += 1
                    lb = j + size

    cdef int int_comp(void* a, void* b) nogil:
        cdef int ai = (<int*>a)[0]
        cdef int bi = (<int*>b)[0]
        return (ai > bi ) - (ai < bi)

    def pyselect2(numpy.ndarray[int, ndim=1, mode="c"] na, int n):
        cdef int* a = <int*>&na[0]
        qselect2(a, len(na), sizeof(int), n, int_comp)

Here are the benchmark results (1,000 tests):

#of elements   K      #qsort (s)                     #qselect2 (s)
1,000          50     0.1261                         0.0895
1,000          100    0.1261                         0.0910

10,000         50     0.8113                         0.4157
10,000         100    0.8113                         0.4367
10,000         1,000  0.8113                         0.4746

100,000        100    7.5428                         3.8259
100,000        1,000  7,5428                         3.8325
100,000        10,000 7,5428                         4.5727

For those who are curious, this piece of code is a jewel in the field of surface reconstruction using neural networks.
Thanks again to @chqrlie, your code is unique on The Web.

A: Here is a quick implementation for your purpose: qsort_select is a simple implementation of qsort with automatic pruning of unnecessary ranges.
Without && lb < top, it behaves like the regular qsort except for pathological cases where more advanced versions have better heuristics. This extra test prevents complete sorting of ranges that are outside the target 0 .. (k-1). The function selects the k smallest values and sorts them, the rest of the array has the remaining values in an undefinite order.
#include <stdio.h>
#include <stdint.h>

static void exchange_bytes(uint8_t *ac, uint8_t *bc, size_t size) {
    while (size-- > 0) { uint8_t t = *ac; *ac++ = *bc; *bc++ = t; }
}

/* select and sort the k smallest elements from an array */
void qsort_select(void *base, size_t nmemb, size_t size,
                  int (*compar)(const void *a, const void *b), size_t k)
{
    struct { uint8_t *base, *last; } stack[64], *sp = stack;
    uint8_t *lb, *ub, *p, *i, *j, *top;

    if (nmemb < 2 || size <= 0)
        return;

    top = (uint8_t *)base + (k < nmemb ? k : nmemb) * size;
    sp->base = (uint8_t *)base;
    sp->last = (uint8_t *)base + (nmemb - 1) * size;
    sp++;
    while (sp > stack) {
        --sp;
        lb = sp->base;
        ub = sp->last;
        while (lb < ub && lb < top) {
            /* select middle element as pivot and exchange with 1st element */
            size_t offset = (ub - lb) >> 1;
            p = lb + offset - offset % size;
            exchange_bytes(lb, p, size);

            /* partition into two segments */
            for (i = lb + size, j = ub;; i += size, j -= size) {
                while (i < j && compar(lb, i) > 0)
                    i += size;
                while (j >= i && compar(j, lb) > 0)
                    j -= size;
                if (i >= j)
                    break;
                exchange_bytes(i, j, size);
            }
            /* move pivot where it belongs */
            exchange_bytes(lb, j, size);

            /* keep processing smallest segment, and stack largest */
            if (j - lb <= ub - j) {
                sp->base = j + size;
                sp->last = ub;
                sp++;
                ub = j - size;
            } else {
                sp->base = lb;
                sp->last = j - size;
                sp++;
                lb = j + size;
            }
        }
    }
}

int int_cmp(const void *a, const void *b) {
    int aa = *(const int *)a;
    int bb = *(const int *)b;
    return (aa > bb) - (aa < bb);
}

#define ARRAY_SIZE  50000

int array[ARRAY_SIZE];

int main(void) {
    int i;
    for (i = 0; i < ARRAY_SIZE; i++) {
        array[i] = ARRAY_SIZE - i;
    }
    qsort_select(array, ARRAY_SIZE, sizeof(*array), int_cmp, 50);
    for (i = 0; i < 50; i++) {
        printf("%d%c", array[i], i + 1 == 50 ? '\n' : ',');
    }
    return 0;
}


Q: What is eating up my disk space? I have very recently installed Ubuntu 15.10. I have been watching the available amount of memory over two days, and i noticed that the free memory goes on decreasing at a slow rate. Initially the used memory was 5GB, Then it went on increasing to 6 to 6.5 and now it stands around 6.8. I haven't installed anything significant over this period (except some small packages worth a few MBs) .My home folder is just few 100kbs. What is eating up my disk space? How can find out if something is going on?

A: The indicated amount seems to be .deb cache in majority. Issue this command:
sudo apt-get clean

and after that check again the disk usage.

A: You can find out how much space sub-directories occupy using the following command:
sudo du -hxd 1 YOUR_PATH 2>/dev/null | sort -hr

What it does:

*

*sudo: run the du command as root - only needed/recommended if you want to list stuff outside your own home directory.

*du: disk usage analyzing tool. Arguments:

*

*-h: use human readable numeric output (i.e. 2048 bytes = 2K)

*-x: stay on the same file system, do not list directories which are just mounted there

*-d 1: display recursion depth is set to 1, that means it will only print the given directory and the direct subdirectories.

*YOUR_PATH: The path which should be analyzed. Change this to whatever path you want.

*2>/dev/null: we do not want error output (e.g. from when it tries to get the size of virtual files), so we pipe that to the digital nirvana a.k.a. /dev/null.

*|: use the output of the previous command as input for the next command

*sort: sort the input. Arguments:

*

*-h: recognize numbers like 2K and sort them according to their real value

*-r: reversed order: print the largest numbers first

Example for my file system root /:
$ sudo du -hxd 1 / 2>/dev/null | sort -hr
5,7G    /
4,0G    /usr
1,3G    /var
358M    /lib
49M     /opt
15M     /etc
13M     /sbin
13M     /bin
840K    /tmp
32K     /root
16K     /lost+found
8,0K    /media
4,0K    /srv
4,0K    /mnt
4,0K    /lib64
4,0K    /cdrom

Note that the given directory's total size is also included, not only the subdirectories.


Q: Get values with no repeated data I have a query like this:
SELECT
      P.LegacyKey
      ,D.DesignNumber
      FROM tbl1 AS [SO]
 GROUP BY D.DesignNumber,P.LegacyKey
 ORDER BY LegacyKey

it returning values like:
+-----------+--------------+
| LegacyKey | DesignNumber |
+-----------+--------------+
|     17134 |            1 |
|     17134 |            2 |
|     18017 |            7 |
+-----------+--------------+

That I want to do is to find duplicate LegacyKeys and get only values who legacyKey is exist one time, so I use HAVING COUNT:
SELECT
      P.LegacyKey
      ,D.DesignNumber
      , COUNT([P].[LegacyKey])
      FROM tbl1 AS [SO]
 GROUP BY D.DesignNumber,P.LegacyKey
 HAVING COUNT([P].[LegacyKey])  = 1
 ORDER BY LegacyKey

But this is returning bad data, because it is returning LegacyKey = 17134 again and desire result is to get values where LegacyKey exists one time.
So desire result should be only
  18017 |            7

What am I doing wrong?

A: You can simply do:
SELECT P.LegacyKey, MAX(D.DesignNumber) as DesignNumber
FROM tbl1 AS [SO]
GROUP BY P.LegacyKey
HAVING COUNT(DISTINCT D.DesignNumber) = 1;
ORDER BY LegacyKey;

No subquery is necessary.

A: You need something like this:
select t2.LegacyKey, t2.DesignNumber
from
(
    select t.LegacyKey
    from tbl1 t
    group by t.LegacyKey
    having count(t.LegacyKey ) = 1
)x
join tbl1 t2 on x.LegacyKey = t2.LegacyKey

or
select t2.LegacyKey, t2.DesignNumber
from tbl1 t2
where t2.LegacyKey in
(
    select t.LegacyKey
    from tbl1 t
    group by t.LegacyKey
    having count(t.LegacyKey ) = 1
)

A: You could try this
NB - This is untested
SELECT  *
FROM    (
            SELECT
                  P.LegacyKey AS LegacyKey,
                  D.DesignNumber AS DesignNumber,
                  COUNT([P].[LegacyKey]) AS cnt
             FROM tbl1 AS [SO]
             GROUP BY D.DesignNumber,P.LegacyKey
             HAVING COUNT([P].[LegacyKey])  = 1
        ) a
WHERE   COUNT() OVER (PARTITION BY LegacyKey) = 1


Q: @IBDesignable doesn't work in "old" project I have UIView subclass, for example, this:
@IBDesignable
class GradientView: UIView {

    @IBInspectable var firstColor: UIColor = UIColor.red
    @IBInspectable var secondColor: UIColor = UIColor.green

    @IBInspectable var vertical: Bool = true

    override func awakeFromNib() {
        super.awakeFromNib()

        applyGradient()
    }

    func applyGradient() {
        let colors = [firstColor.cgColor, secondColor.cgColor]

        let layer = CAGradientLayer()
        layer.colors = colors
        layer.frame = self.bounds
        layer.startPoint = CGPoint(x: 0, y: 0)
        layer.endPoint = vertical ? CGPoint(x: 0, y: 1) : CGPoint(x: 1, y: 0)

        self.layer.addSublayer(layer)
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        applyGradient()
    }
}

It successfully renders in Interface Builder for a new project, but it doesn't work for my "old" project.
Does anyone know why it happens?


Q: How do I refer to the people living in the particular city? Is it random always? Where do demonyms come from? At times they take -ite, some times -an, -er and this one is jaw-dropping '-siders!'

A person living in New York is a New Yorker (-er)   A person living in Delhi is Delhiite (-ite)  A person living in Sydney is Sydneysider (-sider -OMG! Really?)   A person living in Las Vegas is Las Vegan (-an)

There are innumerable cities across the world and remembering a demonym for each of them does not seem practical.
I don't get demonyms without searching them on the Internet (and trust me, even after searching I fail to get them for some cities' residents!).
This becomes further difficult when the city name is long - say St. Louis, Amsterdam, Rio de Janeiro (Cariocas -full marks who knew this!) and many more.
Is there any way we can assume/know the demonym of the city by looking at its spelling?

A: Is there a hard and fast rule? Sadly, no. But there is a rule of thumb--which means it works, except when it doesn't.
First: if the city is outside of the United States, US English usually (but not always) uses the naming convention of the native country. So "Liverpudlian" and "Muenchner" don't follow these rules; you need to learn that country's rules.
Within the United States, look at the sound (not the spelling!) of the last syllable of the city's name.
Does it end in a vowel sound? Add -n or -an.

*

*Atlantan

*Cincinattian

*Kenoshan

*Pennsylvanian

Does it end in a hard d or k? Add -er.

*

*New Yorker

*Oaklander

*Portlander

*Salt Laker

Does it end in an -l, or -r sound? Consider adding -ite.

*

*Seattleite

*New Hampshirite

Does it end in an -s sound preceded by a schwa? Replace the s with an n.

*

*Kansan

*Texan

For all other consonants, the most common rule is to add an -ian

*

*Oregonian

*Bostonian

*Knoxvillian

As always with English, there are then a ton of exceptions that you just have to learn.


Q: Passing object messages in Azure Queue Storage I'm trying to find a way to pass objects to the Azure Queue. I couldn't find a way to do this.
As I've seen I can pass string or byte array, which is not very comfortable for passing objects.
Is there anyway to pass custom objects to the Queue?
Thanks!

A: You can use the following classes as example:
 [Serializable]
    public abstract class BaseMessage
    {
        public byte[] ToBinary()
        {
            BinaryFormatter bf = new BinaryFormatter();
            byte[] output = null;
            using (MemoryStream ms = new MemoryStream())
            {
                ms.Position = 0;
                bf.Serialize(ms, this);
                output = ms.GetBuffer();
            }
            return output;
        }

        public static T FromMessage<T>(CloudQueueMessage m)
        {
            byte[] buffer = m.AsBytes;
            T returnValue = default(T);
            using (MemoryStream ms = new MemoryStream(buffer))
            {
                ms.Position = 0;
                BinaryFormatter bf = new BinaryFormatter();
                returnValue = (T)bf.Deserialize(ms);
            }
            return returnValue;
        }
    }

Then a StdQueue (a Queue that is strongly typed):
   public class StdQueue<T> where T : BaseMessage, new()
    {
        protected CloudQueue queue;

        public StdQueue(CloudQueue queue)
        {
            this.queue = queue;
        }

        public void AddMessage(T message)
        {
            CloudQueueMessage msg =
            new CloudQueueMessage(message.ToBinary());
            queue.AddMessage(msg);
        }

        public void DeleteMessage(CloudQueueMessage msg)
        {
            queue.DeleteMessage(msg);
        }

        public CloudQueueMessage GetMessage()
        {
            return queue.GetMessage(TimeSpan.FromSeconds(120));
        }
    }

Then, all you have to do is to inherit the BaseMessage:
[Serializable]
public class ParseTaskMessage : BaseMessage
{
    public Guid TaskId { get; set; }

    public string BlobReferenceString { get; set; }

    public DateTime TimeRequested { get; set; }
}

And make a queue that works with that message:
CloudStorageAccount acc;
            if (!CloudStorageAccount.TryParse(connectionString, out acc))
            {
                throw new ArgumentOutOfRangeException("connectionString", "Invalid connection string was introduced!");
            }
            CloudQueueClient clnt = acc.CreateCloudQueueClient();
            CloudQueue queue = clnt.GetQueueReference(processQueue);
            queue.CreateIfNotExist();
            this._queue = new StdQueue<ParseTaskMessage>(queue);

Hope this helps!

A: Extension method that uses Newtonsoft.Json and async
    public static async Task AddMessageAsJsonAsync<T>(this CloudQueue cloudQueue, T objectToAdd)
    {
        var messageAsJson = JsonConvert.SerializeObject(objectToAdd);
        var cloudQueueMessage = new CloudQueueMessage(messageAsJson);
        await cloudQueue.AddMessageAsync(cloudQueueMessage);
    }

A: I like this generalization approach but I don't like having to put Serialize attribute on all the classes I might want to put in a message and derived them from a base (I might already have a base class too) so I used...
using System;
using System.Text;
using Microsoft.WindowsAzure.Storage.Queue;
using Newtonsoft.Json;

namespace Example.Queue
{
    public static class CloudQueueMessageExtensions
    {
        public static CloudQueueMessage Serialize(Object o)
        {
            var stringBuilder = new StringBuilder();
            stringBuilder.Append(o.GetType().FullName);
            stringBuilder.Append(':');
            stringBuilder.Append(JsonConvert.SerializeObject(o));
            return new CloudQueueMessage(stringBuilder.ToString());
        }

        public static T Deserialize<T>(this CloudQueueMessage m)
        {
            int indexOf = m.AsString.IndexOf(':');

            if (indexOf <= 0)
                throw new Exception(string.Format("Cannot deserialize into object of type {0}",
                    typeof (T).FullName));

            string typeName = m.AsString.Substring(0, indexOf);
            string json = m.AsString.Substring(indexOf + 1);

            if (typeName != typeof (T).FullName)
            {
                throw new Exception(string.Format("Cannot deserialize object of type {0} into one of type {1}",
                    typeName,
                    typeof (T).FullName));
            }

            return JsonConvert.DeserializeObject<T>(json);
        }
    }
}

e.g.
var myobject = new MyObject();
_queue.AddMessage( CloudQueueMessageExtensions.Serialize(myobject));

var myobject = _queue.GetMessage().Deserialize<MyObject>();

A: In case the storage queue is used with WebJob or Azure function (quite common scenario) then the current Azure SDK allows to use POCO object directly. See examples here:

*

*https://learn.microsoft.com/en-us/sandbox/functions-recipes/queue-storage

*https://github.com/Azure/azure-webjobs-sdk/wiki/Queues#trigger
Note: The SDK will automatically use Newtonsoft.Json for serialization/deserialization under the hood.

A: I liked @Akodo_Shado's approach to serialize with Newtonsoft.Json.  I updated it for Azure.Storage.Queues and also added a "Retrieve and Delete" method that deserializes the object from the queue.
public static class CloudQueueExtensions
{
    public static async Task AddMessageAsJsonAsync<T>(this QueueClient queueClient, T objectToAdd) where T : class
    {
        string messageAsJson = JsonConvert.SerializeObject(objectToAdd);
        BinaryData cloudQueueMessage = new BinaryData(messageAsJson);
        await queueClient.SendMessageAsync(cloudQueueMessage);
    }

    public static async Task<T> RetreiveAndDeleteMessageAsObjectAsync<T>(this QueueClient queueClient) where T : class
    {

        QueueMessage[] retrievedMessage = await queueClient.ReceiveMessagesAsync(1);
        if (retrievedMessage.Length == 0) return null;
        string theMessage = retrievedMessage[0].MessageText;
        T instanceOfT = JsonConvert.DeserializeObject<T>(theMessage);
        await queueClient.DeleteMessageAsync(retrievedMessage[0].MessageId, retrievedMessage[0].PopReceipt);

        return instanceOfT;
    }
}

The RetreiveAndDeleteMessageAsObjectAsync is designed to process 1 message at time, but you could obviously rewrite to deserialize the full array of messages and return a ICollection<T> or similar.

A: That is not right way to do it. queues are not ment for storing object. you need to put object in blob or table (serialized).
I believe queue messgae body has 64kb size limit with sdk1.5 and 8kb wih lower versions.
Messgae body is ment to transfer crutial data for workera that pick it up only.


Q: Help needed renaming custom post I really have very little Wordpress knowledge and I need help with the following:
I have a theme which uses a custom post called 'services'. I needed another custom post created which worked exactly the same as services so I went through all the code and copied and pasted wherever I found references to services and changed it to "signage". This worked ok, however on the WP admin screen, "signage" is called "posts" as is the original "posts", and I cant work out how to change the name to signage. I have been able to change the original "posts" name but not the custom post.

A: It could be the 'name' in the labels array of the register post type. It would be much easier to help if you can show us your code.


Q: How to add FTP site in IIS 7 in Windows Vista Home premium edition How to add the FTP server in IIS 7 using Windows vista Home Premium Edition?

A: Please check if FTP 7.5 can be used on your Windows Vista machine, http://www.iis.net/expand/FTP
If not, FileZilla is a free alternative, http://filezilla-project.org/download.php?type=server


Q: Unable to install any program Total newbie here, I installed Kubuntu about three days ago and have been trying to install some programmes, to date no success. No matter what I try to install I get the same error. I would be very grateful if someone could explain what is happening and how to resolve it, or point me to a document that can help.
Thanks in advance for your help,
Noel
sudo apt-get install muon
[sudo] password for nleric:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 muon : Depends: apt-xapian-index but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

A: the package "apt-xapian-index" is in the universe repository since Ubuntu 16.04 Xenial (see http://packages.ubuntu.com/xenial/apt-xapian-index). Before Ubuntu 16.04 Xenial the package "apt-xapian-index" was in the main repository, so it was always available, even if the user had the "universe" repository disabled. It's not the case anymore.
To confirm what is above just run the following:
apt-cache policy apt-xapian-index

If the result is not available it's because apt-get can't find it in the present repositories present in the file /etc/apt/sources.list.
My guess is that you have removed/disabled the universe repository from your APT /etc/apt/sources.list file. Make sure to add "universe" at the end of the the lines starting with "deb" in that file. Example, change the following line to have the universe repository enabled, in the file /etc/apt/sources.list file:
deb http://archive.ubuntu.com/ubuntu/ xenial main

To something like (add the last word in the line):
deb http://archive.ubuntu.com/ubuntu/ xenial main universe

Then update apt-get repositories:
sudo apt-get update

Apt-get will update its sources of available packages, now with the universe repository enabled. Then try to fix the problem:
sudo apt-get install -f


Q: NLog not creating a log file inside AWS ec2 Linux I have a .net core application in AWS ec2 linux and it does NOT create a log file. The application on AWS ec2 linux is published with Deployment Mode: Self-contained and Target Runtime: linux-x64.
I tried it on windows and it does create a log file but somehow it's not working in AWS ec2 linux.
Heres what I did.

*

*Open ubuntu machine terminal (CLI) and Go to the project directory

*Provide execute permissions: chmod 777 ./appname

*Execute application

*./appname
Note: It displays the Hello World.
public static void Main(string[] args)
    {
        try
        {
            using (var logContext = new LogContextHelper(null, "MBP", "MBP",
        new JObject() {
                    { "ASD", "asd" },
                    { "ZXC", "asd" },
                    { "QWE", "asd" },
                    { "POI", "" }
        }, setAsContextLog: true))
            { }
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: {0}", e);
        }
        //sample s = new sample("consuna") { objectinitial = "objuna"};

            Console.WriteLine("Hello World!");
        Console.ReadLine();
    }
}

    Here is the NLog.config

    <?xml version="1.0" encoding="utf-8" ?>
        <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd                NLog.xsd"
          autoReload="true"
          throwExceptions="false"
          internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">

        <variable name="myvar" value="myvalue"/>

        <targets>
        <target xsi:type="File" name="fileMBP" fileName="/home/ec2-user/mbpTESTING.log"`enter code here`
              layout="Logger="MBP API",
        TimeStamp="${event-context:item=datetime}",
        TimeStampMel="${event-context:item=datetimeMel}",
        Message="${message}",
        Context="${basedir}",
        Command="${event-context:item=command}",
        ${event-context:item=properties}"
            archiveFileName="/home/ec2-user/MBP.{#}.txt"
            archiveEvery="Day"
            archiveNumbering="DateAndSequence"
            maxArchiveFiles="7"
            concurrentWrites="true"
            keepFileOpen="false"/>

       </targets>

       <rules>
        <logger name="MBP" minlevel="Trace" writeTo="fileMBP"/>
       </rules>
       </nlog>

        I expect that it will create a log file with logs on it just like on windows.


Q: EditText length with "exceptions" I have an EditText and I'd like to set maxLength to four numbers (in range -9999 to 9999). Problem is that if I setandroid:maxLength="4" in xml I can write there e.q "9999" but it doesn't accept "-9999" because of length (5 char). Is there any opportunity how to solve it (programatically or anyhow)
Thanks


Q: Understanding hashCode(), equals() and toString() in Java I am beginner in Java and although I have a look at several questions and answers in SO, I am not sure if I completely understand the usage of hashCode(), equals() and toString() in Java. I encountered the following code in a project and want to understand the following issues:
1. Is it meaningful to define these methods and call via super like return super.hashCode()?
2. Where should we defines these three methods? For each entity? Or any other place in Java?
3. Could you please explain me the philosophy of defining these 3 (or maybe similar ones that I have not seen  before) in Java?
@Entity
@SequenceGenerator(name = "product_gen", sequenceName = "product_id_seq")
@Table
@Getter
@Setter
@ToString(callSuper = true)
@NoArgsConstructor
public class Product extends BaseEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "product_gen")
    private long id;

    @Override
    public int hashCode() {
        return super.hashCode();
    }

    @Override
    public boolean equals(Object other) {
        return super.equals(other);
    }
}

A: *

*toString() method returns the String representation of an Object. The default implementation of toString() for an object returns the HashCode value of the Object. We'll come to what HashCode is.
Overriding the toString() is straightforward and helps us print the content of the Object. @ToString annotation from Lombok does that for us. It Prints the class name and each field in the class with its value.
The @ToString annotation also takes in configuration keys for various behaviours. Read here. callSuper just denotes that an extended class needs to call the toString() from its parent.
hashCode() for an object returns an integer value, generated by a hashing algorithm. This can be used to identify whether two objects have similar Hash values which eventually help identifying whether two variables are pointing to the same instance of the Object. If two objects are equal from the .equals() method, they must share the same HashCode

*They are supposed to be defined on the entity, if at all you need to override them.

*Each of the three have their own purposes. equals() and hashCode() are majorly used to identify whether two objects are the same/equal. Whereas, toString() is used to Serialise the object to make it more readable in logs.
From Effective Java:

You must override hashCode() in every class that overrides equals().
Failure to do so will result in a violation of the general contract
for Object.hashCode(), which will prevent your class from functioning
properly in conjunction with all hash-based collections, including
HashMap, HashSet, and HashTable.


Q: How to reference a variable from one activity to another I'm trying to get a variable string and integer from
Main2Activity.java to MainActivity.java

But the problem is that I don't want to use the:
startActivity(intent);

For it to work. I just want the information to be passed so I can use it in my current activity. Is there any way to do this? What am I missing. This is how my MainActivity looks like:
btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        TextView textView = (TextView)findViewById(R.id.textView7);

        Intent intent = getIntent();
        String A = intent.getStringExtra("Apples");
        textView.setText(A);
    }
});

And my Main2Activty:
Intent intent = new Intent(Main2Activity.this, MainActivity.class);
intent.putExtra("Apples", "Red");

Thanks for helping. Please only comment if you know what you're talking about.

A: There is an other way, you can define a Class DataHolder and static variable for sharing variable between Activity
Example
class DataHolder {
    public static String appleColor = "";
}

Then you can use like this:
Intent intent = new Intent(Main2Activity.this, MainActivity.class);
DataHolder.appleColor = "RED";

Then
btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        TextView textView = (TextView)findViewById(R.id.textView7);

        Intent intent = getIntent();
        textView.setText(DataHolder.appleColor);
    }
});


Q: Replace black boot screen with Purple ( default ) I used to have Gnome and Cinnamon on my laptop. Maybe because of that, the boot screen has changed to a black one than default Purple boot screen. I have since then upgraded to 16.04 from 14.04 and everything was good.
But recently, I am facing frequent boot failure. The boot screen flashes, goes transparent and shows some terminal like activities in the background. In the end, mostly it will say some process failed and I never get to the GUI.
This is happening so frequently that I am not able to use my PC at all. Will replacing black boot screen with Purple solve this problem ? If no, kindly suggest a solution for the same. Thanks.
PS: I now use Unity alone with 16.04


Q: Only grep img tags that contain a keyword, but not img tags that don't? Using grep/regex, I am trying to pull img tags out of a file. I only want img tags that contain 'photobucket' in the source, and I do not want img tags that do not contain photobucket.
Want:

Do Not Want:

We like photobucket

What I have tried:
()

This did not work, because it pulled the second example in "Do Not Want", as there was a 'photobucket' and then a closing bracket. How can I only check for 'photobucket' up until the first closing bracket, and if photobucket is not contained, ignore it and move on?
'photobucket' may be in different locations within the string.

A: Just add a negation of > sign:
(]*?photobucket.*?>)

https://regex101.com/r/tZ9lI9/2

A: grep -o ']*src="[^"]*photobucket[^>]*>' infile

-o returns only the matches. Split up:

<img          # Start with ]*         # Zero or more of "not >"
src="         # start of src attribute
[^"]*         # Zero or more or "not quotes"
photobucket   # Match photobucket
[^>]*         # Zero or more of "not >"
>             # Closing angle bracket

For the input file

We like photobucket

this returns
$ grep -o ']*src="[^"]*photobucket[^>]*>' infile

The non-greedy .*? works only with the -P option (Perl regexes).

A: Try the following:
]*?photobucket[^>]*?>

This way the regex can't got past the '>'

A: Try with this pattern:

I´m not sure the characters admited by the name folders, but you just need add in the ranges "[]" before and after the "photobucket".


Q: Maximum number reached for Sharepoint 2007 number-type column In a SharePoint 2007 List, there is a number-type column which have a maximum value 1000. Suppose that the column is used for a auto-increment ID, what will happen if the ID exceed 1000?
Will the next ID be reset to 0 or a error will occur?


Q: Icon color of html5 input date picker How can I change the icon color of the native HTML5 date input (<input type="date" />)?
Is it possible to change the calendar icon color to HEX: #018bee or RGB: (1, 139, 238)? I saw a post saying that it was possible using filters, but I was unsuccessful.

Codepen Example:
https://codepen.io/gerisd/pen/VwPzqMy
HTML:
 <input type="date" id="deadline" name="deadline" value="2021-01-01" required>

CSS:
#deadline{
  width: 100%;
  min-width: 100px;
  border: none;
  height: 100%;
  background: none;
  outline: none;
  padding-inline: 5px;
  resize: none;
  border-right: 2px solid #dde2f1;
  cursor: pointer;
  color: #9fa3b1;
  text-align: center;
}

input[type="date"]::-webkit-calendar-picker-indicator {
  cursor: pointer;
  border-radius: 4px;
  margin-right: 2px;
  filter: invert(0.8) sepia(100%) saturate(10000%) hue-rotate(240deg);
}

A: Have you tried using webkit? I found a similar qustion from
enter link description here
try this code from that question maybe:
::-webkit-calendar-picker-indicator {
filter: invert(1);

}


Q: how can i display data in detail component from list component? i have problem to display data from one component to another component.
i put the data which i fetch from the serve in prova and i display the list of all work. but I can't transfer the data that is on "prova" to another component to make the details visible through their own id.
this is my apicall service

import { Injectable } from '@angular/core';
import {HttpClient,HttpClientModule,HttpResponse} from '@angular/common/http';
import {Observable} from "rxjs";
import {map} from "rxjs/operators";
import {results} from "./results"

@Injectable({
  providedIn: 'root'
})
export class GetApiService {

  constructor(
    private http:HttpClient,
  ) { }

  apiCall():Observable<results[]>
  {
    return this.http.get('https://www.themuse.com/api/public/jobs?category=Engineering&page=10')
    .pipe(map
    (
      (response:any) => {
        const data = response.results;
        console.log (data)
        return data ;

      }
    )
    );
   }
}

this is my observable results
  export interface results
    {
  categories : any;
company: string;
contents:string;
id : number;
 levels:string;
 locations:string;
 model_type: string;
 name: string;
 refs: string;
 short_name: string;
 type:string;

  }

this is my component where are a list of works
import {results} from "../results";
import {GetApiService} from '../get-api.service';
import {switchMap} from "rxjs/operators";
import { Observable } from 'rxjs';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-work-list',
  templateUrl: './work-list.component.html',
  styleUrls: ['./work-list.component.css']
})
export class WorkListComponent implements OnInit {

  prova: results[]=[] ;
 item: any;
  selectedId: any ;
  constructor(
    private api :GetApiService,
    private route: ActivatedRoute,
  ) { }

  ngOnInit(){

    this.api.apiCall()
    .subscribe
      (
        (data:results[]) => {
          this.prova=data;
        console.log (data);

        });

}
}

and the respectiv html connected by id

 {{ item.name }}

 {{ item.id }}

 {{ item.categories[0].name }}

 {{ item.name }}

this is the details where i can't display the selected work with its own details
import { ActivatedRoute } from '@angular/router';
import {results}  from '../results';
import {GetApiService} from '../get-api.service';
import {switchMap} from "rxjs/operators";

@Component({
selector: 'app-work-details',
templateUrl: './work-details.component.html',
styleUrls: ['./work-details.component.css']
})
export class WorkDetailsComponent implements OnInit {
@Input()
item: {
  categories: any;
  company: string;
  contents: string;
  id: number;
  levels: string;
  locations: string;
  model_type: string;
  name: string;
  refs: string;
  short_name: string;
  type: string;
} | undefined;
@Input ()
prova: results[]=[];
selectedId:string | undefined;
constructor(
  private route: ActivatedRoute,
  private api: GetApiService,
) { }

ngOnInit():void {

   this.route.paramMap.subscribe
    (params => {
      this.item=this.prova[+params.get('selectedId')];

**// it should  be somewthing like this but prova is empty.**

    })
  ;
}
}

A: It looks like you're mixing two different mechanisms?
One is of a parent -> child component relationship where you have your WorkDetailsComponent with an @Input() for prova, but at the same time, it looks like the component is its own page given your  and the usage of this.route.paramMap.subscribe....
Fairly certain you can't have it both ways.
You either go parent -> child component wherein you pass in the relevant details using the @Input()s:

  <app-work-details [prova]="prova" [selectedItem]="selectedItem"></app-work-details>

OR you go with the separate page route which can be done one of two ways:

*

*Use the service as a shared service; have it remember the state (prova) so that when the details page loads, it can request the data for the relevant id.

*Pass the additional data through the route params
For 1, it would look something like:
private prova: results[]; // Save request response to this as well

public getItem(id: number): results {
  return this.prova.find(x => x.id === id);
}

And then when you load your details page:
ngOnInit():void {

   this.route.paramMap.subscribe
    (params => {
      this.selectedId=+params.get('selectedId');

   this.item = this.service.getItem(this.selectedId);

    });
}

For 2, it involves routing with additional data, something like this:
..

This article shows the various ways of getting data between components in better detail.


Q: Shifting elements of an array to the right I am aware that there are solutions for shifting arrays out there. However no solution works for me. The code should achieve the following:
The method shift(int[] array, int places) takes in an array, shifts the elements places - times to the right and replaces the "leftover" elements with "0".
So far I have:
public static int[] shiftWithDrop(int[] array, int places) {

    if (places == 0 || array == null) {
        return null;
    }
    for (int i = array.length-places-1; i >= 0; i-- ) {
        array[i+places] = array[i];
        array[i] = 0;
    }
    return array;
}

This code does only somehow work, but it does not return the desired result. What am I missing?

A: There are several issues in this code:

*

*It returns null when places == 0 -- without shift, the original array needs to be returned

*In the given loop implementation the major part of the array may be skipped and instead of replacing the first places elements with 0, actually a few elements in the beginning of the array are set to 0.

Also it is better to change the signature of the method to set places before the vararg array.
So to address these issues, the following solution is offered:
public static int[] shiftWithDrop(int places, int ... array) {
    if(array == null || places <= 0) {
        return array;
    }
    for (int i = array.length; i-- > 0;) {
        array[i] = i  < places ? 0 : array[i - places];
    }

    return array;
}

Tests:
System.out.println(Arrays.toString(shiftWithDrop(1, 1, 2, 3, 4, 5)));
System.out.println(Arrays.toString(shiftWithDrop(2, new int[]{1, 2, 3, 4, 5})));
System.out.println(Arrays.toString(shiftWithDrop(3, 1, 2, 3, 4, 5)));
System.out.println(Arrays.toString(shiftWithDrop(7, 1, 2, 3, 4, 5)));

Output:
[0, 1, 2, 3, 4]
[0, 0, 1, 2, 3]
[0, 0, 0, 1, 2]
[0, 0, 0, 0, 0]