text:
Q: BibDesk to Word via bibfuse: some coding I have recently started working with clinical colleagues who think LaTeX is a synthetic rubber used to make examination gloves, and have been forced to work with MS Word. In my Tex setup, I use BibDesk as my reference manager on a Mac OS, and have found bibfuse to be a nice way of citing papers in Word from BibDesk. The problem is that bibfuse seems to only be able to handle citing journal articles. It does not work very well at citing books, book entries (i.e., "incollection" entries in BibDesk), and websites. Does anyone know how to add to or modify the sampletemplate.doc file in the bibfuse package to accept these entries? The sampletemplate.doc file contains only the following lines of code:
<$publications>
<$itemIndex/>.
<$pubAuthors.unpunctuatedAbbreviatedNormalizedName.stringByRemovingTeX.@componentsJoinedByCommaAndAmpersand/> (<$pubFields.Year/>) <$pubFields.Title/>. <$pubFields.Journal/>
<$pubFields.Volume/>, <$pubFields.Pages/>.
</$publications>

If no one knows how to do that, can anyone tell me what language this is, so I might figure it out and modify if possible?

A: I have been playing with BibFuse, and have improved it for my own use.  It provides a very nice way to integrate Word with BibTeX (via BibDesk).  I am using it on Mac OS X.
You can get a lot of information from BiBDesk's help file (under the Appendix "Template Tags").  The language is Apple's Key-Value Coding.
Here is the template I have developed for my references:
<$publications>
<$pubType=article?>
<$authors.abbreviatedNormalizedName.stringByRemovingCurlyBraces.@componentsJoinedByCommaAndAmpersand/> <$fields.Year.stringByAppendingCommaAndSpaceIfNotEmpty/><$fields.Journal.stringByDeTeXifyingString/>, <$fields.Volume.stringByRemovingTeX/>, <$fields.Pages.stringByAppendingFullStopIfNotEmpty/>
<?$pubType=inproceedings?>
<$authors.abbreviatedNormalizedName.stringByRemovingCurlyBraces.@componentsJoinedByCommaAndAmpersand/> <$fields.Year.stringByAppendingCommaIfNotEmpty/> in <$fields.Series.stringByAppendingCommaIfNotEmpty/> Vol. <$fields.Volume.stringByAppendingCommaIfNotEmpty/> <$fields.Booktitle.stringByAppendingCommaIfNotEmpty/> ed. <$editors.abbreviatedName.stringByRemovingCurlyBraces.stringByAppendingCommaIfNotEmpty.@componentsJoinedByCommaAndAnd/> <$fields.Pages/>.
<?$pubType=book?>
<$authors.abbreviatedNormalizedName.stringByRemovingCurlyBraces.@componentsJoinedByCommaAndAmpersand/> <$fields.Year.stringByAppendingCommaAndSpaceIfNotEmpty/><$fields.Title.stringByTeXifyingString.stringByRemovingCurlyBraces/>.
<?$pubType?>
<$authors.abbreviatedNormalizedName.stringByRemovingCurlyBraces.@componentsJoinedByCommaAndAmpersand/> <$fields.Year.stringByAppendingCommaAndSpaceIfNotEmpty/><$fields.Journal.stringByDeTeXifyingString/>, <$fields.Volume.stringByRemovingTeX/>, <$fields.Pages.stringByAppendingFullStopIfNotEmpty/>
</$pubType?>
</$publications>

This works for entries for articles, proceedings, and books.
This language is very sensitive to the syntax.  One misplaced character and it doesn't work!
Good luck!


text:
Q: How do I make a battery indicator? I want to make a battery indicator where there is only one red LED that would light up when the battery drops below a 3V.
Components I want to include in this circuit
-Transistor(BJT)(2N3904)
-Zener diode
pls tell me how do I built the circuit

redpajama_set_name: RedPajamaStackExchange


text:
Q: intelligently using the ellipsis in an R function I had a function with a signature like this:
myFunction=function(class="Class",v1='y',v2='y',dfparam=df){

where df is a dataframe and it is assumed that there is an attribute called Class in df.    I wanted to make it more general so that it can accept a variety of dataframes, df, not just one that has an attribute called Class.
So I added in a className parameter and classValue parameter to replace the class parameter. Also, I want to allow unlimited arguments v1, v2, v3 etc. and so I am using the elipsis like this:
myFunctionGeneral = function(className="Class", classValue="democrat", dfparam=df, ...){
  arguments <- list(...)

Prior to using the elipsis, I had a line that used the arguments as follows:
X_bool=dfparam$V1==v1 & dfparam$V2==v2

I started out doing this:
X_bool=dfparam[,2]==arguments[1] & dfparam[,3]==arguments[2]

but I want to do this for an unlimited number of possible paremeters in the elipsis.
So I need to expand this statement by somehow unraveling the ellipsis.
Here is an example:
install.packages("vcd")
library(vcd)
data(Arthritis)
AAr=Arthritis[,-c(1,4)]

myFunctionGeneral=function(className="Class",classValue="democrat",dfparam=df, ...){

  dfparam$names<-rownames(dfparam)
  arguments<-list(...)

  dfparamDroppedClass=dfparam[,-1]
  #X_bool=dfparam[,2]==arguments[1] & dfparam[,3]==arguments[2]
  X_bool=do.call(all, Map("==", dfparamDroppedClass, arguments))

  X=dfparam[X_bool,]

}

A: This should illustrate the principle:
arguments <- list(1, 2, 3)
params <- list(1, 2, 3)
do.call(all, Map("==", arguments, params))
#[1] TRUE

params <- list(1, 2, 4)
do.call(all, Map("==", arguments, params))
#[1] FALSE

All is equivalent to an arbitrary number of &, and Map iterates == over the two lists.
Edit:
Apparently your data.frame has more than one observation. Then you can't use all, but need to use Reduce as in Reduce("&", Map("==", arguments, params)). With your example:
myFunctionGeneral=function(className="Class",classValue="democrat",dfparam=df, ...){

  dfparam$names<-rownames(dfparam)
  arguments<-list(...)

  dfparamDroppedClass=dfparam[, -c(1, 4)]
  #X_bool=dfparam[,2]==arguments[1] & dfparam[,3]==arguments[2]
  X_bool=Reduce("&", Map("==", dfparamDroppedClass, arguments))

  dfparam[X_bool,]
}

myFunctionGeneral('Treatment','Placebo',AAr,'Male','Marked')
#   Treatment  Sex Improved names
#4    Treated Male   Marked     4
#5    Treated Male   Marked     5
#6    Treated Male   Marked     6
#8    Treated Male   Marked     8
#14   Treated Male   Marked    14
#52   Placebo Male   Marked    52


text:
Q: Reasons to disable / enable SELinux In the line of this question on StackOverflow and the completely different crowd we have here, I wonder: what are your reasons to disable SELinux (assuming most people still do)? Would you like to keep it enabled? What anomalies have you experienced by leaving SELinux on? Apart from Oracle, what other vendors give trouble supporting systems with SELinux enabled?
Bonus question: Anyone has managed to get Oracle running on RHEL5 with SELinux in enforcing targeted mode? I mean, strict would be awesome, but I don't that is even remotely possible yet, so let's stay with targeted first ;-)

A: RedHat turns SELinux on by default because its safer. Nearly every vendor that uses Redhat-derived products turns SELinux off because they don't want to have to put in the time (and therefore money) to figure out why the thing doesn't work. The Redhat/Fedora people have put in a massive amount of time and effort making SELinux more of a viable option in the Enterprise, but not a lot of other organizations really care about your security. (They care about their security and the security reputation of their product, which is a totally different thing.)
If you can make it work, then go for it. If you can't, then don't expect a lot of assistance from the vendors out there. You can probably get help from the Redhat/Fedora guys, from the selinux mailing lists and #selinux channel on freenode. But from companies like Oracle -- well, SELinux doesn't really factor in to their business plan.

A: Typically you're better off running SELinux in Permissive rather than disabling it entirely.  You can then check (via audit2why) after a while to see what kinds of violations would have been denied during your regular usage, and build custom policies via audit2allow if those 'violations' are false-positives for your setup.
I have found SELinux behaviour on non-Fedora derived systems to be significantly touchier than what you get with a typical Fedora/RHEL system by default.
If you haven't seen it already, you may find the Fedora SELinux User Guide educational.

A: I disabled SELinux for AppArmor, I found it much friendlier and easy to maintain than SELinux.

A: Reasons for:

*

*Higher level of security through mandatory access control

*You need a reason beyond higher level of security? :-)

Reasons against:

*

*Difficult to understand

*Difficult to manage

*Difficult to troubleshoot

That said if you're considering SELinux, I recommend the book SELinux by Example.
I worked for a company that had SELinux enabled, in enforcing mode, on every system. The key for us was understanding and using the audit2allow program which can be used to create new context rules.
First, we'd generate a template with audit2allow, and then use a script to build it, like this:
export NAME="my_serviced"
sudo audit2allow -m "${NAME}" -i /var/log/audit/audit.log > ${NAME}.te
sudo setup_semodule ${NAME}

The setup_semodule script:
#!/bin/sh

# Where to store selinux related files
SOURCE=/etc/selinux/local
BUILD=/etc/selinux/local
NAME=$1

/usr/bin/checkmodule -M -m -o ${BUILD}/${NAME}.mod ${SOURCE}/${NAME}.te
/usr/bin/semodule_package -o ${BUILD}/${NAME}.pp -m ${BUILD}/${NAME}.mod
/usr/sbin/semodule -i ${BUILD}/${NAME}.pp

/bin/rm ${BUILD}/${NAME}.mod ${BUILD}/${NAME}.pp

This builds the module from the template (.te file), generates a package, and then loads the module.
We used Puppet for our configuration management system, and we wrote configuration for Puppet to manage all this.
SELinux Puppet Module:

*

*http://github.com/sansnoc/puppet/tree/master/selinux

A: The reason to turn it off is because it can be a pain to debug.
However we don't turn it off now.
We nearly always keep it running.
I do occasionally turn it off to quickly verify if SElinux is a problem or not.
It' much easier to debug now, especially if you make yourself familir with audit2allow.
You don't really need to understand it with audit2allow, but you can some times end up opening thins up wider than you think with audit2allow.
Having said that some SELinux is better than none.
I'm by no means an SELinux expert and have only been using it for a  couple of years.
I still don't really understand the basics, but I know enough to get apps running, btoh those included with the distro and random stuff compiled of the 'net.
The main thing I've had to use are the ls -lZ (show selinux context), audit2allow, chcon, semodule, getenforce, setenforce and booleans. With those tools I've managed to get every app I needed to running under SELinux.
I find one of he big problems with debugging SELinux problems,, is simply remebering to check for SELinux problems when I have other wise inexplicable problems. It usually takes me a little wile to go "h! check SELinux!!".
According to the bind man page SELinux is far safer than running bind in a chroot jail.
A lot of other people who have far more clue than I also recommend it so I run it blindly now. And suspect despite the occasional problem it is probably worth doing.

A: There is no reason to turn it off when you can run it in Permissive mode.
It will not interfere with the running application and it will still provide useful security logging.
The only exception is about the user contexts: if you are changing between different users living inside another linux instance running in a chroot you could have issues.

A: SE Linux is not as hopelessly unfriendly as it used to be, at least it's not in commercially supported distros like RHEL5. For the most part you can leave it on, and it'll be fine with anything provided by RedHat. With anything else it can be variable. The problem is that professional service work to get applications working with SE Linux enabled is a nice revenue stream for companies like RedHat and Oracle, so they have no incentive to make everything work nicely ootb.


text:
Q: Why parenthesis are ignored in the expression (o.method)() I want to understand why the parenthesis around o.method in the expression
(o.method)()

are ignored and so it's behaving equally to o.method(), with execution context of method referencing o. I was expecting it to behave similarly to (o.method || true)(), where execution context inside method references global object.
If I evaluate (o.method) on its own, it returns reference to a standalone function not bound to any context. Simply rewriting it like this
var a = (o.method); a();

will have global context as expected. And I've just shortened the code by replacing a, and it produced different result.

A: I think it has to do with ES5 11.1.6:

11.1.6 The Grouping Operator # Ⓣ
The production PrimaryExpression : ( Expression ) is evaluated as follows:

*

*Return the result of evaluating Expression. This may be of type Reference.

NOTE This algorithm does not apply GetValue to the result of evaluating Expression. The principal motivation for this is so that operators such as delete and typeof may be applied to parenthesised expressions.

Let's see how function invocation is done in JS:
The key point is that o.method is a Reference (as defined by the spec):

A Reference is a resolved name binding. A Reference consists of three components, the base value, the referenced name and the Boolean valued strict reference flag.

So, o.method is not a Function YET; it is basically [[o, "method", false]]. When invoked with an argument list, o.method(), the reference value is taken by GetValue, then the method invocation proceeds (as described in 11.2.3).
When you do (o.method)(), (o.method) is still a Reference - GetValue has still not been applied to it (per the quoted 11.1.6). So nothing changes.
When you do (o.method || true)(), || will apply GetValue to the left side (per 11.11) and produce a function value - not a Reference any more. Thus, it cannot be evaluated as a method invocation, since the information about the base and referenced name (that was present in Reference) is lost.

A: This is called Method Invocation.
When a function is stored as a property of an object, we call it a method. When a method is invoked, this is bound to that object. If an invocation expression contains a refinement (that is, a . dot expression or [subscript] expression), it is invoked as a method.
So in your case when you call o.method, this will refer to the object 'o'.
this will call to window object in case of function invocation.
Please refer : https://www.safaribooksonline.com/library/view/javascript-the-good/9780596517748/ch04s03.html


text:
Q: How to invert numpy.where (np.where) function I frequently use the numpy.where function to gather a tuple of indices of a matrix having some property.  For example
import numpy as np
X = np.random.rand(3,3)
>>> X
array([[ 0.51035326,  0.41536004,  0.37821622],
   [ 0.32285063,  0.29847402,  0.82969935],
   [ 0.74340225,  0.51553363,  0.22528989]])
>>> ix = np.where(X > 0.5)
>>> ix
(array([0, 1, 2, 2]), array([0, 2, 0, 1]))

ix is now a tuple of ndarray objects that contain the row and column indices, whereas the sub-expression X>0.5 contains a single boolean matrix indicating which cells had the >0.5 property.  Each representation has its own advantages.
What is the best way to take ix object and convert it back to the boolean form later when it is desired?   For example
G = np.zeros(X.shape,dtype=np.bool)
>>> G[ix] = True

Is there a one-liner that accomplishes the same thing?

A: mask = X > 0
imask = np.logical_not(mask)

For example
Edit: Sorry for being so concise before. Shouldn't be answering things on the phone :P
As I noted in the example, it's better to just invert the boolean mask. Much more efficient/easier than going back from the result of where.

A: The bottom of the np.where docstring suggests to use np.in1d for this.
>>> x = np.array([1, 3, 4, 1, 2, 7, 6])
>>> indices = np.where(x % 3 == 1)[0]
>>> indices
array([0, 2, 3, 5])
>>> np.in1d(np.arange(len(x)), indices)
array([ True, False,  True,  True, False,  True, False], dtype=bool)

(While this is a nice one-liner, it is a lot slower than @Bi Rico's solution.)

A: Something like this maybe?
mask = np.zeros(X.shape, dtype='bool')
mask[ix] = True

but if it's something simple like X > 0, you're probably better off doing mask = X > 0 unless mask is very sparse or you no longer have a reference to X.


text:
Q: Form Designer unable to find type In a windows form I am populating a combo box with the following code.
this.JackStudTypeComboBox.Items.AddRange(ViewController.GetJackStudMaterialType().ToArray());

When I attempt to open the Form Designer I get the message that the ViewController type is not found.
The ViewController class is located in the same project as the form.  Compiling the project has no issues, and running the project results in the expected behaviour.
So, how do I convince the Form Designer to locate this particular class, or to ignore the fact that it is unable to find it or do anything useful with it when in static design mode?

A: Don't do that.
You should never put any custom logic in InitializeComponent().
Move that to the constructor and everything will work fine.


text:
Q: textarea by mistake contains part of page html I had a partial view rendered inside a page and it worked fine. Then I introduced a textarea control in that partial view.
The rest of the page (that should have rendered after this textarea) is rendered INSIDE this textarea, to the extent that all the rest of the page is blank and I can see the HTML that should have rendered in the view as text in this textarea.
This is my Razor:
@if (Model == null || (Model != null && String.IsNullOrEmpty(Model.QuoteNo)))
{

    my Comment

     <textarea name="comments" cols="100" rows="10" />

}

Sorry for my formatting, but this editor doesn't show up html tags otherwise.
This partial view is rendered like this:
 @if (Model == null)
            {
                Html.RenderPartial("_HeaderAndPartsList", Model);
            }

A: Your textarea tag is incorrect. Try this:
<textarea name="comments" cols="100" rows="10"></textarea>

A: According to the HTML spec, the textarea tag requires an end tag:
<textarea name="comments"></textarea>

Also of note are that HTML tags require opening < brackets.  Your markup seems broken in a couple of different ways.
When debugging strange behavior in HTML markup, the first tool to use is the W3C validator.  It would identify issues like this and provide links to the official spec for reference.

A: It turns out that I should have closed the textarea like this:
</textarea>


text:
Q: How to increase the size of request in ab benchmarking tool? I am testing with ab - Apache HTTP server benchmarking tool.
Can I increase the size of the request in Apache (now I see 1 request has the size of 146 bytes).
I tried to increase the size of TCP send/receive buffer (-b option), but It seems does not work. Because I still see the "Total transferred" is 146 bytes.
Do you know any way to increase the size of the request? (change the source code or something).
Or if it is impossible, can you give me a suggestion about some tools which are similar to ab but it can increase the size of the request.
Thank you so much!

A: Although -b option does seem like it should've worked, I can't say for sure as I haven't used.
Alternatively, have you tried sending a dummy large file in your POST request? that can be accomplished with the -p option followed by a plain text file for instance, that you can either create yourself or Google for something like "generate large file in bytes online" that you can download and pass into the command.
As far as alternatives go, I've heard another open source project called httpperf from HP to be a great option as well, though I doubt we're unable to figure it out how to do it with Apache Benchmark.


text:
Q: C++ multi threaded server I'm working on a server that just connects a client and sends back what they type. So far it works well, but I want to make it multi-threaded so I can connect more clients, so they can "Talk." Can you guys refer me to any source code that I can look over to make some adjustments to my own code? Thanks. I would also like this to work on different networks, and I am not sure how to do this so some source code to that as well would work. Also I'm in eighth grade and haven't had a lot of experience so a well-explained answer would be appreciated.
int main() {

    WSADATA wsaData;

    // Initialize Winsock
    int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if(iResult != 0)
    {
        printf("WSAStartup failed: %d\n", iResult);
        return 1;
    }

    struct addrinfo *result = NULL,
                    hints;

    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_INET;      // Internet address family is unspecified so that either an IPv6 or IPv4 address can be returned
    hints.ai_socktype = SOCK_STREAM;    // Requests the socket type to be a stream socket for the TCP protocol
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_PASSIVE;

    // Resolve the local address and port to be used by the server
    iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
    if (iResult != 0)
    {
        printf("getaddrinfo failed: %d\n", iResult);
        WSACleanup();
        return 1;
    }

    SOCKET ListenSocket = INVALID_SOCKET;

    // Create a SOCKET for the server to listen for client connections
    ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);

    if (ListenSocket == INVALID_SOCKET)
    {
        printf("Error at socket(): %d\n", WSAGetLastError());
        freeaddrinfo(result);
        WSACleanup();
        return 1;
    }

    // Setup the TCP listening socket
    iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);

    if (iResult == SOCKET_ERROR)
    {
        printf("bind failed: %d", WSAGetLastError());
        freeaddrinfo(result);
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    freeaddrinfo(result);

    // To listen on a socket
    if ( listen(ListenSocket, SOMAXCONN) == SOCKET_ERROR)
    {
        printf("listen failed: %d\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    SOCKET ClientSocket;

    ClientSocket = INVALID_SOCKET;

    // Accept a client socket
    ClientSocket = accept(ListenSocket, NULL, NULL);

    if (ClientSocket == INVALID_SOCKET)
    {
        printf("accept failed: %d\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    char recvbuf[DEFAULT_BUFFER_LENGTH];
    int iSendResult;

    // reveice until the client shutdown the connection
    do {
        iResult = recv(ClientSocket, recvbuf, DEFAULT_BUFFER_LENGTH, 0);
        if (iResult > 0)
        {
            char msg[DEFAULT_BUFFER_LENGTH];
            memset(&msg, 0, sizeof(msg));
            strncpy(msg, recvbuf, iResult);

            printf("Received: %s\n", msg);

            iSendResult = send(ClientSocket, recvbuf, iResult, 0);

            if (iSendResult == SOCKET_ERROR)
            {
                printf("send failed: %d\n", WSAGetLastError());
                closesocket(ClientSocket);
                WSACleanup();
                return 1;
            }

            printf("Bytes sent: %ld\n", iSendResult);
        }
        else if (iResult == 0)
            printf("Connection closed\n");
        else
        {
            printf("recv failed: %d\n", WSAGetLastError());
            closesocket(ClientSocket);
            WSACleanup();
            //return 1;
        }
    } while (iResult > 0);

    // Free the resouces
    closesocket(ListenSocket);
    WSACleanup();

    getchar();
    return 0;
}

A: There are dozens of ways how to implement this solution.
First of all, it is better to design what approach is preferable for your educational purposes.
Considering network programming:
One of the best guides for network programming I can recommend is Beej's Guide.
Considering server-side architecture:
I would like to recommend C++ Concurrency in Action: Practical Multithreading by  Anthony Williams for further reading.
Before you, a whole sea of possibilities - go for it!
Ps: considering general questions like this
It is better to look for an answer to such questions in softwareengineering forum.


text:
Q: Reading Current Uncore Frequency and Setting Uncore Frequency Multipliers I'm working on a project that requires reading and setting Uncore Frequency on an Intel Skylake Xeon Gold 6126 Server CPU (I will need to do the same for another Haswell based processor). I'm running an Ubuntu with Linux 4.15.0-134.
I've loaded the msr kernel module.
I am now trying to first read the current Uncore frequency. I am doing the following:
sudo wrmsr 0x700 0x2000000000000000
sudo wrmsr 0x703 0x400000
sudo rdmsr 0x704

I found the above solution on an Intel discussion thread
However, I am now trying to modify the minimum and maximum uncore frequencies.
To do that I am first trying to read the minimum frequency (to store it for later reference):
sudo rdmsr 0x620

The above returns 1818. I'm not sure what this number is. The technical document calls the first 7 bits of it a minimum frequency ratio (which would have a value of 24 in decimal). But I am not sure what this value is. Furthermore, according to the document, bits 8-14 store the maximum frequency ratio. However, the bits 8-14 turn out to be 24 as well.
Could someone please explain what these values are? And which value are they calculated in respect to?
Also, would changing the uncore frequency simply require writing to the appropriate bits of register at 0x620, like so?
sudo wrmsr 0x620 0x1c18

I would be extremely grateful for any guidance with regards to the aforementioned questions.

A: Your uncore frequency monitoring approach is correct. You must enable the monitoring in (U_MSR_PMON_FIXED_CTL) and then you may read the performance counter (U_MSR_PMON_FIXED_CTR). From my experience writing to U_MSR_PMON_GLOBAL_CTL is not necessary.  See Uncore performance monitoring manual.
Your uncore frequency ration 24, represents frequency 2.4 GHz, which you will be able to see from the U_MSR_PMON_FIXED_CTR.
In default the MSR_UNCORE_RATIO_LIMIT keeps the minimum and the maximum possible values, which are not the same. As of I know, these limits are not stored in any other available MSR, so you should store them. Rebooting the system will restore the default values.
Two extra hints:
To read/write MSRs on Intel (also works fine for AMD CPUs) it is good approach to use msr-safe, since it allows access registers without sudo rights based on a list of registers (specifying which register can be accessed) and their masks (specifying which bits can be written).
To tune and monitor (not-only) uncore frequency you may use my library MERIC.


text:
Q: Ranking in rails I want to create a ranking of users. It should sort users descending by count of added events.
That's my files:
User.rb:
class User < ActiveRecord::Base
  has_many :events
  #...
end

ranking.html.erb:

    <% User.all.each  do |user| %>
     <%= user.name %>
     <%= user.events_count %>

<% end %>

schema.rb:
create_table "users", force: true do |t|
  #...
  t.integer  "events_count", default: 0
end

How to do it?

A: I'm guessing you want to use a counter cache.
Event.rb:
class Event < ActiveRecord::Base
  belongs_to :user, counter_cache: true
end

ranking.html.erb:

  <% User.order(events_count: :desc).each do |user| %>
    ...


text:
Q: What is the reason for the existence of undefined variable in the global scope in JavaScript? I've found many discussions about undefined as value e.g. how to check if is equal etc. But what is the "engineering" reason for the existence of the undefined as a global variable? There is no null variable in opposite...
console.log(undefined in this);  // logs true
console.log(null in this);  // logs false

A: In JavaScript, null is a reserved word; undefined isn't, but is implemented by the environment as a global variable with a value of undefined.
You'll notice you can change the value of undefined, but not of null, except in strict mode (which will throw an error) or ES5 (which will ignore the assignment.)
Now, why undefined is not reserved, I do not know.

A: The simple answer is that ECMAScript defines a property of the global object called undefined whose initial value is undefined. This object is created before entering any execution context, so it always exists before any code is run.
It is likely a convenience for testing for the undefined value, otherwise it would be common do to things like:
var undefined;

// test against undefined.

function foo() {

    // And maybe here too
    var undefined;

   // test against undefined.
}

Since the global undefined property is not write protected, it is common to do things like:
(function(global, undefined) {

  // In here you can be sure undefined has the value undefined

}(this));

Edit
In summary, the goal seems to have been to create two separate ways of returning a value of "there is no value", where undefined means "my value is not defined at all", whereas null means "I do not have a value".
e.g.
function getElement(id) {
  if (document && document.getElementById) {
    return document.getElementById(id);
  }
  // return undefined implied
}

If the above function returns null, you know it ran successfully but didn't find an element with the provided id, whereas if it returns undefined, you know it didn't even try.
In regard to:

There is no null variable in opposite

I guess you are saying "why is undefined a global variable whereas null is global object.
The answer is the same: because that's how the spec was written. One explanation (not a reason) is that JavaScript was prematurely optimised and there are a few fundamental issues that should have been sorted earlier, but it's too late to change them now (and has been for many years).
Perhaps it would have been much better (IMHO) if undefined was implemented just like null (i.e. as a read–only property of the global object) and that:
typeof undefined === 'undefined'

and
typeof null === 'null'

since that is what they actually are. But changing that now might create more issues than it solves.
And then there is NaN…


text:
Q: How can I resample wav file Currently I'm recording an audio signal with following specs:

*

*Channels: 1

*SamplesPerSecond: 8000

*BitsPerSample: 16

How can I convert this .wav-file to eg following specs (pure c# is preferred):

*

*Channels: 1

*SamplesPerSecond: 22050

*BitsPerSample: 16

A: Windows API (one of) to resample audio is Audio Resampler DSP. This transform class is pretty straightforward to set up input and output types, then push input data and pull output.
Another task you would possible deal additionally with is reading from file and writing into a new file (you did not specify if it is actually needed in your original description though).
You might also want to use third party libraries like NAudio.
See also:

*

*C# resample audio from 8khz to 44.1/48khz

*Audio DSP in C#

A: try Naudio - it is a free + opensource .NET library offering several things including the ability to resample AFAIK.
As requested sample source for resampling

A: AS3 function for resampling. You can easy change to convert this code to C#:
    private function resampling(fromSampleRate:int, toSampleRate:int, quality:int = 10):void
    {
        var samples:Vector.<Number> = new Vector.<Number>;

        var srcLength:uint = this._samples.length;
        var destLength:uint = this._samples.length*toSampleRate/fromSampleRate;
        var dx:Number = srcLength/destLength;

        // fmax : nyqist half of destination sampleRate
        // fmax / fsr = 0.5;
        var fmaxDivSR:Number = 0.5;
        var r_g:Number = 2 * fmaxDivSR;

        // Quality is half the window width
        var wndWidth2:int = quality;
        var wndWidth:int = quality*2;

        var x:Number = 0;
        var i:uint, j:uint;
        var r_y:Number;
        var tau:int;
        var r_w:Number;
        var r_a:Number;
        var r_snc:Number;
        for (i=0;i<destLength;++i)
        {
            r_y = 0.0;
            for (tau=-wndWidth2;tau < wndWidth2;++tau)
            {
                // input sample index
                j = (int)(x+tau);

                // Hann Window. Scale and calculate sinc
                r_w = 0.5 - 0.5 * Math.cos(2*Math.PI*(0.5 + (j-x)/wndWidth));
                r_a = 2*Math.PI*(j-x)*fmaxDivSR;
                r_snc = 1.0;
                if (r_a != 0)
                    r_snc = Math.sin(r_a)/r_a;

                if ((j >= 0) && (j < srcLength))
                {
                    r_y += r_g * r_w * r_snc * this._samples[j];
                }
            }
            samples[i] = r_y;
            x += dx;
        }

        this._samples = samples.concat();
        samples.length = 0;
    }

A: Try code below from C# resample audio from 8khz to 44.1/48khz
static void Resample(string fileName)
{
    IntPtr formatNew = AudioCompressionManager.GetPcmFormat(2, 16, 44100);
    WaveReader wr = new WaveReader(File.OpenRead(fileName));
    IntPtr format = wr.ReadFormat();
    byte[] data = wr.ReadData();
    wr.Close();
    //PCM 8000 Hz -> PCM 44100
    byte[] dataNew = AudioCompressionManager.Resample(format, data, formatNew);
    WaveWriter ww = new WaveWriter(File.Create(fileName + ".wav"),
        AudioCompressionManager.FormatBytes(formatNew));
    ww.WriteData(dataNew);
    ww.Close();
}


text:
Q: Auto generate class diagram cli tool for CI We just finished a webservice and I just created a SHFB project file to generate chm and html documentation (with auto inserted example code snippets!) being build on a TeamCity server. The last thing I need, is a tool to auto generate a class diagram (with associations!) based on a namespace, class names or similar (C#). Any thoughts?

A: Doxygen supports generating class diagrams (at least for C++), try it out.


text:
Q: как в списке убрать кавычки Господа помогите плз, я начинающий, я получил список, в нем каждое слово в кавычках, как мне сделать, чтобы этот же список слов был без кавычек
import re
a = """По мнению Рубина, слова которого приводит Defense News, саудовская система ПВО не смогла обнаружить низколетящие
 ракеты и беспилотники, поскольку ее датчики отслеживали цели только над горизонтом. Кроме того, Саудовская Аравия имеет
  большую территорию, что также усложняет защиту воздушного пространства мнению."""

c = re.findall("[а-яА-Я\-]{1,}", a)
print(c)

A: Никак, потому что там нет кавычек. Эти кавычки не входят в элемент списка, а означают, что данный элемент - строка. Они не являются частью списка.


text:
Q: Smooth image contours using python I applied some operations on the image to remove the white background(color clustering), but the issue is that the result is not smooth on the contours as you can see here: https://imgur.com/a/QLwpE.
What's your advice for smoothing the contours without blurring the entire image?
Thanks in advance!

A: What you need is called image matting. The basic idea is to determine the amount of background color (white) present in the pixel and to replace it with black. This will anti-alias the outlines.

A: I think a simple Bilateral filter could do the job. You can also try more advanced filters like Total Variation Denoising.
Keep in mind that this process is never going to be perfect if your input images are very different from each other.

A: I found one way to solve my problem. The first step is to approximate the contours using approxPolyDp(https://docs.opencv.org/3.4.0/d3/dc0/group__imgproc__shape.html#ga0012a5fdaea70b8a9970165d98722b4c). The second step is to have a gradual transparency on the contours.
The results are not perfect for each image, but it's a lot cleaner.
Hope it helps !


text:
Q: make_unique does not compile I'm trying to create and use make_unique for std::unique_ptr, in the same way std::make_shared exists for std::shared_ptr described here. Herb Sutter mentions the possible implementation of make_unique that looks like this:
template<typename T, typename ...Args>
std::unique_ptr<T> make_unique( Args&& ...args )
{
    return std::unique_ptr<T>( new T( std::forward<Args>(args)... ) );
}

It doesn't seem to work for me. I'm using the following sample program:
// testproject.cpp : Defines the entry point for the console application.
#include "stdafx.h"

#include <iostream>
#include <memory>
#include <utility>

struct A {
  A(int&& n) { std::cout << "rvalue overload, n=" << n << "\n"; }
  A(int& n)  { std::cout << "lvalue overload, n=" << n << "\n"; }
};

template<typename T, typename ...Args>
std::unique_ptr<T> make_unique( Args&& ...args ) {
  return std::unique_ptr<T>( new T( std::forward<Args>(args)... ) );
}

int main() {
  std::unique_ptr<A> p1 = make_unique<A>(2); // rvalue
  int i = 1;
  std::unique_ptr<A> p2 = make_unique<A>(i); // lvalue
}

And the compiler (I'm using VS2010) gives me the following output:
1>d:\projects\testproject\testproject\testproject.cpp(15): error C2143: syntax error : missing ',' before '...'
1>d:\projects\testproject\testproject\testproject.cpp(16): error C2065: 'Args' : undeclared identifier
1>d:\projects\testproject\testproject\testproject.cpp(16): error C2988: unrecognizable template declaration/definition
1>d:\projects\testproject\testproject\testproject.cpp(16): error C2059: syntax error : '...'
1>d:\projects\testproject\testproject\testproject.cpp(22): error C2143: syntax error : missing ';' before '{'
1>d:\projects\testproject\testproject\testproject.cpp(22): error C2447: '{' : missing function header (old-style formal list?)

Also if you replace the make_unique implementation to the following
template<class T, class U>
std::unique_ptr<T> make_unique(U&& u) {
  return std::unique_ptr<T>(new T(std::forward<U>(u)));
}

(which is taken from this example), it compiles and works fine.
Can anyone tell me what's the problem? It seems to me that VS2010 is having some trouble with ... in template declaration, and I don't know what can I do about it.

A: According to MSDN, variadic templates are not supported in Visual C++ 2010 or 2012.

A: Variadic templates aren't available in the released version of Visual C++ 11. You can, however, simulate the argument expansion with either lots of copy/paste code for different number of parameters, or use the same compiler tricks used in Microsoft's own implementation of "pseudo-variadics". From this comment on Herb Sutter's blog: http://herbsutter.com/gotw/_102/#comment-6428
#include <memory> // brings in TEMPLATE macros.

#define _MAKE_UNIQUE(TEMPLATE_LIST, PADDING_LIST, LIST, COMMA, X1, X2, X3, X4)  \
\
template<class T COMMA LIST(_CLASS_TYPE)>    \
inline std::unique_ptr<T> make_unique(LIST(_TYPE_REFREF_ARG))    \
{    \
    return std::unique_ptr<T>(new T(LIST(_FORWARD_ARG)));    \
}

_VARIADIC_EXPAND_0X(_MAKE_UNIQUE, , , , )
#undef _MAKE_UNIQUE


text:
Q: Extracting information from entries in a LDIF file I've a file that contains entries like this:
ddn: cn=312548,ou=Entities,ou=Active,ou=Vault,o=abc
member: cn=312548001,ou=Unnamed,ou=Identities,ou=Active,ou=Vault,o=abc
member: cn=312548999,ou=ServiceAccounts,ou=Active,ou=Vault,o=abc
abcName: something else

dn: cn=312544,ou=Entities,ou=Active,ou=Vault,o=abc
member: cn=312544001,ou=Unnamed,ou=Identities,ou=Active,ou=Vault,o=abc
member: cn=312544999,ou=ServiceAccounts,ou=Active,ou=Vault,o=abc
abcName: after bike

dn: cn=312542,ou=Entities,ou=Active,ou=Vault,o=abc
member: cn=312542001,ou=Unnamed,ou=Identities,ou=Active,ou=Vault,o=abc
member: cn=312542999,ou=ServiceAccounts,ou=Active,ou=Vault,o=abc
abcName: pen mark

dn: cn=312539,ou=Entities,ou=Active,ou=Vault,o=abc
member: cn=312539999,ou=ServiceAccounts,ou=Active,ou=Vault,o=abc
member: cn=312539001,ou=Unnamed,ou=Identities,ou=Active,ou=Vault,o=abc
abcName: used car

dn: cn=312537,ou=Entities,ou=Active,ou=Vault,o=abc
member: cn=312537001,ou=Unnamed,ou=Identities,ou=Active,ou=Vault,o=abc
member: cn=312537999,ou=ServiceAccounts,ou=Active,ou=Vault,o=abc
abcName: Book bike

dn: cn=312534,ou=Entities,ou=Active,ou=Vault,o=abc
member: cn=312534999,ou=ServiceAccounts,ou=Active,ou=Vault,o=abc
member: cn=312534001,ou=Unnamed,ou=Identities,ou=Active,ou=Vault,o=abc
member: cn=fe7316f7-05d6-439b-8b9b-4364f4936615,ou=Named,ou=Identities,ou=Acti
 ve,ou=Vault,o=abc
abcName: Apple

Now I want to know only the dn entries which have a member "Named".
The output should contain the "abcName" and the "dn".

A: With GNU sed
sed 'H;/^$/{h};/abcName/{x;/,ou=Named,/{s/member:[^\n]*\n//g;p}};d' file

dn: cn=312534,ou=Entities,ou=Active,ou=Vault,o=abc
abcName: Apple

A: On your sample,
awk -vRS= -F': *|\n' '/,ou=Named,/{print $2, $NF}' < file

would output:
cn=312534,ou=Entities,ou=Active,ou=Vault,o=abc Apple

(that assumes abcName is the last attribute in each entry and that ,ou=Named, may not be found in other attributes or the dn, and that the attribute values are not encoded).
To account for LDIF line continuations (where for instance ou=Named could become ou=Na\n med), you can first remove them:
awk -vRS= -F': *|\n' '{gsub(/\n /, "")}; /,ou=Named,/{print $2, $NF}' < file


text:
Q: Capture first visible div id while scrolling (viewport) I have this page:

I want to capture on which div I am while I'm scrolling.
I know If I use:
if( $(document).scrollTop() > $('#div1').position().top) {
console.log('Div1')
  }

...it will capture the div1 but instead of using this code for every div I want to set 1 snippet for all divs
Something like:
var a =   // The div i am at
if( $(document).scrollTop() > $(a).position().top) {
    console.log($(a).attr('id'))
}

I am looking something like the viewport: http://www.appelsiini.net/projects/viewport/3x2.html
Can I achieve that without a plugin, simply 2-3 lines?

A: Here's a nice way to do it. You may want to optimize the '<=' with a pixel offset to improve user experience and  move the div selector ($divs) outside the callback to increase performance.  Have a look at my fiddle: http://jsfiddle.net/brentmn/CmpEt/
$(window).scroll(function() {

    var winTop = $(this).scrollTop();
    var $divs = $('div');

    var top = $.grep($divs, function(item) {
        return $(item).position().top <= winTop;
    });
});

A: Just throw it into a loop.
var list = [];
$("div").each(function(index) {
    if( $(document).scrollTop() > $(this).position().top)
        list.push($(this));
});

alert(list);

The list will than have every div that is within your viewport.

A: I'd suggest using the jQuery Inview plugin:
https://github.com/protonet/jquery.inview
Well maintained Plugin that detects whatever content is in the viewer currently, enabling you to bind functions to an inview event. So as soon as your div is in view you could fire off all the relevant functions you wanted and then again when it has left the users view. Would be great for your needs.

A:    $(window).scroll(function () {

        $("#privacyContent div").each(function () {
            var bottomOffset = ($(this).offset().top + $(this).height());
            console.log("Botom=",bottomOffset ,"Win= ", $(window).scrollTop());
            if (bottomOffset > $(window).scrollTop()) {

                $("#menu a").removeClass("active");
              //  console.log("Div is= ",$(this).attr('id'));
                $("#menu a[href='#" + $(this).attr('id') + "']").addClass("active");
                $(".b").removeClass("fsActive");
                var div = $(this);
                div.find(".b").addClass("fsActive");

                return false;
            }
        });

});

I do it like  this it works fine it detect all div id


text:
Q: why wont my background change color? I was working on this lab in class and when I tried changing the background color it would stay at its default of white can someone please explain where I my programming went wrong.
import javax.swing.*;
import java.awt.*;
public class  DemoPoly extends JFrame {

// constructor
public DemoPoly() {
  // defines Frame characteristics

  int size = 300;
  setSize(size,size);
  setTitle("a random window");

  getContentPane().setBackground(Color.red);

  setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  setVisible(true);
}

public static void main (String[] args){
  //  instantiates a JFrame
  //  exits on close (opional)
  JFrame object = new DemoPoly();
}

public void  paint  (Graphics g){
  // This provides the Graphics object g,  where
  // you are going to use you graphics primitive
  // to paint on the content pane of the frame.
  int[] arr = {0,100,100,0};
  int[] yarr = {0,0,100,100};
  Square object = new Square(arr,yarr,Color.red);
  AbstractPolygon randSquare = new Square(arr, yarr, Color.red);
}

A: I see a couple of problems in your code:

*

*Extending JFrame is like saying your class is a JFrame, JFrame is a rigid container, instead create your GUI based on JPanels. See Java Swing extends JFrame vs calling it inside of class for more information.

*You're breaking the paint chain by removing the super.paint(g) call on the paint(...) method. When changing your GUI to extend JPanel instead of JFrame you should use the paintComponent(...) method instead. Take the Lesson: Performing Custom Painting in Swing.

*You forgot to add @Override notation on the paint(...) method.

*You're not placing your program on the Event Dispatch Thread (EDT) which could cause threading issues.
You can solve this by changing your main() method like this:
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            //Your constructor here
        }
    });
}

*Instead of setting the JFrame size, override the getPreferredSize() method and call pack(). See Should I setPreferred|Maximum|MiniumSize in Java Swing?. The general consensus says yes.

Your problem gets solved by adding
super.paint(g);

on the paint(...) method:
@Override
public void paint(Graphics g) {
    super.paint(g); //Never remove this
    //Your code goes here
}

With all the above recommendations taken into account, your code should look like this now:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

public class DemoPoly {

    private JFrame frame;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new DemoPoly().createAndShowGui();
            }
        });
    }

    public void createAndShowGui() {
        frame = new JFrame(getClass().getSimpleName());

        CustomPanel cp = new CustomPanel();
        cp.setBackground(Color.RED);
        frame.add(cp);
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

class CustomPanel extends JPanel {
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(300, 300);
    }
}

Which produces this output (and is the same output that you'll get with your current code but better because it gives you more control over your components)

A: I'm don't understand your question. But here is code for change your background to RED;
public class DemoPoly extends JFrame {

    public DemoPoly() {
        // defines Frame characteristics

        int size = 300;
        setSize(size, size);
        setTitle("a random window");

        //change background here
        getContentPane().setBackground(Color.red);

        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        //  instantiates a JFrame
        //  exits on close (opional)
        JFrame object = new DemoPoly();
    }
}

Your code is well. Maybe use @override in your paint method.


text:
Q: Switching out implementation source files in C project For simplicity, let's say I have the following C project structure:
src/
  utils/
    logger.c
    logger.h
   main.c
   secondary_component.c

main.c starts with:
#include "utils/logger.h"

I would like to keep the code and its structure as-is, but stub out logger.c, logger.h and avoid compiling secondary_component.c (i.e. only use the subset of main and logger). For instance, instead of the regular logger.c writing to a file, the stubbed version would include a simple printf.
My attempted solution: create an extra folder stubbed_src/utils and place my new logger.c, logger.h inside that folder. Then, I perform:
clang -iquote stubbed_src -iquote src -o main_proj main.c stubbed_src/utils/logger.c
The goal is that when clang sees the #include logger.h in main.c, it will first look at the stubbed_src folder and find it (and thereby ignore the original src/utils/logger.h). Unfortunately, clang always looks at the current folder first (i.e. it looks for utils/logger.h starting at src, where main.c is located) and only if it doesn't find it will it then looks at the iquote folders. In which case, it will always stop when it finds the implementation in src/utils.
There used to be a clang command line workaround which disabled this current working directory behavior, but it has since been deprecated.
If I were willing to change main.c's #include to be an angle bracketed #include, then using -I would also solve the problem since -I has no such restriction regarding the current directory. But this would be an improper usage of angle brackets, and also I'm unable to change main.c in this case.
Ideally, my stubbed versions of logger.c, logger.h would be much reduced in size and only implement functions used in main.c. For instance, I would like to discard any logger functions called by secondary_component.c since I only want to compile main.c. In addition, those extraneous functions called by secondary_component.c introduce their own #include requirements into the original logger files and I'm trying to avoid compiling those extra #includes. I would like to be able to simply compile main.c and have it work with stubbed logger functions and be able to avoid compiling any extra files.
Any other suggestions on how to use an alternative/stubbed out implementation of logger.c, logger.h?

A: The normal practice when mocking functions in C (or otherwise using different implementations) is to use different .c source files in your build process. Normally, header files are not replaced.
If header files really must be replaced, then the #include "header.h" include directive must not refer to a file that can be found directly from the current source's directory.  The C standard specifies that the #include "..." form must always first look in the current directory before starting to look into other paths.


text:
Q: Lead Status Converted Value to Contact Status We have a converted Lead Status value "Sales Accepted", which we have in a custom Contact Status field on the Contact level as well. When a Lead is converted, where do the Converted values get mapped to? How can I map a Lead Status (default field) to a Contact Status (custom field).
For some reason, I believe our Org already had this mapping, which I have since proven myself wrong. Can anyone assist?

A: From the docs:

When you convert a lead, data in standard lead fields is transferred
  into standard account, contact, and opportunity fields. For custom
  lead fields, the data is mapped to custom account, contact, and
  opportunity fields as specified by your administrator.
Currently we can only map custom Lead fields with custom fields on
  Accounts, Contacts or Opportunities objects.
If you want to map a Standard Lead field to a custom field on Accounts
  or Contacts or Opportunities object, follow below given steps.
For Example: How to map standard Rating field on lead record to custom
  field on Contact object?
Step 1: Click on Setup | Customize | Leads | Fields | Click the "New"
  button | select Data Type: Formula | Return Type: Text Formula:
  Text(Rating) | Save it. This custom field in Leads will get the value
  from the standard field.
Step 2: Click on Setup | Customize | Contacts | Fields | Click the
  "New" button | select Data Type: Text We are creating a field in
  contact object with same data type as the field on lead.
Step 3: Click on Setup | Customize | Leads | Fields Click the Map Lead
  Fields button | Map: Custom formula "Rating field" from step 1 to
  custom Contact object "Rating field" from step 2 and click Save. With
  the above steps we can pass value from standard Lead field to custom
  field on Contact object.
The same can be done for account and opportunity objects too

A: If you set up custom lead fields, you specify how that custom information converts to custom fields in accounts, contacts, and opportunities.

*

*From the object management settings for leads, go to the fields section, then click
Map Lead Fields.

*For each custom lead field, choose a custom account, contact, or opportunity field into which you want the information inserted when you convert a lead.

*Save your work.
This will solve your problem.


text:
Q: How to get the process user name by PID on Mac OS? I used getpid() to know the process PID, and now how can I get the process user name?
I tried this shell command, ps -o user= PIDNUM, but on Mac 10.4, it doesn't work for me.
Are there any other methods?

A: ps -ef | grep <process_pid> --- this will give you all the information you need.

A: I'd use ps and awk:
% ps aux | awk -v PID=13521 '$2 == PID { print $1 }'
root

...where 13521 is the PID in question. Substitute for your own PID or ${environment_variable} to taste!
If you don't have the PID, you can find all users running Google Chrome (for example) like:
% ps aux | awk -v app='Google Chrome' '$0 ~ app { print $1 }'

A: the following would do it: ps -efj | grep PID
where

*

*e: selects all processes

*f: does full format listing

*j: job control format.

[http://linux.die.net/man/1/ps][1]


text:
Q: jQuery mCustomScrollbar update error Here is the problem: I'm using mCustomScrollbar with a div on which data are dinnamicaly loaded from another html file.
Javascript:
function updateScrollbar()
{
    $("#frame_holder").mCustomScrollbar('update');
}

function loader(name)
{
    //loads the selected file into div.

    var loading = "./rosliny/"+name+".html";
    $("#frame_holder").load(loading, function ()
    {
        //enable scrollbar
        $("#frame_holder").mCustomScrollbar();
    });
}

index.html file:

Roślinność

 Ogólna charakterystyka

Drzewa

Brzoza

Buk

Daglezja

Dąb

Jodła

Klon

Lipa

Modrzew

Sosna

Świerk

Wiąz

Html site to load:

Modrzew europejski (Larix decidua Mill.)

Ciekawostki

When I click on li element a webpage containging text and image should be loaded into #frame_holder div. This works correctly. But after that scrollbar update should occur. That is not happen. I can only click once again on the same li element and then the mCustomScrollbar recalculates and works ok. What should I do to make this code work properly after the first click? Please help me, because I'm run out of ideas.

A: Seems to be issue with multiple calls of mCustomScrollbar() after each loader without destroying it and again calling the update.
Ideally you should call mCustomScrollbar() once after you show the modal, means when you click on Roślinność at bottom of page. Loader function fall back should have then update method then.
First get rid of this function: updateScrollbar();
Second, call this after Roślinność click: $("#frame_holder").mCustomScrollbar();
Third, update scrollbar inside loader function:
Edit: load inside the frame_holder's generated container (.mCSB_container).
function loader(name)
{
    //loads the selected file into div.

    var loading = "./rosliny/"+name+".html";
    $("#frame_holder .mCSB_container").load(loading, function ()
    {
        //enable scrollbar
        $("#frame_holder").mCustomScrollbar('update');
    });
}


text:
Q: Spring WS sendSourceAndReceiveToResult method via POST How to use sendSourceAndReceiveToResult() from  Using Spring Web Services on the Client with custom serializer?

A: The question isn't correct. Any SOAP request is POST over HTTP transport.
If we take a look to the WebServiceTemplate#sendSourceAndReceiveToResult source code, we'll see:
 Boolean retVal = doSendAndReceive(uri, transformer, requestPayload, requestCallback,
                new SourceExtractor<Boolean>() {

                    public Boolean extractData(Source source) throws IOException, TransformerException {
                        if (source != null) {
                            transformer.transform(source, responseResult);
                        }
                        return Boolean.TRUE;
                    }
                });

Pay attention to the doSendAndReceive internal method invocation. Any high-level WebServiceTemplate# API do the same. And on the backgound the org.springframework.ws.transport.http.HttpUrlConnectionMessageSender is used as default SOAP transport, where connection.setRequestMethod(HttpTransportConstants.METHOD_POST); is used to build HttpUrlConnection.
That's all.


text:
Q: winform appliacation (service) upload and download files from OneDrive(SkyDrive) I have winform application, that send files and download files to/from OneDrive. I have login, password and app key. I have to use oaAutentification but I generate service without user interface.
Help me thanks.
Thanks, I tried .Net client, OneDrive and oauth20_desktop.srf but user must click to New windows with allow permision

A: I'm unsure exactly what you're really asking here. Have you tried using the special oauth20_desktop.srf endpoint in the redirect URL?

https://login.live.com/oauth20_desktop.srf

This is specifically for applications such as desktop programs and mobile apps.
Note: you'll still have to host the authentication session using a web browser control. Once the user logs in, you can then pick off the access token from the end of the URL when Microsoft redirects them to the desktop.srf page. You'll have to hook into the Navigated event of the browser control and then check the browser's Url in your event handler.
There's more here on Microsoft Live's OAuth 2 implementation:
http://msdn.microsoft.com/en-gb/library/dn631818.aspx
And more here on responding to the Navigated event in the web browser control:
http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.navigated.aspx
I hope this helps.


text:
Q: PostgreSQL query very slow with limit 1 My queries get very slow when I add a limit 1.
I have a table object_values  with timestamped values for objects:
 timestamp |  objectID |  value
--------------------------------
 2014-01-27|       234 | ksghdf

Per object I want to get the latest value:
SELECT * FROM object_values WHERE (objectID = 53708) ORDER BY timestamp DESC LIMIT 1;

(I cancelled the query after more than 10 minutes)
This query is very slow when there are no values for a given objectID (it is fast if there are results).
If I remove the limit it tells me nearly instantaneous that there are no results:
SELECT * FROM object_values WHERE (objectID = 53708) ORDER BY timestamp DESC;
...
Time: 0.463 ms

An explain shows me that the query without limit uses the index, where as the query with limit 1 does not make use of the index:
Slow query:
explain SELECT * FROM object_values WHERE (objectID = 53708) ORDER BY timestamp DESC limit 1;
QUERY PLAN`
----------------------------------------------------------------------------------------------------------------------------
Limit  (cost=0.00..2350.44 rows=1 width=126)
->  Index Scan Backward using object_values_timestamp on object_values  (cost=0.00..3995743.59 rows=1700 width=126)
     Filter: (objectID = 53708)`

Fast query:
explain SELECT * FROM object_values WHERE (objectID = 53708) ORDER BY timestamp DESC;
                                                  QUERY PLAN
--------------------------------------------------------------------------------------------------------------
 Sort  (cost=6540.86..6545.11 rows=1700 width=126)
   Sort Key: timestamp
   ->  Index Scan using object_values_objectID on working_hours_t  (cost=0.00..6449.65 rows=1700 width=126)
         Index Cond: (objectID = 53708)

The table contains 44,884,559 rows and 66,762 distinct objectIDs.
I have separate indexes on both fields: timestamp and objectID.
I have done a vacuum analyze on the table and I have reindexed the table.
Additionally the slow query becomes fast when I set the limit to 3 or higher:
explain SELECT * FROM object_values WHERE (objectID = 53708) ORDER BY timestamp DESC limit 3;
                                                     QUERY PLAN
--------------------------------------------------------------------------------------------------------------------
 Limit  (cost=6471.62..6471.63 rows=3 width=126)
   ->  Sort  (cost=6471.62..6475.87 rows=1700 width=126)
         Sort Key: timestamp
         ->  Index Scan using object_values_objectID on object_values  (cost=0.00..6449.65 rows=1700 width=126)
               Index Cond: (objectID = 53708)

In general I assume it has to do with the planner making wrong assumptions about the exectution costs and therefore chooses for a slower execution plan.
Is this the real reason? Is there a solution for this?

A: You can avoid this issue by adding an unneeded ORDER BY clause to the query.
SELECT * FROM object_values WHERE (objectID = 53708) ORDER BY timestamp, objectID DESC limit 1;

A: I started having similar symptoms on an update-heavy table, and what was needed in my case was
analyze $table_name;

In this case the statistics needed to be refreshed, which then fixed the slow query plans that were occurring.
Supporting docs: https://www.postgresql.org/docs/current/sql-analyze.html

A: You're running into an issue which relates, I think, to the lack of statistics on row correlations. Consider reporting it to pg-bugs for reference if this is using the latest version Postgres.
The interpretation I'd suggest for your plans is:

*

*limit 1 makes Postgres look for a single row, and in doing so it assumes that your object_id is common enough that it'll show up reasonably quickly in an index scan.
Based on the stats you gave its thinking probably is that it'll need to read ~70 rows on average to find one row that fits; it just doesn't realize that object_id and timestamp correlate to the point where it's actually going to read a large portion of the table.

*limit 3, in contrast, makes it realize that it's uncommon enough, so it seriously considers (and ends up…) top-n sorting an expected 1700 rows with the object_id you want, on grounds that doing so is likely cheaper.
For instance, it might know that the distribution of these rows is so that they're all packed in the same area on the disk.

*no limit clause means it'll fetch the 1700 anyways, so it goes straight for the index on object_id.
Solution, btw: add an index on (object_id, timestamp) or (object_id, timestamp desc).

A: Not a fix, but sure enough switching from limit 1 to limit 50 (for me) and returning the first result row is way faster...Postgres 9.x in this instance.  Just thought I'd mention it as a workaround mentioned by the OP.


text:
Q: Custom helper for  CakePHP I am still learning about CakePHP and I want to create a custom helper for a picture tag. I already used and made one for < source > but now I can't figure out how to wrap it inside the < picture >. It should be solved with some sort of array I assume, including 3 < source > and 1 .
The View:

<picture>
    <?= $this->Picture->source($article, 'photolg_dir', 'photolg', '1200px'); ?>
    <?= $this->Picture->source($article, 'photomd_dir', 'photomd', '992px'); ?>
    <?= $this->Picture->source($article, 'photosm_dir', 'photosm', '768px');?>
    <?= $this->Picture->img($article, 'photo_dir', 'photo'); ?>
</picture>

The Custom helper where I create the < source > and want to add the < picture >
<?php
 namespace Cake\View\Helper;

 use Cake\Core\Configure;
 use Cake\Http\Response;
 use Cake\View\Helper;
 use Cake\View\StringTemplateTrait;
 use Cake\View\View;

 class RestHelper extends Helper
 {

     use StringTemplateTrait;

     public $helpers = ['Url'];

     protected $_defaultConfig = [
         'templates' => [
             'link' => '{{content}}',
             'image' => '',
             'source' => '<source srcset="{{url}}"{{attrs}}/>',
         ]
     ];

     public function __construct(View $View, array $config = [])
     {
         parent::__construct($View, $config);
         $this->response = $this->_View->response ?: new Response();
     }

    public function link($title, $url = null, array $options = [])
    {
        $escapeTitle = true;
        if ($url !== null) {
            $url = $this->Url->build($url, $options);
            unset($options['fullBase']);
        } else {
            $url = $this->Url->build($title);
            $title = htmlspecialchars_decode($url, ENT_QUOTES);
            $title = h(urldecode($title));
            $escapeTitle = false;
        }

        if (isset($options['escapeTitle'])) {
            $escapeTitle = $options['escapeTitle'];
            unset($options['escapeTitle']);
        } elseif (isset($options['escape'])) {
            $escapeTitle = $options['escape'];
        }

        if ($escapeTitle === true) {
            $title = h($title);
        } elseif (is_string($escapeTitle)) {
            $title = htmlentities($title, ENT_QUOTES, $escapeTitle);
        }

        $confirmMessage = null;
        if (isset($options['confirm'])) {
            $confirmMessage = $options['confirm'];
            unset($options['confirm']);
        }
        if ($confirmMessage) {
            $options['onclick'] = $this->_confirm($confirmMessage, 'return true;', 'return false;', $options);
        }

        $templater = $this->templater();

        return $templater->format('link', [
            'url' => $url,
            'attrs' => $templater->formatAttributes($options),
            'content' => $title
        ]);
    }

    public function image($path, array $options = [])
    {
        $path = $this->Url->image($path, $options);
        $options = array_diff_key($options, ['fullBase' => null, 'pathPrefix' => null]);

        if (!isset($options['alt'])) {
            $options['alt'] = '';
        }

        $url = false;
        if (!empty($options['url'])) {
            $url = $options['url'];
            unset($options['url']);
        }

        $templater = $this->templater();
        $image = $templater->format('image', [
            'url' => $path,
            'attrs' => $templater->formatAttributes($options),
        ]);

        if ($url) {
            return $templater->format('link', [
                'url' => $this->Url->build($url),
                'attrs' => null,
                'content' => $image
            ]);
        }

        return $image;
    }

     public function source($path, array $options = [])
     {

         $path = $this->Url->image($path, $options);
         $options = array_diff_key($options, ['fullBase' => null, 'pathPrefix' => null]);

         if (!isset($options['alt'])) {
             $options['alt'] = '';
         }

         $url = false;
         if (!empty($options['url'])) {
             $url = $options['url'];
             unset($options['url']);
         }

         $templater = $this->templater();
         $source = $templater->format('source', [
             'url' => $path,
             'attrs' => $templater->formatAttributes($options),
         ]);

         if ($url) {
             return $templater->format('link', [
                 'url' => $this->Url->build($url),
                 'attrs' => null,
                 'content' => $source
             ]);
         }

         return $source;
     }

     public function implementedEvents()
     {
         return [];
     }
 }
?>

Another Helper where I connect between view and the RestHelper:
<?php
namespace App\View\Helper;

use Cake\View\Helper;
use Cake\View\View;

/**
 * Bild helper
 */
class PictureHelper extends Helper
{
    public $helpers = ['Rest', 'Html'];
    /**
     * Default configuration.
     *
     * @var array
     */
    protected $_defaultConfig = [
    ];

    public function picture(\App\Model\Entity\Article $article)
    {

    }

    public function source(\App\Model\Entity\Article $article, $dir, $size, $brpnt)
    {
        return $this->Rest->source('/' . $article->$dir . '/' . $article->$size, ['class' => 'img-fluid', 'alt' => 'Responsive image', 'media' => "(min-width: $brpnt)"]);
    }

    public function img(\App\Model\Entity\Article $article, $dir, $size)
    {
        return $this->Rest->image('/' . $article->$dir . $article->$size, ["class" => "img-fluid"], ["alt" => "Responsive image"]);
    }

    public function thumb(\App\Model\Entity\Article $article, $dir, $size)
    {
        return $this->Rest->image('/' . $article->$dir . '/' . 'thumbnail-' . $article->$size, ["class" => "img-fluid"], ["alt" => "Responsive image"]);
    }
}

Thanks a lot for the help.

A: Found a Solution. Just check if the columns with the pictures you want to use in the < picture > are filled or not, and then call the source function.
To slim this down a bit more just save the path as a hole in the DB instead of like i did storing the folder and name separately.
The Helper:
class PictureHelper extends Helper
{
    use StringTemplateTrait;

    public $helpers = ['Html', 'Url'];

    protected $_defaultConfig = [
        'templates' => [
            'source' => '<source srcset="{{url}}"{{attrs}}/>',
        ]
    ];

    public function source($path, array $options = [])
    {

        $path = $this->Url->image($path, $options);
        $options = array_diff_key($options, ['fullBase' => null, 'pathPrefix' => null]);

        if (!isset($options['alt'])) {
            $options['alt'] = '';
        }

        $url = false;
        if (!empty($options['url'])) {
            $url = $options['url'];
            unset($options['url']);
        }

        $templater = $this->templater();
        $source = $templater->format('source', [
            'url' => $path,
            'attrs' => $templater->formatAttributes($options),
        ]);

        if ($url) {
            return $templater->format('link', [
                'url' => $this->Url->build($url),
                'attrs' => null,
                'content' => $source
            ]);
        }

        return $source;
    }

    public function thumb($what, $dir, $size)
    {
        return $this->Html->image('/' . $what->$dir . '/' . 'thumbnail-' . $what->$size, ["class" => "img-fluid"], ["alt" => "Responsive image"]);
    }

    public function picture($what, $large, $largedir, $medium, $mediumdir, $small, $smalldir, $xsmall, $xsmalldir)
    {
        //
        if (!empty($what->$large)) {
            $lg = $this->source('/' . $what->$largedir . '/' . $what->$large, ['class' => 'img-fluid', 'alt' => 'Responsive image', 'media' => "(min-width: 1200px)"]);
        } else {
            $lg = NULL;
        }

        if (!empty($what->$medium)) {
            $md = $this->source('/' . $what->$mediumdir . '/' . $what->$medium,['class' => 'img-fluid', 'alt' => 'Responsive image', 'media' => "(min-width: 998px)"]);
        } else {
            $md = NULL;
        }

        if (!empty($what->$small)) {
            $sm = $this->source('/' . $what->$smalldir . '/' . $what->$small,['class' => 'img-fluid', 'alt' => 'Responsive image', 'media' => "(min-width: 768px)"]);
        } else {
            $sm = NULL;
        }

        $img = $this->Html->image('/' . $what->$xsmalldir . $what->$xsmall, ["class" => "img-fluid"], ["alt" => "Responsive image"]);

        return "<picture> $lg $md $sm $img</picture>";
    }
}

In the View:

    <?= $this->Picture->picture($article, 'photolg', 'photolg_dir', 'photomd', 'photomd_dir', 'photosm', 'photosm_dir', 'photo', 'photo_dir'); ?>


text: Q: Connect two devices with ssh on local network I would like to connect 2 device (my company laptop, and a raspberry pi 3), I would like to develop on my laptop and test on raspberry using vs code and ssh. It's possible to connect the raspberry to lan(which is managed by my company),without actually using my company lan/proxy configuration. Basically I don't want my company detect the pi or the po' causing security issue since the pi is not well protected. The final result I want is like direct connect the laptop to the pi with the ethernet cable, but passing through my company cable system


text:
Q: Write fails to NAS drive connected with cifs Hello I have serveral NAS hooked up in my network. In fstab they're all setup the same way. Problem is only one I can't write to. My fstab looks like this:
//IPADDRESS/foldername/ /media/foldername   cifs    vers=1.0,username=username,password=password,iocharset=utf8,file_mode=0777,dir_mode=0777,nofail 0   0
What can I change to get it so I can wrote to it? I am using a login with those privileges. I'm using Ubuntu 20.04.
Thanks

A: Got it to work by adding in uid=username.


text:
Q: How to change initial condition in while loop I am entering a while loop with a specific initial condition (m=0). Inside the while loop I have a for loop which needs to break if a spec. condition is reached, here if my growth rate is >= 20%.
If this condition is reached I want to leave the for loop and use i to set the new m. Then I want to do a new for loop and again leave the loop if the condition is reached and use the new i for m.
I tried with m+=i but this sums up the i's, which I don't want. I want the every new i is used for m. Please find below the code
nvdia=pd.read_csv(r"/NVDA.csv",sep=",").round(1)
nvdia["Date"]=pd.to_datetime(nvdia["Date"])
nvdia=nvdia.set_index(nvdia["Date"])

nvdia=nvdia.drop("Date",1)
nvdia=nvdia.loc["2017-07-01":"2018-07-01"]

#nvdia["Close"].plot()

m=0
i=0
while m<len(nvdia.index):
  m+=i ###This is what I use but it is wrong. If I use i=m the loop is goes infinity, which really is  strange
  for i in range(m,len(nvdia.index)):
    percentage_growth=100*(nvdia["Close"].values[i]/nvdia["Close"].values[m]-1)
    if percentage_growth>=20:
        break

A: @zmf: Thank you it helped. However I needed to add an additional break statement to leave the while loop, since my condition m

In case someone might have one day same/similar issue, here is the solution
m=0
while m<=len(nvidia.index):
  for i in range(m,len(nvidia.index)):
    percentage_growth=100*(nvidia["Close"].values[i]/nvidia["Close"].values[m]-1)
    if percentage_growth>=20:
        m=i
        print(m,percentage_growth)
        break
    else:
        percentage_growth=100*(nvidia["Close"].values[i]/nvidia["Close"].values[m]-1)

  if i+1==len(nvidia.index):
      break


text:
Q: Docker images and the kernel have just spun up a docker image which is running Ubuntu 15.10 on my own machine which is still on 14.04. From what I have read, docker containers use your existing systems services, including the kernel.
How can a docker image which contains the latest version of an OS run on a machine running a version of the same OS, albeit 3 major versions behind and yet still use the same kernel?
Is the kernel a separate thing from linux OS images? And if so, are there really no issues from running different major versions of kernels (i.e. 3 -> 4) on the same OS version? I would have imagined backward compatibility issues as well as 'missing features'

A: generally, the kernel ABI for userspace does not change between kernel versions, so user space tools compiled against newer kernel versions will be able to run on older kernel versions.


text:
Q: Android ParseException getCode() returning -1 I'm trying to validate a sign up using Parse. Normally the sign up works but I'm trying to incorporate some error checks. When printing the ParseException to the logs as Log.d("Error",""+e); I get the error message.
But when I use e.getCode() instead, I don't get the error code displayed. It's -1 always.
                parseUser.signUpInBackground(new SignUpCallback() {
                    @Override
                    public void done(ParseException e) {
                        registerProgressDialog.dismiss();
                        if (e == null) {
                            // No error

                            goToProfileActivity(getActivity(), false);
                        } else {

                            Log.d("Error", "" + e);
                            signupErrorHandler(e.getCode());
                        }
                    }
                });


text:
Q: How to retrieve random JSON object by key from JSON dictionary? I have a JSON object which consists of a long list of other JSON objects which have some common properties to each other such :
var myData = {
    "0291" : { "Firstname" : "Jeremy", "Surname" : "Dyson" },
    "0398" : { "Firstnname" : "Billy", "Surname" : "Bunter" },
    "6714" : { "Firstnname" : "Harry", "Surname" : "Peterson" },
    "9080" : { "Firstnname" : "Barry", "secondname": "Joe", "Surname" : "Mainwaring"}
    ...
    ...
}

I already built an html template. With the JS, I want to pick or iterate (random pick + loop) through the objects in data{} in random order, so I can fill up the HTML on the fly for each visitor. The random part is important, so each visitor likely get a different data.
Plain JavaScript or jQuery solutions will work in the context in which this is being deployed.

EDIT: Solution I implemented is below.
1. Collect all keys :
var keyArray = Object.keys(myData);

2. Shuffle function:
function shuffle(o){ //v1.0
    for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};
keyArray = shuffle(keyArray); // shuffle it!

3. Loop to iterate:
for (var i = 0; i < keyArray.length; ++i) {
    var current = data[keyArray[i]];
    ... // what you want to do each time.
}

A: First, convert the data object to an array (the keys on the first level will be lost), like shown here: https://stackoverflow.com/a/11474071/664108
var dataArray = $.map(data, function (value, key) { return value; });

Then shuffle the array (see How to randomize (shuffle) a JavaScript array?)
Alternatively you could just shuffle the keys and then operate on the original object. This way you also have still the keys:
var keyArray = $.map(data, function (value, key) { return key; });

shuffle(keyArray); // example (shuffle function has to be implemented, see above)

for (var i = 0; i < keyArray.length; ++i) {
    var current = data[keyArray[i]];
    // do stuff with current dataset
}

Addition from the comments
the key array can also be created by:
var keyArray = Object.keys(data);

But note that this only works on modern browsers, you should not use it if you want to support Internet Explorer in versions up to IE 8 (see: http://msdn.microsoft.com/en-us/library/ie/ff688127(v=vs.94).aspx)

A: Have you think about generating the JSON randomly already or shufflng it? Shuffle in Javascript
If you shuffle the array, you can apply foreach and you get the items in a random order. :)
Note: It might be faster to shuffle just a copy of the IDs.
Disclaimer! I asuumed that for your case you need just Pseudorandomness.

A: use the Object.keys function
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']

more: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys


text:
Q: psql date_trunc issue I have a query in my psql database but I have a slight problem:
select sge_job.j_id,
       sge_job_usage.ju_id,
       sge_job_usage.ju_slots,
       date_trunc ('hour',sge_job_usage.ju_start_time) – date_trunc ('hour',sge_job.j_submission_time) as "Wait time"
from sge_job,
     sge_job_usage
where sge_job.j_id = sge_job_usage.ju_id
and   sge_job_usage.ju_start_time >= sge_job.j_submission_time

The problem is the information I get for my ju_start_time and j_submission_time will leave it within the hour format but some of them will have information thats 3 days 12hours for example.
They are both timestamp without timezone but I need it to calculate if it's 2 days and add them into hours. so my current out put is:
71 |    71 |        1 | 01:00:00
72 |    72 |        1 | 01:00:00
73 |    73 |        2 | 4 days 03:00:00
74 |    74 |        2 | 01:00:00
75 |    75 |        2 | 03:00:00
76 |    76 |        2 | 03:00:00
77 |    77 |        1 | 22:00:00
78 |    78 |        1 | 18:00:00
79 |    79 |        2 | 19:00:00
80 |    80 |        2 | 20:00:00
81 |    81 |        2 | 20:00:00
82 |    82 |        2 | 11:00:00
83 |    83 |        2 | 21:00:00
84 |    84 |        2 | 1 day 10:00:00
85 |    85 |        2 | 1 day 17:00:00
86 |    86 |        2 | 2 days 17:00:00

so with the date_trunc hour it changes my time format to how many hours, but I can't seem to get a function that will get rid of my days and put them into hour format so i would like 86's column to be 48 hours ( 2 days) + 17 = 65 hours as it's result, any suggestions what to try ? thanks in advance

A: Subtracting a timestamp from another timestamp yields an interval value. You have to convert that interval to hours in order to get your display.
To convert an interval to e.g. hours, you use the following:
extract(epoch from <interval_value>) / 3600

epoch returns seconds. Dividing that value by 3600 gives you hours.
In your case, the following should do what you want:
extract(epoch from date_trunc('hour',sge_job_usage.ju_start_time) – date_trunc ('hour',sge_job.j_submission_time)) / 3600 as "Wait time"


text:
Q: Woocommerce how to display products from specific category on archive page On my archive-product page I want to display some products from a specific category.
I tried to do this:
echo '<div>';
echo wc_get_product_category_list( 'special_items', $category ));
echo '</div>';

inside the product loop, but it doesn't work.
How can I achieve that?

A: In woocommerce some shortcode available. You may call echo do_shortcode in your template files
https://docs.woocommerce.com/document/woocommerce-shortcodes/#scenario-5-specific-categories


text:
Q: Loading local TileFile layer in pydeck Am trying to load a local TileFile layer in pydeck(0.5) in jupyter notebook
I am using the following code:
    import pydeck as pdk
    data ='https://localhost:/home/user/myfolder/tiles/{z}/{x}/{y}.png`

    layer = pdk.Layer(
      'TileLayer',  # `type` positional argument is here
      data=data
      )

    # Set the viewport location
    view_state = pdk.ViewState(
      longitude=50,
      latitude=50,
      zoom=0,
      min_zoom=0,
      max_zoom=5,
      pitch=40.5,
      bearing=-27.36)

    # Combined all of it and render a viewport
    r = pdk.Deck(layers=[layer], initial_view_state=view_state)
    r.to_html('TileLayer-example.html'

This just creates a blank view window in Jupyter where it should show an image.
If I take launch the TileLayer-example.html independently into a browser I also get a blank window, However browser (Firefox) console output is as follows:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:/home/user/myfolder/tiles/0/0/0.png. (Reason: CORS request did not succeed).

TypeError: NetworkError when attempting to fetch resource. tile-layer.js:18:56
    value tile-layer.js:18
    value tile-layer.js:136
    t tile-2d-header.js:90
    u runtime.js:45
    _invoke runtime.js:271
    e runtime.js:97
    Babel 2
        r
        u

I am not sure if the problem is CORS related (calling a local file) or if my data path is just plain wrong? I have tried may variants on path but all seem to have the same console warning issues.
Any suggestions for simple safe ways around the CoRs problem, or suggestions for accessing local TileFiles in PyDeck would be much appreciated

A: For other folk currently looking to implement TileLayer in Pydeck. It appears TileLayer is not yet documented or currently supported in pydeck and can only be achieved with a custom layer see this github issue and this suggested workaround with a custom layer
With respect to the CoRs issue of trying to display a local file resource in the browser when called from a URL. if you are looking for a quick fix to do a test/debug then in Firefox: the suggestions here help. For Firefox specifically they suggest the following:
go to about:config
search for privacy.file_unique_origin
set it to false.
Note this is a security risk so reset it to true after debugging.
The only workable solution currently seems to be to put the tilefile in the working directory from which your deck project is launched


text:
Q: What is the easiest way to mix 8bit 8000Hz PCM_ULAW samples? I want to mix to multiple ULAW samples together in Java. Is there a way to do so without converting to PCM? Im trying to do a 8000Hz 8bit VoIP app. Im testing with AU files (created in goldwave) since they use the ULAW encoding. My current implementation is:
[code]
    AudioFormat f = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 8000, 16, 1, 2, 8000, false);
    SourceDataLine sdl = AudioSystem.getSourceDataLine(f);
    sdl.open(f);
    sdl.start();

    File file1 = new File("C:\\Scream3.au");
    AudioInputStream ais1 = AudioSystem.getAudioInputStream(file1);
    AudioInputStream aisTarget1 = AudioSystem.getAudioInputStream(f, ais1);

    File file2 = new File("C:\\Blackout3.au");
    AudioInputStream ais2 = AudioSystem.getAudioInputStream(file2);
    AudioInputStream aisTarget2 = AudioSystem.getAudioInputStream(f, ais2);

    byte[] data = new byte[10000];
    int[] calc = new int[5000];
    AudioInputStream[] streams = {aisTarget1, aisTarget2};
    int count = streams.length + 1;
    while (true) {
        int r = -1;
        for (int i = 0; i < streams.length; i++) {
            r = streams[i].read(data, 0, data.length);
            if (r == -1) break;
            for (int j = 0; j < calc.length; j++) {
                int tempVal = ((data[j * 2 + 1] << 8) | (data[j * 2] & 0xFF));
                calc[j] += tempVal;
            }
        }
        for (int i = 0; i < calc.length; i++) {
            calc[i] /= count;
            data[i * 2 + 0] = (byte) (calc[i] & 0xFF);
            data[i * 2 + 1] = (byte) (calc[i] >> 8);
        }
        if (r == -1) break;
        sdl.write(data, 0, data.length);
    }

[/code]
If its not possible to mix the ulaw samples directly and I have to convert to PCM, how do I convert from PCM Format (AudioFormat.Encoding.PCM_SIGNED, 8000 Hz, 16bits, 1 channel, 2 byte framesize, 8000 frame rate, little endian)
to ULAW (8bit 8000Hz).
Do I do something like:
1) Write a WAVE header to a Byte stream
2) Write the PCM data to the byte stream
3) Get PCM AIS with AudioSystem.getAudioInputStream(byte stream)
4) Get ULAW Target AIS with AudioSystem.getAudioInputStream(ulawFormat, PCM AIS)
Any help is appreciated.
EDIT:
Trying to convert from Mu-LAW to PCM (Trying to use equation from http://en.wikipedia.org/wiki/Ulaw):
[CODE]
    AudioFormat f = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 8000, 8, 1, 1, 8000, false);
    SourceDataLine sdl = AudioSystem.getSourceDataLine(f);
    sdl.open(f);
    sdl.start();
    File file1 = new File("C:\\scream3.au");
    FileInputStream fis = new FileInputStream(file1);
    // Skip header
    fis.skip(24);
    byte[] data = new byte[8196];

    while (true) {
        int r = fis.read(data, 0, data.length);
        if (r == -1) break;
        for (int i = 0; i < r; i++) {
            float y = ((float) data[i] / Byte.MAX_VALUE);
            float sample = -1.0f * (float) (Math.signum(y) * (1.0f / 255.0f) * (Math.pow(1 + 255, Math.abs(y)) - 1.0f));
            data[i] = (byte) (sample * Byte.MAX_VALUE);
        }
        sdl.write(data, 0, data.length);
    }
    sdl.drain();
    sdl.stop();
    sdl.close();
    fis.close();

[/CODE]

A: I would convert from/to linear encoding by hand, one sample at a time, using the formulas from Wikipedia:μ-law algorithm.
Example code (based on OP's code):
float sample1 = Math.signum(y1)/255.0*(Math.pow(256, Math.abs(y1))-1);
float sample2 = Math.signum(y2)/255.0*(Math.pow(256, Math.abs(y2))-1);
float combined = somethig * sample1 + (1-something) * sample2;
float result = Math.signum(combined)*Math.log(1+255*Math.abs(combined))/Math.log(256);


text:
Q: avoid middle whitespace in UITextField I am new to Iphone development. I have tried the following code, but it does not work with middle whitespace in UITEXTFIELD.
NSString *t1 = [txt.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

How can I avoid middle whitespace?

A:
Use this code may this use full.
NSString *t1=[txt.text stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];

A: NSString *t1= [txt.text stringByReplacingOccurrencesOfString:@" " withString:@""]


text:
Q: How do I integrate PrivateIdentity authentication at HTML level? I want to integrate Private Identity authentication into my web app, at the HTML level. How do I do that? Where do I find the iframe code and how do I get an API key?

A: If you want to integrate private identity into your web app, you can get the iframe code from https://github.com/openinfer/PrivateIdentity/wiki/DIV-HTML and for API key you need to go to AWS Marketplace and subscribe to Private Identity then you will get the API key Another way you can contact to support@private.id


text:
Q: SCDF: Can I use an outside microservice as a source? I am trying to work through a solution where the workflow is like this:

*

*User hits a microservice to upload images

*That microservice de-duplicates the image and if it really is new, queues it up for processing

*The processing chain lives in Spring Cloud Dataflow

The microservice already exists, and we are trying to extend it to do the fancy processing.  My initial cut was to use the Http Source from the sample starter pack since that would be something I didn't have to create.  The problem is that the source doesn't register itself with Spring Discovery server, so there is no way to get an end point without making gross assumptions (like it lives on the dataflow server at port XYZ).
We can create a Queue endpoint and send the data directly a Queue source that receives the outside event and forwards it to an SCDF queue.
What would be awesome is if DataFlow could connect the start of the queue for me, without repackaging the microservice as a Source.
The major issue with Spring Data Flow is that it does not automatically start up deployed streams when the server starts up, and we need to be reasonably sure that microservice is always up.

A: The lifecycle of the server is decoupled from the apps it deploys, that was intentional.
I'm not following your thoughts on how dataflow could connect the start of the queue, but from your description there's a few things you could do:
You would need to modify the app in order to have it registered with eureka, but this is a very simple operation, no more than a few lines of code:

*

*You can either start from a stream app perspective: https://start-scs.cfapps.io/ , select http source, your binder, and then add the spring-cloud-netflix library as well as @EnableDiscoveryClient at the Main boot class

*Start with http://start.spring.io Select Stream Rabbit or Stream Kafka, add Web and netflix libraries, then add the @EnableDiscoveryClient and @EnableBinding annotations and create a simple HTTP endpoint for your use case.
In any case should be a small addition.
You can also open an issue at :https://github.com/spring-cloud-stream-app-starters/http/issues suggesting that we add @EnableDiscoveryClient to the http source app, we can take that in consideration on our next iteration as well.

A: I'll try to clarify few bits.

upload images -> if it really is new -> queues it up for processing

Upon a new upload event, you'd want to process the image. Here's a similar use-case, but more of a real-time streaming style solution. This is not what you're looking to do, but I thought it might be useful.
Porting the image processing code to a Spring Cloud Stream application is as simple as adding @EnableBinding(Processor.class). It is the same business logic - whether you're running it separately or orchestrating it via SCDF, it is still a standalone microservice. However, SCDF expects it to be either a Source, Processor, Sink, or Task application types. We will be opening this up to support any arbitrary "functions" (lambdas) in the future release.

We can create a Queue endpoint and send the data directly a Queue source that receives the outside event and forwards it to an SCDF queue.

This is one of the standard solutions. You can directly consume new events (images) from a queue/topic and process it in the image-processor that we created in previous step. The named-channel support in DSL facilitates just that.

What would be awesome is if DataFlow could connect the start of the queue for me, without repackaging the microservice as a Source.

I'm not sure I understand this. If I were to assume, you're looking for "named-channel" as source and that is supported.

The major issue with Spring Data Flow is that it does not automatically start up deployed streams when the server starts up, and we need to be reasonably sure that microservice is always up.

The moment you deploy a Stream in SCDF, all the individual steps included in the DSL (i.e., stream definition) are resolved and deployed as standalone apps in the target runtime (cloud foundry, kubernetes, etc.,). Once deployed, it is left to the platform where the apps run for lifecycle management. SCDF does not retain or track the app states.


text:
Q: Align graphs in Jupyter Notebook When I draw graphs in a Notebook I would like to have them aligned but the graphs will shift more to the right if the values on the y-axis are big since numbers then take more space.
How can I make the graphs (actually the x-axis) to be aligned?


text:
Q: No Retain Cycle, But why still got retain cycle warning? I am trying to use UIImageView extension of AFNetworking2.6.3 to get images from a remote server. everything works fine, images have returned and rendered successfully. but I get a retain cycle warning in Xcode7.3.1: Capturing 'cell' strongly in this block is likely to lead to a retain cycle
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if(self.dataSourceModel) {
        Model *model = self.dataSourceModel.items[indexPath.row];
        NSURL *url = [NSURL URLWithString:model.imageURL];
        NSURLRequest *theRequest = [NSURLRequest requestWithURL:url];
        UIImage *placeholderImage = [UIImage imageNamed:@"placeholder"];

        //I don't use __weak cell in the block
        [cell.imageView setImageWithURLRequest:theRequest placeholderImage:placeholderImage success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull image) {
            cell.imageView.image = image; //get warning at this line
            [cell setNeedsLayout];
        } failure:nil];
    }
    return cell;
}

I can see since the cell instance has been captured in the block, so the block has the ownership of the cell instance(and cell.imageView as well). if the retain cycle really exists, the cell or imageView should have the ownership of the block.
but I have reviewed the UIImageView+AFNetworking.h and UIImageView+AFNetworking.m source code, the UIImageView doesn't have any property of blocks. the block is just a parameter of the method, not a instance variable. UITableViewCell doesn't have the ownership of the blocks either.
I even used Leaks to check, and Leaks didn't report any error.
So I believe there is no retain cycle here, but why I still get the Xcode warning here ?? If I use __weak cell__weak UITableViewCell *weakCell = cell;, the warning will go away. But I still wanna know:

*

*does it have a retain cycle here?

*do I really need to use __weak cell?

*or maybe imageView or cell really has the ownership of the block which I didn't realize?

Any hints will help, thanks a lot.

A: There's certainly no retain cycle, and you can avoid the warning by omitting the code in the completion block.  Taking a look at the AFNetworking imageView subclass (line 152), the culminating point of setImage... is to set the image view's image.  There's need for your code to set it again, or to change the layout state.
There should also be no need for if (self.dataSourceModel).  If the datasource is built right, we've answered the number of rows in tableView:numberOfRowsInSection:, and that answer is zero when the model is empty, avoiding the call to cellForRow... altogether.


text:
Q: Get a working toolbar in a UIPickerView Swift So I have a textfield that uses a pickerview. But for some reason as of iOS 11.x it doesn't seem to show up. I can't seem to figure out why. I have looked at some of the other questions and it seems my implementation is the same, yet the toolbar does not appear on loading the picker view.
Below is the code where I declare and set the toolbar for the pickerview :
let picker: UIPickerView
    picker = UIPickerView(frame: CGRect(x: 0, y: 200, width: view.frame.width, height: 300))

    picker.showsSelectionIndicator = true
    picker.delegate = self
    picker.dataSource = self

    let toolBar = UIToolbar()
    toolBar.barStyle = UIBarStyle.default
    toolBar.isTranslucent = false
    toolBar.tintColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 1)
    toolBar.sizeToFit()

    let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(UploadViewController.donePicker))
    let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)

    toolBar.setItems([spaceButton, doneButton], animated: false)
    toolBar.isUserInteractionEnabled = true

    requestTextField.inputView = picker
    requestTextField.inputAccessoryView = toolBar

A: You need to make sure that you declare translatesAutoresizingMaskIntoConstraints = false or else any constraints you set won't work.
Also it doesn't look like you have any constraints. But before you can add constraints to the view make sure that the view is added to the parent - if this is not done either through storyboards or using view.addSubView(picker) the constraints will cause your app to crash.
Use this example to add constraints to your view.
picker.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor)
In addition, use view.leadingAnchor for the left constraint and view.trailingAnchor for the right instead of view.frame.width for the width of your UIPicker