Q:

ASP.NET Chart Custom Label Show HH:MM:SS From Total Time In Seconds

I need to add a custom label to my chart to show HH:MM:SS in asp.net the time coming from the sql server is in seconds and the chart is being filled as follows:
    SqlConnection con = new SqlConnection(easystone);
    SqlDataAdapter graph = new SqlDataAdapter("SELECT [User], sum([Total Time]) as [total time]  ,[week] FROM [Toolpaths].[dbo].[totaltimeuser] where [week] like '" + DropDownList2.Text + "' group by [user], [week] order by 'total time' desc", con);
    DataTable graphdata = new DataTable();
    graph.Fill(graphdata);
    chart1.DataSource = graphdata;

    chart1.ChartAreas["ChartArea1"].AxisX.Title = "";

    chart1.Series["Series1"].XValueMember = "User";
    chart1.Series["Series1"].YValueMembers = "total time";
    year.Text = DropDownList2.Text;

A:

Try this:
    protected void Page_Load(object sender, EventArgs e)
    {
        foreach (DataRow row in graphdata.Rows)
        {
            int total = (int)row["total time"];
            int index = chart1.Series[0].Points.AddXY(row["User"], new object[] { total });

            chart1.Series[0].Points[index].Label = string.Format("{0:00}:{1:00}:{2:00}", (total / 60) / 60, (total / 60) % 60, total % 60);
        }
    }


Q:

How String.charAt(int i) is implemented in Java?

If I want to check every char in a String using String.charAt(int i), would it count from start every time or it is converted to an array automatically and get the charAt index directly?
Would it be more efficient if I create a char array by String.toCharArray() and then go through the array by index?
Can I check this up in JavaDoc? Where?

A:

The JRE is mostly open source. You can download a zip file here or browse online with websites like grepcode.
String.charAt:
public char charAt(int index) {
    if ((index < 0) || (index >= value.length)) {
        throw new StringIndexOutOfBoundsException(index);
    }
    return value[index];
}


Q:

Firefox defaulting to several Mobile Websites

My problem involved specifically firefox defaulting to mobile sites (but only certain mobile sites).  Here is the fix that worked for me.

A:

go into the: "about:config" area of Firefox (type into browser url, ok through warning).
Checked a couple hundred lines.. changed some to default values then I saw one stand out.
network.http.accept.default = "text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8,text/vnd.wap.wml;q=0.6"
The second I saw that wap.wml I knew we had a problem.. turns out via the firefox knowledge base that the q value sets the preference (0.0 lowest, 1.0 highest). When I clicked the reset button the value shot back to:
network.http.accept.default = "text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8
I didn't look at the source code of the pages that I had problems with.. but 2 of them were: www.cnn.com and www.paypal.com (both of which shot me to m. version of the page).
after just recently working w/ some htaccess files.  I realized that the coding in the htaccess (or in the site's javascript, depending on how you do it) will detect what type of device your own.  Some will work w/ your browsers/device. some will look for what your capabilities are.  The problem I had as specified above is that my firefox said I was wap capable... some htaccess files say: if wap capable then go to mobile site.  Others will say if browser/device = "" then go to mobile site.  So really it's how the company codes their backend.. The problem being is that the htaccess isn't taking into consideration the weights of what type you prefer to accept.
anyways fixed and shared..


Q:

How do I import shared object libraries at runtime in Android?

I am developing an open-source emulator project, and it has multiple, customizable native plug-ins.  These plug-ins are built as native shared object libraries (.so files), and have various interfaces between native and Java through JNI.  Rather than distribute the APK with every single plug-in ever created, and in order to allow folks to build their own custom plug-ins, I need a method of importing these .so files any time after the app has been installed.
I've found that I can copy files to the folder /data/data/[package_name], but not to the lib/ sub-folder (because it is owned by the "system" group).  To utilize the JNI interfaces in Java, I must call System.loadLibrary( libname );  However, this seems to require the .so file to be located in the lib/ sub-folder.  The only way around this I can think of is to require the user to have a rooted device.  Is there another way to accomplish this?

A:

Use System.load() instead:
static
{
    final String[] libs = {
        "/data/data/com.foo.test/lib/liba.so",
        "/data/data/com.foo.test/lib/libb.so"
    };

    for (int i=0; i<libs.length; ++i)
    {
        Log.d(TAG, "Loading " + libs[i] + "...");
        System.load(libs[i]);
    }
}

$ adb logcat
D/LibTest ( 1022): Loading /data/data/com.foo.test/lib/liba.so...
D/dalvikvm( 1022): Trying to load lib /data/data/com.foo.test/lib/liba.so 0x40512640
D/dalvikvm( 1022): Added shared lib /data/data/com.foo.test/lib/liba.so 0x40512640
D/dalvikvm( 1022): No JNI_OnLoad found in /data/data/com.foo.test/lib/liba.so 0x40512640, skipping init
D/LibTest ( 1022): Loading /data/data/com.foo.test/lib/libb.so...
D/dalvikvm( 1022): Trying to load lib /data/data/com.foo.test/lib/libb.so 0x40512640
D/dalvikvm( 1022): Added shared lib /data/data/com.foo.test/lib/libb.so 0x40512640
D/dalvikvm( 1022): No JNI_OnLoad found in /data/data/com.foo.test/lib/libb.so 0x40512640, skipping init


Q:

How to remove blank cells from dataframe?

I have the attached csv file. How can I fill the blank cells with NA or remove them?
I have tried following codes from Change the Blank Cells to "NA" but nothing happens.
sm2=read.csv('sample_info_2.csv',header=T, na.strings=" ")
sm3 <- sm2 %>% mutate_all(na_if,"")
sm3=sm2[complete.cases(sm2),]

I want to remove the blank cells or fill them with NA. Any help? Best, Zillur

A:

I think @akrun's comment is right (and this really should be handled on data-import if possible), but if you need to handle it post-import then it might be missing one point: since your mutate_all(na_if, "") did not work, you have fields that are whitespace-only with one or more whitespace characters. If all of these fields have the same amount of whitespace, then perhaps
sm2 %>% mutate_all(na_if, " ") # or "  " or "   " ...

will work, but it is inflexible. A more accommodating technique might be:
sm2 %>% mutate_if(is.character, ~ if_else(grepl("\\S", .), ., NA_character_))

which does two things:

I do not assume that all of your columns are strings, so mutate_if(is.character, ...) instead of mutate_all, perhaps minor; and
grepl("\\S", .) will return TRUE for all elements of a vector that have one (or more) non-whitespace character, and the if_else handles replacement when false. (It might also be feasible to picture this as nzchar(gsub("\\s", "", .)) which first removes all whitespace and then returns true for string length greater than 0.)


Q:

Xpath sum valubles from multiple nodes

So i want to find the total screen time for movies where Star Wars is part of the movie name. Should return an integer number
//Disney/Subsidiaries/Subsidiary[@id='Lucasfilms']
  <Subsidiary id="Lucasfilms">

  <Movie>
    <Name lang="en">Star Wars: The Force Awakens</Name>
    <Year>2015</Year>
    <ScreenTime unit="minutes">135</ScreenTime>
    <Cast>
  <Movie>
    <Name lang="en">Star Wars: The Last Jedi</Name>
    <Year>2017</Year>
    <ScreenTime unit="minutes">152</ScreenTime>
    <Cast>
  <Movie>
    <Name lang="en">Solo: A Star Wars Story</Name>
    <Year>2018</Year>
    <ScreenTime unit="minutes">135</ScreenTime>
    <Cast>

I do know ur supposed to use sum, but i struggle to put it together. May someone please help me

A:

I constructed a well-formed XML based on my imagination. Here is a working sample for you.
XML
<Disney>
    <Subsidiaries>
        <Subsidiary id="Lucasfilms">
            <Movie>
                <Name lang="en">Star Wars: The Force Awakens</Name>
                <Year>2015</Year>
                <ScreenTime unit="minutes">135</ScreenTime>
            </Movie>
            <Movie>
                <Name lang="en">Star Wars: The Last Jedi</Name>
                <Year>2017</Year>
                <ScreenTime unit="minutes">152</ScreenTime>
            </Movie>
            <Movie>
                <Name lang="en">Solo: A Star Wars Story</Name>
                <Year>2018</Year>
                <ScreenTime unit="minutes">135</ScreenTime>
            </Movie>
        </Subsidiary>
    </Subsidiaries>
</Disney>

XPath
sum(/Disney/Subsidiaries/Subsidiary[@id='Lucasfilms']/Movie/ScreenTime/text())

Outcome:
422


Q:

Difference between Interop Outlook and Outlook Object Library

I have a question about visual studio, I noticed when you add references in the COM section you can find: Microsoft Office Outlook 12.0 Object Library. While on the Assemblies you can see the Microsoft.Office.Interop.Outlook
I would like to know the difference between this two, I tried researching but i have only found topics on each one of those but not the differences, I would love if somebody could provide me with an explanation, Juts simple curiosity. (I'm kind of a beginner). Thanks!

A:

They are both pretty much the same - when you reference OOM from the COM tab, VS under the covers creates an interop dll (which is essentially nothing  but a header file in a binary format). That is the same interop dll that you can add to your project as a reference.
The biggest advantage of adding a reference to an interop dll instead of the COM library itself is the ability to build the project even if the COM library is not installed, e.g.on a dedicated builder machine, which might not have Office installed.


Q:

What libraries/code to I need to use a MyoWare muscle sensor with a Raspberry pi?

My robotics class is trying to take signals from a MyoWare Muscle Sensor and feed them to a Raspberry Pi Zero. For ADC, we are using a MCP3008 chip.
Because most people use Arduinos for these sensors, we can't find any example code or libraries. Does anyone know of a place where we can start, code-wise? We are trying to use c++.

A:

This is a minimal example in C how to interface an I²C chip (a DS7505 in that case) without any further libraries. You have to read the MCP3008 datasheet, then tweak that example program as you need it for your chip.


Q:

What is this hanging, green-white plant?

I brought this plant and it didn't have a name or instructions attached to it as other ones they sell. Would anyone know what kind of plant this is and how to maintain it? It's really pretty and I would hate for it to die due to ignorance.

A:

What you have is "Marble Queen" Pothos, a variegated variety of Pothos, Epipremnum aureum. This is a very easy to maintain houseplant. It is also quite easy to propagate.
Please refer to the internet where extensive information on maintenance is available. Low to moderate light, moist soil and very occasional fertilization is all that is usually needed. I'd definitely keep the plant away from pets.
FYI, I grow this outdoors in Zone 9B in a very shaded area.


Q:

Childrens/YA fantasy series with wizard siblings and homeless Angels

When I was younger I read this fantasy series involving two siblings who find out they are wizards. Their parents are involved to some extent but I think they are mostly learning from their uncle (maybe? a slightly older gentleman at least).
There are some things that I remember specifically including: that there is one scene in which the mother tells one of the children that they should always treat homeless people with kindness and give them any money they could. This is because sometimes homeless people were Angels who would watch over you after showing selflessness; in one of the books there is a detailed description of the hanging gardens of Babylon in which they are residing at the time. Another thing I remember is that wizards were capable of drawing perfect circles and lines because of their use in many spells.
I am pretty sure that it was a trilogy, or maybe when I read it there were only three books written, I think I read them sometime between 2006-2010.

A:

This immediately reminded me of when I read the first volume of the "Children of the Lamp" series by P. B. Kerr. I did a little Googling just now to confirm my very vague recollections. (If you click on the series title, the link will take you to Wikipedia's detailed entry on the entire series.)
Here are some points of correspondence between your description and what I can confirm from other sources:

When I was younger I read this fantasy series involving two siblings who find out they are wizards.

The co-stars of the series are John and Philippa Gaunt, twins who are 12 years old as the series starts.

Their parents are involved to some extent but I think they are mostly learning from their uncle (maybe? a slightly older gentleman at
  least).

The Wikipedia entry for the series says:

During an operation to get the wisdom teeth removed, they both have
  the same dream in which their uncle, Nimrod, asks that they come to
  London. He tells them that they are djinn (genies).

The Wikipedia entry also confirms (as I thought I remembered) that the twins' mother tried her best to live as a normal person (i.e. zero use of magic powers) after she married her non-magical husband and settled down to raise children with him. Which explains why her brother Nimrod is the one who takes the lead in teaching the kids about magic when they're old enough to benefit from the instruction.

There are some things that I remember specifically including: that there is one scene in which the mother tells one of the children that
  they should always treat homeless people with kindness and give them
  any money they could because sometimes homeless people were Angels who
  would watch over you after showing selflessness;

I can't swear that I remember that bit of advice from their mother (although you may well be right), but a little Googling found this in a character entry on the Wiki dedicated to the series:

Afriel was an angel, disguised as a homeless person, who met John and
  Philippa in the third book.

Also:

in one of the books there is a detailed description of the hanging gardens of Babylon in which they are residing at the time.

I cannot swear to the "detailed description" part, but Book 2 is titled The Blue Djinn of Babylon and some Googling tells me that it does, in fact, involve a visit to the famous Hanging Gardens.

I am pretty sure that it was a trilogy, or maybe when I read it there were only three books written, I think I read them sometime
  between 2006-2010.

Wikipedia says Book 1 came out in 2004, and Books 2 and 3 came out in 2006. So if you first noticed the series around late 2006, there would have been just three volumes available in bookstores and libraries at that time. (But the full series only ended when Book 7 was released in 2011.)


Q:

Checkmark in table disappearing only after second touch on device

I got the checkmarks appearing and disappearing correctly when scrolling and it works perfectly on simulator.
However on the device, a 4s, the touch to make the checkmark disappear again does not work properly. Meaning, I need to touch the row, which I want the checkmark to disappear twice. Only after the second touch the checkmark disappears.
Furthermore all selected columns remain with the blue background until I touch them again.
So here is the sequence (on the device):

touch row is selected, blue background, checkmark appears
touch on the same row blue background disappears, checkmark remains
touch on the same row, checkmark disappears, blue background

What I definitely need, is that the checkmark disappears, as soon as I touch the row again, actually the behavior I am having on the simulator.
The background I guess I am able to control via the didDeselectRow method. However, I struggle with imagining, how to control the checkmark issue. Any ideas??
Here is the code from the didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

NSInteger thisCardID;
NSInteger thisCardIndex;
NSString *cellValue;

UITableViewCell *thisCell = [tableView cellForRowAtIndexPath:indexPath];
cellValue = thisCell.textLabel.text;

if(searching) {
    thisCardID = [[self.aCopyOfCardIDArray objectAtIndex:indexPath.row] integerValue];
    thisCardIndex = [self.aCopyOfCardIDArray indexOfObject:[NSNumber numberWithInteger:thisCardID]];
    if (thisCell.accessoryType == UITableViewCellAccessoryNone) {
        [self.searchedSelectedRowArray replaceObjectAtIndex:thisCardIndex withObject:@"YES"];
        thisCell.accessoryType = UITableViewCellAccessoryCheckmark;
        [self.searchedSelectedCardIDs addObject:[NSNumber numberWithUnsignedInteger :thisCardID]];
    }
    else {
        [self.searchedSelectedRowArray replaceObjectAtIndex:thisCardIndex withObject:@"NO"];
        thisCell.accessoryType = UITableViewCellAccessoryNone;
        [self.searchedSelectedCardIDs removeObject:[NSNumber numberWithUnsignedInteger:thisCardID]];
    }

}
else {
    thisCardIndex = [self.tempCardArray indexOfObject:cellValue];

    if (thisCell.accessoryType == UITableViewCellAccessoryNone) {
        [self.selectedRowArray replaceObjectAtIndex:thisCardIndex withObject:@"YES"];
        thisCell.accessoryType = UITableViewCellAccessoryCheckmark;
        [self.selectedCardIDs addObject:[NSNumber numberWithUnsignedInteger :thisCardID]];
    }
    else {
        [self.selectedRowArray replaceObjectAtIndex:thisCardIndex withObject:@"NO"];
        thisCell.accessoryType = UITableViewCellAccessoryNone;
        [self.selectedCardIDs removeObject:[NSNumber numberWithUnsignedInteger:thisCardID]];
    }
}

}

To make sure I am making myself clear, I added some screenshots:

A:

Was to early to go to sleep and Heureka, it's the didDeselectRowAtIndexPath which does the magic. That's why the second touch is not recognized by the didSelect... method. Logical, if you know it :-)
Now it's time to count sheeps...
Here the code:
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *thisCell = [tableView cellForRowAtIndexPath:indexPath];
thisCell.selectionStyle = UITableViewCellSelectionStyleNone;
thisCell.accessoryType = UITableViewCellAccessoryNone;
}


Q:

Canceling an async call on a static HttpClient

I am using a static HttpClient (for scalability reasons - see What is the overhead of creating a new HttpClient per call in a WebAPI client?) and would like to be able to cancel individual requests that take too long. There is an overload on SendAsync that takes a CancellationToken - but I don't know if it's thread-safe since my HttpClient instance is static. For example, if I have several requests being sent thru the HttpClient simultaneously and I try to cancel one, does it cancel the right one?
I looked thru the HttpClient code and at first glance it doesn’t look like it is thread-safe to do so since the cancellation is sent to the HttpClientHandler (which is the same for all requests). But I could be missing something.  So my questions are:

Can I cancel individual requests on a static HttpClient?
If not, how can I accomplish this?

NOTE:
Since testing this, requires a way to reliably create a race condition, in code that I do not control, I don't see a way to test this.

A:

Each SendAsync call is totally independent from each other, canceling the token for one request does not cancel other outstanding requests.
Your assumption that because HttpClientHandler is shared for all requests that means all requests get canceled is incorrect. If you look in to the decompiled source of HttpClientHandler you will see
[__DynamicallyInvokable]
protected internal override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
  if (request == null)
    throw new ArgumentNullException(nameof (request), SR.net_http_handler_norequest);
  this.CheckDisposed();
  if (Logging.On)
    Logging.Enter(Logging.Http, (object) this, nameof (SendAsync), (object) request);
  this.SetOperationStarted();
  TaskCompletionSource<HttpResponseMessage> completionSource = new TaskCompletionSource<HttpResponseMessage>();
  HttpClientHandler.RequestState state = new HttpClientHandler.RequestState();
  state.tcs = completionSource;
  state.cancellationToken = cancellationToken;
  state.requestMessage = request;
  try
  {
    HttpWebRequest prepareWebRequest = this.CreateAndPrepareWebRequest(request);
    state.webRequest = prepareWebRequest;
    cancellationToken.Register(HttpClientHandler.onCancel, (object) prepareWebRequest);
    if (ExecutionContext.IsFlowSuppressed())
    {
      IWebProxy webProxy = (IWebProxy) null;
      if (this.useProxy)
        webProxy = this.proxy ?? WebRequest.DefaultWebProxy;
      if (this.UseDefaultCredentials || this.Credentials != null || webProxy != null && webProxy.Credentials != null)
        this.SafeCaptureIdenity(state);
    }
    Task.Factory.StartNew(this.startRequest, (object) state);
  }
  catch (Exception ex)
  {
    this.HandleAsyncException(state, ex);
  }
  if (Logging.On)
    Logging.Exit(Logging.Http, (object) this, nameof (SendAsync), (object) completionSource.Task);
  return completionSource.Task;
}

The cancellation token is getting wrapped up in a new HttpClientHandler.RequestState state object every call of SendAsnyc, when the token is canceled only the state.webRequest associated with that state object is the one that will be canceled.


Q:

How do I export an object from blender and import in Maya?

I need a way to export a specific model from my Blender scene (for example a textured table) and import it in an already created scene in Maya.
Example case to be more specific:
I created a classroom in Maya and a bedroom in Blender. I want to export the desk I created in Blender and import it as a desk in Maya. How can that be achieved?

A:

The easiest way would be to select the object (desk) you want to export in Blender and export it as .obj file one of these ways:

click File -> Export -> Wavefront (.obj) OR
press space and type "export" -> click Export Scene: Export OBJ

Make sure to check Selection Only in the Export OBJ section, otherwise you would export the whole scene.
In Maya simply click

File -> Import...

and select the exported file.


Q:

Spring framework annotation question

In case of supporting both XML and annotation, when spring framework do the annotation scan and how to process it?
Could someone give detail scenario?
For XmlWebApplicationContext, it use loadBeanDefinations() via Xml file. But when it do the annotation scan and use which class to process it?
Could explain the detail for ?
Thanks.
Franklin

A:

In an XML based Application Context, annotations are only registered if you explicitly configure that:
<!-- register default annotations (e.g. @Required) -->
<context:annotation-config />

<!-- scan for components in selected package -->
<context:component-scan base-package="org.example"/>

Reference:

Annotation-based container
configuration
Classpath scanning and managed
components

And if you want to check the inner workings, see:

CommonAnnotationBeanPostProcessor
JavaDoc, Source Code
ComponentScanBeanDefinitionParser
JavaDoc, Source Code


Q:

Can DB2 and SQL Server be installed on the same machine?

I suspect there should be no problem as those are separate pieces of software, but ideally I would like to have some 'official' confirmation or denial as it will be production environment.
I'm targeting newest versions of both databases.
I was not able to find any information in official channels, but maybe I was looking in the wrong places.
Information about individual successes of failures would also be useful.

A:

The two products can co-exist peacefully because:

There is no overlap in the default installation path for the 2 products;
They don't require the same TCP port number for servicing requests - DB2 listens on port 50000 while SQL Server listens on port 1433.

Your real worries should be about server load during production.
Without knowing what your current usage is, the installation of another database server will at least impact resource contention and utilization (of CPU, memory, HDD etc).


Q:

foreach loop submit button issue

First of all i start writing php this week and there may be unnecessary lines:)
I'm just trying figuring out the logic. For now everything went fine(thx to stackoverflow). Until,
In my foreach loop statement i put submit button, I added the db id after button name. So i put the id after $_POST too. But the problem is only the first submit button works. When i click the others nothing happens.
Thanks for your help. (btw i tried all other answers for foreach button issues. didn't help)
if (isset($_POST['arama'])) {
    $ara = trim(strip_tags($_POST["ara"]));
    $duzelt = trim(strip_tags($_POST["duzelt"]));
    $id = $_SESSION["id"];

    if (!empty($ara)) {
        echo '
';
        echo '

';
        echo "İsim	Cep Telefonu	Sabit Telefonu
";

        $ara1 = '%'.$ara.'%';
        $sql = $db -> query("SELECT * FROM rehber WHERE k_id='".$id."' AND isim LIKE '%$ara%'");
        $yok = $sql->rowCount();;

        if ($yok != 0) {

            echo "<form action=''  method='POST'>";
        foreach ($sql as $dizi) {
            $iden=$dizi[id];
            echo "
<input type='text' name='isim1' value='$dizi[isim]'>	";
            echo "<input type='text' name='cep1' value='$dizi[cepno]'>	";
            echo "<input type='text' name='ev1' value='$dizi[evno]'>	";
            echo "<input type='hidden' name='id2' value='$iden'>";
            echo "<input type='submit' name='duzelt".$iden."' value='duzelt'>	</form>
";
        }
        echo "
";

        echo "
";

    }else{
        echo '

'.$ara.' adında bir kullanıcı kayıtlı değildir.

';
        header("refresh:3;rehber.php?mr=arama");
    }
    }
    else{
        echo '

Arama kutusu boş. Lütfen aramak istediğiniz kişinin adını yazınız.

';
        header("refresh:3;rehber.php?mr=arama");

    }
}
$buton = "duzelt".$_POST["id2"];
if (isset($_POST[$buton]) && $_POST[$buton]) {
    $duz = $_POST[$buton];
    if (!empty($duz)) {
            echo $_POST["isim1"];
            echo $_POST["cep1"];
            echo $_POST["ev1"];
            echo $_POST["id2"];
            echo $buton;

            $sql1 = $db -> prepare("UPDATE rehber SET isim = ?, cepno = ?, evno = ? WHERE id = ?");
            $sql1 -> execute(array($_POST["isim1"], $_POST["cep1"], $_POST["ev1"], $_POST["id2"]));
            echo "Kayıt başarıyla tamamlanmıştır.";
            header("refresh:3;rehber.php?mr=duzen");
        }else{
            echo "kaydedilecek veri yok";
        }
        }

A:

The only real issue that I can see if that the initial form constructor appears outside of the form element, whilst the form element is closed in the foreach loop. I would move the form constructor into the foreach loop. Also, as a secondary, you are using id as a constant value in your $iden constructor. This is easily resolved, but it seems you really want the index, which you can get from the foreach loop.
Please observe:
    foreach ($sql as $iden => $dizi) { // <-- $iden is now the index
        //$iden=$dizi[id]; <- no longer required
        echo "<form action=''  method='POST'>"; // <--form created inside loop
        echo "
<input type='text' name='isim1' value='$dizi[isim]'>	";
        echo "<input type='text' name='cep1' value='$dizi[cepno]'>	";
        echo "<input type='text' name='ev1' value='$dizi[evno]'>	";
        echo "<input type='hidden' name='id2' value='$iden'>";
        echo "<input type='submit' name='duzelt".$iden."' value='duzelt'>	</form>
";
    }

Now you have the form being constructed within the loop, and the index is properly being passed along.


Q:

И снова частица НЕ

Предложение такое: "...иначе это будет не()удобочитаемо". Ворд мне подчеркивает оба варианты: и слитное написание "не" и раздельное. Я понимаю, что в зависимости от контекста, это слово может писать и слитно, и раздельно, но как быть в данном конкретном случае? Я написала раздельно, но потом засомневалась.
Заранее спасибо.

A:

Я понимаю, что в зависимости от
контекста, это слово может писать и
слитно, и раздельно, но как быть в
данном конкретном случае?

Да, зависит от контекста (нужен более широкий, чем у Вас приведён). Скорее всего, потребуется слитное написание.
Попробуйте воспользоваться этим правилом:

§ 148. С существительными, прилагательными, наречиями на -о
отрицание не пишется слитно в
следующих случаях. <...>
4. Если при прилагательном, а также при наречии на -о имеются слова
очень, крайне, весьма, чрезвычайно, явно, довольно (довольно-таки),
достаточно, вопиюще, исключительно, в
высшей степени — слова со значением
степени проявления признака,
подчеркивающие утверждение,
§ 149... При отсутствии в контексте слов, помогающих распознать
отрицание или утверждение и,
следовательно, отличить частицу
не от приставки не-, пишущий должен проверить, какие слова
— усиливающие отрицание или
подчеркивающие утверждение — возможны
по смыслу в данном контексте.
При возможности подстановки слов,
подчеркивающих утверждение (очень,
достаточно и др., см. § 148, п. 4),
не пишется слитно.
http://orthographia.ru/orfografia.php?sid=79#pp79


Q:

What's the `./configure` command?

I usually see ./configure to build something. It looks a script produced by a tool. And today, I realized that I don't know what that is.
What's this? What's the role of this script, and who does make this? And how can I make something like that?

A:

It's usually a script created by GNU autoconf. Other build tools might use the same name too. Autoconf is quite a complex tool, but there's several short tutorials available on the web. I like this one: http://www.edwardrosten.com/code/autoconf/index.html

A:

Every system is different. For example, there are different compilers and compiler versions, the tools of your system might support certain flags (or not), you might have certain libraries installed or not, etc. pp. There a lots of things that are different on computers that might influence how to compile a project.
The configure script tries to figure out all these things and complain if prerequisites aren't met (for example, when the compiler is missing or when a library is missing). It then generates a Makefile that is specific to your system, and just typing make will (hopefully) build the project correctly on your system.
Prior to configure, we had to hand-tune the Makefiles (often the tunable parts were offset into a separate Makefile). This meant that you needed to know a lot about your system and often that you needed to modify the Makefiles. It was a big hurdle, especially since almost every project did it differently. GNU autoconf and automake (which parse the Makefile.am and configure.ac files to generate Makefile.in and configure scripts) really simplified things here (especially if you're doing exotic things like cross-compiling for which almost no project cares to add support; if you're doing autoconf/automake in a clean manner than you get cross-compile support for free, for example).


Q:

Where i can find valid values for the version attribute of the web-app element in web.xml?

Typical web.xml looks like this:
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<web-app version="2.4">
  <display-name>Archetype Created Web Application</display-name>
</web-app>

How can I find out which values are valid for the version attribute of <web-app>?
<web-app version="?">

Is it 2.5 or may be 3.0?
Does someone know a URL with the schema or DTD for web.xml validation? URL's for DTD of different web-app versions are different is there some source where I can see full list?
//doctype for servlet 2.3
<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">

//doctype for servlet 2.2
<!DOCTYPE web-app PUBLIC
  "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
  "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

A:

You can try this url:
http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/javaee/index.html
Here you can find
http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/javaee/web-app_3_0.xsd
http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/javaee/web-app_2_5.xsd


Q:

An explanation from Calvinist about why Cain's offering is not accepted by God?

This question is following the question before, where Calvin said :

We must, however, notice the order here observed by Moses; for he does
  not simply state that the worship which Abel had paid was pleasing to
  God, but he begins with the person of the offerer; by which he
  signifies, that God will regard no works with favor except those the
  doer of which is already previously accepted and approved by him

The bold sentence from Calvin's quotation above, lead to a conclusion that :
1. God elect Abel before the foundation of the world.
2. He regenerate Abel in time and give him faith, don't know when but before the offering event.
3. Those 2 points above causing Abel do a correct offering.
4. Now God has a reason to look with favor on Abel + his offering.
5. and now God can give him approval as righteous through his offering.
So, "God begins with the person of the offerer" as in this case is number 1 and number 2.
The logical conclusion about Cain is :
Because God did not elect Cain and God did not regenerate Cain in time and give Cain faith then Cain offering is not accepted by God. He had no regard for Cain and his offering as mentioned in Gen 4:5.
My question : (according to the Calvinist)
1. What is the cause of Cain's offering is not accepted by God ?
2. Has God regenerated Cain and gave him faith by the time God speak to Cain as read in verse 6 and 7 ?

A:

Why does God approve of Abel as righteous because of his offering?
You stated this in point 5 of your question, and though it wasn’t explicitly asked, I wanted to address it because it is contrary to our first principles. Conversely, God approves of Abel’s offering because of his righteousness- a righteousness, like all godly righteousness, that comes to him by faith. When Calvin says, "God begins with the person of the offerer" he means that the value of the offering is that it is an expression of adoration, and not that it is an attempt to gain approval; the value of the sacrifice exists solely in the heart of the offerer, because the approval of God cannot be earned, except so perfectly.
What is the cause of Cain's offering not being accepted by God ?
In Book 2 of Calvin’s Institutes of the Christian Religion, Calvin discusses the episode of Cain and Abel. He offers an interpretation of Genesis 4:7 that is not common, even among modern translations of the passage, acknowledging the error of Catholic translators.

They adduce the passage of Genesis, “Unto thee shall be his desire, and thou shalt rule over him,” (Gen. 4:7). This they interpret of sin, as if the Lord were promising Cain that the dominion of sin should not prevail over his mind, if he would labour in subduing it. We, however, maintain that it is much more agreeable to the context to understand the words as referring to Abel, it being there the purpose of God to point out the injustice of the envy which Cain had conceived against his brother. And this He does in two ways, by showing, first, that it was vain to think he could, by means of wickedness, surpass his brother in the favour of God, by whom nothing is esteemed but righteousness; and, secondly, how ungrateful he was for the kindness he had already received, in not being able to bear with a brother who had been subjected to his authority.

Now, it helps to remember that the Reformers, among other complaints, rejected the teaching of the Roman Church that justification is a consequence of godly living. The concern of the Catholic presbyters was the moral living of their congregants and their dedication to the authority of Rome, and their teaching reflected that concern. It is not surprising that a person with such a perspective regarding righteousness would naturally adopt an interpretation that God spoke to Cain, saying that he ought to overcome his temptation through labour. To the contrary, Calvin posits that God was prophesying the very domination over Abel that Cain was later to display, in a similar way that He demolishes the pride of the wicked throughout the narrative that follows Genesis, which culminates in his demolition of all wickedness.
Calvin continues, giving the objector the benefit of the doubt by supposing that 4:7 does refer to sin. He posits then that the words constitute either an order or a promise, and examines both cases. In so doing, he addresses your second question.
Has God regenerated Cain and gave him faith by the time God speak to Cain as read in verse 6 and 7 ?
If God had regenerated Cain, he would have been able to speak the words in that passage as a promise, that is, offering assurance. It is common throughout the scriptures for God, through visions, prophets, or apostles, to offer the assurance of justification- a promise- to the elect. Calvin considers this as he continues.

If so, his words contain either an order or a promise. If an order, we have already demonstrated that this is no proof of man’s ability; if a promise, where is the fulfillment of the promise when Cain yielded to the sin over which he ought to have prevailed?

Because Cain fails, Calvin concludes that the passage cannot be a promise, lest the word of God fail, and must therefore be a command, then makes a statement that I believe answers your question.

For, if the dominion spoken of refers to sin, no man can have any doubt that the form of expression is imperative, declaring not what we are able, but what it is our duty to do, even if beyond our ability. Although both the nature of the case, and the rule of grammatical construction, require that it be regarded as a comparison between Cain and Abel, we think the only preference given to the younger brother was, that the elder made himself inferior by his own wickedness.

But surely Cain had faith. One might ask, how could a man such as Cain, who heard the voice of God, lack faith? What is the difference between the faith of Cain and that of Abel?
In the third book of Institutes, On Faith, Calvin answers.

But since the heart of man is not brought to faith by every word of God, we must still consider what it is that faith properly has respect to in the word. The declaration of God to Adam was, “Thou shalt surely die,” (Gen. 2:17); and to Cain, “The voice of thy brother’s blood crieth unto me from the ground,” (Gen. 4:10); but these, so far from being fitted to establish faith, tend only to shake it. At the same time, we deny not that it is the office of faith to assent to the truth of God whenever, whatever, and in whatever way he speaks: we are only inquiring what faith can find in the word of God to lean and rest upon. When conscience sees only wrath and indignation, how can it but tremble and be afraid? And how can it avoid shunning the God whom it thus dreads? But faith ought to seek God, not shun him. It is evident, therefore, that we have not yet obtained a full definition of faith, it being impossible to give the name to every kind of knowledge of the divine will.

It is not the practice of faithfulness or measure of faith that is concomitant with the approval of God, but indeed a faith with a specific object and nature. God did not approve of Cain’s sacrifice because with it he sought the favor of God, and even to surpass the favor of his brother. Abel on the other hand loved God and did not seek righteousness with his sacrifice, but offered it as an expression of his adoration. Cain’s heart was hard, and so though he had “faith” in the sense of knowledge of the existence and identity of God, he lacked faith in the sense of knowledge that God himself is the sole source of righteousness by favor, that is, by grace, and that his favor is not obtained as recompense by sacrifice and labor, but a gift given according to trust and love that are the product of illumination by his Spirit.
Calvin returns to the episode in his commentary on Hebrews 11:4, saying,

The Apostle’s object in this chapter is to show, that however excellent were the works of the saints, it was from faith they derived their value, their worthiness, and all their excellences; and hence follows what he has already intimated, that the fathers pleased God by faith alone.
Now he commends faith here on two accounts, — it renders obedience to God, for it attempts and undertakes nothing, but what is according to the rule of God’s word, — and it relies on God’s promises, and thus it gains the value and worth which belongs to works from his grace alone. Hence, wherever the word faith is found in this chapter, we must bear in mind, that the Apostle speaks of it, in order that the Jews might regard no other rule than God’s word, and might also depend alone on his promises.
He says, first, that Abel’s sacrifice was for no other reason preferable to that of his brother, except that it was sanctified by faith: for surely the fat of brute animals did not smell so sweetly, that it could, by its odor, pacify God. The Scripture indeed shows plainly, why God accepted his sacrifice, for Moses’s words are these, “God had respect to Abel, and to his gifts.” It is hence obvious to conclude, that his sacrifice was accepted, because he himself was graciously accepted. But how did he obtain this favor, except that his heart was purified by faith.


Q:

What is the Google Closure Compiler REST API request limit?

Performing too many requests from the Closure Compiler API you get this error:
Error(22): Too many compiles performed recently.  Try again later.

What is the actual/current limit? Is it an hourly limit? A rolling window?
Any documentation on how this is calculated? The only information about this I could find is on this page (search for "abuse"): https://developers.google.com/closure/compiler/docs/gettingstarted_ui?hl=en

A:

There are per minute/per hour/per day caps.  This is not currently documented, but I believe it the caps allow a sustained rate of ~1 per minute.  In my experience when people run into this problem, they would would be either happier with the command-line tool, or a local compilation server like Plovr or are hitting it by accident (i.e. they don't realize that they are continuously hitting the web service).


Q:

Can the ajax url option take an array of urls instead of just one

How do I fetch data from an array of json urls and store their contents in an array
<script type="text/javascript">
    urls = ["https://spreadsheets.google.com/feeds/list/1RsiDuydBBHyu4OBjlxq1YH6yT3qcJDMB6-YKU-xxd_k/od6/public/basic?hl=en_US&alt=json","https://spreadsheets.google.com/feeds/list/1Pk4KnjBtYsIJF65ZQFEdBLqPufPK-HSFqhZvmxjZD_E/od6/public/basic?hl=en_US&alt=json"];
    local = {};
       $.ajax({
          url: urls,
          cache: false,
          context: local,
          dataType: 'jsonp',
          success: function(data){
            console.log(data);
          }

       });
    </script>

The console.log method does not return any data and it does not return an error. How do I obtain data from the 2 urls I've used

A:

No.
The array will be converted to a string, which won't be any of the URLs that you want, so you'll usually end up with a 404 error (which you won't see because you don't have an error handler (and I think there might be issues with detecting errors on JSONP requests anyway)).
If you want to loop over an array of URLs and make an Ajax request for each one, then you'll have to write the loop yourself, and call $.ajax each time you go around it.
You might want to consider using an iterator that you bump in the success function rather than using a simple for loop so that you don't attempt to fire off lots of requests in parallel.

A:

jQuery doesn't have an overload for this by default, but you can achieve the same thing using promises and performing one AJAX request for each URL in the array:
var urls = ["https://spreadsheets.google.com/feeds/list/1RsiDuydBBHyu4OBjlxq1YH6yT3qcJDMB6-YKU-xxd_k/od6/public/basic?hl=en_US&alt=json","https://spreadsheets.google.com/feeds/list/1Pk4KnjBtYsIJF65ZQFEdBLqPufPK-HSFqhZvmxjZD_E/od6/public/basic?hl=en_US&alt=json"];
var $deferredArray = $.map(urls, function(url) {
       console.log("here");
       return $.ajax({
              url: url,
              cache: false,
              success: function(data){
                console.log("Success");
              }
       });
    });
$.when.apply($, $deferredArray).then(function() {
    console.log('All done');
});


Q:

Vb.Net formatting datagridview

I have been browsing sample pictures for some form designs and found this picture

This picture looks like a datagridview with textbox and comobobx columns. I am ok with how to add a combobx to a datagridview. How can I format a datagridview to have the exact same look?

A:

This is not a DataGridView, As far as i know i thinks its access form where as textbox , combobox controls are placed in Details sections and it will repeated for each row in query behind the access form.
If you want to use a DataGridView with combo boxes please refer following questions
vb.net / DataGridView / ComboBoxCell?


Q:

Internal class objects not resetting after instantiating a custom class in Python 3.6

I am using Python 3.6.4 and built a custom class where I'm doing a computation and changing one of the internal class variables.  I noticed it always runs correctly when I'm running the algorithm (e.g. instantiating class, etc.) and always failing the 2nd time.  Even if it's the same line code repeated twice in a row.  I've been able to replicate the error in it's more simple form.
Why is the lr_space that is being changed in the first object propagating to the 2nd instantiated object?
class testing(object):
    def __init__(self,
                n_iter=5,
                n_space=10,
                model_type="logistic",
                lr_space={
                    "C":(1e-6, 1.0),
                    "penalty":["l1", "l2"],
                },
                lr_kws=dict(max_iter=10000, solver="liblinear"),
                ):
        self.n_iter = n_iter
        self.n_space = n_space
        # Logistic Regression
        self.lr_space = lr_space
        self.lr_kws = lr_kws
        print("", self, self.lr_space,"", sep="\n\t")
        self.model_type = model_type.lower()
        self.models = self._test_function()

    def _test_function(self):
        """
        Internal: Label models
        Need to extend this for using different hyperparameters
        """
        models = list()
        self.param_index = OrderedDict()

        # Indexing for hyperparameters and models
        a = np.ones(self.n_iter*2)
        b = np.arange(a.size)
        if self.model_type == "logistic":
            self.lr_space["C"] = np.linspace(*self.lr_space["C"], self.n_space)

        return models
print("=====Instantiating and running `instance_1`=====")
instance_1 = testing()
print("=====Instantiating and running `instance_2`=====")
instance_2 = testing()

Output:
=====Instantiating and running `instance_1`=====

    <__main__.testing object at 0x136154400>
    {'C': (1e-06, 1.0), 'penalty': ['l1', 'l2']}

=====Instantiating and running `instance_2`=====

    <__main__.testing object at 0x127649390>
    {'C': array([  1.00000000e-06,   1.11112000e-01,   2.22223000e-01,
         3.33334000e-01,   4.44445000e-01,   5.55556000e-01,
         6.66667000e-01,   7.77778000e-01,   8.88889000e-01,
         1.00000000e+00]), 'penalty': ['l1', 'l2']}

Error:
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
     in ()
         38 instance_1 = testing()
         39 print("=====Instantiating and running instance_2=====")
    ---> 40 instance_2 = testing()
<ipython-input-342-24f241984973> in __init__(self, n_iter, n_space, model_type, lr_space, lr_kws)
     17         print("", self, self.lr_space,"", sep="\n\t")
     18         self.model_type = model_type.lower()
---> 19         self.models = self._test_function()
     20
     21     def _test_function(self):

<ipython-input-342-24f241984973> in _test_function(self)
     31         b = np.arange(a.size)
     32         if self.model_type == "logistic":
---> 33             self.lr_space["C"] = np.linspace(*self.lr_space["C"], self.n_space)
     34
     35

TypeError: linspace() takes from 2 to 6 positional arguments but 11 were given

A:

Solution:
If you assign the default value of lr_space inside the init function instead it works:
 from collections import OrderedDict
 import numpy as np

 class testing(object):
     def __init__(self,
                 n_iter=5,
                 n_space=10,
                 model_type="logistic",
                 lr_space=None,
                 lr_kws=dict(max_iter=10000, solver="liblinear"),
                 ):
         if lr_space is None:
           lr_space = {
                     "C":(1e-6, 1.0),
                     "penalty":["l1", "l2"],
           }
         self.n_iter = n_iter
         self.n_space = n_space
         # Logistic Regression
         self.lr_space = lr_space
         self.lr_kws = lr_kws
         print("", self, self.lr_space,"", sep="\n\t")
         self.model_type = model_type.lower()
         self.models = self._test_function()

     def _test_function(self):
         """
         Internal: Label models
         Need to extend this for using different hyperparameters
         """
         models = list()
         self.param_index = OrderedDict()

         # Indexing for hyperparameters and models
         a = np.ones(self.n_iter*2)
         b = np.arange(a.size)
         if self.model_type == "logistic":
             self.lr_space["C"] = np.linspace(*self.lr_space["C"], self.n_space)

         return models
 print("=====Instantiating and running `instance_1`=====")
 instance_1 = testing()
 print("=====Instantiating and running `instance_2`=====")
 instance_2 = testing()

Why:
When you assign default values to arguments in def __init__(...), they are assigned before the new instance exists. This doesn't matter when using simple non-mutable values such as 5 and "logistic" but of you use a dict, you are creating a object outside of the instance and then assigning it to a reference in the __init__ call.
This is a dangerous anti-pattern that you should avoid. You can read more about it here: Using a mutable default value as an argument
When you create new instances, the reference is assigned again, but it's still referencing the same object. Your code above is equivalent to:
default_dict = {
    "C":(1e-6, 1.0),
    "penalty":["l1", "l2"],
}

class testing(object):
     def __init__(self,
            n_iter=5,
            n_space=10,
            model_type="logistic",
            lr_space=default_dict,
            lr_kws=dict(max_iter=10000, solver="liblinear"),
            ):


Q:

How to create a single node AKS cluster using a 1-year reserved instance?

As the title says, I can't figure out how you're supposed to do this.  The pricing calculator allows for it, so I'm assuming it's possible.
I've tried:
1) Creating a new cluster
2) Creating a vm and adding it to an existing cluster, then deleting the initial node (Tried with and without the scaleset option)
For #1, I see no options to add a reserved instance during cluster initialization.  For #2, I see no options to add an existing vm to an existing aks cluster.
Anyone know how to do this?

A:

After you buy an Azure Reserved Virtual Machine Instance, the reservation  discount is automatically applied to virtual machines that match the attributes and quantity of the reservation. A reservation covers the compute costs of your virtual machines. Source

In the documentation you can see that this also applies to AKS.
In other words, you buy a reserved instance and after you create your AKS cluster selecting instances with the same size, the discount will be automatically applied.

A reservation discount applies to the base VMs that you purchase from the Azure Marketplace.

By Marketplace you can also read AKS.


Q:

immutableList but still able to modify elements in the list

I am using com.google.common.collect.ImmutableList to not allow any modification to the element in the list. The code looks like below but the assertion failed.
MyObj doesn't override clone method, is that why it fails?
    MyObj myObj = new MyObj();
    myObj.setName("foo");
    Collection<MyObj> sets = new HashSet<MyObj>();
    sets.add(myObj);
    ImmutableCollection<MyObj> immutableSets = ImmutableList.copyOf(sets);
    for(MyObj obj : immutableSets){
        obj.setName("var");
    }
    assertTrue(myObj.getName()=="foo");

A:

You are modifying an object inside the list, not the list itself.
If you want to avoid such modifications, your immutable list must contain immutable objects.


Q:

Calling super.tableView(tableView: UITableView, cellForRowAtIndexPath... with reuseIdentifier

First, I wanted to point out the reason I want to make a common call, when a reusable cell is dequeued in a base class, it's because of this line of code you will see again soon further in my question:
cell.backgroundColor = cell.contentView.backgroundColor;

This is a bug fix for iPad not respecting the UITableView.backgroundColor = myCustomColor and UITableViewCell.backgroundColor = clearColor I have set. iPad displays white instead, everything is fine in iPhone versions, you can see this bug here, I have to set the background color again each time the cell is dequeued that is the only solution that works for me. I am trying to do this once in my base class, and come up with a solution where I do not have to remember to call a func for every child class (might not be possible).
I have a couple custom UITableViewControllers classes, let's call them ATableViewController and BTableViewController they inherit from a base class called UIBaseDashboardTableViewController which inherits from UITableViewController.
I am generating dynamic Prototype Table cells and making use of the function below in ATableViewController and BTableViewController:
 override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("ATableViewCellId", forIndexPath: indexPath)

        //common setting to fix always white background in iPad bug
        cell.backgroundColor = cell.contentView.backgroundColor;
        return cell
    }

The TableViewCell Id ACustomTableCellId is unique or different for ATableViewController and BTableViewController. I have a common setting for all my UITableViewControllers that inherit from my base class, UIBaseDashboardTableViewController. You can see the backgroundColor line of code above is my common setting that will be the same in all child classes of UIBaseDashboardTableViewController. In each child class I first tried to do the following:
  override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    super.tableView(tableView: tableView, cellForRowAtIndexPath: indexPath)
    ...
}

But that is not going to work, I need the ReusableCellIndentifer.
My current solution, which really is just fine probably, is the following, in my child classes I have the following:
 override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let data = dataArray[indexPath.row]
        let dequeuedCell = tableView.dequeueReusableCellWithIdentifier("BTableViewCellID", forIndexPath: indexPath)
        let cell = dequeuedCell as! MyCustomTableViewCell
        // Configure the cell...
        cell.model = data

        //call common settings for cells function in base class
        super.setDequeueReusableCellCommon(cell)

        return cell
    }

And then in my base class UIBaseDashboardTableViewController I implemented:
func setDequeueReusableCellCommon(cell: UITableViewCell) {
        cell.backgroundColor = cell.contentView.backgroundColor
    }

The only downside to this is that I have to remember to call super.v setDequeueReusableCellCommon in all my child classes.
Any better suggestions on how solve this?

A:

You are changing background color for cell, but made inheritance for tableViews. Use inheritance for tableViewCell, not the whole tableView. And in root class for tableViewCell setup self.backgroundColor = self.contentView.backgroundColor in awakeFromNib method.


Q:

primefaces GMmap inside a dialog not rendering

I want to open a Gmap inside my jsf page, i tried these sample but it didn't work:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<script src="http://maps.google.com/maps/api/js?sensor=false"
    type="text/javascript"></script>
</h:head>
<body>
<ui:composition template="/WEB-INF/template/template.xhtml">
    <ui:define name="content">
        <p:commandButton type="button" icon="ui-icon-pin-s" value="Show Map"
            onclick="dlg.show()" />

        <p:dialog widgetVar="dlg" width="625" height="400" modal="true">
            <p:gmap center="41.381542, 2.122893" zoom="15" type="HYBRID"
                style="width:600px;height:400px" widgetVar="mymap" />
        </p:dialog>
    </ui:define>
</ui:composition>
</body>
</html>

A:

Your mistake is: in composition, you have to include <h:head></h:head> to apply css, but any code from that have not been loaded. You need to add script to /WEB-INF/template/template.xhtml
template.xhtml:
<h:head>
    // other here
    <script src="http://maps.google.com/maps/api/js?sensor=false"
    type="text/javascript"></script>
</h:head>

See also:understand the purpose of jsf ui:composition


Q:

How to keep the water bottles erect in the refrigerator door?

When opening or closing my refrigerator's door, the water bottle(s) stored there often fall sideways:

This is irritating, and as you can see, I did try to place a heavier bottle besides it, which helps a bit but still not enough.
Is there a way to keep the bottles always erect and preventing them from falling as in the above image?

A:

Keep just one water bottle in the door, and move it all the way to the left (nearest the door hinges). This reduces the speed at which the bottle moves when you open the door: excessive speed causes the bottles to fall over.
Put the rest of the bottles in the bottle rack.


Q:

Fork and Waitpid calls in a CTF linux binary

I'm doing one of my first linux crackmes.
In the first blocks of code, it goes inside some anti-debug routine and inside one of those it forks and after it calls a waitpid routine. I can verify it and understand purely the code but I can't get why the creators put this code and how it can be an anti-debug technique. These are the interesting blocks.

A:

Basically, the process calls fork, on the child side it'll try to attach a debugger to the parent process:
ptrace(PTRACE_ATTACH, getppid(), 0, 0);

If this syscall failed, it probably means a debugger is already attached to the parent process, this is your anti-debugger. To notify the parent process, the developer relies on the exit code. It's 1 if a debugger is attached, 0 otherwise.
On the parent side, it retrieves the exit code with the macro WEXITSTATUS. In C this is defined as:
#define WEXITSTATUS(x)  (_W_INT(x) >> 8)

Which gives in assembly:
sar     eax, 8
movzx   eax, al
test    eax, eax
jz      short no_debugger

This is another way to do a PTRACE_TRACEME. :)


Q:

Complex number (finding range of values)

Let $z_1 = 2 e^{i\pi/6}$ and $z_2 = re^{i\theta}$, where $r>0$ and $0\le\theta<2\pi$. Find the range of values of $r$ and $\theta$ for which $z_1z_2$ is:
a) a real number greater than $5$
b) a purely imaginary number with modulus less than $1$

This question was in my math textbook and I can't figure it out. There are no worked example to show the method in the textbook. Any hint on how I should approach it. I converted $z_1$ from polar to rectangular form and got $z_1 = \sqrt 3 + i$
I think $\theta$ has to be greater than $\pi$ and less than $2\pi$ because that will make value of $\sin\theta$ negative which would give the multiplication of $z_1z_2$ the form of $(a+b)(a-b)$ removing the imaginary part and leaving only real number. But I don't know how to get the number to be greater than $5$.

Answer in the textbook is
a) $r>5/2$ and $\theta=11\pi/6$
b) $r<1/2$ and $r > 0$ and $\theta=\pi/3$ or $\theta=4\pi/3$

A:

Let $z_1=2e^{i\pi/6}$ and $z_2=re^{i\theta}$ where anyways $r\gt0$ and $0\leq\theta\lt2\pi$
Now the product $z_1z_2=2re^{i(\theta+i\pi/6)}$
The argument of the above complex number is $2r$ and for the first part:
$1.)$$$2r>5$$ which means $$r>\frac{5}{2}$$
To make $z_1z_2$ as a real number the argument should be $0$ $or$ $2\pi$ which means
$$ \theta+\pi/6=2\pi$$ giving $$\theta=11\pi/6$$
And for the second Part:
$2.)$ The modulus of $z_1z_2$ is to be less than $1$ so
$$2r\lt1$$
Giving $$r\lt\frac{1}{2}$$ Also the amplitude is a positive quantity, $r\gt0$
Combining you get $$0\lt r\lt\frac{1}{2}$$
And to make the number purely imaginary the argument should be either $\pi/2$ or $3\pi/2$
$$\theta+\pi/6=\pi/2\space or\space 3\pi/2$$
So the values for $\theta$ will be $$\theta = \pi/3 \space or \space 4\pi/3$$
Hope this helps ….


Q:

Defining a string as a variable to make code run faster

Suppose I have a dictionary in java and its keys are strings. I call this dictionary millions of times (in a for loop). Is it faster to define the keys names at the beginning and use these variables or is it the same as using the string itself?
String p = "key1"
dic.put(p,value)

vs
dic.put("key1", value)

If so, then why?

A:

The same bytecode is generated from these two code snippets. So, it does not matter.


Q:

Jsoup - Missing content

I'm executing the following code with JSoup
Document parse = Jsoup.connect("http://www.google.com/movies?near=<MyCity>&sort=1&start=0")
                       .followRedirects(true)
                       .ignoreContentType(true)
                       .timeout(12000)
                       .userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0")
                       .referrer("http://www.google.com")
                       .execute()
                       .parse();
Elements elements = parse.select(".movie_results .movie");

but when I inspect elements, it clearly miss a lot of content. I'm trying to get movie title and description from the page above.
What am I missing? Can this be related to missing header parameters, cookies?
Is there any other lib that could solve the problem?
I culd reproduce the same problem by executing:
curl http://www.google.com/movies?near=<MyCity>&sort=1&start=0 > page.html

ProTip
Just highlighting one of the comments: try.jsoup.org is a good place to start using Jsoup. It helps you to parse the html in a very clean way.
Please, +1 if you liked the tip and saved your day :D

A:

After some investigation using Google Chrome Dev Tools, I figured out that some header info was missing. The final code is similar to this one:
Jsoup.connect(url)
  .followRedirects(true)
  .ignoreContentType(true)
  .timeout(12000) // optional
  .header("Accept-Language", "pt-BR,pt;q=0.8") // missing
  .header("Accept-Encoding", "gzip,deflate,sdch") // missing
  .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36") // missing
  .referrer("http://www.google.com") // optional
  .execute()
  .parse();

Thanks for your answers!


Q:

How do I use MySQL through XAMPP?

I installed XAMPP v3.2.1 because I wanted to learn how to create database in MySQL and learn more about TOMCAT. However, I am a little confused about what to do now. I have read many blogs and the documentation on this page http://dev.mysql.com/doc/refman/5.0/en/creating-database.html.
While following the directions I found that:
I can't access my local host.
Attempted Solution: I shut down skype because I read that might be an issue.
I don't have any older versions of XAMPP on my computer and I don't believe I am connected to any other servers. So, I don't have permission to do anything.
OR
Am I trying to access mysql through the wrong command prompt? I am trying to use MySQL from the XAMPP shell. I am not sure why I cannot get everything working. Am I going about this the wrong way?
Thanks for any help

A:

XAMPP only offers MySQL (Database Server) & Apache (Webserver) in one setup and you can manage them with the xampp starter.
After the successful installation navigate to your xampp folder and execute the xampp-control.exe
Press the start Button at the mysql row.

Now you've successfully started mysql. Now there are 2 different ways to administrate your mysql server and its databases.
But at first you have to set/change the MySQL Root password. Start the Apache server and type localhost or 127.0.0.1 in your browser's address bar. If you haven't deleted anything from the htdocs folder the xampp status page appears. Navigate to security settings and change your mysql root password.
Now, you can browse to your phpmyadmin under http://localhost/phpmyadmin or download a windows mysql client for example navicat lite or mysql workbench. Install it and log in to your mysql server with your new root password.


Q:

jQuery Bounce Effect on click no jQuery UI

I cannot find a solution to an animation to make a div bounce, using just jQuery animations. Something like does not work:
$("#bounce").click(function() {
    $(this).effect("bounce", {
        times: 3
    }, 300);
});.

I would prefer not to use jQuery UI or any external plugin, such as the easing one. A wobble effect would be just as good in my case, so either will do.
Here is an example, any help would be much appreciated! Thanks in advance

A:

You could simply chain together some animate calls on the element like so:
$("#bounce").click(function() {
    doBounce($(this), 3, '10px', 300);
});

function doBounce(element, times, distance, speed) {
    for(var i = 0; i < times; i++) {
        element.animate({marginTop: '-='+distance}, speed)
            .animate({marginTop: '+='+distance}, speed);
    }
}

Working example: http://jsfiddle.net/Willyham/AY5aL/

A:

Use this function for damped bounces. Be sure to give the bouncing element a unique class if using the code without changes.

var getAttention = function(elementClass,initialDistance, times, damping) {
  for(var i=1; i<=times; i++){
      var an = Math.pow(-1,i)*initialDistance/(i*damping);
      $('.'+elementClass).animate({'top':an},100);
  }
  $('.'+elementClass).animate({'top':0},100);
}

$( "#bounce").click(function() {
 getAttention("bounce", 50, 10, 1.2);
});
#bounce {
    height:50px;
    width:50px;
    background:#f00;
    margin-top:50px;
    position:relative;
    border-radius: 50px;
}


Q:

Get the sum for each SQL row

Hi I have written the query bellow and the problem I have is that is obviously returning the sum for the whole table (All employees together) and I would want it to return the total sum per employee, would this be possible at all?
DECLARE @temp TABLE
(
TotalAmount DECIMAL,
ExpenseCategory UNIQUEIDENTIFIER,
EmployeeId UNIQUEIDENTIFIER,
CategoryName NVARCHAR(100)
)

INSERT INTO @temp

SELECT  SUM(dbo.ExpenseDetails.TotalAmount) AS TotalAmount,
dbo.ExpenseDetails.ExpenseCategory, dbo.ExpenseDetails.EmployeeId,
dbo.ExpensesCategories.CategoryName
FROM            dbo.ExpenseDetails INNER JOIN
                     dbo.ExpensesCategories ON
dbo.ExpenseDetails.ExpenseCategory = dbo.ExpensesCategories.CategoryId
WHERE        (CONVERT(DATE, dbo.ExpenseDetails.DateAdded) < CONVERT(DATE,
DATEADD(m, DATEDIFF(m, 0, CONVERT(DATE, GETDATE())), 23 - 1))) AND
(CONVERT(DATE, dbo.ExpenseDetails.DateAdded) > CONVERT(DATE,
                      DATEADD(MONTH, - 1, DATEADD(m, DATEDIFF(m, 0,
CONVERT(DATE, GETDATE())), 23 - 1))))
GROUP BY dbo.ExpenseDetails.ExpenseCategory, dbo.ExpenseDetails.EmployeeId,
dbo.ExpensesCategories.CategoryName

SELECT
EmployeeId,
(SELECT SUM(TotalAmount) FROM @temp WHERE EmployeeId = [@temp].EmployeeId
and ExpenseCategory = '6CC0F801-D295-4997-9D1F-3E5B2BE692ED') AS TotalFuel,
(SELECT SUM(TotalAmount) FROM @temp WHERE EmployeeId = [@temp].EmployeeId
and ExpenseCategory = '3E54C10B-ECBE-4B28-87A4-5A4E43AACDFC') AS TotalRail,
(SELECT SUM(TotalAmount) FROM @temp WHERE EmployeeId = [@temp].EmployeeId
and ExpenseCategory = '31CC43A4-80E6-4DD4-A28C-039F05AF62A3') AS
TotalParking,
(SELECT SUM(TotalAmount) FROM @temp WHERE EmployeeId = [@temp].EmployeeId
and ExpenseCategory = '01250A30-3865-40D2-9E49-DA2B9898B1F4') AS
TotalMileage,
(SELECT SUM(TotalAmount) FROM @temp WHERE EmployeeId = [@temp].EmployeeId
and ExpenseCategory = 'F4E4582D-DEDF-499D-BBC1-45003B865218') AS TotalEquip,
(SELECT SUM(TotalAmount) FROM @temp WHERE EmployeeId = [@temp].EmployeeId
and ExpenseCategory = '55F471C1-6E52-4898-8263-0B7684B78E7C') AS TotalPPS,
(SELECT SUM(TotalAmount) FROM @temp WHERE EmployeeId = [@temp].EmployeeId
and ExpenseCategory = '1EE0FC40-193F-4720-9143-0B61FFDE7B8D') AS TotalOther

FROM @temp GROUP BY EmployeeId

A:

Use SUM with condition:
SELECT
    EmployeeId,
    TotalFuel = SUM(CASE WHEN ExpenseCategory = '6CC0F801-D295-4997-9D1F-3E5B2BE692ED' THEN TotalAmount END)
FROM @temp
GROUP BY EmployeeId


Q:

Drawing zoomable audio waveform timeline in Javascript

I have raw 44,1 kHz audio data from a song as Javascript array and I'd like to create a zoomable timeline out of it.
Example timeline from Audacity:

Since there are millions of timepoints normal Javascript graphics libraries probably don't cut it: I think, not sure, that normal graph libraries will die on this many timepoints. But does there exist already libraries for this sort of visualization for JS? Canvas, webGL, SVG all are acceptable solutions.
A solution preferably with zoom and pan.
Note that this happens strictly on client side and server-side solutions are not accetable.

A:

I've looked into this same problem pretty extensively. To the best of my knowledge, the only existing project that does close to what you want is wavesurfer.js.  I haven't used it, but the screenshots and the description sound promising.
See also this question.
Best of luck.


Q:

UnicodeWarning: special characters in Tkinter

I have written a program in Tkinter (Python 2.7), a scrabblehelper in Norwegian which contains some special characters (æøå), which means my wordlist (ordliste) contains words with special characters.
When I run my function finnord(c*), it returns 'cd'. I am using an entry.get() to get the word to put in my function.
My problem is with the encoding of entry.get(). I have local coding UTF-8, but I get an UniCodeError when I am writing any special characters in my entrybox and matching them to my wordliste.
Here is my output.
Warning (from warnings module):
  File "C:\pythonprog\scrabble\feud.py", line 46
if s not in liste and s in ordliste:
UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode -
interpreting them as being unequal

When i write in my shell:
> ordinn.get()
u'k\xf8**e'
> ordinn.get().encode('utf-8')
'k\xc3\xb8**e'
> print ordinn.get()
kø**e
> print ordinn.get().encode('utf-8')
kÃ¸**e

Anyone knows why I can't match ordinn.get() (entry) to my wordlist ?

A:

I can reproduce the error this way:
% python
Python 2.7.2+ (default, Oct  4 2011, 20:03:08)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 'k\xf8**e' in [u'k\xf8**e']
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False

So perhaps s is a str object, and liste or ordliste contains unicode, or (as eryksun points out in the comments) vice versa. The solution is to decode the str objects (most likely with the utf-8 codec) to make them unicode.
If that does not help, please print out and post the output of
print(repr(s))
print(repr(liste))
print(repr(ordliste))

I believe the problem can be avoided by converting all strings to unicode.

When you generate ordliste from norsk.txt, use
codecs.open('norsk.txt','r','utf-8'):
encoding = sys.stdin.encoding
with codecs.open('norsk.txt','r','utf-8') as fil:
    ordliste = [line.rstrip(u'\n') for line in fil]

Convert all user input to unicode as soon as possible:
def get_unicode(widget):
    streng = widget.get()
    try:
        streng = streng.decode('utf-8')
    except UnicodeEncodeError:
        pass
    return streng

So perhaps try this:
import Tkinter as tk
import tkMessageBox
import codecs
import itertools
import sys

alfabetet = (u"abcdefghijklmnopqrstuvwxyz"
             u"\N{LATIN SMALL LETTER AE}"
             u"\N{LATIN SMALL LETTER O WITH STROKE}"
             u"\N{LATIN SMALL LETTER A WITH RING ABOVE}")

encoding = sys.stdin.encoding
with codecs.open('norsk.txt','r',encoding) as fil:
    ordliste = set(line.rstrip(u'\n') for line in fil)

def get_unicode(widget):
    streng = widget.get()
    if isinstance(streng,str):
        streng = streng.decode('latin-1')
    return streng

def siord():
    alfa=lagtabell()
    try:
        streng = get_unicode(ordinn)
        ordene=finnord(streng,alfa)
        if len(ordene) == 0:
            # There are no words that match
            tkMessageBox.showinfo('Dessverre..','Det er ingen ord som passer...')
        else:
            # Done: The words that fit the pattern
            tkMessageBox.showinfo('Ferdig',
                'Ordene som passer er:\n'+ordene.encode('utf-8'))
    except Exception as err:
        # There has been a mistake .. Check your word
        print(repr(err))
        tkMessageBox.showerror('ERROR','Det har skjedd en feil.. Sjekk ordet ditt.')

def finnord(streng,alfa):
    liste = set()
    for substitution in itertools.permutations(alfa,streng.count(u'*')):
        s = streng
        for ch in substitution:
            s = s.replace(u'*',ch,1)
        if s in ordliste:
            liste.add(s)
    liste = [streng]+list(liste)
    return u','.join(liste)+u'.'

def lagtabell():
    tinbox = get_unicode(bokstinn)
    if not tinbox.isalpha():
        alfa = alfabetet
    else:
        alfa = tinbox.lower()
    return alfa

root = tk.Tk()
root.title('FeudHjelper av Martin Skow Røed')
root.geometry('400x250+450+200')
# root.iconbitmap('data/ikon.ico')

skrift1 = tk.Label(root,
                text = '''\
Velkommen til FeudHjelper. Skriv inn de bokstavene du har, og erstatt ukjente med *.
F. eks: sl**ge
Det er kun lov til å bruke tre stjerner, altså tre ukjente bokstaver.''',
                font = ('Verdana',8), wraplength=350)
skrift1.pack(pady = 5)

ordinn = tk.StringVar(None)
tekstboks = tk.Entry(root, textvariable = ordinn)
tekstboks.pack(pady = 5)

# What letters do you have? Eg "ahneki". Leave blank here if you want all the words.
skrift2 = tk.Label(root, text = '''Hvilke bokstaver har du? F. eks "ahneki". La det være blankt her hvis du vil ha alle ordene.''',
                font = ('Verdana',8), wraplength=350)
skrift2.pack(pady = 10)

bokstinn = tk.StringVar(None)
tekstboks2 = tk.Entry(root, textvariable = bokstinn)
tekstboks2.pack()

knapp = tk.Button(text = 'Finn ord!', command = siord)
knapp.pack(pady = 10)
root.mainloop()


Q:

Dynamic form generation

I have a model for event invitations:
class EventInvitation(models.Model):

    from_user = models.ForeignKey(User, related_name="inviters")
    to_user = models.ForeignKey(User, related_name="invited")
    text = models.CharField(max_length= 150)
    event = models.ForeignKey(Event)
    sent = models.DateTimeField(auto_now=True)
    status = models.IntegerField(choices=INVITATION_STATI, default=0)

What I am trying to accomplish is to have a dynamic invitation form (NOT ModelForm), where the inviter has a selection of users, based on a query / people who CAN be invited by that particular user, and a selection of groups, also based on a query (the inviter has to be the owner of the group)... Since the EventInvitation is for a single user, I would then iterate through the selected users AND members of the group and create individual invitations for all of them. Any idea how I could generate this dynamic form?

A:

As I understand, you want a logged in user, from an event page, click on a "Invite Others" button, which shows him a form, where he can select specific users and groups, specify some text, and click on "Send".  Then your app should create many instances of the invitation (one per user) and send them, tracking the status of invitation.  If this is correct, here are my suggestions for implementing this:
Using the following models will give you more control over your data (keeping the text only once, and allowing you to look up all users for a specific invitation):
class EventInvitation(models.Model):
    inviter = models.ForeignKey(User, related_name="inviters")
    event = models.ForeignKey(Event)
    text = models.CharField(max_length= 150)
    created = models.DateTimeField(auto_now=True)

class EventInvitationInvitee(models.Model):
    event_invitation = models.ForeignKey(EventInvitation)
    user = models.ForeignKey(User, related_name="invited")
    status = models.IntegerField(choices=INVITATION_STATI, default=0)

Use a simple form like this:
from django.contrib.auth.models import User, Group

class InviteForm(forms.Form):
    text = forms.CharField(widget=forms.Textarea)
    users = forms.ModelMultipleChoiceField(queryset=User.objects.all())
    groups = forms.ModelMultipleChoiceField(queryset=Group.objects.all())

    def __init__(self, user, *args, **kwargs):
      super(InviteForm, self).__init__(*args, **kwargs)
      self.fields['users'].queryset = User.objects.filter( ... )
      self.fields['groups'].queryset = User.objects.filter( ... )

Replace ... with your code for filtering the correct groups and users.
And a view in this fashion:
def invite(request, event_id):
    event = get_object_or_404(Event, pk=event_id) # you can check if your user is allowed to access this event here
    if request.method == 'POST':
        form = InviteForm(request.user, request.POST)
        if form.is_valid():
            invitation = EventInvitation.objects.create(inviter=request.user, event=event,  text = form.cleaned_data['text'])
            users = set()
            for user in form.cleaned_data['users']:
                users.add(user)
                EventInvitationInvitee.objects.create(event_invitation=invitation, user=user)
            for group in form.cleaned_data['groups']:
                for user in group.user_set.all():
                    if user not in users:
                        users.add(user)
                        EventInvitationInvitee.objects.create(event_invitation=invitation, user=user)
            return HttpResponseRedirect('/thanks/') # Redirect after POST
    else:
        form = InviteForm(request.user)

    return render_to_response('invite.html', {'form': form})

Update:  You can also create a dynamic form in a more pythonic way like this:
def get_invite_form(user):

  class InviteForm(forms.Form):
      text = forms.CharField(widget=forms.Textarea)
      users = forms.ModelMultipleChoiceField(queryset= ... )
      groups = forms.ModelMultipleChoiceField(queryset= ... )

  return InviteForm

replacing ... with a queryset using the user parameter, and later use get_invite_form(request.user)(request.POST) and get_invite_form(request.user)() instead of InviteForm().


Q:

Calculus - Solving limits with square roots

I am having trouble understanding how to solve this limit by rationalizing. I have the problem correct (I used Wolfram Alpha of course), but I still don't understand how it is completed. I was trying to solve this by multiplying both the numerator and the denominator by $\sqrt{x^2+11}+6$, but I am stuck. Is that the way to solve this? If so, could you walk me through it so I can solve others?
Problem:

A:

$$\begin{align}
\lim_{x\to 5}\frac{\sqrt{x^2+11}-6}{x-5}
  &= \lim_{x\to 5}\frac{\left(\sqrt{x^2+11}-6\right)
    \left(\sqrt{x^2+11}+6\right)}{(x-5)\left(\sqrt{x^2+11}+6\right)} \\[2ex]
  &= \lim_{x\to 5}\frac{\left(\sqrt{x^2+11}\right)^2-6^2}
    {(x-5)\left(\sqrt{x^2+11}+6\right)} \\[2ex]
  &= \lim_{x\to 5}\frac{x^2+11-36}{(x-5)\left(\sqrt{x^2+11}+6\right)} \\[2ex]
  &= \lim_{x\to 5}\frac{x^2-25}{(x-5)\left(\sqrt{x^2+11}+6\right)} \\[2ex]
  &= \lim_{x\to 5}\frac{(x-5)(x+5)}{(x-5)\left(\sqrt{x^2+11}+6\right)} \\[2ex]
  &= \lim_{x\to 5}\frac{x+5}{\sqrt{x^2+11}+6} \\[2ex]
  &= \frac{5+5}{\sqrt{5^2+11}+6} \\[2ex]
  &= \frac{10}{12} \\[2ex]
  &= \frac{5}{6}
\end{align}$$