Advanced search in Multidomain - Multilanguage catalog webpage Drupal 7

Question: I have a quite complex products database. I have migrated most of the content and hierarchy into Drupal taxonomy, content type and relationships scheme. However, I am not sure if I will be able to configure some Advanced search module to look for products according to name of product, category (taxonomy) and other intrincate parameters. Can you advice some module which is easy to configure and write own MySQL search strings?
Answer: There are at least two options. You can use the Views module to expose search filters on the products.
If you have access to an Apache Solr search server you can use some of the modules that integrate with Solr for advanced searching.


Untouchable UITableViewCell

Question: I have table view cell with segmented control on it. I want to make my cell untouchable. It shouldn't highlight grey when user touches it. If I set user interaction enabled property to false, segmented control, doesn't work. How should I make my cell untouchable to work with segmented control.
Answer: Undtouchable means, that there is no User Interaction allowed (also with all your Controls inside your Cell)
If you just want to remove the cell selection, set this to None:
<code>cell.selectionStyle = UITableViewCellSelectionStyleNone;
</code>
Comment: This will disable the colour when touched. If you also want to disable to selection action, return `nil` from `-tableView:willSelectRowAtIndexPath:` for that row.
Answer: As @thelaws said, tableView:willSelectRowAtIndexPath: should be used here, generally it is used when you want to select some other row ( row other than selected by the user) but if you return nil, it will not select any row.
And for disabling selection color just use
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];

Untouchable UITableViewCell


There are no redirect URIs registered with DocuSign

Question: We went live with DocuSign integration a while back. In the development, we're able to authenticate the DocuSign credentials of the user and then they're able to send documents for eSign.
After going live, our customers trying to authenticate their DocuSign credentials on our app are getting URI not present error.
Any idea where we're going wrong.
Answer: You need to configure the key again in the production environment.
These URIs are not copied over for you even after you went live.


Which graphs solution for Drupal 7 can be used to upgrade my Open Flash Chart solution from Drupal 6?

Question: I have upgraded from Drupal 6 to Drupal 7 and for me, everything is better in Drupal 7 until I hit this problem.
What I'm trying to achieve:
I have to create and show graphs to users depending on whatever the data they have stored on the site, I mean I have collected the data and stored in a Mysql database. I now have to fetch these data from that Mysql database and display it as a neat graph.
In drupal 6, making such dynamic graph is a cake walk..! I used Charts and graphs module with "Open Flash Chart" to create some very interactive and pretty graphs. But it does not has a Drupal 7 version..!
Attempting to use the 'Charts' module fails:
Then I searched for one that could work in D7 and found the charts module. It looked very promising and has a Drupal 7 version too. So I tried to install it, but I can simply not get it to work! I found a patch, but still no luck. Even if I get it to work, it will only work with Google Charts and not with Open Flash Charts or Fusion Charts because it requires those charts to be installed by us and Open Flash Charts or Fusion Charts, do not have a D7 version..!! FYI, the same problem existed in D6: when I installed everything (even Open Flash Chart API), it said "no chart plugin installed". And not even a single line of documentation is provided regarding how to install these plugins and make other charts work. Hence I think its out of the picture.
My Question(s): So what can I do now..?? How can I create graphs..? What can I use..??
Update about this question:
Since I didn't find any graphs module that I could use in my Drupal 7 site, I tried using an external PHP charting library "pChart". I configured everything without getting any errors or warnings, but I only get a bizarre output ...
I have explained everything in detail, along with the code I have used to create the graph in my (new) question What is causing the unusual output when trying to create charts in Drupal 7 using the pChart library? Any help to answer that new question would be greatly appreciated!
Comment: Have you tried [Views Dataviz](http://drupal.org/project/views_dataviz)? Here's a quick [how-to video](http://codekarate.com/daily-dose-of-drupal/views-dataviz-module)
Comment: Well, thanks for your response. I finally, solved my problem by using fusion Charts free, http://www.fusioncharts.com/goodies/fusioncharts-free/  . Views Dataviz really looks interesting as it would even work on iphone n ipad...! upvote for the suggestion..:)
Answer: I've used highcharts script before, not with this module, but it might work for you http://drupal.org/project/highcharts
Comment: Hicharts, looks really cool.. but at the time I was looking for a graphs module, it lacked some good documentation I guess, am not sure though..:) Thanks for reply.
Answer: A few years later now, but the question seems still relevant. That's one of the reasons why I started my Comparison of Charting Modules. Then I started working on Chart 2.0 ...
Recently I extended the above mentioned comparison with Maintenance Scorecards for all Native Charting Modules. Consider using these scorecards to decide about using which "charting modules" these days.
Disclosure: I'm a (co-)maintainer of some of the charting modules mentioned,
I hope this does not violate the site's policy on self-promotion.
Comment: Thanks a lot for your contributions! I'm working on a project that we need quite many charts, and I considered to use chart module. But the API was somewhat unclear and coupled with the charting library (Google chart for example). We ended up inventing our own wheel, but I am more than happy to assist for a 2.x version.
Comment: Thank you Ayesh for your feedback. I can picture how you confused you were about chart, charts, Google-something-libs, etc (I still am a little bit too). To provide assistance, please look at "Chart 2.0" at https://www.drupal.org/node/2368793 ... or look at the "HowTo contribute" community pages of either Chart or Charts. And consider my hint above for the "funding" of bounties I want to start launching. Last but not least: the "chart"-deadline of April 2015 is getting close, but "my" solution for it also (can't give details on that right now yet, sorry).


Timeline bar with colour/fill based on time-series' value (R ggplot)

Question: I've got a time-series data frame with pressure readings taken at regular intervals.
                  time   pressure        diff
1 2014-09-09 09:12:29  1.6191598  0.00000000
2 2014-09-09 09:12:28  3.0137784 -0.07668387
3 2014-09-09 09:12:27  1.1958183  0.58693260
4 2014-09-09 09:12:26  2.2803681  1.07774954
5 2014-09-09 09:12:25 -0.7614310 -0.17864232
6 2014-09-09 09:12:24  0.9914106 -0.70121973

I can easily make a line plot of the pressure using ggplot2. But below this line plot, I'd like to have a horizontal bar where the fill colour depends on the pressure differential between two consecutive samples (df field diff).
For example, the bar would be white at times where the pressure differential is zero (i.e. pressure has not changed bewteen two consecutive samples). The fill colour would go towards a deeper shade of (say) red as the differential increases positively, and blue as it increases in the negative values.
generate sample data:
 dfTimeSeries <- data.frame(time = Sys.time()-seq(1:10),
                            pressure = rnorm(10,1),
                            diff = c(0,diff(dfTimeSeries$pressure)))

First part of the plot
 ggplot(data = dfTimeSeries)+
     geom_line(aes(x=time, y=pressure))

How can I code this horizontal bar that would span along the entire x (time) axis and whose fill colour would vary based on the on the  diff field of my df for the corresponding timestamp?
Comment: I just thought I could use `geom_rect()` to draw rectangles side-by-side on one horizontal line, and set `aes(  [...]  fill=diff)`?
Is there a better way ?
Comment: `geom_rect` is certainly how I'd do it.
Answer: I ended up putting geom_rect objects side-to-side, one rectangle for each value of diff. Here's the basic concept:
ggplot(data = dfTimeSeries)+
  geom_line(aes(x=time, y=pressure))+
  geom_rect(aes(xmax=time+.5, xmin=time-.5,ymax=-3,ymin=-2, fill=diff))

I'd need to to adjust the colour scale, fit the bars in a different graph, and do a bit more cosmetic arrangmeents, etc.


Sampling from degree distribution of graph

Question: I have a simple, stupid Python problem. Given a graph, I'm trying to sample from a random variable whose distribution is the same as that of the degree distribution of the graph.
This seems like it should pretty straightforward. Yet somehow I am still managing to mess this up. My code looks like this:
import numpy as np
import scipy as sp
import graph_tool.all as gt

G = gt.random_graph(500, deg_sampler=lambda: np.random.poisson(1), directed=False)
deg = gt.vertex_hist(G,"total",float_count=False)

# Extract counts and values
count = list(deg[0])
value = list(deg[1])

# Generate vector of probabilities for each node
p = [float(x)/sum(count) for x in count]

# Load into a random variable for sampling
x = sp.stats.rv_discrete(values=(value,p))
print x.rvs(1)

However, upon running this it returns an error:
Traceback (most recent call last):
  File "temp.py", line 16, in <module>
    x = sp.stats.rv_discrete(values=(value,p))
  File "/usr/lib/python2.7/dist-packages/scipy/stats/distributions.py", line 5637, in __init__
    self.pk = take(ravel(self.pk),indx, 0)
  File "/usr/lib/python2.7/dist-packages/numpy/core/fromnumeric.py", line 103, in take
    return take(indices, axis, out, mode)
IndexError: index out of range for array

I'm not sure why this is. If in the code above I write instead:
x = sp.stats.rv_discrete(values=(range(len(count)),p))

Then the code runs fine, but it gives a weird result--clearly the way I've specified this distribution, a value of "0" ought to be most common. But this code gives "1" with high probability and never returns a "0," so something is getting shifted over somehow.
Can anyone clarify what is going on here? Any help would be greatly appreciated!
Comment: You say "if I write instead" but you copy down the same line, should there be a different line?
Comment: Ah yes, you're right. I've made the edit.
Comment: Does `range(len(count))` have the same values as `value`?
Comment: I believe it does. It lists from 0 up to max degree in the graph, which is what `value` should return as well. But let me double check...
Comment: Yes, it does. But no matter, your solution below fixed the problem. I'm still not sure what the error message is exactly saying, but hey, whatever works...
Answer: I believe the first argument for x.rvs() would be the loc arg.  If you make loc=1 by calling x.rvs(1), you're adding 1 to all values.
Instead, you want
x.rvs(size=1)

As an aside, I'd recommend that you replace this:
# Extract counts and values
count = list(deg[0])
value = list(deg[1])

# Generate vector of probabilities for each node
p = [float(x)/sum(count) for x in count]

With:
count, value = deg       # automatically unpacks along first axis
p = count.astype(float) / count.sum()  # count is an array, so you can divide all elements at once

Comment: I may be mistaken, but earlier versions of python might force a hidden integer division on your normalization. You may want to cast (`.astype`) an array to a floating point representation.
Comment: Thanks @Hooked, done.  An alternative solution would be `from __future__ import division` which is what I usually use.
Comment: Ah, this is great. Thanks for clearing that up. I should've paid more attention to the documentation. Anyways, you're helping me a lot. I appreciate it!


Is a closed convex subset of a Hilbert space with empty interior necessarily thin?

Question: Let's say that a subset $C$ of a real Hilbert space $H$ is thin if for every $\epsilon>0$ there exists a hyperplane $M$ such that $C$ is contained in the $\epsilon$-neighborhood of $M$. Equivalently, $C$ is thin if for every $\epsilon>0$ there exists a unit-norm linear functional $f$ on $H$ such that $\operatorname{diam} f(C)<\epsilon$.
Suppose $C\subset H$ is closed, convex, and has empty interior. Does it follow that $C$ is thin?
Remarks

Such $C$ need not be contained in a hyperplane: the Hilbert cube is an example.
Every compact subset of $H$ is thin, but $C$ need not be compact: e.g., it could be a hyperplane itself.
It's necessary to assume that $C$ is closed; otherwise, $\ell^1 \subset \ell^2$ (or any other dense subspace) would be a counterexample.
The same question could be posed in other normed spaces.
Answer: I think here is a counterexample: the non-negative cone in $L_2[0,1]$
$$
C=\{x\in L_2\colon x\ge 0\text{ a.e.}\}.
$$
Clearly, it is a closed convex set with an empty interior.
On the other hand, $L_2=C-C$ since any $x\in L_2$ can be split as $x=x_+-x_-$ where
$$
x_+=\max\{x,0\},\quad x_-=\max\{-x,0\}
$$
are the positive resp. negative part of the function $x$. If $|f(C)|\le\epsilon$ then
$$
|f(L_2)|\le |f(C)|+|f(C)|\le 2\epsilon<1
$$
for small enough $\epsilon$, which contradicts the unity norm assumption on $f$.
Comment: Oh... and the same example works in the sequence space $\ell^2$. And you don't need small $\epsilon$, since $f(L_2)$ has to be all of $\mathbb R$ for any nonconstant $f$... a nonconstant functional cannot be uniformly bounded on the space.
Comment: @Gerry My first reaction was that in $\ell^2$ the interior of the non-negative cone is not empty, but you are right, it works since $x_n\to 0$.


Multiple Counting Buttons JS

Question: I'm trying to create something a page that creates post so every time someone clicks a button it creates a text with another button to like. I want each separate like button to be incremented upon clicking but it doesn't work. Either only one count is updated or none. I'm using HTML5 and CSS with javascript.
$(function(){
$('.input_button').on('click', function(){
    text = $('.input_text').val();
    var btn = document.createElement("BUTTON");
    var t = document.createTextNode("Like");

    btn.appendChild(t);
    document.body.appendChild(btn);
var clicks = 0;
    btn.onlick = function() {
        clicks += 1;
    document.getElementById("clicks").innerHTML = clicks;
    };
    if (text != undefined) {
        post = '
' + '' + '
jaleelg:
' + text +
        '
Clicks: 0
' + "
" + Date() + " " + '
';
        new_post = $('.post_feed').append($(post))
        new_post = $('.post_feed').append($(btn))
    }
});

});
Comment: Some code, please... Have you actually tried anything?
Comment: yes i added the code
Comment: Did you get any errors?
Answer: There were a bunch of things wrong with the code, but I fixed them: https://jsfiddle.net/yak613/opoy49ox/
$(function(){
$('.input_button').on('click', function(){
    text = $('.input_text').val();
    var btn = $("<button></button>");
    btn.text(text);
    $("body").append(btn);
    btn.after("")
    var clicks = 0;
    btn.click(function() {
        clicks++;
        $(this).next(".clicks").html(clicks);
    });
    if (text != undefined) {
        post = '
' + '' + '
jaleelg:
' + text +
        '
Clicks: 0
' + "
" + Date() + " " + '
';
        new_post = $('.post_feed').append($(post))
        new_post = $('.post_feed').append($(btn))
    }
});
});

Comment: This overrides the first count every time one of the new button counts is clicked. I had something similar in one of my trials. I need each button to have it's own count.
Comment: works in the link but not in the complete code but thank you very much I guess it's just my error now! Thanks!
Answer: this is how to make a button:
**function onClick() {
    clicks += 1;
    document.getElementById("clicks").innerHTML = clicks

<button type="button" onClick="onClick()">Click Me!</button>

clicks: $0

**

Multiple Counting Buttons JS


Use entity_uri or drupal_path_alias()?

Question: What are the difference? And when should you use which one?
entity_uri() is rather new to me (Drupal 7) and I see it little used. But it appears to be a lot cleaner and better performing then drupal_get_path_alias().
FYI: I want to get some background information to deal with an issue on Tagadelic.
Answer: These functions actually have not much in common. There is no question of using one or the other. You will in fact use both of them, although you will most likely not call drupal_get_path_alias() directly.
entity_uri() returns an array that contains the path and options to link to an entity. So for example for a node, you call it like this: entity_uri('node', $node) and it will return node/$node->nid. That's kinda trivial. It gets more interesting with other entity types, like private messages (where the path is messages/view/$message->thread_id#privatemsg-mid-$message->mid).
You use the returned array like this: url($uri['path'], $uri['options']) (or similarly with l()). Then, that function will call drupal_get_path_alias() internally to check if there is an alias for that internal path and will use that.
The idea is that you can generate the internal path for any entity, without any kind of special handling. A real life example is the Userpoints project. Userpoints transactions support to reference an entity by specifying type and id (Yes, Userpoints used the entity_type terminology since Drupal 5...). Previously, there was a large bunch of code with support for nodes, comments and users and a custom hook to be able to support more things. When I ported the module to Drupal 7, I was able to replace all that with a simple call to entity_uri() and it now supports all entities out of the box: userpoints_create_description().
Answer: The 'problem' with a lot of entity-centered functions is that the entity type is a required parameter. (I ran into that before...) Also, entity_uri() requires a fully loaded entity, so I guess it may be bad for performance if you have to do a lot of entity_uri calls.
On the other hand, drupal_get_path_alias requires you to know (read: hard code) the url patterns (like node => node/[nid]) for every entity type. That might be OK for a a custom module, but it could break in a contrib module that is supposed to work with all kinds of entities.
Answer: entity_uri() returns the URI associated with the entity passed as argument, while drupal_path_alias() returns the alias of the path passed as argument, which could also be not associated with an entity (which is what happens with URLs to administrative pages).
For example, if you have an alias for example.com/node/1 (e.g. example.com/home), the following code would set $alias to "home."
$alias = drupal_get_alias('node/1');

The following code would set $path to "node/1."
$node = node_load(1);
$uri = entity_uri('node', $node);
$path = $uri['path'];

In the latter case, you could have used "node/" . $node->nid. Using entity_uri() allows you to get the correct URI, even in the case the URI associated with nodes are changed, and the same code works for different type of entities.

Use entity_uri or drupal_path_alias()?


If $a_{2n}-a_n\to 0$, does the sequence $a_n$ have a limit?

Question: Is this claim true or false?

Given $\lim \limits_{n\to \infty}\ (a_{2n}-a_n)=0$ then $\lim \limits_{n\to \infty}\ a_n$ exists.
Comment: This one is worth thinking about for a long time on your own before seeking hints.
Comment: False. Take $a_n=\log\log n$
Answer: It's false: take $a_n = 1$ if $n = 2^m$ for some $m$, and $0$ otherwise.
Comment: Very nice!$\ \ $


How to Make .exe file for P.H.P. offline Application with Security

Question: I have shown this Convert a PHP script into a stand-alone windows executable , but my problem is still remains :(
I have developed a Offline Application using Core P.H.P., now I want to Sell it to my client, but my problem is that I don't want to allow Client can see my Source code or can access my Source code, they can run my application on their system but cannot able to change the Code.
If I made the .EXE of my application, user cannot even copy my source code, if he/she had done this then it cannot remains useful for them,
AND ALSO THE MAIN THING IS I WANT A UNIQUE SECURITY FOR A PARTICULAR USER, EVERY USER SHOULD NOT HAVE THE SAME ACCESS KEY TO ACCESS THIS APPLICATION
I have found this on GOOGLE and also on this SITE also,but still I didn't get my answer perfectly.
Actually I have no idea about this in P.H.P, If somebody found mistakes in my question then you are pleased to suggest me.
Comment: http://stackoverflow.com/questions/9046675/convert-a-php-script-into-a-stand-alone-windows-executable
Comment: Even if you "convert" or "compile" it to .exe you can always reverse engineer it. Also I think it would be fairly simple to do so. If you're afraid about them ripping your code host it yourself and ask for a monthly fee.
Comment: Just because you state what you want and scream a bit in caps and bold will not get this questions reopened. Show you have done research to all parts (obfuscation, license keys, generating one per client) and show you understand enough about it to do it yourself. Then if you have a programming-specific problem you cannot solve, ask a new question. The perfect answer to your question as you require may not be on the web; you are a developer to tie small working parts together in a larger problem-solving solution.
Comment: @Sagar I am not an owner nor a moderator, just somebody who sometimes has some spare time on his hands. I will not use that time to help people who are not willing to show what they have tried. Being a beginner does not keep you from reading about the subject and showing what you understand. Now your question just says _"I need a ready-made solution, pronto"_, which is not what this site is for. If anything you found does not solve your problem directly, does not mean you cannot use that solution at all. Name what you found and tell what you miss about it.
Comment: In this case there is no need to vote down this question, I am not harassing or disturbing you, then why you VOTED me down
Comment: i have tried (http://stackoverflow.com/questions/9046675/convert-a-php-script-into-a-stand-alone-windows-executable) this all web-sites trick and also downloaded this soft's, and also run this all, but i am not getting perfect answer
Answer: You can use PHP LockIt Software. it will encode your code and your client can not modify your code.
Comment: I have use this software and it works well, but how many times I have to run this software ? I have many clients to buy this app.. Your answer is good, but not perfect
Comment: You can lock root folder.
Comment: @Sagar so any obfuscation software that doesn't support multi-user configurations out of the box you cannot use? Do you even want to program?
Answer: Take a look at hiphop php. A good and reliable 'compiler' for PHP
http://en.wikipedia.org/wiki/HipHop_for_PHP
https://github.com/facebook/hiphop-php/
Comment: @Robert Podwika, I have found some solutions thank you
Answer: Check Zend Guard.
Zend Guard, the most widely accepted PHP encoding and obfuscation product on the market, protects your application from unlicensed use and reverse engineering.

Prevent reverse engineering & unauthorized modifications
Protect your code from unauthorized use
Zend Optimizer and Zend Guard Loader - the free runtime decoders for Zend Guard

It's really good solution to protect your project.


Returning an array from function to main sub

Question: I'd like to store all tab names in a string array, that I'll later use for other things. My current problem is, that I'd like to populate my array in a separate function and when thats done, hand it back to my main sub.
It throws

Can't assign to array

as an error, what am I'm not seeing here?
Sub Captions_Formatting()
    Dim tabName() As String
    Dim totaltabs As Long
    Dim ws As Worksheet
    Dim captionlines As Integer

    totaltabs = get_Tabs
    tabName = getTabNames(ws, totaltabs)

End Sub

Function getTabNames(ws As Worksheet, totaltabs As Long) As String()
Dim i As Integer
ReDim tabName(totaltabs)

    For Each ws In Sheets
        If ws.Name <> "Overview" Then
            tabName(i) = ws.Name
            i = i + 1
        End If
    Next ws

getTabNames = tabName

End Function

Thanks a lot!
Comment: try `Function getTabNames(ws As Worksheet, totaltabs As Long) As Variant`
Comment: Your function has two arguments, which you are not populating.
Answer: You need to type your array to match the function return type:
ReDim tabName(totaltabs) As String

If you do not then its an array of variants and such a thing cannot be cast to an array of strings automatically (or at all).
Comment: Hi Alex, thanks a lot, thats it! I wasn't aware that if I redim an array, it also needs a type, since it was initially dimmed as string()
Comment: Well the tabName in Captions_Formatting is a string but its local to that function so the tabName in getTabNames is a completely separate thing.
Comment: Ah ok, if I'd like to use the same array I probably need to pass the array by using byRef, correct?
Comment: Yes you could, although no point in this case as you return the data anyway.


Optimizing Bash script, subshell removal

Question: I have a bash script that lists the amount of ip addresses connected on a port. My issue is, is that with large amounts of connections it is slow as poo. I think it is because of the subshells in use, but I am having trouble removing them without borking the rest of the script. Here is the script in its entirety as it is fairly short:
    #!/bin/bash

    portnumber=80
    reversedns_enabled=0

    [ ! -z "${1}" ] && portnumber=${1}
    [ ! -z "${2}" ] && reversedns_enabled=${2}

    #this will hold all of our ip addresses extracted from netstat
    ipaddresses=""

    #get all of our connected ip addresses
    while read line; do
            ipaddress=$( echo ${line} | cut -d' ' -f5 | sed s/:[^:]*$// )
            ipaddresses="${ipaddresses}${ipaddress}\n"
    done < <( netstat -ano | grep -v unix | grep ESTABLISHED | grep \:${portnumber} )

    #remove trailing newline
    ipaddresses=${ipaddresses%%??}

    #output of program
    finaloutput=""

    #get our ip addresses sorted, uniq counted, and reverse sorted based on amount of uniq
    while read line; do
            if [[ ${reversedns_enabled} -eq 1 ]]; then
                    reversednsname=""

                    #we use justipaddress to do our nslookup(remove the count of uniq)
                    justipaddress=$( echo ${line} | cut -d' ' -f2 )
                    reversednsstring=$( host ${justipaddress} )
                    if echo "${reversednsstring}" | grep -q "domain name pointer"; then
                            reversednsname=$( echo ${reversednsstring} | grep -o "pointer .*" | cut -d' ' -f2 )
                    else
                            reversednsname="reverse-dns-not-found"
                    fi

                    finaloutput="${finaloutput}${line} ${reversednsname}\n"
            else
                    finaloutput="${finaloutput}${line}\n"
            fi
    done < <( echo -e ${ipaddresses} | uniq -c | sort -r )

    #tabulate that sheet son
    echo -e ${finaloutput} | column -t

The majority of the time spent is doing this operation: echo ${line} | cut -d' ' -f5 | sed s/:[^:]*$// what is the best way to inline this to produce a faster script. It takes well over a second with 1000 concurrent users (which is my base target, although should be able to process more without using up all of my cpu).
Comment: This is not an unreasonable script. Try running it from the command line using the `-v` option to `bash` -- e.g. `bash -v script-name`. That option will print each line as it is read. See if any noticeable delay occurs just after a line is printed to the screen. That would be the place to start looking for performance issues in your script.
Comment: Add the `-t` option to `netstat` to restrict the output to just TCP sockets (So you don't need to filter out UNIX sockets), and remove the `-o` option since you don't seem to be doing anything with the extra timing output. Also, all that buffering in to variables is unnecessary if you embrace pipelines; for example, here's a single pipeline that I believe accomplishes what the non-reverse-DNS branch of your code above does: `netstat -nta | awk 'match($4,/:80$/) && $6=="ESTABLISHED" {sub(/:[0-9]+/,"",$5); print $5}' | uniq -c | column -t | sort -nr`
Comment: Aha, thank you for that, I did not know of the -v switch. So, the issue is with the subshells I believe- this line in particular: echo ${line} | cut -d' ' -f5 | sed s/:[^:]*$//
Comment: I appreciate that @ElliottFrisch, you are correct.
Answer: I'll take a stab at a couple of issues:
The following line from the script which performs incremental string concatenation will not be be efficient without the means to allocate a reasonable buffer:
ipaddresses="${ipaddresses}${ipaddress}\n"

For another, using a while loop with read line when a pipeline will do is significantly worse than the pipeline. Try something like this instead of the first loop:
netstat -ano |
grep -v 'unix' |
grep 'ESTABLISHED' |
grep "\:${portnumber}" |
cut -d' ' -f5 |
sed 's/:[^:]*$//' |
while read line; do ...

Also, try combining at least two of the three sequential grep commands into one invocation of grep.
If nothing else, this will mean you are no longer spawning a pipeline which creates new cut and sed processes for each line of input processed in the first loop.
Comment: @jett Whether you redirect into a Unix shell `while` loop using a pipe -- i.e. `|` -- or another stream redirection like `<` makes no difference. That is a feature of Unix shells, pipe, and standard input, output, and error.
Comment: @jett As far as any performance with "subshells" in your script, the single best thing you can do is to use pipes and not spawn new Unix processes for each line of input. Either the body of a `while` loop should use only Bash built-in commands, or the work per line performed in the body of the loop should be significant enough per line of input to justify the resources used. But again, if a pipeline can be used instead of a `while` loop use it. Use it even if you need to use temporary files as buffers because of the requirements of conditional logic.
Comment: Perhaps I'm misunderstanding you here, but as far as I can tell the pipeline into while method will not actually work? Is it just an toward refactoring or should it actually be working as is?
Answer: You could reduce that with cut -d' ' <<< "$line" | sed ....  You could write a more complex sed script and avoid the use of cut.
But the real benefit would be in avoiding the loop so there's only one sed (or awk or perl or …) script involved.  I'd probably look to reduce it to ipaddresses=$(netstat -ano | awk '...') so that instead of 3 grep processes, plus one cut and sed per line, there was just a single awk process.
ipaddresses=$(netstat -ano |
              awk " /unix/           { next }  # grep -v unix
                   !/ESTABLISHED/    { next }  # grep ESTABLISHED
                   !/:${portnumber}/ { next }  # grep :${portnum}  "'
                                     { sub(/:[^:]*$/, "", $5); print $5; }'
             )

That's probably rather clumsy, but it is a fairly direct transliteration of the existing code.  Watch for the quotes to get ${portnumber} into the regex.
Since you feed the list of IP addresses into uniq -c and sort -r. You probably should use sort -rn, and you could use awk to do the uniq -c, too.
The only bit that you can't readily improve is host; that seems to only take one host or IP address argument at a time, so you have to run it for each name or address.
Comment: For examples of `awk`, see [Programming Pearls](http://www.cs.bell-labs.com/cm/cs/pearls/). Almost all of the articles were originally printed in the [Communications of the ACM](http://cacm.acm.org/) to present small programming problems and solutions. `Awk` was used for the code samples even though the articles were not about `awk`.
Comment: Replacing a process — or three processes — per line with a single process for all lines is almost invariably a huge performance win.  I can't think of many situations in which it would not be a big win.
Comment: Yes, `awk` would be a very good choice to replace everything in the first loop that is applied to the output of `netstat`. That includes the three invocations of `grep`...
Comment: Very interesting, extremely fast as compared to before as well. Time to learn some awk!
Answer: Here is a whole script optimized & refactored:
#!/bin/bash

portnumber=80
reversedns_enabled=0

[[ $1 ]] && portnumber=$1
[[ $2 ]] && reversedns_enabled=$2

#this will hold all of our ip addresses extracted from netstat
ipaddresses=''

#get all of our connected ip addresses
while IFS=' :' read -r type _ _ _ _ ipaddress port state _; do
    if [[ $type != 'unix' && $port == "$portnumber" && $state == 'ESTABLISHED' ]]; then
        ipaddresses+="$ipaddress\n"
    fi
done < <(netstat -ano)

#remove trailing newline
ipaddresses=${ipaddresses%%??}

#output of program
finalOutput=""

#get our ip addresses sorted, uniq counted, and reverse sorted based on amount of uniq
while read -r line; do
    if (( reversedns_enabled == 1 )); then
        reverseDnsName=""

        #we use justipaddress to do our nslookup(remove the count of uniq)
        read -r _ justipaddress _ <<< "$line"
        reverseDnsString=$(host "$justipaddress")
        if [[ $reverseDnsString == *'domain name pointer'* ]]; then
            reverseDnsName=${reverseDnsName##*domain name pointer }
        else
            reverseDnsName="reverse-dns-not-found"
        fi

        finalOutput+="$line $reverseDnsName\n"
    else
        finalOutput+="$line\n"
    fi
done < <(echo -e "$ipaddresses" | sort -ur)

#tabulate that sheet son
echo -e "$finalOutput" | column -t

As you can see, there are almost no external tools used (no sed, awk or grep). Awesome!


How to run a function on each row in pandas dataframe and have it stop when a condition is met

Question: I have a DataFrame, I'm running a function on each row, the function compares values in the row, once a condition is met one of the row elements is added to a dictionary. At this point I want to the function to end, it's not a conventional loop so I can't use break.
Should I used a different method of applying the function to each row or is there a way to stop the apply method for 'applying' ?
The code
test =  # exert from the df I'm using
    30MA    close
29  0.001311    0.000900
30  0.001313    0.001060
31  0.001294    0.001150
32  0.001290    0.001000
33  0.001293    0.000950
34  0.001305    0.000906
35  0.001310    0.000767
36  0.001318    0.000800
37  0.001325    0.000598
38  0.001331    0.000601

# Create and run buy and hold backtest

# buy and hold is measured by the appriciation from first price that crosses the 30MA to close of the most recent period

buy_and_hold_results = {}
coin = 'BBR'
def buy_and_hold(close, MA, coin):

    if MA < close:
        entry = close
        exit = coins[coin].loc[len(coins[coin].index)-1].close

        profit = exit / entry

        buy_and_hold_results[coin] = profit

test.apply(lambda x : buy_and_hold(x['close'], x['30MA'], coin), axis=1)

buy_and_hold_results

Answer: I setup the following code:
import pandas as pd
ma = [0.001311, 0.001313, 0.001294, 0.001290, 0.001293, 0.001305, 0.001310, 0.001318, 0.001325, 0.001331]
close = [0.000900, 0.001060, 0.001150, 0.001000, 0.000950, 0.000906, 0.000767, 0.000800, 0.000598, 0.000601]
df = pd.DataFrame(list(zip(ma, close)),
               columns =['30MA', 'Close'])
df

This outputs something similar to what you gave:
    30MA        Close
0   0.001311    0.000900
1   0.001313    0.001060
2   0.001294    0.001150
3   0.001290    0.001000
4   0.001293    0.000950
5   0.001305    0.000906
6   0.001310    0.000767
7   0.001318    0.000800
8   0.001325    0.000598
9   0.001331    0.000601

Your lambda function will in fact apply the same function individually to each row. I would just do this instead:
buy_and_hold_results = {}
coin = 'BBR'
for ind, row in df.iterrows():
    if row['30MA'] < row['Close']:
        entry = close
        exit = coins[coin].loc[len(coins[coin].index)-1].close
        profit = exit / entry
        buy_and_hold_results[coin] = profit
        break

buy_and_hold_results

Note that the above code outputs an empty dictionary. I am not sure what the code is supposed to be doing.


Windows Server 2012 R2 and permissions for folder created with gpo

Question: I would like to ask. How can I set up automatically permissions for folder which is created by GPMC this method:
http://www.morgantechspace.com/2014/03/Create-a-Folder-on-Desktop-through-Group-Policy.html
Server creating this folder automatically for every user which is logged in for the first time.
Thank you very much for help
Answer: You can create a batch file to do this and use the same GPO to run the batch file after create the folder.

Create a bat file and write:

timeout 10
icacls "%userprofile%\Desktop\SupportTeam" /grant Everyone:M

Timeout 10 to wait until the folder is created. Everyone:M is to grand Everyone access to the folder.

Put the batch file on a shared folder on your network. Make sure to Everyone have access to this shared folder.
Add the batch file to the GPO --> User Configuration --> Windows Settings --> Scripts--> Logon

Click on Add --> Browse for the batch file (where you save the bat file "The Shared folder on your network", you don't need to add any script parameters).

Logoff and back in. (permissions are applied when the user logs on to the computer).
Comment: Oh thank you, but what If I want to change "Everyone" to user who is logging in? I think that will be a little bit complicated isn't it?
Comment: Change "Everyone" to %userdomain%\%username%. The problem you will probably have though is you are not running this in the logged on user's security context, so %username% may incorrectly identify the account. Typically, the folder would be created in the user's home directory on your file server as part of the user creation script and the permissions would be set for that user later in that script. You can then you group policy to create a shortcut to the folder.
Comment: Oh maybe that will works. Because you know. I have problem with that I have this structure:
D:\Users Data
|---Tom
|---Martin
|---Another user

And in these folders I'm using redirection for downloads and documents and everything and what I need is create in these folders another folder automatically with specific permissions for user.
And my problem is that, user can't access to "D:\Users Data", but If someone find someone name and put into address panel: D:\Users Data\Tom, he can access to this folders, but not subfolders created with redirection.
Comment: Okay, I maybe solved the problem. I think that group Authenticated users could solve the problem. And I think when I create the folder with script and no with the GPO. The permissions should be setted up correctly for the folder, because it would be like created by the user and not by the system.
Comment: Please give some credit to the answer If that help to fix your issue.
Answer: Okay. Sorry. I can't write earlier.
So I tried create new folder using your steps, but the script don't run and I don't know why. I setted up excactly how you describe.
So. My script is located here:

\\SERVER-LUNA\Scripts$\wwwroot dir.bat

and Everyone have access to this script and here is my wwwroot dir.bat
timeout 10
if not exist "\\SERVER-LUNA\Users$\%username%\wwwroot" mkdir "\\SERVER-LUNA\Users$\%username%\wwwroot"

When I run the command manually, it works. Thanks
Comment: I think you're missing a few think on your path. It should be something like this: \\SERVER-LUNA\C$\Users\%username%\wwwroot

You can put a pause on the script and check for any errors (Pls post the error if any).
Comment: I think, that the script don't run with the user login.

My path is correct.The Users folder is located on D drive and is shared like Users$.
Comment: Is a GPO script, should run fine if is configured correctly. Add a pause to the script and post the error.
Comment: I don't see a mistake anywhere.
Comment: Okay. Now I'm noticed, that the folder is created, but after few minutes. Don't know why..
Comment: Remove the timeout from the script and check if that helps.
Comment: I've done it before and it takes about 4-5 minutes than it's created.
Comment: How many GPO's you have? Can you set this GPO to be the 1st one?
Answer: I found the solution why is logon script via GPO delayed. You need to enable and change policy via GPO:
https://support.microsoft.com/en-us/kb/2895815
Thanks for help
Comment: Welcome to Server Fault! Whilst this may theoretically answer the question, please [provide context around links](http://serverfault.com/help/how-to-answer) so others will have some idea what it is and why it's there. If possible summarise or quote the most relevant part of an important link, in case the target site is unreachable or goes permanently offline.


Views filter using user field

Question: I have a webform for students to select their teachers.
The data displayed in Views to show the submitted values are the following:
----------------------------------
Instructor  | student
----------------------------------
teacher A   | student name A
teacher B   | student name B
teacher A   | student name C
teacher A   | student name D
--------------------------------
When "teacher A" login, I am expecting "teacher A" can see all his students, without entering filter value "teacher A"
----------------------------------
Instructor  | student
----------------------------------
teacher A   | student name A
teacher A   | student name C
teacher A   | student name D
--------------------------------
I want to have something like automatic filter with the field "Instructor", not typing own name in the exposed filter. So every teacher can get his own students automatically in the table.
Is there any specific module to do that, or a way to get that?
Answer: if instructor is a user entity (or reference), you can add a contextual filter in your view for your field, like this:
Comment: The value Instructor is from the select option list (list of instructors).
Comment: ok - cannot imagine what you mean by select option list, but this seems to be the field you want to filter. for the filter you want to use the actual user - right ?
Comment: Yes that is the field user wants to filter using his name (contain the user name). The values of field to filter are webform submitted data (select option component) submitted by other users.
Comment: Yes that is the field that instructor user wants to filter using his name (contain the name). The values of field to filter are webform submitted data (manually defined in webform select option component) submitted by student users.
Comment: so - are you able to make a contextual filter for this field ?
Comment: No, I cannot find the solution. I have tried to define the field that I want to filter in relationships, then use contextual filter. But still not working.

Views filter using user field


Zeros of Dirichlet L-functions on the line $\Re(s)=1$ in proof of Dirichlet's theorem

Question: In the proof of Dirichlet's theorem, we show that $L(s,\chi_0)$ has a simple pole at $s=1$ where $\chi_0$ is the principal character and that $L(1,\chi)\neq 0$ otherwise. Therefore the logarithmic pole at $s=1$ of $\log L(s,\chi_0)$ is not canceled by a (negative) logarithmic pole of $\log L(s,\chi)$ at $s=1$ for any other $\chi$, so that the main term of the asymptotic expansion is $\frac x{\log x}$ multiplied by the residue of the pole.
What I don't understand is the following: in the proof of the prime number theorem, it is necessary to show not only the existence of a simple pole at $s=1$  and so a logarithmic pole of $\log \zeta(s)$ (in the case of the PNT we are concerned only with the Riemann zeta function, so there are no other L-functions to cancel the pole) but also the lack of any zeros, and thus (negative) logarithmic poles with real part $1$. Why is this not necessary in the case of Dirichlet's theorem?
Answer: To prove only the statement that there are infinitely primes in arithmetic progressions, you only look at the limit
$$ \lim_{s \to 1} \sum_{p \equiv a \pmod n} \frac{1}{p^s} \tag{1}$$
and show that it's infinite. So the only point of analytic interest is $s = 1$. To understand $(1)$, one ends up looking at a sum of the Dirichlet $L$-functions $L(s, \chi)$ of with characters $\chi$ mod $N$.
A parallel statement can be said about the Riemann $\zeta$ function. Since
$$\zeta(s) = \prod_p \left( 1 - \frac{1}{p^s}\right)^{-1},$$
and since we know
$$ \lim_{s \to 1} \zeta(s) = \infty,$$
we know that there must appear infinitely many terms in the product. And thus there are infinitely many primes.
But the Prime Number Theorem (PNT) is much stronger than saying that there are infinitely many primes. It describes asymptotics of the number of primes and is obtained by performing a particular integral transform (an inverse Mellin Transform, or a Laplace Transform, or a particular line integral) and using more than merely local analytic behaviour.
If you want to prove the analytic asymptotics for primes in arithmetic progressions, then you can use very similar techniques. And for these, you do need to understand the analytic behaviour of each $L$-function on the line $\Re s = 1$.


How to create a single image style for both landscape and portrait images?

Question: In a Drupal 7 environment, I want to apply a style to all images within a view. I want every image to be 180px wide & 128px high -OR- 128px wide and 180px high depending on the orientation of the original image.
Can this be done with an image style or do you know any module that would help in achieving this?
Answer: ImageCache Actions

Aspect Switcher new 2009-08 - lets you perform different actions or
  use different dimensions based on whether the image is 'landscape' or
  'portrait'
Comment: Linking to the official project page for modules is preferred, if possible.
Comment: If you end up doing this, make sure you read issues about ImageMagick compatability.
Comment: Thanks a lot. One needs to create three image styles, one for landscape, one for portrait and one that is doing the switching action. But it works like a charm.


Buffering Input files and parallel processing in java

Question: I have a collection of 1000 files in gz format. I want to process them in chunks in parallel, say 8 in each round. When I let every thread opens a file and read from disk that resulted in a significant delay due to many processes trying to read from different locations.
I just wonder if there is an efficient method to handle multiple files reads? Or shall I buffer all the files into memory first (e.g. all 8 files and then hand the buffers to the threads). If so, what would be the best way of buffering files? bufferArray? or some alternative structures?
Thank you.
Answer: I suspect you're swamping your process with 1000 threads. Threads aren't particularly lightweight (e.g. each will grab by default 512k of stack space).
A more efficient model may be to use a thread pool (via ThreadPoolExecutor) and tune it for the optimal number of simultaneous threads on your system (e.g. you've suggested 8 above - I'd suggest this hinges to some degree on the number of free CPUs you have).
Each .gz file would be represented by one Callable submitted to the executor, and the executor will look after running multiple jobs simultaneously.
Comment: Thanks Brain. This is what I'm doing right now with a fixed pool size based on the number of free cpus and each file is represented with a Callable. This is not efficient.
Answer: If you use a fixed size pool of say 8 (because you have 8 cores) you may find this is reasonably efficient as decompressing the files is cpu intensive.
You may find however that this is no faster than using 4 threads or only 2 because the real bottleneck is reading the data from disk.  If this is the case, the only thing you can do is get a faster disk. e.g. mirror the disk, or use an SSD which can be 20x faster.


I need to change a javascript code

Question: I made an onclick popup redmore button for my sidebar text widget in wordpress just copied and pasted this code I found here. I did some little changes and everything worked fine.
The problem occurred when I had to make more onclick popups like that one for the rest of the sidebar widgets, exactly the same popup with same values but with different img and content text.
The problem is both "redmore" buttons in the first widget and in the second one link to the same thing - so it will open the same one no matter which redmore button you click -
this is the website check out the first two items in the right sidebar.
Since I don't know much about Javascript, I'm asking you if you can help me changing the javascript tag link in the code in order to link to another different popup and not the same one - and let me understand how to change it since I have to make a few popups.
Comment: Include code when linking to JSFiddle. (And in general when you want help with some code).
Answer: You need to change the id for every popup Like
getElementById('fade')
getElementById('light')

[the first]
getElementById('fadesec')
getElementById('lightsec')

[the second]
And so on..  same thing on html content, don't just copy,  change ids
Example two:

This is the main content. To display a lightbox click here

This is the lightbox content. Close

Answer: You should change the Id attribute of the Contents for eg

for the second pop up and change the javascript of the second read more text to
here

Same should be applied to all other pop ups.
Here i have changed the fiddle
Comment: You could mark it as correct if it solved the issue :) .
Comment: yeah of course, but I'm new here, how do I do that ?

I need to change a javascript code


Using the Cauchy product with $\sin(x)\sinh(x)$

Question:
Find an expression for the nth non-zero term of the Maclaurin series for f(x), where $f(x)=\sin(x)\sinh(x)$

I tried to start with the Cauchy Product of the two series :
$$\begin{align}\left(\sum_{i=0}^{\infty}{\frac{(-1)^ix^{2i+1}}{(2k+1)!}}\right)\left(\sum_{j=0}^{\infty}{\frac{x^{2j+1}}{(2j+1)!}}\right)&=\sum_{k=0}^{\infty}\sum_{l=0}^k{\frac{(-1)^lx^{2l+1}x^{2(k-l)+1}}{(2l+1)!(2(k-l)+1)!}}\\&=\sum_{k=0}^{\infty}\sum_{l=0}^{k}{\frac{(-1)^lx^{2(k+1)}}{(2l+1)!(2k-2l+1)!}}\end{align}$$
Providing the algebra is correct, I'm not too sure how to continue this or if I missed a trick with $f(x)$ that makes the expansion easy to find. I know some terms will be zero due to $\sin0$ in the expansion but not sure how to get around the series.
EDIT : Trying with exponentials, now fixed (thanks @jjagmaths)
$$\begin{align}\left(\frac{e^{ix}-e^{-ix}}{2}\right)\left(\frac{e^x-e^{-x}}{2i}\right)&=\frac{e^{ix}e^x-e^{ix}e^{-x}-e^{-ix}e^{x}+e^{-ix}e^{-x}}{4i}\\&=\frac{e^{ix}e^{2x}-e^{ix}-e^{-ix}e^{2x}+e^{-ix}}{4ie^{x}}\\&=\frac{(e^{x(2+i)}-e^{x(2-i)})+(e^{-ix}-e^{ix})}{4ie^{x}}\\&=\frac{2ie^{2x}\sin(x)-2i\sin(x)}{4ie^{x}}\\&=\frac{i\sin(x)(e^{2x}-1)}{2ie^{x}}\\&=\frac{1}{2}e^{-x}\sin(x)(e^{2x}-1)\end{align}$$
Comment: Your answer looks correct. The non-zero condition probably refers to the fact that the function is even, hence all odd terms are zero.
Comment: I think Cauchy product is overkill for this task. It would be a lot easier to write $f$ in terms of exponentials first. Anyway you might find this [similar question](https://math.stackexchange.com/questions/4495752/show-that-sum-ell-0k-binom2k12-ell-22k) (using Cauchy product to find the series expansion of $\sin x\cos x$) helpful.
Comment: @user170231 I was thinking it's too overkill... but I knew it would give something at least. I'll take a look at the link.
Comment: In your try with exponentials you made a mistake: $\displaystyle\sin x = \frac{e^{i x}-e^{-ix}}{2\color{red}i}$
Comment: @jjagmath thanks :)
Answer: Continuing:

$$\begin{align}\sin(x)\sinh(x)&=\cdots\\&=\sum_{k\ge0}x^{2(k+1)}\sum_{\ell=0}^k(-1)^\ell\cdot\frac{1}{(2\ell+1)!(2(k-\ell)+1)!}\\&=\sum_{k\ge0}\frac{x^{2(k+1)}}{(2(k+1))!}\sum_{\ell=0}^k\binom{2(k+1)}{2\ell+1}(-1)^\ell\\&=\sum_{k\ge0}\frac{x^{2(k+1)}}{(2(k+1))!}\sum_{\ell=0}^k\binom{2(k+1)}{2\ell+1}i^{2\ell+1-1}\\&=\frac{1}{2i}\sum_{k\ge0}\frac{x^{2(k+1)}}{(2(k+1))!}\sum_{\ell=0}^{2(k+1)}\binom{2(k+1)}{\ell}(i^\ell-(-i)^{\ell})\\&=\frac{1}{2i}\sum_{k\ge0}\frac{x^{2(k+1)}}{(2(k+1))!}((1+i)^{2(k+1)}-(i^{-1}(1+i))^{2(k+1)})\\&=\frac{1}{2i}\sum_{k\ge0}\frac{x^{2(k+1)}}{(2(k+1))!}(1-(-1)^{k+1})(1+i)^{2(k+1)}\\&=i^{-1}\sum_{m\ge0}\frac{x^{2(2m+1)}}{(2(2m+1))!}(1+i)^{2(2m+1)}\\&=i^{-1}\sum_{m\ge0}\frac{x^{4m+2}}{(4m+2)!}\cdot(\sqrt{2}\exp(\pi i/4))^{4m+2}\\&=i^{-1}\sum_{m\ge0}\frac{x^{4m+2}}{(4m+2)!}2^{2m+1}\exp(\pi i(m+1/2))\\&=\sum_{m\ge0}(-1)^m\cdot\frac{2^{2m+1}x^{4m+2}}{(4m+2)!}\end{align}$$

A significantly easier method, similar to the one suggested in the comments:

$$\begin{align}\sin(x)\sinh(x)&=\Im\cosh(x+ix)\\&=\Im\sum_{k\ge0}\frac{(x(1+i))^{2k}}{(2k)!}\\&=\Im\sum_{k\ge0}\frac{x^{2k}}{(2k)!}\cdot(\sqrt{2}\exp(\pi i/4))^{2k}\\&=\Im\sum_{m\ge0}\frac{x^{2k}}{(2k)!}\cdot2^k\exp(\pi ik/2)\\&=\Im\sum_{m\ge0}\frac{x^{2(2m+1)}}{(2(2m+1))!}\cdot2^{2m+1}\exp(\pi i(m+1/2))\\&=\sum_{m\ge0}(-1)^m\cdot\frac{2^{2m+1}\cdot x^{4m+2}}{(4m+2)!}\end{align}$$

"What's wrong here"? You forgot to divide by $i$: you wrote $\sin(x)\overset{?}{=}\frac{e^{ix}-e^{-ix}}{2}$ but actually it is $\sin(x)=\frac{e^{ix}-e^{-ix}}{2\color{red}{i}}$. More than that, you should have left it in exponential form! Because then all you have to do is add together the easier-to-handle (than a Cauchy product) exponential series.
You also made a mistake factorising your expression. Even after dividing by $i$, it is not true that $\sin(x)\sinh(x)\overset{?}{=}\sin(x)\cdot\frac{e^{2x}-1}{2}$ - that equation is off by a factor of exactly $e^x$ (the RHS is $e^x\sin(x)\sinh(x)$).
Comment: found the mistake, just didn't multiply the denominator by $e^{x}$ also. thanks for the answer.
Comment: @AnthonyML you're welcome


Do CNAME records require time to propagate?

Question: When I typically update DNS ("A" records) I will allow for an extended period of time for the changes to propagate throughout the root nameservers.
Do I need to make this same allowance for updates and changes to CNAME records?
Comment: possible duplicate of [How long does it take for an A record to propagate?](http://serverfault.com/questions/125371/how-long-does-it-take-for-an-a-record-to-propagate)
Comment: @MichaelHampton - true, if we change `an A record` to `DNS records` in the title of that question.  Neither question is specifically about A records.  [update] I have submitted that edit.
Answer: No you don't because DNS records don't propagate. What you do need to allow for is for any cached records to expire, based on the TTL of the record in question.
If this is a new record, no caching can have occurred so the new record should be available and should resolve immediately.
Additionally, the root servers (first level; .) don't host DNS zones or records for any third level domain names. The root servers know which name servers are responsible for the gTLD zones (second level; .com, .edu, etc.), which in turn know which name servers are responsible for your zone (third level; yourcompany), which in turn hold a copy of your zone file. No other DNS server holds a copy of your zone file or DNS records other than your name servers.

.
COM
YOURCOMPANY
Comment: @JohnGardeniers, thank you--yes! This was a particularly illuminating part of the answer for me :) I appreciate the lesson.
Comment: Glad to help...
Comment: @Jaryd, please pay ver particular attention to that very first sentence. Far too many people around here just don't understand that.
Answer: [Edit - It appears I misread the question]
There are two ways in which your zone data 'propagates'.  And the root servers are not (directly) involved.  They allow other computers to find your servers, and hence your zone data. But it's other systems that check the root and tld servers before they get down to yours.
Here's how your data does propagate.
First, you push that data to your authoritative servers, and some of those may use (incremental) zone transfer to update each other.  This may take up to the REFRESH time of the zone to complete.
Second, each record in your zone, and that includes anything, including A and CNAME records, may be cached anywhere between your authoritative servers and any clients.
How long that data is cached should depend on the record's individual TTL (time to live).  Theoretically, it should not take longer than the sum of the zone refresh and the record's ttl for a cached entry to time out.  However, there's a lot of different software out there.  Google for dns ttl bugs - last count I did was around 850k.
But you can have CNAME records for www.example.com point to something like www-server.dynamic.example.com, and set the TTL and refresh times for stuff inside
dynamic.example.com to much lower values than the parent.  This allows operators
to quickly redirect traffic to other infrastructure when the need arises.
Comment: Setting a faster TTL only helps in situations where the DNS cache servers are not overriding or ignoring the TTLs set in the zone files, which is unfortunately more common than one would think.
Comment: And becoming more common all the time. Plus, many systems will only obey the TTL if it's greater than some predefined period, so the shorter you make the TTL the more likely it will be ignored.


Is it possible to alphabetize a sorted view?

Question: Drupal 7.18 w/ Views 7.x-3.8 user here.
I have a view set up that consists of rows of objects, which have names and 'yes/no' properties. By default, it is sorted alphabetically by object name. I want to allow the user to be able to sort through the view using the various properties, but to then have those sorted results be alphabetized for them post-hoc. Currently, when the user sorts through the view using property X (with either 'yes' or 'no' content), the objects seem to be retrieved based on their location in the database table, or some other factor. Either way, they are in no way alphabetical which means that this view of 500+ results is impractical to sort in this fashion.
So, is it possible to set up a sort mechanism where the results are (1) sorted by property into their respective 'yes'/'no' groups (or any other groups with identical content for that matter) and then (2) alphabetized?
To demonstrate what I mean, I currently have something like this:
NAME    PROPERTYX
Alpha   yes
Beta    no
Delta   yes
Epsilon no
Gamma   yes

Which when sorted using PROPERTYX (let's say descending), might return something like:
NAME    PROPERTYX
Delta   yes
Alpha   yes
Gamma   yes
Epsilon no
Beta    no

(As I said, I suppose this random order is based on the object's actual location in the database table.)
When the desired output would be:
NAME    PROPERTYX
Alpha   yes
Delta   yes
Gamma   yes
Beta    no
Epsilon no

Can this be accomplished somehow?
Answer: It is definitely be possible to add a second sort to the query which will give the desired effect, but you will have to write some custom code.
There are several hooks that Views provides that you can use in a custom module.  I suggest looking at hook_views_query_alter().  The example code on the API page actually shows it altering a WHERE clause, but creative use of dsm()'s will help you figure out what you need to change.
I'm sorry that I can't give you code (because this kind of modification is highly specific to your installation), but this is definitely the way to go.
Answer: If I understand correctly, you want to sort by PROPERTYX first, and then alphabetically sort the items with the same PROPERTYX value - is that correct?
You can do that by adding multiple sort criteria. Make sure that the "Sort by PROPERTYX (desc)" criterium comes first and the "Sort bt title (asc)" comes second.
Comment: Yes! That did the trick. By placing the "sort by title (asc)" criterium at the very end, the items of all of the preceding sorts with the same value are now alphabetized. Thank you!
Comment: Although -- if the title is the first item in the sort menu, this now means that it is now not possible to sort by title descending. The "sort by title (asc)" criterium at the end overrides that.
Comment: Of course you should not add two sort criteria on the same field or property, that wouldn't make sense. Just add (or rearrange) the sort criteria in the right order, and remove the ones you don't need.


Does Kubernetes internally maintain tasks queue?

Question: We are in the development phase. We are using Kubernetes cluster consisting of master and slave EC2 instances. We are submitting tasks to Kubernetes cluster using Kubernetes_Pod_Operator of Airflow. We are looking to scale this process. So we are going to use Celeryexecutor of Airflow which is used to concurrently submit and schedule tasks on Airflow.
So the question is, should we care about number of tasks submitted to Kubernetes or irrespective of number of tasks submitted to Kubernetes, Kubernetes will service all the tasks without failure by any internal queuing ?
Answer: First of all, note that Kubernetes is not meant to do this kind of operations, precisely because there is no queuing idea in Kubernetes. So, you do care about the number of submitted tasks.
From the source code of "kubernetes_pod_operator.py" it seems that it just creates a pod in the right namespace, with the right image, etc.
In the end it is a pod, so it will do a job and finish (status: completed).
Taking this into consideration, it will depend on the jobs it will have to run, and your machine type. An example:
Say you are running simple pipelines that consume about 0.1CPU and few MB of memory. If your nodes are 4-CPU machines (lets assume you have enough memory), then you can run ~40 concurrent jobs per node. If you run more, you will get an error (saying your pods can't be scheduled).
So,

(recommended) If you can actually determine a standard resource consumption per task (per pod), I would recommend you to set resource requests and limits per pods (As by default a pod can consume the 100% of the nodes resources), and always try to run the maximum amount of pods. You will need to keep the track of the number of pods.
(not recommended) If you can't determine the pod consumption, you could either monitor the nodes and add tasks as long as they have enough room, or to try creating the pods with exponential back-off, if you get an error on pod creation because it can't be scheduled.

Hope it helps. Again, this is not something that I am used to see on kubernetes.


Criar um diretório protegido no storage do dispositivo

Question: Através de uma aplicação é possível criar, editar e remover, tanto arquivos, quanto diretórios, porém sabemos que é necessário o usuário dar permissão de leitura e escrita dependendo a ocasião. Para que de fato essa permissão seja concedida, normalmente deve inserir uma tag <users-permission /> no <manifest></manifest>, como exemplo READ_EXTERNAL_STORAGE e WRITE_EXTERNAL_STORAGE.
Veja abaixo um comando simples para criar um diretório:
File dir = new File(context.getExternalFilesDir(Environment.DIRECTORY_DCIM), filename );
if (!dir.exists()) {
    dir.getParentFile().mkdirs();
}

Depois de todo procedimento feito, inserindo documentos e imagens dentro desse diretório, ao acessar um gerenciador/galeria de arquivos, sendo ele nativo do smartphone ou não, o usuário consegue ver esses arquivos normalmente.
Tenho uma aplicação no qual gostaria de visualizar estes documentos somente dentro dele, portanto da forma como é hoje, os arquivos também podem ser visualizados através da galeria.
É possível criar um diretório protegido no storage do dispositivo? Existe alguma outra forma de resolver esse problema, para que o usuário não consiga vizualizar os arquivos fora da aplicação, ou que visualize somente através de uma senha?
Comment: Como você obtém o `path` que usa em  `new File(path)`?
Comment: @ramaral eu coloquei esse código somente como exemplo. Você acha que é relevante colocar na pergunta?!
Comment: É porque isso é que irá determinar se o directório é privado ou não. Vou colocar uma resposta.
Comment: Uma maneira simples é deixar o diretório com um ponto antes do nome, exemplo. ".AppX". Isso mantém o diretório oculto, e impede que a galeria e os exploradores nativos encontre o diretório ou os arquivos dentro. Somente alguns aplicativos que tem permissão de root e a opção de visualizar arquivos ocultos.
Comment: Por que está a usar [DIRECTORY_DCIM](https://developer.android.com/reference/android/os/Environment#DIRECTORY_DCIM)? Não faz sentido já que ela se refere à pasta pai das pastas públicas.
Comment: @ramaral Eu tinha colocado apenas como exemplo por você ter cobrado. Na realidade estou criando um diretório com nome `apptal` dentro de `/mnt/sdcard/`. Então na realidade está ficando assim `/mnt/sdcard/apptal`
Comment: Não deve usar caminhos escritos na mão. Já tentou usar `getExternalFilesDir()` com por exemplo **DIRECTORY_PICTURES**? É que assim verificava se o que eu digo na resposta se confirma e que a documentação está certa(nem sempre está).
Answer: OS dispositivos Android dispõem de duas áreas de armazenamento de arquivos: interna(internal storage) e externa(external storage).
Arquivos criados na área interna são sempre privados, apenas a aplicação que os criou pode acedê-los.
Use getFilesDir() para obter o caminho.
Em relação aos arquivos criados na área externa depende do tipo área externa e do modo como o caminho é obtido.
Alguns dispositivos usam parte da memória interna como external storage, emulando um sdcard. Mesmo não tendo um sdcard ela é apresentada à API como se fosse.
Assim, em relação à external storage, verifica-se o seguinte:

external storage no sdcard:

Os arquivos são públicos e aplicações com permissões READ_EXTERNAL_STORAGE e WRITE_EXTERNAL_STORAGE podem acedê-los.
Se o caminho for obtido por getExternalFilesDir() não são visíveis pela galeria e serão eliminados quando a aplicação é desinstalada.

external storage emulado:

Os arquivos são privados se o caminho for obtido por getExternalFilesDir().
Nota: Pelo menos é o que entendo da documentação:

If a shared storage device is emulated (as determined by     Environment.isExternalStorageEmulated(File)), it's contents are backed by a private user data partition, which means there is little benefit to storing data here instead of the private directories returned by getFilesDir(), etc.

É possível criar um diretório protegido no storage do dispositivo?

Uma solução é encriptar os arquivos usando as classes Cipher, CipherOutputStream e CipherInputStream.
Comment: @Viana Parece ser o caso de [marcar uma resposta como aceita](http://meta.pt.stackoverflow.com/questions/1078/). Se tem uma resposta que realmente te ajudou, marque-a como aceita. Se chegou sozinho à solução, poste a solução como resposta. Assim o conteúdo fica mais organizado e fácil de ser encontrado futuramente por outras pessoas com problemas parecidos.


How to find the stationary point of $f(x,y)=\sin x \sin y \sin (x+y)$

Question: How to find the stationary point(s) of $f(x,y)=\sin x \sin y \sin (x+y)$
With $x,y\in(0,\pi)$
So far I have found $$\nabla f =(\color{red}{\sin x\cos (x+y)+\cos x\sin (x+y)\sin y},\color{blue}{\sin y\cos (x+y)+\cos y\sin (x+y)\sin x)}$$
So we need
$$(\sin x \cos (x+y)+\cos x \sin (x+y)) \sin y=0 \\ (\sin y \cos (x+y)+\cos y\sin (x+y))\sin x=0$$
Problem is I don't know how to solve this.
Comment: $\sin x \cos (x+y)+\cos x \sin (x+y)=\sin(x+(x+y))=\sin(2x+y)$ (classical formula $\sin a \cos b+ \sin b \cos a=\sin(a+b)$ and the same kind of transformation for the other parenthesis.
Comment: Okay so we get $\sin (2x+y)\sin y=0$ and $\sin (x+2y)\sin x=0$ but $\sin x$ and $\sin y$ are never $0$ on the region we care about so $\sin (2x+y)=0=\sin(x+2y) \implies (x+2y)=(2x+y) \implies x=y$ so we need to search for in the range such that $3x=\pi$ so we have $x=\pi /3$ so there is one stationary point at $(\pi /3 , \pi /3)$ is that correct?
Answer: $\left(\sin x \cos(x+y) + \cos x\sin(x+y)\right) \sin y = 0$ when $\sin x \cos(x+y) + \cos x\sin(x+y) = 0$ or when $\sin y = 0$.  I trust that you know when $\sin y = 0$.  What about that first one?
\begin{align}
  \sin x \cos(x+y) + \cos x\sin(x+y) &= 0 \\
  \sin x \cos(x+y) &= -\cos x\sin(x+y)\\
  -\tan x &= \tan(x+y)\\
  \tan(-x) &= \tan(x+y)
\end{align}
Because tangent is periodic with period $\pi$, then this equation is satisfied when $x+y = -x + n\pi$, where $n$ is any integer (provided there are no domain restriction violations).  This is equivalent to $y = -2x + n\pi$.
The second equation you mentioned is nearly identical.


Reason for difference in power.prop.test and epiR::epi.sscompb results

Question: I was trying to rework the examples in Epidemiology Study Design and Data Analysis by Mark Woodward using R. Example 8.12 deals with calculation of sample size to test for a population proportion of 0.3 against the one sided alternative that it is greater than 0.32.
I tried two commands
power.prop.test(n = NULL, p1=0.3, p2=0.32, power =0.9, alternative = "one.sided")
epiR::epi.sscompb(n = NA, treat = 0.3, control = 0.32, power = 0.9, sided.test = 1 )

The results (sample size) given by the two functions are very different.

Two-sample comparison of proportions power calculation
          n = 9157.159
         p1 = 0.3
         p2 = 0.32
  sig.level = 0.05
      power = 0.9
alternative = one.sided

NOTE: n is number in each group

$n.total [1] 4568
$n.treat [1] 2284
$n.control [1] 2284
$power [1] 0.9
$lambda [1] 0.937500 1.066667

The result by epi.sscompb agrees with the value in the book.
Can someone tell me if there is an error in the code? If there is no error in the code, why are the results different?
Thanks, ajith
Answer: epi.sscompb is meant for a one-sample proportion test, while power.prop.test is meant for a two-sample proportion test. This is why you get different results.
There is no equivalent to epi.sscompb in the R stats package (so you won't find any relevant function starting with "power.something.something"). If you're looking for testing epi.sscompb against another implementation of power calculation for one-sample proportion test in R, the R pwr package implements it:
library(pwr)
pwr.p.test(h=ES.h(p1=0.3, p2=0.32), sig.level = 0.05, power = 0.9, alternative = "less")
proportion power calculation for binomial distribution (arcsine transformation)

              h = -0.04324895
              n = 4578.442
      sig.level = 0.05
          power = 0.9
    alternative = less

Occasionally, as in your case, the results from pwr.p.test may be a bit different from epi.sscompb because epi.sscompb uses a formula based on an approximation, while pwr.p.test relies on the definition of power according to Jacob Cohen (Statistical Power Analysis for the Behavioral Sciences, 1988, pp. 179-213, in particular section 6.4.3 p. 208, and p. 549). When they disagree (generally not by much), pwr.p.test will generally give you a bit more power than epi.sscompb.

On the other hand, if you want a result in line with power.prop.test (two-sample case) in the epiR package, you should use epi.sscohortc as they suggest in their documentation:

Users are referred to the epi.sscohortc function which relates to the
two-sample problem where neither proportion is known (or assumed, at
least).

In your case, it gives:
epi.sscohortc(irexp1=0.3, irexp0=0.32, power = 0.90, r = 1,
                  design = 1, sided.test = 1, finite.correction = FALSE,
                  nfractional = T, conf.level = 0.95)
$n.total
[1] 18314.32

In short, here is a table summarizing the packages and their relevant functions, depending on the kind of test you plan to use:

epiR package
pwr package
stats package

power for one-sample proportion test
epi.sscompb
pwr.p.test
N/A

power for two-sample proportion test
epi.sscohortc
pwr.2p.test
power.prop.test

You may want to ask a separate question, in case you want to learn about the difference between a one-sample proportion test and a two-sample proportion test. Note that there are already some similar questions on this website about the difference between one-sample vs. two sample:

Proportion test: one sample or two sample?

hypothesis test one-sample vs two-sample

Additionally, the pwr documentation offers some examples of the one-sample case vs. the two-sample case.
Comment: Hi,Thanks for your answer. I understood the result of epi.sscompb because that is the same example from the textbook. What I don't understand is why power.prop.test is different from it. You say that "If you want a result in line with power.prop.test, where neither proportion is known, ...". But, how is both proportion not known when we use power.prop.test?  I am calling it with only n set as NA - power.prop.test(n = NULL, p1=0.3, p2=0.32, power =0.9, alternative = "one.sided").
Comment: @ajith I rewrote my answer, hopefully it will make things a bit clearer. It boils down to the difference between a one-sample proportion test, and a two-sample proportion test.


How does Matlab compute bicubic interpolation kernel for large kernels?

Question: I am using Matlab's imresize function to downscale a 3000x2000 image to 120x80 pixel using bicubic interpolation. I stepped through the impementation of Matlab and noticed that a huge number of kernel weights are computed for each output pixel, not just 4x4 as I expected.
Does anyone has an idea how Matlab is computing these kernel weights ?
Comment: For downsampling it probably smooths the image to avoid aliasing.
Answer: When downscaling images, the resampling kernel is typical dilated to mitigate aliasing, like Cris said.
The cubic kernel for this factor 25x decimation would be 100x100 in units of input pixels, which is 4x4 in units of output pixels. In other words, each output pixel is computed from a patch of 100x100 input pixels. It makes sense considering the large decimation factor that so many pixels need to be aggregated for anti-aliasing.
Kernel weights for standard bicubic resampling are computed from Keys' cubic kernel function, the "W(x)" function described here on Wikipedia.


Question about polynomials

Question: Let $R$ be an infinite domain and $p(x), q(x) \in R[x]$ such that $q(x) \neq 0$. If for all but a finitely many $s \in R, q(s)|p(s)$, then is is true that $q(x)|p(x)$ in $R[x]$? This seems a little silly, but I cannot figure out why it should be true or false. What about the case where $q(x)$ is not a constant and $q(x)$ is monic?
Answer: Let $R=\mathbb{Z}$, let $q(x)=2$ (identically), and let $p(x)=x(x-1)$. Then $q(a)$
divides $p(a)$ for every integer $a$, but $q(x)$ does not divide $p(x)$.
Comment: More substantial editing will be needed.  Let $q(x)=2(x^2+1)$ and $p(x)=x(x-1)(x^2+1)$.
Comment: If $R$ is a field, then $q(s)|p(s)$ for all $s$ such that $q(s) \ne 0$, no matter what $p$ and $q$ are.
Comment: @Rankeya: This is not a silly question, no need to feel bad! And we should leave this up in case anyone else comes along with the same question.
Comment: Thanks. Is there a way to close down this post? I feel silly.
Comment: I was actually trying to show that if $R$ is an integrally closed domain, then so is $R[x]$, and at some point I came across a statement of this nature. Oh well.
Comment: Don't worry about it, everyone slips up sometimes, I more than most. There is a way of flagging a moderator, and moderators are all-powerful.
Comment: André is correct, if you really want to delete this question, a moderator (such as myself) will be able to do it. But I do encourage you to leave it up, there is nothing wrong with seeking to improve your understanding.
Comment: The answer leaves the question open for non-constant polynomials $q$.
Comment: Okay. Can I edit this question to one where $q(x)$ is non-constant? Perhaps even that has a straightforward counter-example.
Comment: Ahh, Gerry and I had the same thought at almost the same time.
Comment: This is nice. Thanks.
Comment: Andre one more small edit. Sorry!
Comment: @Rankeya: For $\mathbb{Z}$, and close relatives, the *positive* assertion would be that $q(x)$ divides $cp(x)$ for some non-zero $c$.
Answer: Since $q(x)$ is monic, we can divide $p(x)$ by $q(x)$ in $R[x]$: $$p(x) = q(x) f(x) + r(x)$$ where $f(x), r(x) \in R[x]$ and either $r(x)=0$ or $\deg r < \deg q$.  If $r(x)=0$, then $q(x)|p(x)$.  Otherwise, since $q(s)|p(s)$ for all but finitely many $s$, then $q(s)|r(s)$ for all but finitely many $s$.  In other words, $(q,r)$ satisfy the same hypotheses as the initial $(q,p)$, except now we have the extra condition that $\deg r < \deg q$. So to prove the original statement, we must show that $\deg r < \deg q$ cannot happen if $q(s)|r(s)$ for all but finitely many $s$.
In the case $R=\mathbb{Z}$, this is easy: If $\deg r < \deg q$ then $|r(s)|<|q(s)|$ for sufficiently large $|s|$, so that we cannot have $q(s)|r(s)$ for such $s$.
More generally, if $R$ is a subring of the ring of integers of $\mathbb{Q}(\sqrt{d})$ where $d<0$, then $R$ is an unbounded, discrete subset of $\mathbb{C}$, so a similar argument works.
On the other hand, as in my comment, if $R$ is a field, then the original statement is false because any polynomials $p$ and $q$ satisfy the hypotheses.
Comment: I think this is quite a satisfactory answer, considering my question stemmed from a problem I was stuck on in Algebraic Number Theory. It would, however, be an interesting question, if my domain $R$ did not have a natural order.
Comment: It's also true for the ring of integers of any number field, since any counterexample would yield a counterexample in $\mathbb{Z}$ by taking the product of all conjugates of $p$ and and all conjugates of $q$.  In fact, so far I can't think of any counterexamples other than fields; if $\deg r < \deg q$ and $q(s)|r(s)$ for most $s$, somehow it looks like the ring would have to have "a lot" of units so it's pretty close to being a field.

Question about polynomials


WPF MessageBox close without any action

Question: I have a confirmation message box for the user in one of my apps. Below is the code for that,
MessageBoxResult res= System.Windows.MessageBox.Show("Could not find the folder, so the D:  Drive will be opened instead.");
                if (res == MessageBoxResult.OK)
                {
                    MessageBox.Show("OK");
                }
              else
                {
               MessageBox.Show("Do Nothing");
                }

Now, when the user clicks on the OK button, I want certain code to execute but when they click on the red cross at the upper right corner, I just want the messagebox to close without doing anything. In my case I get 'OK' displayed even when I click on the red cross icon at the upper right corner. Is there a way I can have 'Do Nothing' displayed when I click on the cross. I not want to add any more buttons.
Comment: In this case, no.  You are only giving the user one choice ("OK").  If you really want two paths ("OK" or "Do Nothing", i.e. "Cancel") you need to implement it that way.  That's standard Windows behavior, and to do it contrary to the "accepted" standard will be unintuitive to users of your application.
Comment: Right now the only possible result is OK, but since you are actually expecting Ok/cancel input from the user, you should use Show() call with MessageBoxButton.OKCancel buttons.
Comment: so does that mean that there is no difference between clicking on the Ok button and clicking on the red cross button on the upper right corner? Doesnt red cross icon mean closing without doing anything?
Answer: Yes there is a very simple way, just add the "MessageBoxButtons.OKCancel" param to your MessageBox.Show method. this way you will have two buttons (OK and Cancel). this way if the user clicks the cancel button or the red cross the DialogResult.Cancel message will be returned. the following code described the solution:
System.Windows.Forms.DialogResult result = System.Windows.Forms.MessageBox.Show("Could not find the folder, so the D:  Drive will be opened instead.",
            "", System.Windows.Forms.MessageBoxButtons.OKCancel);

        if (result == System.Windows.Forms.DialogResult.OK)
            MessageBox.Show("OK");
        else
            MessageBox.Show("Do nothing.");

Comment: if thats the case then as you mentioned eariler, there is no way to solve this problem.
Comment: He doesn't want to add any more buttons.
Answer: No, there isn't.
You could make your own custom dialog form.
Comment: so does that mean that there is no difference between clicking on the Ok button and clicking on the red cross button on the upper right corner? Doesnt red cross icon mean closing without doing anything?

WPF MessageBox close without any action


Writing wrappers for Python 3 vs Python 2

Question: In Python, is there any difference in how one would write Python wrappers for c++ libraries if one aims to make it compatible with Py3 vs Py2?
Or should a wrapper originally written for Py2 work the same way for Py3 and visa versa? As I understand it, Python wrappers are written in c++ in a .cxx file which then have to be compiled.
Details
I ask because I'm wanting to install Aggdraw (wrapper for c++ Anti Grain Geometry drawing library), which works in Python 2.6-7, but results in errors on Python 3.4 (Windows 7 32-bit, via "PATH=C:/Python27[or Python34]" and "python setup.py install" in the command line). My hope is to revive this amazing wrapper module for Python 3, and was hoping anyone else here would be interesting in helping out.
I can get it compiled on Python 2.6 and 2.7 without any problems, and I have both Visual C++ 2008 and 2010 so it's not a compiler problem. The problem seems to be in the actual .cxx wrapper code.
Could it be that the Aggdraw wrapper was only written with Python 2x in mind (almost 10 years ago now), and so it didn't take into account problems that might arise in Python 3x? My best guess is that the wrapper fails to convert certain c++ objects/types over to Python due to deprecated and changed features in version 3.4.
I might be willing to go through the .cxx wrapper code to change the necessary parts, if someone can help me identify what the troubleparts are (see command line error codes below)? If we get it fixed then I'll update this post with a link to the "revived" wrapper code.
If there should´t be a difference between Python 2 and 3 wrappers, any idea why I´m getting the error codes below in Py3 but not Py2?
Thanks!
Original wrapper code: click here
<code>C:\Users\BIGKIMO\Desktop\aggdraw-master>python setup.py build
=== freetype not available (edit setup.py to enable)
running install
running build
running build_ext
building 'aggdraw' extension
C:\Program Files\Microsoft Visual Studio 10.0\VC\BIN\cl.exe /c /nologo /Ox /MD /
W3 /GS- /DNDEBUG -Iagg2/include -IC:\Python34\include -IC:\Python34\include /Tpa
ggdraw.cxx /Fobuild\temp.win32-3.4\Release\aggdraw.obj
aggdraw.cxx
aggdraw.cxx(124) : error C2440: 'initializing' : cannot convert from 'const char
 [5]' to 'Py_ssize_t'
        There is no context in which this conversion is possible
aggdraw.cxx(126) : error C2440: 'initializing' : cannot convert from 'destructor
' to 'printfunc'
        This conversion requires a reinterpret_cast, a C-style cast or function-
style cast
aggdraw.cxx(128) : error C2440: 'initializing' : cannot convert from 'getattrfun
c' to 'setattrfunc'
        This conversion requires a reinterpret_cast, a C-style cast or function-
style cast
aggdraw.cxx(142) : error C2440: 'initializing' : cannot convert from 'const char
 [4]' to 'Py_ssize_t'
        There is no context in which this conversion is possible
aggdraw.cxx(144) : error C2440: 'initializing' : cannot convert from 'destructor
' to 'printfunc'
        This conversion requires a reinterpret_cast, a C-style cast or function-
style cast
aggdraw.cxx(161) : error C2440: 'initializing' : cannot convert from 'const char
 [6]' to 'Py_ssize_t'
        There is no context in which this conversion is possible
aggdraw.cxx(163) : error C2440: 'initializing' : cannot convert from 'destructor
' to 'printfunc'
        This conversion requires a reinterpret_cast, a C-style cast or function-
style cast
aggdraw.cxx(187) : error C2440: 'initializing' : cannot convert from 'const char
 [5]' to 'Py_ssize_t'
        There is no context in which this conversion is possible
aggdraw.cxx(189) : error C2440: 'initializing' : cannot convert from 'destructor
' to 'printfunc'
        This conversion requires a reinterpret_cast, a C-style cast or function-
style cast
aggdraw.cxx(191) : error C2440: 'initializing' : cannot convert from 'getattrfun
c' to 'setattrfunc'
        This conversion requires a reinterpret_cast, a C-style cast or function-
style cast
aggdraw.cxx(207) : error C2440: 'initializing' : cannot convert from 'const char
 [5]' to 'Py_ssize_t'
        There is no context in which this conversion is possible
aggdraw.cxx(209) : error C2440: 'initializing' : cannot convert from 'destructor
' to 'printfunc'
        This conversion requires a reinterpret_cast, a C-style cast or function-
style cast
aggdraw.cxx(211) : error C2440: 'initializing' : cannot convert from 'getattrfun
c' to 'setattrfunc'
        This conversion requires a reinterpret_cast, a C-style cast or function-
style cast
aggdraw.cxx(488) : error C3861: 'PyString_Check': identifier not found
aggdraw.cxx(489) : error C3861: 'PyString_AS_STRING': identifier not found
aggdraw.cxx(575) : error C3861: 'PyString_Check': identifier not found
aggdraw.cxx(583) : error C3861: 'PyString_AS_STRING': identifier not found
aggdraw.cxx(584) : error C3861: 'PyString_GET_SIZE': identifier not found
aggdraw.cxx(730) : error C3861: 'PyInt_Check': identifier not found
aggdraw.cxx(730) : error C3861: 'PyInt_AS_LONG': identifier not found
aggdraw.cxx(731) : error C3861: 'PyInt_Check': identifier not found
aggdraw.cxx(731) : error C3861: 'PyInt_AS_LONG': identifier not found
aggdraw.cxx(735) : error C3861: 'PyInt_Check': identifier not found
aggdraw.cxx(735) : error C3861: 'PyInt_AS_LONG': identifier not found
aggdraw.cxx(736) : error C3861: 'PyInt_Check': identifier not found
aggdraw.cxx(736) : error C3861: 'PyInt_AS_LONG': identifier not found
aggdraw.cxx(742) : error C3861: 'PyInt_Check': identifier not found
aggdraw.cxx(742) : error C3861: 'PyInt_AS_LONG': identifier not found
aggdraw.cxx(745) : error C3861: 'PyInt_Check': identifier not found
aggdraw.cxx(745) : error C3861: 'PyInt_AS_LONG': identifier not found
aggdraw.cxx(759) : error C3861: 'PyInt_Check': identifier not found
aggdraw.cxx(760) : error C3861: 'PyInt_AsLong': identifier not found
aggdraw.cxx(763) : error C3861: 'PyString_Check': identifier not found
aggdraw.cxx(765) : error C3861: 'PyString_AS_STRING': identifier not found
aggdraw.cxx(788) : error C3861: 'PyString_Check': identifier not found
aggdraw.cxx(789) : error C3861: 'PyString_AS_STRING': identifier not found
aggdraw.cxx(1157) : error C3861: 'PyString_FromStringAndSize': identifier not fo
und
aggdraw.cxx(1289) : error C3861: 'PyString_FromString': identifier not found
aggdraw.cxx(1294) : error C3861: 'Py_FindMethod': identifier not found
aggdraw.cxx(1482) : error C3861: 'Py_FindMethod': identifier not found
aggdraw.cxx(1890) : error C3861: 'Py_FindMethod': identifier not found
aggdraw.cxx(1910) : error C3646: 'initaggdraw' : unknown override specifier
aggdraw.cxx(1911) : error C2091: function returns function
aggdraw.cxx(1911) : error C4430: missing type specifier - int assumed. Note: C++
 does not support default-int
aggdraw.cxx(1912) : error C2039: 'ob_type' : is not a member of '_typeobject'
        c:\python34\include\object.h(334) : see declaration of '_typeobject'
aggdraw.cxx(1912) : error C2039: 'ob_type' : is not a member of '_typeobject'
        c:\python34\include\object.h(334) : see declaration of '_typeobject'
aggdraw.cxx(1913) : error C2039: 'ob_type' : is not a member of '_typeobject'
        c:\python34\include\object.h(334) : see declaration of '_typeobject'
aggdraw.cxx(1913) : error C2039: 'ob_type' : is not a member of '_typeobject'
        c:\python34\include\object.h(334) : see declaration of '_typeobject'
aggdraw.cxx(1913) : error C2039: 'ob_type' : is not a member of '_typeobject'
        c:\python34\include\object.h(334) : see declaration of '_typeobject'
aggdraw.cxx(1915) : error C3861: 'Py_InitModule': identifier not found
aggdraw.cxx(1940) : warning C4508: 'DL_EXPORT' : function should return a value;
 'void' return type assumed
</code>
Answer: The Python FFI library (ctype) has changes between each version of python. It would be up to you to go through the change list and see what exactly is different and why it isn't working.
For example, ssizet and strings are different between the two Python versions.
https://docs.python.org/3/whatsnew/3.2.html#ctypes
Differences in ctypes between Python 2 and 3
Answer: In the interest of expanding upon the previous answer, there are many functions which acted upon string in Py2.7 and now act upon bytes or unicode in Py3. Similarly, what referred to int may now refer to long. As just one example of this that caused a problem here, PyString_Check has been deprecated by pyBytes_Check. Read the following for more details:
https://docs.python.org/3/howto/cporting.html?highlight=pystring


prove the existence of convex sets containing compact set

Question: How could I prove that every compact set is contained in a convex set/s?  Seems like an obvious claim but I want to formalize this idea.
Thanks in advance
Comment: Every subset of $\mathbb R^n$ is contained in a convex set, namey the whole space... Perhaps you mean this: every compact set is contained in a *compact* convex set?
Comment: Well that's what I want to prove next but as part of that proof I want to first generate a set containing all the convex sets which contain some compact set.  Then I'll take the intersection of those and proceed from there.  I guess I could've worded my question better by asking how to generate  a set containing all such convex sets
Comment: Oh, you're talking about the [convex hull](https://en.wikipedia.org/wiki/Convex_hull).
Comment: Yup, I'm trying to prove that such a convex set exists.  Namely, that a unique convex set B contains some compact set A, and B lies in all compact convex sets that contain A.  So my thinking is to take the intersection of the set containing all convex sets containing A, and then proving that the intersection of convex sets is also convex
Answer: I assume you are working on a normed vector space. Every compact subset is bounded, hence contained in a ball, which is convex.
Comment: I didn't ask the question in quite the way I wanted to, however you gave a perfect response to the question I asked so I'll accept your answer and re-ask my question.  Thanks
Comment: @lhf true, edited
Answer: If you are willing to restrict yourself to Banach spaces then you can say a bit more; if $K$ is a compact set in a Banach space then its closed convex hull (the smallest closed convex set containing $K$) is itself compact. This is the content of Mazur's compactness theorem.
Comment: Thanks for the response.  Well I want to prove the existence of the convex hull.  So what I want is to generate a set containing all the convex sets containing the compact set, then I can finish the proof from there.  But I'm not sure how to formalize the set containing all convex sets containing the compact set


How to individually change colors in an array?

Question: basically I'm doing an Ionic 5 application where I show some information from an array into an  and when you click it's supposed to change the color of the background, but when I click it changes the color of all the cards, not the only one I clicked.
This is the part of .ts for the color change:
  private buttonColor: string = "light";

  someAction() {
    this.buttonColor = "primary";
  }

And this is the .html:
<ion-grid>
    <ion-row>
      <ion-col *ngFor="let A of Animales">

        <ion-card [color]="buttonColor" (click)="someAction()" tappable>

          <ion-card-content>

            <ion-title>{{A.nombre}}</ion-title>

{{A.nombre}} {{A.raza}} es un {{A.especie}}. Su alimentación es a base de
              {{A.alimentacion}},
              por lo general viven en {{A.ecosistema}}.

          </ion-card-content>
        </ion-card>
      </ion-col>
    </ion-row>
  </ion-grid>

Answer: Because button color is same for all the cards, A simple solution would be to add a color to Animals array
<ion-col *ngFor="let A of Animales">
   <ion-card [color]="A.buttonColor || 'light'" (click)="someAction(A)" tappable>

and modify the someAction function to receive the animal
someAction(animal) {
  animal.buttonColor = "primary";
}

If you want you could also keep a separate array of colors but then instead of passing the animal to someAction pass the index
Answer: All buttons are changing color because you are using only one variable buttonColor as the source of data, and you are modifying this when any button is clicked.
You have to uniquely identify the button you are clicking, and then change the color of only that button.
In your component, create an array buttonColors with same length as your Animals array.
private buttonColors: string[];

// After 'Animals' data is available, initialize this array.
this.buttonColors = new Array(Animales.length).fill("light");

Modify *ngFor to include an index, and pass this index to the click event handler function.
  <ion-col *ngFor="let A of Animales; let i = index">
     <ion-card [color]="buttonColors[i]" (click)="someAction(i)" tappable>
      ...
      ...
    </ion-card>
  </ ion-col>

Modify the click event handler function to only change clicked button's color.
someAction(i) {
  this.buttonColors[i] = "primary";
}

Answer:
Here is working Example

  Animales = [{
    nombre: "Hellow",
    raza: "Hellow"
  },
  {
    nombre: "Hellow",
    raza: "Hellow"
  },{
    nombre: "Hellow",
    raza: "Hellow"
  },{
    nombre: "Hellow",
    raza: "Hellow"
  },

  ]
  buttonColor =['secondary','dark','danger'];

.html
 <ion-grid>
    <ion-row>
      <ion-col *ngFor="let A of Animales ;let i = index">
        <ion-card [color]="buttonColor[i]" (click)="someAction(i)" tappable>
          <ion-card-content>
            <ion-title>{{A.nombre}}</ion-title>

{{A.nombre}} {{A.raza}}

          </ion-card-content>
        </ion-card>
      </ion-col>
    </ion-row>
  </ion-grid>