.split python word count

Question: I need to count the words in a sentence. For example, "I walk my dog." Would be 4 words, but "I walk my 3 dogs" would only be 4 words because numbers are not words. The code can only count alphabetic words. I understand how to count words by simply using the following:
len(string.split)

but this doesn't account for numbers. Is there a simply way (for a beginner) to account for numbers, symbols, etc? thank you.
Comment: What about "I walk my Beagle-Harrier"?  Is that a possible sentence of four words?  (I ask because it will break some `isalpha()` approaches.)
Comment: I would submit that numbers in a sentence *are* words.
Comment: What if I spelled `4` as `four` instead? The meaning of the sentence has not changed! `4` is a word too in your sentence.
Answer: totalWords = sum(1 for word in line.split() if word.isalpha())

You can use split function on the line to split it based on spaces. And then check if each word has only alphabets using isalpha function. If it is true, then include 1. Sum all of them at the end.
Comment: if there anyway of doing this without using .isalpha that you can think of? Somehow make a list of your string or something?
Comment: @jerry2144 Do you consider punctutation marks as well as the word separators?
Comment: `if not word.isdigit()` would allow `"don't"` and `'back-to-back'` to be counted as words.  Of course, `'3rd'` and `'3.145'` would count as words.  Perhaps `if not word[0].isdigit()` would be better.  But you would still have a problem with `"'3"` in `"'3 cats are missing,' she said."`  Least problematic would be `if any(c.isalpha() for c in word)`.
Comment: @StevenRumbalski Yup. I thought of all the cases for which this could fail. But its not very clear what does he exactly expect. :(
Answer: Here's another option:
import re

lines = [
    'I walk by dog',
    'I walk my 3 dogs',
    'I walk my Beagle-Harrier' # DSM's example
]

for line in lines:
    words = re.findall('[a-z-]+', line, flags=re.I)
    print line, '->', len(words), words

# I walk by dog -> 4 ['I', 'walk', 'by', 'dog']
# I walk my 3 dogs -> 4 ['I', 'walk', 'my', 'dogs']
# I walk my Beagle-Harrier -> 4 ['I', 'walk', 'my', 'Beagle-Harrier']

Answer: You can use .isalpha() on strings.
len([word for word in sentence.split() if word.isalpha()])

Answer: If you don't want to use .isalpha
sum(not word.isdigit() for word in line.split())

This will return True for each word that is not a number, and False for each word that is a number.  This code takes advantage of the fact that in python, True == 1 and False == 0, so you will get the number of non-number words.

If you are uncomfortable with using the int-ness of bools, you can make it explicit to the reader of your code by adding the int function (this is 100% not needed, but can make the code clearer if you like it that way)
sum(int(not word.isdigit()) for word in line.split())

Comment: If your requirements are more than simply not numbers, let me know and I can modify this to your needs.  I am basing this code on your example.  What if you had something like "I <3 U"?  "<3" is not counted as a digit.
Answer: Since, due to comments it looks like he wants something that doesn't use .isalpha, we could run this in a try/except.
count = 0
for word in line.split():
    try:
        int(word)
    except ValueError:
        count += 1

I know it's not pretty, but it handles it correctly.
Comment: Or perhaps `float(word)` to get rid of floating points as well.  Your try-except has the similar behavior to just checking `not word.isdigit()`.
Comment: I assumed that since the op didn't want .isalpha, that he wouldn't want any of he others of that style.

.split python word count


'Open in a new page'. Should a text link or a button be used to show this behaviour?

Question: I'm designing an interface which includes 8 pieces of content underneath the content is an option for the user to 'see more'.
This 'see more' component is a requirement for mobile and desktop. Slightly more users are currently viewing the website on mobile.
In regards to the design of the 'see more', is it better to use a text link or a button? (I've also been told it's a business requirement to use one design pattern for both mobile and desktop)
Comment: If possible, could you show a screenshot of how it is now? or even a diagram would do fine.
Comment: Both options are acceptable, but buttons will be more inviting and noticeable. If you want to encourage users to click, you should definitely use a button.
Comment: Without prior warning, if a text-link opened in a new page I'd be somewhat surprised (and possibly a little irritated). If a button did that, I'd be less surprised (and probably not annoyed). If you indicate beforehand that a new page will open, then either can be used (though I'd probably prefer a button).
Answer: Keeping Affordance in mind, please choose a button as most of your users are using Mobiles -


Is it odd to have search results displayed in a way that is inconsistent with the rest of an app?

Question: I've spent a few days thinking about how to layout my mobile app's interface and I think I've found a way that makes sense to me. I just need some advice to check that I'm not veering too far from best practices.
My app has the following hierarchy:

Timers > Tasks

Each timer can have a static list of one to many tasks.
I contemplated displaying a single list of tasks with timer headers on just one screen, but there were over 100 tasks so it seemed like too many to scroll through (especially since I needed a way to configure individual timers). So I want to have three screens:

A timer screen that displays a list of timers
Tapping a timer will bring up the tasks screen which lists the names of all the tasks for that timer, and allows the user to configure settings for the timer
Tapping a task will bring up the task detail screen which displays more information about a task

However, I want to add search functionality at the timer screen level to find tasks.
My question is about whether it's okay to display different details about the tasks in the search results compared to any of the other 3 screens.
e.g.

The timer screen displays a name, time, number of tasks, and a notification on/off indicator
The tasks screen displays a name, and whether it has been completed
The task detail screen displays the time, name, whether it has been completed, a description, statistics, and other information.
The search results on the timer screen show a task name, the time, and whether it has been completed.

Does anything about this sound like bad UX? This is the first ever mobile app I've worked on, so the UX part has been especially hard to figure out.
Answer: The search result screen is displaying the required information from the task screen (task name, completed?)  and task detail screen (time).
It is good not to overload the user with information. I feel your approach is right.


include a new mixin in all enumerable classes

Question: I'd like to add a module to all Enumerable classes.  Is there a good way to do this?
My solution at this point is:
module Enumerable
  include my_module
end

class Array
  include Enumerable
end

class ____
etc...

Unless I include the new version of Enumerable in all of the classes which include the original Enumerable, they do not get updated.  Is there a better way of doing this?  Perhaps with some meta programming?
Thanks!
Comment: What are you trying to achieve?
Comment: I didn't think that mattered for the question at hand.  But, I'm trying to add a palindrome? method for enumerables for a homework assignment.  I understand that it's silly for things like Hashes, but it's what I'm trying to do.
Answer: As far as I know you have to write the method code inside the Enumerable module
module Enumerable
    def so
        "StackOverflow!"
    end
end

a = [1, 3, 7]
a.so
#=> "StackOverflow!"

Comment: Yep, that makes a lot of sense.  Thanks.


mysql fetch array is not showing result

Question: So I have been working on this code for a while. I believe I am really close. My if statement that is inside my while loop isn't showing any data in the area it's suppose to show. I know mysql is old and deprecated. I am going to change it once I figure this out.
$result = mysql_query("SELECT * FROM inventoryTable",$db);
$result2 = mysql_query("SELECT * FROM users WHERE username='$username' and sub = 'yes'",$db);
echo "
";
echo"
"."Title"."	";
echo""."Authors First Name"."	";
echo""."Authors Last Name"."	";
echo""."ISBN"."	";
echo""."Publisher"."	";
echo""."Course Number"."	";
echo""."Source"."
";
while ($myrow = mysql_fetch_array($result))
    {
        echo "
".$myrow["title"]."	";
        echo "".$myrow["authorsFirst"]."	";
        echo"".$myrow["authorsLast"]."	";
        echo "".$myrow["ISBN"]."	";
        echo "".$myrow["publisher"]."	";
        echo "".$myrow["courseNum"]."	";
        while ($subResults = mysql_fetch_row($result2))
            {
                If($subResults == 'yes' )
            {
                echo "".$myrow["source"]."	";
            } else {
                echo ""."Please subscribe to View"."	";
        }
                echo "
";
        }
    }
?>

This is the part of my code that isn't showing any results.
while
while ($myrow = mysql_fetch_array($result))
    {
        echo "
".$myrow["title"]."	";
        echo "".$myrow["authorsFirst"]."	";
        echo"".$myrow["authorsLast"]."	";
        echo "".$myrow["ISBN"]."	";
        echo "".$myrow["publisher"]."	";
        echo "".$myrow["courseNum"]."	";
        while ($subResults = mysql_fetch_row($result2))
            {
                If($subResults == 'yes' )
            {
                echo "".$myrow["source"]."	";
            } else {
                echo ""."Please subscribe to View"."	";
        }
                echo "
";
        }
    }

I want my session user to be able to see the source from my inventory table if they have a yes in the sub field. If they do not have a yes in the sub field, they will see please subscribe to view. Am i doing the mysql_fetch incorrectly or is there a problem because I have 2 while loops going on at once.
Comment: Apart from the =/== issue – $username likely contains a string value, yes? But what you are comparing it to is an array.
Comment: And of course your inner while loops only once, on the first iteration of the outer while loop. After that, `mysql_fetch_array($result2)` will continue to return false, so the loop body isn't executed any more. You'll need to use `mysql_data_seek` to reset the record pointer for that result set, if you want to loop over it again.
Comment: And the MySQL extension has been deprecated for long time now already, and has been completely removed in PHP 7. You should be using MySQLi or PDO instead.
Comment: @CBroe - the OP knows that and posted this"... I know mysql is old and deprecated. I am going to change it once I figure this out. ..." indicating that will be fixed in due course
Comment: $username is from the session. `mysql_data_seek` requires 2 parameters. What should I use as an offset if I am searching the table?
Answer: you need to have "==" to compare two values, otherwise you assign the second value to the first variable:
...If($username == $subResults)...

or to use a strict comparison of type and content, use "==="
If($username === $subResults)

also I am thinking the code should be
...If($subResults ==="yes"){echo"....///desired content";}else{echo"...//alternate content";}...

and you are missing the echo statement and closing 	 in the code
   "".$myrow["source"];

should be
echo"".$myrow["source"]."	";

in fact - aren't you missing the closing td's in all of the cells?
Comment: Nothing shows under `code`"".$myrow["source"];`code` still. The row is just blank but every other row loads data from my inventory table correctly.
Comment: answer amended - look at the last half :)
Comment: I am getting an error now. The error says syntax error, unexpected '""' (T_CONSTANT_ENCAPSED_STRING), expecting ',' or ';'  on line 42. Line 42 is  `code`".$myrow["authorsFirst"].""`code`
Comment: that would proabably be becuase the preceding TD isn't being closed - you need to go through and close all TD's that have been opened  as well as the TR. also - i just noticed that your border styling is wrong too - you need a "#" before the border color declaration ... "#A4A4A4"...
Comment: I am no longer getting an error. "Please subscribe to View" is showing up 7 times though. I thought it was showing up 7 times because there may have been 7 users in my users table. There's 10 so it can't be that.
Comment: probably there are 7 table cells in your row - perhaps its best if you trashed the entire code as it is an rewrote it carefully, making sure that you have all code structure correct
Comment: I edited my old post with my new code. Can I have multiple `code`mysql_query`code` in one  area?
Comment: yup - also look at the rest of your code for errors - eg: Source"; should be Source"; ... and I would suggest losing the capitalisation on these elements. best we don't keep commenting on this though- SO has a policy of restricting comments and reducing chat on posts - good luck with your code

mysql fetch array is not showing result


Displaying Raw JSON in HTML With Special Characters

Question: I am trying to display some raw JSON data in HTML, and some of this JSON data may contain HTML special characters (<, & etc.) that need to be displayed and not interpreted by the page as HTML.
I am inserting the data onto the page using javascript like so:
<code>$(child).html(JSON.stringify(bigJSONObject, null, 4));
</code>
Check out this JSFiddle for an example using a couple of different wrappers to display the JSON data.  http://jsfiddle.net/4ae7u/
As you can see, each of the wrappers interpret the JSON data as HTML.  What is the best way to have Javascript escape the HTML entities so the full JSON data shows up?
Answer: Use <code>.text()</code> instead. http://jsfiddle.net/4ae7u/1/
<code>$(child).text(JSON.stringify(bigJSONObject, null, 4));
</code>
Comment: I'm positive this is a duplicate of some other question, but i'm having a difficult time finding it.
Comment: It might be, but I couldn't find anything related to this before posting.  Thanks!


Regex matching digit in between?

Question: I would like to get number in between these strings.
strings = ["point_right: account ISLAMIC: 860328 9221 asdsad",
       "account 723123123",
       "account823123213",
       "account 823.123.213",
       "account 823-123-213",
       "account:123213123 ",
       "account: 123213123 asdasdsad 017-299906",
       "account: 123213123",
       "point_right: account ISLAMIC: 860328 9221"
      ]

Result would be
[860328 9221,723123123, 823123213, 823.123.213, 823-123-213, 123213123, 123213123, 123213123]

And i can do processing later to make them into number. So far my strategy is to get everything after pattern and anything before a letter. I have tried:
for string in strings:
    print(re.findall("(?<=account)(.*)", string.lower()))

Please help to give some pointers on the regex match.
Comment: `r'(?<=\D)\d[^A-Za-z]+\b'` seems to work.
Answer: Try this pattern:
(?=[^0-9]*)[0-9][0-9 .-]*[0-9]

Breakdown:

(?=[^0-9]*) Lookahead for a word, such as "account", non-matching
[0-9] Find a digit
[0-9 .-]* Find any number of digits or special characters (in your strings you have spaces, dashes, periods so I included those)
[0-9] Find another digit (to prevent spaces at the end)

Check it out here, and sample code here
Answer: (?!\W)([\d\s.-]+)(?<!\s)

The negative lookahead and lookbehind seems like overkills here but I wasn't able to get a clean match otherwise. You may see the results here
(?!\W) Negative lookahead to exclude any non-word characters [^a-zA-Z0-9_]
([\d\s.-]+) The capturing group for your numbers
(?<!\s) Negative lookbehind to exclude whitespace characters [\r\n\t\f\v ]
Answer: If the numbers must be the first numbers after the account substring use
re.findall("account\D*([\d\s.-]*\d)", s)

See the Python demo and the regex demo.
Pattern details

account - a literal substring
\D* - 0+ chars other than digits
([\d\s.-]*\d) - Capturing group 1 (the value returned by re.findall): 0 or more digits, whitespaces, . and - chars followed with a digit.

Regex matching digit in between?


Azure Media services: storage encrypted rest api didn't work

Question: I am using azure media services rest api to create an asset which should be storage encrypted.
The below steps where successful:
1: created an asset with "Options": "1"(storage encryption).
2: created the a content key with ContentKeyType":"1""ProtectionKeyType":"0".
3: Associated the content key with asset created.
4: created the asset file.
5: created the Access policy.
6: created the SAS url(StartTime is five minutes before the current time).
7: uploaded the file to the SAS url by correctly specifying the file name(I did a chunk upload to the blob storage).
8: Deleted the Locator & AcessPolicy.
Problem:

I was not able to encode the asset.
From the blob storage, I was able to download the file and play. The file was not encrypted at storage!

Further inference

I could verify the asset file with AMS Explorer(image attached).
Downloading the file from AMS Explorer didn't work.
Answer: From docs - "If you have unencrypted media that you wish to encrypt prior to upload you should specify AssetCreationOptions.StorageEncrypted when creating the asset. This encrypts media locally prior to uploading it to Azure storage where it will be stored encrypted."
From REST API reference (https://msdn.microsoft.com/en-us/library/azure/hh974277.aspx) -
StorageEncrypted = 1: Specifies that an asset's files should be encrypted on for upload and storage when creating the asset.
What is mean that providing StorageEncryption option you just telling system that your asset has been encrypted before uploading. .Net SDK doing it for you, but when you are using rest api you have to encrypt file yourself before uploading.
You can look at https://github.com/Azure/azure-sdk-for-media-services/blob/dev/src/net/Client/Entities/AssetFileData.cs to see how encryption for asset file implemented in .net SDK.
You have to create content key and associate it with asset and use it for encryption.
Once you have all this information i system, azure media services will be able to decrypt your content during encoding to other formats.
Comment: I am convinced.Thanks George.


How to customize a SeekBar with minimum value at right side and maximum value at left side

Question: I want to customize a Seekbar in android reversely. Minimum value at right and maximum value at left side. Here is the image.

SeekBar look is not a matter, it could be the default android Seekbar look but the Max and Min value should be inverted. Maximum value will be 10 and minimum value will be 0. If any body have idea please help me.
Comment: if you work on android 11+ you can set on the xml android:rotation="180"
Answer: You have to stuff some code.
<code>seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser){
                    MAX_VALUE=MAX VALUE-progress;
                    //YOU CAN USED THIS VALUE AND SET INTO SEEKBAR.

                }
</code>
Comment: I tried putting max value at the left and min value at right and I did some calculation in onProgressChanged() but Seekbar is not moving because of that onProgressChanged() is not getting called.
Comment: I did samething which you mentioned in answer at seProgress() also. Now its working fine.


$\sum_{p \le x, p \equiv 3 \bmod 10} \frac{1}{p} = \frac{1}{4} \log\log(x)+A+O(\frac{1}{\log x})$

Question: I wish to prove the following equality
$$\sum_{p \le x, p \equiv 3 \bmod 10} \frac{1}{p} = \frac{1}{4} \log\log(x)+A+O(\frac{1}{\log x})$$
For some constant A
Own work:
Let $$A(x) = \sum_ {p \le x} \frac{\log p}{p} $$
and let:
$a(n)= 1$, when $n$ is prime, and let $a(n)=0$ otherwise
$$\sum_{p \le x} \frac{1}{p} = \sum_{n \leq x} \frac{a(n)}{n}$$
and
$$A(x) = \sum_{n \leq x} \frac{a(n)}{n} \log n$$
If $f(t) = \frac{1}{\log t}$, and since $A(t) = 0$ for $t<2$
$$\sum_{p \le x} \frac{1}{p} = \sum_{n \leq x} \frac{A(n)}{\log x} + \int_{2}^{x} \frac{A(t)}{t\log^2 t} dt$$
I know that:
$$\sum_ {p \le x} \frac{\log p}{p} =  \log x + O(1)$$
Which can be plugged in to obtain:
$$\sum_{p \le x} \frac{1}{p} =  \frac{\log x + O(1)}{\log x} + \int_{2}^{x} \frac{\log t + R(t)}{t\log^2 t} dt$$
Which will be:
$$\sum_{p \le x} \frac{1}{p} = 1 + O(\frac{1}{\log x}) + \int_{2}^{x} \frac{1}{t\log t} dt +\int_{2}^{x} \frac{ R(t)}{t\log^2 t} dt $$
But I think, I think I didn't start correct.
I think I have to do more with $p \equiv 3 \bmod 10$
Answer: Here is a heuristic proof.
Start with
$\sum_{p < x} \dfrac1{p}
=\ln \ln x + O(1)
$.
Then,
mod any positive integer $m$,
the primes in the
$\phi(m)$ congruence classes
$p \equiv k \bmod m$
for $(k, m) = 1, 1\le k \lt m$
are approximately equally
distributed,
so
$\sum_{p < x, p \equiv k \bmod m} \dfrac1{p}
=\dfrac1{\phi(m)}\ln \ln x + O(1)
$.
Since $\phi(10)=4$,
all you have to do is make this rigorous.
Note:
Look up "prime number races."
Comment: The first statement is known. I'm not sure about the equal distribution.
Comment: Can I just use the start of your proof, or do I have to prove your first statement first? And what do you mean my make this rigorous?


Who is collecting the Dancing Stars?

Question: I got a Dancing Star in my travels, and the flavour text for it says that "rumor has it, someone is collecting these". That makes me think that they serve some kind of purpose. Who wants these? What are they good for?
Answer: Dancing stars can be traded in at the Springdale Community Center at night. An npc there will give you different victory poses for your yo-kai once you have completed his quest. The yo-kai will need to be at least a certain level to unlock specific poses. When you win a battle, your yo-kai will randomly perform one of their victory poses.

Who is collecting the Dancing Stars?


Finding all $a,b,c$ such that $(ax)^2+(b+cy)^2 \leq 1$ whenever $x^2+y^2 \leq 1$.

Question: Suppose $x,y,a,b,c \in \mathbb R$ and suppose that $$(ax)^2+(b+cy)^2 \leq 1$$ for all $x,y$ such that $x^2+y^2 \leq 1$. What are the allowed values of $a,b,c$?
Plugging in $x=1$, $y=0$ we get $a^2+b^2 \leq 1$. Similarly for $x=0,y=1$ we get $(b+y)^2 \leq 1$. Are there any additional constraints imposed on $a,b,c$?
Answer: One is a circle centered at $(0,0)$ and with radius $1$.
The other is an ellipse
$$
\left( {ax} \right)^{\,2}  + \left( {b + cy} \right)^{\,2}  = \left( {{x \over {1/a}}} \right)^{\,2}  + \left( {{{b/c + y} \over {1/c}}} \right)^{\,2}  \le 1
$$
centered at $(0, -b/c)$, and with semi-axes $(1/a, 1/c)$.
You want (if I understood exactly) that the ellipse be contained in the circle.
Can you proceed from here , using , e.g., the polar coordinates ?
Otherwise please specify what tools bag you have.
Comment: That's great thanks! The geometrical interpretation is very helpful.
Comment: @gene: glad it helped; for a further help have a look to my comment to *marty*'s answer
Answer: I played around for a bit
and came to a point
where I didn't want
to go further.
I'll show what I did
in the hope that
someone else
might find this useful.
Assume that
$x$ and $y$
are on the boundary,
so
$x^2+y^2 = 1
$.
This becomes
$\begin{array}\\
1
&\ge a^2x^2+b^2+2bcy+c^2y^2\\
&=a^2(1-y^2)+b^2+2bcy+c^2y^2\\
&=a^2+b^2+2bcy+(c^2-a^2)y^2\\
\end{array}
$
or
$1-a^2-b^2
\ge 2bcy+(c^2-a^2)y^2
$.
The equality case for this is
$\begin{array}\\
y
&=\dfrac{-2bc\pm\sqrt{4b^2c^2+4(c^2-a^2)(1-a^2-b^2)}}{2(c^2-a^2)}\\
&=\dfrac{-bc\pm\sqrt{b^2c^2+(c^2-a^2)(1-a^2-b^2)}}{(c^2-a^2)}\\
&=\dfrac{-bc\pm\sqrt{a^4 + a^2 b^2 - a^2 c^2 - a^2 + c^2}}{(c^2-a^2)}\\
\end{array}
$
And that's where
I stop.
Comment: As for my answer, since we have a circumference and a displaced ellipse, if you search for their intersection, then you may have none, two or four points. And since the center of the ellipse is on the $y$ axis, the points are symmetrical to that (2 sol. in $y$) . First we shall have $|b/c| \le 1$ for the center of the ellipse to be inside, then take your 2nd inequality, think of it as a parabola (in $y$) and fix the conditions for it not to cross the $y=0$ axis.


SQL select with complex insert

Question: I am trying to concatenate 2 tables into 1 table with 1 mysql command.  I also want to concatenate a file path into one path in the new table.  Any information would be helpful.  Thank you.
Something like this :
INSERT INTO table3 VALUES (Location) SELECT "A.Loc_Path B._FilePath" FROM Table2 A INNER JOIN table1 B ON A._Loc_ID = B._Loc_ID

I would like to take Table 1 & 2 and create Table 3
Table 1
| ID | _FilePath        | _Loc_ID |
| 1  | 001\yay\txt.html |    1    |
| 1  | 002\yay\txt.php  |    2    |

Table 2
| _Loc_ID | Loc_Path           |
|    1    | D:\documents\test\ |
|    2    | C:\Temp\test\      |

Table 3
|  Id  | Location                           |
|   1  | D:\documents\test\001\yay\txt.html |
|   2  | C:\Temp\test\002\yay\txt.php       |

Comment: http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_concat
Answer: Use concat
INSERT INTO table3 (Location) SELECT concat (A.Loc_Path , B._FilePath)
FROM Table2 A INNER JOIN table1 B ON A._Loc_ID = B._Loc_ID

Comment: Hey, i'm curious, isnt it supposed to be `INSERT INTO table3(Location) VALUES (XXX)` where XXX is the concatenation result ? I mean as the doc says... If you don't mind explaining :-)
Comment: @Enissay please explain better your comment . I don't understand  .. you need a better explanation of concat?
Comment: No, the `VALUES` keyword position confuses me; Also using the `INSERT... SELECT ` syntax, it should be `INSERT INTO table3(Location) SELECT...` xD
Comment: Well, @Nir Levy came up with the same solution, that made me think it was some alternative form to do so as I'm trying to re-build my rusty sql knowledge xD ; Thks <3 [upvoted]
Answer: what you need is to use the concat function to concatenate the two columns:
INSERT INTO table3 VALUES (Location) SELECT CONCAT(A.Loc_Path, B._FilePath) FROM
  Table2 A INNER JOIN table1 B ON A._Loc_ID = B._Loc_ID

SQL select with complex insert


How to remove duplicate column results, and include a count of number of columns in each table?

Question: some quick questions.
I have this query:
SELECT u.Table_Name, u.Column_Name
FROM User_Tab_Columns u;

Which gives me these results:
TABLE_NAME                     COLUMN_NAME
------------------------------ -----------
BONUS                          ENAME
BONUS                          JOB
BONUS                          SAL
BONUS                          COMM
DEPT                           DEPTNO
DEPT                           DNAME
DEPT                           LOC
DUMMY                          DUMMY
EMP                            EMPNO
EMP                            ENAME
EMP                            JOB
EMP                            MGR
EMP                            HIREDATE
EMP                            SAL
EMP                            COMM
EMP                            DEPTNO
SALGRADE                       GRADE
SALGRADE                       LOSAL
SALGRADE                       HISAL

I'm unsure how to make it so that the table_name results do not repeat (so one of each result) and to have the number of columns that each table has in place of the column_name.
Thanks in advance for any help.
Answer: Using the GROUP BY clause, you can group your tables so that you can run an aggregate function, in this case COUNT, on the columns you wish to count.
SELECT u.Table_Name, COUNT(1) AS Column_Count FROM User_Tab_Columns u GROUP BY u.Table_Name

Comment: why `count(1)` and not `count(*)`?
Comment: (I just wanted to make sure you aren't falling for the popular myth that `count(1)` is faster than `count(*)`) But `count(column_name)` will return something different than `count(*)`
Comment: `COUNT(column_name)` will return the count of non-null values for the column. `COUNT(1)` returns all rows for the entire result set.
Comment: @SylvainLeroux I stand corrected. I looked it up - my previous understanding was wrong.
Comment: Just a habit, you can use `COUNT(*)` or even `COUNT(Column_Name)`. The `COUNT(*)` or `COUNT(1)` will perform a little better (no difference between the two to just count the number of rows for the group).
Comment: It's almost magical. Thanks. Is there a way to add the number of rows in each table, too?
Comment: Not necessarily. By itself and with no NULLs, it returns the same. But the columns can give you additional options, like counting non-null or distinct values.
Comment: Without the optimizer, `COUNT(*)` would hydrate the whole row into memory when counting whereas `COUNT(1)` by nature does not. However, the optimizer transforms `COUNT(*)` to `COUNT(1)` prior to execution.
Comment: I agree completely about COUNT(1) and COUNT(*) being identical. Best writeup I've read is: http://stackoverflow.com/questions/1221559/count-vs-count1. I fell into the myth until I read that, and still have it as a habit. I only suggested COUNT(Column_Name) because you were going off a list of tables/columns...you wouldn't have a null column name.
Comment: Is there a way to add the number of rows (like     count(row) or some equivalent?) like the number of columns has been listed?
Comment: @ShaunKelly01 - Assuming statistics are relatively updated, in Oracle, you'd run `SELECT table_name, num_rows FROM user_tables`. In SQL Server to use the statistics, it's a longer query, but good blog here: http://weblog.kevinattard.com/2011/07/how-to-get-table-row-count-for-all.html
Comment: Thanks. I input the SELECT query you gave, but the Num_Rows results were blank.
Comment: That's probably because your db doesn't have any stats computed for the tables. `ANALYZE TABLE table_name COMPUTE STATISTICS` computes the stats, but you should probably log a new question to get more eyes on it for best practices and when the stats update
Comment: @JordanParmer _"Without the optimizer, `COUNT(*)` would hydrate the whole row into memory"_ If don't think so, as according SQL-92, `COUNT(*)` is the _cardinality_ of the table expression. The content of the row is irrelevant.


Total of three wires in wall junction box (two are hot). How can I wire this to become an outlet that is controlled by an in-wall timer?

Question: Sorry if my title sounds confusing. To elaborate further. In my garage I have a junction box with three sets of Romex wires tucked into the box with a flat cover plate. (no outlet at this box). After removing the cover plate and when using my voltage tester two of the black wires light up when an in-wall timer they are connected to in another location is in the "ON" position. The third one does not.  This in-wall timer turns on our outdoor entryway light and outdoor garage lights at the same time. I was hoping to install an outlet at this junction box in my garage so that I can plug in a transformer to turn on my landscape lights at the same time the in-wall timer turns on the entryway and garage lights. When I turn on the in-wall timer manually, the wires become hot. And when I turn them off there is no detection of voltage at this junction box with three Romex wires.
I tried using a GFCI outlet with the third prong hole facing down and installed the black wires (that were hot when I turned the power on at the in-wall timer) to the brass screws (one wire per hole). And the two coordination white wires at on the side with the silver screw. I then used the bottom brass screw to connect the wire that wasn't hot when the power was on along with the white wire to the silver screw at the bottom. It's not working and all I see is the bottom red light (which should be green to let you know it's good to go and has power. Otherwise the outlet does not provide power.
How do I wire this correctly in order for this outlet to serve as a power source that only turns on when my in-wall timer sends power through these three wires?
Comment: You don't you do not have an earth ground. If you have bare wires in the box please let us know, they are earth ground. It would help if you posted a picture of the box. It also matters which wire is connected to which. It sounds like they are all connected together (white to white, black to black) and it is on a switch (timer).
Answer: Turns out I was able to figure this out. First of all, I was wrong about the wiring. There is only one hot wire. The other two power the two pairs of lights in the front of our garage door. I think what happened was I didn't separate the Romex wires well enough and the current was passing through to the next Romex; making me believe two were hot. After I put some distance between them only one of them tested as hot.
It's a long story but to be quick; one pair of lights were controlled by an old manual in-wall timer (where the three wires I was working with connected at a junction box I described above that had a flat cover plate to hide/protect them. I forgot I had that old manual timer removed last year in order to connect them all together and turn all the lights on at the garage. Not to mention, it was so loud and was clicking like an old clock I could hear in the house (when we had our garage door to our kitchen open). I The other wire turns on the other pair of lights along with the entryway lights. I know, it's goofy. My voltage detector is a bit shoddy so I bought a new one this evening and correctly discovered there was only one hot wire. After going to a big box store I bought some wago connectors (for four wires) and was informed to use one for all the black, one for the white wires and one for the ground wires. I used the fourth wago hole insert to pigtail to a new outlet I bought which is not GFCI. He said I didn't need a GFCI since these are what power the two pairs of LED lights in front of my garage along the underside of the eve.
Here is an image of the two pairs of lights that were once controlled separately by one manual in-wall timer and another switch that also controlled the light at the entryway. Now it is wired so that they all go on at the same time with a digital in-wall timer. And my outlet is working perfectly inside the garage to power my landscape lights.
Image of the two pairs of lights in front of the garage:

Images of my landscape lights:

Now, everything including my landscape lights all turn on at the same time. Yay!
Comment: Where is this house located, i.e., in USA? If not what country?
Comment: I'm in southern California, US.


Why are *to_init[0] and *to_init not the same thing when dealing with pointers to pointers?

Question: void initialize_char(char** to_init, char* source, int start, int end)
{

    printf("%p\n",*to_init[0]);
    printf("%p\n",*to_init);
}

I noticed that *to_init and *to_init[0] are completely different memory addresses. But as I understand it (which I'll need correcting):
Order of precedence means in *to_init[0], to_init[0] comes first, then followed by the indirection operator. Technically speaking, doesn't subscripting to_init[0], simply reference the pointer that is being pointed at by **to_init, and then wouldn't the use of the indirecrion operator simply allow me to access what's inside this pointer?
Thus shouldn't the aforementioned then be the same as *to_init?
Comment: You seem to be asking why **toinit and *toinit aren't the same.
Comment: So to_init[0] doesn't subscript what it's pointing to?
Comment: If you do  printf("%p\n",*to_init[0]);
 printf("%p\n",**to_init); They should be same.
Answer: to_init[0] is translated as *(to_init + 0) or just *to_init. Therefore *to_init[0] would be equivalent to *(*to_init) or just **to_init.
to_init is char**, which makes *to_init a char * and **to_init to a char.
This means that *to_init[0] is giving you the actual char of the char array and *to_init is giving you a pointer to the first position of the char array. That's why the values are different.
Comment: `to_init` is a pointer to a pointer to a char. `*to_init` is a pointer to a char. `**to_init` is just a char.
Comment: Given the declaration `char **to_init;`, then the expression `**to_init` is __not__ a pointer.
Comment: When you use the operator * on the code (not on the declaration of the function)  you are actually getting the content of what the variable is pointing at. So:

to_int is char** -> *to_int is char * (because, char** points to char *) -> **to_int is char (because char * points to char)
Comment: Simply, use *(to_init +index) or to_init[index], this will get you what you the char *, that what to_init is pointing at
Comment: Ok we're getting somewhere, but earlier (before asking this) i tried *to_init[some_number]=character and my program kept crashing because it thought i was trying to modify to_init
Comment: meaning i had to change it to (*to_init)[number], even though *to_init[number] still gets my at **to_init
Comment: So what happened there
Comment: that's why i thought *to_init[0] and *to_init had to be the same due to that problem
Comment: *to_init[number] -> [] has precedence over * so your code was taking *(to_init + number), which is getting a value different of what you want because is only to_init that points where the data you want is, than taking the value of this position.

When you used the () the precedence goes to *to_init, which is pointing to char array you want, get this value and add the number then get the value of that position
Answer: to_init[0] is the same as *to_init (a pointer to the char which to_init points to)
so *to_init[0] is the same as **to_init (the char) NOT *to_init (the pointer to char).
Answer: to_init is of type char**, meaning a 'pointer to a pointer to a char'.
*to_init dereferences the variable, essentially getting the 'pointer to the char' of type char*.
Since the [] operator has higher precedence than the * dereference, the first char* is dereferenced to a char. The first printf should therefore print a character value, not a pointer.
As you can see here this is correct - the first line returns hexadecimal 0x61, which is the ASCII value for a. The second line returns a memory address, being the location of the compiled string value.
Comment: @OliCharlesworth oops, corrected - funnily result stays the same as it means you're dereferencing a `char*` to a char instead of returning the first char in a `char*`   :)
Answer: They say a picture is worth a thousand words. Hopefully, the ASCII diagrams work as well as pictures.
Let's you have:
int A = 10;
int* ip = &ip;
int** ipp = &ipp;

The memory used by those variables look something like:
A
|
v
+----------------+
|    10          |
+----------------+

ip
|
v
+----------------+
| Address of A   |
+----------------+

ipp
|
v
+----------------+
| Address of ip  |
+----------------+

Now, let's look the exressions that are similar to what you are using:
*iip[0] = *(iip[0]) = *(ip) = 10
*iip = ip = Address of A

*iip[0] is not a memory address. It's the value of A.


Gesture interfering with sheet drag

Question: I am showing a camera preview view on a .sheet.
I need to detect when the user's finger touches the preview area and when the user's finger leaves the preview area.
The only solution I have found to do that was this
  CameraPreview()
    .gesture(DragGesture(minimumDistance: 0)
                          .onChanged { _ in
                            // finger touches
                          }
                          .onEnded { _ in
                            // finger leaves
                          })

but as this preview is being displayed on a sheet and sheets must be closed by dragging them from the top down, this drag gesture prevents the sheet drag gesture from working.
Any ideas?
NOTE: I do not need to detect dragging. I need to detect single tap on a view and then receive a callback when the finger leaves that view.
Answer: You need to use UIViewRepresentable for this. Here are the steps:

Create a custom version of AnyGestureRecognizer taken from here:

class AnyGestureRecognizer: UIGestureRecognizer {
    var onCallback: () -> Void
    var offCallback: () -> Void

    init(target: Any?, onCallback: @escaping () -> Void, offCallback: @escaping () -> Void) {
        self.onCallback = onCallback
        self.offCallback = offCallback
        super.init(target: target, action: nil)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
        if let touchedView = touches.first?.view, touchedView is UIControl {
            state = .cancelled
            offCallback()
        } else if let touchedView = touches.first?.view as? UITextView, touchedView.isEditable {
            state = .cancelled
            offCallback()
        } else {
            state = .began
            onCallback()
        }
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        state = .ended
        offCallback()
    }

    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent) {
        state = .cancelled
        offCallback()
    }
}

Create a custom UIViewRepresentable view and attach the AnyGestureRecognizer to it:

struct GestureView: UIViewRepresentable {
    var onCallback: () -> Void
    var offCallback: () -> Void

    func makeUIView(context: UIViewRepresentableContext<GestureView>) -> UIView {
        let view = UIView(frame: .zero)
        let gesture = AnyGestureRecognizer(
            target: context.coordinator,
            onCallback: onCallback,
            offCallback: offCallback
        )
        gesture.delegate = context.coordinator
        view.addGestureRecognizer(gesture)
        return view
    }

    func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<GestureView>) {}

    class Coordinator: NSObject {}

    func makeCoordinator() -> GestureView.Coordinator {
        Coordinator()
    }
}

extension GestureView.Coordinator: UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        true
    }
}

Use it as an overlay:

struct ContentView: View {
    var body: some View {
        Color.blue
            .sheet(isPresented: .constant(true)) {
                Color.red
                    .overlay(
                        GestureView(onCallback: { print("start") }, offCallback: { print("end") })
                    )
            }
    }
}

Comment: Thanks but unfortunately your code does not work as expected. If I tap and hold for a little bit. It will never detect the finger touching the button. Your code works If I tap fast, then it will trigger both actions in sequence.
Comment: @Duck You can replace `TapGesture()` with `LongPressGesture(minimumDuration: 0)` - see updated answer.
Comment: Now touch down/up are detected correctly but we are back to square one, because if the view this is in is displayed on a .sheet the .sheet stops responding to the drag gesture, what is the point of the question. So, it is impossible to close the sheet by dragging it down. I can add a close button, but I am sure my boss will complain...
Comment: if there is no solution for that I will have to add a close button. :(

Gesture interfering with sheet drag


awk automatically rounding off the output

Question: i used the below awk command
awk -F ':' '
  { s3 += $3; }
  { s4=s4+$4; }
  { s5=s5+$5; }
  END { print s3,","s4,","s5,","s3/s5 }' sample.txt > sample1.txt

And my input file (sample.txt) is:
05/05/2013:0:47623.49:1007:180
05/05/2013:1:35959.84:1959:132
05/05/2013:2:26317.05:690:85
05/05/2013:3:8715.40:107:32
05/05/2013:4:5713.27:66:24
05/05/2013:5:10533.34:1025:17
05/05/2013:6:10748.54:602:58
05/05/2013:7:44429.87:1644:203
05/05/2013:8:97096.44:4320:415
05/05/2013:9:148065.87:6603:639
05/05/2013:10:194488.19:8426:900
05/05/2013:11:231119.09:10991:986
05/05/2013:12:263701.11:10771:1070
05/05/2013:13:275892.40:10005:1054
05/05/2013:14:272595.88:9702:1120
05/05/2013:15:286506.75:10953:1110
05/05/2013:16:119102.11:4298:504

but the command is automatically rounding off, the output is:
2078610.00,83169 ,8529 ,243.711

I want the output as 2078609.56 (exact value without round off), how to achieve this in awk?
Answer: try this line:
 awk -F ':' '{ s3 += $3;s4+=$4;s5+=$5} END{ printf "%.2f,%d,%d,%f", s3,s4,s5,s3/s5 }' input

awk could specify the output format by using function printf. I notice that your $3 and the $3/$5 may need special precision, I just add %.2f and %f, you could adjust it for your needs.
the output of the above line:
2078608.64,83169,8529,243.710709

i don't know how did you get the "exact value" 2078609.56 typo in your input file?
Answer: The problem is that the default output format (OFMT) rounds to the first six most significant digits (%.6g). You can modify this value to %.10f to print 10 digits after decimal point. You can change the first line of Your command to:
awk -F ':' -vOFMT=%.10f '

Also to treat s3/s5 as a float You should modify the END closure as
END { print s3,",",s4,",",s5,",",s3/s5 }'

There is two problems using this:

OFMT works only for float numbers. Numbers like 123 or 123.00 is considered as integers internally by awk, so they will be printed without using this variable. IMHO the output in the question should be something like this:
2.07861e+06 , 83169 , 8529 , 243.711
Actually not the 2078609.56 value is the exact value. As the numbers are represented in binary form, they will be added as such. So if You set the output format to %.10f you will get something like this:
2078608.6399999999 , 83169 , 8529 , 243.7107093446


Split string and print the value of string separately in autocad

Question: 534-W1A-R1 this is my file name and I want to split it so it prints like
Code=534 Phase=1 Zone=A

in my Autocad file.
Comment: Use split : string input = 534-W1A-R1; string[] splitArray = input.Split(new char[] {"-"});
Comment: That 1 is in between W and A
Answer: You have different ways to do it. if you are sure about the format of the text you can just use this:
var str= "534-W1A-R1";
var parts=str.Split('-');
var code= parts[0];
var secondPart= parts[1];
var phase=secondPart.Substring(1,secondPart.Length-2);
var zone=secondPart[secondPart.Length-1];

You can also use Regex if it is more complicated.
Comment: format will be change according to project i mean the value of 1 will be two or three digit sometime.
Comment: give this a try.@Ajjags
Comment: Thanks @Rakitić +1 ;)
Comment: The split method overload that takes array of chars and returns array of tokens is bit easier to use, see related comment under the question
Comment: @GeorgeBirbilis I also used split. take a look at line 2
Comment: If I remember well, one splits in two parts, other version in multiple parts. Might remember wrong though
Comment: @GeorgeBirbilis :O how do you split in 2 parts?! when you split("-") it will be 3 parts already
Answer: The below split code should work:
string str = @"534-W1A-R1";

var split = str.Split('-');

string code = split.First();
string phase = new string(split.ElementAt(1).Skip(1).Take(1).ToArray());
string zone = new string(split.ElementAt(1).Skip(2).Take(1).ToArray());

string result = String.Format("Code={0} Phase={1} Zone={2}", code, phase, zone);
Console.WriteLine(result);

Output:
Code=534 Phase=1 Zone=A

Answer: Use the Substring() method.
string input = "534-W1A-R1";
string sub = input.Substring(0, 3);
string sub2 = input.Substring(5, 1);
string sub3 = input.Substring(6, 1);
Console.WriteLine("Code={0} Phase={1} Zone={2}", sub, sub2, sub3);

Output:
Code=534 Phase=1 Zone=A

Comment: Thanks for the edit, we also missed the second part which I just corrected ;)
Answer: Using Regex
Edit: added some comments (pattern description)
var pattern = @"^(\d+)-[A-Z](\d+)([A-Z])-";
/* pattern description:
^(\d+)  group 1: one or more digits at the begining
-       one hyphen (literal)
[A-Z]   one alphabetic character
(\d+)   group 2: one or more digits
([A-Z]) group 3: one alphabetic character
-       one hyphen (literal)
*/
var input = "534-W1A-R1";
var groups = Regex.Match(input, pattern, RegexOptions.IgnoreCase).Groups;
var code = groups[1].Value;
var phase = groups[2].Value;
var zone = groups[3].Value;


Django - reverse foreignkey select_related

Question: So, similar questions have been asked before, but I have been unable to find a conclusive answer.
Given the following models:
class Parent(models.Model):
    name = models.CharField(max_length=250)

class ChildA(models.Model):
    parent = models.ForeignKey('Parent')

class ChildB(models.Model):
    parent = models.ForeignKey('Parent')

How can I get all the children of a given parent? Select related only goes forwards, so that won't work as far as I can tell. Prefetch related seems to only operate when there is an actual field reference in the parent (ie, if the parent has a field that is a m2m with a child) so I don't see how that would work.
I'm sure this is something I've just overlooked in the docs, given how rudimentary and common this sort of problem is.
Answer: This has nothing to do with select_related or prefetch_related. To get all the children of a parent with your structure, you will always need to do two queries:
my_children = list(my_parent.childa_set.all()) + list(my_parent.childb_set.all())

Comment: So for N children, I will always need at least N queries? Ok. What is the parent.childa_set syntax you are using?
Comment: https://docs.djangoproject.com/en/1.4/topics/db/queries/#following-relationships-backward
Comment: Ah, fantastic,thanks. So it's basically a shorthand for Child.objects.filter(parent=myparent)


Error When Downloading Files from flask on Linux Server

Question: My code works perfectly on my windows machine:
@app.route('/downloads/<filename>', methods=["GET", "POST"])
def downloads(filename):
    return send_file(filename, as_attachment=True)

It uses  tags to pass the variable through for each specific item in a list on an html page. On my windows machine i specify the filename (Which is the directory for the file) variable with backslash's (which then translate into '%5C' in the search bar for whatever reason). This works fine but when i run the same code on my linux machine it gives me an "Internal Server Error" on the browser and this error in the server.
FileNotFoundError: [Errno 2] No such file or directory: '/home/pi/ss/python_files\\user\\file.py'

Now i understand that Linux uses 'forward slashes' for directories and Windows uses 'back slashes' for whatever reason and i figured this was the error but when i try to use 'forward slashes' in the directory instead it gives me a 404 error in the browser:
'Not Found The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.'
And it gives me this in the server:
"GET /downloads/python_files/user/file.py HTTP/1.1" 404 -

Which would make you think that maybe I just have the wrong path to the file, but when I go into the same directory as the server's python file and type:
python3 python_files/user/file.py

It runs the file, so its nothing wrong with the path...
Anyways this is where I became stumped and realized I don't have enough knowledge to fix the error. Your help is much appreciated!
Comment: enter `pwd` command where you run your app, and also use it where you have the file and see if they're the same.,
Comment: @HosseinHeydari I get '/home/pi/ss', and '/home/pi/ss/python_files/user'
Comment: how you are creating directory path to access file.
Answer: refer to this section https://flask.palletsprojects.com/en/1.1.x/quickstart/#variable-rules

Optionally, you can use a converter to specify the type of the argument like <converter:variable_name >.

so if you specify <path:filename> as converter in your route, that should solve your issue
@app.route('/downloads/<path:filename>', methods=["GET", "POST"])

because if NOT explicitly specified, it defaults to string converter and it will accept any text without a slash that's why you got the error
"GET /downloads/python_files/user/file.py HTTP/1.1" 404 -

Comment: Thank you, you're a life savor! I'm new to the stack overflow and have a question, am i suppose to just show your answer and leave my question the same or update mine with the correct way to do it?
Comment: @TheAdmin on Stackoverflow you asked a question and you mostly got answer(s) and you don't have to correct your question accordingly because that does not make sens and the answer you got has no reason to be there and probably will be a subject for downvotes (very bad for reputation) .. You may update your question with new elements (in general you titled the new section with UPDATE / EDIT to keep history), to make it clear and concise so you can get the right answers.


can i possible to execute a single method as current user privileges in the application that running as administrator?

Question: In my application, i need all logical drives including mapped network drives. Its working fine without run as administrator. But my application by default run as administrator and i am not able to mapped network drives. I know that why its happened.
I am using DriveInfo.GetDrives() for collection drives.
My question is,
can i possible to execute a single method(collecting all mapped drives) as current user privileges in the application that running as administrator?
Or any other ways to collect all network drives.
Thanks in advance.
Comment: How will you know which user to execute the method as?  Different users may have different mapped drives.  If the app runs fine without administrator privileges, then you should just run it that way anyway.  Running as administrator should be discouraged.
Comment: Hey chris, In this wpf application, any user can use this page, so we have to show mapped drive by current logon user
Answer: You could create another application without Administrator privileges and then run it from your main program.
<code>Process.Start("myNormalApp.exe");
</code>
In "myNormalApp.exe" you place drives-mapping code. Then, you can write mapped drives to a file and open that file in your main application. It's a bit complex, but I think it's the only way. Let me say, however that I can't imagine why you say that an elevated application can't access to network drives (seems a bit strange to me)
The code is not tested, but it should work.
Hope this helps,
FWhite
Comment: thanks PWhite,  but it should be not a proper way. I am looking for  mapped user drives from same application.


Proving $\sum\limits_{k=0}^{\infty}\binom {m-r+s}k\binom {n+r-s}{n-k}\binom {r+k}{m+n}=\binom rm\binom sn$

Question:
Question: How do you show the following equality holds using binomials$$\sum\limits_{k=0}^{\infty}\binom {m-r+s}k\binom {r+k}{m+n}\binom {n+r-s}{n-k}=\binom rm\binom sn$$

I would like to prove the identity using some sort of binomial identity. The right-hand side is the coefficient of $x^m$ and $y^n$ in$$\begin{align*}a_{m,n} & =\left[x^m\right]\left[y^n\right](1+x)^r(1+y)^s\\ & =\binom rm\binom sn\end{align*}$$
However, I don't see how the left-hand side can be proven using the binomials. Using the generalized binomial theorem, we get the right-hand side as
$$\begin{align*}(1+x)^r(1+y)^s & =\sum\limits_{k\geq0}\sum\limits_{l\geq0}\binom rk\binom slx^ky^l\end{align*}$$However, what do I do from here?
Comment: Not that it entirely corresponds to your question, but this may be of a little help, away the use of Binomial Theorem: https://math.stackexchange.com/questions/2381429/proving-this-infinite-sum-of-a-product-of-three-binomials-sum-limits-s-bino?rq=1
Answer: $$
\begin{align}
&\sum_{k=0}^\infty\binom{m-r+s}{k}\binom{r+k}{m+n}\binom{n+r-s}{n-k}\\
&=\sum_{k=0}^\infty\sum_{j=0}^\infty\binom{m-r+s}{k}\binom{k}{j}\binom{r}{m+n-j}\binom{n+r-s}{n-k}\tag1\\
&=\sum_{k=0}^\infty\sum_{j=0}^\infty\binom{m-r+s}{j}\binom{m-r+s-j}{k-j}\binom{r}{m+n-j}\binom{n+r-s}{n-k}\tag2\\
&=\sum_{j=0}^\infty\binom{m-r+s}{j}\binom{m+n-j}{n-j}\binom{r}{m+n-j}\tag3\\
&=\sum_{j=0}^\infty\binom{m-r+s}{j}\binom{m+n-j}{m}\binom{r}{m+n-j}\tag4\\
&=\sum_{j=0}^\infty\binom{m-r+s}{j}\binom{r-m}{n-j}\binom{r}{m}\tag5\\
&=\binom{s}{n}\binom{r}{m}\tag6
\end{align}
$$
Explanation:
$(1)$: Vandermonde's Identity applied to the sum in $j$
$(2)$: $\binom{m-r+s}{k}\binom{k}{j}=\binom{m-r+s}{j}\binom{m-r+s-j}{k-j}$
$(3)$: Vandermonde's Identity applied to the sum in $k$
$(4)$: $\binom{m+n-j}{n-j}=\binom{m+n-j}{m}$
$(5)$: $\binom{m+n-j}{m}\binom{r}{m+n-j}=\binom{r-m}{n-j}\binom{r}{m}$
$(6)$: Vandermonde's Identity applied to the sum in $j$
Comment: right: that is in line with the  explanation I gave in previous answer [to this related post](https://math.stackexchange.com/questions/2155025)
Comment: @robjohn, do you mind checking this binomial identity, Thank you so much!! https://math.stackexchange.com/questions/3278355/a-binomial-identity-conjecture-numerically-true-very-hard-to-prove
Answer: With OP asking for formal power series in the evaluation of
$$\sum_{k\ge 0} {m-r+s\choose k} {r+k\choose m+n}
{n+r-s\choose n-k}$$
we write
$$[z^n] (1+z)^{n+r-s}  [w^{m+n}] (1+w)^r
\sum_{k\ge 0} {m-r+s\choose k}
z^k (1+w)^k
\\ = [z^n] (1+z)^{n+r-s}  [w^{m+n}] (1+w)^r
(1+z+zw)^{m-r+s}
\\ = [z^n] (1+z)^{n+r-s}  [w^{m+n}] (1+w)^r
\sum_{q=0}^{m-r+s} {m-r+s\choose q}
(1+z)^{m-r+s-q} z^q w^q
\\ = \sum_{q=0}^{m-r+s} {m-r+s\choose q}
{m+n-q\choose n-q} {r\choose m+n-q}.$$
Note that
$${m+n-q\choose n-q} {r\choose m+n-q}
= \frac{r!}{(n-q)! \times m! \times (r+q-m-n)!}
\\ = {r\choose m} {r-m\choose n-q}.$$
We thus have
$${r\choose m}
\sum_{q=0}^{m-r+s} {m-r+s\choose q} {r-m\choose n-q}
\\ = {r\choose m} [z^n] (1+z)^{r-m}
\sum_{q=0}^{m-r+s} {m-r+s\choose q} z^q
\\ = {r\choose m} [z^n] (1+z)^{r-m} (1+z)^{m-r+s}
= {r\choose m} {s\choose n}.$$
This is the claim.
Comment: Sorry for the necro-post, but is there a collection of these infinite binomial sums? I'm trying to generate larger sums that are similar as the one in the question using the same methodology.
Comment: There is this list of [Egorychev method / method of coefficients](http://pnp.mathematik.uni-stuttgart.de/iadm/Riedel/egorychev.html) applications. It is not limited to binomial coefficients.
Comment: I'm mainly looking for identities similar to the ones in the question though: infinite sum, composed of binomials, closed form is a product of binomials. I'm trying to derive more identities using the same process you've demonstrated in your answer, but every time I try, it ends up simplifying to the sum in the question; was wondering if there were others
Comment: Another list is H. W. Gould's *Combinatorial identities.*
Answer: Premise
Let's first see which are the  series corresponding to the basic manipulations involved in the algebraic demonstration of the identity in question.
1) Convolution
$$
\eqalign{
  & \left( {1 + yx} \right)^{\,r} \left( {1 + x} \right)^{\,s}  = \sum\limits_{0\, \le \,k} {\sum\limits_{0\, \le \,j} {
 \left( \matrix{ r \cr   j \cr}  \right)\,\left( \matrix{  s \cr  k \cr}  \right)x^{\,j} y^{\,j} \;x^{\,k} }    }  =   \cr
  &  = \sum\limits_{0\, \le \,k} {\sum\limits_{0\, \le \,j}   {
 \left( \matrix{ r \cr   j \cr}  \right)\,\left( \matrix{  s \cr   k + j - j \cr}  \right)x^{\,j + k} y^{\,j} }   }  =   \cr
  &  = \sum\limits_{0\, \le \,l} {\left( {\sum\limits_{0\, \le \,j} {
 \left( \matrix{ r \cr   j \cr}  \right)\,\left( \matrix{  s \cr  l - j \cr}  \right)y^{\,j} } } \right)x^{\,l}    }
   \cr}
$$
in which, of course, one can put $x$ and/or $y$ to $1$, or other value.
2) Trinomial Revision
Trinomial Revision does not have a single z-Transform for the repeated index, but the double one is quite simple
$$
\eqalign{
  & \left( {1 + y\left( {1 + x} \right)} \right)^{\,r}  =   \cr
  &  = \sum\limits_{0\, \le \,k} {\left( \matrix{
  r \cr
  k \cr}  \right)y^{\,k} \left( {1 + x} \right)^{\,k} }  = \sum\limits_{0\, \le \,k} {\sum\limits_{0\, \le \,m\,\left( { \le \,k} \right)} {\left( \matrix{
  r \cr
  k \cr}  \right)\left( \matrix{
  k \cr
  m \cr}  \right)y^{\,k} x^{\,m} } }  =   \cr
  &  = \left( {1 + y + yx} \right)^{\,r}  =   \cr
  &  = \sum\limits_{0\, \le \,m} {\left( \matrix{
  r \cr
  m \cr}  \right)\left( {yx} \right)^{\,m} \left( {1 + y} \right)^{\,r - m} }  = \sum\limits_{0\, \le \,j} {\sum\limits_{0\, \le \,m} {\left( \matrix{
  r \cr
  m \cr}  \right)\left( \matrix{
  r - m \cr
  j \cr}  \right)y^{\,m} y^{\,j} x^{\,m} } }  =   \cr
  &  = \sum\limits_{m\, \le \,m + j} {\sum\limits_{0\, \le \,m} {\left( \matrix{
  r \cr
  m \cr}  \right)\left( \matrix{
  r - m \cr
  \left( {m + j} \right) - m \cr}  \right)y^{\,\left( {m + j} \right)} x^{\,m} } }  = \sum\limits_{0\, \le \,\left( {m\, \le } \right)\,k} {\sum\limits_{0\, \le \,m} {\left( \matrix{
  r \cr
  m \cr}  \right)\left( \matrix{
  r - m \cr
  k - m \cr}  \right)y^{\,k} x^{\,m} } }  \cr}
$$
Your Request
Considering the requirement of your post, if we take the expansion already given
in the related post, which is equivalent to that given above by robjohn,
and attempt to go backwards, we will realize that we are going into a complicated formal series involving
some five or six variables, which does not seem to be much of interest.
That's mainly due to the Trinomial Revision asking for a double sum.
The first step in such a backward route was already given in the answer to the cited related post.
Comment: Sorry, I'm still kind of confused. Just give me some time; still processing everything! :)


Is there any way to get the relationship from the unsupervised dataset?

Question: I have some data, the dataset includes features such as device id (int), phone (int), name(string), device id etc. But all data do not have the label. my task is to get the probability of a person using multiple ids or multiple devices. I have no idea how to do it, Does anyone have an idea?
for clear, here is an example.
the dataset is like
<code>  name   id    phone  device_id
 Jason   123    12345   12341231     ......
 James   1345   312312  312312312    ......
 Jason   123    53523   23115124    ......
</code>
so we can find that Jason has 2 phone numbers,
how do I get the probability by using the machine-learning method or deep learning method?
Answer: One of the possible way to do this is to compute similarity of user.
As I can understand the device similarity for a user is your end goal.
For starters combine name and Id field which uniquely identifies an user.
Generate, a feature vector for all remaining as an array.
Afterwards you can just run nested for loop with all user over other.
This will give you closest match and you can set a threshold or you can pick kNN to do that.
take a look at this:
Convert Nested dictionary to Pyspark Dataframe
Comment: I think in its current state, your proposed solution is vague. For instance, what distance measure will be used for computing similarity? kNN is a classifier and has nothing to do with clustering?
Comment: Thanks for your answer, it is really helpful. I may add some detail to this question.

1. it is not just the similarity of device id but also uses other features such as name, phone, .... to judge the similarity between 2 data sample (2 rows).

2. is there any possibility to transfer the `phone number` or `device id` to vector format? so I can compute the similarity between 2 vectors.

Looking forward to your reply.
Comment: @mmm As for the your questions no.1 what distance measure should be used ? Practically , choice of distance metrics would depend on kind of data cosine similarity or any similarity measure can be applied. question no.2 it has nothing to do with clustering, K nearest neighbour essentially will pick-up top k similar devices out of all universe of devices being computed.
Comment: @h2222 if you could share the same data to replicate , it would help to put up a solution. I agree it not about device but the entire row similarity ,I mentioned in context device bcoz discuss take that into highlight. Thanks..!!


What is the material and how to seal it?

Question: As you can see In the photo the layer (paint?) on my bathroom ceiling has fallen off.

I think the red/brownish colour part is off-gassing a smell.  Does anybody know what material this is and be what it is off-gassing exactly?

How do I seal this smell in?  Will any paint work/reduce it to negligible levels or does this material/ceiling require some sort of purpose built sealant (is that the thing that's coming off?).

Once the paint or sealant has been applied, generally speaking how long before most of the smell will go?
Comment: Test it for lead and scrape/peel it off before applying new paint. The issue happened due to too much moisture (humidity). Solve the humidity problem and you shouldn't encounter this issue again.
Comment: For sealing in odors you can do a search on this site for shellac, there are   questions on odor and  answers for using shellac to seal. Shellac then paint.
Comment: @Alaska Man if I apply shellac and leave it will that be sufficient.  If the shellac seals it in and the shellac itself doesn't gas off more than paint does I'd rather leave it just with the shellac.  Thanks.
Answer: The painted coating (it looks to be at least the most recent coat of paint and an additional layer below, of either paint or primer) has obviously failed. The cause of the failure is most likely inadequate surface preparation prior to application, exacerbated by high-humidity conditions.
It is very unlikely that the ceiling plaster itself is "off-gassing" or that it is, in and of itself, the cause of any odor. What is likely is that the odor is mildew growth, of which there are some tell-tale signs of along the edge of the wall.
You need to:

strip all unsound material
chemically kill all mildew (there are various methods; I use dilute bleach
sand the entire substrate (while also patching any gaps and defects such as the linear crack where the wall meets the ceiling)
clean/wash the entire area
properly prime and paint using high quality paint products and professional grade applicators

NOTE- a special bonding primer (e.g. shellac) is not necessary if you prep the job as described.
NOTE- a paint with a sheen, such as gloss or semi-gloss, would tend to resist problems associated with moisture better than flat paints.
NOTE- pro-grade applicators and high-quality paints result in a better looking, better performing, and easier job.
NOTE- for longevity and bio-growth prevention, you should ensure there is adequate ventilation. Now is the time to consider upgrading your exhaust fan.
Comment: Thank you for the detailed answer.  My only pickle is that the odour doesn't smell like mildew at all.  I sniffed and it takes me to the browny area while the small amounts of mould are still on the surface paint.
Answer: Problem is coming from above?
Is it possible water (or something) is coming down from above?  Those white rings look like something wet has come thru and dried, leaving behind what was dissolved in the water.  I am sad to say that I have seen those rings on my bathroom ceiling from leaky toilets one floor above.  Mine did not have white stuff though.
If water is coming from above there might be more serious problems deeper and that is what you are smelling.  Dried urine leaves white rings.  Rat urine does not smell like mildew.  I hope that is not the case.
Comment: If I just clean the white rings up could this remove the odour? Also could the leak/urine you have cited be the cause for the peeling in the first place?  Thanks
Comment: Whatever caused that peeling has been going on for a long time and it involves moisture.  My guess is white rings and peeling is related.   If it is coming from moisture inside the bathroom it will be obvious to you.  If it is coming from a space above the bathroom you will need to find out what is going on in that space, because you want it to stop!
Comment: Re cleaning it up to remove odoro - if you have a ceiling element soaked with animal urine to the point where the paint peels off, that ceiling element will have to be replaced.


Ryan Fait custom form elements plugin. Multiple CSS classes issues

Question: I'm using Ryan Fait's Custom form elements plugin http://ryanfait.com/resources/custom-checkboxes-and-radio-buttons/ for checkboxes and radio buttons styling.
<input type="checkbox" name="check" value="" class="styled" id="check" />
Check me!

Plugin finds input with .styled class, hides it and adds a  element instead.
This works fine until I add another CSS class to the input:
<input type="checkbox" name="check" value="" class="styled required" id="check" />
Check me!

In this case default input disappears but as I understand after this  element is not added and I only see the label. Looks like the plugin just can't find element with '.styled' class.
It' doesn't matter what class I add to the input before or after .styled class, so I\m sure it's not a CSS issue.
Does anybody have the same issue?
Thank you!
Answer: The problem was in the plugin.
If you are using Ryan Fait's Custom form elements and there is a need to add more classes to input element, the plugin must be edited.
What I did to fix this behavior is a next little change. I replaced this statement
inputs[a].className == "styled"

with this one
($(inputs[a]).hasClass("styled"))

in all cases. After this styling started working correctly.


How do I start a new game without going bankrupt?

Question: I have completed the game but didn't research large games until year 34. I feel like I've missed out on quite a few aspects of the game, therefore I want to start a new one. Now I know I could just run my company into the ground, but I want my guy to retire rich and happily (yes, I'm one of THOSE people) and it's very time consuming because I have 150 Million. Do you know how to start a new game without just going bankrupt on purpose?
Comment: You can mark the question as answered by clicking on the green mark, it will also reward the one who answered with rep. point.
Answer: Yes, you can simply press Esc and choose the "New" option:


MS Word VBA: I need a color palette dialog box

Question: In VBA for MS Word 2010, how can I get Word to bring up a color palette dialog box so the user can pick a color?

There are tons of examples on how to do it in Excel, but I haven't found any help for Word users. Here's the code for Excel:
Application.Dialogs(xlDialogPatterns).Show

Problem is, there's no wdDialogPatterns equivalent, nor can I find anything with a name that suggests a color palette dialog. I've found wdFormatBordersAndShading, but it's not quite the same: I want the user to select a color for later and repeated use.
Thanks!
Comment: Generally, any approach that works in Excel can also work in Word. Please provide information about how you do it in Excel using the EDIT link below your question.
Comment: Thanks. Did that above.
Answer: As far as I know Word does not have the same option as in Excel.
Instead you can call a Windows inbuilt solution via .dll.
I have recently created one in order to be able to pick more colors as text background color.
Fisrtly the Windows documentation where you can see all the options you can modify:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms646830(v=vs.85).aspx
Hint: CC_ANYCOLOR = 0x00000100 = &H100 (You need to use this form in VBA)
From my code example you can see how to implement it:
This goes top of Module:
Private Type CHOOSECOLORSTRUCT
   lStructSize     As Long
   hwndOwner       As Long
   hInstance       As Long
   rgbResult       As Long
   lpCustColors    As Long
   flags           As Long
   lCustData       As Long
   lpfnHook        As Long
   lpTemplateName  As String
End Type

Private Declare Function ChooseColor Lib "comdlg32.dll" _
   Alias "ChooseColorA" _
  (lpcc As CHOOSECOLORSTRUCT) As Long

This is the picker caller function with optionally submitted OriginalColor:
Public Function PickColor(Optional OriginalColor As Variant = 8421376) 'You can define any colour as default instead of 8421376)
    Dim cc As CHOOSECOLORSTRUCT
    Dim dwCustClrs(0 To 15) As Long

    With cc
        .Flags = &H100 Or &H1 Or &H2
        .lStructSize = Len(cc)
        .hwndOwner = 0
        .lpCustColors = VarPtr(dwCustClrs(0))
        .rgbResult = OriginalColor
    End With

    If CHOOSECOLOR(cc) = 1 Then
        PickColor = cc.rgbResult
    End If
End Function

And finally this is how you call it in action:
Sub F_HáttérSzínVálasztó()
    With Selection.Font.Shading
        .BackgroundPatternColor = PickColor(Selection.Font.Shading.BackgroundPatternColor)
    End With
End Sub

Comment: I was able to use this solution with Access 2016 (32 bit) when the old [Access 97 sample](http://access.mvps.org/access/api/api0060.htm) from Terry Kreft did not.  In a simplified manner it can be used like this:   `txtCtl.Properties("BackColor") = PickColor(Me.txtCtl.Properties("BackColor"))`
Answer: On x64 Word you must modify Ádám's code below as follows:
Option Explicit
Option Base 0

Private Type CHOOSECOLOR
  lStructSize As LongLong
  hwndOwner As LongPtr
  hInstance As LongPtr
  rgbResult As LongLong
  lpCustColors As LongPtr
  flags As LongLong
  lCustData As LongLong
  lpfnHook As LongLong
  lpTemplateName As String
End Type

Private Declare PtrSafe Function MyChooseColor _
    Lib "comdlg32.dll" Alias "ChooseColorW" _
    (ByRef pChoosecolor As CHOOSECOLOR) As Boolean

Public Function GetColor(ByRef col As LongLong) As _
    Boolean

  Static CS As CHOOSECOLOR
  Static CustColor(15) As LongLong

  CS.lStructSize = Len(CS)
  CS.hwndOwner = 0
  CS.flags = &H1 Or &H2
  CS.lpCustColors = VarPtr(CustColor(0))
  CS.rgbResult = col
  CS.hInstance = 0
  GetColor = MyChooseColor(CS)
  If GetColor = False Then Exit Function

  GetColor = True
  col = CS.rgbResult
End Function

Use the function for example with the TextColor property of a Font object:
Sub FontColorTest()
  Dim col As LongLong
  col = rgb(200, 100, 50)
  GetColor col
  Dim p As Word.Paragraph
  Set p = ActiveDocument.Paragraphs(1)
  p.Range.Font.TextColor.rgb = CLng(col)
End Sub

Please note, that the GetColor function requires a parameter of type LongLong whereas the TextColor.rgb property is of type Long.
Comment: Somehow if I want to select a color from the continuum on the right, I have to click on a basic color on the left first.


Windows Workflow Foundation and IIS ApplicationPool recycle (particularly after editing Web.config)

Question: I am involved in testing an ASP.NET MVC site that uses a WF service hosted as a separate site on the same IIS server.
We currently use Log4Net to assist with diagnostics in Stage and Production, so sysadmins are regularly setting the logging levels from WARN to DEBUG and back again for brief periods in order to capture logs.
I've noticed some strange behaviour with the WF service when the WF service's site's web.config is edited (or maybe I just don't understand WF well enough.) I understand that IIS watches the web.config and forces an AppPool recycle when it is modified, but what confuses me is, the WF service seems to hibernate until it next receives a service request. This means that all pending workflows which are waiting on timers will do nothing until the first service request post-AppPool-recycle and then all the ones that would have fired earlier will fire all at once.
I'm hoping this is just some simple config setting we've overlooked, but any help would be most appreciated, and feel free to give me an RTFM with link if so :)
Edit: Wow, no WF love on here. We've still got this issue sitting on the backburner, more important fish to fry but this problem still concerns me greatly.
Comment: Nothing after 2 days? :(
Answer: This is a problem with IIS. Basically IIS doesn't start up the app pool until a request is received for it. This will happen if web.config is modified but also if there are no requests to your site for a period of time (I think 10 minutes).
The solution to this is to "Warm up" IIS using this utility from Microsoft. It simulates the first request to make sure that the app pool is always running.
Hope this helps.
Comment: Cheers, that looks very interesting. I'm still intrigued as to how I missed this in all the WF docs I read through. Seems like such a critical piece of the puzzle.
Answer: Windows Server AppFabric has a WorkflowManagement Service which will restart the workflows after a recycle.


What are the best icons for cancel, delete and close?

Question: What's best icon for cancel, delete and close?
(i want define 1 icon per situation in my application)

i found 1,2 is cancel action what's different between 1,2? / or \ is right?

I have screen shot for use delete and cancel edit action
Comment: This is a graphic design question really as there's no other context or use case information provided in order to say whether one is more suitable for your situation than another, but I'd go for number 5 out of those options.
Comment: To clarify - you want one common icon to act for all three situations - cancel + delete + close?
Comment: As Katie said, we can't give you useful answers without more context. Can you elaborate on what you mean by "what's different between 1,2? / or \"? Our [FAQ](http://ux.stackexchange.com/faq#questions) also has advice on what makes a good question. Because it's not really answerable in its current form, I'm closing the question for now. If you decide to make improvements, let me know with an @ reply and we'll consider re-opening it.
Comment: Without knowing the context of the action and the interface you are using it on it is not possible to give you a qualified answer. Can you post some screenshots?
Comment: @3iscuit Welcome to UX Stack Exchange. To reply to someone, put an @ before their name at the beginning of your comment. That way they'll be notified of the reply.
Comment: Id love to answer this.  I clicked re-open.  The circle with the slash through it generally means "restricted" or "not allowed".  I find the circles with horizontal dash to be confusing because it often means open/close, not delete.  5 and 6 are much more universal, although depending on the situation you might use gray rather than red.  Red is generally meaning "destroy" and harsh.  A gray x might feel softer.  User Experience includes graphic design, so this question is perfectly rational to me.
Comment: @Patrick McElhaney may be my screenshot can make clearer question. What is best icon for this situation?
Answer: That's actually a question for google:
-> Delete
-> Cancel
-> Close
As you can see from the results, there is no real difference between the icons used for these actions (except maybe the trash can for delete).
Solution: Always use text with the icon (or use text only). The only exception I can think of is when the action is obvious from the context (like the close button on the top right or left of a window/dialog).
Hope that helps, Phil
Comment: @3iscuit: Not many icons are understood by all users and usually don't enhance usability. I'd recommend to read this: http://uxmyths.com/post/715009009/myth-icons-enhance-usability
Comment: And to the person who downvoted: A comment would be appreciated.
Comment: why we use icon and text? Is it duplicate?
Comment: Old, but just had same issue, so DELETE = TRASH / BIN, CLOSE or CANCEL = X or circle striked through.
Answer: It all depends on situation...
1, 2 — "No", "cancel"
4 — "Stop", may be used in alerts
5, 6 — "Delete", "cancel" if placed near some action, or "close" if placed on top corner of ui element.
Also minus icon is great for remove action.
Comment: He wants *one common icon* for *all* actions...
Comment: Yes - one common icon for all three was my interpretation of the bit in square brackets, but I might be wrong - its not *that* clear from the English. I'll ask to make sure.
Comment: What's different between 1,2?


SPClaimsAuthRoleProvider.GetUsersInRole(string roleName) encountered a role '0(.s|true' with unsupported original issuer type 'SecurityTokenService'

Question: Getting the following error message in the SharePoint 2010 ULS Logs when some custom code attempts to invoke SPUtility.GetPrincipalsInGroup():
SPClaimsAuthRoleProvider.GetUsersInRole(string roleName) encountered a role '0(.s|true' with unsupported original issuer type 'SecurityTokenService'.

Any ideas what would cause this? This is a Claims-Based-Authentication site and this code works fine on another server with Claims-Based-Authentication configured.
Answer: Still have no idea what causes this issue, but the role '0(.s|true' is NT AUTHORITY\authenticated Users on SharePoint 2010 and 'Everyone' on SharePoint 2013. Checking for this user and then avoiding the call to SPUtility.GetPrincipalsInGroup() if it is this user will allow you to avoid the issue.


is this bathroom mold a health hazard?

Question: Its all over the ceiling. Its really black spots everywhere and its because the awning windows (hinged at bottom) dont provide enough ventialition. The paint is cracking and pealing, i think its supposed to be water-resistant but no use. This is the third time this happened after redoing the ceiling.
Comment: Are you removing all the mold before repainting?  Or are you just repainting on top of it?  The paint failure is indicative of lousy or nonexistent paint prep.  Prep over glossy surfaces requires at least a modest effort in prep.
Answer: Though this doesn't seem to be much of a problem at the moment, it can get really bad if you don't take care of it. First, I suggest you clean it with normal soap and warm water, and then there are stronger liquids (or other sorts of detergents) you can use, but I think normal soap will do the trick (unless you'll repaint it later, then use strong detergents). But, this doesn't mean that this won't happen again. So you'll need to remove the moisture problem. Firstly, if possible, check if there are any water pipes inside the ceiling. If there are then make sure they're not leaking. Second, try to install a better ventilation system in your bathroom (i.e. air ventilator). Make sure you open doors and windows regularly or keep them always open.
Comment: Emphasis on ventilation system. Replacing an old ceiling vent (or installing one outright) will always help with keeping this room dry, even better than opening a window. (I can relate, my home was built without bath vents because of their qualifying openable windows).
Comment: Can you elaborate on why you believe this mold is likely to present a health hazard? I certainly agree that removal and cleaning should occur, though. FWIW, here is a CDC link on mold: https://www.cdc.gov/mold/stachy.htm
Comment: the apartment above me tends to allow leaking into our ceiling but i believe its a ventaliation problem because of the mold as i dont see any moisture on the ceiling.

is this bathroom mold a health hazard?


UIScrollView scrollRectToVisible:animated: not taking rect into account on iOS7

Question: [self.scrollView scrollRectToVisible:rect animated:YES];

Does anyone have a clue of why this works perfectly fine on iOS6.1 and on iOS7.0.4 always scrolls to the UITextField that has become firstResponder no matter what kind of rect I send as an argument?
CGRect rect = CGRectMake(0, self.scrollView.frame.size.height - 1, 320, 1);
[self.scrollView scrollRectToVisible:rect animated:YES];

This code will scroll the UIScrollView to its bottom when the keyboard is showed due to a UITextField inside the UIScrollView has become first responder on iOS6.1 but on iOS7.0.4 it is scrolled so that the UITextFiled is visible instead.
As I figure this, the UIScrollView in the iOS7 SDK no matter what, autoscrolls to whatever has become the first responder inside of it when scrollRectToVisible:animated: is called.
Comment: @staticVoidMan the UIScrollView scrolls when I call its scrollRectToVisible:animated: method and on iOS6 this will scroll the UIScrollView to the specified rect but on iOS7 it scrolls to whatever UITextField that has become first responder and not to the specified rect.
Comment: Have you tried saving the current visible rectangle, then disabling animations, setting first responder, then scrolling back to the original rect, re-enabling animations then calling your scrollRectToVisible?
Comment: I haven't come across a `UIScrollView` auto-scrolling to the `firstResponder`. Are you sure or am I misunderstanding your question? check your `UITextFieldDelegate`s and ensure you aren't manually scrolling to the current `textField`
Comment: No @Putz1103, I haven't made any effort doing this in another way because it works as supposed to on iOS6. Kind of waiting for iOS updates to fix this on iOS7.
Comment: @HenrikHolmgren : then there's something fishy. one thing is certaian... the issue doesn't lie in the code you have provided in the question.
Comment: Have you checked the `contentSize` property?
Answer: I suspect that most of you developers are using scrollRectToVisible:Animated: in conjunction with system keyboard notifications as explained in the Apple Docs here. For me the sample code provided by Apple didn't work (well, only half of it did).
Putting the method call inside a dispatch block fixed the problem for me:
dispatch_async(dispatch_get_main_queue(), ^{
    [self.scrollView scrollRectToVisible:rect animated:YES];
});

I don't fully understand why this works and I'm not sure if this is 100% safe but on the other hand it feels a lot safer than just delaying the call by 0.1 seconds as suggested in another answer by Rikkles.
I'm not an expert on threading issues (yet) but it seems like whatever hidden system method is overriding the scrolling behavior is already on the main queue when the UIKeyboardDidShowNotification is sent. So if we put our method call on the main queue as well it will be executed afterwards and therefor yield the desired effect. (But that's only a guess.)
Comment: This worked for me as well.I had three textfields in a scrollview out of which the first one was working well always.The other two were behaving weird.Was stuck on this.Thanks man.
Answer: On iOS 8 (and possibly 7), the OS autoscrolls to the UITextField at the tail end of the runloop operation, just before it goes back to listening to user input.
I haven't found any way to get in after the OS autoscroll and before the user input. Neither UIKeyboardWillShowNotification nor UIKeyboardDidShowNotification are hooks that will work.
However, what will always work is the good old trick of performing a selector after delay. Simply put the scrolling code in its own method, and call that method like this:
- (void)keyboardDidShow:(NSNotification*)aNotification {
  // ... all code to choose the view you want ...
  [self performSelector:@selector(moveToView:) withObject:visibleView afterDelay:0.1];
}

- (void)moveToView:(UIView *)aView {
  [self.scView scrollRectToVisible:aView.frame animated:YES];
}

And that will run after the OS autoscrolls, and you're golden.
Comment: @Rikkles +1 for you. Great answer.. Helped a lot. Saved so much time. THANKS..!!!
Answer: I met this problem before. Not an easy one, but boring for sure.
It was because I set contentSize to 0 (because you don't want it to scroll). And you should set at least 1.
[scrollView setContentSize: CGSizeMake(1, self.view.frame.size.height)];

I hope it's the solution ;)
Answer: I found a solution to this problem, but it is not a pretty one. In order to scroll the scrollview to the desired location, u must register for both the keyboardWillShow and keyboardDidShow notifications. Then code to set the scrollview's insets is placed in the keyboardWillShowNotification's observer's selector and the code to scroll the scrollview to the desired location is placed in the keyboardDidShowNotification's observer's selector. Here is what I have:
Inside viewDidLoad:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];

Notification Methods:
- (void) keyboardWillShow: (NSNotification*) aNotification;
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    float kbHeight = kbSize.height < kbSize.width ? kbSize.height : kbSize.width;
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbHeight, 0.0);
    _scrollView.contentInset = contentInsets;
    _scrollView.scrollIndicatorInsets = contentInsets;
}

-(void)keyboardDidShow:(NSNotification*)notification
{
    CGRect aRect = CGRectMake(0, 0, _scrollView.frame.size.width, _scrollView.frame.size.height - _scrollView.frame.origin.y - self.scrollView.contentInset.bottom);
    CGRect scrollFrame = CGRectMake(self.loginView.frame.origin.x + self.loginButton.frame.origin.x, self.loginView.frame.origin.y + self.loginButton.frame.origin.y, self.loginButton.frame.size.width, self.loginButton.frame.size.height);
    if (!CGRectContainsRect(aRect, scrollFrame)) {
        [_scrollView scrollRectToVisible:scrollFrame animated:YES];
    }
}

Comment: This doesn't work any more (maybe it did earlier, but on iOS 8 it fails)
Answer: I was following the Apple docs but with no success. Then I tried calling setContentOffset(_:animated:) on my scrollView, instead of scrollRectToVisible(_:animated:), and that made it work.
The code below scrolls to myView if it is hidden under keyboard, supposing you call keyboardWillShow function when you receive a UIResponder.keyboardWillShowNotification.
Swift 5
@objc private func keyboardWillShow(_ notification: Notification) {
    if let keyboardHeight = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.size.height {
            scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardHeight, right: 0)

        let visibleViewFrame = myView.frame
        var scrollViewFrame = scrollView.frame
        scrollViewFrame.size.height -= keyboardHeight

        if !scrollViewFrame.contains(visibleViewFrame) {
            scrollView.setContentOffset(CGPoint(x: 0, y: visibleViewFrame.origin.y), animated: true)
        }
    }
}


Is there a way to round numbers into a reader friendly format? (e.g. $1.1k)

Question: Much like the Stackoverlow reputation rounding, I'm hoping to do the same thing with currency
$1,000 => 1k
$1,000,000 => 1m
How can I achieve this in JavaScript (preferably in jQuery)?
Comment: Thanks guys -- as you can see I'm new to Stack Overflow.  I'm excited that you all think this is an interesting problem!
Comment: This currently doesn't qualify as an acceptable code-golf question. see
http://meta.stackexchange.com/questions/24258 You need a few more test cases, to make it community wiki and finally you should accept the shortest (in code size) answer. Single language code-golfs are boring, you should also open it to other languages
Comment: David created a [code-golf] version: http://stackoverflow.com/questions/2692323/code-golf-friendly-number-abbreviator
Answer: Here is a simple function to do it:

function abbrNum(number, decPlaces) {
  // 2 decimal places => 100, 3 => 1000, etc
  decPlaces = Math.pow(10, decPlaces);

  // Enumerate number abbreviations
  var abbrev = ["k", "m", "b", "t"];

  // Go through the array backwards, so we do the largest first
  for (var i = abbrev.length - 1; i >= 0; i--) {

    // Convert array index to "1000", "1000000", etc
    var size = Math.pow(10, (i + 1) * 3);

    // If the number is bigger or equal do the abbreviation
    if (size <= number) {
      // Here, we multiply by decPlaces, round, and then divide by decPlaces.
      // This gives us nice rounding to a particular decimal place.
      number = Math.round(number * decPlaces / size) / decPlaces;

      // Handle special case where we round up to the next abbreviation
      if ((number == 1000) && (i < abbrev.length - 1)) {
        number = 1;
        i++;
      }

      // Add the letter for the abbreviation
      number += abbrev[i];

      // We are done... stop
      break;
    }
  }

  return number;
}
console.log(abbrNum(1200, 3))

Outputs:
abbrNum(12 , 1)          => 12
abbrNum(0 , 2)           => 0
abbrNum(1234 , 0)        => 1k
abbrNum(34567 , 2)       => 34.57k
abbrNum(918395 , 1)      => 918.4k
abbrNum(2134124 , 2)     => 2.13m
abbrNum(47475782130 , 2) => 47.48b

Demo: http://jsfiddle.net/jtbowden/SbqKL/
Comment: `function a(n,d){x=(''+n).length,p=Math.pow,d=p(10,d);x-=x%3;return Math.round(n*d/p(10,x))/d+" kMGTPE"[x/3]}` --- Sufficiently Golfed (108)? :)
Comment: this feels golfy. how small can we get this function?
Comment: http://stackoverflow.com/a/25612036/1729885
Comment: `abbrNum(999950, 0) => 1000k`, yeah it only happens 50 / 1M times but still.
Comment: @crizCraig: Good catch!  I added a special case handler for that in the code.  There is probably a more efficient way to do it, but it works for now.
Comment: FUND IT.

Seriously though, I'd love to see that in a golf thread.
Comment: @ Damien Wilson: Code-golf tag added. What do you mean by fund?
Comment: @Baloney: I was just making it flexible.  Do what is best for your application.  An "appropriate cut-off" point is often subjective and/or application specific.
Comment: Code golf version posted [here](http://stackoverflow.com/questions/2692323/code-golf-number-formatter). For contributing members of OP question: feel free to change the parameters of the question...I had a difficult time deciding the limitations/boundaries.
Comment: **104 bytes** `function(a,b,c,d){c=(''+a).length;d=Math.pow;b=d(10,b);return((a*b/d(10,c-=c%3))+.5|0)/b+' kMGTPE'[c/3]}`
Comment: I have an optimised version of the above code in objective C over here. http://stackoverflow.com/a/35742809/1920799.    ...   .... @JeffB : your method doesn't work for negative numbers. you need to use the following   .....       if(size <= Math.abs(Math.round(number)))   .....

instead of .....
if(size <= number) .........

Which has an extra benefit of removing your code block of 'Handle special case where we round up to the next abbreviation'
Comment: can without round ?  abbrNum(1432, 1); => 1.4k;  abbrNum(1992, 1); => 1.9k
Comment: @padavan Just change the `Math.round` above to `Math.floor`.
Answer: var floor=Math.floor, abs=Math.abs, log=Math.log, round=Math.round, min=Math.min;
var abbrev = ['k', 'Mil', 'Bil']; // abbreviations in steps of 1000x; extensible if need to edit

function rnd(n, precision) {
    var prec = 10**precision;
    return round(n*prec)/prec;
}

function format(n) {
    var base = floor(log(abs(n))/log(1000));
    var suffix = abbrev[min(abbrev.length-1, base-1)];
    base = abbrev.indexOf(suffix) + 1;
    return suffix ? rnd(n/1000**base,2)+suffix : ''+n;
}

Demo:
> tests = [-1001, -1, 0, 1, 2.5, 999, 1234,
           1234.5, 1000001, 10**9, 10**12]
> tests.forEach(function(x){ console.log(x,format(x)) })

-1001 "-1k"
-1 "-1"
0 "0"
1 "1"
2.5 "2.5"
999 "999"
1234 "1.23k"
1234.5 "1.23k"
1000001 "1Mil"
1000000000 "1Bil"
1000000000000 "1000Bil"

Comment: This one is the best since it works with negative numbers too
Comment: @shrekuu: seems to be passed just fine as `round`ing to two decimal places in  `round(n/pow(...), 2)`; feel free to clarify
Comment: Oh sorry my bad. Failed to read it more carefully. I will delete my previous comment to avoid misleading.