Turn screen off using C windows 8

Question: I want to write a very tiny app using C that would turn the screen off or on. mapping keys to call a specific function should not be difficult.
Which are the system commands to turn the screen off or on on windows?
Thanks
Comment: I answered this question in a few minutes by googling your two requirements. a) a free utility and b) creating a shortcut
Comment: What does "screen" mean? Do you want to power-off the physical monitor? Do you want to dim/lock the session? Is this intended for a desktop? laptop? phone?
Comment: Since He says on windows, I guess it's for a Windows PC. Therefore, the question is what means "turn screen off"
Comment: I would like this, or as a script. Do you have a link to a safe download? i got one but not sure its not malware
Answer: <code>// Turn off monitor
Sleep(500); // Eliminate user's interaction for 500 ms
SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, (LPARAM) 2);

// Turn on monitor
SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, (LPARAM) -1);

// Low power monitor
Sleep(500); // Eliminate user's interaction for 500 ms
SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, (LPARAM) 1);
</code>
Note that
<code>**1** - the display is going to low power.
**2** - the display is being shut off.
**-1** - the display is being turned on (undocumented value).
</code>

Turn screen off using C windows 8


What is the probability of getting 2 new balls out of 3 at the third time of picking 3 out of 12?

Question: Here is the question: (don't bother with the title if you don't get the question)
You are going to pick 3 balls out of 12 and put it back every time. The ball that gets picked is considered an old one. So what is the probability of getting 2 new balls when picking 3 balls at the third time?
My idea is that at the third time, there could be 3,4,5,6 balls picked before. Under each circumstances, it is a hypergeometric example. And I sum them up and get,
$$P(X=2 ;3|4|5|6)= \sum _{n=3}^6  \frac{ \binom{12-n}{2}\binom{n}{3-2}}{\binom{12}{3}} = \frac{83}{44} = 1.88636$$
which is definitely not the answer since probability can't be more than 1.
I think this is because I did not take conditional probability into account. How to figure that out? Also, is there another simpler way to solve this question? (I don't know if my solution is on the right track, either) Extension of this problem can be what is the probability of getting 2 new balls when picking 3 balls at the nth time, and would that be much more terrible and difficult?
Answer: Your suspicion is right in that you didn't take the conditional probabilities into account. The numbers of new/old balls in each draw of $3$ balls do have hypergeometric conditional distributions. As you seem to have done, I'll define "success" in this distribution as getting an old ball. If $X_k$ is the number of old balls in the $k^{th}$ draw, then the probability we require is
\begin{eqnarray*}
P(X_3=1) &=& \sum_{i=0}^{3}{P(X_2=i) P(X_3=1\mid X_2=i)}\qquad\qquad\text{($i=$ #old balls in $2^{nd}$ draw)} \\
&& \\
&=& \sum_{i=0}^{3}{\dfrac{\binom{3}{i} \binom{9}{3-i}}{\binom{12}{3}} \dfrac{\binom{6-i}{1} \binom{6+i}{2}}{\binom{12}{3}}} \\
&& \\
&=& \dfrac{1377}{3025} \approx 0.455.
\end{eqnarray*}
Comment: Wow, impressive. I think this is the correct answer. Thank you very much.
Answer: Well, from your equation, I notice that it is only increasing, which can't be right, since the probability should keep going down. So, instead of having a constant denominator, there needs to be some variable there. Also, if I checked this right, there should be a 0 probability of getting a "new" ball on your 6th try.
I would say that you actually have 10 balls to choose from after you draw your first 3, since you're allowed to pick one of your old balls. Then, after that, you've added 2 more "old" balls. So, you only have 8 choices. Keep going, you've got 6, 4, 2, and finally 0.  So, yeah, it is much simpler than you thought originally. You should be taking the probability of getting 2 new balls on the first pulls and then multiplying it by the probability of getting 2 more new balls on the second, and so on.
I got $\frac{84}{6655}$ as the probability. Do you know what the correct answer is?
Comment: Actually, since the balls are put back after each draw, I can keep getting the same 3 balls 6 times in a row (nearly impossible, but possible after all) so the 6th try I get a new ball won't be 0? Is it the way I worded my question incorrect that made you misunderstand?
Comment: Once you put the 2 new balls back, do they become "old" balls? Or are you allowed to pick them again, and only the original 3 that you picked are considered "old"?
Comment: they are old because they have been picked.
If you picked ball A, it is old forever.


.Net Core 3 worker service application with plugins with constructor with parameters

Question: I'am building windows service with re loadable plugins using .Net Core 3.
I started with Worker Service project template and added plugins feature using recommendations in Microsoft article Create a .NET Core application with plugins. My plugins use external dependencies and everything is load fine. Also, my solution can load/unload plugins without restarting service and for now all works fine.
Now I want to add parameters to plugin constructor (at this moment plugin constructor is parameter less) which will be resolved by DI from service, but without success. I need to pass ex. ILogerFactory, DbContext to plugin via constructor injection.
To create plugin instance I'm using
ActivatorUtilities.CreateInstance(this._serviceProvider, pluginType)

this._serviceProvider is constructor parameter in method from which plugins are created and it is correctly resolved from DI:
public TransformFile(ILogger<TransformFile> logger, IConfiguration configuration, IServiceProvider serviceProvider)

If I have plugin constructor like this
public TransformationPlugin(ILoggerFactory loggerFactory)

exception is thrown
Unable to resolve service for type 'Microsoft.Extensions.Logging.ILoggerFactory' while attempting to activate 'Transformation.TransformationPlugin'.

If I have plugin constructor like this
public TransformationPlugin(IServiceProvider serviceProvider)

i receive serviceProvider with 45 registered services but GetService returns null for every service.
If I stop execution in plugin constructor in Immediate Window I'm able to resolve ex. ILoggerFactory.
I try both with and without
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>

in plugin .csproj but result is same.
Also in plugins .csproj I have <Private>false</Private> for project in which interface is defined.
Answer: I found a solution. From documentation was clear that for two types to be treated as same they must be loaded from the same assembly. My wrong assumption was that Microsoft.* and Systems.* assemblies will be loaded in the same way as is shared project loaded. After some investigation, I found that these assemblies in the main program are loaded from the bin folder but in the plugin, they are loaded from C:\Users\username\.nuget\packages...
The reason for this is how AssemblyDependencyResolver works.
So in PluginAssemblyLoadContext in Load overridden method I replaced
string assemblyPath = _resolver.ResolveAssemblyToPath(assemblyName);
        if (assemblyPath != null)
        {
            return LoadFromAssemblyPath(assemblyPath);
        }

with
if (!assemblyName.FullName.StartsWith("Microsoft", StringComparison.OrdinalIgnoreCase) && !assemblyName.FullName.StartsWith("System", StringComparison.OrdinalIgnoreCase))
        {
            string assemblyPath = _resolver.ResolveAssemblyToPath(assemblyName);
            if (assemblyPath != null)
            {
                return this.LoadFromFile(assemblyPath);
            }
        }

and now in both main program and plugin Microsoft.* and System.* assemblies are shared and types (ILoggerFactory, IConfiguration, ...) are treated as same.


How to add a free document viewer to a web project?

Question: I'm developing a web project with asp.net and c #. (Excel, word, powerpoint, image, etc.) But I couldn't find a free document viewer. Is there an easy way to do this? I would like to add a document viewer to my free project.
Comment: There is already an article with this same issue. https://stackoverflow.com/questions/11939370/asp-net-html-document-viewer
Comment: Yes Alen, already asked... But I could not solve my problem despite my review. I look  there. usually using google docs with iframe... I need a more detailed resource.
Answer: You have 2 options to achieve the functionality that you are wanting. Your first option will be to use a combination of various open source libraries in order to get it to work. The second option will be to use a commercial sdk.
Option 1 - Open Source (Pdf.js, iTextSharp, Microsoft.Office.Interop)
To add a document viewer to your web application that isn't using an iframe with google docs, you could look into using PDF.JS. Here is information on how to view PDFs using PDF.JS:
Using PDF.JS to display PDFs in web browser
Then the next step is converting your documents and images to PDF. You can convert all of your input images to PDF using iTextSharp:
How to use iTextSharp to convert to PDF
Then you have to figure out how to convert the office formats to PDF. One option is using the Microsoft.Office.Interop to achieve this:
How to: Use Microsoft Office Interop C#
This allows you to use the Microsoft Office software installed on your machine to do the conversions for you.
Option 2 - Commercial SDK (LEADTOOLS)
Disclaimer: I am an employee of this company
The LEADTOOLS SDK is a commercial SDK that provides you with a DocumentViewer Control that you can embed in your application to display all different kinds of formats, including over 150+ different image formats as well as all of the common Office formats. One of the many benefits is that you do not have to use the Microsoft.Office.Interop to view the Microsoft formats as the LEADTOOLS SDK has native support for each office format.
You can demo the Document Viewer here :
https://demo.leadtools.com/JavaScript/DocumentViewer/


Set Theory Proof: Valid or not?

Question: I'm trying to gain understanding of set proofs and I came across this one. I can't help but think the proof is too simple and that there is more to it.
Problem: Prove or disprove for arbitrary sets $A$, $B$, $C$
$A\subset B\Rightarrow (A\cap C\subset B\cap C)$
My proof is:
Let $x$ be an arbitrary element
1) $\{x\mid (x\in A \rightarrow x\in B)\rightarrow [(x\in A \wedge x\in C)\rightarrow (x\in B\wedge x\in C)]\}$
by definition of subset and intersection
2) $\{x \mid (x\in A\rightarrow x\in B) \rightarrow (x\in A\rightarrow x\in B)\}$ by Simplification
3) $\{x \mid A\subset B \rightarrow A\subset B\}$ by definition of subset
QED
Would this be a valid proof for this particular problem? If not, how come?
Comment: I don't understand your notation in 1, 2, and 3.  Usually set theorists (and mathematicians in general) use { ... | ... } to mean a particular set, which is like a mathematical *object*; in a proof, you need to be writing *statements* (about mathematical objects).
Answer: I don't quite follow your proof, it looks like you end by stating the trivial fact that $A \subset B \implies A \subset B$. This does not establish that $A\subset B \implies A\cap C \subset B \cap C$. I would prove this result by doing the following:
Let $x \in A\cap C$. This means $x \in A$ and $x \in C$. Since $A \subset B$ then $x \in B$, so $x\in B \cap C$. The result follows.
Answer:
Note that $A\cap C=A-C^c$ and $B\cap C = B-C^c$.

$$A\subset B\Rightarrow A-C^c\subset B-C^c \Rightarrow A\cap C\subset B\cap C$$

Set Theory Proof: Valid or not?


nginx serving from html instead of gunicorn

Question: I have a nginx / gunicorn / django app I've set up following
https://medium.com/@_christopher/deploying-my-django-app-to-a-real-server-part-ii-f0c277c338f4
It works when I go to the main IP from the browser  (I got Django tried these URL patterns, in this order: admin/...) but when I go to /admin I got a 404. Nginx logs are as follows:
2019/07/05 00:30:28 [error] 13600#13600: *1 open() "/usr/share/nginx/html/admin" failed (2: No such file or directory), client: 22.214.171.124, server: 127.0.0.1, request: "GET /admin HTTP/1.1", host: "188.8.131.52"

So it is trying to serve files from html/ instead of serving gunicorn, why?
Nginx config:
server {
    listen 80;
    server_name 127.0.0.1;
    location = /favicon.ico {access_log off;log_not_found off;}

    location = /static/ {
        root /home/juan/site;
    }
    location = /media/ {
        root /home/juan/site;
    }

    location = / {
        include proxy_params;
        proxy_pass http://unix:/home/juan/site/site.sock;
    }
}

Comment: try setting `listen 8000` and restart nginx, then visit 127.0.0.1:8000 in your browser. If it works that would mean you have another server listening on port 80.
Answer: Remove the = from all the Location directives except the first. That means exact match, instead of the prefix match you want.
location = /favicon.ico {access_log off;log_not_found off;}

location /static/ {
    root /home/juan/site;
}
location /media/ {
    root /home/juan/site;
}

location / {
    include proxy_params;
    proxy_pass http://unix:/home/juan/site/site.sock;
}


image archive VS image strip

Question: i've noticed that plenty of games / applications (very common on mobile builds) pack numerous images into an image strip.
I figured that the advantages in this are making the program more tidy (file system - wise) and reducing (un)installation time. During the runtime of the application, the entire image strip is allocated and copied from FS to RAM.
On the contrary, images can be stored in an image archive and unpacked during runtime to a number of image structures in RAM.
The way I see it, the image strip approach is less efficient because of worse caching performance and because that even if the optimal rectangle packing algorithm is used, there will be empty spaces between the stored images in the strip, causing a waste of RAM.
What are the advantages in using an image strip over using an image archive file?
Answer: Caching will not be as much of an issue as you think, if the images in the strip are likely to appear at the same time - i.e. are all part of an animation.
As far as packing algorithms are concerned, most generic algorithms produce similar levels of efficiency - to get huge increases in packing efficiency you normally have to write an algorithm that is optimised for the dataset involved.
As is usually the case with optimization of any kind - caching or packing - don't worry about it until it's been proved to be an issue, and then you need to approach the problem with a good understanding of the context.

image archive VS image strip


How can I suppress "CSS file not found" errors on production?

Question: "One or more CSS files were not found or does not exist" errors are being displayed to users on production.  Of course I should fix the source of these errors, but in the meantime, I would like to suppress this error message.
On admin/config/development/logging, I have set Error messages to display to None.  Is there some other step I need to take to suppress these errors?
I have also cleared all caches (Drupal, Redis, Varnish) but the error (only present on some pages) is still being displayed to authenticated (non-admin) users.
Answer: I would first ask, are you logged in as super admin? I believe if you are logged in as super admin the message will display regardless of the setting in development/logging.
If you are not logged in as admin and are viewing the page anonymously did you clear your browser cache. If the messages are still being displayed, is your site being cached via varnish? You may need to clear the varnish cache or simply add an extra query parameter to the end of the url to make certain you are viewing an unvarnished page. Ex: www.example.com/homepage?extraquery
This is generally unadvisable but when push comes to shove and you need to hide something quickly on the production site, you can alway hide the error message box with css until you actually fix the error. AGAIN, i would only use this as a last resort and if deadlines are rapidly approaching and there just is no other option.
You could do something like .error {display:none;} in your global.css file or wherever seems more suitable.
Good luck
Comment: I am not logged in as an admin, just a standard authenticated user.  I am using Varnish and Redis (on Pantheon), but all caches have been cleared.


Android Database in my own directory

Question: I'm trying to use my own database in an Android application.   Most all the topics and tutorials on this topic suggest that you can create it and open it using SQLiteOpenHelper, which by default use data/data/com.my.application/databases folder.  I've seen the recommendation to copy the file from context.getAssets.open(dbname) to the default sqlite path.  If this is in fact the solution, what is the right path to pass my database.db file?
Comment: so do you want to know which path? destination?
Comment: yeah thats the case.. i thought i had to put the database file in the "assets" folder of the project
Answer: my friend you can try this one code
/**
 *
 * Purpose: Open and Read database to fetch records from different database
 * tables.
 *
 * @version 1.0
 *
 * @author ketan kalariya(email@example.com)
 *
 * **/

    public class DataBaseHelper extends SQLiteOpenHelper {

        private Context myContext;
        private SQLiteDatabase myDataBase;
        // Comman KEYs of tables
        public static String MASTERFENCE_TABLE = "MasterFence";
        public static String KEY_ID = "_id";
        public static String AREA = "area";
        public static String TAG = "tag";
        public static String TITLE = "title";
        public static String DESCR = "description";
        public static String NO = "no";

        public static String ADDFENCEPOINT_TABLE = "AddFencePoint";
        public static String ADDLATLONG_TABLE = "AddLatLong";
        public static String LAT = "lat";
        public static String LONG = "long";

        public static String TEMPFENCEPOINT_TABLE = "TempFencePoint";
        public static String TEMPLATLONG_TABLE = "TempLatLong";

        public DataBaseHelper(Context context) {
            super(context, context.getResources().getString(R.string.dbname), null,
                    1);
            this.myContext = context;
        }

        @Override
        public void onCreate(SQLiteDatabase arg0) {

        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        }

        // ---Create the database---
        public void createDataBase() throws IOException {

            // ---Check whether database is already created or not---
            boolean dbExist = checkDataBase();

            if (!dbExist) {
                this.getReadableDatabase();
                try {
                    // ---If not created then copy the database---
                    copyDataBase();
                    this.close();
                } catch (IOException e) {
                    throw new Error("Error copying database");
                }
            }
        }

        // --- Check whether database already created or not---
        private boolean checkDataBase() {
            try {
                final String myPath = "/data/data/" + myContext.getPackageName()
                        + "/databases/" + myContext.getString(R.string.dbname);
                final File f = new File(myPath);
                if (f.exists())
                    return true;
                else
                    return false;
            } catch (SQLiteException e) {
                e.printStackTrace();
                return false;
            }
        }

        // --- Copy the database to the output stream---
        public void copyDataBase() throws IOException {

            final InputStream myInput = myContext.getAssets().open(
                    myContext.getString(R.string.dbname));

            final String outFileName = "/data/data/" + myContext.getPackageName()
                    + "/databases/" + myContext.getString(R.string.dbname);

            final OutputStream myOutput = new FileOutputStream(outFileName);

            final byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer)) > 0) {
                myOutput.write(buffer, 0, length);
            }

            myOutput.flush();
            myOutput.close();
            myInput.close();
        }

        public void openDataBase() throws SQLException {

            // --- Open the database---
            final String myPath = "/data/data/" + myContext.getPackageName()
                    + "/databases/" + myContext.getString(R.string.dbname);

            myDataBase = SQLiteDatabase.openDatabase(myPath, null,
                    SQLiteDatabase.OPEN_READWRITE);
        }

        /**
         * Close the database
         */
        public synchronized void closeDatabase() {
            if (myDataBase != null)
                ;
            myDataBase.close();
            SQLiteDatabase.releaseMemory();
            super.close();
        }

        /** This method is insert require detail in database table. **/
        public long insertMasterFence(String area, String title, String descr,
                String tag) {
            ContentValues values = new ContentValues();

            values.put(AREA, area);
            values.put(TITLE, title);
            values.put(DESCR, descr);
            values.put(TAG, tag);
            Log.v("  db ", area + " " + title + " " + " " + descr + " " + tag);
            return myDataBase.insert(MASTERFENCE_TABLE, null, values);

        }

Comment: drop the `extends SQLiteOpenHelper` part if you don't use the `onCreate` / `onUpgrade` mechanism. Although it might work if you use it correctly it can give you a lot  of errors because if you get your db via `.getWritableDatabase` it might give you an empty database (since there is no code in onCreate

Android Database in my own directory


Loop Mediaelement.js video only 5 times

Question: I would like to loop my Mediaelement.js video only 5 times. I've found the setting where you can set loop: true, which makes you video loop. But with this setting, it loops infinitely. I would like to stop the loop after 5 times.
$(this).mediaelementplayer({
    loop: true,
    alwaysShowControls: false,
    startVolume: 0,
    features: [],
});

Does the Mediaelement have some extra settings to limit this loops? Or should I do this by using custom Javascript?
Comment: Why downvote, whats wrong with this question?
Answer: there is an event that fire when the video ends, you could use it to know how many time the vid played and stop it at five, this code is not tested, but should point you in the right direction
var player = $('videoContainer').mediaelementplayer();
var playCount = 0;

player.media.addEventListener('ended', function(e) {
    playCount++;
    if (playCount>=5){
        player.stop();
    }
}, false);

Loop Mediaelement.js video only 5 times


How can I improve my interpretation, "reciting" ability or just voice expressiveness?

Question: I've been taking some singing lessons lately and I really feel like the main error I have to absolutely correct is lack of emotions and expressiveness in my voice. My teacher some times tries to make me interpret the song, reciting it instead of singing to improve on that aspect but I'm not even close to satisfied with the results. Reciting it makes it even more evident my incapability of expressing emotions through my voice.
As a person, I'm a bit of an introvert, not like shy, but I don't talk a lot. I think the problem with expression is true for my voice generally, even when speaking. I use a "flat" tone and volume but I don't really know how to work on this.
Note that this problem is only true for my voice. I've never had any problem in communicating emotions with my facial expressions and words.
Any suggestions, exercises or even an explanation on what kind of role all this has in singing?
Comment: You might consider acting lessons.
Answer: Some actors only take parts where they can be themselves. What you see is pretty well what they are like in real life. Watch a good character actor, and you'll be convinced that's what they're like in real life. Except they're not. They take on a different persona - characteristics, gait, facial expressions, accent, etc.
You seem like you need to do a fair bit of pretending - not just in singing, but maybe in other aspects. Sounds odd, maybe, but try thinking of some emotions - love, hate, tenderness, timidity, victoriousness, loneliness come to mind. Imagine what the person who wrote the song was going through at the time of writing. Often it's actually what the song is about - it's a sort of cathartic act, if you like. Try to be that person in that situation.
If the song's about losing a loved one, put on a sad face, and sing in a completely different way than you would with a song that's about someone who's just fallen in love.
Your teacher should help with this: finding songs which require one emotion in particular, and persevering with it until you show that emotion - eventually it will become part of you - second nature. I remember in a choir some time ago, the conductor was having trouble getting us to sing as he wanted. He wound us all up and made us pretty angry. We sang it again, and he finished by saying 'Thank you. That's exactly the way it should be sung. And that was the only way I could get the emotion to come from you!'


How to prove this is a decreasing sequence?

Question: I have this sequence: $\{a_n\} = {\frac {1}{n^{1+\frac {1}{n}}}}$
I tried to take the derivative to show the rate of change is negative for some n but the derivative is not very nice to work with. I tried to show $\frac {\{a_{n+1}\}}{\{a_n\}}<1$ but again the ratio didn't clearly show that to me. What other method can I try to clearly show as n increases the sequence decreases?
EDIT: Also is there any property to say that if a sequence is bounded above by a decreasing sequence, then our sequence is also decreasing? Like $\frac {1}{n}$ in this case?
Answer: Being bounded above by a decreasing sequence does not imply that a sequence is decreasing.

Since the logarithm is an increasing function, it is sufficient to show that
$$\ln n^{1 + \frac 1 n}$$
is an increasing function. But this just reduces to studying
$$\left(1 + \frac 1 n\right) \ln n.$$
The derivative of this is
$$\left(1 + \frac 1 n\right) \frac 1 n - \frac{\ln n}{n^2} \approx \frac 1 n > 0$$
once $n$ is sufficiently large.
Comment: Is there a fast way to notice that the last line is approximately equal to 1/n for large n? I understand intuitively ln(n) is not going to grow nearly as quickly as n^2 but I was wondering if there was a more formal technique to show it?
Comment: Yes, there is. $\log (1+x) \leq x$ for all $x>0$ so the expression in the last line is at least equal to $(1+{\frac 1 n} )$ ${\frac 1 n}$ - ${\frac {n-1} {n^{2}}}$ $= {\frac 2 {n^{2}}$. For a proof the inequality for logarithm just note that $e^{x} \geq 1+x$ from its series expansion and taking logarithms gives you what you want.
Comment: Or simply that $(1+1/n)/n-(\ln n)/n^2=(n+1-\ln n)/n^2>0$   because $ n+1-\ln n=$ $n+1-\int_1^n(1/x)dx\geq $ $n+1-\int_1^n(1)dx=$ $n+1-(n-1)=2>0 $ for $n\geq 1.$


Como obter X e Y do clique em Canvas

Question: Gostaria de obter X e Y de um clique em minhas canvas.

var canvas;//o elemento canvas sobre o qual desenharemos
var ctx;//o "contexto" da canvas que será utilizado (2D ou 3D)
var dx = 5;//a tava de variação (velocidade) horizontal do objeto
var dy = 5;//a tava de variação (velocidade) vertical do objeto
var x = 250;//posição horizontal do objeto (com valor inicial)
var y = 100;//posição vertical do objeto (com valor inicial)
var WIDTH = 800;//largura da área retangular
var HEIGHT = 600;//altura da área retangular

function Desenhar() {
    ctx.beginPath();
    ctx.fillStyle = "blue";
    ctx.arc(x, y, 10, 0, Math.PI*2, true);
    ctx.fill();
}

function LimparTela() {
    ctx.fillStyle = "white";
    ctx.strokeStyle = "black";
    ctx.beginPath();
    ctx.rect(0, 0, WIDTH, HEIGHT);
    ctx.closePath();
    ctx.fill();
    ctx.stroke();
}

function Placar(){
 ctx.font = "14px Arial";
 ctx.fillStyle = "red";

 ctx.fillText('X = '+ x,745,10);
 ctx.fillText('Y = '+ y,745,25);
}

function Iniciar() {
    canvas = document.getElementById("canvas");
    ctx = canvas.getContext("2d");
    return setInterval(Atualizar, 10);
}

function KeyDown(evt){
    switch (evt.keyCode) {
        case 38:  /*seta para cima */
            if (y - dy > 0){
                y -= dy;
            }
            break;
        case 40:  /*set para baixo*/
            if (y + dy < HEIGHT){
                y += dy;
            }
            break;
        case 37:  /*set para esquerda*/
            if (x - dx > 0){
                x -= dx;
            }
            break;
        case 39:  /*seta para direita*/
            if (x + dx < WIDTH){
                x += dx;
            }
            break;
    }
}

function Atualizar() {
    LimparTela();
    Desenhar();
 Placar();
}
window.addEventListener('keydown', KeyDown, true);
Iniciar();
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>Canvas</title>

        <canvas id="canvas" width="800" height="600">
        Se você visualizar esse texto, seu browser não suporta a tag canvas.
        </canvas>

Como faço isso?
Answer: Crie um evento click para a área do canvas:
document.getElementById("canvas").addEventListener('click', KeyDown, true);

Depois inclua na função KeyDown() o código para pegar a posição do clique:
evt.clientX (eixo X) e evt.clientY (eixo Y)
É importante também saber a distância do canvas em relação ao topo e à esquerda para que a posição seja relativa ao canvas e não à janela do navegador:
canvas.offsetLeft e canvas.offsetTop
Veja:

var canvas;//o elemento canvas sobre o qual desenharemos
var ctx;//o "contexto" da canvas que será utilizado (2D ou 3D)
var dx = 5;//a tava de variação (velocidade) horizontal do objeto
var dy = 5;//a tava de variação (velocidade) vertical do objeto
var x = 250;//posição horizontal do objeto (com valor inicial)
var y = 100;//posição vertical do objeto (com valor inicial)
var WIDTH = 800;//largura da área retangular
var HEIGHT = 600;//altura da área retangular

function Desenhar() {
    ctx.beginPath();
    ctx.fillStyle = "blue";
    ctx.arc(x, y, 10, 0, Math.PI*2, true);
    ctx.fill();
}

function LimparTela() {
    ctx.fillStyle = "white";
    ctx.strokeStyle = "black";
    ctx.beginPath();
    ctx.rect(0, 0, WIDTH, HEIGHT);
    ctx.closePath();
    ctx.fill();
    ctx.stroke();
}

function Placar(){
 ctx.font = "14px Arial";
 ctx.fillStyle = "red";

 ctx.fillText('X = '+ x,745,10);
 ctx.fillText('Y = '+ y,745,25);
}

function Iniciar() {
    canvas = document.getElementById("canvas");
    ctx = canvas.getContext("2d");
    return setInterval(Atualizar, 10);
}

function KeyDown(evt){

   var canvas = document.getElementById("canvas");

   // posição dos cliques descontando a distância da borda da janela
   var posX = evt.clientX - canvas.offsetLeft;
   var posY = evt.clientY - canvas.offsetTop;

   console.clear();
   console.log("Posição do clique: ", posX+","+posY);

    switch (evt.keyCode) {
        case 38:  /*seta para cima */
            if (y - dy > 0){
                y -= dy;
            }
            break;
        case 40:  /*set para baixo*/
            if (y + dy < HEIGHT){
                y += dy;
            }
            break;
        case 37:  /*set para esquerda*/
            if (x - dx > 0){
                x -= dx;
            }
            break;
        case 39:  /*seta para direita*/
            if (x + dx < WIDTH){
                x += dx;
            }
            break;
    }
}

function Atualizar() {
    LimparTela();
    Desenhar();
 Placar();
}
window.addEventListener('keydown', KeyDown, true);
document.getElementById("canvas").addEventListener('click', KeyDown, true);
Iniciar();

  <canvas id="canvas" width="800" height="600">
  Se você visualizar esse texto, seu browser não suporta a tag canvas.
  </canvas>

Comment: Você é um gênio! Obrigado!
Answer: Criei um método Clique, que é chamado no clique ao canvas.
Nele recebo o evento de clique, neste evento verifico se ele contem pageX ou pageY, se conter não preciso realizar o calculo para saber a posição do clique em relação a pagina, se não realizo o calculo com as devidas propriedades, e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft, então obtendo este valor, realizo a subtração do offsetTop para Y e offsetLeft para X

var canvas;//o elemento canvas sobre o qual desenharemos
var ctx;//o "contexto" da canvas que será utilizado (2D ou 3D)
var dx = 5;//a tava de variação (velocidade) horizontal do objeto
var dy = 5;//a tava de variação (velocidade) vertical do objeto
var x = 250;//posição horizontal do objeto (com valor inicial)
var y = 100;//posição vertical do objeto (com valor inicial)
var WIDTH = 800;//largura da área retangular
var HEIGHT = 600;//altura da área retangular

function Desenhar() {
    ctx.beginPath();
    ctx.fillStyle = "blue";
    ctx.arc(x, y, 10, 0, Math.PI*2, true);
    ctx.fill();
}

function LimparTela() {
    ctx.fillStyle = "white";
    ctx.strokeStyle = "black";
    ctx.beginPath();
    ctx.rect(0, 0, WIDTH, HEIGHT);
    ctx.closePath();
    ctx.fill();
    ctx.stroke();
}

function Placar(){
    ctx.font = "14px Arial";
    ctx.fillStyle = "red";

    ctx.fillText('X = '+ x,745,10);
    ctx.fillText('Y = '+ y,745,25);
}

function Iniciar() {
    canvas = document.getElementById("canvas");
    canvas.addEventListener('click', Clique);
    ctx = canvas.getContext("2d");
    return setInterval(Atualizar, 10);
}

function KeyDown(e){
    switch (e.keyCode) {
        case 38:  /*seta para cima */
            if (y - dy > 0){
                y -= dy;
            }
            break;
        case 40:  /*set para baixo*/
            if (y + dy < HEIGHT){
                y += dy;
            }
            break;
        case 37:  /*set para esquerda*/
            if (x - dx > 0){
                x -= dx;
            }
            break;
        case 39:  /*seta para direita*/
            if (x + dx < WIDTH){
                x += dx;
            }
            break;
    }

    var px = canvas.clientWidth - x;
    var py = canvas.clientHeight - y;
    console.log(px);
    console.log(py);
}

function Clique(e) {
   var px;
   var py;
   if (e.pageX || e.pageY) {
      px = e.pageX;
      py = e.pageY;
   } else {
      px = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
      py = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
   }
   px -= canvas.offsetLeft;
   py -= canvas.offsetTop;
   console.log('x:', px);
   console.log('y:', py);
}

function Atualizar() {
    LimparTela();
    Desenhar();
    Placar();
}
window.addEventListener('keydown', KeyDown, true);

Iniciar();
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>Canvas</title>

        <canvas id="canvas" width="800" height="600">
        Se você visualizar esse texto, seu browser não suporta a tag canvas.
        </canvas>

Como obter X e Y do clique em Canvas


list index out of range ao tentar resolver questão do google developer day 2010

Question: Primeiramente, vou copiar aqui o enunciado da questão para se situarem:
Na pacata vila campestre de Ponteironuloville, todos os telefones têm 6 dígitos. A companhia telefônica estabelece as seguintes regras sobre os números:

Não pode haver dois dígitos consecutivos idênticos, porque isso é chato;
A soma dos dígitos tem que ser par, porque isso é legal;
O último dígito não pode ser igual ao primeiro, porque isso dá azar.

Então, dadas essas regras perfeitamente razoáveis, bem projetadas e maduras, quantos números de telefone na lista abaixo são válidos?
(A lista da questão está no começo do meu código.)
Dado o enunciado, eis a minha tentativa de resolução:
lista = '''213752 216732 221063 221545 225583 229133 230648 233222 236043 237330
         239636 240138 242123 246224 249183 252936 254711 257200 257607 261424
         263814 266794 268649 273050 275001 277606 278997 283331 287104 287953
         289137 291591 292559 292946 295180 295566 297529 300400 304707 306931
         310638 313595 318449 319021 322082 323796 326266 326880 327249 329914
         334392 334575 336723 336734 338808 343269 346040 350113 353631 357154
         361633 361891 364889 365746 365749 366426 369156 369444 369689 372896
         374983 375223 379163 380712 385640 386777 388599 389450 390178 392943
         394742 395921 398644 398832 401149 402219 405364 408088 412901 417683
         422267 424767 426613 430474 433910 435054 440052 444630 447852 449116
         453865 457631 461750 462985 463328 466458 469601 473108 476773 477956
         481991 482422 486195 488359 489209 489388 491928 496569 496964 497901
         500877 502386 502715 507617 512526 512827 513796 518232 521455 524277
         528496 529345 531231 531766 535067 535183 536593 537360 539055 540582
         543708 547492 550779 551595 556493 558807 559102 562050 564962 569677
         570945 575447 579937 580112 580680 582458 583012 585395 586244 587393
         590483 593112 593894 594293 597525 598184 600455 600953 601523 605761
         608618 609198 610141 610536 612636 615233 618314 622752 626345 626632
         628889 629457 629643 633673 637656 641136 644176 644973 647617 652218
         657143 659902 662224 666265 668010 672480 672695 676868 677125 678315'''

lista = lista.split()
#como simplesmente copiei a lista, não quis separar 200 elementos manualmente.

validos = []
#lista vazia onde irei inserir os números válidos.

for ca in range(len(lista)):
    n_inv = False
    e = list(lista[ca])
    for cb in range(len(e) - 1):
        cc = cb + 1
        if e[cb] == e[cc]:
            n_inv = True
    if n_inv == False:
        validos.append(lista[ca])
#2 loops(externo e interno) para selecionar os números de acordo com a primeira
#condição dada, até aqui tudo bem.

for ca in range(len(validos)):
    a = 0
    e = list(validos[ca]) #o IDLE acusa o erro aqui(list index out of range)
    for cb in range(len(e)):
        a += int(e[cb])
    if a % 2 != 0:
        del validos[ca]
#loop para filtrar os números anteriormente selecionados de acordo com a condição 2.

for ca in range(len(validos)):
    e = list(validos[ca])
    if e[0] == e[-1]:
        del validos[ca]
#loop para filtrar os números anteriormente selecionados de acordo com a condição 3.

print(len(validos))

Já estou há algumas horas quebrando a cabeça pra fazer esse código. Já tive alguns outros problemas com ele, mas consegui resolver, principalmente com a ajuda do python tutor. Esse eu não consigo visualizar a execução porque o site limita os loops em 300 pra evitar loopings infinitos. Se puderem me ajudar mais essa vez, agradeço muito.
Answer: Olha, não entendo de python, mas acho que neste trecho:
for ca in range(len(validos)):
    a = 0
    e = list(validos[ca]) #o IDLE acusa o erro aqui(list index out of range)
    for cb in range(len(e)):
        a += int(e[cb])
    if a % 2 != 0:
        del validos[ca]

Você está deletando os elementos da lista ao mesmo tempo que está iterando ela. Como resultado, durante a iteração, a lista diminui de tamanho, mas você ainda tenta acessar todos os elementos como se ainda estivessem ali. O resultado é que uma hora você vai acabar tentando acessar um elemento fora da lista.
Penso nas seguintes soluções:

Reprojetar o laço para incrementar o ca apenas se o elemento não tiver sido removido.
Ao invés de remover os elementos da lista, substituí-los por alguma coisa que indica que devam ser desconsiderados (por exemplo, um zero) e então no final você conta quantos elementos não são zeros.
Ao invés de remover os elementos inválidos da lista, copiar os válidos para uma outra lista que será então usada na etapa seguinte.
Iterar a lista de números apenas uma vez, já verificando as três condições em uma mesma iteração. E então, basta manter um contador de quantos números válidos você encontrou. Com isso, você não precisa alterar e nem excluir elementos e nem inserí-los em listas auxiliares.
Comment: @JeffersonCarvalho Acredito que por questão de desempenho, ele só vai avaliar o `range(len(validos))` uma vez. Pelo menos em todas as outras linguagens que conheço, é isso que acontece. Quanto a modificar o `while`, você usou `ca <= len(validos)`, mas deveria ser `ca < len(validos)`.
Comment: Estranho, eu pensei que sempre que eu removesse um elemento, quando eu voltasse pro começo do loop ele ia atualizar o tamanho da lista `validos` então eu não teria esse problema(já que a condição de parada pro loop é o próprio tamanho da lista). Tentei modificar com while, conforme você disse, mas o erro persistiu:

ca = 0
while ca <= len(validos):
    a = 0
    e = list(validos[ca])
    for cb in range(len(e)):
        a += int(e[cb])
    if a % 2 != 0:
        del validos[ca]
    else:
        ca += 1

Porém, deu certo ao transformar os números inválidos em `'0'` e removê-los depois.
Answer: Como mencionado pelo Victor, o problema acontece quando você utiliza o del para remover o item da lista. Isso acontece nos dois últimos laços for do código:
for ca in range(len(validos))
    ...
    del validos[ca]

A expressão len(validos) é avaliada somente uma vez, no momento em que range é avaliado. Quando você remove um elemento seja por pop ou del, a exceção IndexError é gerada.
Como bem citado pelo Victor, ao invés de remover os números inválidos, copie somente os válidos para a lista validos.
Poderia também ser economizado algumas linhas de código avaliando as condições no mesmo laço for.
O seu código com essas modificações pode ficar assim:
#!/usr/bin/python
# -*- coding: utf-8 -*-

lista = '''213752 216732 221063 221545 225583 229133 230648 233222 236043 237330
         239636 240138 242123 246224 249183 252936 254711 257200 257607 261424
         263814 266794 268649 273050 275001 277606 278997 283331 287104 287953
         289137 291591 292559 292946 295180 295566 297529 300400 304707 306931
         310638 313595 318449 319021 322082 323796 326266 326880 327249 329914
         334392 334575 336723 336734 338808 343269 346040 350113 353631 357154
         361633 361891 364889 365746 365749 366426 369156 369444 369689 372896
         374983 375223 379163 380712 385640 386777 388599 389450 390178 392943
         394742 395921 398644 398832 401149 402219 405364 408088 412901 417683
         422267 424767 426613 430474 433910 435054 440052 444630 447852 449116
         453865 457631 461750 462985 463328 466458 469601 473108 476773 477956
         481991 482422 486195 488359 489209 489388 491928 496569 496964 497901
         500877 502386 502715 507617 512526 512827 513796 518232 521455 524277
         528496 529345 531231 531766 535067 535183 536593 537360 539055 540582
         543708 547492 550779 551595 556493 558807 559102 562050 564962 569677
         570945 575447 579937 580112 580680 582458 583012 585395 586244 587393
         590483 593112 593894 594293 597525 598184 600455 600953 601523 605761
         608618 609198 610141 610536 612636 615233 618314 622752 626345 626632
         628889 629457 629643 633673 637656 641136 644176 644973 647617 652218
         657143 659902 662224 666265 668010 672480 672695 676868 677125 678315'''

lista = lista.split()
validos = []

for indice in range(len(lista)):
    soma = 0
    ff = 0
    invalido = True
    elemento = list(lista[indice])
    soma = sum(map(int, elemento))
    for caractere in range(len(elemento) -1):
        proximoCaractere = caractere + 1
        if (elemento[caractere] == elemento[proximoCaractere]) or (int(soma) % 2 != 0) or (elemento[0] == elemento[-1]):
            invalido = True
            break
        else:
            invalido = False

    if invalido == False:
        validos.append(elemento)

print ("Válidos: {0} / Original: {1}".format(len(validos), len(lista)))

Exemplo funcional no repl.it.
Comment: @JeffersonCarvalho Desculpe-me já corrigi o código. =)
Comment: Interessante, realmente o código ficou bem menor. Mas a resposta acabou saindo errado, o seu código gerou 76 e o correto seria 39. Talvez isso tenha acontecido porque você se esqueceu de somar os números dos elementos antes de verificar se ele era par.
Answer: Achei interessante a questão e gostaria complementar com uma solução com uma cara mais OO.
# -*- coding: utf-8 -*-

from itertools import tee

class ListaTelefones(object):

    def __init__(self, lista_de_telefones):
        self.telefones = lista_de_telefones.split()
        self.telefones_validos = []
        self.telefones_invalidos = []

    def dois_a_dois(self, iterable):
        "s -> (s0,s1), (s1,s2), (s2, s3), ..."
        a, b = tee(iterable)
        next(b, None)
        return zip(a, b)

    def digitos_consecutivos_identicos(self, telefone):
        """ Não pode haver dois dígitos consecutivos idênticos,
            porque isso é chato. """
        return all([True if el1 != el2 else False
                   for el1, el2 in self.dois_a_dois(telefone)])

    def soma_digitos_e_par(self, telefone):
        """ A soma dos dígitos tem que ser par, porque isso é legal. """
        return sum(map(int, telefone)) % 2 == 0

    def primeiro_e_ultimo_digito_diferentes(self, telefone):
        """ O último dígito não pode ser igual ao primeiro,
            porque isso dá azar. """
        return telefone[0] != telefone[-1]

    def checar_validade(self, telefone):
        condicao1 = self.digitos_consecutivos_identicos(telefone)
        condicao2 = self.soma_digitos_e_par(telefone)
        condicao3 = self.primeiro_e_ultimo_digito_diferentes(telefone)
        return all([condicao1, condicao2, condicao3, ])

    def obter_telefones_validos(self):
        self.telefones_validos = []
        for li in self.telefones:
            if self.checar_validade(li):
                self.telefones_validos.append(li)

    def imprimir_telefones(self):
        for li in self.telefones:
            print(li)

    def imprimir_telefones_validos(self):
        for li in self.telefones_validos:
            print(li)

    def contar_telefones(self):
        print(len(self.telefones))

    def contar_telefones_validos(self):
        print(len(self.telefones_validos))

lista = '''213752 216732 221063 221545 225583 229133 230648 233222 236043 237330
         239636 240138 242123 246224 249183 252936 254711 257200 257607 261424
         263814 266794 268649 273050 275001 277606 278997 283331 287104 287953
         289137 291591 292559 292946 295180 295566 297529 300400 304707 306931
         310638 313595 318449 319021 322082 323796 326266 326880 327249 329914
         334392 334575 336723 336734 338808 343269 346040 350113 353631 357154
         361633 361891 364889 365746 365749 366426 369156 369444 369689 372896
         374983 375223 379163 380712 385640 386777 388599 389450 390178 392943
         394742 395921 398644 398832 401149 402219 405364 408088 412901 417683
         422267 424767 426613 430474 433910 435054 440052 444630 447852 449116
         453865 457631 461750 462985 463328 466458 469601 473108 476773 477956
         481991 482422 486195 488359 489209 489388 491928 496569 496964 497901
         500877 502386 502715 507617 512526 512827 513796 518232 521455 524277
         528496 529345 531231 531766 535067 535183 536593 537360 539055 540582
         543708 547492 550779 551595 556493 558807 559102 562050 564962 569677
         570945 575447 579937 580112 580680 582458 583012 585395 586244 587393
         590483 593112 593894 594293 597525 598184 600455 600953 601523 605761
         608618 609198 610141 610536 612636 615233 618314 622752 626345 626632
         628889 629457 629643 633673 637656 641136 644176 644973 647617 652218
         657143 659902 662224 666265 668010 672480 672695 676868 677125 678315'''

lista_telefones = ListaTelefones(lista_de_telefones=lista)
lista_telefones.obter_telefones_validos()
lista_telefones.imprimir_telefones_validos()
lista_telefones.contar_telefones_validos()

https://gist.github.com/arthuralvim/f0e7f62414e4ade71745
Comment: Boa parte desse código eu ainda não entendo pois sou iniciante, rs
Mas pelo menos a resposta final está correta, que é 39.


Use SDWebImage to load a image for imageview, How can i get the width of image?

Question: when i use setImageWithURL to load online image, i got 0.000000,
  but when i load local image,i got the correct width.
<code>NSURL * url1=[NSURL URLWithString:@"http://img.hb.aicdn.com/7f46b5eb65320f18f797a4a26ebe9ba328b547832f7b3-KYR0Xn_fw192"];
UIImageView * img2=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 192,400)];
[img2 setImageWithURL:url1];
//[img2 setImage:[UIImage imageNamed:@"0.gif"]];
//load local image

[self.view addSubview:img2];
CGFloat height1=img2.image.size.width;
NSLog(@"%f",height1);
</code>
Comment: u dont display any code using SDWebImage
Answer: I know this is a very old question but I got the same problem a while ago and thought my answer could help someone who runs into the same problem.
To get the image width, you should download the image independently with SDWebImageManager. I'm pretty sure it is explained in their wiki page.
Here is the example code to do the task :
<code>-(UIImage *)downloadImageAsync:(NSString *)imageKey
{
    NSLog(@"image key : %@",imageKey);
    __block UIImage *returnedImage;
    SDWebImageManager *manager = [SDWebImageManager sharedManager];
    [manager downloadWithURL:[NSURL URLWithString:imageKey] options:0 progress:^(NSUInteger receivedSize, long long expectedSize){
        NSLog(@"received size %d expected size %lld", receivedSize, expectedSize);

    }completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType,BOOL finished){
        if(image && finished) {
            returnedImage = image;
        }
    }];

    if(returnedImage == nil) {
        NSLog(@"Returned Image Nil");
    }
    return returnedImage;
}
</code>
So when the UIImage finishes downloading, you can get the width and height of it. Hope this helps.
Cheers.


Table Cell into two lines in iOS

Question: I'm working on iOS App and I want the text label to be in two lines. I found the following code but it doesn't seem to work. Any ideas on what I'm doing wrong?
<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];

        [[cell textLabel] setNumberOfLines:2];

        cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
        cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:10.0];

        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    //Configure cell
}
</code>
Answer: Try this
<code> [[cell textLabel] setNumberOfLines:0];
</code>
Comment: It works fine for me.Please check my sample code here https://github.com/slysid/iOS/tree/master/MutlipleLineCell
Answer: I have tested it and this is working fine..
<code>cell.textLabel.numberOfLines=2
</code>
Comment: Thanks @Ashish…I used @slysid's proposal and got the problem resolved. Thanks for the suggestion though.

Table Cell into two lines in iOS


Block taxonomy list count with filter by search term?

Question: Currently I have setup a view to display custom search results based on search terms (exposed filter):
/blog/search?keys=user+entered+term
On the page I am looking to show a list of tags with counts based on that search term, for example:
Code (x)
Tutorial (x)
Help (x)
A block has already been created in the view with the following:
CONTEXTUAL FILTERS
(term) Taxonomy term: Name (-> display summary with count)
RELATIONSHIPS
Content: Taxonomy terms on node
FIELDS
(term) Taxonomy term: Name
While the above does output the taxonomy terms, it displays the counts for all of the taxonomy, rather than filtering it based on the search term.
Seems like I am most of the way there, but would appreciate any thoughts/suggestions anyone could offer.
Answer: Contextual Filter Wont do here. Please follow these steps:

Add another field "Taxonomy:term name".
Under the advanced settings tab, turn on SQL Aggregation.
Edit the sql aggregation settings against the newly added field "taxonomy term" to make it "COUNT". Not "COUNT DISTINCT" remember.
If there is any sort option, please remove it for this to work. Let the filter remain as it is.
Now you will have taxonomy tags, with the number of nodes against each.
Comment: Unfortunately this didn't work and just output 1 total number.  I removed the contextual filter, as well as the sort options, keeping the existing relationship and set the aggregation on the taxonomy term field to 'count'
Comment: So What all fields are there at present?..can you post a screenshot of your views screen?..this did work for me.
Comment: here you go: http://troll.ws/image/0997d4c0#.UlalfmRAQ98
Comment: I am evaluating. Here is a quickie: Please dont apply COUNT on both the fields. One taxonomy term field should be without count and other should be with count. Please change this and let me know. Till then I am looking into the screenshot.
Comment: http://troll.ws/image/81278f53#.UlaqxmRAQ98 v2 with count on 2nd taxonomy:term name field (the first is set to group, no option to disable)

This is appearing as before with the Contextual Filter, however I need it to filter nodes based on the search term from the search results page (also within that view).
Comment: are you using a group by too?...if so you even need to remove that. the aggregation will take care of it.

BTW, I think you should create a fresh view for testing, do a bare minimum, start with my steps above, and also add the relationship. Then if the grouping works, add the exposed filters and see. this will help you detect the bug. The above approach works for me and there is no reason it should not work for you.


MySQL COUNT DISTINCT

Question: I'm trying to collect the number of distinct visits in my cp yesterday, then count them.
SELECT
    DISTINCT `user_id` as user,
    `site_id` as site,
    `ts` as time
FROM
    `cp_visits`
WHERE
    ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)

For some reason this is pulling multiple results with the same site id....how do i only pull and count the distinct site_id cp logins?
Answer:  Select
     Count(Distinct user_id) As countUsers
   , Count(site_id) As countVisits
   , site_id As site
 From cp_visits
 Where ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)
 Group By site_id

Comment: I love SQL because you get questions like "How do I count distinct user IDs" and the answer is just "`Count(Distinct user_id)`"
Comment: for mysql it could return an error because user_id isn't in group by clause
Comment: @AlexeySh. , no it will not give any error.
Answer: Overall
SELECT
       COUNT(DISTINCT `site_id`) as distinct_sites
  FROM `cp_visits`
 WHERE ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)

Or per site
  SELECT
         `site_id` as site,
         COUNT(DISTINCT `user_id`) as distinct_users_per_site
    FROM `cp_visits`
   WHERE ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)
GROUP BY `site_id`

Having the time column in the result doesn't make sense - since you are aggregating the rows, showing one particular time is irrelevant, unless it is the min or max you are after.
Answer: You need to use a group by clause.
SELECT  site_id, MAX(ts) as TIME, count(*) group by site_id

MySQL COUNT DISTINCT


Finding the probability that a specific state is reached in an absorbing state Markov Chain

Question: Suppose an RNG generates a random number in the inclusive range [1, M] and continues to generate numbers in the inclusive range [1, m], where m is the previously generated number, until a 1 is generated. I'm interested in knowing the probability that a specific value, x, is generated at some point during this process.
I have the Markov Chain set up and know the probability of the range being [1, m] at the end of the Nth generation, denoted as P(m, N). However, I'm having difficulty in using this information to answer the above question. I've simulated various results and am noticing that the answer is equal to the sum of P(x+1, N) for all N >= 1, but I don't know why this is the case. For example, with M = 10 and x = 2, the answer appears to be 50%, which is equal to P(3, 1) + P(3, 2) + P(3, 3) + ...
Any insight on this problem in particular or tips on what I should study in order to find the answer would be greatly appreciated!
Answer: Here is a process that generates a uniformly random integer in the range $[1,m]$. Start going through the values $m, m-1, m-2, \dots, 1$ in descending order; at each value $k$, stop and return $k$ with probability $\frac1k$, and keep going otherwise. (If we get to $1$, the probability of stopping is $\frac11 = 1$.) This is uniform because the overall probability that we stop at $k$ (and not earlier) is $\frac{m-1}{m} \cdot \frac{m-2}{m-1} \cdots \frac{k}{k-1} \cdot \frac1k = \frac1m$: the same for every $k$.
Suppose that at every step in our overall algorithm (pick a random number between $1$ and the previously picked number, inclusive) we use the process above. However, we have a particular value, $x$, in mind, and we want to know if we'll ever see $x$.
After some variable number of steps, we will get to a range $[1,m]$ for which the subprocess that picks a random integer in the range $[1,m]$ gets to the point of considering the value $k=x$. It is at this moment in time that the fate of $x$ is decided!

With probability $\frac1k = \frac1x$, the subprocess stops and returns $x$. This means that from the point of view of the overall algorithm, $x$ has now been generated.
With probability $1 - \frac1k$, the subprocess keeps going to $k-1$, and then maybe onwards to $k-2, k-3, \dots$. The subprocess will now return a value smaller than $x$, and from then on, there will no longer be any chance of generating $x$ in the overall algorithm.

Therefore the probability of ever generating $x$ is equal to $\frac1x$, for all integers $x \in [1,M]$. (This is true regardless of whether we use this particular subprocess for picking random integers, because the method we use should not affect the distribution.)
This process is often considered with the goal of knowing how many numbers are generated overall. There are many ways to answer that question, but after what we've done here, it becomes easy to answer: if the probability of ever generating $x$ is $\frac1x$, then the expected number of values generated is $$\sum_{x=1}^M \frac1x = 1 + \frac12 + \frac13 + \dots + \frac1M$$ which is $H_M$, the $M^{\text{th}}$ harmonic number.
Comment: Thank you so much for the detailed answer; I really appreciate your assistance! It's such an elegant solution, and it brings me joy.


Armazenar 10 valores em R

Question: Bom dia a todos, tenho que fazer um exercício onde tenho que armazenar 10 valores digitados repetidamente e dizer quantos são negativos e positivos.
Preciso usar o comando while mas não sei como fazer para armazenar estes valores.
Comment: você tentou resolver esse exercício de alguma maneira? coloque o seu código para exemplificar
Answer: Tente o seguinte:
conta <- 0
x <- numeric(0)
while(conta < 10){
    y <- scan(nmax = 1)
    x <- c(x, y)
    conta <- conta + 1
}

positivo <- x[x > 0]
negativo <- x[x < 0]
zero <- x[x == 0]

Agora se quiser saber quantos são os positivos, negativos ou zero (que falta na pergunta?) basta usar length.
length(positivo)
length(negativo)
length(zero)

Para os ver,
positivo
negativo
zero

Armazenar 10 valores em R


Campo Unique Update com Hibernate

Question: Como trato um campo unique na hora de fazer um update com hibernate.
Ele apresenta a msg de campo duplicado.
<code>Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '41987523699' for key 'UK_4yakf5drp3py7vaalfeb1mrv7'
</code>
Comment: Um pouco mais sobre UNIQUE: [É possível ter mais de uma Primary key em uma tabela?](https://pt.stackoverflow.com/questions/214088/%C3%89-poss%C3%ADvel-ter-mais-de-uma-primary-key-em-uma-tabela/214091#214091)
Answer: Isso é restrição do banco de dados. O Hibernate não pode tratar essa restrição. O que você pode fazer é retirar a restrição (cuidado com essa opção) ou verificar se já existe este campo restrito antes de um insert ou update

Campo Unique Update com Hibernate


Implicit differentiation of trigonometric function $x\tan(y)=6-x^2$

Question: I am asked to find the equation of the tangent and the normal to the curve $$x\tan(y)=6-x^2$$ at the point $(2,\pi/4)$.
Rearrange to $$x\tan(y)+x^2-6=0$$
By product rule $$\frac{d}{dy}( x\tan(y)) = \tan(y)$$ so $$\frac{d}{dx} x\tan(y)+x^2-6 = \tan(y)-2x$$
At $(2,\pi/4)$ $$\frac {dy}{dx}=\tan(\pi/4)-2\cdot2
\tan(\pi/4)=1$$ therefore at $(2,\pi/4)$, $\frac{dy}{dx}=5.$
However, the book answer for this question is that the equation of the tangent is
$4y+5x=\pi+10$ and that for normal is $20y-16x=5\pi-32.$
The book answer means that at $(2,\pi/4)$, $dy/dx=-5/4$, not $5$.
Where have I gone wrong?
Answer: You haven't differentiated the equation of curve properly. We are differentiating with respect to x. So, $$\frac{d}{dx}\left( x\tan(y)\right)+\frac{d}{dx}(x^2)+\frac{d}{dx}(-6)=0$$ Hence, by applying product rule, $$\left(x\frac{d}{dx}(\tan(y))+\tan(y)\frac{d}{dx}(x)\right)+2x+0=0$$ $$x\sec^2(y)\frac{dy}{dx}+\tan(y)+2x=0$$
Now, put  $x=2$, and $y=\pi/4$. You will get the required answer.


d-regular bipartite graph

Question: I'm looking to prove that any $d$-regular bipartite graph satisfies the HALL condition and contains a perfect matching.
I'm having trouble seeing why, if $G=(V,W,E)$, for any $H \subseteq V$, $|H|\leqslant |N(H)|$.
Would appreciate an answer!
Edit: For degree $\geqslant 1$ obviously.
Answer: Let $H \subset X$ in an $d$-regular $X,Y$-bigraph $G$.  Let $N(H)$ denote the neighbors of the vertices in $H$.  There are $d\lvert H\rvert$ edges between $H$ and $N(H)$.
If $\lvert N(H)\rvert < \lvert H\rvert$ then $d\lvert N(H)\lvert < d\lvert H\rvert$, so the number of edges between $H$ and $N(H)$ exceeds the number of edges incident with any vertex of $N(H)$, a contradiction.

d-regular bipartite graph


How to change windows phone APP language during runtime?

Question: I followed this example to build a multilingual app: How to: Build a Localized Application for Windows Phone.
I successfully bound the resource data to text like this:
<TextBlock x:Name="ApplicationTitle" Text="{Binding Path=MultiLangResources.Mainpage_Welcome, Source={StaticResource MultiLang}}"/>

And I tried to change the Thread.CurrentThread.CurrentUICulture and I can output correct key with code:
ApplicationTitle.Text = LangResource.Mainpage_Welcome;

However, the bound text never update.
How to make the bound text update like ordinary bind?
Is there anyone could help me with this problem?
I also tried this with no luck.
public class MultiLang : INotifyPropertyChanged
{
    public MultiLang()
    {
    }

    private static MLTest.LangResource multiLangResources = new GigapodV2.LangResource();

    public MLTest.LangResource MultiLangResources
    {
        get { return multiLangResources; }
        set
        {
            if (value != multiLangResources)
            {
                multiLangResources = value;
                NotifyPropertyChanged("MultiLangResources");
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(string property)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    }
}

Answer: It can be easily done:
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("ca-ES");
Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("ca-ES");

The main problem is that the text on all the pages that are ALREADY loaded (for example the main page, if you put the language choose there), will need to be "manually refreshed".
But this can be easily done programatically:
this.btnChangeLanguage.Content = AppResources.Txt_Aceptar;

Answer: The LangResource class isn't observable by itself, and thus any bound properties from it won't be observed. And also, the phone won't notify all properties that's related to the CurrentCulture just because you change it on-the-fly.
Language change in that fashion would otherwise require a reboot of your app. But I would advice you to be careful with this, as the OS itself allows language swapping, meaning you need to have a really good reason for your app to allow it in itself.
The solution is to create a wrapper class, that notifies all properties that they been updated, when you change the CurrentCulture. Using Simon's NotifyPropertyWeaver's [DependsOn] attribute could probably make this very easy.


Leverage point in a dataset

Question: Given a data set $(x_1, ... , x_n)$, is there a condition which makes a point $x_i$ leverage? That is, how can we point ( except for just considering it 'too far from the other points and probably being an error estimate' ) ? Is there an algorithm for that?
Answer: I presume you are talking about linear regression. There is a rule-of-thumb measure for leverage. It is based on the diagonal values of the hat matrix $H=X(X^TX)^{-1}X^T$ Point i is considered leverage point if $h_{ii} > 2 \frac{k}{N}$, where k is the number of parameters including the intercept and N is the number of observations. If the data set is small you might want to use 3 instead of 2. See John Fox An R Companion to Applied Regression
Comment: Yes, I was talking about this. Thank you!

Leverage point in a dataset


Probability, making a selection of 5 people from 10, with two married couples with restrictions

Question:
10 people. must make a committee of 5 people

So the restrictions are

1) Mr and Mrs Q can't be separated
2) Mr and Mrs P can't be in the same committee.

So how many possible committees can you form.
4 CASES:
CASE 1: No P AND no Q's
$$ \binom{6}{5}=6 $$
CASE 2: Q's AND NO P
$$ \binom{6}{3} = 20 $$
CASE 3: 1P and Q's
$$ \binom{6}{2} * 2=30$$
CASE 4: 1P and NO Q's
$$ \binom{6}{4}*2=30 $$
86 possible committees
Am I doing this correctly?
Comment: The second restriction is phrased in a strange way. "Mr. and Mrs. P can't be on the same committee" suggests that there will be multiple committees, and that Mr. and Mrs. P must be on different committees (if both are on a committee). I wonder why it wasn't phrased as "Mr. and Mrs. P can't both be on the committee."
Comment: Sorry thats just my writing. The full question is : There are two married couples amongst the group of ten: Mr and Mrs P, and
Mr and Mrs Q. When a committee of ve is formed, since Mr and Mrs P argue all the time, at
most one of these two can be chosen, whereas Mr and Mrs Q are inseparable, so a committee
must either contain both of Mr and Mrs Q or else neither of them.
With these constraints, now how many distinct ve-person committees can be formed? @CameronBuie
Comment: Gotcha. In that case, I'll upvote your question and Ross's answer, since they're right on track.
Answer: The title on case 1 should be no P's or Q's.  Some of the others may be married, but you don't care.  The logic is fine.
Comment: Ok thanks. But is my maths correct?
Comment: Looks good to me.
Comment: Thank you Ross, very helpful


Add callback to existing migrate field mapping

Question: I have a use case where I want to use the callbacks functionality for the body field in a D6->D7 migration using migrate and migrate_d2d modules. However, according to the above-referenced docs page, this is done when you are adding a new field mapping:
<code>$this->addFieldMapping('destination_field', 'source_field')->callbacks('my_callback');
</code>
not adding to an existing mapping. How can I add a callback to an existing mapping? Do I have to remove and then re-add the mapping, or is there another way?
Answer: With some debugging and looking at code, it turned out to be pretty easy. All of the mappings are MigrateFieldMapping objects in $this->codedFieldMappings, so it's just a matter of getting a reference to that object and calling the callbacks() method. For example, to add a callback to the body field, you would use:
<code>$this->codedFieldMappings['body']->callbacks('my_callback');
</code>


On the definition of totally unimodular matrix

Question: I'm a bit confused about the definition of a totally unimodular matrix, since my lecture notes states that this matrix is not totally unimodular:
$$\begin{pmatrix}
1 && 0 \\ 1 && -1 \\ -2 && 1
\end{pmatrix}$$
I don't see a submatrix which doesn't have a determinant in $\lbrace 0,\pm1 \rbrace$. What am I doing wrong?
Answer: From Schrijver's Theory of Linear and Integer Programming (1998):

In Chapters 19 to 21 we consider totally unimodular matrices, which are matrices with all subdeterminants equal to $1$, $-1$, or $0$ (in particular, each entry is $1$, $-1$, or $0$). Totally unimodular matrices yield a prime class of linear programming problems with integral optimum solutions.

Note that $-2 \notin \{-1,0,1\}$.
Comment: Ah, the wiki page didn't seem to mention this. Maybe I overlooked smt, or we're just dealing with different definitions. Thanks anyway, I guess your answer is correct, since Schrijver's book indeed is pensum for this class. Thanks!


Simplifying $\cos(x-360^\circ)$

Question:
If $\cos(360^\circ + x)$ simplifies to $\cos x$, then how do I simplify $\cos(x - 360^\circ)$?

I have tried different online checks, and I cannot find a definitive answer.
Answer: Since you know $$\cos (360^\circ+x)=\cos(x)$$
Then,
$$\cos (x-360^\circ)= \cos (360^\circ+x-360^\circ)=\cos(x)$$
Answer: Since $\cos$ is periodic with period $2\pi=360°$, $\forall k\in \mathbb{Z}$
$$\cos (x\pm k\cdot360°)=\cos x$$

Simplifying $\cos(x-360^\circ)$


How to play this B on Oboe

Question:
As you can see, there is a B flat (or A sharp), but I am asking about the same note, B without flat (or A without sharp)
What's the fingering on Oboe?
Note
I think that I can play it the same as normal B but with the octave key. In other words, with the left index finger and the octave key, but I am not sure.
Answer: That is correct- it's the same fingering as an octave lower, with the octave key added. But there are lots of fingering charts online.  Here's one: http://www.oboesforidgets.com/fingerings/oboechart.pdf
Comment: The note is played with the **second** octave key unless the oboe is full automatic.

How to play this B on Oboe


How can I check if a command-line argument is equal to '<' from input in Perl?

Question: #!/usr/bin/perl -w

foreach $arg (@ARGV) {
        if ($arg eq "--version") {
                print "$0: version 0.1\n";
                exit(0);
        } elsif ($arg =~ /-[0-9]+/) {
                $n = $arg;
                $n =~ s/-//g;
        } elsif ($arg eq <){
                print "in";
        } else {
                push @files, $arg;
        }
}

How can I check if $arg is equal to < from input?
thanks in advance.
Answer: You correctly used quotes for the string --version. You should use quotes for <, too.
Note that you are checking command line arguments, not input. Also note that on *nix systems, if you call the script like
myscript.pl -12 < input

the < input part is processed by the shell and doesn't appear in the argument list.
See also Getopt::Long.
Comment: @hahahakebab: Why do you need it? You can read the contents of the redirected file from standard input.
Comment: @hahahakebab, There's no way to differentiate `bash -c 'myscript.pl 12 <input'` (`<` used in command) from `bash -c 'myscript.pl 12' <input` (`<` not used in command). For starters, you can't even tell if the program was launched from a shell command or not.
Answer: @hahahakebab: What @choroba said is exactly correct. When you are passing < as the command line argument put that in double quote "<" so that it takes as input to the program and modified code as below
    foreach my $arg (@ARGV) {
            if ($arg eq "--version") {
                    print "$0: version 0.1\n";
                    exit(0);
            } elsif ($arg =~ /-[0-9]+/) {
                    $n = $arg;
                    $n =~ s/-//g;
            } elsif ($arg eq "<"){
                    print "in";
            } else {
                    push @files, $arg;
            }
    }

Answer: If < was used in the command line, then standard input is coming from a file.
If < was not used in the command line (and | is not used to specify input from the output stream of another process), then standard input is from a terminal.
You can distinguish between these two cases in Perl by checking -t STDIN
if (-t STDIN) {
    print "input is from terminal\n";
} else {
    print "input is from a file/pipe\n";
}


How to know if a sprite touched the particle emitter

Question: i have a particle emitter of fire and i have an object. I want to know when does the object touches the fire. Any ideas?
Thanks in advance.
Comment: you mean individual particles? that's not possible
Comment: @LearnCocos2D i mean the all particles, not individually. let's say i am a particles named "fire" and a sprite named "player", i want to know if player touched fire (and of this particles, not matter.) thanks
Comment: and one of his particle*
Comment: then calculateaccumulatedframe may work
Answer: calculateAccumulatedFrame is a method that returns the largest rectangle that includes all of the SKNodes children. This should be able to solve your problem
BUT It might be better creating your own polygon which represents the area where all the particles are usually held and doing a test with that, It gives you more accuracy and gives u more control


Nginx com Erro de conexão SSL

Question: Criei um certificado SSL para testar no servidor e configurei no Nginx da seguinte forma:
# HTTPS server
#
server {
    listen 443;
    server_name kriaki.com.br;

    root /home/ubuntu/public_kriaki;
    index index.html index.htm;

    ssl on;
    ssl_certificate /etc/nginx/ssl/kriaki.com.br.cert;
    ssl_certificate_key /etc/nginx/ssl/kriaki.com.br.key;
#
#   ssl_session_timeout 5m;
#
    ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2;
#   ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv3:+EXP;
#   ssl_prefer_server_ciphers on;
#
#   location / {
#       try_files $uri $uri/ =404;
#   }
}

Salvei e utilizei o seguinte comando para checar se esta tudo ok:
sudo nginx -t -c /etc/nginx/nginx.conf

E tudo ok. Reiniciei o Nginx, e fui acessar a url com https:// e o navegador retorna o erro: Código de erro: ERR_SSL_PROTOCOL_ERROR
Será que o erro está no certificado? Mas fiz ele como sempre faço:
sudo openssl req -new -newkey rsa:2048 -nodes -keyout kriaki.com.br.key -out kriaki.com.br.csr
sudo openssl x509 -in kriaki.com.br.csr -out kriaki.com.br.cert -req -signkey kriaki.com.br.key -days 30

O que poderia ser?
Comment: Resolvi aqui, no arquivo de configuração `default` eu tinha habilitado outro certificado e por algum motivo deu conflito. Tenho outros dominios no servidor que quando acesso eles em `https://` eles tentam acessar o certificado que pus ali em cima que é especifico daquele dominio. Deixei `server_name`  claro para `kriaki.com.br`, porque os outros dominios estão carregando também o mesmo certificado de kriaki.com.br?
Comment: Gilson, responda sua própria pergunta, e descreva em detalhes como conseguiu. Depois de dois dias marque ela como certo
Answer: Como eu estava testanto configurações no nginx, no arquivo de configuração default que fica em /etc/nginx/sites-available/default já tinha uma configuração para ssl para outro dominio.   Provavelmente com os dois juntos e a caracteristica de ssl de um ip por ssl, eles estavam dando esses erro de ssl ao acessar. Somente deixei um e funciona normal. Mas como eu estava necessitando somente de um dominio com ssl deixei assim mesmo.
Answer: Você ainda pode criar um bloco de server para cada domínio com certificado que você tiver...
Você tem necessidade de declarar
ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv3:+EXP; ?
Isso pode causar erros com clientes que usam outros tipos de ciphers.
Comment: Na verdade essa linha esta ali, mas não está ativa, note que tem um `#` na frente.
Comment: Voce citou `bloco de server`, mas isso se eu tiver um ip dedicado para cada certificado correto?

Nginx com Erro de conexão SSL


How can differential entropy be negative?

Question: Entropy is defined as $$H(x) = E_{x\sim p(x)}[ - \log p(x)]$$
and $- \log p(x) \geq 0$ so it makes sense that the expectation is always non-negative, here is a proof.
However, Wikipedia says the entropy of a normal distribution is $\tfrac{1}{2} \ln(e2\pi\sigma^2 $), which means that the entropy can be negative for some values e.g. $\sigma = 0.01$ but how can be this be the case and how can it be interpreted?
Comment: The differential entropy in not the (traditional / Shannon) entropy. https://math.stackexchange.com/questions/2552895/uniformly-random-number-on-0-1-has-zero-entropy/2553036#2553036 https://math.stackexchange.com/questions/2880612/comparing-differential-entropy-of-normal-distribution-to-shannon-entropy/2880947#2880947 https://math.stackexchange.com/questions/1398438/differential-entropy/1398471#1398471
Answer: You're either confusing $p(x)$ with probability $P(E)$, the probability mass function $P(x)$ or the cumulative distribution function $F(x)$ which are all constrained to be $\in [0, 1]$.
However, $p(x)$ denotes the probability density function (pdf), which can take any non-negative value.
Thus, $-\log (p(x))$ can indeed be
a negative quantity.
Answer: $-\ln p(x)$ is not necessary nonnegative.
For example, if $p(x)$ is a density of $N(0, 0.01)$ then $p(x) \ge x$ for some $x$.
Answer: As your second link says, the entropy of a continuous distribution with density $f$ can be negative, as $f$ may be greater than $1$ (though $\int_\mathbb{R} f$ must still be $1$) and thus $-\log f$ may be negative. The continuous case is a bit less well-behaved than the discrete one in general; it's also not invariant under a change of variables (though there is a reasonable formula for a constant rescaling factor).


Why does python only run a single test_method in my TestCase?

Question: I have a set of unit tests that look basically like this:
import unittest

class MyTestCase(unittest.TestCase):

    def test_one(self):
        self.assertEqual(1,1)

    def test_two(self):
        self.assertEqual(2,2)

if __name__ == '__main__':
    unittest.main()

When I run the tests, I would expect to see results from both test_methods (test_one and test_two), but I only get results for one:
$ python -m unittest -v tests.test_dummy
test_one (tests.test_dummy.MyTestCase) ... ok

----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

What's going on here?
Comment: Which python version are you using?
Comment: Python 2.7.6

(This text added to make my comment long enough.)
Comment: Cannot replicate, works in pycharm and when run from the command line
Comment: 2.7.3 shows two tests
Comment: This is mystifying to me. I get the same result on 2.6. I'm running Mac OS X 10.10.4 with python installed through anaconda.
Answer: Oh, this is mortifying.
It was an indentation problem. The test file had a combination of tabs and spaces, so the second test wasn't being identified.
I copied the invisible glitch from my real code, to the simplified MyTestCase class I used to replicate the error. But stackoverflow stripped out the tabs, so no one else was able to replicate.
Here's the bug that was killing my code. Tabs are shown with hyphens: ----
import unittest

class MyTestCase(unittest.TestCase):

    def test_one(self):
        self.assertEqual(1,1)

----def test_two(self):
--------self.assertEqual(2,2)

if __name__ == '__main__':
    unittest.main()

Comment: You should get a proper text editor (like Notepad++, or Sublime), they deal with tab/space mixed code. It's the only sane option.
Comment: I'm using Sublime 2, which is partly why I was so surprised this happened.
Comment: That's really weird. Did you change any settings? Is your file saved as *.py*?


Estender classes com construtor privado

Question: Porque não posso estender classes com construtor privado?
Consirando as classes A:
public class A {
    private A(){}
    public static void limao(){}
}

e B:
public class B extends A {
    private B(){}
    public static void banana(){}
}

Por que B não pode estender A?
There is no default constructor available my.package.name.A
Meu objetivo é ter algumas classes que contém apenas membros estáticos e gostaria de garantir que elas sejam utilizadas da maneira correta (sem instâncias) mas que também herdam de outras classes por terem métodos em comum. Atualmente faço isso em C# atráves de classes estáticas mas não consigo aplicar algo parecido no meu projeto Android.
Answer: Se todos os métodos são estáticos, para que herdar da classe? Você pode simplesmente, na classe B, importar todos os métodos de A de modo que você continue podendo chamá-los sem precisar ficar usando A.metodo.
B.java
import static meu.pacote.A.*;

public class B {
    private B(){}
    public static void banana(){
        limao();
    }
}

Se for mesmo necessário herdar, use um construtor protected como sugerido por @Cigano Morrison Mendez. Ou, se as classes estiverem no mesmo pacote, um "package protected" (i.e. sem modificador) - pois isso evita que qualquer classe fora do pacote herde de A. Você pode ainda marcá-la como abstract (impedindo a instanciação) ou talvez lançar uma exceção no construtor (impedindo a instanciação de subclasses), se achar necessário tornar seu código "à prova de idiotas". Fica a seu critério...
Answer: Porque isto vai contra a definição formal de proteção de métodos da teoria de orientação a objetos clássica. Se um membro é private, ele não pode ser acessado por nenhuma outra classe que não a própria classe.
Para este caso, use protected para que o construtor possa ser acessível pelas classes que extendem sua classe A.
Comment: Até onde eu sei o proteced é modificador de acesso que deixa visível a classe e/ou atributo para todas as outras classes e subclasses QUE PERTENCE AO MESMO PACOTE. Edit: Fonte http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
Comment: Neste caso não vale a pena eu mudar a resposta, porque a questão do pacote é própria do Java, e expliquei falando da teoria geral da orientação a objetos.
Answer: Porque o construtor foi declarado como privado em A e o B não consegue acessar membros privados, apenas public ou protected. Quando você declara um construtor como privado nenhum outra classe vai enxerga-lo sendo impossível herdar da mesma ou instancia-la em outra classe.

Estender classes com construtor privado


Alter specifically coupon validation minimum amount filter hook in Woocommerce

Question: I want to Alter function validate_coupon_minimum_amount() adding a condition that if a user use coupon "refresh18", check to see if subtotal in cart for a product category is greater than the coupon's minimum amount.
How could I do that?
Here is my code below that doesn't work:
function check_minimum_parts_amount_in_cart($coupon) {

    $cart_parts_subtotal = 0;

    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
      $_product   = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
      $product_id = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key );

    $terms = get_the_terms( $product_id, 'product_cat' );
    if ( $_product && $_product->exists() && $cart_item['quantity'] > 0 && apply_filters( 'woocommerce_cart_item_visible', true, $cart_item, $cart_item_key ) && has_term( 'ice-shaving-parts', 'product_cat', $product_id ) ) {
        //echo '
' . print_r($cart_item , 1) . '
';
        //echo $cart_item['quantity'];
        $cart_parts_subtotal = $cart_parts_subtotal + ( $_product->get_price() * $cart_item['quantity'] );
     }
    }

    $subtotal = wc_remove_number_precision( $this->get_object_subtotal() );
    if( $coupon->get_name() == 'refresh2018' ){
      if( $coupon->get_minimum_amount() > 0 && apply_filters( 'woocommerce_coupon_validate_minimum_amount', $coupon->get_minimum_amount() > $cart_parts_subtotal, $coupon, $cart_parts_subtotal )){
        /* translators: %s: coupon minimum amount */
        throw new Exception( sprintf( __( 'The minimum spend for this coupon is %s.', 'woocommerce' ), wc_price( $coupon->get_minimum_amount() ) ), 108 );
      }else{
        return true;
      }
    }else{
      if ( $coupon->get_minimum_amount() > 0 && apply_filters( 'woocommerce_coupon_validate_minimum_amount', $coupon->get_minimum_amount() > $subtotal, $coupon, $subtotal )) {
        /* translators: %s: coupon minimum amount */
        throw new Exception( sprintf( __( 'The minimum spend for this coupon is %s.', 'woocommerce' ), wc_price( $coupon->get_minimum_amount() ) ), 108 );
      }else{
        return true;
      }
    }
}
add_filter('validate_coupon_minimum_amount', 'check_minimum_parts_amount_in_cart');

Answer: Updated:
Since Woocommerce 3.2+ use instead woocommerce_coupon_validate_minimum_amount filter hook… So you should try this revisited code (Where you will have to set your product category):
add_filter( 'woocommerce_coupon_validate_minimum_amount', 'custom_check_minimum_amount_in_cart', 10, 3 );
function custom_check_minimum_amount_in_cart( $valid, $coupon, $subtotal ) {
    // HERE below your settings (Coupon code and product category)
    $coupon_code = 'refresh18';
    $product_category = 'clothing'; // <== To be replaced by your targeted product category

    $cat_subtotal = 0;

    foreach ( WC()->cart->get_cart() as $cart_item ){
        if( has_term( $product_category, 'product_cat', $cart_item['product_id'] ) )
            $cat_subtotal += $cart_item['line_subtotal'];
    }

    if( $coupon->get_code() == $coupon_code && $coupon->get_minimum_amount() > $cat_subtotal ){
        throw new Exception( sprintf( __( 'The minimum spend for this coupon is %s.', 'woocommerce' ), wc_price( $coupon->get_minimum_amount() ) ), 108 );
    }
    return $valid;
}

This code goes on function.php file of your active child theme (or theme). It should work.

Note: For everybody, remember to set in this function the coupon code in lowercase.
Comment: Thank you so much for your reply. The `$coupon->get_name()` throwing this error "Call to undefined method WC_Coupon::get_name()" so I changed it to get_code. But it still not working with `$coupon->get_minimum_amount() > $cat_subtotal`. When I have total more than minimum but not in category "clothing", the coupon still work. Any ideas?


How to select data from array when having only 1 piece of array-data (own data class)

Question: Hi and all the best from Germany,
having a problem with an array.
I have an array with 2 sets of data (data 1 (a, b, c), data 2 (d, e, f)).
Now I want to extract "d" and "e", when having the Information "f".
My code:
public class MapsActivity extends FragmentActivity {

[...]
class Data {
    public Data(int category,
                String quality,
                String title,
                String snippet,
                float lng,
                float lat,
                String homepage,
                String phonenumber,
                float distance,
                float duration

               )
    {
        super();
        this.category = category;
        this.quality = quality;
        this.title = title;
        this.snippet = snippet;
        this.lng = (float)lng;
        this.lat = (float)lat;
        this.homepage = homepage;
        this.phonenumber = phonenumber;
        this.distance = (float) distance;
        this.duration = (float) duration;

    }
    int category;
    String quality;
    String title;
    String snippet;
    float lng;
    float lat;
    String homepage;
    String phonenumber;
    float distance;
    float duration;

}

Data[] data = {
        new Data(1,
                "***",
                "title1",
                "snippet1",
                0.0f,
                0.0f,
                "http://www.something.something",
                "tel:+00000000",
                0,0),

        new Data(1,
                "***",
                "title2",
                "snippet2",
                0.0f,
                0.0f,
                "http://www.something.something",
                "tel:+00000000",
                0,0),
/**
        new Data(1, -79.402206f,43.657688f, "College St",
                "Lots of discount computer stores if you forgot a cable or need to buy hardware."),

        new Data(1, -79.390381f,43.659878f, "Queens Park Subway",
                "Quickest way to the north-south (Yonge-University-Spadina) subway/metro line"),

        new Data(1, -79.403732f,43.666801f, "Spadina Subway",
                "Quickest way to the east-west (Bloor-Danforth) subway/metro line"),

        new Data(1, -79.399696f,43.667873f, "St George Subway back door",
                "Token-only admittance, else use Spadina or Bedford entrances!"),

        new Data(1, -79.384163f,43.655083f, "Eaton Centre (megamall)",
                "One of the largest indoor shopping centres in eastern Canada. Runs from Dundas to Queen."),
 */
};

@Override
protected void onCreate(Bundle savedInstanceState) {
[...]

    // 8. when the infowindow ist clicked
    myMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
                @Override
                public void onInfoWindowClick(Marker marker) {
                    String titleOfClickedMarker = marker.getTitle();

                    Toast.makeText(getApplicationContext(),titleOfClickedMarker, Toast.LENGTH_SHORT).show();

// HERE I NEED HELP: I now have the title (for example title 1), and now the Point: HOW DO I GET THE OTHER INFORMATION OF THE "TITLE1" data set (e.g. snippet 1, etc.).

                }
            }
    );

}

I appreciate every help, even if short.
Comment: Please tag your question with the programming language used.
Answer: Instead of storing all your Data instances in an array, you can consider storing them in a HashMap, assuming you are working with Java. So essentially, your data instance now becomes:
class Data{
  /* etc... */
  public String getText(){
    return this.title;
  }
}

Data data1 = new Data(1, "***", "title1", "snippet1",
                      0.0f, 0.0f, "http://www.something.something",
                      "tel:+00000000", 0,0);

Data data2 = new Data(1, "***", "title2", "snippet2",
                      0.0f, 0.0f, "http://www.something.something",
                      "tel:+00000000",
                      0,0);
/* etc... */

HashMap<String, Data> hashMap = new HashMap<String, Data>();
for(int i = 0; i < dataCount; i++) // add data instances in a loop. Define your own dataCount
  hashMap.add(data.getTitle(), data);

/* etc... */

myMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
  @Override
  public void onInfoWindowClick(Marker marker) {
    String titleOfClickedMarker = marker.getTitle();
    Data data = hashMap.get(titleOfClickedMarker);
    /* etc.. */
 }

Hope this helps.
Comment: There are three addional questions: (1) How can "data1", "data2", etc. be stored in a HashMap automatically (e.g. via for-Loop). (2) What does "data1.getTitle()" mean? Is this meant to have the "title1" twice, at first place and on third? (3) The "data = hashmap.get(titleOfClickedMarker)": What exactly does this produce: the set of the data, e.g. data1 (with "1", "***", "title1", etc. in it)? Appriciate your comment.
Comment: I have updated my answer to include your new questions (1) and (2). I am not sure what your question (3) meant.


Erlang's equivalent of Haskell's as-patterns

Question: How can I write in Erlang an equivalent of this Haskell snippet?
name@(x:xs)
Answer: You can do it with syntax like Name=[X|Xs]. An example usage is
headlist([H|T]=L) -> io:format("List (~p) with head ~p ~n",[L,H]).

Comment: Note that it's often more readable to put the more specific pattern to the left and the variable to the right, as in headlist([H|T]=L) -> .... This way, multiple clauses align better, and you focus first on what is being matched rather than on the extra variable.
Comment: I agree with @RichardC but just want to say that both are legal and fully equivalent with each other.
Comment: @RichardC I don't code much in erlang so I am not very familiar about the coding practices. Thanks for pointing that out.


linux conversion of caf file with iLBC codec 2 wav

Question: Used http://www.ilbcfreeware.org/software.html - I only get static from the files that ilbc_test.exe creates.
Does anyone have other suggestions? sox doesn't seem to be able to convert it as far as I can tell.
Comment: Better to follow a good writing skills and make some explanation of your problem.
Answer: This was solved by using the software on the url above.  Also we needed to remove the caf headers from the ilbc file.


How to find the percent variation in Y is explained by X?

Question: I know that the r^2 value for the data is 0.9832. Is there a way to use that value to find the percent variation in Y is explained by X? Or do I need to use the data given to me?
Comment: That's exactly what $r^2$ means. (Convert to a percentage if you like.)
Comment: @DanielR.Collins Doesn't  r^2 represent X by Y?
Comment: Perhaps you left out some words or something? Your comment isn't coherent.
Answer: $r^2*100$ is the percentage of variance explained by $X$.
When you regress $Y$ on $X$ you get $\hat{Y}=a+r\frac{s_y}{s_x}X$
And $Var(\hat{Y})=r^2Var(Y)$ from the above equation.
So $\frac{Var(\hat{Y})}{Var(Y)}*100=r^2*100$ is the percentage of variance explained by x.


D7: Get terms from node and display other nodes with same term in block?

Question: I have a node that has terms:
Artist1
And need a block to show all the other nodes that has Artist1 as a term
I tried this solution Display the title of related nodes from taxonomy in block
I set it to "Provide a default argument", and configured that to use the nid of the node being viewed... and nothing
this seems simple but been working at it for hours now.
Answer: Try this module - https://drupal.org/project/views_arguments_extras
This allows you to select a field from the current node as a contextual filter.
Enable this module.
Create a  new view, block display, and the chose the relevant field as the contextual filter.
Configure the view as per your requirement and show the block on your node page. It should work.
Answer: You need a block view that accepts a term (from your node) as argument. I'm not sure how you'd best pass the term as argument to the view block but here's a possible solution: Passing Arguments to block in 7.x Views
Answer: This answer works in Views version 2 or higher. First you need to install Views attach ( http://drupal.org/project/views_attach ). Please read about Views attach before proceeding further. Views attach is best explained by this video http://mustardseedmedia.com/podcast/episode37
Now we get to Views attach. Please enable the views attach module before proceeding. Essentially Views attach attaches a view at the end of the node. In our case our view will be a listing of other articles with the same term.
We will essentially need to "pass" the taxonomy term of the node to the view. Let the name of your Vocabulary be called MyVocab.
Steps to make the view.

Lets call the view display_other_articles_with_same_taxonomy.
Add a display of type Node Content (available after enabling Views attach). This is a display just like block and page displays but with special ability of attaching itself to the node.

Make the following settings in the Node Content Display
Node content settings
Node types: [select the content types you are interested in seeing the list of nodes with same taxonomy term]
Build modes: Teaser, Full node
Arguments: token
Show title: No

You should select Use tokens from the node the view is attached to under Arguments. Let the token be [term-id] This is the "ID of top taxonomy term". This is very important!! Essentially you are going to be passing the taxonomy term of the node from the MyVocab (See http://groups.drupal.org/node/11788#comment-38332). If it has the lowest weight, the taxonomy vocabulary will be the first vocabulary in the taxonomy section of your node edit form. Add an argument Taxonomy: Term Id.
Add the fields you are interested in e.g. Node: Title. Make sure the Node: Title is made into a hyperlink by ticking Link this field to its Node
So what this view is going to do is:

Take the taxonomy term from the MyVocab vocabulary in the Node that is currently being viewed
Pass that as argument to the view display_other_articles_with_same_taxonomy
List all the nodes that have the same taxonomy term as the node being displayed.

Thats it!
If you're using Views 3 (currently at alpha3 at the time of writing) and you want a block (right now the articles have same taxonomy term come at the end of node body) you can do it in the following fashion:

Forget about views attach... its not required
Add a block view. It should contain the same argument, fields and filters as the instructions above for the Node Content display.
You need to modify the settings for the argument Taxononomy: Term Id just slightly: Under Action to take if argument is not present: choose [x] Provide Default Argument. Choose [x] Taxonomy Term ID from URL. Now make sure [] Load default argument from term page is unselected and [x] Load default argument from node page, thats good for related taxonomy blocks. Also [x]Limit terms by vocabulary and choose the Series vocabulary.
Make sure you name the block and put it in the appropriate region.

Note: This answer is subset of the answer I provided at https://stackoverflow.com/questions/3895213/how-to-just-show-nodequeue-block-on-included-nodes/3909670#3909670 In that scenario the requirement was that the related articles are explicitly selected and listed in a particular order. Its a little more complex and uses Nodequeues which we don't need here at all.
Answer: Not advisable, but as an option you can use php codes inside the views contextual filters, code something like below.
Assuming this view block has to be placed with a node, so taking arg(1) as nid.
  $node = node_load(arg(1));
  if($node && isset($node->your_taxonomy_field_name[LANGUAGE_NONE])) {
      foreach($node->your_taxonomy_field_name[LANGUAGE_NONE] as $term) {
          $terms[] = $term['tid'];
      }
      return implode('+',$terms);
  }
  else {
      return;
  }