SSRS - Sort by Colors

Question: I am trying to sort a column in SSRS by the Font Color of that column, but am unable to grasp how... The color code that I have developed works as such.
<code>=Switch(Fields!Prk_name.Value = "Lot 1", "DarkGoldenrod",
        Fields!Emp_default.Value = "L" OR Fields!Emp_default.Value = "B", "Black",
        Fields!Emp_default.Value = "C" AND Fields!Perm_prk.Value = "Y", "Green",
        Fields!Emp_default.Value = "C", "Purple")
</code>
What I was think of running under the SortExpression is this:
<code>=Switch(Fields!Name.Color = "DarkGoldenrod" SortExpression (),
        Fields!Name.Color = "Black" SortExpression (),
</code>
So on and so forth just don't know what to put for SortExpression? I would need a way to sort for all 4 color types the base form of this is group by color then sort ABC.
Chris Lätta's post gave me an idea I gave that a try still does not work, but it might help to narrow down what I am looking for.
<code>=Switch(Fields!Name.Color = "Darkgoldenrod", 1,
    Fields!Name.Color = "Purple", 2,
    Fields!Name.Color = "Black", 3,
    Fields!Name.Color = "Green", 4,
    True, 5)
</code>
Answer: Just sort by a number as your first sort expression:
<code>=Switch(Fields!Prk_name.Value = "Lot 1", 1,
    Fields!Emp_default.Value = "L" OR Fields!Emp_default.Value = "B", 2,
    Fields!Emp_default.Value = "C" AND Fields!Perm_prk.Value = "Y", 3,
    Fields!Emp_default.Value = "C", 4,
    True, 5)
</code>
then add another sort criteria to sort by the ABC column.
Comment: This did not work, still does not sort based on the Font color.
Comment: Would it be possible to do the ORDER BY Column.Color or something like this in Dataset query?

SSRS - Sort by Colors


Will 1x4 or 1x6 boards span 3 feet between beams for a walking bridge?

Question: I have a foot bridge I wish to plank with 1x4 or 1x6 material. The bridge is 3' wide.  The planks will be simply supported at each end by 4" beams. Will a 1x4 or a 1x6 3' long support a 200 pound load?
Comment: You say "plank" but the plank is generally the top - ie walking - surface of the bridge.  I think you mean cross-beam?
Answer: The boards will flex something awful, which makes for an unpleasant walking experience. Tying them together with an unsupported stringer in the middle will make things quite a bit less wobbly. If the bridge is short then an X-shaped brace between the beams will give you much better support with the same look.
I personally would opt for the 1x4 if all other things were equal. Three feet is a really wide span for rotten or insect-damaged boards. Falling through a floor all the way to your hip is hilarious for everyone who sees it, but not an experience I'd be keen to repeat. With a 4" board any way you stand you're spanning two of them.
Answer: This all seems like "opinion-based" answers.
Okay, I'll give one more "opinion-based" answer. The op's question is, "...will 1x4 or 1x6 that is 3' long support 200 lbs.?"
Structural calculations are based on "ultimate design" or "working stress design".
When using ultimate design (or failure) we then calculate a "safety factor" into the calculations. Depending on the structural element we'll use a higher or lower factor, (say:1.5 for common area floors and 2.2 for critical beams.)
Working stress design has a safety factor already calculated into the equations.
Unfortunately, I don't know of a safety factor for "bridges".  (FIU bridge designers evidently don't either.)
Hmmm...so, based on experience, I wouldn't use anything less than a 2x material. If the material is cedar or redwood, which is good for exterior use, (but weaker than other species,) or if it's pressure treated material (which looses its strength when pumped full of pressure treatment liquid), only 2x material will support 200 lbs. (BTW, the op didn't say 200 lbs. per square foot...just 200 lbs. for a 1x4 or 1x6. )
Also, all grading rules allow some "non-compliant" material to be included. So, if you choose one of those boards, they will fail.
Comment: I agree with your grading comment I see #2 stamped wood all the time that I would not trust for use in the bridge. In years past the wood had many more "rings" the minimum today is 4 per inch if memory serves.
Answer: 1x4's will flex more than 1x6 material. As to whether it can support a 200 pound load is up in the air because we have no idea what type of material you are using. Oak boards would hold more than fir boards which in turn will be able to support more than soft pine boards.
Another thing to consider is that often time a bridge structure is built with the support beams closer together than the full width of the bridge tread boards. This has the decided advantage of letting the boards support more because the span between the beams is less. The boards overhang some but can still support the load near the ends. For say a 3 foot wide tread let them overhang the beams by 3.5 inches on each end. If you have 4x4 posts bolted to the side of the beam that extend up for a safety/hand rail just notch the boards around the posts.
Comment: Where does one find clear 2x4s?
Comment: Although I kind of agree I would never use less than a. Clear 2×4 depending on the type of support and conditions I might even want more substantial planking. I have repaired an old steel cable foot bridge long ago we had a tough time because of limited $  we used rough fir that was soaked in cresode, that lasted many years close to 20 before some planks needed replacing. It was easy to see the boards that had to be replaced because they were treated with copper as cresode was not legal in California any longer. They did use a rolled roofing on the planks and sealed the nails with black Jack.
Comment: They can be had at mills that cut larger trees, my mill cuts small trees so not many boards we cut are clear hull oaks lumber? Spelling?,  still cuts large logs and they do have a larger price tag but the tighter grain and clear wood is worth the extra $ for projects that have flex, we had a cable bridge at our last farm that could support a horse and rider we used it as a schooling device for mountain trail competition this was built from for. Mary's lumber has cedar but it is even more expensive. So it is out there I just happen to know a few since I am close and use their products.
Answer: Five-quarter decking is much more appropriate for that span, and even that is still a bit light. Two-by decking is much better.
Regardless, run a floating rail down the center and screw each deck board to it with two screws. This will spread the load to adjacent deck boards and prevent most of your flex.
The bottom line is that pressure-treated one-by boards are probably more expensive than PT 5/4 decking anyway. I would certainly  not use untreated one-by boards. They'll be rotting and (more) dangerous within a few years.


Cannot Instantiate the Type T

Question: I have a class that looks like this...
public class LegionInputFormat
        extends FileInputFormat<NullWritable, LegionRecord> {

    @Override
    public RecordReader<NullWritable, LegionRecord>
            createRecordReader(InputSplit split, TaskAttemptContext context) {

        /* Skipped code for getting recordDelimiterBytes */

        return new LegionRecordReader(recordDelimiterBytes);
    }
}

I'd like to use a generic type so it could return any type of RecordReader specified by the user, like so:
public class LegionInputFormat<T extends RecordReader<NullWritable, LegionRecord>>
        extends FileInputFormat<NullWritable, LegionRecord> {

    @Override
    public RecordReader<NullWritable, LegionRecord>
            createRecordReader(InputSplit split, TaskAttemptContext context) {

        /* Skipped code for getting recordDelimiterBytes */

        return new T(recordDelimiterBytes);
    }
}

As the post title suggests, I'm being told I "cannot instantiate the Type T." From other Stack Exchange posts, I've gathered that this is not possible due to something with how generics work. What I've not been able to gather is an intuitive explanation of why that's the case. I learn best by understanding, so that would be really helpful if somebody can offer it.
I'm also interested in the best practice for accomplishing what I'm looking to do here. Should the constructor for LegionInputFormat accept a RecordReader class, store that, and then reference it later to create a new instance? Or is there a better solution?
(Additional background - context here is Hadoop, but I doubt it matters. I'm a fairly accomplished Data Scientist, but I'm pretty new to Java.)
Comment: The compiler has no way of knowing whether `T` has a constructor that accepts `recordDelimiterBytes` as argument.
Comment: At compile time, `T` gets replaced by `java.lang.Object`. **Not** `LegionRecordReader`.
Comment: [Type Erasure](https://docs.oracle.com/javase/tutorial/java/generics/erasure.html).
Comment: I'm not sure why that prevents this, though? So, at compile time, `T` gets replaced by `LegionRecordReader` or any other `RecordReader` class I specify... Why does that prevent `return new T` from becoming `return new LegionRecordReader` at compile time?
Comment: I have once or twice solved a similar problem with an abstract factory method that would create the `T` for me. It just requires the users of the class to make a little specialization implementing the factory method with that line, `return new LegionRecordReader(recordDelimiterBytes);`.
Comment: Possible duplicate of [Instantiating generics type in java](http://stackoverflow.com/questions/2434041/instantiating-generics-type-in-java).
Answer:
As the post title suggests, I'm being told I "cannot instantiate the Type T." From other Stack Exchange posts, I've gathered that this is not possible due to something with how generics work.

This is because generics in Java are purely a compile-time feature; the compiler throws away the generics (this is called "type erasure") so that at runtime, there is no such thing as a type variable T, so you cannot do new T(...).
You can do this in Java by passing a Class<T> object to the method that needs to create an instance of T, and then creating an instance through reflection.
Comment: It's not being replaced by `XRecordReader` at compile time, but by `Object`. For example, a `List` just looks like a raw `List` that contains any kind of `Object` at runtime.
Comment: @JohnChrysostom That would mean a separate version of the method would have to be made for every `T` that's used with it, i.e. it becomes a template. With erasure, you only need 1 version of the method. It's simply a design choice, that also happens to be backwards compatible.
Comment: "there is no such thing as the type variable T at runtime." That really helps the type erasure explanation click for me. If T is being replaced by `XRecordReader` at compile time, why isn't it also replaced in `return new T` at compile time?
Answer: In your second code example the compiler has no way of knowing whether T has a constructor that accepts recordDelimiterBytes as argument. This is so because each class is a separate compilation unit, so when LegionInputFormat is compiled, the compiler only knows that T is a RecordReader<NullWritable, LegionRecord>. It doesn't know which concrete types are used for T, and it has to assume that someone at a later time can stick in any class that extends RecordReader<NullWritable, LegionRecord>. We can tell the compiler something about T using extends, but there is no way in Java that we can specify that T has a constructor T(byte[]) (or whatever the type of recordDelimiterBytes is).
I have used the following solution a couple of times, and even though it requires creating subclasses, I am quite happy with it. The work is still within the generic class. It is now declared abstract:
public abstract class InputFormat<T extends RecordReader<NullWritable, LegionRecord>>
        extends FileInputFormat<NullWritable, LegionRecord> {

    private byte[] recordDelimiterBytes;

    @Override
    public RecordReader<NullWritable, LegionRecord> createRecordReader(InputSplit split, TaskAttemptContext context) {

        /* Skipped code for getting recordDelimiterBytes */

        return constructRecordReader(recordDelimiterBytes);
    }

    // factory method for T objects
    protected abstract RecordReader<NullWritable, LegionRecord> constructRecordReader(byte[] recordDelimiterBytes);
}

For instantiation it requires you write a concrete subclass with just these few lines:
public class LegionInputFormat extends InputFormat<LegionRecordReader> {

    @Override
    protected RecordReader<NullWritable, LegionRecord> constructRecordReader(byte[] recordDelimiterBytes) {
        return new LegionRecordReader(recordDelimiterBytes);
    }

}

In the subclass we know the concrete class of T and therefore the class' constructor/s, so we can instantiate it. Though not quite as simple as you might have hoped for, I consider the solution nice and clean.
In my own code I have taken the opportunity to declare the factory method as returning type T:
protected abstract T constructRecordReader(byte[] recordDelimiterBytes);

Then you just have to follow up in the implementation:
protected LegionRecordReader constructRecordReader(byte[] recordDelimiterBytes) {

In this case it even gets a few chars shorter. On the other hand, in your case you don't seem to need it, so you may prefer to stay with the weaker return type of RecordReader<NullWritable, LegionRecord>.

Cannot Instantiate the Type T


How do I capture a regex greedily based on a different situation?

Question: Currently, I am trying to implement string interpolation for my language.
The string interpolation looks something like this:
let x = " Baby"
let message = "Hello $(x)"

My current regex to capture interpolated expression is:
const regex = /[$][(].*?[)]/g;

However, the regex above works well with non-bracketed expressions, but it does not work properly when the interpolated expression have brackets, for example:
let message = "My number is $(square(1+2))"
// the captured group would be `$(square(1+2)` , which is missing a bracket

I could not use greedy quantifiers. If not it will not work when there is more than one interpolated expression, such as:
let message = "My number is $(x) $(y) $(z)"
// if capture greedily, it would be `$(x) $(y) $(z)`, which is not desired

How do I greedily capture interpolated expressions based on situations?
Note: I'm looking for answer in JavaScript.
Comment: I don't think even the new ES 2018 features add support for balanced capture or any other scheme for capturing things like that in a single run of the expression - I feel fairly confident you'll be well served to build a stateful parser that will find a `$(` then either the next `(` (and parse it further as a nested expression), or a `)` to signal the end of each nested expression
Comment: You really should attempt some minimal level of parsing.  Not everything is meant to fit inside a single regex.
Comment: In JS regex, you cannot match nested brackets.
Comment: I will say that if you know you only need to support nesting 2 or 3 deep (or maybe even up to 10? -- if you're really masochistic) then you can create multiple regex expressions for each case you want to support. But matching expressions with arbitrary nesting depth is prone to failure in countless ways in JavaScript
Comment: @JayC Yeap, I will try it because it does not seems too hard actually.
Comment: If these strings are separated by at least 1 whitespace then you may be able to use this regex: `/\$\(\S*\)/g`
Answer: You can use template string (or literal string) like this

let x = 1, y = 2, z = 3;
console.log(`Mu number ${x} ${y} ${z}`);
Comment: Why do you need to re-implement it? it's a javascript core structure, always safer than your (or mine) code
Comment: different...but same :)   they are both hight level languages. think about that
Comment: Thanks for answering, but your answer is too off-topic, because I was asking how to implement string interpolation, not how to use it.
Comment: Because I am creating my own programming language  my friend.
Comment: so, you can't do it with only regex. You have to implement an algorithm.. and you need to study regular language theory :)  and only a suggestion, i would not use js to implement an other languages.. few years i tried to do that by using c++
Comment: Actually I use TypeScript, which is a superset of JavaScript with strong typing and discriminated unions.
Answer: Updated regex what you created, this will allow you to capture the second bracket it is there. Please find the following regex, btw I am not able to understand the third scenario. Test this regex and let me know if it fulfills your reqt. If not then elaborate on the third scenario and I will update my regex.
For scenario 3:
'[$][(].*?[\)]+' will capture '$(x)' '$(y)' '$(z)' differently. Mean to say match individually.
'[$][(].*[\)]+' will capture '$(x) $(y) $(z)' as one string. Whole string.
Please let me know if it works.


Reading from file not fast enough, how would I speed it up?

Question: This is the way I read file:
    public static string readFile(string path)
    {
        StringBuilder stringFromFile = new StringBuilder();
        StreamReader SR;
        string S;
        SR = File.OpenText(path);
        S = SR.ReadLine();
        while (S != null)
        {
            stringFromFile.Append(SR.ReadLine());
        }
        SR.Close();
        return stringFromFile.ToString();
    }

The problem is it so long (the .txt file is about 2.5 megs). Took over 5 minutes. Is there a better way?
Solution taken
    public static string readFile(string path)
    {

       return File.ReadAllText(path);

    }

Took less than 1 second... :)
Comment: I'd hope it would take rather a lot less than 1 second. 2.5MB really is a very small amount of data...
Comment: I know, I had an infinite loop this is why it took so long, time to take a break I think :D
Answer: S = SR.ReadLine();
while (S != null)
{
    stringFromFile.Append(SR.ReadLine());
}

Of note here, S is never set after that initial ReadLine(), so the S != null condition never triggers if you enter the while loop.  Try:
S = SR.ReadLine();
while (S != null)
{
    stringFromFile.Append(S = SR.ReadLine());
}

or use one of the other comments.
If you need to remove newlines, use string.Replace(Environment.NewLine, "")
Comment: actually, wouldn't this miss the first line of the file?
Comment: You are right +1 too. Thx, this is the reason it took so long. I took some code on the web and try to clean it up. My mistake!
Answer: Leaving aside the horrible variable names and the lack of a using statement (you won't close the file if there are any exceptions) that should be okay, and certainly shouldn't take 5 minutes to read 2.5 megs.
Where does the file live? Is it on a flaky network share?
By the way, the only difference between what you're doing and using File.ReadAllText is that you're losing line breaks. Is this deliberate? How long does ReadAllText take?
Comment: Off topic, but Jon, I enjoyed your appearance on Dot Net Rocks.
Comment: @Giovanni: Great - it was a lot of fun, if somewhat nerve-wracking.
Answer: return System.IO.File.ReadAllText(path);

Answer: Marcus Griep has it right.  IT's taking so long because YOU HAVE AN INFINITE LOOP.  copied your code and made his changes and it read a 2.4 M text file in less than a second.
but I think you might miss the first line of the file.  Try this.

S = SR.ReadLine();
while (S != null){
    stringFromFile.Append(S);
    S = SR.ReadLine();
}

Answer: Do you need the entire 2.5 Mb in memory at once?
If not, I would try to work with what you need.
Comment: This is good advice.  I had a colleague who seemed to think he needed an entire 300+MB XML file in memory at once.  Didn't work too well.
Comment: I once tried to read a 500+ MB XML file into a DOM. Needless to say, it didn't work. It sat there for like minutes before throwing an OutOfMemoryException. I did some research and found that a DOM uses four to ten times as mach memory as the as the size of the XML-file. In end I used a hybrid: an XmlTextRead to create "domlet" for each "record". "Less is more" is usually good programming advise.
Answer: Use System.IO.File.RealAllLines instead.
http://msdn.microsoft.com/en-us/library/system.io.file.readalllines.aspx
Alternatively, estimating the character count and passing that to StringBuilder's constructor as the capacity should speed it up.
Answer: Try this, should be much faster:
var str = System.IO.File.ReadAllText(path);
return str.Replace(Environment.NewLine, "");

Comment: Faster than System.IO.File.ReadAllText(path);?
Comment: @Daok: You're right. My point was the use of `Replace`. I overlooked the easier solution.
Answer: By the way: Next time you're in a similar situation, try pre-allocating memory. This improves runtime drastically, regardless of the exact data structures you use. Most containers (StringBuilder as well) have a constructor that allow you to reserve memory. This way, less time-consuming reallocations are necessary during the read process.
For example, you could write the following if you want to read data from a file into a StringBuilder:
var info = new FileInfo(path);
var sb = new StringBuilder((int)info.Length);

(Cast necessary because System.IO.FileInfo.Length is long.)
Answer: ReadAllText was a very good solution for me. I used following code for 3.000.000 row text file and it took 4-5 seconds to read all rows.
string fileContent = System.IO.File.ReadAllText(txtFilePath.Text)
string[] arr = fileContent.Split('\n');

Answer: The loop and StringBuilder may be redundant; Try using
ReadToEnd.
Answer: To read a text file fastest you can use something like this
public static string ReadFileAndFetchStringInSingleLine(string file)
    {
        StringBuilder sb;
        try
        {
            sb = new StringBuilder();
            using (FileStream fs = File.Open(file, FileMode.Open))
            {
                using (BufferedStream bs = new BufferedStream(fs))
                {
                    using (StreamReader sr = new StreamReader(bs))
                    {
                        string str;
                        while ((str = sr.ReadLine()) != null)
                        {
                            sb.Append(str);
                        }
                    }
                }
            }
            return sb.ToString();
        }
        catch (Exception ex)
        {
            return "";
        }
    }

Hope this will help you. and for more info, please visit to the following link-
Fastest Way to Read Text Files


If $\lim_{t\to\infty}\gamma(t)=p$, then $p$ is a singularity of $\gamma$.

Question: I'm trying to solve this question:

Let $X$ be a vectorial field of class $C^1$ in an open set
  $\Delta\subset \mathbb R^n$. Prove if $\gamma(t)$ is a trajectory of
  $X$ defined in a maximal interval $(\omega_-,\omega_+)$ with
  $\lim_{t\to\infty}\gamma(t)=p\in \Delta$, then $\omega_+=\infty$ and
  $p$ is a singularity of $X$.

The first part is easy because $\gamma$ is contained in a compact for a large $t$, my problem is with the second part, I need help.
Thanks in advance
Comment: Just a guess ... Could you say that once you know that $\lim_{t\to\infty}\gamma(t)=p$ then $\gamma(t)-p=c_1\exp(-c_2t)$ with $c_1,c_2$ constants and $c_2>0$, and then, since $X$ at $\infty$ is the derivative of $\gamma(t)$ at $\infty$, then you have that $\dot \gamma(t)=-c_1\exp(-c_2t)$, which evaluated at $t=\infty$ gives the desired result???
Answer: For $n \geq 0$, let $t_n \in (n,n+1)$ such that $\gamma'(t_n)=\gamma(n+1)-\gamma(n)$ (use mean value theorem).
Then $\gamma'(t_n)=X(\gamma(t_n)) \underset{n \to + \infty}{\longrightarrow} X(p)$ and $\gamma'(t_n) \underset{n \to + \infty}{\longrightarrow} p-p=0$. Thus $X(p)=0$.


Is it ok to use text area for multiple subjects?

Question: When user is answering question with radio buttons that opens new more specific questions. Is it bad idea to wrap those questions in one text area?
In my case user want might add multiple "compensations" so if used text fields there should be feature that enables adding multiple different "compensations". With text area there's no need for that feature because user can add all the information in one field.
I think text fields would be more clear in many case but in this one it might be better to use text area, or what you think?
Comment: Well, why not just have one single text area that does the whole form? Answer that, and you will have your answer.
Comment: Thanks for answer! I forgot explain that text fields/area shows up when user clicks yes. Radio button question would be mandatory and after user answers yes text fields/area shows up. If you meant to use only text area that should be optional? And in that case user could skip that question.
Answer:
user want might add multiple "compensations"

Assuming the field(s) are optional. In that case, better to have one Textarea instead of multiple text fields.
Reason:
People usually don't like too many question fields for a single reason :). I am also thinking you might want to rename the label to something generic like "Please explain" instead of "What, where, and when".
Comment: Thanks for answer! "Please explain" might be too open but good idea to rethink label.


Apache Pulsar - acknowledge from different thread

Question: I've spun up a Pulsar Java consumer in thread T1 and I'm handing over the messages for processing to thread T2.
Is it safe to acknowledge messages from T2? Specifically, is calling consumer.acknowledge(messageId) on the instance shared between two threads ok?
Comment: Good question. We would like to do a simimar setup in our project as well.
Answer: Yes, the java client is thread safe, so the interaction you described should be fine.
Comment: @MilosGregor every class in the Pulsar Java client is thread safe. We will make it more explicit in the Javadocs
Comment: Do you have some reference? The javadoc seems rather brief and the [documentation][1] not explicit enough.

  [1]: https://pulsar.incubator.apache.org/docs/latest/clients/Java/#Consumers-j8vfvs]


What is the cheapest way to get the Showroom award in GTA Online?

Question: I want to get the Showroom platinum award in GTA Online.  I'm wondering what is the cheapest way to do so.  Which cars, buildings, and mods do I need to buy and how much is the minimum price of this award?
Edit: I'm specifically playing on Xbox 360.  But I'd be willing to try answers for any system.
Answer: On the PS4, you cannot steal modded cars for it to count. Unlike in PS3.
PS4 - The best way to do this is to buy Rebels, and many of them. Do a basic suspension, transmission (etc) overhaul. No need to change the paint, unless you want to.
PS3 - On the PS3 you can actually steal modded cars and it will be counted. Although, it is a good idea if you add a cheap carbon spoiler on it or something, just to seal the deal. Apart from stealing, you can also buy Karin Rebels just like in PS4.
Hope it helped.
Answer: So I just finished The Showroom award and this was the list I came up with.
TLDR: If you just order 30 Elegy RH8s and can store them all, you should get the award.
Properties
You need three properties with 10 car garages to store all 30 cars.  The three cheapest properties with 10 car garages are:

1623 South Shambles St - Garage - 105,000
1337 Exceptionalist Way - Garage - 112,500
Unit 76 Greenwich Parkway - Garage - 120,000

Property total just garages: 337,500
I'm going to assume that someone would want at least one high rise apartment in order to do Heists and other things.  So instead of the most expensive garage, you'd buy the cheapest 10 car apartment:

1623 South Shambles St - Garage - 105,000
1337 Exceptionalist Way - Garage - 112,500
Del Perro Heights, Apt 7 - Apartment - 200,000

Property with apartment: 417,500
Cars
You need 30 cars total and I see 3 different sources for getting these cars.
One source is getting Elegy RH8s which are free on consoles if you sign up for the social club.  Plus, they already count as "modded" which will help in the next section.  Unfortunately, if you are on PC, they cost 95,000 and the total will jump up to 2,850,000.
The other two options are stealing cars or buying Karin Rebels.

Elegy RH8 - 30*0 (on consoles) = 0
Stealing Cars - 30*0 = 0
Karin Rebel - 30*3,000 = 90,000

Mods
If you have Elegy RH8s you won't have to buy any mods and you are done.  If you steal cars or buy Rebels, then you'll have to mod every single car.  The cheapest mod I could find across cars that makes sure there's a cosmetic change was the Exhaust.  It seemed like the cheapest Exhaust mod was usually $750.

Got Elegy RH8s - 30*0 = 0
Modding cars with Exhaust - 30*750 - 22,500

Total
So assuming that you have no 10 car properties already and no cars, the absolute cheapest to get with 3 10 car garages and Elegy RH8s on consoles would be 337,500.  This money would be completely spent on the garages.  The most expensive if you just buy 30 Karin Rebels, Exhausts, and get the cheapest 10 car apartment would be 530,000.


How to convert array of doubles into JS array?

Question: I have base64 encoded binary data(~2.5MB). The data is consisting of c double value array. In c language it comes with no cost using this array - you just read the whole data into memory and use double* address to access any element.
However, now I need to use this data in javascript. I'm looking for most efficient way to be able to read this array from js code.
Comment: Can you add a short sample of such base64 encoded data and what the expected output for it would have to be?
Comment: I don't have short sample unfortunately and not sure how to trim 2.5MB base64 data into short piece. In terms of bytes, each double is 8 byte signed number. Expected output would be `Array` of `Number` types or a stream class to access elements with index.
Comment: Can't you produce a short sample from a short array of double in C?
Comment: @ikhvjs how is the C tag relevant here? How can somebody who has knowledge of C help here?
Comment: @VLAZ, I just think people who know both C and Javascript will help the issue. The question mentions the data type in C.
Comment: Is this for browser or Node.js?
Comment: @trincot. I have no knowledge/tools to produce it in C.
Comment: @jabaa. Node.js
Comment: _you just read the whole data into memory and use double* address to access any element._ This is not always true, you have to make sure endianness and the format is the same on both systems. C does not make a specific float format mandatory nor does C say anything about how systems should implement their endianness. Especially for floating points, there exist some systems with weird endianness.
Answer: You could use this function in Node:
function doublesFromBase64(base64) {
    let buff = Buffer.from(base64, 'base64');
    let result = [];
    for (let i = 0; i < buff.length; i += 8) {
        result.push(buff.readDoubleLE(i));
    }
    return result;
}

To test it, I produced a sample base64 encoded string from the following piece of C code, which uses a function base64_encode found in this answer:
double arr[] = {15.9234, 2.05e30, -19};
size_t output_length;
char * result = base64_encode((unsigned char *) arr, 3* sizeof(double), &output_length);
printf("%s", result);

This outputs:
uECC4sfYL0Cjw3dB6N85RgAAAAAAADPA

I passed this string to the function at the top:
function doublesFromBase64(base64) {
    let buff = Buffer.from(base64, 'base64');
    let result = [];
    for (let i = 0; i < buff.length; i += 8) {
        result.push(buff.readDoubleLE(i));
    }
    return result;
}

let result = doublesFromBase64("uECC4sfYL0Cjw3dB6N85RgAAAAAAADPA");

console.log(result);

This outputs:
[ 15.9234, 2.05e+30, -19 ]


Websphere 9 isn't publishing WSDL as expected

Question: When opening the webservice URL for verifying it's WSDL, the following property is set as:
<wsdlsoap:address location="https://localhost:443/HR/services/EmployeeInformation" />

But I need it to be set as follows:
<wsdlsoap:address location="https://ipw3e.e.corpintra.net:443/HR/services/EmployeeInformation" />

If I go to Application servers > server_name > Installed applications > app_name > Webservices properties > Provide HTTP endpoint URL information, the URLs are configured as below:
HTTP endpoint URL information
On the path Application servers > server_name > Installed applications > app_name > Webservices properties > Publish WSDL files I can download a zip file that contains de WSDL's correctly configured.
So, the question is: Why Websphere isn't using those WSDL files?
The localhost config comes with the .ear file that development team provides for installing on Websphere. We have another environment running WAS 8 that makes this change automatically and, as far as I know, there is no special configuration made for this.
Answer: According to this,
https://www.ibm.com/support/knowledgecenter/en/SSEQTP_9.0.0/com.ibm.websphere.base.doc/ae/uwbs_providehttp.html
there's a jvm prop. you might need to set, com.ibm.ws.webservices.enableHTTPPrefix. Maybe that didn't get carried foward from the 8.x installation.


Integrating source-compiled package into ubuntu

Question: For performance reasons, I compiled GSL with icc (intel C compiler).
I ran ./configure with some flags, make, make check and sudo checkinstall.
I had to remove libgsl0ldbl, which is used by a number of packages (bogofilter bogofilter-bdb ink-generator inkscape libgsl0ldbl octave-gsl octave-statistics octave-vrml pyxplot pyxplot-doc qtiplot). I had to remove these packages, run checkinstall to install gsl from source. Then when I tried to install the packages back, they wanted to erase my version of gsl and install the pre-compiled one.
Is there any way to make those packages use the source-compiled version of gsl?
Answer: I think to get the best performance, you'll want to also rebuild the applications with icc, and I'm not entirely sure that using a library built with icc and an application built with gcc will actually work.
But to answer the question as asked, there are basically two ways:

Rebuild a libgsl0ldbl package, using icc, with a different version suffix (or a different name but Provides: libgsl0ldbl), and install that, then install the packages which should no longer want the Ubuntu libgsl0.
Force installation of the application packages despite not having libgs0ldbl installed.  One crude way to accomplish this is dpkg --force-deps octave-gsl*deb on the deb file.


Laravel 8 call other model relationship in model relationship

Question:
I have that relationship, and the main problem is how do I show Product where has relationship with product_image / discounts and render that on the blade?
There my Cart class model :
public function products()
{
    return $this->belongsTo(Product::class, 'product_id','id');
}

There's my product class model :
public function discounts()
{
    return $this->hasMany(Discount::class, 'product_id', 'id');
}

public function images()
{
    return $this->hasMany(ProductImage::class, 'product_id', 'id');
}

public function getProductImage()
{
    return $this->images->image_name;
}

This is both whatdiscount and product_images code to returning relationship
public function products()
{
    return $this->belongsTo(Product::class, 'product_id','id');
}

And how do I show that on my Cart blade? I've use this but still shows error
@foreach($cart as $data)
    @foreach ($data->products as $item)

            image->image ) }}"class="border" style="width:120px;" alt="">

    @endforeach
@endforeach

Comment: WHAT IS THE ERROR????
Comment: im just trying to show product_images on cart view using relationship on product model and still can't find how to show that
Comment: please share what is `@dd('$cart')` is showing......... also what is `@dd('$data')` and `@dd('$data->products')` are showing
Comment: sorry bro , already answered with this topic https://stackoverflow.com/questions/58897935/render-has-many-relationship-with-eager-loading-data-in-blade-using-compact-gets
Answer: you are trying to get a single value directly from multiple relations.
public function getProductImage()
{
    return $this->images->image_name;
}

You are trying to directly print the image of more than one image.
@foreach($cart as $data)
    @foreach ($data->products as $item)

            image->image ) }}"class="border" style="width:120px;" alt="">

    @endforeach
@endforeach

It could be like this.
You determine the first image of the product as the main image.
Product Model:
.....
    protected $appends = ["mainImage"];
.....
public function getMainImageAttribute()
    {
        return $this->images()->first()->image_name;
    }

Thus, you can capture the image with the attribute you have defined from within the product.
@foreach($cart as $data)
    @foreach ($data->products as $item)

            mainImage ) }}"class="border" style="width:120px;" alt="">

    @endforeach
@endforeach

Comment: it's already solved by another topic that i found on stackoverflow , but thanks for advice, maybe sometime it's may help me on future^^


Is there a way in Postgres / SQL to substitute characters in strings from columns where the characters in the string are column names?

Question: I have a table called sentences, and a table called logs.
The sentences table looks like this:
|------------|---------------------------------------|
|     id     |                sentence               |
|------------|---------------------------------------|
|     1      |     [var1] says hello!                |
|------------|---------------------------------------|
|     2      |     [var1] says [var2]!               |
|------------|---------------------------------------|
|     3      |     [var1] says [var2] and [var3]!    |
|------------|---------------------------------------|
|     4      |     [var4] says [var2] to [var1]!     |
|------------|---------------------------------------|

The logs table looks like this:
|------------|------------------|--------------|--------------|--------------|--------------|
|     id     |     sentenceId   |     var1     |     var2     |     var3     |     var4     |
|------------|------------------|--------------|--------------|--------------|--------------|
|     1      |         1        |     Sam      |              |              |              |
|------------|------------------|--------------|--------------|--------------|--------------|
|     2      |         2        |     Joe      |   what's up  |              |              |
|------------|------------------|--------------|--------------|--------------|--------------|
|     3      |         3        |     Tim      |     hey      | how are you  |              |
|------------|------------------|--------------|--------------|--------------|--------------|
|     4      |         4        |     Joe      |     hi       |              |    Tiffany   |
|------------|------------------|--------------|--------------|--------------|--------------|

The result I am trying to get is:
|------------|-----------------------------------------|
|  logs.id   |            sentences.sentence           |
|------------|-----------------------------------------|
|     1      |   [Sam] says hello!                     |
|------------|-----------------------------------------|
|     2      |   [Joe] says [what's up]!               |
|------------|-----------------------------------------|
|     3      |   [Tim] says [hey] and [how are you]!   |
|------------|-----------------------------------------|
|     4      |   [Tiffany] says [hi] to [Joe]          |
|------------|-----------------------------------------|

I'm not sure how to write the SQL query to make the database do the text substitutions for me.
I could just select everything from both tables using an inner join, and then loop through in code and do the substitutions myself. I.e.:
SELECT logs.id, sentences.sentence, logs.var1, logs.var2, logs.var3, logs.var4 FROM logs INNER JOIN sentences ON logs.sentenceId = sentences.id

And then in code:
logs.forEach(log => log.sentence.replace(/\[(.*?)\]/g, ($matchedString, $columnName) => log[$columnName] ))

But if possible, I'd like the database to do that for me so that I don't have to select more data than I need.
Comment: You could do a bunch of `REPLACE()` functions: `SELECT logs.id, REPLACE(REPLACE(REPLACE(REPLACE(sentence.sentence, '[var1]',var1), '[var2]', var2), '[var3]', var3), '[var4]', var4) FROM logs... ` I don't believe there is a dynamic way to do this though, short of dynamically writing out the sql and then executing it.
Answer: I would write a function to do that:
create function replace_vars(p_sentence text, p_vars jsonb)
 returns text
as
$$
declare
  l_rec record;
  l_result text;
begin
  l_result := p_sentence;
  for l_rec in select * from jsonb_each_text(jsonb_strip_nulls(p_vars)) as x(var,value)
  loop
     l_result := replace(l_result, l_rec.var, l_rec.value);
  end loop;
  return l_result;
end;
$$
language plpgsql;

Then you can use it like this:
select s.id, s.sentence, replace_vars(s.sentence, to_jsonb(l)) new_sentence
from sentences s
  left join logs l on l.sentenceid = s.id;

Online example
Answer: Elegance is always nice, but sometimes brute force gets it done.
with logsnn (sentenceid, var1, var2, var3,var4) as
    ( select sentenceid
           , coalesce(var1,'')
           , coalesce(var2,'')
           , coalesce(var3,'')
           , coalesce(var4,'')
        from logs
    )
select s.id
     ,(replace(replace(replace(replace(s.sentence
        , '[var1]',l.var1)
        , '[var2]',l.var2)
        , '[var3]',l.var3)
        , '[var4]',l.var4)
      )  AS sentence
  from sentences s
  left join logsnn l
        on l.sentenceid = s.id;

If you really need the brackets on the result change the replacement settings to
'[var1]','[' || l.var1 || ']')

The answer by @JNevill is close to the same, bit I believe that one will return Null if any of var1,var2,var3, or var4 are Null. The CTE here changes Null with the empty string. Postgres does not consider the empty string the same as null.


Connecting a Washing Machine with Aquastop

Question: We've just moved into a new flat and bought a new washing machine. The provided cable isn't long enough to fit to the water outlet.
I bought an extension cable, along the lines of this:
https://www.bunnings.com.au/kinetic-1000mm-flexible-water-connector_p4750083
But I'm not certain if these needs to go before or after the Aquastop. The Aquastop is the electric variety but there is no additional cable to the maschine.
Answer: You'll want to put the extension between the Aquastop and the machine, so that the Aquastop can stop the water supply even if there's a leak in the extension hose.


ubuntu 12.04 acer idea issues

Question: So I was trying to install ubuntu 12.04 LTS onto my acer iDea 510.
I succeeded to install it, though everytime I try to install the wireless and graphics card drivers it crashes and send this message that it "can't enumerate usb device port 3" over and over again. I tried to reinstall it several times with no success.
Do you have any idea?
Thank you very much for you're help!!!
Answer: You need to install legacy firmware/drivers for the older wireless and graphics cards in the iDea 510.  This should fix the USB port enumeration errors.
For the graphics card, if you have drivers currently installed, remove them:
sudo apt-get purge xserver-xorg-video-nouveau
sudo apt-get purge xserver-xorg-video-vesa

Next, edit sources.list to add a non free repository:
sudo gedit /etc/apt/sources.list
Add the following line to the end of the file:
deb http://ftp.us.debian.org/debian testing main contrib non-free
Save and close.
Now update and add the legacy nVidia drivers:
sudo apt-get update
sudo apt-get install nvidia-kernel-legacy-173xx-dkms nvidia-glx-legacy-173xx build-essential nvidia-settings nvidia-xconfig

After it's downloaded, execute the Xconfig file:
sudo nvidia-xconfig
sudo reboot

When you reboot, it should load back up normally.
For the wireless card, download the firmware-b43-installer and it should automatically extract and install everything for you (Source):
sudo apt-get install firmware-b43-installer

You will be asked to automatically fetch and install the firmware into the correct location.

ubuntu 12.04 acer idea issues


Why do I get integers in array when adding np.random.normal() to each element?

Question: When I run this code
import numpy as np

y = np.arange(1,11)
for i in range(len(y)):
    y[i] = y[i] + np.random.normal()

print(y)

I get the output
[ 2  1  2  3  2  6  6  7 10 10]

Why do all numbers in y gets converted into integers? np.random.normal() clearly do return floats.
Comment: doing: `y+np.random.normal(size=(len(y),))` will implicitely cast your `y` array and the result will be a `float64` array. But numpy will use implicite casting only if we apply an operation with a differente dtype on the whole array.
Comment: @obchardon, `y[i] + np.random.normal()` casts to float as well.  It's the following element  assignment that converts that back to the `y.dtype`.  What you are suggesting makes a whole new float array which remains float with `y=...`, but not with `y[:]=...`.
Answer: It is as the y array in your example implicitly gets set to dtype=int. Therefore, while doing y[i] = y[i] + np.random.normal(), it is equivalent to int = int + float; i.e. a float has to be type-casted into an int before storing it.
You can circumvent this issue by manually specifying the dtype while creating the numpy array.
import numpy as np

y = np.arange(1, 11, dtype=float)
for i in range(len(y)):
    y[i] = y[i] + np.random.normal()

print(y)
# Sample output: [ 2.16400377  1.5604771   2.69698066  4.17251939  4.13071869  5.99501597  7.06189783  7.69103035 10.51589948 10.31083259]

Answer: Trying it out, it appears that y[] has a dtype of int32, and does not change this when elements are modified.


Does Array provide a way to search for index of an element with arbitrary logic

Question: Is there any lambda-based approach which will allow one to find the index of (the first) occurrence of an element in an array based on custom logic?
I know I can find the element itself using Array.First but can I find the index of that element without manually iterating the array?
Comment: `Array.IndexOf` ?
Comment: Do you mean you want to find the index of the specific element by its value?
Comment: You mean based on a property value? There is `Array.IndexOf` for the object itself.
Comment: `Array` and `List` both have convenience methods for this; see [this](https://stackoverflow.com/q/1290603/4137916) for a more general question on doing this for any `IEnumerable` (all those answers are easily extended to predicates rather than specific values, where desired).
Comment: If you call Array.IndexOf(), the iteration happens through the array. But if I understand the question correctly, you want the index of the first item you were looking for. But you don't want to iterate through the whole array or part of the array. Unfortunately, this is impossible if the element is not at the beginning or end of the array. This is due to the mechanism of how arrays are built.
Comment: Does this answer your question? [Getting the index of a particular item in array](https://stackoverflow.com/questions/4388600/getting-the-index-of-a-particular-item-in-array)
Comment: I just edited the question as I realised IndexOf is not quite adequate.
Comment: the accepted answer in the second duplicate should still satisfy your criteria. Does it?
Answer: You could use Array.IndexOf(). Example:
var array = new string[] { "one", "two", "three" };
var index = Array.IndexOf(array, "two");
// index = 1

Answer: You can use Array.IndexOf() that "Searches for the specified object and returns the index of its first occurrence in a one-dimensional array or in a range of elements in the array." :
var foo = new int [] { 10, 42, 42, 51, 42, 100 };

Console.WriteLine(Array.IndexOf(foo, 42)); // output is 1

Although this will iterate under the hood, you don't have to manually [iterate] the array
Answer: You can do this:
var s = new string[] {"foo", "bar"};
var index = Array.FindIndex(s, s1 => s1 == "foo"); // returns 0

NOTE: it will return -1 if the element was not found
Comment: I was sure something existed but forgot to check static members. Why I wonder is it only available that way?
Answer: There's the Array.IndexOf method.
The following code:
    String[] strings = { "the", "quick", "brown", "fox", "jumps",
                 "over", "the", "lazy", "dog", "in", "the",
                 "barn" };
    Console.WriteLine(Array.IndexOf(strings, "dog"));

Will output 8.
MSDN: https://learn.microsoft.com/en-us/dotnet/api/system.array.indexof


Wood rotted on thermal pane windows

Question: The wood that is up against the glass on the double pane windows has rotted. How do we repair them without taking the glass out? We have to paint them every summer but with our Montana winters they seem to get worse every year.
Comment: Hello, and welcome to Home Improvement. Is this inside or outside? (A picture would help.)
Answer: First of all treat the rot with an appropriate fungicide.  You do NOT want one that coats, but rather penetrates.
Look for WEST -- wet epoxy saturation technology, or something like that.
In a nutshell:
Remove the clearly rotten wood.  Initially mix up small batches and paint it on.  If you find it leaking through use some fine mesh fiberglass cloth to seal it.
If the holes are large, wet blobs of fiberglass chop, and stuff in there. Paint the entire surface with the resin to seal it.
You can mix colourants into the resin. Since paint doesn't stick well, decide on a colour for the final coat or two.
It's been 25 years since I've read about this.  Details fade, and practices change.  But if the wood is only starting to rot, you may not need to replace it.

Wood rotted on thermal pane windows


Trigger UNNotificationServiceExtension on Simulator via Xcode 11.4 push feature

Question: Xcode 11.4 (beta) allows developers to trigger push notifications on the simulator.
I'm currently doing this via command-line using:
xcrun simctl push [device] [my.bundle.identifier] payload.apns

However I also have some UNNotificationServiceExtension that loads an image from an external URL given in a custom field of the payload. The image is then displayed in the notification popup. Unfortunately this extension is never called using the given command-line.
I also tried to use the bundle identifier of the extension in the command-line, but that just doesn't do anything.
I am aware that Xcode 11.4 is still in its first beta, but did anyone discover a way to trigger a notification service extension using this new feature?
Comment: Please update your question with the contents of the apns file you are trying to send.
Comment: @quellish The payload does not matter in this case though. The notification itself is shown correctly (without image then) on the simulator and the extension works fine when sending the same payload to a real device.
Comment: I am unable to trigger the NotificationServiceExtension by dragging and dropping into the simulator. I am using latest XCode.
Answer: Certain kinds of notifications are not currently supported, including service extensions and VoIP.
edit: As of iOS 16 Simulator can get real push notifications from the APNS Sandbox environment on compatible Macs. This allows more extension types to be supported than previously. The existing local payload mechanism is also still supported.
Comment: Does anyone have the source for this information?
Comment: @razorSharp As the author himself was/is working as one of the developers on the Simulator at Apple, I consider him to be a trusted source on these things.
Answer: Starting from Xcode 14 and iOS 16, you can send a push notification to your simulator with the Sandbox environment.
Xcode 14 Release Notes > Simulator > New Features: https://developer.apple.com/documentation/xcode-release-notes/xcode-14-release-notes
And you can debug the ServiceExtension just like what you did with the real devices. Xcode > Debug > Attach to Process > find your ServiceExtension. Then send a push again, your breakpoints on Extensions should work.


Why spider's result is different in cmd.exe and in file?

Question: I write a spider to get someting in a website.I print it in cmd.exe,and I also print it in file,but there are ,between words in file, there are no , in cmd.exe.Here is my code:
answer_name = soup.select('.UserLink-link')[1].get_text()
print answer_name

the result in cmd.exe is that: vczh
the result in file is that: v,c,z,h
why?And how can I get the result that no ,
Comment: my code is that:'code'  item['answer_name'] =[n.encode('utf-8') for n in answer_name] . Yes , it's wrong,I have known,thank you very much.
Comment: post the write to file code, and 知乎来的大兄弟啊.................
Comment: 额额,写入文件我是直接在命令行输入"scrapy crawl  zhihu  -o  bcd.csv"
Comment: post the `yield item` code, I think you yield data in wrong way.
Answer: change yield item code, I think you yield data in the wrong way.


How can I disable the android emulator keyboard from popping up

Question: In the following screenshot, I have an image that is followed by a scrollview. The scrollview contains a tablelayout and then some edittext fields, followed by a button

When I want to enter values into my fields, the keyboard pops up and it's blocking my view of the fields, like so:

As you can see, it blocks my view of the edittext fields. Is there an elegant fix for hiding the keyboard? If not, I will change my layout, however I'm not sure what to change. My layout looks like:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#CCCCCC"
    android:weightSum="1" android:id="@+id/llid">
    <TextView ... >
    </TextView>

    <ScrollView
        android:id="@+id/svid"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginTop="3dp">
        <LinearLayout>
            <TableLayout ... >
                <TableRow>
                    <TextView ... />
                    <TextView ... />
                </TableRow>
                <TableRow>
                    <TextView ... />
                    <TextView ... />
                </TableRow>
                <TableRow>
                    <TextView ... />
                    <TextView ... />
                </TableRow>
            </TableLayout>
            <EditText>
            ...
            </EditText>
            <EditText>
            ...
            </EditText>
            <EditText>
            ...
            </EditText>
            <Button>
            ...
            </Button>
        </LinearLayout>
    </ScrollView>
</LinearLayout>

Answer: My first thought is go to the settings within the emulator:
settings -> language and keyboard
and uncheck "Android keyboard" and the other odd ones if they are checked too
Comment: What's the path for that? I have gone into 'menu -> settings -> language & keyboard'. I've unchecked 'Android Keyboard'. I have also unchecked every single option under 'menu -> settings -> language & keyboard -> Android Keyboard Settings' but no joy
Comment: It doesn't show up initially when I input a value into my edittext field. But, when I move to the next edittext field and input a value, the keyboard still pops up :S
Comment: I've updated my post to reflect my problem more accurately. Any help appreciated.
Comment: It seems like its just one of those things that is going to be an annoyance that cant be fixed...because even if you could disable it in the emulator..that wont disable it for the users.
Answer: Since the emulator is suppose to emulate what would be seen on the phone it makes sense that if you are trying to enter values into a text field the keyboard will pop up. I understand it can be irritating but, you should not try to disable it in your code, because that will disable it on the phone and then how will the user enter their inputs?
Also, you can press the hardware back button to dismiss the keyboard when it pops up.
Comment: Well, this application is only a prototype and so I'm using the emulator. I won't be running it on a phone. It's just a test app so I'm not concerned about running it on a phone.
Comment: Second guessing the users intention and other social engineering to avoid the question is not considered a answer.
Answer: Programmatically you can set keyboard disabled by
public void removeKeyboard(EditText e, Context context){
    InputMethodManager keyB = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
    keyB.hideSoftInputFromWindow(e.getWindowToken(), 0);
}

where EditText e or some other view calling for text input
UPDATE!
If you set user input with SearchView i have found some short way to close down the keyboard by just
nameButton.clearFocus();


Simple way of enabling SSLv2 and SSLv3 in OpenSSL?

Question: Fresh install of Ubuntu here and trying to use the SSLScan tool, only to find out that I get these error:
OpenSSL version does not support SSLv2
SSLv2 ciphers will not be detected

OpenSSL version does not support SSLv3
SSLv3 ciphers will not be detected
Testing SSL server xyzx on port 443

  TLS renegotiation:
Session renegotiation not supported

  TLS Compression:
OpenSSL version does not support compression
Rebuild with zlib1g-dev package for zlib support

I found some article online on trying to re-compile OpenSSL without those flags being explicitly disabled, but I can't even get past the first few steps in some of these guides. For example, one guide recommends running sudo apt-get build-dep openssl. I can't run that because then I get the following error:
[03.14.2017/23:47:31] user@box $ sudo apt-get build-dep openssl
Reading package lists... Done
E: You must put some 'source' URIs in your sources.list

Although I have many uncommented sources in my /etc/apt/sources.list file.
Any suggestions? I just want to enable SSLv2 and SSLv3, and at least enable compression too. Can I just simply re-enable all of the disabled features?
Comment: Did you get it work? I have similar problem i need opessl s_client to support -ssl2 and -ssl3 flags. I found some work around. If you interest lets discuss it online. You can contact using gtalk email@example.com
Comment: Nope I haven't found a solution yet. I'm not all that familiar with compiling and stuff too so I just left it alone :(
Answer: My solution was to build just the openssl binary to avoid overwriting the system OpenSSL installation:
wget https://openssl.org/source/openssl-1.0.2k.tar.gz
tar -xvf openssl-1.0.2k.tar.gz
cd openssl-1.0.2k/
# --prefix will make sure that make install copies the files locally instead of system-wide
# --openssldir will make sure that the binary will look in the regular system location for openssl.cnf
# no-shared builds a mostly static binary
./config --prefix=`pwd`/local --openssldir=/usr/lib/ssl enable-ssl2 enable-ssl3 no-shared
make depend
make
make -i install
sudo cp local/bin/openssl /usr/local/bin/

To test:
$ openssl s_client -connect google.com:443 -ssl2
CONNECTED(00000003)
139675635414688:error:1407F0E5:SSL routines:ssl2_write:ssl handshake failure:s2_pkt.c:412:

$ openssl s_client -connect google.com:443 -ssl3
CONNECTED(00000003)
140647504119456:error:1408F10B:SSL routines:SSL3_GET_RECORD:wrong version number:s3_pkt.c:365:

I've got a more complete script here if you're interested: https://gist.github.com/bmaupin/8caca3a1e8c3c5686141
Comment: should also add `enable-ssl3-method`  to ./config , at least if you want to link it to curl and use ssl3 in curl
Answer: I also had this exact problem! (And this post is now the first hit on Google.)
I solved it by building sslscan myself, with static linking; this puts the SSLv2 and SSLv3 support into the executable itself. It might be dangerous to have the global openssl library support old vulnerable protocol versions.
The source code repo for sslscan is here: https://github.com/rbsec/sslscan
I could not get the instructions there to work without problems, because I did not have any deb-src lines in /etc/apt/sources.list, giving the error:
E: You must put some 'source' URIs in your sources.list

However, I ignored the error and it worked for me anyway. Building took about 10 minutes on my laptop (-j flag did not work). The build failed once for some reason (test not passing) but compiling again made it work.
TL;DR: Run:
sudo apt-get install build-essential git zlib1g-dev

git clone https://github.com/rbsec/sslscan.git
cd sslscan
make static

Verify the output
./sslscan --version
                1.11.13-rbsec-9-g55ec8c7-static
                OpenSSL 1.0.2-chacha (1.0.2g-dev)

Answer: I ran into the same error. Uncommenting all the lines beginning with deb-src in /etc/apt/sources.list that had matching uncommented lines  followed by a sudo apt-get upgrade cleared up the error for me on Ubuntu 16.04.
I was mostly following https://www.hackwhackandsmack.com/?p=46 and now I have ssl3 working (I think I missed an extra flag for ssl2, so just a heads up to double check you get all the patches/series and rules options set).


Can't connect to Amazon S3 on scala. Python connection works well, but on Scala I am getting 403 Forbidden response

Question: Also I have port number, but i didn't find where to set it. How can I fix this problem? Through python's "boto" client I successfully connected to my service, but on Scala it always returns forbidden message.
object a extends App{

      import com.amazonaws.auth.BasicAWSCredentials

      val accessKey = "myAccessKey"
      val secretKey = "mySecretKey"
      val credentials = new BasicAWSCredentials(accessKey, secretKey)

      import com.amazonaws.services.s3.AmazonS3Client

      val s3client = new AmazonS3Client(credentials)

      s3client.setEndpoint("address")

      val s3object = s3client.getObject("myBucket", "file.txt")

      println(s3object.getKey, s3object.getObjectMetadata.getLastModified)
    }

Here is error log:
Exception in thread "main" com.amazonaws.services.s3.model.AmazonS3Exception: Forbidden (Service: Amazon S3; Status Code: 403; Error Code: 403 Forbidden; Request ID: null; S3 Extended Request ID: null), S3 Extended Request ID: null
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1639)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1304)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1056)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:743)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:717)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:699)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:667)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:649)
    at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:513)
    at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:4319)
    at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:4266)
    at com.amazonaws.services.s3.AmazonS3Client.getObject(AmazonS3Client.java:1406)
    at com.amazonaws.services.s3.AmazonS3Client.getObject(AmazonS3Client.java:1267)
    at a$.delayedEndpoint$a$1(a.scala:17)
    at a$delayedInit$body.apply(a.scala:3)
    at scala.Function0.apply$mcV$sp(Function0.scala:34)
    at scala.Function0.apply$mcV$sp$(Function0.scala:34)
    at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
    at scala.App.$anonfun$main$1$adapted(App.scala:76)
    at scala.collection.immutable.List.foreach(List.scala:389)
    at scala.App.main(App.scala:76)
    at scala.App.main$(App.scala:74)
    at a$.main(a.scala:3)
    at a.main(a.scala)

Answer: The AWS SDK somehow discourages using the endpoint (JavaDoc):

Only use this if using a non-standard service endpoint - the recommended approach for configuring a client is to use {@link #withRegion(String)}

Instead, use the withRegion:
import com.amazonaws.auth.{AWSStaticCredentialsProvider, BasicAWSCredentials}
import com.amazonaws.regions.Regions
import com.amazonaws.services.s3.AmazonS3Client

AmazonS3Client.builder()
  .withCredentials(new AWSStaticCredentialsProvider(
    new BasicAWSCredentials("accessKey", "secretKey")))
  .withRegion(Regions.EU_WEST_1).build()


Removing a Sprites Color Key libGDX

Question: I am trying to remove the color key from a sprite. In this case my sprite backgrounds are purple. I have tried using the spritebatch setColor() function, but that turns the whole screen to the sprites background color. does anyone have a solution on how to remove the color?
Thanks for any help
Answer: I don't think libGDX (or OpenGL ES) support "colorkey" transparency.  As far as I know, everyone just uses an alpha (transparency) channel in the image.  (In addition to red, green blue, each pixel has an alpha value representing its transparency.)
If you remove the background color in an offline tool and save the image with transparency information you should be fine.  (And I believe this is what most existing libGDX apps do.)
Alternatively, you can probably do this at runtime by defining a shader that converts colorkey pixels into transparent pixels.
Comment: I have removed the background from the image in Paint.Net. I always did that when doing anything with Slick2D, it always worked fine but for some reason it's not working with libGDX.
Comment: I'm confused. Is the background purple or not?  Are you saving the image in a format that preserves transparency?  If your image is stored with transparency information (i.e., an alpha channel) then you're having problems at render time.  Blending should be enabled by default, though ...
Comment: Sorry. I should have been more clear. What I do when I create a sprite is, I set the background to purple, draw the sprite and then remove the purple background with the magic wand tool.Then save it and import the sprite to my assets folder for the game

Removing a Sprites Color Key libGDX


Using bash commands in expect script

Question: I've tried using some bash commands in an expect script before spawning anything, and this doesn't seem to work:
#!/usr/bin/expect

sudo ifdown usb0
sudo ifup usb0

expect "[sudo] password for stud:"
send "FirstPassword\r"

spawn ssh email@example.com
expect "firstname.lastname@example.com's password:"
send "SecondPassword\r"

expect eof

I've tried running this with the first part of the script commented out (because it's not neccesary to do this check 100% of the time, just better), but in that case I enter the device, and literally can't do anything there. I'd like to ifdown ifup, enter pass, ssh, enter pass, and scope to that shell.
Answer: Nope. you can't expect to run bash commands in an expect interpreter, just like you can't run perl commands in a python interpreter -- they're different languages. If you want to run some bash commands that require user interaction (sudo), then you have to spawn bash
set prompt {\$ $}    ; # this is a regular expression that should match the
                       # *end* of you bash prompt. Alter it as required.
spawn bash
expect -re $prompt

send "sudo ifdown usb0\r"
expect {
    "[sudo] password for stud:" {
        send "FirstPassword\r"
        exp_continue
    }
    -re $prompt
}
send "sudo ifup usb0\r"
expect -re $prompt

send "ssh firstname.lastname@example.com\r"
expect "firstname.lastname@example.com's password:"
send "SecondPassword\r"
expect eof

Answer: If the command you want to run inside an expect script is supposed to generate some output that you want to consume inside the script then consider running your command outside the script and then passing whatever value you need as a parameter.
An example for openvpn that requires an OTP token as a parameter:
autovpn.exp
#!/usr/bin/expect -f

set OTP_CODE [lindex $argv 0]

set timeout -1

spawn sudo openvpn --config my_vpn_profile.ovpn

expect "Enter Auth Username:"
send -- "myuser\r"

expect "Enter Auth Password:"
send -- "mysecret\r"

expect "CHALLENGE: Enter Authenticator Code"
send -- "$OTP_CODE\r"
expect_background

Now you can run the expect script passing the opt code as first argument:
./autovpn.exp $(oathtool -b --totp 'my_otp_seed_ABCDEFGH')

Using bash commands in expect script


How the Weapons Attributes works?

Question: I know there are six attributes (Physical, Beam, Ether, Thermal, Electric, Gravity), but I really don't know how they work on weapons.
There are some arts that causes  Res Down, so I suppose that a weapon/art of that element will do more damage.
But without this, how do I know what kind of weapon attribute will do more damage and on what kind of enemy? There is anything related to the enemy type (Theroid/Insectoid/Piscinoid...)?
Thanks guys.
Answer: As you fight more enemies you will gather information about them under intel -> enemy index.
Most enemies will resist according to their type.  Here's a few standard weaknesses
<code>Theroids: -50% thermal, -25% ether
Piscinoid: -50% electric
Humanoid: -25% beam
Mechanoid: -50% gravity
</code>
If an enemy is flying, it is also likely weak to gravity.  Tyrants generally have a +5% resist modifier on top of the base resistances for their type.

Every weapon has a type.  That type will be used for auto-attacks and for arts which say they do "weapon" damage.

How the Weapons Attributes works?


Clearing a div and children using jQuery

Question: Wondering what the best / good way of doing this would be in jQuery.  I have a
 that contains an unordered list which is populated using code.  I'd like to put a reset button on the page so things go from this:

value 1

value 2

to this:

Use .empty() or .html('') creatively, something like that perhaps?
Comment: Since you already know about the functions that could be used, what is the problem?
Answer: .empty() is the way to go:
$('#a_list').empty();

Answer: $("#resetButtonId").click(function(){ $("#a_list").empty() });

On reset button click, empty the unordered list


Why put the controls in the bottom (or the top) of a music player UI?

Question: Among alot of the music players around the player controls have usually been arrange to the top of the application window, or to the bottom.
What is the rationale behind the positioning, the choice of placement?
Edit ↓
In which cases should one go for top-aligned controls when designing?
In which cases should one go for bottom-aligned controls when designing?
Comment: I prefer when the controls are close to my taskbar, so I can switch to the player and pause the music quickly. Of course there are other ways to do that (Windows 7 has player controls on the preview window, Ubuntu's unity has an applet next to the clock, your keyboard might have a shortcut for that), but sometimes you need to do it the old way. Personally, I usually use taskbars at the top of the screen (sometimes on the left),  which integrates nicely with top controls but is annoying on Windows Media Player, which has bottom controls...
Answer: To build on Benny's answer, which I really like, I think there's a natural mapping here. Cassette decks used physical buttons, which didn't work so well when you put them vertically. In order to put the buttons on the side, you'd either have to stack the buttons vertically or significantly extend your UI area.

download bmml source – Wireframes created with Balsamiq Mockups
Intuitively, neither of those options really work. I don't think there's an explicit logic behind it, but they just don't feel right.
Good old Winamp did a bunch of funky things with button placement using skins. While fun, none of those designs really caught on as the norm. A more standard top / bottom row of buttons is what we're used to, and it's what people have come to expect. Just like how green means go, and red means stop.
Answer: The controls naturally reside next to the time bar slider. This slider is horizontal, so they fit best on top or on bottom.

download bmml source – Wireframes created with Balsamiq Mockups
Why put it on top in iTunes? Because toolbars and quick actions historically go there.
Why put it on bottom in Spotify? Because of hierarchy and our reading order left-to-right and top-to-bottom:

A directory (left) or a search (top) is used to find a list of songs,
A list of songs (from an album, an artist or a playlist) contain the song,
The song has controls.

So starting from the top, drilling down, the controls should go with the song, that will end up in the bottom.

download bmml source
Comment: I'd only favor congruency with the rest of the design. Which is clear in both iTunes and Spotify (while WMP not so much), and I prefer the keyboard media keys anyway. :)
Comment: You would favor a bottom-aligned design then?
Answer: As many other digital controls, this one probably originates from the cassette player button placement, where you mechanically pushed the audio head onto the tape on a cassette player. When the audio player was possible on a software, designers probably thought it would be a good idea to mimic the real worlds cassette players, which looked like this:

Note to reviewer: This answer was made to the original question, having a different meaning
Why put the controls in the bottom of a music player UI?
Among alot of the music players around the player controls have usually been arrange to the top of the application window, or to the bottom.
What is the rationale behind the positioning?
Comment: This seems like a guess to me, especially since there were other music players with controls all over the place. Can you make a more concrete connection between the two?
Comment: You couldn't put controls all over the place:  in the days of early (piano key) cassette players you had to keep the buttons close to each other as you had to press down both the record (red) button and the play button at the same time using two fingers to start recording.
Comment: @dhmholley I'll do my best
Comment: I might have messed up your answer by modifying the title a bit. :S
Comment: @yusf No worries! One can see the original question if one clicks on the edit time link. I might get back and make an update later :-)
Answer: Bottom positioning is usually used at players, that have both audio and video possibilities (WMP is most popular one). And in video playback most important stage activities usually is placed over the middle of the frame (especially faces/eyes of video participants). Also to manipulate playback you don't have to move cursor over the scene (and disturb any action) — that is another reason of placement at the bottom.
So it originates from backward compatibility with video playback and to maintain consistence between audio and video controls. In other cases top or bottom placement usually goes from visual hierarchy and other goals — so there is no straight pattern.
Answer: When viewing the applications from a desktop (e.g. with a mouse), top or bottom makes little difference in terms of space used or usability.  Thus, the decision of where to place important controls is more a matter of taste.
However, for touch-friendly/mobile devices, bottom is definitely the better option.  This is because your finger does not have to travel as far or cover up the main display when you use them.
Thus, to achieve consistency between desktop and mobile versions of the applications, mobile wins and the most heavily-used controls should go at the bottom.
Comment: @yusf:  I don't have an Android device, but I did search for "Android music player" on Google images, and through at least the first 50 images, every result that had play/ff/rew buttons had them below the viewing area, so I apologize but I'm not sure what you are referencing.
Comment: Guess Android didn't get that bottom toolbar memo heh?
Answer: The biggest reason to place them at the top or bottom is scanability. You can very easily glance immediately to the top or bottom of the player, regardless of the content, without a close look. If the buttons are in the middle you have to search for them.
Also as Matt Obee mentioned, it makes the most sense for the time bar to be horizontal (how time is generally represented in info visualization) so a vertical layout for controls is generally ruled out.
As for why is the bottom the most common position? I suspect it's largely because it's often where TVs present menus/overlays. Any sort of "pop-in" menu often appears at the bottom (like Youtube's controls).
I'm not sure there's a great reason for bottom alignment being the most common (though if you have a large TV craning your neck up is usually less comfortable than glancing down, an TVs are usually at or above eye-level), but it's now common enough to be a convention. Once something's a convention it's rarely worth challenging conventions without real data to support a change.
Answer: It is in part due to the progress bar, which of course needs to be presented horizontally; it makes sense for the playback controls to be located in the same place.
Comment: But why at the bottom?
Comment: It's not always the bottom. The question asked why they are often arranged "to the top of the application window, or to the bottom. I believe it's just because the horizontal width is required.
Comment: Why does a progress bar need to be presented horizontally? Actually, that could make a good question, hang on...
Comment: That question was added as "[Why are progress bars horizontal?](http://ux.stackexchange.com/questions/25463/why-are-progress-bars-horizontal)"
Answer: I think iTunes did it on the top perhaps as it's like a toolbar, and according to Apple HIG, toolbar should be at the top.
Spotify does this at the bottom as they try to act like a browser it seems, and somehow the music toolbar went to be a secondary toolbar (pretty funny for a music player). Personally, I don't like that the Spotify controls are at the bottom.
Windows Media Player has its toolbars because of movies, as Alex said, this is plausibe - if the content itself is visual, we expect to read it from right-to-left, top-to-bottom. In case of videos, it'd be disturbing to have meaningful content at the top which doesn't belong to the actual media. For similar reasons, sometimes gallery applications of online newspapers place navigation at the bottom and try to have the fewest top elements possible.
Comment: The browser argument seems legit, as Spotify positions itself besides it's kins such as Grooveshark and other browser based music services.


Question for a collage maker app

Question: I am creating a collage maker app for Windows Phone. I have a simple yet intriguing question in mind.
Being a student developer, I cannot support both borderless collages and those with borders (shortage of time).
Given the case, should I create the app with borders between the pictures or should the collage be thrown in borderless.
Which one will be better?
Thanks!
EDIT: Consider these as an example:
Borderless:
With Borders :
could you please also suggest how thick should the border be? Is the thickness correct in the second pic above or should it be thinner?
Comment: Both of these mean the same thing: "I cannot support both borderless collages and those without borders." Can you clarify what you mean? Give examples of what kind of collage you're talking about? Perhaps some of your own thinking about why border or borderless is better?
Comment: @DrewBeck I apologize for the confusion, I have edited my description. Have also added pics to describe what I am saying. Can you please suggest something now?
Comment: This isn't really a UX question.
Comment: Not sure where else to ask it though..  Can you please answer anyway?
Comment: I'm a big fan of the border look. you can always release the borderless option as a feature later.
Comment: I see, how thick should the border be? Is the correct like in the second pic above? Or should I go with a thinner version?
Answer: Purely aesthetically I like the balance of the one with borders. This provides some breathing room for one image to transition into another. The one with thin lines looks awkward because those pictures don't really work when fit together.
Comment: Thanks for your explanation.. Just one more question, how thick should the border be.  Is it fine like in the second picture above, or should it be thinner than that?
Answer: Whether an image (or group of images) has a border or not is highly dependent on a) the images in question and b) the aesthetic opinion of the artist.
So, ideally it's an option, and adjustable at that. But it sounds like you have to pick one or the other. In that case, as you can see by the answers thus far: it doesn't matter as everyone is going to have a different opinion.
Unless you can ask the users of the app and you can come to a conclusion that one is significantly better than the other, it doesn't matter. Just pick whichever you think looks better.
Comment: Thanks for your insights. I'll try and come to a conclusion soon.
Answer: Thinking from the product perspective, i would suggest break it down as a feature and its components and define priorities within these feature backlogs. That's how it is done with good product development life cycles.
I would break it down like:

Having no border
Ability to have border and define thickness and color

I would consider the border and its ability to be user defined as the pictures will make this decision subjective to the user and you cannot have an objective answer like #000000 and 1px thick would always fit for everyones collage!
Hope you find your way out of this.. Good luck with your app!
Cheers,
Nishant
Answer: Go with a thin border. Don't hint to the user whether or not you'll have borders. Just do it.
Comment: Hey, should it be thinner than the one in the second example pic above?  Half of it would be alright?
Comment: 1 pixel, exactly as shown in the first picture.
Comment: They asked for an approach and/or what to do regarding a border. Answer: Go with a thin border. How and why is this response not an answer?
Comment: @MickaelCaruso: It's not a particularly *good* answer, it's just a personal preference suggestion. You've provided no reasoning, no explanation or anything other than personal preference. If OP decides to take your approach and is questioned on it the only answer he has is *'I did it because one person on the internet thought it was a nice idea'*. It'd be far better if your answer gave some solid reasoning behind it as that'd lend it some credibility.
Comment: So I learn there's unspoken rules here - don't post unless you can back it up with professional research. I know my post was short because the question was simple. Now when I cite personal experiences and why such a UI confuses me an d offer suggestions of what I've done, it's not allowed. SMH.
Comment: @MickaelCaruso, it is not an "unspoken rule". It is very prominent seen in other answers, expressed in the FAQ and discussed on the UX meta site. Good UX is not about personal opinion, it is about how people actually behave (we have a lot of psychologists in the field). Why should I "go with a thin border"? Why should I "hint to the user"? What are the UX implications if I "just do it"? If your answer comes purely from personal experience, discuss that experience.

Question for a collage maker app


How to know the file system of my USB memory from the terminal?

Question: I have connected a USB memory to my PC. It has been automatically mounted and I can access it from /media/....
How can I know the file system of this memory from the terminal?
Comment: why the downvote? Leave a comment!
Answer: Run mount | grep ^/. You'll get something like this:
/dev/sda1 on / type ext4 (rw,errors=remount-ro)

As you can see, the file system is ext4 in my case.


Getting name and email from contact list is very slow

Question: I'm implementing an AutoCompleteTextView and I need Name and E-Mail of all my contacts.
I found this snippet that I'm running asynchronously but it's very slow.
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

if (cur.getCount() > 0) {
    while (cur.moveToNext()) {
        String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
        String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

        Cursor emailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[]{id}, null);

            while (emailCur.moveToNext()) {

                String email = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                    autoCompleteAdapter.add(name + " - " + email);
            }

            emailCur.close();
        }
    }
}

I'm performing a sort of inner query and I think that's the problem. Is there a way to tune it and make it faster?
Comment: Did you manage to get it working ?
Comment: The outer `if (cur.getCount() > 0)` is redundant and may be removed.
Answer: private static final String[] PROJECTION = new String[] {
    ContactsContract.CommonDataKinds.Email.CONTACT_ID,
    ContactsContract.Contacts.DISPLAY_NAME,
    ContactsContract.CommonDataKinds.Email.DATA
};

...

ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, PROJECTION, null, null, null);
if (cursor != null) {
    try {
        final int contactIdIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.CONTACT_ID);
        final int displayNameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
        final int emailIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
        long contactId;
        String displayName, address;
        while (cursor.moveToNext()) {
            contactId = cursor.getLong(contactIdIndex);
            displayName = cursor.getString(displayNameIndex);
            address = cursor.getString(emailIndex);
            ...
        }
    } finally {
        cursor.close();
    }
}

few notes:

use just ContactsContract.CommonDataKinds.Email.CONTENT_URI to get information you need, see ContactsContract.CommonDataKinds.Email for information what columns you can query
use projection to get only those columns you really need, you save some memory and increase query performance
get column indexes only once, just before the while cycle
Comment: how can i read whole v-card in efficient way it means to read whole address book.
Answer: You should not query directly the ContactsContract.Contacts
Make just one query on the ContactsContract.CommonDataKinds with the email data kind.
The ContactsContract.CommonDataKinds.Email inherits a lot of other interfaces that you can use to build your projection. (see inherited constants from the documentation)
For example :
import android.provider.ContactsContract.CommonDataKinds.Email;

[...]

public static final String[]  EMAILS_PROJECTION = new String[] {
    Email._ID,
    Email.DISPLAY_NAME_PRIMARY,
    Email.ADDRESS
};

to be used with the
Email.CONTENT_URI

You can retrieve a lot of information (such as user id, user display name ...) directly from the email data kind.
EDIT:
I just realized you're trying to build an AutoCompleteTextView.
You should override the runQueryOnBackgroundThread method and the convertToString of your CursorAdapter and use the Email.CONTENT_FILTER_URI
I really strongly suggest you to take a look at the ApiDemo samples.
Especially the AutoComplete4.java sample that you can find HERE.
Comment: Thanks Timothée, your explanation is very well done. Too bad I can't mark both answers as correct. I think that biegleux's answer is very good (works incredibly well) for other users looking for a quick snippet.
Answer: ContentResolver cr = mContext.getContentResolver();
Cursor cursor = mContext.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, PROJECTION, "HAS_PHONE_NUMBER <> 0", null, null);

if (cursor!= null)
{
    final int displayNameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
    final int numberIndex = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
    final int idIndex= cursor.getColumnIndex(ContactsContract.Contacts._ID);
    String displayName, number = null, idValue;

    while (cursor.moveToNext())
    {
        displayName = cursor.getString(displayNameIndex);
        idValue= cursor.getString(idIndex);

        Cursor phones = mContext.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, "contact_id = '" + idValue + "'", null, null);
        phones.moveToFirst();

        try
        {
            number = phones.getString(phones.getColumnIndex("data1"));
        }
        catch (CursorIndexOutOfBoundsException e)
        {
        }

        phones.close();
        userList.add(new ContactModel(displayName, number, null));
    }
}


Right mouse click, choose delete on website

Question: I'm implementing a javascript folder tree with basic explorer function: add/update/delete. It's like this:
<code>[Menu] Add new school

+School A
-- Class A1
-- Classs A2
-----Student Tom
+School B
-- Class B1
-----Student Jerry
</code>
Currently we click on the name to show a modal box for editing. User can drags students to re-order a class. As a customer request, when the school manager right-click on "Student Tom", a pop-up menu appears that allow him to delete Tom.
My question is: is this reasonable in user UI experience? I think it's not natural for people to right-click on a website except when they want to access the default browser command (save link as,...)? Or I'm just over-thought?
My recommendation is that when the user hover on the name, a delete button appears.
Comment: I think your recommendation of a delete button is a good idea.
Comment: I'd disagree about the 'hover to show a button' approach. As soon as you hover-off the name then the button would (presumably) disappear so you'd not actually be able to get to the button. Also as you mouse-over any element on the page you'd get flashes of buttons appearing all over the place. You'd have to have a couple of delays in there - one in place when you start hovering and another delay when you mouse-out - so many delays you might as well have gone with a click anyway.
Comment: @GrandmasterB: I hope that too. But since there is a customer request that just go opposite, I think I would go their way if it does no harm. I'm not a UI master.
Comment: I think you'll be fine with a right-click if thats what the customer insists.  Users will just need to be taught that the right-click menu is there because they wont be expecting it.  You could possibly add something that says 'right click for options' when an item is selected.
Comment: I've seen a UI where hovering anywhere on a row shows edit and delete buttons, with a fade transition. It seemed natural enough.
Answer: Right clicking on the web is indeed much less used.
Hover should be avoided in my opinion, especially if there any chance this will be used on a mobile device where this isn't possible.
I'd also point out that edit and delete are related actions and in iOS in particular you often click "edit" to reveal a "delete".
Based on the usage frequency of edit vs. delete I'd stick with the left click and choose how to display the 2 options:

Open the edit dialog and have a button for delete
or on click show 2 buttons of "edit" and "delete" and continue from there.

Hope this makes sense.
Comment: I'm in much agreement with this view, and would go with option 1 - click = show editor. Just wanted to add that the benefit in having a delete option in the dialog is three-fold: 1) You're saving the space of a button in the toolbar (tiny bit of info for the eye to deal with); 2) Users are two clicks away from deleting something, instead of one (safer, less chance of accidental mouse click); 3) The button on the editor can say 'Delete' where on the toolbar it would normally show 'X'.
Comment: I would also consider a sliding editor rather than a dialog - the latter being more fashionable with desktop applications, but not as much with web ones.
Answer: On the web, it is counter intuitive to right click for contextual menu related to the content instead of the user agent. I would suggest a [x] button with delete functionality.


Is it possible to point a domain name to my Google drive?

Question: Is it possible to point a domain name to my Google drive?
Comment: I have a google account , and I have some files in Google drive , is it possible to point a domain name (www.something.com) to this drive
In an other way using Google drive as web host
Comment: No, not really. You could redirect your site to the URL of the file if it's a public file using ``, or maybe stream the file, but I don't know what language you are using on your server.
Comment: Thanks for replying
Could you please give me an example
I am using PHP/python.
Answer: You could probably use readfile in PHP to do this. Here is the example they give:
<?php
    $file = 'monkey.gif';

    if (file_exists($file)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        ob_clean();
        flush();
        readfile($file);
        exit;
    }
?>

Replace monkey.gif with the URL of the public file.


Remove header and footer from 1st page

Question:  class MyDocTemplate(BaseDocTemplate):
        def __init__(self, filename, **kw):
            self.allowSplitting = 0
            apply(BaseDocTemplate.__init__, (self, filename), kw)
            template = PageTemplate('normal', [Frame(1.0*cm, 1*cm, 19*cm, 27*cm, id='F1')])
            self.addPageTemplates(template)

        def afterFlowable(self, flowable):
            if flowable.__class__.__name__ == 'Paragraph':
            text = flowable.getPlainText()
            style = flowable.style.name
            if style == 'Heading1':
                level = 0
            elif style == 'Heading2':
                level = 1
            else:
                return
            E = [level, text, self.page]
    #if we have a bookmark name append that to our notify data
            bn = getattr(flowable,'_bookmarkName',None)
            if bn is not None:
                E.append(bn)
            self.notify('TOCEntry', tuple(E))

 class FooterCanvas(canvas.Canvas):

     def __init__(self, *args, **kwargs):
         canvas.Canvas.__init__(self, *args, **kwargs)
         self.pages = []

     def showPage(self):
         self.pages.append(dict(self.__dict__))
         self._startPage()

     def save(self):
         page_count = len(self.pages)
         for page in self.pages:
             self.__dict__.update(page)
             self.draw_canvas(page_count)
             canvas.Canvas.showPage(self)
         canvas.Canvas.save(self)

     def draw_canvas(self, page_count):
         page = "Page %s" % (self._pageNumber)
         self.saveState()
         self.setFont('Times-Roman', 10)
         self.line(40,23,560,23)
         self.drawString(280, 25, page)
         self.line(40, 810, 560, 810)
         self.drawString(40,813,"abc")
         self.restoreState()

As you can see this will create TOC as well as header and footer from FooterCanvas class and FooterCanvas class is getting applied to all the pages but I don't want it to be applied to first page of my pdf. So how can I achieve this?
Comment: It looks that you only have one PageTemplate. When I want similar control, I create two separate PageTemplates, e.g.
 frontpage = PageTemplate(id='FrontPage',
                                 onPage=footer,
                                 frames=[],
                                         )
backpage = PageTemplate(id='BackPage',
                                onPage=header,
                                frames=[]
MyDocTemplate.addPageTemplates(frontpage)
MyDocTemplate.addPageTemplates(backpage)
Comment: It worked. @Jaco
Comment: glad I could help, I have posted it as an answer, please mark it as helpful/solution.
Answer: It looks that you only have one PageTemplate. When I want similar control, I create two separate PageTemplates, such as below.
frontpage = PageTemplate(id='FrontPage', onPage=footer, frames=[])
backpage = PageTemplate(id='BackPage', onPage=header, frames=[])

MyDocTemplate.addPageTemplates(frontpage) MyDocTemplate.addPageTemplates(backpage)

Answer: I have found one more way to do it with the help of other answers. So here it is.
Frame1=Frame(x1,y1,width,height,id='F1')
Frame2=Frame(x1,y1,width,height,id='F2')

def FooterCanvas(canvas,doc):
    page = "Page %s" % (canvas._pageNumber)
    canvas.saveState()
    canvas.setFont('Times-Roman', 10)
    canvas.drawString(280, 15, page)
    canvas.restoreState()

class MyDocTemplate(BaseDocTemplate):
    def __init__(self, filename, **kw):
        self.allowSplitting = 0
        apply(BaseDocTemplate.__init__, (self, filename), kw)
        self.addPageTemplates([PageTemplate(id='firstPage',frames=Frame1),PageTemplate(id='allpages',frames=Frame2,onPage=FooterCanvas)
            ])

    def afterFlowable(self, flowable):
        if flowable.__class__.__name__ == 'Paragraph':
            text = flowable.getPlainText()
            style = flowable.style.name
            if style == 'Heading1':
                self.notify('TOCEntry', (0, text, self.page))
            if style == 'Heading2':
                self.notify('TOCEntry', (1, text, self.page))

Story=[]
write your styles here and write your TOC styles. create TOC instance and add levels for TOC(levels are optional).

Story.append(NextPageTemplate('firstpage'))
First page with some paragraph or graphics.

Story.append(NextPageTemplate('allpages'))
Story.append(PageBreak())
Rest of the pages with some paragraph or graphics.

doc=MyDocTemplate("abc.pdf")
doc.multiBuild(Story)

Remove header and footer from 1st page