text:
Q: How to handle the setText("Some Text") event on a disabled TextBox I want to fire an event when setting a value in a TextBox with setText("something")
What I tried so far
w.addChangeHandler(new ChangeHandler() {
    @Override
    public void onChange(ChangeEvent event) {
    isChanged = true;
}
});

And I tried also to have a custom a TextBox that listen to past event
class CustomTextBox extends TextBox implements HasHandlers {

 private HandlerManager handlerManager;

 public CustomTextBox() {
     super();
     handlerManager = new HandlerManager(this);
     sinkEvents(Event.ONPASTE);
 }

 @Override
 public void onBrowserEvent(Event event) {
   super.onBrowserEvent(event);

   switch (event.getTypeInt()) {
     case Event.ONPASTE:{
      fireEvent(new TextChangeEvent());
       break;
     }
     default:
       // Do nothing
   }
 }

 @Override
 public void fireEvent(GwtEvent<?> event) {
   handlerManager.fireEvent(event);
 }

 public HandlerRegistration addTextChangeEventHandler(TextChangeEventHandler handler) {
   return handlerManager.addHandler(TextChangeEvent.TYPE, handler);
 }
}

With no success, any suggestions would be appreciated.

A: setText won't fire events.
Add a ValueChangeHandler<String> to your TextBox, then use setValue("something", true) to fire a ValueChangeEvent<String> to all handlers while setting the new value, whether the box id disabled or not.


text:
Q: Text formatting, indent How can I remove the indent after 'itemize'? I want 'algorithm 1...' to be written from the same place as header and first sentence.
Is there a better way than \qquad to format lines after 'Inputs:' and 'Outputs:' with indentation in the text?
\documentclass{article}
\documentclass[runningheads,a4paper]{article}
\usepackage[ruled,vlined]{algorithm2e}
\usepackage{calc}
\usepackage[a4paper,bindingoffset=0.2in,%
 left=0.5in,right=0.5in,top=0.5in,bottom=0.5in,%
 footskip=.25in]{geometry}
\usepackage{tabularx}
\newenvironment{algotabularx}
 {\tabularx{\linewidth-\inoutsize-\widthof{~~~}-4\tabcolsep-
\rightskip}[t]}
{\endtabularx}

\begin{document}
\section{The Dijkstra's algorithm}
The Dijkstra's algorithm is used for finding shortest paths in a graph G = $\langle{V,E}\rangle$. The characteristics of the Dijkstra's algorithm variant presented here are as follows:

\begin{itemize}
    \item Works on a \underline{weighted graph}.
    \item Only \underline{non-negative weights} are allowed.
    \item Calculates minimum distances from one node $v_0$ to all the others
    \item It has the complexity of $O(\left|V\right|^2)$.
\end{itemize}

Algorithm 1 presents a pseudocode for the Dijkstra's algorithm.\\

\begin{algotabularx}{@{}p{3cm}p{0.5cm}p{10cm}X@{}}

Inputs: \\
\qquad $G = \langle{V,E}\rangle$  & - & a weighted graph \\
\qquad $v_0$ & - & the initial node to determine distances from \\

Outputs: \\
\qquad $\forall v \in V : d(v)$ & - & a set of distances from $v0$ calculated for all nodes $v \in V$  \\
\qquad $\forall v \in V : d(p)$ & - & a set of predecessors on the shortest path from v0 \\

\end{algotabularx}

\end{document}

A: The double line break after \end{itemize} indicates that you are starting a new paragraph, which causes the indentation. Remove one of the line breaks to indicate that it is part of the same paragraph:
\documentclass[runningheads,a4paper]{article}
\usepackage[ruled,vlined]{algorithm2e}
\usepackage{calc}
\usepackage[a4paper,bindingoffset=0.2in,%
left=0.5in,right=0.5in,top=0.5in,bottom=0.5in,%
footskip=.25in]{geometry}
\usepackage{tabularx}
\newenvironment{algotabularx}
{\tabularx{\linewidth-\inoutsize-\widthof{~~~}-4\tabcolsep-
        \rightskip}[t]}
{\endtabularx}

\begin{document}
    \section{The Dijkstra's algorithm}
    The Dijkstra's algorithm is used for finding shortest paths in a graph G = $\langle{V,E}\rangle$. The characteristics of the Dijkstra's algorithm variant presented here are as follows:

    \begin{itemize}
        \item Works on a \underline{weighted graph}.
        \item Only \underline{non-negative weights} are allowed.
        \item Calculates minimum distances from one node $v_0$ to all the others
        \item It has the complexity of $O(\left|V\right|^2)$.
    \end{itemize}
    Algorithm 1 presents a pseudocode for the Dijkstra's algorithm.\\

    \begin{algotabularx}{@{}p{3cm}p{0.5cm}p{10cm}X@{}}

        Inputs: \\
        \qquad $G = \langle{V,E}\rangle$  & - & a weighted graph \\
        \qquad $v_0$ & - & the initial node to determine distances from \\

        Outputs: \\
        \qquad $\forall v \in V : d(v)$ & - & a set of distances from $v0$ calculated for all nodes $v \in V$  \\
        \qquad $\forall v \in V : d(p)$ & - & a set of predecessors on the shortest path from v0 \\

    \end{algotabularx}

\end{document}

leads to:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Which class loader is used by JNI calls in native code? I have A.jar which uses jna to call into some native code B.dll, which in turn uses JNI to call into C.jar.
The class in A.jar which does all the jna calls to B.dll is loaded with a CustomClassLoader which has C.jar and A.jar added to its URL list - A.jar's system class loader does not have C.jar in its URL list.
When the native code in B.dll calls env->FindClass('some/class/in/c.jar') it can not find the class. If I remove the CustomClassLoader and add C.jar to the URL list of A.jar's system class loader, env->FindClass('some/class/in/c.jar') is able to find the class. However, I would really really like the class in A.jar to be loaded with the CustomClassLoader, because when the execution arrives in C.jar I do not want that code to have the same class loader as A.jar.
So, is it possible to somehow ensure that when B.dll runs the JNI call env->FindClass('some/class/in/c.jar/') the CustomClassLoader is being used?

A: To answer your question, findClass documentation states:

FindClass locates the class loader associated with the current native
  method; that is, the class loader of the class that declared the
  native method.

One solution to your problem can be sending the CustomClassLoader instance in a method parameter to the C code and cache it there, whenever you need to do class lookup you can use that classloader instance (call the method findClass).


text:
Q: How can I get the total count of records in mongo db database using Express.js Here is my Controller
    const getCountofCenters = async (req, res) => {

        const result =  Center.countDocuments();

        await result.then(() => res.status(200).send(result))
            .catch((err) => {
                res.status(200).send(err)
            });
    }

This is the Api call
    router.get("/count", CenterController.getCountofCenters);

This is the output which I get from the Postman test, empty array
    {}

enter image description here

A: Try this:
const getCountofCenters = async (req, res) => {
  try {
    const result = await Center.countDocuments();
    return res.status(200).json(result);
  } catch {
    return res.status(400).json({ success: false });
  }
}

A: model.countDocuments returns a promise that you need to resolve so you can get the value of count
so the correct implementation on this within an async function is
await Center.countDocuments()

then sequentially you can return the response


text:
Q: Java method for accessing multiple collections as one, without join
Possible Duplicate:
Combine multiple Collections into a single logical Collection?

I have a lot of small collections that I would like to access as a whole.
I could e.g. create a new LinkedList and add all elements to it. But I was thinking, there might be some tool to add complete Collections without having to re-link every item. I am not speaking about addAll. The Collections shall stay seperate, but only from the outside seem to be one.
Any ideas?

A: The Google Guava project has a class called Iterators that provides utilities for taking iterators and applying transforms to them.  One of the functions they provide is called Iterators.concat, which takes in multiple iterators and produces a new iterator that iterates over the concatenation of those individual iterators.  This may not be exactly what you're looking for, but it would provide you the functionality of iterating across multiple elements without having to duplicate all of them.
One question you may need to think about when using a collection as you've proposed is what happens if you try to mutate the collection.  For example, if you add an element, where would it go?  If all you need is iteration and you don't need to think about this, the Iterators.concat method may be what you're looking for.

A: In standard Java, the best you can do is to create a collection of collections.
If you were to adopt "guava", you could use "Iterable" to create such a beast:
http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Iterables.html#concat%28java.lang.Iterable,java.lang.Iterable,java.lang.Iterable%29
PS:
Say "Hi!" to Gregor Samsa for me!

A: Check out the Google Guava library, which includes a Iterators class containing many useful static methods.  In this case, you can use concat to combine the iterators over each small collection into a single iterator that will traverse all collections.
// First collection.
List<String> l = new LinkedList<String>();
l.add("Hello");
l.add("Hi");

// Second collection.
Set<String> s = new HashSet<String>();
s.add("Goodbye");

// Combine iterators over both collections.
Iterator<String> it = Iterators.concat(l.iterator, s.iterator());


text:
Q: Blazor cascading component preventing StateHasChanged So I'm new to Blazor and I've just found out about CascadingValue and their possible use for showing error messages. I am creating an Outlook Add In for saving mails and attachments in Sharepoint, so I'm dynamically retrieving the current Outlook mail using Office-js and JSInterop, such that my Add In always uses the selected mail.
But now that I'm trying to implement a cascading component for error messages I've run into problems with StateHasChanged.
Following code is my cascading error component:
<CascadingValue Value=this>
    @ChildContent
</CascadingValue>

        @ErrorMessage

    x

@code {
    [Parameter]
    public RenderFragment ChildContent { get; set; }
    public string ErrorMessage { get; set; }

    public void ProcessError(Exception ex)
    {
        ErrorMessage = ex.Message;
        StateHasChanged();
    }

    public void DismissError()
    {
        ErrorMessage = null;
        StateHasChanged();
    }
}

And the component I'm having troubles with (atleast the important parts):

    {Showing details from OutlookMail here}

@code {
    [CascadingParameter] public Error Error { get; set; }
    public OutlookMail OutlookMail { get; set; }
    private static Action<OutlookMail> _receiveMailAction;
    protected override async Task OnInitializedAsync()
    {
        _receiveMailAction = UpdateMail;
        await base.OnInitializedAsync();
    }
    private void UpdateMail(OutlookMail mail)
    {
        InvokeAsync(() =>
        {
            OutlookMail = mail;
            StateHasChanged();
        });
    }
    [JSInvokable]
    public static void ReceiveMail(OutlookMail mail)
    {
        _receiveMailAction?.Invoke(mail);
    }
    public async Task MethodWithError()
    {
        try
        {
            await DoStuffWithPossibleError();
        }
        catch (Exception e)
        {
            Error.ProcessError(e);
        }
    }
}

Everything works fine until Error.ProcessError gets called and the error message is shown, after that StateHasChanged stops rerendering my component which gives inconsistent data to the users.
I am probably doing something wrong, since I can't really find anyone else with the same problem, but I'm not seeing it, so I'm hoping someone on here has a better understanding of where things are going wrong, or maybe even a better way of going about showing error messages if the problem is with using CascadingValue like this.
All the help is appreciated.
Edit 1: After some more looking into this, it seems that it's actually not updating OutlookMail, even when I move it outside of InvokeAsync. So there might be something weird happening with instances of my component

A: After my first edit, I found out it was indeed a problem with instances, since I'm overwriting a static Action within OnInitialized, each time it creates a new instance, the old instances no longer works. And the code which returned the error happened to have a auth dialog with a redirect callback to the same page, it closes directly after, but loading the page actually creates a new instance of my component, which in turn invalidates the one my user works with. So I'll probably just have to create a singleton service that handles the incoming mail data, so that my component can always access the correct data.


text:
Q: IIS web.config : Rewrite URL file as subdomain I am trying to rewrite my url with a web.config file.
Actual URL: sudomain.mydomain.com/legal.html
Wished URL: legal.mydomain.com
I have already hide the html extension.
<rule name="Hidehtml" enabled="true">
      <match ignoreCase="true" url="Legal" />
          <conditions>
             <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
             <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
             <add input="{URL}" pattern="(.*)\.(.*)" negate="true" />
           </conditions>
       <action type="Rewrite" url="Legal.html"/>
</rule>

I saw this kind of rewrite is possible with subfolder, but I wonder if it is possible with a file.
I am trying this one but it give me a DNS error.
 <rule name="testrule" stopProcessing="true">
        <match url="legal(.*)" />
        <conditions>
            <add input="{HTTP_HOST}" pattern="mydomain.com" />
        </conditions>
        <action type="Redirect" url="http://legal.mydomain.com" />
    </rule>

I wonder if I am not missing something, maybe a redirect is needed too?
Thanks for your help !

A: To achieve this,
I just registered two CNAME for my website.
FQDN:subdomain.mydomain.com
FQDN:legal.mydomain.com

Then I apply them to my IIS site.

Just make sure both of them can be accessed in web browser.
Then I apply following rewrite rules
  <rules>
                <rule name="testrule" stopProcessing="true">
                    <match url="(.*)" />
                    <conditions>
                        <add input="{URL}" pattern="^/legal\.[a-zA-Z]+" />
                        <add input="{HTTP_HOST}" pattern="subdomain.candy.com" />
                    </conditions>
                    <action type="Redirect" url="http://legal.candy.com" />
                </rule>
                <rule name="rewrite rule">
                    <match url="(.*)" />
                    <conditions>
                        <add input="{HTTP_HOST}" pattern="legal.candy.com" />
                        <add input="{URL}" pattern="^(/)?$" />
                    </conditions>
                    <action type="Rewrite" url="http://subdomain.candy.com/legal.html" />
                </rule>
            </rules>

When you access sudomain.mydomain.com/legal.html, the request will be redirected to legal.mydomain.com/ and legal.mydomain.com will rewrite back to /legal.html for response content.
Please keep in mind that legal.mydomain.com is always required to be registered in DNS even you just use it as a mask.
If your website are forwarding the public internet, please remember to purchase domain for legal.domain.com as well.


text:
Q: convert +44 into 0044 phone number How can I change +44 phone number into a 0044 phone number within the select statement?

A: Presumably, + only occurs once in the phone number, so you can use replace():
replace(phonenumber, '+44', '0044')

A: using concat -
select concat('00', replace(phonenumber,'+','')) from tableName


text:
Q: Use multiple functions in MySQLdb (python) this code below runs just fine, but i want to separate this code into function (this is my first time using MySQLdb) ,
import MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","user_name","pass","db_name" )

cursor = db.cursor()
sql = "SELECT activity_log.datetime FROM activity_log"
cursor.execute(sql)
date_data = cursor.fetchall()
for content in date_data:
    print content

# disconnect from server
db.close()

Question: how could I create one database connection and use it to multiple functions, this is what i've wrote so far (doesn't work):
import MySQLdb

class DB():
    def __init__(self):
        db = MySQLdb.connect("locahost", "user_name", "pass", "db_name")
        self.cur = db.cursor()

    def time_statistic(self):
        sql = "SELECT activity_log.datetime FROM activity_log"
        self.cur.execute(sql)
        self.date_data = self.cursor.fetchone()
        for content in self.date_data:
            print content

    def test1(self):
        pass

if __name__ == '__main__':

    db = DB.connect("db_name" )
    db.time_statistic(self)
    db.test1(self)
    db.close()

A: You need to pass the arguments to init to make sure that the class connects to the right DB.
import MySQLdb

class DB():
    def __init__(self, server, user, password, db_name):
        db = MySQLdb.connect(server, user, password, db_name)
        self.cur = db.cursor()

    def time_statistic(self):
        sql = "SELECT activity_log.datetime FROM activity_log"
        self.cur.execute(sql)
        self.date_data = self.cursor.fetchone()
        for content in self.date_data:
            print content

    def test1(self):
        pass

if __name__ == '__main__':

    db = DB(<server>, <user>, <password>, <db_name>)
    db.time_statistic()
    db.test1()

Replace the arguments in <> with actual values you need to connect to the db. You may also want to add some error handling in the above code.


text:
Q: Getting first n unique elements from Python list I have a python list where elements can repeat.
>>> a = [1,2,2,3,3,4,5,6]

I want to get the first n unique elements from the list.
So, in this case, if i want the first 5 unique elements, they would be:
[1,2,3,4,5]

I have come up with a solution using generators:
def iterate(itr, upper=5):

    count = 0
    for index, element in enumerate(itr):
        if index==0:
            count += 1
            yield element

        elif element not in itr[:index] and count<upper:
            count += 1
            yield element

In use:
>>> i = iterate(a, 5)
>>> [e for e in i]
[1,2,3,4,5]

I have doubts on this being the most optimal solution. Is there an alternative strategy that i can implement to write it in a more pythonic and efficient
way?

A: If your objects are hashable (ints are hashable) you can write utility function using fromkeys method of collections.OrderedDict class (or starting from Python3.7 a plain dict, since they became officially ordered) like
from collections import OrderedDict

def nub(iterable):
    """Returns unique elements preserving order."""
    return OrderedDict.fromkeys(iterable).keys()

and then implementation of iterate can be simplified to
from itertools import islice

def iterate(itr, upper=5):
    return islice(nub(itr), upper)

or if you want always a list as an output
def iterate(itr, upper=5):
    return list(nub(itr))[:upper]

Improvements
As @Chris_Rands mentioned this solution walks through entire collection and we can improve this by writing nub utility in a form of generator like others already did:
def nub(iterable):
    seen = set()
    add_seen = seen.add
    for element in iterable:
        if element in seen:
            continue
        yield element
        add_seen(element)

A: Here is a Pythonic approach using itertools.takewhile():
In [95]: from itertools import takewhile

In [96]: seen = set()

In [97]: set(takewhile(lambda x: seen.add(x) or len(seen) <= 4, a))
Out[97]: {1, 2, 3, 4}

A: You can use OrderedDict or, since Python 3.7, an ordinary dict, since they are implemented to preserve the insertion order. Note that this won't work with sets.
N = 3
a = [1, 2, 2, 3, 3, 3, 4]
d = {x: True for x in a}
list(d.keys())[:N]

A: I would use a set to remember what was seen and return from the generator when you have seen enough:
a = [1, 2, 2, 3, 3, 4, 5, 6]

def get_unique_N(iterable, N):
    """Yields (in order) the first N unique elements of iterable.
    Might yield less if data too short."""
    seen = set()
    for e in iterable:
        if e in seen:
            continue
        seen.add(e)
        yield e
        if len(seen) == N:
            return

k = get_unique_N([1, 2, 2, 3, 3, 4, 5, 6], 4)
print(list(k))

Output:
[1, 2, 3, 4]

According to PEP-479 you should return from generators, not raise StopIteration - thanks to @khelwood & @iBug for that piece of comment - one never learns out.
With 3.6 you get a deprecated warning, with 3.7 it gives RuntimeErrors: Transition Plan if still using raise StopIteration

Your solution using elif element not in itr[:index] and count<upper: uses O(k) lookups - with k being the length of the slice - using a set reduces this to O(1) lookups but uses  more memory because the set has to be kept as well. It is a speed vs. memory tradeoff - what is better is application/data dependend.
Consider [1, 2, 3, 4, 4, 4, 4, 5] vs [1] * 1000 + [2] * 1000 + [3] * 1000 + [4] * 1000 + [5] * 1000 + [6]:
For 6 uniques (in longer list):

*

*you would have lookups of O(1)+O(2)+...+O(5001)

*mine would have 5001*O(1) lookup + memory for set( {1, 2, 3, 4, 5, 6})

A: There are really amazing answers for this question, which are fast, compact and brilliant! The reason I am putting here this code is that I believe there are plenty of cases when you don't care about 1 microsecond time loose nor you want additional libraries in your code for one-time solving a simple task.
a = [1,2,2,3,3,4,5,6]
res = []
for x in a:
    if x not in res:  # yes, not optimal, but doesnt need additional dict
        res.append(x)
        if len(res) == 5:
            break
print(res)

A: Assuming the elements are ordered as shown, this is an opportunity to have fun with the groupby function in itertools:
from itertools import groupby, islice

def first_unique(data, upper):
    return islice((key for (key, _) in groupby(data)), 0, upper)

a = [1, 2, 2, 3, 3, 4, 5, 6]

print(list(first_unique(a, 5)))

Updated to use islice instead of enumerate per @juanpa.arrivillaga.  You don't even need a set to keep track of duplicates.

A: Using set with sorted+ key
sorted(set(a), key=list(a).index)[:5]
Out[136]: [1, 2, 3, 4, 5]

A: Given
import itertools as it

a = [1, 2, 2, 3, 3, 4, 5, 6]

Code
A simple list comprehension (similar to @cdlane's answer).
[k for k, _ in it.groupby(a)][:5]
# [1, 2, 3, 4, 5]

Alternatively, in Python 3.6+:
list(dict.fromkeys(a))[:5]
# [1, 2, 3, 4, 5]

A: You can adapt the popular itertools unique_everseen recipe:
def unique_everseen_limit(iterable, limit=5):
    seen = set()
    seen_add = seen.add
    for element in iterable:
        if element not in seen:
            seen_add(element)
            yield element
        if len(seen) == limit:
            break

a = [1,2,2,3,3,4,5,6]

res = list(unique_everseen_limit(a))  # [1, 2, 3, 4, 5]

Alternatively, as suggested by @Chris_Rands, you can use itertools.islice to extract a fixed number of values from a non-limited generator:
from itertools import islice

def unique_everseen(iterable):
    seen = set()
    seen_add = seen.add
    for element in iterable:
        if element not in seen:
            seen_add(element)
            yield element

res = list(islice(unique_everseen(a), 5))  # [1, 2, 3, 4, 5]

Note the unique_everseen recipe is available in 3rd party libraries via more_itertools.unique_everseen or toolz.unique, so you could use:
from itertools import islice
from more_itertools import unique_everseen
from toolz import unique

res = list(islice(unique_everseen(a), 5))  # [1, 2, 3, 4, 5]
res = list(islice(unique(a), 5))           # [1, 2, 3, 4, 5]

A: Profiling Analysis
Solutions
Which solution is the fastest? There are two clear favorite answers (and 3 solutions) that captured most of the votes.

*

*The solution by Patrick Artner - denoted as PA.

*The first solution by jpp - denoted as jpp1

*The second solution by jpp - denoted as jpp2

This is because these claim to run in O(N) while others here run in O(N^2), or do not guarantee the order of the returned list.
Experiment setup
For this experiment 3 variables were considered.

*

*N elements. The number of first N elements the function is searching for.

*List length. The longer the list the further the algorithm has to look to find the last element.

*Repeat limit. How many times an element can repeat before the next element occurs in the list. This is uniformly distributed between 1 and the repeat limit.

The assumptions for data generation were as follows. How strict these are depend on the algorithm used, but is more a note on how the data was generated than a limitation on the algorithms themselves.

*

*The elements never occur again after its repeated sequence first appears in the list.

*The elements are numeric and increasing.

*The elements are of type int.

So in a list of [1,1,1,2,2,3,4 ....] 1,2,3 would never appear again. The next element after 4 would be 5, but there could be a random number of 4s up to the repeat limit before we see 5.
A new dataset was created for each combination of variables and and re-generated 20 times. The python timeit function was used to profile the algorithms 50 times on each dataset. The mean time of the 20x50=1000 runs (for each combination) were reported here. Since the algorithms are generators, their outputs were converted to a list to get the execution time.
Results
As is expected the more elements searched for, the longer it takes. This graph shows that the execution time is indeed O(N) as claimed by the authors (the straight line proves this).

Fig 1. Varying the first N elements searched for.
All three solutions do not consume additional computation time beyond that which is required. The below image shows what happens when the list is limited in size, and not N elements. Lists of length 10k, with elements repeating a maximum of 100 times (and thus on average repeating 50 times) would on average run out of unique elements by 200 (10000/50). If any of these graphs showed an increase in computation time beyond 200 this would be a cause for concern.

Fig 2. The effect of first N elements chosen > number of unique elements.
The figure below again shows that processing time increases (at a rate of O(N)) the more data the algorithm has to sift through. The rate of increase is the same as when first N elements were varied. This is because stepping through the list is the common execution block in both, and the execution block that ultimately decides how fast the algorithm is.

Fig 3. Varying the repeat limit.
Conclusion
The 2nd solution posted by jpp is the fastest solution of the 3 in all cases. The solution is only slightly faster than the solution posted by Patrick Artner, and is almost twice as fast as his first solution.

A: Why not use something like this?
>>> a = [1, 2, 2, 3, 3, 4, 5, 6]
>>> list(set(a))[:5]
[1, 2, 3, 4, 5]

A: Example list:
a = [1, 2, 2, 3, 3, 4, 5, 6]

Function returns all or count of unique items needed from list
1st argument - list to work with, 2nd argument (optional) - count of unique items (by default - None - it means that all unique elements will be returned)
def unique_elements(lst, number_of_elements=None):
    return list(dict.fromkeys(lst))[:number_of_elements]

Here is example how it works. List name is "a", and we need to get 2 unique elements:
print(unique_elements(a, 2))

Output:

A: a = [1,2,2,3,3,4,5,6]

from collections import defaultdict
def function(lis,n):
    dic = defaultdict(int)

    sol=set()

    for i in lis:
            try:
                if dic[i]:
                    pass
                else:
                    sol.add(i)
                    dic[i]=1
                    if len(sol)>=n:
                        break
            except KeyError:
                pass

    return list(sol)

print(function(a,3))

output
[1, 2, 3]


text:
Q: make_hash() function? hash codes? My boss sent me a process, in to which I need to:

*

*make a function that creates a temp table

*grab data from a table

*use a function to refine the data

*create a hash code for 2 of the columns

*insert all the data from the temp to the original data

*drop the table

I've been trying to look what the make_hash() function does. Whenever I run the FUNCTION it gives me an error on that line, so I'm guessing I need to declare it first before the begin statement in the create function. Or is it a user-created function? If so, is there a way for me to find which schema the function is located?
I've been trying to research in the books and online but I couldn't find anything, even in the PostgreSQL website.
--------------------------------------------

ERROR:  function make_hash(character varying) does not exist
LINE 1: UPDATE temp_match_queue_04022012 SET title_hash = make_hash(...
                                                          ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
QUERY:  UPDATE temp_match_queue_04022012 SET title_hash = make_hash(as_title) WHERE as_title IS NOT NULL
CONTEXT:  PL/pgSQL function "metadata_matching_temp" line 30 at SQL statement

********** Error **********

ERROR: function make_hash(character varying) does not exist
SQL state: 42883
Hint: No function matches the given name and argument types. You might need to add explicit type casts.
Context: PL/pgSQL function "metadata_matching_temp" line 30 at SQL statement

A: As @Clodoaldo mentioned look into pgcrypto (which you would get by installing it to your postgres, on debian its in postgresql-contrib iirc).
Any function you call must be available before the BEGIN section. You can combine functions into packages if you need more than one.

A: Nevermind! The make_hash function was written psql that's why it wasn't working properly. I'm using pgAdmin III and the schema name had to be called together with the function for it to work. Thanks a bunch for the help though!


text:
Q: remove data before and after a special characters in SSRS In SSTS I want to remove data before "\" and after "\". Please see the image here. We want to do it from SSRS not from SQL SP. Is it possible.

A: This link can be a good start - converting RTF to TXT


text:
Q: Getting the length of data in a PScustomobject while querying AD I am trying to get a pscustomobject to sort by Canonicalname length, but in order to do this I need the length of each CanonicalName within the PScustomobject.
The Canonicalnamelen is where the length needs to be stored and sorted.
The reason I need to do this is so I can delete OU's within AD that are longer before the lower OU's(But that is not the issue) - i.e. (delete OU /computers/location/IT/test before deleting /computers/location/IT)
So as a result of sorting the list by Canonical Length the canon locations would show like this:
/computers/location/IT/test
/computers/location/IT
The lesser length being always below.
Hope I have explained OK.
My code is as below:
$SourceOU = "OU=Computers,DC=domain,DC=my,DC=my"
##Load up OU's into variable
$OUszero = Get-ADOrganizationalUnit -Properties CanonicalName, DistinguishedName, Description  -Filter *  -SearchBase $SourceOU | Sort-Object CanonicalName |
ForEach-Object {
    [pscustomobject]@{
        Name          = Split-Path $_.CanonicalName -Leaf
        ###I need the length of each object string from CanonicalName and display below in
        ##CanonicalNamelen.
        CanonicalName = $_.CanonicalName
        DistinguishedName  = $_.DistinguishedName
        #UserCount     = @(Get-AdUser -Filter * -SearchBase $_.DistinguishedName -SearchScope Subtree).Count
        ComputerCount = @(Get-AdComputer -Filter * -SearchBase $_.DistinguishedName -SearchScope Subtree).Count
        ###Here is where I need the length of the object to appear.
        ##But it just gives a count of canonical names
        CanonicalNamelen = ($OUszero.Canonicalname.Length)

    }
} | Where-Object ComputerCount -EQ 0

$OUszero | FT


text:
Q: IRichBolt Error when running topology on storm-1.0.0 and pyleus-0.3.0 I'm running storm topology "pyleus --verbose local xyz_topology.jar" using storm-1.0.0, pyleus-0.3.0, centos-6.6 and getting the Error

Exception in thread "main" java.lang.NoClassDefFoundError:
  backtype/storm/topology/IRichBolt

Running: java -client -Ddaemon.name= -Dstorm.options= -Dstorm.home=/usr/local/apache-storm-1.0.0
-Dstorm.log.dir=/usr/local/apache-storm-1.0.0/logs -Djava.library.path=/usr/local/
lib:/opt/local/lib:/usr/lib -Dstorm.conf.file= -cp /usr/local/apache-storm-1.0.0/lib/asm-5.0.3.jar:
/usr/local/apache-storm-1.0.0/lib/clojure-1.7.0.jar:/usr/local/apache-storm-1.0.0/lib/disruptor-3.3.2.jar:
/usr/local/apache-storm-1.0.0/lib/kryo-3.0.3.jar:
/usr/local/apache-storm-1.0.0/lib/log4j-api-2.1.jar:/usr/local/apache-storm-1.0.0/lib/log4j-core-2.1.jar
:/usr/local/apache-storm-1.0.0/lib/log4j-over-slf4j-1.6.6.jar:
/usr/local/apache-storm-1.0.0/lib/log4j-slf4j-impl-2.1.jar:/usr/local/apache-storm-1.0.0/lib/minlog-1.3.0.jar:
/usr/local/apache-storm-1.0.0/lib/objenesis-2.1.jar:/usr/local/apache-storm-1.0.0/lib/reflectasm-1.10.1.jar:
/usr/local/apache-storm-1.0.0/lib/servlet-api-2.5.jar:/usr/local/apache-storm-1.0.0/lib/slf4j-api-1.7.7.jar:
/usr/local/apache-storm-1.0.0/lib/storm-core-1.0.0.jar:
/usr/local/apache-storm-1.0.0/lib/storm-rename-hack-1.0.0.jar:xyzTopology.jar:
/usr/local/storm/conf:/usr/local/apache-storm-1.0.0/bin
-Dstorm.jar=xyz_topology.jar com.yelp.pyleus.PyleusTopologyBuilder --local
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: backtype/storm/topology/IRichBolt
        at java.lang.Class.getDeclaredMethods0(Native Method)
        at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
        at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
        at java.lang.Class.getMethod0(Class.java:3018)
        at java.lang.Class.getMethod(Class.java:1784)
        at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
        at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
Caused by: java.lang.ClassNotFoundException: backtype.storm.topology.IRichBolt
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        ... 7 more
pyleus local: error: [StormError] Storm command failed. Run with --verbose for more info.

The same topology worked well and without any errors when using the old version of storm-0.10.0 and pyleus-0.3.0.
I looked at the storm-0.10.0 and storm-1.0.0 docs and found that in storm-1.0.0
(a) the package structure has been changed and
(b) the IRichBolt class is not presented and instead of that there are two new classes - BaseStatefulBoltExecutor and BasicBoltExecutor - which implement IRichBolt interface.
It seems new storm-1.0.0 release can't work with pyleus-0.3.0 as it was with old storm-0.10.0 version.
What would be the best solution to resolve the issue and allow to run the topology on storm-1.0.0 and pyleus-0.3.0 ?

A: Storm 1.0.0 includes a major refactoring with regard to package names. All packages backtype/* got replaced by org/apache/storm. Thus, you need to recompile your topology using Storm 1.0.0 (including some code change; ie, using different imports to align to the new package structure).
As an alternative, you can enable backward compatibility in your Storm cluster (see https://storm.apache.org/releases/1.0.0/index.html)

NOTE

In the latest version, the class packages have been changed from "backtype.storm" to "org.apache.storm" so the topology code compiled with older version won't run on the Storm 1.0.0 just like that. Backward compatibility is available through following configuration
client.jartransformer.class: "org.apache.storm.hack.StormShadeTransformer"
You need to add the above config in storm installation if you want to run the code compiled with older versions of storm. The config should be added in the machine you use to submit your topologies.
Refer to https://issues.apache.org/jira/browse/STORM-1202 for more details.


text:
Q: /playsound Globally on Server I need to play a sound file (Disk 11) on my server so that everyone can hear it, but the problem I have is that the sound plays, but when the person goes too far away from where they were, it gets quieter and finally you can't hear it at all. Is there a way to play a sound globally so that everyone can hear it and when they move they still hear it fine. Here is what I have tried:
/playsound records.11 @a

Plays for everybody but still gets quieter as you move away!
/playsound records.11 @a [High Wolume]

Blasts your ears at the beginning!
/playsound records.11

Doesn't work, requires a player
I guess what I am asking is how to play the sound server-wide so you can hear it continuously until the end?

A: /playsound has a volume and a minimumVolume optional argument:
/playsound <sound> <player> [x] [y] [z] [volume] [pitch] [minimumVolume]

If you set the minimumVolume to something other than 0, players will be able to hear it at that volume outside of the sound's normal audible range.
For example:
/playsound records.11 @a 0 0 0 1 1 1

It should also be noted that a volume larger than 1 doesn't actually make the sound louder, it just makes it able to be heard from further away.

A: You could try /execute @a ~ ~ ~ playsound records.11 @p.
What this does is execute /playsound records.11 @p for every player, and plays the sound to them.


text:
Q: Orchestra.MahApps custom window I'm trying to create custom MahApps.Metro window with Orchestra framework.
I have copied currennt ShellWindow content (both view + code behind) and created my own Window. Then in App.xaml.cs I have used my window instead of ShellWindow like this:
shellService.CreateWithSplash<MyShellWindowView>()

And problem is, that this window is not correctly styled (for example, minimize/max/close buttons)

Here's my window:
<orchestra:MetroDataWindow x:Class="CatelApp.Views.MyShellWindowView"
                         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                         xmlns:catel="http://catel.codeplex.com"
                         xmlns:orchestra="https://github.com/orcomp/orchestra"
                         SaveWindowPosition="False" d:DesignHeight="696" d:DesignWidth="480" mc:Ignorable="d">

  <orchestra:MetroDataWindow.Resources>
    <ResourceDictionary>
      <Style TargetType="catel:TabControl" BasedOn="{StaticResource {x:Type TabControl}}" />
    </ResourceDictionary>
  </orchestra:MetroDataWindow.Resources>

  <Border x:Name="border" BorderThickness="1">
    <DockPanel LastChildFill="True" Margin="15, 5, 15, 5">

      <StatusBar x:Name="statusBar" DockPanel.Dock="Bottom">
        <orchestra:AnimatingTextBlock x:Name="statusTextBlock" HorizontalAlignment="Left" VerticalAlignment="Center">
          <orchestra:AnimatingTextBlock.ShowStoryboard>
            <Storyboard>
              <DoubleAnimation Storyboard.TargetProperty="Opacity" To="1.0" Duration="0:0:0.2"/>
            </Storyboard>
          </orchestra:AnimatingTextBlock.ShowStoryboard>
          <orchestra:AnimatingTextBlock.HideStoryboard>
            <Storyboard>
              <DoubleAnimation Storyboard.TargetProperty="Opacity" To="0.0" Duration="0:0:0.2"/>
            </Storyboard>
          </orchestra:AnimatingTextBlock.HideStoryboard>
        </orchestra:AnimatingTextBlock>
      </StatusBar>

      <ContentControl x:Name="contentControl" />
    </DockPanel>
  </Border>

</orchestra:MetroDataWindow>

And code behind
namespace CatelApp.Views
{
    /// <summary>
    /// Interaction logic for MyShellWindowViewModel.xaml
    /// </summary>
    public partial class MyShellWindowView : MetroDataWindow, IShell
    {
        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="ShellWindow"/> class.
        /// </summary>
        public MyShellWindowView()
        {
            var serviceLocator = ServiceLocator.Default;

            var themeService = serviceLocator.ResolveType<IThemeService>();
            ThemeHelper.EnsureApplicationThemes(GetType().Assembly, themeService.ShouldCreateStyleForwarders());

            MahAppsHelper.ApplyTheme();

            InitializeComponent();

            var accentColorBrush = ThemeHelper.GetAccentColorBrush();
            border.BorderBrush = accentColorBrush;

            var statusService = serviceLocator.ResolveType<IStatusService>();
            statusService.Initialize(statusTextBlock);

            var commandManager = serviceLocator.ResolveType<ICommandManager>();
            var flyoutService = serviceLocator.ResolveType<IFlyoutService>();
            var mahAppsService = serviceLocator.ResolveType<IMahAppsService>();

            serviceLocator.RegisterInstance<IAboutInfoService>(mahAppsService);

            var flyouts = new FlyoutsControl();
            foreach (var flyout in flyoutService.GetFlyouts())
            {
                flyouts.Items.Add(flyout);
            }

            Flyouts = flyouts;

            var windowCommands = mahAppsService.GetRightWindowCommands();

            if (mahAppsService.GetAboutInfo() != null)
            {
//              var aboutWindowCommand = WindowCommandHelper.CreateWindowCommandButton("appbar_information", "about");

//              var aboutService = serviceLocator.ResolveType<IAboutService>();
//              commandManager.RegisterAction("Help.About", aboutService.ShowAbout);
//              aboutWindowCommand.Command = commandManager.GetCommand("Help.About");

//              windowCommands.Items.Add(aboutWindowCommand);
            }

            RightWindowCommands = windowCommands;

            var mainView = mahAppsService.GetMainView();
            contentControl.Content = mainView;

            SetBinding(TitleProperty, new Binding("ViewModel.Title") {Source = mainView});
        }

        #endregion
    }
}

A: Did you include the MahApps themes in your app resources? For example, see the code below:

<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="/Resources/Icons.xaml" />

    <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
    <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
    <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colors.xaml" />

    <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.AnimatedTabControl.xaml" />
</ResourceDictionary.MergedDictionaries>


text:
Q: How to add filter based on the maximum of group field value in pymongo aggregations In my MongoDB collection, each documents has a field score and a filed query, so I am trying to group documents by query, i.e., get groups of documents with the same query filed, and meanwhile, I only want those groups containing files with score = 3 (range of score is 0,1,2,3). Here is my first aggregation clause:
agg = [{
    "$group": {
        "_id": "$query",
        "src_ids": {"$push": "$src_id"},
        "sources": {"$push": "$source"},
        "scores": {"$push": "$score"}
    }
}]

So I guess, I have to add a $match regarding the maximum in scores in agg, but how should I do that?
===========================
Edit
if we have 6 files:
{"query": "bread", "score": 2, ...}
{"query": "bread", "score": 1, ...}
{"query": "meat", "score": 2, ...}
{"query": "meat", "score": 3, ...}
{"query": "fruit", "score": 0, ...}
{"query": "fruit", "score": 3, ...}
So here by the using the above aggregation clause: db.collection.aggregate(agg), we have 3 groups of: bread, meat, fruit. However, if we consider the score issue, bread should not be returned.

A: So the added match condition will look in the scores array for 3.
agg = [
{
    "$group": {
        "_id": "$query",
        "src_ids": {"$push": "$src_id"},
        "sources": {"$push": "$source"},
        "scores": {"$push": "$score"}
    }
},
{
    "$match": {
        "scores": 3
    }
}
]

A: Inspired by @Mani, in fact it's pretty simple but I am very new to Mongodb.
agg = [{
    "$group": {
        "_id": "$query",
        "src_ids": {"$push": "$src_id"},
        "sources": {"$push": "$source"},
        "scores": {"$push": "$score"},
        "max_score": {"$max": "$score"}
    }},
    {
    "$match": {
        "max_score": {"$eq": 3}
    }}
]


text:
Q: Can I minimize VMWare Workstation from exclusive mode? I am running a VM on two monitors, in fullscreen exclusive mode.
I would like to be able to minimize the VM and mess around in the Host, then go back to the VM.
I can do this by pressing CTRL+ALT to get out of fullscreen mode, but this puts the VM back onto a single monitor, which moves all my VM's windows back to the main virtual screen. This is annoying, because when I come back to the VM, I have to go back to multiple monitor mode, and move windows back to where they should be.
Is there a way to temporarily escape from fullscreen exclusive mode, without disturbing multi-monitor layout?
I should note that I'm only using exclusive mode to get rid of the popup toolbar that otherwise appears when your mouse gets too close to the top of the screen. If there's another way to kill that, please let me know.
My host and guest are both Windows 7 x64, and I'm running VMWare Workstation 8.

A: You can use these keyboard shortcuts from the default VMWare configuration:

*

*Ctrl+Alt: Ungrab cursor from guest

*Win+D: Show host desktop

To return to the guest screen, just click on the VMWare window in the taskbar. The multiple monitor configuration will persist.


text:
Q: How get an item in control center of Touch Bar on the right? The app TouchSwitcher add item beside lightscreen and volume items :
https://hazeover.com/touchswitcher.html

Is there a solution to display an item into the control strip on the right region of touch bar ?
I can't find any help in official documentation about it...
Please help me !

A: After decompiling, I discovered some APIs in a framework called DFRFoundation located under /System/Library/PrivateFrameworks, and a related method DFRElementSetControlStripPresenceForIdentifier. I find it quite difficult to get further, so I answer here only to let you know that the API for this is in a private framework. Hope someone would reveal the secrets someday.

A: Here's what I use. Pass an NSView and an identifier of your choice to the controlStrippify() function. My attempts at doing the exact same thing using Swift have resulted in crashes, ports welcome :). Inspiration from https://github.com/a2/touch-baer.
@import Cocoa;
@import Foundation;

// See: https://github.com/a2/touch-baer
extern void DFRElementSetControlStripPresenceForIdentifier(NSString *string, BOOL enabled);

@interface NSTouchBarItem ()
+ (void)addSystemTrayItem:(NSTouchBarItem *)item;
@end

@interface NSTouchBar ()
+ (void)presentSystemModalFunctionBar:(NSTouchBar *)touchBar systemTrayItemIdentifier:(NSString *)identifier;
@end

void controlStrippify(NSView *view, NSString *identifier) {
  if (@available(macOS 10.12.2, *)) {
    NSCustomTouchBarItem *touchBarItem = [[NSCustomTouchBarItem alloc] initWithIdentifier:identifier];
    touchBarItem.view = view;
    [NSTouchBarItem addSystemTrayItem:touchBarItem];
    DFRElementSetControlStripPresenceForIdentifier(identifier, YES);
  } else {
    // Fail!
  }
}


text:
Q: Rails simple model attributes not saved to database I am developing a small Rails 3 app that reads data from the Steam API. What I am seeing is that the model attributes for any ActiveRecord model I create are not saved to the database nor are they output if I debug them.
Here my sample model
class NonPlayableApp < ActiveRecord::Base
  attr_accessor :name, :steam_id
  attr_accessible :name, :steam_id
end

With the migration file being:
class CreateNonPlayableApps < ActiveRecord::Migration
  def change
    create_table :non_playable_apps do |t|
      t.string :name
      t.string :steam_id
      t.timestamps
    end
  end
end

Here are few tests with the Rails console, I get the same results when I try them in a controller and inspect or yaml the model:
irb(main):001:0> temp = NonPlayableApp.new( steam_id: 33333, name: "Testing" )
=> #<NonPlayableApp id: nil, name: nil, steam_id: nil, created_at: nil, updated_at: nil>
irb(main):002:0> temp.steam_id
=> 33333
irb(main):003:0> temp.name
=> "Testing"
irb(main):004:0> temp.save
   (0.1ms)  begin transaction
  SQL (4.0ms)  INSERT INTO "non_playable_apps" ("created_at", "name", "steam_id", "updated_at") VALUES (?, ?, ?, ?)  [["created_at", Fri, 26 Feb 2016 19:40:37 UTC +00:00], ["name", nil], ["steam_id", nil], ["updated_at", Fri, 26 Feb 2016 19:40:37 UTC +00:00]]
   (8.8ms)  commit transaction
=> true
irb(main):005:0> temp.steam_id
=> 33333
irb(main):006:0> temp
=> #<NonPlayableApp id: 64, name: nil, steam_id: nil, created_at: "2016-02-26 19:40:37", updated_at: "2016-02-26 19:40:37">
irb(main):007:0> temp2 = NonPlayableApp.first
  NonPlayableApp Load (1.6ms)  SELECT "non_playable_apps".* FROM "non_playable_apps" LIMIT 1
=> #<NonPlayableApp id: 64, name: nil, steam_id: nil, created_at: "2016-02-26 19:40:37", updated_at: "2016-02-26 19:40:37">
irb(main):008:0> temp2.steam_id
=> nil
irb(main):009:0> temp2.name
=> nil

What am I missing?

A: attr_accessor :name, :steam_id overrides the setter and getter methods that Rails automatically generates for that attributes.
Just delete the attr_accessor :name, :steam_id line from your model.


text:
Q: node.js Error: write after end - AWS Polly I am trying to use AWS Polly for speech synthesis in my node.js app. When I run the speak(text) function for the first time everything works fine however if I run it again I get this error:
events.js:160
  throw er; // Unhandled 'error' event
  ^

Error: write after end
at writeAfterEnd (/Users/noahchalifour/Desktop/HomeServer/Jarvis-Node/node_modules/readable-stream/lib/_stream_writable.js:229:12)
at Speaker.Writable.write (/Users/noahchalifour/Desktop/HomeServer/Jarvis-Node/node_modules/readable-stream/lib/_stream_writable.js:269:20)
at PassThrough.ondata (_stream_readable.js:555:20)
at emitOne (events.js:96:13)
at PassThrough.emit (events.js:188:7)
at PassThrough.Readable.read (_stream_readable.js:381:10)
at flow (_stream_readable.js:761:34)
at resume_ (_stream_readable.js:743:3)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickDomainCallback (internal/process/next_tick.js:128:9)

Here is the code I am trying to run:
// AWS Polly
// Load the SDK
const AWS = require('aws-sdk')
const Stream = require('stream')
const Speaker = require('speaker')

// Create an Polly client
const Polly = new AWS.Polly({
    signatureVersion: 'v4',
    region: 'us-east-1'
})

// Create the Speaker instance
const Player = new Speaker({
  channels: 1,
  bitDepth: 16,
  sampleRate: 16000
})

function speak(text) {
    let params = {
        'Text': text,
        'OutputFormat': 'pcm',
        'VoiceId': 'Brian'
    }
    Polly.synthesizeSpeech(params, (err, data) => {
        if (err) {
            console.log(err.code)
            console.log('error');
        } else if (data) {
            if (data.AudioStream instanceof Buffer) {
                // Initiate the source
                var bufferStream = new Stream.PassThrough()
                // convert AudioStream into a readable stream
                bufferStream.end(data.AudioStream)
                // Pipe into Player
                bufferStream.pipe(Player)
            }
        }
    })
}

speak("Hello World!")

setTimeout(function() {
    speak("This is so cool!")  // error is here
}, 10000)

Edit
After reordering the .pipe() and .end() here is the new error:
request.js:31
        throw err;
        ^

Error: write after end
at writeAfterEnd (/Users/noahchalifour/Desktop/HomeServer/Jarvis-
Node/node_modules/readable-stream/lib/_stream_writable.js:229:12)
at Speaker.Writable.write (/Users/noahchalifour/Desktop/HomeServer/Jarvis-Node/node_modules/readable-stream/lib/_stream_writable.js:269:20)
at PassThrough.ondata (_stream_readable.js:555:20)
at emitOne (events.js:96:13)
at PassThrough.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:176:18)
at PassThrough.Readable.push (_stream_readable.js:134:10)
at PassThrough.Transform.push (_stream_transform.js:128:32)
at afterTransform (_stream_transform.js:77:12)
at TransformState.afterTransform (_stream_transform.js:54:12)

A: As mentioned answer earlier, Try to create Player object every time inside synthesizeSpeech handler. It should solve the issue.
Change this line,
// Pipe into Player
bufferStream.pipe(new Speaker({
  channels: 1,
  bitDepth: 16,
  sampleRate: 16000
}))


text:
Q: Is it the right way using `[weak self]` in swift closure? I always using [weak self] in swift closure to prevent reference cycle.
Here is the code below, is it the correct way?
someTask(completion: {[weak self] (result) in
        if self == nil {
            return
        }

        //is it safe when reach here?

        self!.xxx = yyy
        self!.doLongTermWork()
        self!.finish()  //will crash when self is nil?
    })

Weak self does not keep a strong hold on the instance. So when self.doLongTermWork(), will self be set to nil again somewhere else?

A: You said:
someTask(completion: {[weak self] (result) in
    if self == nil {
        return
    }
    //is it safe when reach here?
    self!.xxx = yyy
})

No! You have not retained self, so in theory it might become nil at any time during the execution of the closure. It probably won't, but "probably" is not good enough. And exclamation marks are always an invitation to crash.
Do the weak-strong dance, and do it correctly:
someTask(completion: {[weak self] (result) in
    if let self = self {  // or let `self` before Swift 4
        // here, self is safe, because you made the reference strong again
        self.xxx = yyy
    }
})

A: Your pattern has race condition. If self was deallocated at the exact same time as your completion handler closure was executing, it could crash. As a general rule, avoid using the ! forced unwrapping operator if you can.

*

*I'd lean towards the guard "early exit" pattern (reducing nested braces, making code easier to read). The standard Swift 4.2 solution is:
someTask { [weak self] result in
    guard let self = self else { return }

    self.xxx = yyy
    self.doLongTermWork()
    self.finish()
}

*Before Swift 4.2, which implemented SE-0079, we would have to do something like:
someTask { [weak self] result in
    guard let strongSelf = self else { return }

    strongSelf.xxx = yyy
    strongSelf.doLongTermWork()
    strongSelf.finish()
}

You can see why we prefer the Swift 4.2 improvement, as this strongSelf syntax is inelegant.

*The other obvious alternative is just:
someTask { [weak self] result in
    self?.xxx = yyy
    self?.doLongTermWork()
    self?.finish()
}

Sometimes you need the "weak self - strong self dance" (the first two alternatives), but it would not appear to be the case here. This is likely sufficient.
There are other scenarios/edge cases that one might contemplate, but these are the basic approaches.

A: You can use it like this from Swift 4.2
someTask(completion: {[weak self] (result) in
    guard let self = self { return }

    //it safe when reach here always

    self.xxx = yyy
    self.doLongTermWork()
    self.finish()
})


text:
Q: Password protected site dialog Over the course of the last week I have been attempting to make a web-based application for work. I have successfully managed to create and implement everything to a point that it is functional.
I'm not sure if this last piece of the project I'm embarking on is even a possibility, but I also don't seem to know how to search for it, if it is.
The URL that is bookmarked on the work 'dashboard' (iPod) is password protected. Currently, after the splash screen, it presents the log in screen with the following fields displayed:

"Authentication Required
"www.adsomneum.com"
"user name"
"password"

What I'm wondering is if it is possible to remove, replace, or hide the line that reads "www.adsomneum.com" as this is my private website, and others at my work place have no need for information regarding it.
I'm using .htaccess and .htpasswd as my means for password protection.

A: You say you are using .htaccess and .htpasswd, so I'm guessing that means you are using auth-basic. In the config variables of your .htaccess file you should have one called AuthName - I think that the browser is displaying that. Do you have www.adsomneum.com as your AuthName? If so just change it to "private area" or "xyz tool" or something similar.

A: Normally there's an option of using AuthName in the .htaccess to set a name for the protected area (eg: "Admin Console" or "Member's Area").
BUT I'm fairly certain (and my quick testing just now confirms it) that iOS will only ever show the domain. I'm pretty sure this is for security reasons so there's no way around it.


text:
Q: Help Setting up Ruby on Rails and MySQL - Reward Offered I am desperately in need of help from any charitable ruby/rails experts out there. I really want to learn RoR, but I can't get anywhere because every time I get to the stage where I need to connect to the database, something is messed up. Here's what I've got going at the moment.
[ Mac OSX 10.6.6 --
Ruby 1.9.2 --
Rails 3.0.5 --
MySQL 5.5.10 ]
All of these are the latest versions, freshly installed, and running smoothly. I also have rvm installed. All I want to know is how I can set up a new Rails project using a MySQL database and connect to it properly. I have spent countless hours googling around and getting error after error after error.
Can anyone help me out by outlining step by step how I can just get a working rails project connected to a mysql database? If anyone can help me with this I will not only owe you my life, but I will make amazing web and interface designs for you for free and/or collaborate on your next project as a UI designer. I will in addition give you free photoshop/graphics advising for life.
I want to learn rails so so bad, but I am in over my head right now with this file configuration stuff and wasting massive amounts of time. Please help!

A: Give a look at this post here :http://freddyandersen.wordpress.com/2010/10/03/mysql-5-5-snow-leopard-and-rails/

A: You'll owe me your life!!!! WOW! Seriously, try this:
rails new example -d mysql

config.database.yml created
development:
  adapter: mysql2
  encoding: utf8
  database: example_development
  pool: 5
  username: root
  password:
  socket: /var/run/mysqld/mysqld.sock

Go into your new project
cd example

Then install gems needed (mysql2)
bundle install

Then create your database
rake db:create

Profit!
If you can't use /var/run/mysqld/mysqld.sock as a pointer to connect to your mysql, then edit it to look like this https://gist.github.com/878434 and customize the port and username/password


text:
Q: Forces and momentum in a hemispherical pipe. Consider the hemispherical pipe, where the measured force is the force upwards.
F (force on pipe = measured force) = mass flow rate times (u1 + u2)

My answer:
Part 1: If u2 is less than u1, that means there is a greater change in velocity and therefore momentum.
Part 2: Since u2 is less, that means according to the equation, the measured force will be smaller.
However my problem with this answer is that, friction is acting upwards against the fluid and will therefore have an upwards component. Does this not mean that the measured force should increase?
Two contradicting theories, anyone know which answer is correct?
Any help will be greatly appreciated!

A: Your answer to Part 1 is incorrect. There is a smaller change in velocity $(u_2+u_1)$ and momentum. However, your conclusion in Part 2 is correct : there is a smaller upward force on the hemisphere.
The water exerts outward and downward frictional forces on the hemisphere. The outward forces all have equal and opposite pairs, so they cancel out, but the downward forces add together. The net friction force on the hemisphere is downward.
So both arguments agree that friction decreases the upward force on the hemisphere.


text:
Q: convert struct to objective c array or class I m new for IOS. I have some source code for OS X and java. I was trying to convert to IOS.
In OS X, I have the following.
struct _NoteData {
    int number;             /** The Midi note number, used to determine the color */
    WhiteNote *whitenote;   /** The white note location to draw */
    NoteDuration duration;  /** The duration of the note */
    BOOL leftside;          /** Whether to draw note to the left or right of the stem */
    int accid;              /** Used to create the AccidSymbols for the chord */
};
typedef struct _NoteData NoteData;

@interface ChordSymbol : NSObject <MusicSymbol> {

    _NoteData notedata[20];/** The notes to draw */

}

_NoteData is like an array and class here.  number, whitenote,duration..are instance variable for _noteData.
I was trying to change struct to objective c class:
@interface  _NoteData:NSObject{
    @property NSInteger number_color;
   @property WhiteNote *whitenote;
   @property NoteDuration duration;
   @property BOOL leftside;
   @property NSInteger accid;
  };
    @interface ChordSymbol : NSObject <MusicSymbol> {

    _NoteData notedata[20];/** The notes to draw */

}

In my .m file, it has
+(BOOL)notesOverlap:(_NoteData*)notedata withStart:(int)start andEnd:(int)end {
    for (int i = start; i < end; i++) {

        if (!notedata[i].leftside) {
           return YES;
       }
   }
return NO;
}

!notedata[i] throw error expected method to read array element. I understand _NoteData is a class, not an array. What should I change?
In java:
 private NoteData[] notedata;

NoteData is a class, and notedata is an array which store NoteData.
Same method in java
 private static boolean NotesOverlap(NoteData[] notedata, int start, int end) {
    for (int i = start; i < end; i++) {
        if (!notedata[i].leftside) {
            return true;
        }
    }
    return false;
}

I feel all I need is to declare an array with _NoteData object.  How can I do that?

A: Objective-C is a superset of C, so you can use C struct in Objective-C code. You can keep your code in the first paragraph. You need to move the function declaration in ChordSymbol class's header file.
+(BOOL)notesOverlap:(NoteData*)notedata withStart:(int)start andEnd:(int)end;

In another Objective-C class's implementation file, call the Class function like this.
NoteData y[] = {
    { .leftside = YES },
    { .leftside = YES },
    { .leftside = YES },
    { .leftside = YES }
};

BOOL result = [ChordSymbol notesOverlap:y withStart:0 andEnd:3];
NSLog(@"%d",result);

Edit
You can use NSArray for this purpose. You create an array and populate its data with NoteData objects.
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:20];
NoteData *data1 = [[NoteData alloc] init];
data1.number_color = 1;
[array addObject:data1];

Then you should change (_NoteData*)notedata to (NSArray*)array, and it should work.


text:
Q: Expected maximum of Laplacian random variables Let $X={x_1, x_2,...,x_n}$ be Laplacian iid random variables with mean zero and scale $b$. Let $Y = \max(X)$.
Is there a closed-form expression for the expectation $E(Y)$? If not, is there any non-trivial lower bound that depends on $n$?

A: The cumulative distribution $F(y)$ of $Y$ is the product of the cumulative distributions $f(x)$ of $X$, because
$$F(y)=P[(X_1<y)\cap(X_2<y)\cap\cdots\cap(X_n<y)]=\{f(y)\}^n.$$
Hence
$$F(y)=2^{-n}e^{(n/b)(y-\mu)}\;\;\text{if}\;\;y<\mu,$$
$$F(y)=\left[1-\tfrac{1}{2}e^{-(y-\mu)/b}\right]^n\;\;\text{if}\;\;y>\mu.$$
The expectation value follows upon integration,
$$\mathbb{E}[Y]=\mu+\int_{\mu}^\infty [1-F(y)]\,dy-\int_{-\infty}^\mu F(y)\,dy=\mu+bc_n.$$
(I allow for nonzero mean $\mu$.)
I don't have a closed form expression for the coefficients $c_n$, the values for $n=1,2,3,\ldots 10$ are

$$0,\frac{3}{4},\frac{9}{8},\frac{133}{96},\frac{305}{192},\frac{281}{160},\frac{3647}{1920},\frac{217687}{107520},\frac{153093}{71680},\frac{1442363}{645120}.$$

A: This is to complement Carlo Beenakker's answer by providing a lower bound on the integral in question:
$$\begin{aligned}J_n&:=\int_0^\infty[1-(1-e^{-y}/2)^n]\,dy \\
&>\int_0^\infty[1-\exp\{-ne^{-y}/2\}]\,dy \\
&=\gamma+\ln(n/2)+\int_{n/2}^\infty e^{-t}\frac{dt}t \\
&>\gamma+\ln(n/2)=:L_n,
\end{aligned}\tag{1}$$
where $\gamma=0.577\ldots$ is the Euler gamma; details on the evaluation of the second integral in the above display will be given at the end of this answer.

The lower bound $L_n$ on the integral $J_n$ is asymptotically exact, as we have the following upper bound on $J_n$:
$$\begin{aligned}J_n&=\int_0^1[1-(1-t/2)^n]\,\frac{dt}t \\
&<\int_0^1[1-\max(0,1-nt/2)]\,\frac{dt}t \\
&=\int_0^{2/n}[1-(1-nt/2)]\,\frac{dt}t+\int_{2/n}^1\frac{dt}t \\
&=1+\ln(n/2)\sim L_n.
\end{aligned}$$

Here is a graph of the ratio $J_n/L_n$:

Details on the evaluation of the second integral in display (1): With $m:=n/2$, the integral in question is
$$\begin{aligned}
K_m:=\int_0^\infty[1-\exp\{-me^{-y}\}]\,dy
=\int_0^1[1-\exp\{-m t\}]\,\frac{dt}t
=\int_0^m[1-e^{-u}]\,\frac{du}u.
\end{aligned}$$
By the fourth display on p. 31,
$$\begin{aligned}\gamma&=\int_0^\infty\Big(\frac1{1+u}-e^{-u}\Big)\frac{du}u \\
&=\int_0^m\Big(\frac1{1+u}-e^{-u}\Big)\frac{du}u
+\int_m^\infty\frac{du}{(1+u)u}
-\int_m^\infty\frac{e^{-u}du}u.
\end{aligned}$$
So,
$$\begin{aligned}
&-K_m+\gamma+\ln m+\int_m^\infty e^{-t}\frac{dt}t \\
&=\int_0^m\Big(\frac1{1+u}-1\Big)\frac{du}u
+\int_m^\infty\frac{du}{(1+u)u}
+\ln m=0,
\end{aligned}$$
as claimed.


text:
Q: Usar min() y max() de un array con php El siguiente ejemplo me guarda en la variable $min el numero mas chico de la lista que esta en el array
$array = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$min=min($array);
echo"$min";

Mi pregunta: Lo que yo necesito es que me busque el numero mas chico despues del 1 o sea que me indique la variable $min que el numero mas chico es el 1 y no el 0 como es el caso anterior. espero que se entienda.
Muchas gracias.

A: Usando array_filter puedes obtener un array que excluya todos los elementos menores a 1. Después, solo usas min con ese array.
$array = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$min = min(array_filter($array, function($item) {
    return $item > 0;
}));
echo $min;


text:
Q: Changing readonly variable declared in super class inside subclass SWIFT I am an old objective-c developer trying to get my feet dirty in Swift, but I had the following problem:
we have a super class
class MySuper  {
     private(set) var myReadOnlyVar = true
}

and then I have subclass of MySuper
class Subclass: MySuper {
     func myFunc() {
         super.myReadOnlyVar = false        // error
     }
}

Any workaround I can make here ? I know that swift has no protected access, but it should have something similar.

A: You need to change the Subclass implementation to this
class SubClass: MySuper {
    func myFunc() {
        super.setValue(false, forKey: "myReadOnlyVar")
    }
}


text:
Q: How to calculate ProgressBar percentage for daily drink water I made an app about android water drinking monitor. But it does the wrong calculation as a percentage. What do you think I might have done wrong.
(When the progress bar is 100 at 100, the daily water calculation is wrong)
waterml = sharedPreferences.getInt(WATER_ML, 0);
waterdata = sharedPreferences.getInt(WATER_DATA, 0);
int dailywater = 2838; // example
ml100.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
       //scale 100 ml
        int percent = 100  * 100 / dailywater;
        ProgressBarAnimation anim = new ProgressBarAnimation(circlebar, waterdata, (waterdata + percent));
        anim.setDuration(300);
        circlebar.startAnimation(anim);
        dailywater.setText((waterml + 100) + " / " + dailywater + " ml");
        editor = sharedPreferences.edit();
        editor.putInt(WATER_DATA, (waterdata + percent));
        editor.putInt(WATER_ML, (waterml + 100));
        editor.apply();
    }
});
////
public static class ProgressBarAnimation extends Animation {
    private CircleProgressBar progressBar;
    private float from;
    private float to;
    ProgressBarAnimation(CircleProgressBar progressBar, float from, float to) {
        super();
        this.progressBar = progressBar;
        this.from = from;
        this.to = to;
    }
    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        super.applyTransformation(interpolatedTime, t);
        float value = from + (to - from) * interpolatedTime;
        progressBar.setProgress((int) value);
    }
}

A: It seems to me like your code, namely editor.apply(); is working as follows:
you are trying to save the progress and it occurs that sometimes it is called multiple times in a row. According to documentation if you are sending several apply() or commit() commands only the last one will be executed. Therefore, some clicks might not be processed.
I suggest you simply changing your variable for progress and saving it later:
waterml = sharedPreferences.getInt(WATER_ML, 0);
waterdata = sharedPreferences.getInt(WATER_DATA, 0);
int dailywater = 2838; // example
ml100.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        //scale 100 ml
        int percent = 100  * 100 / dailywater;
        ProgressBarAnimation anim = new ProgressBarAnimation(circlebar, waterdata, (waterdata + percent));
        anim.setDuration(300);
        circlebar.startAnimation(anim);
        dailywater.setText((waterml + 100) + " / " + dailywater + " ml");

        waterdata += percent;
        waterml += 100;
    }
});

and then in your onPause() function you simply save them:
public void onPause() {
    editor = sharedPreferences.edit();
    editor.putInt(WATER_DATA, waterdata);
    editor.putInt(WATER_ML, waterml);
    editor.apply();
}

If you want your percent not to be rounded, you could change putInt to putFloat and getInt to getFloat


text:
Q: R - Clarifications on the expiration of Google's JSON tokens for the Gmail API if application is in "Testing" phase BACKGROUND INFO
I have developed an application in R through the shiny package, and deployed it online through the shinyapps.io service.
Among its different functions, the shiny app can send emails (through my personal Google Account) to users if the fill a form. The emails are sent through the functionalities of the gmailr package, and to make it work I had to follow the procedure on the Google Cloud Platform to create a JSON token, configure the OAuth consent screen, and store the credentials I obtain in a folder of my R project. All the steps to this process are reported at the end of this GitHub issue I opened a while ago.
THE PROBLEM
The JSON token I generated on the Google Cloud Platform expires after some days.
After googling around, I noticed that this can happen if my "Application", on Google Cloud, is still in the Testing phase. First question about this statement:

*

*What does it mean when Google refers, on the OAuth screen, as an Application in Testing phase? My application is already online on shinyapps.io, it's already functioning, and when I create a new token it can also send emails correctly (for a while).

In addition, on the Google's OAuth consent screen, I now have the possibility to "publish" such application. If I do that, the status changes as In production, and this message is displayed. Other questions:

*

*What does it mean that the application will be available to everyone with a Google account? My application deployed on shinyapps.io doesn't require any login or any other data from the users, then what is this app they're talking about?

*What will happen to users that try to connect to my application?

*Are my credentials, as for example the JSON file, safe?

I know that there might be a lot of confusion in this post, but I am relly not an expert in this field, and so I am worried to make some mistakes.
Thanks a lot for your help!

A: The GMail API, OAuth and all, is typically meant to allow your app to send email on behalf of any user. It seems your use-case is a little different - you only ever need to connect one user: your own.

What does it mean when Google refers, on the OAuth screen, as an **Application in Testing phase? My application is already online on shinyapps.io, it's already functioning, and when I create a new token it can also send emails correctly (for a while).

I think you mostly answered this yourself in your further questions. Google thinks you're building an app that any GMail user can connect to, and so for security reasons, they want to differentiate between a test app and a production app. They don't necessarily know whether or not your app is published on shinyapps.io.

What does it mean that the application will be available to everyone with a Google account? My application deployed on shinyapps.io doesn't require any login or any other data from the users, then what is this app they're talking about?

I alluded to this earlier, but the GMail API is intended for apps that allow any GMail user to connect and manipulate their own email. Imagine a third-party email client, or similar. Again - Google's wording sounds a bit odd wrt your app since it doesn't fit that bill.

What will happen to users that try to connect to my application?

If you don't explicitly host your own server that implements OAuth with Google, then nobody can even try to connect. As long as you don't leak the shared secret from your Google Cloud Platform entry, you're safe.

Are my credentials, as for example the JSON file, safe?

Probably anyone with the JSON file can send email on your behalf. Marking your app as 'in production' will not change the security implications of your JSON file.

Unfortunately, Google has pretty tight security around their APIs nowadays. If you want to mark your app as "in production" you might open up a can of worms regarding "restricted scopes" (sending email counts as restricted). However, since you're using the JSON file instead full OAuth, I'm not sure if this applies to you. To my knowledge, you should be safe to try marking your app as "in production". Worst-case scenario, you might be able to weasel around the strict verification requirements by saying your app is "internal":

Internal Use: The app is used only by people in your Google Workspace or Cloud Identity organization. Note that your app will not be subject to the unverified app screen or the 100-user cap if it's marked as Internal.


text:
Q: База mongodb распухает после восстановления из дампа Есть mongo версии 4.0.6 установленная на ubuntu server 16.04.
При восстановлении базы из дампа происходит увеличение ее объема, примерно раза в два. С чем может быть связан такой забавный глюк и как с ним бороться ?
Помимо прочего было замечено еще, что время от времени база начинает пухнуть после рестарта. В логах ничего подозрительного не наблюдается.


text:
Q: How can I do a string object comparison between two csv files in Pandas (Python 2.7) and generate a new dataframe or csv file I am reading two .csv files, "CSV_1" & "CSV_2".  For the most part, they have different columns and data besides the columns I will be using as my string key.
The elements per row in the four columns (basically my key) need to be identical in both in order to concatenate the data from CSV_2 to the end of each row that matches in CSV_1.
The four columns in both csv files are "Date" (format: Month/Day/Year), "Hour" (format: 0-23), "Make", & "Model" and are str obj datatypes.
It would basically read the 1st row in csv_1 and take those four factors, then look through CSV_2 and find any instance the elements of those four columns.  Once it finds a match in both, I want to take all the columns in CSV_1 and CSV_2 and concatenate the columns into a new dataframe without duplicating the "Date", "Hour", "Car", & "Model" columns since they would be identical in both. Isuppose I could delete the duplicate columns from the new dataframe.
I am sure there will be a few instances where there wont be any  matches, I would still need that data as well, so I guess I would need to fillna or something to just generate blank cells at the end of the row from CSV_1 for each column added from CSV_2 before adding the row to the new dataframe.
I generated fake data for the example, but it should do something like this with the outputs (except the data is read from the two csv files, I cannot provide a snippet for the actual code)
CSV_1:
import pandas as pd
from pandas import DataFrame

date = ['5/10/2012', '10/17/2012', '1/2/2013', '5/3/2014']
hr = ['1', '0', '23', '13']
make = ['Honda', 'Toyota', 'Chevy', 'Honda']
model = ['Accord', 'Camry', 'Sonic', 'Civic']
gas = ['9', '9', '7','8']
safe = ['8', '10', '6','7']

dataSet = zip(date, hr, make, model, gas, safe)
df = pd.DataFrame(data = dataSet, columns=['Date', 'Hour', 'Make', 'Model', 'Gas Rating', 'Safety Rating'])
>>>df

CSV_2:
make2 = ['Honda', 'Toyota', 'Honda']
model2 = ['Accord', 'Camry', 'Civic']
mile = ['10', '10','9']
speed = ['7', '7', '6']

dataSet2 = zip(date, hr, make2, model2, mile, speed)
df2 = pd.DataFrame(data = dataSet2, columns=['Date', 'Hour', 'Make', 'Model', 'Mileage Rating', 'Speed Rating'])
>>>df2

Here is where the string key comparison should come into play and basically give me the output of the following code (The headers will always be the same, but the amount of data will not, there are actually close to 100+ columns in both)
Final_df:
date = ['5/10/2012', '10/17/2012', '1/2/2013', '5/3/2014']
hr = ['1', '0', '23', '13']
make = ['Honda', 'Toyota', 'Chevy', 'Honda']
model = ['Accord', 'Camry', 'Sonic', 'Civic']
gas = ['9', '9', '7', '8']
safe = ['8', '10', '6', '7']
mile = ['10', '10', ' ','9']
speed = ['7', '7', ' ', '6']

dataSet3 = zip(date, hr, make, model, gas, safe, mile, speed)
df3 = pd.DataFrame(data = dataSet3, columns=['Date', 'Hour', 'Make', 'Model', 'Gas Rating', 'Safety Rating', 'Mileage Rating', 'Speed Rating'])
>>>df3

A: Initially, you requested joining on 4 different columns (Make, Model, Date, Hour), but second table really only had two matching (Make, Model).
Outer join will still apply, but the original answer is correct:
In [8]: df
Out[8]:
         Date Hour    Make   Model Gas Rating Safety Rating
0   5/10/2012    1   Honda  Accord          9             8
1  10/17/2012    0  Toyota   Camry          9            10
2    1/2/2013   23   Chevy   Sonic          7             6
3    5/3/2014   13   Honda   Civic          8             7

In [9]: df2
Out[9]:
         Date Hour    Make   Model Mileage Rating Speed Rating
0   5/10/2012    1   Honda  Accord             10            7
1  10/17/2012    0  Toyota   Camry             10            7
2    1/2/2013   23   Honda   Civic              9            6

In [10]: final = pd.merge(df,df2, how='outer', on=['Date', 'Hour', 'Make', 'Model'])

In [11]: final
Out[11]:
         Date Hour    Make   Model Gas Rating Safety Rating Mileage Rating  \
0   5/10/2012    1   Honda  Accord          9             8             10
1  10/17/2012    0  Toyota   Camry          9            10             10
2    1/2/2013   23   Chevy   Sonic          7             6            NaN
3    5/3/2014   13   Honda   Civic          8             7            NaN
4    1/2/2013   23   Honda   Civic        NaN           NaN              9

  Speed Rating
0            7
1            7
2          NaN
3          NaN
4            6

In [12]: final.fillna(0, inplace=True)

In [13]: final
Out[13]:
         Date Hour    Make   Model Gas Rating Safety Rating Mileage Rating  \
0   5/10/2012    1   Honda  Accord          9             8             10
1  10/17/2012    0  Toyota   Camry          9            10             10
2    1/2/2013   23   Chevy   Sonic          7             6              0
3    5/3/2014   13   Honda   Civic          8             7              0
4    1/2/2013   23   Honda   Civic          0             0              9

  Speed Rating
0            7
1            7
2            0
3            0
4            6


text:
Q: How to allow nodes of one GKE cluster to connect to another GKE I have a GKE clusters setup, dev and stg let's say, and wanted apps running in pods on stg nodes to connect to dev master and execute some commands on that's GKE - I have all the setup I need and when I add from hand IP address of the nodes all works fine but the IP's are changing,
so my question is how can I add to Master authorised networks the ever-changing default-pool IPs of nodes from the other cluster?

EDIT: I think I found the solution, it's not the node IP but the NAT IP I have added to authorized networks, so assuming I don't change those I just need to add the NAT I guess, unless someone knows better solution ?

A: I'm not sure that you are doing the correct things. In kubernetes, your communication is performed between services, that represents deployed pods, on one or several nodes.
When you communicate with the outside, you reach an endpoint (an API or a specific port). The endpoint is materialized by a loadbalancer that routes the traffic.
Only the kubernetes master care about the node as resources (CPU, memory, GPU,...) provider inside the cluster. You should never have to directly reach the node of a cluster without using the standard way.
Potentially you can reach the NodePort service exposal on the NodeIP+servicePort.

A: What you really need to do is configure the kubectl in jenkins pipeline to connect to GKE Master IP. The master is responsible for accepting your commands (rollback, deployment, etc). See Configuring cluster access for kubectl
The Master IP is available in the Kubernetes Engine console along with the Certificate Authority certificate. A good approach is to use a service account token to authenticate with the master. See how to Login to GKE via service account with token.


text:
Q: How not to supply values to a webMethod I'm working on implementing a webMethod for a webService which has the following header:
 public string addDocument(string docName, int docSize, string docType, string docDestinationPath, int newArch, string archName , int parentID, int archiveID )

When newArch == 0 -> no need to supply parentID value
but when newArch ==1 -> all the values should be supplied
I've tried to supply a default value when parentID isn't supplied
 public string addDocument(string docName, int docSize, string docType, string docDestinationPath, int newArch, string archName="" , int parentID=0, int archiveID=0)

but that didn't work !
What should I do to avoid this error
" Input string was not in a correct format."

A: Have two methods:
public string addDocumentNewArch(string docName, int docSize, string docType, string docDestinationPath, string archName , int parentID, int archiveID )

public string addDocumentOldArch(string docName, int docSize, string docType, string docDestinationPath, string archName , int archiveID )

This will make it very clear to the caller what they are doing.


text:
Q: Best way to run some code only once on server start in Nuxt.js (and not during build) While I wrote this answer for StackOverflow I came across the problem that I wanted to execute some code exactly once in Nuxt.js when the server is started (or while the server is starting).
I thought about writing a module or a plugin, but I did not succeed, since both were executed every time I contacted the server, i.e., every time I made a call to localhost:3000/myPage.
Probably I am missing the right module hook or some plugin setting?
Since I could not find any information on this problem in the official documentation, I now came up with a quite ugly solution: I wrote a serverMiddleware that executes some code (the code that should be run only once) and then returns an empty handler - which now adds (little) unnecessary overhead to every request.
My question: What would have been the best way to execute some code exactly once on a Nuxt.js server during/after startup, but not during building?

Minimal ugly working example:
nuxt.config.js:
export default {
  ...
  serverMiddleware: [ "~/serverMiddleware/run-once.js" ]
  ...
}

~/serverMiddleware/run-once.js:
console.log("Yay, I only run once when the server is started!")
// Since we are a serverMiddleware, we have to return a handler, even if this it does nothing
// I think this is really ugly...
export default function (req, res, next) {
  next()
}

PS: I saw questions such as Is it possible for Nuxt JS plugins to only run once? but it seems to not answer my question since the vue-renderer:ssr:prepareContext nuxt hook also executes every time I send a request to the server.
Also, a module such as the following does not work since it is also executed during nuxt build and not only on nuxt dev or nuxt start:
export default function MyModuleThatShouldOnlyRunOnce (_moduleOptions) {
  console.log("I run on 'nuxt dev' and 'nuxt start', but sadly also on 'nuxt build' :(");
}

A: I don't know if this topic is still relevant, but you can solve this using a 'ready' hook:
First create a file like this (./hooks/hooks.js):
export default (nuxtConfig) => ({
    ready: () => {
        // Execute your code here
    }
});

Then add it to your nuxt.config.js:
import hooks from './hooks/hooks';

export default {

    // Other stuff

    hooks: hooks(this),

    // Other stuff

}


text:
Q: AttributeError: module 'pyexpat.model' has no attribute 'eval' I have an evaluate function that performs testing after training the model. The function runs very well without any errors however I want to link the function to a tkinter button so that when the button is pressed, the testing can be done. I have created the button and fed the function to the command argument of the button but when I press the button, the model.eval() throws this error module 'pyexpat.model' has no attribute 'eval'. Below is my code for demostration:
def evaluate(model, dataloader, data_min, data_max,  label_max, label_min):
    model.eval()
    for i in range(1):
        data, label =iter(dataloader).next()
        pred = model(data)

def main(args):
    global data_max, data_min, label_max, label_min, model, dataloader_valid
    data_min = -20
    data_max = 38
    label_min = 1500
    label_max = 4500

    dataset_valid = torch.load(args.val_anno)
    dataloader_valid = torch.utils.data.DataLoader(
    dataset_valid, batch_size=args.batch_size, shuffle=True)
    model = network.model_dict[args.model]()
    chkpnt = torch.load(args.resume, map_location='cpu')
    model.load_state_dict(chkpnt['model'])

    evaluate(model, dataloader_valid, data_min, data_max, label_min, label_max)

def parse_args():
    import argparse
    parser = argparse.ArgumentParser(description='Testing')
    args = parser.parse_args()
    return args

def combineFunc(*funcs):
    def combinedFunc(*args, **kwargs):
        for f in funcs:
            f(*args, **kwargs)
    return combinedFunc

model_button = customtkinter.CTkButton(master=root, image = Inv, text="", corner_radius=1, fg_color="white", command = combineFunc(
      lambda: evaluate(model, dataloader_valid, data_min, data_max, label_min, label_max),
      lambda: args,
      lambda: main(args)))


text:
Q: Not able to initialize the array in sequence, in-order to avoid the verbosity of code Not able to initialize the array in sequence. Actually, I want to construct the message with the length of 64. providing 64 array indexes, the code looks longer and verbose. I want to do it in sequence in order to avoid verbosity.

But I initialized an array like this buf[]  and I tried as buf[6]  also that didn't work either.
error: expected expression before ']' token

Does anyone tell how to do it? Isn't it possible in C to initialize an array in different line not at declaration?

ARRAY_SIZE just give the count of array indexes.
Code:
void a_test(char in) {

    uint8_t buf[256];
    int i;

    char cmd = in;

    if (cmd == 'a') {
        // it doesn't work like this
        buf[] = { 0xfe, 0xb0, 0x01, 0x22, 0x00, 0x00};

        /* it works like this
        buf[0] = 0xfe;
        buf[1] = 0xb0;
        buf[2] = 0x01;
        buf[3] = 0x22;
        buf[4] = 0x00;
        buf[5] = 0x00; */
    }

    if (cmd == 'b') {
        buf[] = { 0x44, 0xb0, 0x01, 0x03, 0x00};
    }

    for (i = 0; i < ARRAY_SIZE(buf); i++) {
        printf("%02x ", buf[i]);
    }
}

int main() {
  a_test('a');
  return 0;
}

A: You can't use :
buf[] = { 0xfe, 0xb0, 0x01, 0x22, 0x00, 0x00};

except if it is in the declaration e.g:
uint8_t buf[]= { 0xfe, 0xb0, 0x01, 0x22, 0x00, 0x00};

Another way to pass all the values in one statement would be using memcpy:
memcpy(buf, (uint8_t[]) { 0xfe, 0xb0, 0x01, 0x22, 0x00, 0x00 }, sizeof (buf));

A: Arrays do not have the assignment operator but structures do have. So you can wrap an array in a structure.
That is you can do something like the following.
#include <stdio.h>
#include <stdint.h>

void a_test( char in )
{
    struct Array
    {
        size_t n;
        uint8_t buf[256];
    } a = { 0 };

    switch ( in )
    {
    case 'a':
        a = ( struct Array ) { 6, { 0xfe, 0xb0, 0x01, 0x22, 0x00, 0x00 } };
        break;

    case 'b':
        a = ( struct Array ) { 5, { 0x44, 0xb0, 0x01, 0x03, 0x00 } };
        break;
    }

    for ( size_t i = 0; i < a.n; i++ )
    {
        printf( "%02x ", a.buf[i] );
    }
    putchar( '\n' );
}

int main(void)
{
    a_test( 'a' );
    a_test( 'b' );

    return 0;
}

The program output is
fe b0 01 22 00 00
44 b0 01 03 00


text:
Q: How can i add an if else statement to this SQL trigger that calls a Function I have a SQL trigger that calls a function to split the file name from a delimeter. the problem is that the first string determines how to split the data. my question is how can i keep adding to this statement.
USE [dw1]
GO
/****** Object:  Trigger [dbo].[SplitFileName]    Script Date: 03/02/2015 14:18:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER TRIGGER [dbo].[SplitFileName]
   ON  [dbo].[DOCUMENTS]
   AFTER INSERT
AS
BEGIN
    SET NOCOUNT ON;
    declare @varDWDOCID int, @varFILENAME nvarchar(255), @varDEALER_NUM nvarchar(255), @varINVOICE_NUMBER nvarchar(255), @varWEEK_ENDING nvarchar(255), @varDOCTYPE nvarchar(255)
    Select
      @varDWDOCID = inserted.[DWDOCID],
      @varFILENAME = isnull(inserted.[FILENAME],''),
      @varDEALER_NUM = isnull(inserted.[DEALER_NUM],''),
      @varINVOICE_NUMBER = isnull(inserted.[INVOICE_NUMBER], ''),
      @varWEEK_ENDING = isnull(inserted.[WEEK_ENDING],''),
      @varDOCTYPE = isnull(inserted.[DOCTYPE],'')
      from inserted
-- =============================================
-- Author:                            <Name>
-- Create date: 3/2/2015
-- Description: Split document based on dash and also calling a function...
-- =============================================

;WITH cte AS
  (
  SELECT t.dwdocid, t.FILENAME, t.DEALER_NUM, t.INVOICE_NUMBER, t.WEEK_ENDING, t.DOCTYPE,
         NewDOCTYPE = MAX(CASE WHEN o.level = 1 THEN o.val END) OVER(),
         NewDEALER_NUMBER = MAX(CASE WHEN o.level = 2 THEN o.val END) OVER(),
         NewWEEK_ENDING = MAX(CASE WHEN o.level = 3 THEN o.val END) OVER(),
         NewINVOICE_NUMBER = MAX(CASE WHEN o.level = 4 THEN o.val END) OVER()
  FROM dbo.DOCUMENTS_CHRIS t CROSS APPLY dbo.SplitStrings_CTE(t.FILENAME, '-') o where t.DWDOCID=@varDWDOCID and LEFT(FILENAME, 12) ='123InvoiceIn'
  )
Update cte
SET DOCTYPE=NewDOCTYPE,
DEALER_NUM=NewDEALER_NUMBER,
WEEK_ENDING=NewWEEK_ENDING,
INVOICE_NUMBER=NewWEEK_ENDING
FROM inserted
END
/*
;WITH cte AS
 (
  SELECT r.dwdocid, r.FILENAME, r.DEALER_NUM, r.INVOICE_NUMBER, r.WEEK_ENDING, r.DOCTYPE,
         NewDOCTYPE = MAX(CASE WHEN o.level = 1 THEN o.val END) OVER(),
         NewINVOICE_NUMBER = MAX(CASE WHEN o.level = 2 THEN o.val END) OVER()
         NewDEALER_NUM = MAX(CASE WHEN o.level = 3 THEN o.val END) OVER(),
         NewWEEK_ENDING = MAX(CASE WHEN o.level = 3 THEN o.val END) OVER(),
         FROM dbo.DOCUMENTS_CHRIS r CROSS APPLY dbo.SplitStrings_CTE(r.FILENAME, '-') o where t.DWDOCID=@varDWDOCID and LEFT(FILENAME, 13) ='123InvoiceOut'
  )
Update cte
SET DOCTYPE=NewDOCTYPE,
DEALER_NUM=NewDEALER_NUMBER,
WEEK_ENDING=NewWEEK_ENDING,
INVOICE_NUMBER=NewWEEK_ENDING
FROM inserted
END*/

How can i add the '123InvoiceOut' in like a If..Else statement so it will execute at the same time?


text:
Q: What is this regulators package ? I'm reverse engineering / hacking a Chinese board which has the footprint for this regulator which i want to replace. I am not quite sure what the package is though, I'm certain someone here does.

A: It's a D-Pak aka TO-252.
The ST datasheet for 78M05 shows this as a standard package for this part.

A: Looks like D-PAK (TO-252AA)
Dimension E should be 6.5mm, and e ~2.3mm


text:
Q: Creating popup window with a text input for CakePHP I'm using CakePHP 2.3.8 and I want to create a popup upon clicking a link that will have a textxbox input. For example, click a refund button/link, and then a popup appears with an input for the refund amount.
I know how to make confirmation boxes from a link, but I have no idea how to add a text box to it or how to modify it in any way. Ex:
echo $this->Html->link('Something', array('controller' => 'mycontroller', 'action' => 'dosomething', 6),array(),"Are you sure you wish to do something?");

Can I do this with the form helper, or is it something I need JavaScript/jQuery for?
edit I called a friend and he figured it out. He wasn't sure how to do it with the linkhelper, but was able to do it with the formhelper.
echo $this->Form->create('refund',array('onsubmit'=>'return prompt("Refund Value");'));

A: If you read the Cake DOCs, all the Cake form helper does is help you create javascript on the server side which will then be created on the client side.
All in all it will work out better if you write your own javascript than if you rely on Cake's functions in which you basically write javascript into PHP function which will then output to the client anyway.


text:
Q: How to attribute each datapoint to a specific buffer ID I have many datapoints within 57 buffers in GIS (see picture for an example of a couple of the. buffers with datapoint inside). I need to be able to analyze each buffer separately, and therefore need a unique ID representing which data point comes from which buffer.
If I don't 'export by location' iteratively, and just have one layer with all the points extracted from the buffer, is there a way to make GIS attribute each datapoint with an ID that indicates which buffer that data point is within?

A: On your datapoints layer (red in the screenshot below), create a new attribute with field calculator using this expression:
array_first (overlay_nearest('buffer',$id))

Replace buffer with the name of your buffer layer. Where two buffers overlap, you'll get the id of the "closer" one: the one with the nearest centroid.
Red datapoints labeled with the id of the buffer: