Q:

The Great Question Deletion Audit of 2010

First, let me go on record saying I absolutely support the concept that closed questions which are not useful in either content or as a search term variety duplicate, absolutely should be deleted.
That said, it was never the intent of deletion to destroy valid, useful contributions. Questions which contain useful content contributed by your peers should generally be merged, not deleted.
Partially, I blame me. Because we are idiots, delete votes were not rate limited. Also, we now have 17 pages (!) of users who are eligible to cast delete votes. It looks like this was an explosive combination; a few users have gone a bit.. over the top .. with closed question deletions:

Question deletions are getting out of hand
Would you delete these questions? Isn’t closing enough?
Why are we deleting instead of merging?

Example: multiple answers by Eric Lippert got deleted. Eric Lippert, a senior developer on the C# compiler team at Microsoft! That's when I knew we had a serious problem.
(we have since rate limited deletion votes.)
I put together a query which shows the top ~200 deleted (but not migrated) questions that were not self-deleted, nor deleted by moderators -- and have a total score (question + all answers) of more than 15 votes.
Please help me audit this list and determine which of these posts deserves to be completely deleted. Some do, some don't. Flag ones that should be merged with another question for moderator attention, and we will merge them.

132983    2301      7314      Who is your programming hero?
72406     1080      13931     What development book made the most impact on you as a developer?
3947      734       8983      Music to listen to while coding
315470    598       4458      Why do people ask for computer (IT) help if you tell them you're a programmer?
195285    553       3210      What stupid policies affecting developers has your company introduced?
54607     549       5491      What are the best movies about Geeks/Programmers/Hackers. (for inspiration)
27347     466       2173      What annoys you as a programmer?
92159     427       7581      How do you vent stress as a programmer?
53264     347       3312      What Is the most beautiful code you have ever seen or written?
205003    305       3353      Is it wrong to go to interviews while employed?
139097    249       1236      How do you waste work time ie procrastinate?
3830      245       3001      Have you become addicted to Crack Overflow?
53423     151       1612      What virus protection/internet security do you use at home as a programmer
120324    144       1945      Who are some well-known female programmers?
1946925   139       1446      Forbidden to use for loop!
110113    136       952       Which software expert do you have as a role model?
139621    136       1357      Merit of screencasts vs text-based documentation?
115256    136       4265      Skills in demand during 2009
42962     122       918       Do system administration questions belong in stackoverflow?
92257     119       2243      Programmer's food
193551    115       1316      Can you code while drunk?
155743    115       2046      Define a bad programmer
38461     113       1179      What can software developers do to be more "green"?
2821983   106       854       What's the Java equivalent of the term "pythonic"?
187370    94        1542      UNIX man page jokes?
6396      94        1923      Which Programming Language Should I Learn?
171431    93        1538      Most amusing job self-description?
60509     91        1681      How do you get in the zone? (esp. on Saturday...)
2090568   82        444
 or
?
20965     81        2111      What programming books do you recommend?
2647857   80        959       How do I politely tell a colleague to RTFM?
13750     79        601       Why do you like programming?
2782445   78        521       Should I bother with C++ or go straight to C#?
2428816   78        740       How long is a CS degree good for?
2764876   77        1274      What would your three most-telling interview questions be for a new hire?
150816    74        504       What has stackoverflow taught you?
1915      73        2007      How do I know if have RSI or carpal tunnel?
124542    71        743       So in 'good' Python do you have to type every space individually?
406885    66        1306      Knowing or not knowing the salary of your co-worker?
877149    65        489       What activity should be on every programmer's daily list?
163663    62        1512      Remove Experts Exchange from google programming searches
2809660   61        448       Is it better to adopt the same technologies used at work to be effective on your home projects ?
12860     59        867       Why do people on SOFlow seem to think finding programming jobs is trivial?
2804252   59        890       VS2010 has been released, so what do you hate or love about it?
2296799   58        1446      Real iPhone Devs Don't Use Objective-C Anyway!?
48349     57        872       Which power drink or food do you recommend most to boost mental performance?
2782964   55        425       What does this line of code do?  "variable = condition ? true : false"
2793543   55        778       Do people still use Unions in C and C++
535089    55        920       Do ternary operators increase complexity in programs?
2714980   54        401       Brackets or no brackets for one-line statements ?
1910182   54        738       Is it fair to ask about by-reference arguments as a C interview question?
2818428   53        536       Good policy to force all developers in a company to use the same IDE?
130575    52        1134      What's a good free bug tracker for a small shop
2818928   51        483       What does "===" mean?
156121    50        647       What programming languages will be around in 100 years?
466058    48        777       Examples of some of the worst code you've had to manage?
161286    48        861       Most amazing piece of code you've ever seen
1207687   47        417       Should PDF files generated from LaTeX source files be under version control?
97721     46        507       What does it mean when an explanation includes the word "basically?"
2537760   44        586       Premature optimization is the root of all evil, but can it ever be too late?
2772820   43        220       Programmers joy: the process or the result?
2848368   43        663       Why do some languages not use semicolons and braces?
84564     42        1449      Which java web framework you use in your day job ?
76630     41        1518      What is the single most effective way to keep from getting Slashdotted
2798667   40        215       write a c++ programe that displays the following out put.
171527    40        1088      Best console-based (no GUI) code editor?
2741548   39        367       Stopping pirates
833946    39        2750      In C# will the Finally block be executed in a try, catch, finally if an unhandled exception is thrown ?
2732589   38        524       How to emulate OOP with C?
854113    38        720       Why would you choose OO language over functional language?
2762287   36        325       Why does PHP have a bad rep?
2812337   34        318       How to deal with a coworker who keeps asking instead of searching herself?
2754698   34        532       Ruby, Python, or PHP?
2851648   34        566       Will a Ph. D. in Computer Science help?
122632    34        582       First programming language
934727    34        647       Why use "foo" in coding examples?
2838054   33        291       How would I create a random number?
2367939   33        367       Why is ++x preferred to x++?
2861667   33        428       What makes great software?
101548    33        482       Why is the ^ called a caret?
2766100   32        324       I'm a PHP programmer. Should I learn Java to improve my skills?
1098420   32        852       Preparing for my first C# interview...
56147     32        2584      What is your favorite regex editor?
2758800   31        257       Can someone suggest a way to learn regex?
2757210   31        316       Why do people keep parsing HTML using regex?
48851     31        518       What workplace exercises do you do?
2811917   30        439       Are game engines developed in the USA?
160975    30        619       Diet advice for programmers
91526     29        2069      Best Programming Jokes
2803093   28        195       Is Java really fit for mobile phone programes?
2859266   28        214       Programming ideas for an intermediate PHP programmer
2874224   28        289       What are the practical/concrete application of .NET 4.0 enhancements?
2385745   28        298       what is the use of private constructor in C++?
2837502   27        196       C++ file naming convention - uppercase or lowercase the "first letter"?
2758925   27        273       Career advice for a frustrated newbie programmer.
2838822   27        318       What stereotypes about developers are there?
156872    27        1153      How does one create an API?
1652193   26        260       Howto avoid people from having multiple accounts in a free to play multiplayer game?
2828965   26        376       What program should I write to use up the 3,472 minutes on my iPhone 3GS?
2754537   26        389       How can I demonstrate the benefits of abstractions to an old-time C programmer?
2755830   25        251       Is the web still 100% Stateless?
415420    25        581       What skills would you expect from a good programmer who has 5 yrs of experience?
3166      25        585       Supporting stackoverflow
98222     24        699       What's the greatest "WTF" moment you've witnessed from someone who has done the impossible?
78354     24        705       Worst thing you've seen on code.
2821778   23        239       efficient algorithm to test whether a given number is part of the fibonnaci sequence
2810801   23        307       Circular linked list
173996    23        366       What's the next piece of open source software that Microsoft should embrace?
2358391   22        173       What's the reason to use  this way?
2003757   22        244       What is typically the most difficult phase on a development project
1665136   22        367       What is the most effective question to test a C developer during an interview?
87696     22        555       Are unused Using directives expensive?
685375    22        789       Why has Delphi declined?
2659833   21        143       What makes good software good?
2765831   21        150       Which Technology Is More Secure, Perl or PHP?
2796839   21        183       How would I reverse an array of characters?
2758217   21        190       [C] Memory Address Comparisons
2606763   21        259       Greatest of Two Numbers Without Using A Relational Operator
1767048   21        272       If C# is type safe why is this possible without casting?
1085644   21        290       The difference between using == and is.
2885271   21        313       Why Do Programmers Get So Invested in their Favorite Technologies?
2844512   21        318       How does functional programming work?
2852701   21        357       Small utilities useful while programming
1774676   21        403       Execute code in if-else statement
2759742   21        426       My next programming Language
2714133   21        473       I would like to learn C++, what is the first step ?
166540    21        845       Which is the most useful UML diagram?
153184    21        907       The best c++ book
165358    21        1071      What project task manager / bug tracker do you think is best?
134288    21        1546      Interview Question/Puzzle
2744430   20        306       Does march have 32 days?
94558     20        467       What's your favorite programming blog?
180108    20        1304      Best practices for using the 'this' keyword in C#
2758888   19        187       what is this weird icon in my C code ?
2832303   19        202       Is it ethical to work as freelancer even if you are working in a software company as a full time developer?
2863335   19        209       Again, what version control system to choose?
125326    19        421       What do you think the next big thing will be in software development?
1234467   19        500       Parsing logfiles and applying logic - any suggestions?
650362    19        566       Probability of choosing marbles
173318    19        972       What field of software engineering do you work in?
2763272   18        140       Web application performance: PHP or Python?
2815559   18        147       What are the differences between the ASP.NET tags?
1778815   18        174       How should tertiary institutions teach programming ?
2876653   18        180       How does Java pick which method to call?
2849261   18        185       How/when to hire new programmers, and how to integrate them?
2778478   18        196       How can a new hire/intern make a good impression?
1678157   18        196       Why is Visual C++ complaining about a variable I think I've defined?
1842580   18        244       When should I call the Java garbage collector?
2740462   18        255       In C#, why should I use the 'var' data type?
2812560   18        256       this == null; surely not, but yes
1056233   18        363       What best describes clean code?
2789231   18        368       What is the 51702     18        939       Suggestions for free diff tools for Windows
206888    18        4636      What to choose on Windows: Strawberry Perl or ActiveState Perl?
2811995   17        144       Can someone elegantly explain a js closure so it sticks in my head.
2847382   17        147       What is the difference between === and == in PHP?
2787846   17        264       Why do I have to pay for something that I'm not using?
1779694   17        455       What is the shortest source code you have seen to do a complex task?
100905    17        752       Programming vs scripting -- what's your definition?
629032    17        879       Split a string into characters
165554    17        940       How can you make a fair decision with an unfair coin?  (interview question)
317499    17        1047      What is the best software for code-merge that you seen?
65378     17        1092      Is .net really a good choice for mission critical code?
205901    17        1914      C# Equivalent to Java's BigInteger
2793826   16        112       Python: combine two neighbor list components
2685752   16        386       Does software testing have a future?
124122    16        1337      Single return or multiple return statements?
2833188   15        83        Why is there a gap between Business and IT?
2798741   15        118       What is the purpose of CS0161 when switching over an enum and how to work around it?
2785612   15        178       C++ - what does the colon after a constructor mean?
2832367   15        193       what is clean code ?
2768798   15        236       dimension ||  pointer pointer
1225208   15        303       Are Developers bound to their city they live in ?
205691    15        361       New automatic properties in c# 3.0, what's the benefit?
53455     15        486       Why should I use ++i?
573352    15        748       I am considering implementing the RPXNow OpenID selector - can I avoid vendor lock in?

So please, as you have time and inclination, review this list and see if any of the content should be merged with another question before we throw it away.

A:

I'm glad that this discussion was started; I think we desperately need to rally around a community standard for question deletions, otherwise the debates and [un]delete wars will rage on forever.  Whatever the end result may be, if the "management" supports it then I will as well.
Before I just start diving into questions and rationalizing away decisions, I want to lay out some consistent criteria so people can decide if I'm evaluating questions objectively or just being a "deletionist."  I'm including the ones from Jeff's post on the subject, as well as some new ones that have come up.
Reasons for deletion

Does not follow the posting guidelines in the FAQ.  (In other words, fits into any of the closing reasons other than Exact Duplicate.)
Dilutes content of the site.  Takes attention away from "practical" programming questions/problems.
Encourages copycat questions (the "Hidden Features of X" are great examples of this).
Encourages other types of discussion/bikeshed questions by precedent.
Games the rep/badge system, diluting the pool of 3k and 10k "moderators", which can intensify the behaviour in cycles.  Partially mitigated by wiki mode, but only if the question is started as Community Wiki and the majority of votes (including answer votes) were issued as wiki votes.

Reasons against deletion

The question and answers genuinely, tangibly help to advance the relevant skills of specific developers and developers in general.
Question has a high number of views/upvotes (the "will of the people").  IMO, not a particularly good indicator of the actual quality; almost all wide-open questions will gather extreme numbers of votes and answers if allowed to stay open.
Question has an extremely high number of views coming from outside sources (blogs, digg, Google, etc.) and is likely to attract new membership.
One or more answers appear to be particularly interesting/valuable. (The Eric Lippert trump card)
The grandfather clause - i.e. the question is from the Dark Ages (or is that Renaissance?) of Stack Overflow and has important historical value.

With that in mind, I'd like to propose five possible options for dealing with deleted questions or deletion candidates in general:
Possible Actions

Delete or leave deleted.  This should be done if the fundamental premise of the question is flawed or its content is beyond hope of repair.
Undelete (and possibly reopen).  The question may not quite fit the mandate of the site, but has so many other things going for it that deletion seems like a crime.
Undelete and lock.  This is a very valuable option that I think most people are overlooking.  This allows the question to be viewed, but prevents it from being bumped, which nullifies many of the reasons for deletion, especially if a disclaimer appears explaining the reason it was allowed to live and warning against potential copycats.
Edit and undelete.  I suspect that many questions with especially good answers could have been good questions, if only they were asked with the appropriate tone and format.  If it is possible to reword/reformat the question in such a way, then this is the best alternative, by a wide margin.
Merge.  This is specifically for duplicates.  If some of the answers are novel or significantly better than the answers to the original, it should be merged.  This one's easy.

With that out of the way, here's a random selection of questions to start with:

What has stackoverflow taught you?: Delete. Actually, this question should have been migrated to Meta, but it was closed before Meta existed.  The question itself has low votes and none of the higher-voted answers are particularly enlightening.
Remove Experts Exchange from google programming searches: Delete. I hate the evil hyphen site as much as the next guy, but the swarm of upvotes was unwarranted, it's simply not a programming question. I'm tempted to say that it should have been migrated to Super User (if SU were around back then), but it may even be against SU's new-ish policy of not asking about web sites/applications.
Programming ideas for an intermediate PHP programmer: Reopen and reclose as a duplicate, then delete. Maybe merge the top answer into one of the dupes, but that's all. The question should not have been closed as "off-topic", but it is heavily duplicated and doesn't have any of the mitigating factors above.  It also encourages copycat questions in other languages/frameworks.  I think what's truly needed is a canonical, well-written and well-maintained list of "learning projects" - I've looked through all of the duplicates I could find and they are all hit or miss, with a few well-thought-out answers and a lot of trite rubbish.  Conceptually this fits well within the site guidelines and lends itself well to the Community Wiki style, but it's never actually been done properly (at least I couldn't find it).
Why has Delphi declined?: Undelete and lock. Cletus posted a damn good answer, but the question itself is borderline flamebait.  Some conscientious editing might convince me that the question should be unlocked as well; otherwise, it carries a copycat risk and should have a disclaimer.
Does software testing have a future?: Delete. It's argumentative and off-topic, and it wasn't wiki.  There are some okay answers but nothing dazzling.
C# Equivalent to Java’s BigInteger: Delete. I'm convinced by The Cat/Gnome's comment that this doesn't really add anything new other than keywords.  A better solution to undeleting would be to simply add some more tags/keywords to the original question.
Is the web still 100% Stateless?: Delete. This user has a history of poor questions and this one is no exception.  The tone is awful, the answers are decent but not too valuable to lose, and if you look at the big picture, it's basically just arguing over the definition of a word.
Does march have 32 days?: Delete. I'm sympathetic toward Charlie, but the question is completely pointless and may even be a joke.  I cannot see anybody searching for this question or finding value in any of the answers, ever.
Parsing logfiles and applying logic - any suggestions?: Delete. Obvious joke question, which Jeff has specifically asked people not to post.
Best Programming Jokes: Delete. I've checked, and all of the answers are duplicates as well.
Why would you choose OO language over functional language?: Delete. The question could have been OK, if it were worded differently ("What are the advantages of an Object Oriented style over a Functional programming style?"), but if it were to be "fixed" then it would basically become a dupe of this question anyway, which has already come under the radar due to Eric Lippert's answer.  There's maybe a very subtle difference, but the answers aren't thorough enough to make it important.
UNIX man page jokes?: Sounds like this might be appropriate for Super User, but I don't know how they are with "fun" questions.  If it fits the bill, undelete and migrate - otherwise, leave it deleted.
Why do I have to pay for something that I’m not using?: Delete and horse-whip the author.  I think the -9 question score says it all.  It's not much more than a thinly-veiled rant against Java, and the more comments I read, the more it starts to look like he's trolling outright.  The sad thing is, this could have been an OK question if the author had asked for facts and benchmarks regarding the performance impact of said feature; unfortunately, it's too far-gone to fix now.
Programmer’s food: Delete. Two words: Boat Programming.

A:

Not even going to try to review them all.

I'm rejecting a bunch as fluff based on the titles alone. Leave 'em dead, please.
I'm not going to review technical question in areas where I'm clueless. Those are someone else's problem (SEP fields will run practically forever on a single flashlight battery...)

Here's what I've got so far:

Split a string into characters [closed] There is an answer in there that is not represented in the original. A merge would be in order, but the title are also significantly different, so leaving the dup would not be a bad choice either.
Do people still use Unions in C and C++ [closed] Some good answers here, but I didn't see anything that wasn't adequately covered in the linked duplicates. Merging wouldn't be out of place, but is not necessary.
What does this line of code do? “variable = condition ? true : false” [closed] Has better and more complete discussion of the issues surrounding the conditional operator than the original. Which brings us the the questions: do we save stuff because it forms a good discussion while we are trying to discourage users from treating the trilogy sites as discussion boards? Others in this category include Should PDF files generated from LaTeX source files be under version control? [closed], ...
C++ file naming convention - uppercase or lowercase the “first letter”? [closed] Subjective and discussiony, but the answers are actually pretty good. However, I'd be surprised if there wasn't an earlier version. If we can find it we should compare the answers and consider a merge.
Programming vs scripting — what’s your definition? [closed] Doesn't seem to have anything unique. I'd say leave it be.

Questions I want to rant about:

How can I demonstrate the benefits of abstractions to an old-time C programmer? [closed] There may or may not be some good answers in there, but the OPs combative tone and broadly cast aspersions put this one firmly in the "eliminate with extreme prejudice" category for me.

I may get around to reading some more later, but for the moment I've found none that I think definitely should be merged.

A:

I love that you are doing this! However, this is a HUGE list. Most of us are likely to start at the top (or bottom, for us contrarians). We'll run out of steam and leave a large amount of unreviewed material in the middle.
You might consider a feature for 10K users on SO to "assign" review of a random sample of posts that need a personal touch. If you gave us a list of 10-25ish posts to review, many of us would take the time on a regular basis to go through them. These would be "unassigned" if we ignored them for too long, allowing someone else to look at them instead.


Q:

Permanently disable Configuration.ProxyCreationEnabled in EF?

Instead of having to do the following on every query, is there a way to just set that value globally? There is a lazyloading setting in the model view, but there does not seem to be a setting for the ProxyCreation.
        using (var context = new LabEntities())
        {
            **context.Configuration.ProxyCreationEnabled = false;**

            var Query = from s in context.EAssets
                        .Include("Server").Include("Type").Include("Type.Definition")
                        where (s.Type.Definition.b_IsScannable == true) &&
                        (s.Server.s_Domain == Environment.UserDomainName || s.Server.s_Domain == null)
                        select s;
           var Entities = Query.ToList();
        }

I don’t fully understand the benefits of this option, but i know that in visual studio is tags all my objects with gibberish serial suffixes and makes using the debugger unreasonable.

A:

You can disable it in the constructor, so that it gets disabled anytime you create a new context:
public class LabEntities : DbContext
{
   public LabEntities()
   {
      Configuration.ProxyCreationEnabled = false;
   }
}

A:

If you're using a model-first approach, meaning you have a .edmx file, the way to permanently disable this option is to modify the .Context.tt file.  This file is a code generation template that the build process uses to generate your DbContext-derived class.
Open this file and locate the constructor:
public <#=Code.Escape(container)#>()
        : base("name=<#=container.Name#>")
    {
<#
        WriteLazyLoadingEnabled(container);
#>
        //add the following line of code

        this.Configuration.ProxyCreationEnabled = false;
    }

then add the line of code to set this property to false.  Rebuild your project and verify the generated context contains the line.


Q:

Check if a particular string is in a file bash

I want to write a script to check for duplicates
For example: I have a text file with information in the format of /etc/passwd
alice:x:1008:555:William Williams:/home/bill:/bin/bash
bob:x:1018:588:Bobs Boos:/home/bob:/bin/bash
bob:x:1019:528:Robt Ross:/home/bob:/bin/bash
james:x:1012:518:Tilly James:/home/bob:/bin/bash

I want to simply check if there are duplicate users and if there are, output the line to standard error. So in the example above since bob appears twice my output would simply generate something like:
Error duplicate user
bob:x:1018:588:Bobs Boos:/home/bob:/bin/bash
bob:x:1019:528:Robt Ross:/home/bob:/bin/bash

Right now I have a while loop that reads each line and stores each piece of information in a variable using awk -F that is delimited with ":". After storing my username I am not too sure on the best approach to check to see if it already exists.
Some parts of my code:
while read line; do
        echo $line
        user=`echo $line | awk -F : '{print $1}'`
        match=`grep $user $1`($1 is the txtfile)
        if [ $? -ne 0 ]; then
                echo "Unique user"
        else
                echo "Not unique user"
                then somehow grep those lines and output it
        fi
done

The matching does not produce the right results
Suggestions?

A:

instead of re-inventing the wheel, use the following tools:

cut to extract first field
sort and uniq to keep duplicated lines only.
cut -d : -f 1 | sort | uniq -d | while read i ; do
                                   echo "error: duplicate user $i"
                                 done


Q:

Inheriting from the Error object - where is the message property?

I noticed a strange behavior while defining custom error objects in Javascript:
function MyError(msg) {
    Error.call(this, msg);
    this.name = "MyError";
}
MyError.prototype.__proto__ = Error.prototype;

var error = new Error("message");
error.message; // "message"

var myError = new MyError("message");
myError instanceof Error; // true
myError.message; // "" !

Why does new Error("message") set the message property, while Error.call(this, msg); does not? Sure, I can just define this.message = msg in the MyError constructor, but I don't quite understand why it is not already set in the first place.

A:

A. Like, Raynos said, The reason message isn't being set is that Error is a function that returns a new Error object and does not manipulate this in any way.
B. The way to do this right is to set the result of the apply from the constructor on this, as well as setting the prototype in the usual complicated javascripty way:
function MyError() {
    var tmp = Error.apply(this, arguments)
    tmp.name = this.name = 'MyError'

    this.message = tmp.message
    // instead of this.stack = ..., a getter for more optimizy goodness
    Object.defineProperty(this, 'stack', {
        get: function () {
            return tmp.stack
        }
    })

    return this
}
var IntermediateInheritor = function () {}
IntermediateInheritor.prototype = Error.prototype
MyError.prototype = new IntermediateInheritor()

var myError = new MyError("message")
console.log("The message is: '"+myError.message+"'") // The message is: 'message'
console.log(myError instanceof Error)                    // true
console.log(myError instanceof MyError)                  // true
console.log(myError.toString())                          // MyError: message
console.log(myError.stack)                               // MyError: message \n
                                                          // <stack trace ...>

The only problems with this way of doing it at this point (i've iteratted it a bit) are that

properties other than stack and message aren't included in MyError, and
the stacktrace has an additional line that isn't really necessary.

The first problem could be fixed by iterating through all the non-enumerable properties of error using the trick in this answer: Is it possible to get the non-enumerable inherited property names of an object?, but this isn't supported by ie<9. The second problem could be solved by tearing out that line in the stack trace, but I'm not sure how to safely do that (maybe just removing the second line of e.stack.toString() ??).
Update
I created an inheritance library that does this ^ https://github.com/fresheneesz/proto

A:

function MyError(msg) {
    var err = Error.call(this, msg);
    err.name = "MyError";
    return err;
}

Error doesn't manipulate this, it creates a new error object which is returned. That's why Error("foo") works aswell without the new keyword.
Note this is implementation specific, v8 (chrome & node.js) behave like this.
Also MyError.prototype.__proto__ = Error.prototype; is a bad practice. Use
MyError.prototype = Object.create(Error.prototype, {
  constructor: { value: MyError }
});

A:

In Node.js you can create a custom error like this:
var util = require('util');

function MyError(message) {
  this.message = message;
  Error.captureStackTrace(this, MyError);
}

util.inherits(MyError, Error);

MyError.prototype.name = 'MyError';

See captureStackTrace in node docs


Q:

Alasql select in arrary of array with uknown index

suppose I have this structure data
data =[
 {
"id":1,
"link":[
        {
        "id":3
        },
        {
        "id":1
        },
        {
        "id":2
        }
        ]
},
{
"id":2,
"link":[
         {
          "id":30
          },
         {
         "id":11
         },
         {
         "id":22
         }
         ]

}
]

I want see if my structure have a link with id=11
"SELECT * FROM ? WHERE link->[1]->id=11"

work but because I already know that I must check in index 1. How can I check in all indexes?

A:

The SEARCH function would be good if it was fully implemented
alasql('SEARCH / link / WHERE(id=11) .. / .. FROM ?',[data]);

But the parrent .. selector is not implemented yet.
I suggest doing a (not totally elegant) user defined function:
alasql.fn.deepSearch = function(id, obj){
    return alasql("SEARCH / link / WHERE(id=?) FROM ?", [id, [obj]]).length
}

alasql('SELECT * FROM ? WHERE deepSearch(11,_)',[data]);


Q:

postfix cannot getting my domain name?

Hi I'm trying to setup webmin+postfix+dovecot+roundcube, for this moment I want things be as simple as possible so I'm using linux users as email accounts.
I can send/receive from the same domain, I mean user1@mydomain.com can send/receive to/from user2@mydomain.com
I tested smtp/imap with outlook and says no problem.
if I send a mail from gmail it reject with error of:
Technical details of temporary failure:
The recipient server did not accept our requests to connect.

when I login with roundcube the email address display in the right corner is something like user1@com and
I get this error message from logs:
[11-Nov-2012 07:39:03 +0400]: IMAP Error: Login failed for user1 from 187.150.xx.xx. Could not connect to com:143: php_network_getaddresses: getaddrinfo failed: Name or service not known in /var/www/webmail/program/include/rcube_imap.php on line 191 (POST /webmail/?_task=login&_action=login)

it says Could not connect to com:143
looks like it cannot read the domain name.
I used http://mxtoolbox.com/ to check the mx record and it says it can find the server of mail.mydomain.com.
I quit sure the problema is from postfix or my server configs, but I have been looking for every config file and cannot find the answer of this. any suggestion I will appreciate.
here are some of my configs (I don't want to make this question too long, I can provide any other information to solve this question):
postfix main.cf
#myorigin = /etc/mailname

smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU)
biff = no

# appending .domain is the MUA's job.
append_dot_mydomain = no

# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h

readme_directory = no

# TLS parameters
smtpd_tls_cert_file = /etc/ssl/certs/ssl-cert-snakeoil.pem
smtpd_tls_key_file = /etc/ssl/private/ssl-cert-snakeoil.key
smtpd_use_tls=yes
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
smtpd_sasl_security_options = noanonymous
smtpd_sasl_auth_enable = yes
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for
# information on enabling SSL in the smtp client.

mydomain = mydomain.com
myhostname = mail.mydomain.com
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
mydestination = $mydomain, $myhostname
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_command = procmail -a "$EXTENSION"
mailbox_size_limit = 0
recipient_delimiter = +
virtual_alias_domains = mydomain.com
smtpd_recipient_restrictions = permit_mynetworks reject_unauth_destination permit_sasl_authenticated
myorigin = $mydomain

roundcube conf
// ----------------------------------
// IMAP
// ----------------------------------
$rcmail_config['default_host'] = '%d';
$rcmail_config['default_port'] = 143;
$rcmail_config['imap_auth_type'] = null;
$rcmail_config['imap_delimiter'] = null;
$rcmail_config['imap_ns_personal'] = null;
$rcmail_config['imap_ns_other']    = null;
$rcmail_config['imap_ns_shared']   = null;
$rcmail_config['imap_force_caps'] = false;
$rcmail_config['imap_force_lsub'] = false;
$rcmail_config['imap_force_ns'] = false;
$rcmail_config['imap_timeout'] = 0;
$rcmail_config['imap_auth_cid'] = null;
$rcmail_config['imap_auth_pw'] = null;
$rcmail_config['imap_cache'] = null;
$rcmail_config['messages_cache'] = false;

A:

Roundcube
Roundcube error is because of missing auth method
$rcmail_config['imap_auth_type'] = LOGIN;

Postfix
In your main.cf, remove virtual_alias_domains = mydomain.com. That is not needed for single domain config, and also in wrong format. That variable need a map file. Here is complete list of postfix config variable info.
The main problem is smtpd_recipient_restrictions missing permit at the end. Change as follow
smtpd_recipient_restrictions =
    permit_mynetworks
    reject_unauth_destination
    permit_sasl_authenticated
    permit

Restart postfix and re-test external mail. If error still exist, check following for any info related to gmail server connection
/var/log/syslog
/var/log/mail.log
/var/log/mail.err

Then add related log lines in your question.


Q:

Best way to calibrate my camera?

I really didn't notice ubuntu's calibration option ever since i was used with Precise Pangolin.
But what's the best way to calibrate my camera?

A:

I don't know what to say if is the best way or not, but I used for calibration this small tool: luvcview - USB Video Class grabber (it doesn't matter if your camera is not on USB).
After you have installed luvcview, run it from terminal with these options:
luvcview -f yuv -l

See man luvcview for more options.


Q:

Full Calendar Dropping Event Objects After Data Transform

I am having a strange issue with full calendar. I am trying to create a mouseover for different types of events and have had some issues with attributes of an event object disappearing between the "eventDataTransform" and "eventMouseover" functions
This is for a web application that will be loading data from an API to populate full calendar. I am able to get all of the object's attributes when I do not perform a transformation on the event. I am inspecting the object and show that it is present when the object is transformed and not so when it is moused over.
calendar = $("#k_calendar").fullCalendar({
  isRTL: KUtil.isRTL(),
  header: {
    left: "prev,next today",
    center: "title",
    right: "month"
  },
  editable: false,
  eventLimit: false,
  navLinks: true,
  weekends: true,
  eventSources: [
    // Loaded from a previous source
    data,
    "{% url 'pentesting-api:pentest-events' %}"
  ],
  displayEventTime: false,
  // Where the error is
  eventDataTransform: function (eventData) {
    if (eventData.hasOwnProperty('vendor')) {
      eventData.end = moment(eventData.end).add(1, 'days').format();
      eventData.title = eventData.full_name;
      eventData.backgroundColor = statusColors[eventData.status];
      eventData.allDay = true;
      return eventData;

    }
    else {
      eventData.title = eventData.event_name;
      eventData.backgroundColor = eventColors[eventData.event_type];
      // all attributes are on the object here
      console.log(eventData);
      return eventData;
    }
    // Using the below commented out code works but doesn't distinguish between events
    // eventData.end = moment(eventData.end).add(1, 'days').format();
    //   eventData.title = eventData.full_name;
    //   eventData.backgroundColor = statusColors[eventData.status];
    //   return eventData;
  },
  eventMouseover: function (event, jsEvent, view) {
    closePopovers();
    // console.log(event);
    if (event.hasOwnProperty('event_type')) {
      console.log('this mouse over');
      // object dropped the 'end' attribute
      console.log(event);
      let start_base, end_base, start_date, end_date, start_time, end_time;
      start_base = event.start.format().split('T');
      start_date = start_base[0];
      start_time = start_base[1].split('-')[0].split(':')[0] + ':' + start_base[1].split('-')[0].split(':')[1];
      end_base = event.end.format().split('T');
      end_date = end_base[0];
      end_time = end_base[1].split('-')[0].split(':')[0] + ':' + end_base[1].split('-')[0].split(':')[1];
      popoverElement = $(jsEvent.target);
      $(jsEvent.target).popover({
        title: event.event_name,
        content: function () {
          let content;
          content = 'Event Type: ' + event.event_type +
            '
Start: ' + start_date + ' ' + start_time +
            '
End: ' + end_date + ' ' + end_time +
            '
Resource: ' + event.resource;
          return content
        },
        trigger: 'hover',
        html: true
      }).popover('show')
    }
    else {
      var end = event.end.subtract(1, 'days').format().split('T')[0];
      popoverElement = $(jsEvent.target);
      $(jsEvent.target).popover({
        title: event.title,
        content: function () {
          var content;
          content = 'Pentest ID: ' + event.id +
            '
Pentest Status:' + event.status +
            '
Start Date: ' + event.start.format() +
            '
End Date: ' + end +
            '
Resources: ' + event.tester +
            '
Duration: ' + event.duration;
          return content
        },
        trigger: 'hover',
        html: true
      }).popover('show')
    }
  },
  eventMouseout: function (event, jsEvent, view) {
    $(jsEvent.target).popover('hide')
  }
})});

I am expecting the input from the mouseover includes the 'end' object attribute, however, it is not present. When doing the if, else eventDataTransformation, all of the object attributes are there including the 'end' attribute. When the data event is logged in the eventMouseover function, every attribute is there except for 'end'.
Event data transform object (what I want)
{
  "id": 11,
  "resource": "1",
  "event_name": "Test Event",
  "start": "2019-03-29T08:52:44.330075-07:00",
  "end": "2019-03-29T08:52:44.330173-07:00",
  "event_type": "Demo",
  "pentest_id": null,
  "title": "Test Event",
  "backgroundColor": "#ADD8E6"
}

Object being passed to the eventMouseover function (same object but missing the 'end' attribute)
id: "_fc12"
allDay: false
backgroundColor: "#ADD8E6"
className: Array []
end: null
event_name: "Test Event"
event_type: "Demo"
id: 11
pentest_id: null
resource: "1"
source: Object { calendar: {…}, uid: "4", url: "/api/pentesting/events/", … }
start: Object { _isAMomentObject: true, _i: "2019-03-29T08:52:44.330075-07:00", _f: "YYYY-MM-DDTHH:mm:ss.SSSSZ", … }
title: "Test Event"
<prototype>: Object { … }
pentesting:1781:23

A:

According to the specifications (documented well in this bug report - https://github.com/fullcalendar/fullcalendar/issues/3688), the end date MUST be different than the start date (or the end date will be 'null'!)
I would also be careful on making the end date BEFORE the start - in your eventMouseover you are subtracting a day - you should probably do a quick check to make sure the end is > (not = as you will have the 'null' issue...) the start.  I didn't find anything on having the end before the start, but I'm pretty sure fullCalendar would 'dismiss' it (likely with a null as well since end is optional).


Q:

Как мне вывести числа?

Есть много реквизитов в тексте.
Например: А15632, А14752, А12345...
Мне надо вырезать каждую отдельно:
parsed_req = 'А15632RT, А14752RT, А12345RT...'
requisites = re.findall(r'>\d{5}', parsed_req)

вот так дает результат:
А15632 A14752 итд
пишу так а он не работает:
parsed_req = 'А15632RT, А14752RT, А12345RT...'
requisites = re.findall(r'>\d{5}', parsed_req)
requisites2 = re.sub(r'A','',requisites)

пишу на python 3.6

A:

import re

parsed_req = 'А15632RT, А14752RT, А12345RT...'

Просто выцепляем 5 подряд идущих цифр:
requisites = re.findall(r'\d{5}', parsed_req)
print(requisites)  # ['15632', '14752', '12345']

С указанием специализированного шаблона поиска цифр:
requisites = re.findall(r'А(\d{5})RT', parsed_req)
print(requisites)  # ['15632', '14752', '12345']

PS.
У вас в примерах с А символ русский, что странно при наличии латинских RT


Q:

Check a string if it contains a given substring and return BOOLEAN

I am trying to come up with a haskell function that takes 2 string parameters. Then it checks to see if the 1st string contains the second string as a substring. For instance: "bring" contains the substring "in". If passed "bring" "in", the function should return true. Here is what I have so far, but it doesn't really work. Works partially. I don't know how to assign a true value in the recursive cases.
check::[Char]->[Char]->Bool
check [][]              =False
check _[]               =False
check []_               =False
check(x:xs)(y:ys)
 | y==x                 =True
 | otherwise            =check xs (y:ys)

main = do
print $ check "bring" "in"

A:

A straight-forward implementation that does not use libraries or cool tricks at all could be:
substring :: String -> String -> Bool
substring (_:_) [] = False
substring xs ys
    | prefix xs ys = True
    | substring xs (tail ys) = True
    | otherwise = False

prefix :: String -> String -> Bool
prefix [] _ = True
prefix (_:_) [] = False
prefix (x:xs) (y:ys) = (x == y) && prefix xs ys

This is the "canonical" way for naive substring search (in any programming language I guess?): for every suffix of a string, you check if the substring is a prefix.
Note that the substring argument comes before the string.

A:

Reason it is not working is because you only seem to be matching on the first character of the second string:
check::[Char]->[Char]->Bool
check [][]              =False
check _[]               =False
check []_               =False
check(x:xs)(y:ys)
 | y == x               =True -- this line
 | otherwise            =check xs (y:ys)

main = do
print $ check "bring" "in"

Fix it by doing:
check::[Char]->[Char]->Bool
check l s = check' l s True where
    check' _ [] h          = True
    check' [] _ h          = False
    check' (x:xs) (y:ys) h = (y == x && check' xs ys False) || (h && check' xs (y:ys) h)

main = do
print $ check "bring" "in"

Also note as previously pointed out that an empty string is a subset of itself and any non-empty string. The extra boolean is to quickly eliminate the current search and start at the substring again
Finally to be a good programmer, we can make this generic by doing this:
check::Eq a => [a]->[a]->Bool
check l s = check' l s True where
    check' _ [] h          = True
    check' [] _ h          = False
    check' (x:xs) (y:ys) h = (y == x && check' xs ys False) || (h && check' xs (y:ys) h)

main = do
print $ check "bring" "in"


Q:

Commit to SVN without changing the revision

I am commiting files to SVN via jenkins.
This file have no effect on the revision and should not update it and increase revision number. How can I commit it without updating revision number?
svn commit -m "Jeninkins build number update" AndroidStable/BuildNumber.txt --non-interactive --username jenkins --password jenkins

A:

What you are asking for isn't possible.  SVN* doesn't distinguish between "code" and "not code"; any change to the content of the repo is a commit, which is (by definition) a bump in the revision number.
If your aim is to just incorporate the revision number into the final build artifact, there's no need to commit it back to SVN.  You can just pull it in at build-time.
More simply: Don't put auto-generated stuff in version-control.

* Or indeed any version-control system that I'm familiar with.


Q:

Multiple apps from one project

I have a little problem.. which I know there is a fix for, I just don't know what it is.
The problem is the following. A few weeks ago (2 or so) I had to remove 4 apps from the appstore due to a data problem on my server side. I decided to upgrade all the apps to the latest version at the same time giving them some new features. (I have 6 of the same apps out there, targeting different airports). The difference between these versions are the following:

A set of 50-80 or so images that combine the map of each airport. The filenames are the same in each app. (How do I solve that?)
The name of the app
The Default.png (and those for iPad and retina of course)
The App Icon
The content of a details page (which exists in a .plist file)
The content of the "About" page where the page refers back to the app
Some localize content, refering back to the airport the app targets.
The provisioning profiles, of course.

Keeping track of these things are just a pain in the ass, so I want to have 1 project with 1 code base and just add the images and details (mentioned above) and new versions appear. When I "Archive", I want all of the apps to be build and ready to be send of to apple (which I will have to do manually).
How can I achieve this?

A:

I have done this before using multiple targets and conditional compilation. You need one target per deliverable. You can configure the name, icons etc for each target in the usual way.

A set of 50-80 or so images that combine the map of each airport. The filenames are the same in each app. (How do I solve that?)

Keep the images in different directories and for each target only add the images for that app. This technique will also work for the contents of the about page if you can load that from a file.

I also use conditional compilation so that I can define different values for my constants for each app.
To do this add a setting to Other C Flags and Other C++ flags to identify your app. Something like:
-DAPP_VARIANT=1

In your code you can then use the following to implement any app specific behaviour:
- (id)init
{
#if APP_VARIANT == 1
    self->server_url = [[NSURL URLWithString:@"http://app1.example.com"] retain];
#elif APP_VARIANT == 2
    self->server_url = [[NSURL URLWithString:@"http://app2.example.com"] retain];
#endif
}


Q:

Error Domain=AFNetworkingErrorDomain Code=-1011 "Request failed: method not allowed (405)"

I am using AFNetworking for Web services. It is working fine on NSURLConnection. It gives error using AFNetworking.
Here is my code:
 AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];

    [manager POST:@"" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"Succes");
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
                                                            message:[error localizedDescription]
                                                           delegate:nil
                                                  cancelButtonTitle:@"Ok"
                                                  otherButtonTitles:nil];
        [alertView show];
    }];

This is the error I receive:
Error Domain=AFNetworkingErrorDomain Code=-1011 "Request failed: method not allowed (405)" UserInfo=0x1e86b390 {NSErrorFailingURLKey=http://..............url.........., AFNetworkingOperationFailingURLResponseErrorKey=, NSLocalizedDescription=Request failed: method not allowed (405)}.

Can you please help for this.

A:

If your API is RestFul then you want to request using http. Use Below code may be it's helpful for you. Please let us know your comments.
 NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:url];
    [request setHTTPMethod:@"POST"];

NSString *post =[dict JSONRepresentation];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%ld",(long)[postData length]];

[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
[request setHTTPBody:postData];

//Add your request object to an AFHTTPRequestOperation
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request] ;
[operation setCompletionBlockWithSuccess: ^(AFHTTPRequestOperation *operation, id responseObject) {

     NSString *response = [operation responseString];
     NSLog(@"response: %@",response);

 } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
     NSLog(@"error: %@", [operation error]);
 }];

//call start on your request operation
[operation start];


Q:

Javascript Regex get list of string not in single or double quotes

Guy I have a list of string.
Select
id AS "cusId ",
name as 'cusName', gendar as ' Gendar.',
isPaid as " is'Paid ", total, remarks FROM

I need a regex that returns:
Select
id
name
gendar
isPaid
total
remarks
FROM

And also ignore comma and 'AS' keyword.
So far from PHP I can use preg_match_all('/(?<![\S"])([^"\'\s]+)(?![\S"])/') and filter all query keywords later on, but came to JavaScript there is no lookbehind in regex.

A:

DISCLAIMER: The solution below is by no means a generic solution for parsing arbitrary SQL queries. To parse arbitrary SQL queries, you need to build or use an existing one. See also How to parse / tokenize an SQL statement in Node.js.
So, taking into account your specific input strings, you can use a regex that will match what you do not need, and then will capture what you need:
/"[^"]*"|'[^']*'|\s+AS\s+|\s*((?:(?!\sAS\s)[^,\s])+)/gi

See the regex demo
Explanation:

"[^"]*" - match a double-quoted substring that has no " inside (replace with "[^"\\]*(?:\\.[^"\\]*)*" if you need to support escaped " inside)
| - or
'[^']*' - match single-quoted substring having no ' inside (replace with '[^'\\]*(?:\\.[^'\\]*)*' if you need to support escaped ' inside)
| - or
\s+AS\s+ - "AS" word inside 1+ whitespaces
| - or
\s* - 0+ whitespaces
((?:(?!\sAS\s)[^,\s])+) - Group 1 capturing one or more symbols other than , and whitespace (see [^,\s])+) that are not starting a sequence of a whitespace + AS + whitespace. It matches any text that is not space+AS+space.

JS demo:

var re = /"[^"]*"|'[^']*'|\s+AS\s+|\s*((?:(?!\sAS\s)[^,\s])+)/gi;
var str = 'Select id AS "cusId ", name as \'cusName\', gendar as \' Gendar.\', isPaid as " is\'Paid " total , datetime FROM';
var res = [];
while ((m = re.exec(str)) !== null) {
    if (m[1]) {
        res.push(m[1]); // Add the Capture group 1 to the resulting array
    }
}
document.body.innerHTML = "<pre>" + JSON.stringify(res, 0, 4) + "</pre>";


Q:

Assign different class names to div with php mysql

I have four divs in one page which are styled so that it has four alternating colours. And the even div i.e. 2nd and 4th have an extra class name 'r' like this.

The results are pulled from the database, I can use the modulus operator (%) to assign alternating colours for two rows as shown in here but how can I do this for four rows and also add 'r' to the even divs?

A:

As kojow7 says you can use % 2 and % 4, see this code:
<?php

for($i = 1; $i <= 4; $i++) {
  echo "div class='x-$i liner";
  if($i % 2 == 0) echo ' r';
  if($i % 4 == 0) echo ' color';
  echo "'>
\n";
}

?>

Output:
div class='x-1 liner'>

div class='x-2 liner r'>

div class='x-3 liner'>

div class='x-4 liner r color'>

EDIT:
With a foreach should be like this, but I don't know what values have $data
<?php

$i = 1;

foreach($data as $row) {
  echo "div class='x-$i liner";
  if($i % 2 == 0) echo ' r';
  if($i % 4 == 0) echo ' color';
  echo "'>
\n";
  $i++;
}

?>


Q:

Trying to delete a single value from array

I am trying to delete a value from a passed array at the selected index. Basically taking the selected index of a list box that displays the arrays and using it to delete an entry. For some reason nothing is deleted and stays the same when I run the program. I am programing in Visual Studio 2010 in C#
public double [] redrawArray(double[] ary, int selectedIndex)
{
    double[] redoneArray = new double[ary.GetUpperBound(0)];

    for (int i = selectedIndex; i < ary.GetUpperBound(0); i++)
    {
        redoneArray[i] = ary[i + 1];
    }
    //redoneArray[ary.GetUpperBound(0)] = 0;
    return redoneArray;
}

Here is the delete button portion of code
private void btnDelete_Click(object sender, EventArgs e)
{
    int selectedIndex;
    if (this.lstClients.SelectedIndex <= 1)
    {
        return;
    }

    //else if ((this.lstClients.SelectedIndex - 2) < arrayIndex)
    else
    {
            selectedIndex = this.lstClients.SelectedIndex - 2;
            this.lstClients.Items.RemoveAt(this.lstClients.SelectedIndex);
            lbSI.Text = (this.lstClients.SelectedIndex - 2).ToString();
            redrawArray(mFirstNameArray, selectedIndex);
            redrawArray(mLastNameArray, selectedIndex);
            redrawArray(mAgeArray, selectedIndex);
            redrawArray(mHeightArray, selectedIndex);
            redrawArray(mStartWeightArray, selectedIndex);
            redrawArray(mGoalWeightArray , selectedIndex);
            redrawArray(mTotalWeeksArray, selectedIndex);
            //arrayIndex += -1;
            lstClients.Items.Clear();
            loadListBox();
    }

}

And here is my main code that loads it into the list
private void loadListBox()
{
    string currentClient;
    int lineNumber = 0;
    string formattedName;
    string strAvgBMI;
    string strLowBMI;
    string strHghBMI;
    double dStartAvgBMI;
    double dStartLowBMI;
    double dStartHghBMI;
    double dEndAvgBMI;
    double dEndLowBMI;
    double dEndHghBMI;

    lstClients.Items.Add("   CLIENT NAME      AGE    HEIGHT(in)   START WEIGHT    START BMI    GOAL WEIGHT    GOAL BMI     WEEKS");
    lstClients.Items.Add("=================  =====  ===========  ==============  ===========  =============  ==========  =========");

    for (int index = 0; index < arrayIndex; index++)
    {
        if (mFirstNameArray[index] == null)
        {
            continue;
        }
        lineNumber++;
        formattedName = mFirstNameArray[index];
        formattedName += " ";
        formattedName += mLastNameArray[index];
        mStartBMI[index] = calcBMI(mHeightArray[index], mStartWeightArray[index]);
        mEndBMI[index] = calcBMI(mHeightArray[index], mGoalWeightArray[index]);
        currentClient = index.ToString() + "   ";
        currentClient += formattedName.PadRight(18) + " ";
        currentClient += mAgeArray[index].ToString("##").PadLeft(4) + "      ";
        currentClient += mHeightArray[index].ToString("##.#0").PadRight(4) + "          ";
        currentClient += mStartWeightArray[index].ToString("###.0").PadRight(4) + "         ";
        currentClient += mStartBMI[index].ToString("##.#0").PadRight(4) + "         ";
        currentClient += mGoalWeightArray[index].ToString("###.0").PadRight(4) + "         ";
        currentClient += mEndBMI[index].ToString("###.#0").PadRight(4) + "       ";
        currentClient += mTotalWeeksArray[index].ToString("##").PadRight(4);

        lstClients.Items.Add(currentClient);
    }
    dStartAvgBMI = sumAvg(mStartBMI, arrayIndex);
    dStartHghBMI = maxArray(mStartBMI, arrayIndex);
    dStartLowBMI = minArray(mStartBMI, arrayIndex);
    dEndAvgBMI = sumAvg(mEndBMI, arrayIndex);
    dEndHghBMI = maxArray(mEndBMI, arrayIndex);
    dEndLowBMI = minArray(mEndBMI, arrayIndex);

    strAvgBMI = "";
    strHghBMI = "";
    strLowBMI =  "";
    strAvgBMI = "                                            Average:      " + dStartAvgBMI.ToString("0#.#0") + "                       " + dEndAvgBMI.ToString("0#.#0");
    strHghBMI = "                                            High:         " + dStartHghBMI.ToString("0#.#0") + "                       " + dEndHghBMI.ToString("0#.#0");
    strLowBMI = "                                            Low:          " + dStartLowBMI.ToString("0#.#0") + "                       " + dEndLowBMI.ToString("0#.#0");
    lstClients.Items.Add(strAvgBMI);
    lstClients.Items.Add(strHghBMI);
    lstClients.Items.Add(strLowBMI);
}

A:

I'd strongly recommend using a List<double> instead, since it has a more graceful and efficient strategy for adding and removing items.
There is a significant problem with your algorithm, because you haven't actually used selectedIndex to filter out the 'deleted' item. I think it should look like this
public double[] redrawArray(double[] ary, int selectedIndex)
{
    double[] redoneArray = new double[ary.GetUpperBound(0)];
    int i = 0;
    for (; i < selectedIndex; i++)
    {
        redoneArray[i] = ary[i];
    }
    for (; i < redoneArray.Length; i++)
    {
        redoneArray[i] = ary[i + 1];
    }
    return redoneArray;
}

Or even better:
public double[] redrawArray(double[] ary, int selectedIndex)
{
    double[] redoneArray = new double[ary.GetUpperBound(0)];
    Array.Copy(ary, redoneArray, selectedIndex);
    Array.Copy(ary, selectedIndex + 1,
               redoneArray, selectedIndex, redoneArray.Length - selectedIndex);
    return redoneArray;
}

Update
The real problem, however, is that you're redrawArray method returns a new array rather than modifying the existing array. You'd have to use assign the result array back to your variables, like this:
mFirstNameArray = redrawArray(mFirstNameArray, selectedIndex);
mLastNameArray = redrawArray(mLastNameArray, selectedIndex);
mAgeArray = redrawArray(mAgeArray, selectedIndex);
mHeightArray = redrawArray(mHeightArray, selectedIndex);
mStartWeightArray = redrawArray(mStartWeightArray, selectedIndex);
mGoalWeightArray = redrawArray(mGoalWeightArray , selectedIndex);
mTotalWeeksArray = redrawArray(mTotalWeeksArray, selectedIndex);


Q:

Is usage of DISTINCT redundant in a simple query with an aggregate function

Does DISTINCT in a simple query with an aggregate function have any effect?
select DISTINCT salesperson, SUM(sales_amt) from sales GROUP BY salesperson

I realize there are more complicated queries where DISTINCT can have an affect, such as:
select salesperson, SUM(DISTINCT sales_amt) from sales GROUP BY salesperson

(support for that syntax by platform may vary)
But I want to confirm that in the simple query example, DISTINCT is redundant.
EDIT: fixed missing GROUP BY salesperson

A:

Assuming you are missing GROUP BY salesperson (it's invalid in SQL Server if you omit the group by), the DISTINCT is redundant in your first query.  The GROUP BY effectively performs a DISTINCT here by aggregating salesperson.
select DISTINCT salesperson, SUM(sales_amt) from sales GROUP BY salesperson

And you are, as you've noted, correct that placement of the DISTINCT inside the aggregate SUM() may produce a different rowset.


Q:

LDAP authentication in nestJS

I would like to get some help on how to do LDAP login & authentication in nestJS. I am searching for examples on the internet but never found it. Because I am new at javascript and also nestJS I can't understand node js so I can not make any progress. If there is an example you know, could you please, please share with me ?
Thanks for helping !

A:

To do authentication using LDAP, you must have an LDAP admin user 'baseDN' details and password.
Refer below code with which you can connect to LDAP and authenticate the users.
var express = require('express');

var bodyParser = require('body-parser');

var cors = require('cors');

var passport = require('passport');

var ldapstrategy = require('passport-ldapauth');

// connect to LDAP server

var OPTS = {

  server: {
    url: "LDAP://ldap.forumsys.com:389",     //LDAP URL
    bindDN: "CN=adminAccount,DC=forumsys",      //Admin BaseDN details
    bindCredentials: AdminCredentials,
    searchBase: "dc=forumsys",       //search base
    searchFilter: "(|(sAMAccountName={{username}})(employeeID={{username}}))",
    timeLimit: 3000,
  }
}

passport.use(new ldapstrategy(OPTS));

// instantiate the server
var app = express()

// parse the requested data automatically
app.use(bodyParser.json())

// allow cross-origin resource sharing
app.use(cors())

// inject LDAP connection to express server
app.use(passport.initialize())

// listen to port defined

const port = 8085            //process.env.PORT || 8085

app.listen(port, () => {
  console.log(`Listening on port ${port}`)
})

app.post('/login', (req, res, next) => {

  passport.authenticate('ldapauth', {session: false},(err, user, info) => {

    console.log(user)

    var error = err || info

    if (error){
        return res.send({
        status: 500,
        data: error
      })
    }
    if (!user) {
        return res.send({
        status: 404,
        data: "User Not Found"
      })
    }
    else {
        return  res.send({
        status: 200,
        data: user
      })
    }
  })(req, res, next)
})


Q:

The Matrix of a Linear Mapping

My understanding, from multiple sources (here, books, articles, etc.), is that the columns of the matrix
of a matrix of a linear mapping correspond to the images of the basis vectors in the domain expressed
in terms of the basis vectors in the range. That is, if
$$
\phi:E \rightarrow F
$$
is a linear map,
$$
\mathcal{X} = \{x_1, \dots, x_n \}
$$
is a basis for $E$ and
$$
\mathcal{Y} = \{y_1, \dots, y_m\}
$$
is a basis for $F$ then the $m \times n$ matrix that represents $\phi$ has colums determined by
$$
[\phi(x_1)]_\mathcal{Y}, \dots,  [\phi(x_n)]_\mathcal{Y}
$$
I have encountered a definition, if I am reading it correctly, that seems to turn this definition
on its head. The following excerpt comes from Greub's Linear Algebra, 3rd ed:

Consider two linear spaces $E$ and $F$ of dimensions $n$ and $m$ and a linear mapping $\phi E \rightarrow F$.
  With the aid of bases $x_{\nu}(\nu = 1 \dots n)$ and $y_{\mu}(\mu = 1 \dots n)$  every vector $\phi x_{\nu}$
  can be written as a linear combination of the vectors $y_{\mu}$,
$$
\phi x_{\nu} = \Sigma_{\mu} {\alpha}^{\mu}_{\nu} y_{\mu}.
$$
In this way, the mapping $\phi$ determines an $n \times m$ matrix $({\alpha}^{\mu}_{\nu})$ where $\nu$
  counts the rows and $\mu$ counts the columns

To me, it looks like what he's actually defining is the matrix that represents the transpose of the
mapping rather than the mapping itself. Considering though that this book is supposed to be the
"gold standard" of linear algebra, I'm more inclined to believe that I'm misinterpreting his definition.
On the other hand, he clearly states that the matrix is $n \times m$ and this can only be the case is
if it represents the transpose, at least according to the "accepted" definition of this matrix as
stated at the beginning of this post.
Can anyone shed some light on this?

A:

It depends on whether you write $f(v)=Mv$ with column vectors or $f(v)=vM$ with row vectors. The former seems to be more popular, probably because $Mv$ then keeps the same order as a function application. On the other hand, row vectors are more typographically manageable in running copy, which might make some authors prefer them.
Formally, of course, both ways of doing it are equally valid, just as long as you don't get them mixed up without meaning to.
(At least everyone seem to agree that the entries of a matrix product $AB$ are dot products between columns from $B$ and rows from $A$. Given the notational confusion that reigns in some other areas of mathematics, this should be counted as a lucky break).


Q:

reactjs insert in handle variable state update

I'm new to reactjs and am creating a volume bar.
I update my state with my value and I'd like to enter it in handleclick () {}; so I take updated state and insert it into my function setVolume ();
Is there another way for me to enter my setstate into handleclick (); ?
import React from 'react'
import Slider from 'react-rangeslider'
import 'react-rangeslider/lib/index.css'
import './css/Volume.css'

class VolumeBar extends React.Component

constructor(props, context) {
super(props, context)
this.state = {
  volume: 0
}
}

handleOnChange = (value) => {
this.setState({
  volume: value
})
}

handleClick(volume) {
 window.DZ.player.setVolume()
  }

render() {
    let { volume } = this.state
    console.log(volume);
return (
    <div className="VolumeBar">
    <Slider value={volume} orientation="horizontal" onChange=  {this.handleClick} />
    </div>
);
}
}

export default VolumeBar

A:

Have you tried like that?
<Slider value={volume} orientation="horizontal" onChange=this.handleOnChange} />

handleOnChange = (e) => {
  this.setState({
      volume: e.target.value
})

To set the current volume?


Q:

Records of each version in list

I have a list of versions
1.0.0.1 - 10
1.1.0.1 - 10
1.2.0.1 - 10

That is 30 nr in my list. But I only want to show the 5 highest nr of each sort:
1.0.0.5 - 10
1.1.0.5 - 10
1.2.0.5 - 10

How can I do that? The last nr can be any number but the 3 first nr is only
1.0.0
1.1.0
1.2.0

CODE:
import groovy.json.JsonSlurperClassic

def data = new URL("http://xxxx.se:8081/service/rest/beta/components?repository=Releases").getText()

/**
* 'jsonString' is the input json you have shown
* parse it and store it in collection
*/
Map convertedJSONMap = new JsonSlurperClassic().parseText(data)

def list = convertedJSONMap.items.version

list

A:

Version numbers alone usually don't make an easy sort.  So I'd split them into numbers and work from there.  E.g.
def versions = [
"1.0.0.12", "1.1.0.42", "1.2.0.666",
"1.0.0.6", "1.1.0.77", "1.2.0.8",
"1.0.0.23", "1.1.0.5", "1.2.0.5",
]

println(
    versions.collect{
        it.split(/\./)*.toInteger()  // turn into array of integers
    }.groupBy{
        it.take(2) // group by the first two numbers
    }.collect{ _, vs ->
        vs.sort().last() // sort the arrays and take the last
    }*.join(".") // piece the numbers back together
)
// => [1.0.0.23, 1.1.0.77, 1.2.0.666]


Q:

Angular js if condition not working

I have a statement where I need to assign a variable based on condition:
<b>{{ (varA.count > 1 ? {{'varB.status' | localizedString}} : '') }} </b>

where {{varB.status | localizedString}} filters 'varB.Status' with a localizedString specified in another place
if for example varB.Status is "Test" for the chosen localization it would return "Test"
This gives me error of
Syntax Error: Token 'varB.status' is unexpected, expecting [:]

A:

You have syntax error, you do not need interpolation inside interpolation and that too between incomplete expression. Expression will be evaluated as properties against scope itself, assuming varB is also on the scope.
Just do:-
<b>{{ (varA.count > 1 ? varB.status : '') }} </b>

Demo
If you want to apply filter :-
<b>{{ (varA.count > 1 ? (varB.status | localizedString) : '') }} </b>

or even
<b>{{ (varA.count > 1 ? varB.status : '') | localizedString }} </b>


Q:

How to add element to an Object?

JavaScript:
let stock = {
1001: {product: 'Chocolates', cost: 10, quantity: 0},
1002: {product: 'Biscuits', cost: 10, quantity: 0},
1003: {product: 'Bread', cost: 20, quantity: 0},
1004: {product: 'Milk', cost: 25, quantity: 0},
1005: {product: 'Curd', cost: 20, quantity: 0},

}
So, on the JavaScript side, I have declared an object, "stock". Now using HTML's prompt as input I want to add the input code, product, cost, and quantity.
HTML:

My Shop

Enter the Number of New Products to be Added:

<input type="text" id="numberOfNewProducts" value="" placeholder="Enter the number of new Products to be added">
<button type="button" class="btn btn-default" id="addButton" onclick="addProduct()">Add</button>

The end of the while loop is a little perplexed also.
How do I add the input code and all the products, cost and quantity to the object, "stock"?

A:

Just create a object like:
var obj = {product:"Cookie",cost:10,quantity:0};

then add into the stock like:
stock[inputCode] = obj;


Q:

Teamcity - Global VCS Root for all projects

I am in-charge of ~40 TeamCity builds across 7 or so projects.  Currently, they each have their own Git credentials, which is silly, because they are actually all using the same logon.  They are only slightly different from each other, in that

they checkout different branches
they use a different base repos (but are on the same server)

How can I set this up so they all use the same Git logon in team city, such that when this logon expires, I don't have to reset 30-ish passwords?
I understand that there are build parameters, and I can kind of share VCS roots, but these roots only appear to be visible to builds of the same project... and I don't see a way to do this to the "Root" project.

A:

Shared VCS Root
The Root project would be the place to setup a VCS root that is inherited across all projects; and as the same login is used to authenticate with the host repository server you can simply define this at that root level too.
To add a VCS root in the Root project, navigate to:
https://{HostServer}/admin/editProject.html?projectId=_Root&tab=projectVcsRoots
and from there you can click Create VCS root.  Any build configuration in your TeamCity instance will then have access to attach that VCS root.  Set the login details when creating that VCS root.
Parameterising the VCS root

they checkout different branches

You can parameterise the Default branch to enable the VCS root branch to be dynamically configured based on a build parameter, which would need to be provided / overridden at either a sub-project or configuration level.  For example:
%system.DefaultBranch%
as a Default branch value would require any configuration using the VCS root to provide a value for %system.DefaultBranch%.  You can specify a default value for this parameter at the Root project level to make things easier if you have a lot of configurations using, say, refs/heads/master.

they use a different base repos (but are on the same server)

Similarly, you can parameterise the Fetch URL to enable the VCS root to be dynamically configured based on a build parameter, which would need to be provided / overridden at either a sub-project or configuration level.  For example:
git@bitbucket.org:myname/%system.GitRepositoryName%
as a Fetch URL would require any configuration using the VCS root to provide a value for %system.GitRepositoryName%.  This can be provided as a Project parameter or a Build Configuration parameter.  If you have multiple build configurations that all use the same repository under the same project, then it's probably best to go with the Project parameter approach.


Q:

Does iOS support BC4 compressed texture?

I've been designing a new OpenGL image algorithm using BC4 textures at its core.
It works well accross Windows and Mac, my main targets up to now.
But today, the customer added a new requirement : it should work on iOS too !
I'm starting to worry : is BC4 texture (named GL_COMPRESSED_RED_RGTC1 in OpenGL) supported on iOS devices (tablets & iphones alike) ?
I've read that iOS is OpenGL ES 2.0 capable. But i'm unable to know which textures are supported under this API (except PowerVR ones, which are not compatible with PC & Macs...)

A:

OK, i guess i have to answer my own question.
I have not found a single compressed texture format in common between iOS and PC/Mac.
Apparently, the only type of compressed textures supported by iOS are PowerVR-based, which are completely proprietary (e.g. not part of OpenGL standard).
So I guess my question is included in this answer : iOS does not support BC4 textures.


Q:

Buying stock at discount yields unintuitive rate of return

My employer offers an Employee Stock Purchase Program (ESPP).  Long story short, worst case scenario is that they will purchase stock on my behalf at a 15% discount and then I will immediately sell it.  I am confused as to why my gain is 17.65% as opposed to 15%.  Where does the number 17.65% come from?  It is not intuitive to me.  Example calculation:
On purchase day stock price is 10 USD.
I get to buy it using my discount so, I buy it at (.85*10) = 8.50 USD
I then immediately sell it for 10 USD.
So my gain is (10-8.50)/8.50 = 17.65%

A:

The $15\%$ discount is multiplied by the market price to give your purchase price.  The gain is calculated as a percentage of the discount price, which is lower.  As the absolute discount is the same, the gain on sale must be a higher percentage.
The effect is general and gets larger as the discount percentage increases.  If you get a $50\%$ discount you would buy the stock at $5$.  The immediate profit would then be $100\%$ because you can sell it at $10$.  If your discount is $x$, you buy the stock for $1-x$ and sell it for $1$, so the profit is $\frac x{1-x} \gt x$ because the denominator is less than $1$.


Q:

Displaying IDA names in x64dbg or OllyDbg

I like x64dbg, but, without seeing IDA's names, it's hard to keep track of all the hex.  Is there any way to export IDA's names into x64dbg (ideally contiuously)

A:

The plugin labeless (https://github.com/a1ext/labeless) was created for exactly this purpose. You can now also use x64dbgida (https://github.com/x64dbg/x64dbgida) to import/export x64dbg databases.


Q:

How to get the determinant and inverse of a large sparse symmetric matrix?

For example, the following is a $12\times 12$ symmetric matrix. Det and Inverse take too much time and don't even work on my computer. I don't consider the numerical case.
mat = {
  {a[1, 1], 0, 0, a[1, 4], 0, 0, a[1, 7], 0, 0, a[1, 10], 0, 0},
  {0, a[1, 1], 0, 0, a[1, 4], 0, 0, a[1, 7], 0, 0, a[1, 10], 0},
  {0, 0, a[3, 3], 0, 0, a[1, 4], 0, 0, a[1, 7], 0, 0, a[1, 10]},
  {a[1, 4], 0, 0, a[4, 4], 0, 0, a[4, 7], 0, 0, a[4, 10], 0, 0},
  {0, a[1, 4], 0, 0, a[4, 4], 0, 0, a[4, 7], 0, 0, a[4, 10], 0},
  {0, 0, a[1, 4], 0, 0, a[6, 6], 0, 0, a[4, 7], 0, 0, a[4, 10]},
  {a[1, 7], 0, 0, a[4, 7], 0, 0, a[7, 7], a[7, 8], a[7, 9], a[7, 10], 0, 0},
  {0, a[1, 7], 0, 0, a[4, 7], 0, a[7, 8], a[8, 8], a[8, 9], 0, a[7, 10], 0},
  {0, 0, a[1, 7], 0, 0, a[4, 7], a[7, 9], a[8, 9], a[9, 9], 0, 0, a[7, 10]},
  {a[1, 10], 0, 0, a[4, 10], 0, 0, a[7, 10], 0, 0,  a[10, 10], a[10, 11], a[10, 12]},
  {0, a[1, 10], 0, 0, a[4, 10], 0, 0, a[7, 10], 0, a[10, 11], a[11, 11], a[11, 12]},
  {0, 0, a[1, 10], 0, 0, a[4, 10], 0, 0, a[7, 10], a[10, 12], a[11, 12], a[12, 12]}
}

A:

The determinant computation is a matter of memory use in terms of how much we want to store for subdeterminants of a Laplace expansion. Mathematica simply refuses to go that route after 11x11. YOu can do your own as below.
myDet[mat_] /; Length[mat] <= 4 := Det[mat]
myDet[mat_] :=
 myDet[mat] =
  Sum[mat[[1, j]]*myDet[Drop[mat, {1}, {j}]], {j, Length[mat]}]

Timing[dd = myDet[mat];]

(* Out[79]= {0.870000, Null} *)

Using this matrix in solving linear equations will be harder. Might try playing with the Method option, e.g.
SeedRandom[1111];
rhs = RandomInteger[{-100, 100}, Length[mat]];

Timing[
 soln = LinearSolve[mat, rhs, Method -> "OneStepRowReduction"];]

(* Out[83]= {236.080000, Null} *)

LeafCount[soln]

(* Out[84]= 14521350 *)

Slow, and a huge result. No surprises there.


Q:

Create rounded button with inset edge, gradient and inset text with Gimp

This is my first attempt at seriously using Gimp. I am more of a front end developer slash developer myself and I have only used Gimp or Photoshop for very basic stuff such as removing backgrounds, cropping. So this the first time I want to do more and as I am planning on ditching PS I am trying to work with Gimp.
Please see attached image
.
It shows simple rounded buttons with nice inner shades and a beveled background as well as inlaid text. How in Gimp do I:

Create this shade gradient effect on the button?
Do the inlaid/embossed inset text effect?
Make the button background with the inset lines?

Thanks in advance for your help!
Update
Checking http://www.youtube.com/watch?v=p1K3L7RdbKw for engraved text (engraved = embossed)

A:

You will have to use gradient to get that kind of background.
Go through this nice tutorial to understand how gradient works :
http://mygimptutorial.com/round-web-20-button-with-a-metal-ring
And then play around according to your needs. Let me know if you need help with anything specific.


Q:

jQuery hidden ajax optimization

jQuery('select[field]').each(function(){
    var jobj = $(this);
    var pre_field_name = jobj.attr('filtered_by');
    var parent_field_name = jobj.attr('field');
    var data_url =jobj.attr('data-url');
    var val = jobj.val();
    $('select[name='+parent_field_name+']').change(function(){
        console.log('change');
        if($(this).val()){
            console.log('ajax');
            $.get(data_url, {'pk': $(this).val()}, function(response){
                console.log('response');
                var options = '';
                for (var i = 0; i < response.length; i++) {
                    options += '<option value="' + response[i].value + '" '+  (val==response[i].value?'selected="selected"':'') +  '>' + response[i].display + '</option>';
                }
                jobj.html(options);
                jobj.change();
            })
        } else {
            jobj.html('<option value="">------</option>');
            jobj.change();
        }
    }).change();

})

If there are 3 elements on my page that satisfy this jQuery('select[field]') selector - then, in chrome logs I'll see six (doubled by .change() I guess) response log records. But in network tab of chrome console and in server logs, I see that there was only one request. What can be the reason?

A:

It's not hidden optimization, it's a documented behavior that caches the http response,
Cache

If set to false, it will force requested pages not to be cached by the
  browser. Note: Setting cache to false will only work correctly with
  HEAD and GET requests. It works by appending "_={timestamp}" to the
  GET parameters. The parameter is not needed for other types of
  requests, except in IE8 when a POST is made to a URL that has already
  been requested by a GET.


Q:

Disconnect unknow connections at TIdTcpServer OnConnect

I'm having a problem.  I created a TIdTCPServer but I need to prevent false/unknown connections.
I tried this:
procedure Wait(millisecs: Integer);
var
  tick: dword;
  AnEvent: THandle;
begin
  AnEvent := CreateEvent(nil, False, False, nil);
  try
    tick := GetTickCount + dword(millisecs);
    while (millisecs > 0) and (MsgWaitForMultipleObjects(1, AnEvent, False, millisecs, QS_ALLINPUT) <> WAIT_TIMEOUT) do begin
      Application.ProcessMessages;
      if Application.Terminated then Exit;
      millisecs := tick - GetTickcount;
    end;
  finally
    CloseHandle(AnEvent);
  end;
end;

procedure CheckCon(Con: Pointer);
begin
  Wait(5000);

  if TClient(Con).HWID = '' then TClient(Con).Connection.Disconnect;
  EndThread(0);
end;

constructor TClient.Create(AConnection: TIdTCPConnection; AYarn: TIdYarn; AList: TIdContextThreadList = nil);
var
  ThreadId : Cardinal;
begin
  inherited Create(AConnection, AYarn, AList);

  FCriticalSection  := TCriticalSection.Create;
  Queue             := TIdThreadSafeStringList.Create;

  BeginThread(nil, 0, @CheckCon, Self, 0, ThreadId);
end;

OnConnect event code:
procedure TForm1.IdTCPServer1Connect(AContext: TIdContext);
var
  Conexao : TClient;
  Retorno : TArray<String>;
  Query   : TFDQuery;
  Libera  : Boolean;
  IPEX    : Boolean;
begin
  Libera  := True;
  IPEX    := True;
  Conexao := TClient(AContext);
  Retorno := AContext.Connection.IOHandler.ReadLn.Split(['#']);

  if Length(Retorno) = 0 then
  begin
    AContext.Connection.Disconnect;
    Exit;
  end;

  Conexao.IP          := AContext.Connection.Socket.Binding.PeerIP;
  Conexao.HWID        := Retorno[1];
  Conexao.Connected   := Now;
  Conexao.Ping        := Ticks;

  ClientStateUpdated(Conexao, RetornaTraducao(40));

TThread.Queue(nil,
              procedure
              begin
                Memo2.Lines.Add(Format(RetornaTraducao(36), [TimeToStr(Now), Conexao.IP, Conexao.HWID]));
              end);
end;

If I test creating a low number of unknown clients, it works good, but if I flood it with MANY connections, the application crashes. I need something like this to prevent unknown connections in my TIdTCPServer.
I tried calling
Memo2.Lines.Add(Format('[%s]', [AContext.Connection.IOHandler.ReadLn]));

in IdTCPServer1Connect to determine if the connection was my application, but if the client only connects and doesn't send anything, the line doesn't execute.

A:

Starting a worker thread inside of TClient's constructor is completely unnecessary (the TClient object is already run in a thread created by the server). You can simply set a 5 second timeout on the ReadLn() call itself and be done with it.
Also, TIdTCPServer is a multi-threaded component, its events are fired in the context of worker threads, so access to UI controls like Memo2 MUST by synchronized with the UI thread or else bad things happen.
Try something more like this:
constructor TClient.Create(AConnection: TIdTCPConnection; AYarn: TIdYarn; AList: TIdContextThreadList = nil);
begin
  inherited Create(AConnection, AYarn, AList);

  FCriticalSection  := TCriticalSection.Create;
  Queue             := TIdThreadSafeStringList.Create;
end;

...

// code adapted from my reply to your previous question:
//
// https://stackoverflow.com/a/58479489/65863
//
// tweak as needed...
//
procedure TForm1.ClientStateUpdated(Client: TClient; const Msg: string);
var
  IP, HWID: string;
begin
  IP := Client.IP;
  HWID := Client.HWID;

  TThread.Queue(nil,
    procedure
    begin
      Memo2.Lines.Add(Format(RetornaTraducao(36), [TimeToStr(Now), IP, HWID, Msg]));
    end
  );
end;

procedure TForm1.IdTCPServer1Connect(AContext: TIdContext);
var
  Conexao : TClient;
  Retorno : TArray<String>;
begin
  Conexao := TClient(AContext);
  Retorno := AContext.Connection.IOHandler.ReadLn(LF, 5000).Split(['#']);

  if (Length(Retorno) < 2) or (Retorno[1] = '') then
  begin
    AContext.Connection.Disconnect;
    Exit;
  end;

  Conexao.IP          := AContext.Binding.PeerIP;
  Conexao.HWID        := Retorno[1];
  Conexao.Connected   := Now;
  Conexao.Ping        := Ticks;

  ClientStateUpdated(Conexao, RetornaTraducao(40){'connect'});
end;

procedure TForm1.IdTCPServer1Disconnect(AContext: TIdContext);
var
  Conexao : TClient;
begin
  Conexao := TClient(AContext);

  if Conexao.Connected <> 0 then
    ClientStateUpdated(Conexao, RetornaTraducao(...){'disconnect'});
end;


Q:

Two computers in a workgroup, A can see shares on B, but B requires user credentials to see shares on A. What haven't I set?

I have two computers. Lets call them A and B. Both are on the same Workgroup (at least I think they are as far as I can see the workgroup names match). Both are running Windows XP Pro SP3. B is fully up to date, A is in the process of being updated as it's a new installation (the previous incarnation of A died).
A can see B on the network and can browse to B's shared folders. I don't need to enter any user credentials to do this.
B can see A exists but won't browse to A's shared folders or even list them until I enter the credentials of a user on A.
I'm certain it's not the firewall settings I have set it to allow all local network traffic.
I don't think it's anything to do with the way I have shared the folders as I have to enter the credentials before I can even see the shares, let alone browse to them.
Everything I've checked so far indicates that I've enabled File and Printer Sharing on A, but I didn't do this explicitly when I installed the OS.
What else do I need to do on A to allow B to see it's shares without needing a user id and password?
I should add that before I had to rebuild A the two computers could browse each others shared folders just fine. There's clearly something I've forgotten to do this time round.

A:

I've worked out what's going on here. It's down to the accounts set up on each machine and their passwords. Thanks to heavyd for putting me on the right track.
Machine B (the older installation) has two Admin accounts B1 and B2
Machine A (the new installation) has two Admin accounts A1 and A2, plus a number of User accounts (which don't affect the behaviour but are relevant).
The user names and passwords on accounts A1 and B1 match. The user names on accounts A2 and B2 match, but the passwords don't.
A can see B because I'm logged in with account A1 (where everything matches B1).
B can't see A because I'm logged in with account B2 where the names match but the passwords don't. The reason they don't is because I'm locking down the accounts on A to stop the kids installing random stuff, so I'm keeping the password to A1 secret. I will be adding User accounts to B when I do a full OS reinstall in a couple of weeks time. When I do I'll set the accounts so that their names and passwords match those on A.
The primary account on B is B2 and I had forgotten that I'd set account B1 to have the same password as the new A1 account. Hence my confusion.


Q:

.bashrc edit messes up terminal command arrow-up history print

I wanted to give my terminal prompt in Ubuntu a more personal look, and wanted to change the text prior to the '$' when writing a command.
From what I've found this is done by editing the .bashrc file in the home directory, so I went in there and changed
if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi

to
if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
    PS1='\e[1;32m[\W]\$ \e[m'
fi

This works and the terminal looks the way I want it to.
But after some time when entering a couple of commands when I use the arrow-up key to get to the command history, things get weird.
From a clean line and pressing the arrow-up key is works. When pressing it again the text that was on the line gets capped at about ~15 characters and the new command in the history (that is supposed to be displayed) gets capped by a few characters in the beginning, and they are sort of merged together on the command line.
E.g. my two most recent commands are
Java Test4 words-250.txt words-250-in.txt
Javac Test4.java

When pressing the arrow-up key once, the first line is displayed, as it should. When pressing it a second time, this is displayed:
Java Test4 worc Test4.java

Despite this weird output, the terminal works fine. If for instance I press enter after doing the above, Javac Test4.java will run. If I instead try to delete the entire line using backspace, I am only able to delete up until the line says
Java Test4

and if pressing enter after that I get a new empty line, just as if the line was empty when pressing enter.
All of this goes away if I reset the .bashrc file.
Why does this happen and how can I fix it?

A:

I have no idea why (never really understood the escape codes), but adapting the other prompt seems to work:
PS1='\[\033[1;32m\][\W]\$ \[\033[00m\]'

Apparently, you need to enclose the escape sequences in \[...\], to tell bash not to count them while determining the prompt width. Therefore, both the above PS1 and the following would work equally well:
PS1='\[\e[1;32m\][\W]\$ \[\e[m\]'


Q:

How to center the text vertically with richtextbox?

Follow code:
The idea is to center the text horizontally and vertically.
The code below, the text is centered horizontally.
<RichTextBox
    x:Name="richtextbox"
    Height="285"
    Width="341"
    Margin="10,53,0,0"
    VerticalAlignment="Top"
    FontSize="14"
    VerticalContentAlignment="Center"
    HorizontalContentAlignment="Center"
    UseLayoutRounding="False"
    VerticalScrollBarVisibility="Auto"
    Block.TextAlignment="Center"
    Grid.ColumnSpan="2"
    HorizontalAlignment="Left"
    TextChanged="richtextbox_TextChanged"
    BorderThickness="1">
    <FlowDocument>
        <Paragraph>
            This is flow content and you can
            <Bold>edit me!</Bold>
        </Paragraph>
    </FlowDocument>
</RichTextBox>

Result:

With the richtextbox tool you can not center the text vertically. Is there anyway to center text in C#? Implementing C# code to center richtextbox, is it possible?
Maybe I can work to center it with richtextbox.BorderThickness = new Thickness (1, 1, 1, 1);, changing the value of top.
Any solution?

A:

<Border BorderBrush="Black" BorderThickness="1">
<Grid Height="285" Background="White" >
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <ScrollViewer Grid.Row="1" MaxHeight="285" VerticalScrollBarVisibility="Auto">
    <RichTextBox
        x:Name="richtextbox"
        Width="341"
        VerticalAlignment="Top"
        FontSize="14"
        VerticalContentAlignment="Center"
        HorizontalContentAlignment="Center"
        UseLayoutRounding="False"
        VerticalScrollBarVisibility="Auto"
        Block.TextAlignment="Center"
        Grid.ColumnSpan="2"
        HorizontalAlignment="Left"
        BorderThickness="0">
        <FlowDocument>

            <Paragraph>
                This is flow content and you can
                <Bold>edit me!</Bold>
            </Paragraph>
        </FlowDocument>
    </RichTextBox>
    </ScrollViewer>
</Grid>
</Border>

probably not ideal, but it will look the same.


Q:

Detect different kinds of circles and ovals on the image using OpenCV and Python

I need to detect the different shapes on the image such as ellipses and circles with a dashed-border.
Using OpenCV causes some troubles, for e.g. openCV detects not a contour but an amount of small separated lines(contours).
In case of ellipse with a "dashed-border" I need it to be as single contour, not a separated objects.
What would you suggest to solve this problem?
I also need to recognize the ellipses(or circles) with solid border and ellipses(circles) with a dashed-border
Ellipse with solid border

Ellipse with dashed border:

A:

The Hough transform should not have any troubles with either dashed or solid borders, or a mix thereof. I have used it to detect dashed lines in one of my project and ellipses should not be much harder.
OpenCV by default only implements the Hough transform for circles and straight lines but there is a blog entry with code on how to adapt it for elliptical shapes.


Q:

date range picker not working properly

I am trying to add daterangepicker to my page. It should be very simple but it is not working. It gives output Invalid date when I select Today, 7 Days or other range buttons. Please check my following code
  <link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" type="text/css" media="all" href="daterangepicker.css" />

Your Date Range Picker

        <input type="text" id="config-demo" class="form-control">

SCRIPT

A:

Use momentjs to convert the hardcoded date strings to a format daterangepicker can comprehend :
...
"ranges": {
    "Today": [
        moment("2015-10-02T11:06:15.319Z"),
        moment("2015-10-02T11:06:15.319Z")
    ],
    "Yesterday": [
        moment("2015-10-01T11:06:15.319Z"),
        moment("2015-10-01T11:06:15.319Z")
    ],
    "Last 7 Days": [
        moment("2015-09-26T11:06:15.319Z"),
        moment("2015-10-02T11:06:15.319Z")
    ],
    "Last 30 Days": [
        moment("2015-09-03T11:06:15.319Z"),
        moment("2015-10-02T11:06:15.319Z")
    ],
    "This Month": [
        moment("2015-09-30T19:00:00.000Z"),
        moment("2015-10-31T18:59:59.999Z")
    ],
    "Last Month": [
        moment("2015-08-31T19:00:00.000Z"),
        moment("2015-09-30T18:59:59.999Z")
    ]
},
...

Then your code works -> http://jsfiddle.net/jz4tpbrh/
Also corrected the log message
console.log("New date range selected: " + start.format('MM-DD-YYYY') + " to " + end.format('MM-DD-YYYY') + " (predefined range: " + label + ")");


Q:

Highcharts - add additional export options without losing default ones

I'm trying to add an export-to-csv option to a Highcharts chart, without actually removing all the default options (print, PNG, JPG, PDF, SVG export). The solution offered in Highcharts add export as csv results in the existing options being blown away, as does trying to use the Exporting class in DotNet.Highcharts. Is there a way to achieve this?
NB: I can see how to achieve what I want by editing exporting.js, but that's not a desirable way to go about it :)

A:

You can add the new item to the menu right after you define the chart:
Highcharts.getOptions().exporting.buttons.contextButton.menuItems.push({
    text: 'My new button',
    onclick: function () {
        alert('OK');
    }
});

This will keep the default items.
Demo: http://jsfiddle.net/3GNZC/


Q:

Creating websites templates. Spacing on two separate designs is different although it should be the same

My templates are almost same in design besides a an additional gap in spacing I can not explain.

First template, it is divided into two parts, left has some text and right has buttons on it.
    <!DOCTYPE html>

            <link type="text/css" rel="stylesheet" href="stylesheet.css"/>
            <title></title>

                    Something2

 Topicus

 Random Text

                        Sapien

Second template, this one isn't divided vertically but horizontally. With text first and then some buttons after.
    <!DOCTYPE html>

            <link type="text/css" rel="stylesheet" href="stylesheet.css"/>
            <title></title>

                    Something

 Venieie

 Lorem ipsum dolor sit amet,

                    this

After the page title in the
, each page has a
 of class b.
#b is exactly the same in both documents.
#b {

    top: 70px;
    position: relative;

    }

Although the only thing separating text block from the title in both designs is #b spacer/divisor the distance when displayed is different for both of these templates. I am out of ideas what is the root of it, I can fix it by having 2 different values of top:, but obviously this isn't the right way to do it.

A:

when you use float, the ordering of arrange html tags is different. in one template, you used float and the other not.